--- a/pkg/igconnector/chatinfo.go +++ b/pkg/igconnector/chatinfo.go @@ -93,7 +93,8 @@ if info.Username != "" { identifiers = []string{fmt.Sprintf("instagram:%s", info.Username)} } - return &bridgev2.UserInfo{ + // Xessenger: Instagram's placeholder for a person it does not show leaves a named ghost as it is (QA-289). + return ic.keepNamedOnPlaceholder(info.Username, info.FullName, info.ID, info.InteropMessagingUserFBID, &bridgev2.UserInfo{ Identifiers: identifiers, Name: new(ic.Main.Config.FormatDisplayname(DisplaynameParams{ DisplayName: info.FullName, @@ -103,7 +104,7 @@ Avatar: wrapAvatar(info.ProfilePicURL), IsBot: new(info.AIAgentType != ""), ExtraUpdates: ic.updateGhostIGID(info.Username, info.ID, info.InteropMessagingUserFBID), - } + }) } func (ic *IGClient) wrapSearchResultInfo(info *slidetypes.SearchResult) *bridgev2.UserInfo { @@ -112,7 +113,8 @@ if info.Username != "" { identifiers = []string{fmt.Sprintf("instagram:%s", info.Username)} } - return &bridgev2.UserInfo{ + // Xessenger: Instagram's placeholder for a person it does not show leaves a named ghost as it is (QA-289). + return ic.keepNamedOnPlaceholder(info.Username, info.FullName, info.PK, info.InteropMessagingUserFBID, &bridgev2.UserInfo{ Identifiers: identifiers, Name: new(ic.Main.Config.FormatDisplayname(DisplaynameParams{ DisplayName: info.FullName, @@ -121,7 +123,7 @@ })), Avatar: wrapAvatar(info.ProfilePicURL), ExtraUpdates: ic.updateGhostIGID(info.Username, info.PK, info.InteropMessagingUserFBID), - } + }) } func wrapAvatar(avatarURL string) *bridgev2.Avatar { --- /dev/null +++ b/pkg/igconnector/xessenger_placeholder.go @@ -0,0 +1,58 @@ +package igconnector + +import ( + "context" + "strings" + "unicode" + + "maunium.net/go/mautrix/bridgev2" + + "go.mau.fi/mautrix-meta/pkg/metaid" +) + +// placeholderName is the name Instagram gives in place of a person it does not show to this account (an +// account deleted, deactivated or out of its reach). Its username then holds a space, which no Instagram +// username can. +const placeholderName = "Instagram User" + +// placeholderProfile reports whether a profile is Instagram's placeholder for a person it does not show: a +// username no account can have, or the placeholder's name with no username at all. A person who calls +// themselves "Instagram User" has a username of their own, and their profile goes as it came. +func placeholderProfile(username, fullName string) bool { + return strings.ContainsFunc(username, unicode.IsSpace) || (username == "" && fullName == placeholderName) +} + +// keepNamedOnPlaceholder leaves a ghost that has a name as it is when Instagram gives its placeholder for +// the person (QA-289): the placeholder's name does not take the place of theirs, nor its username of +// their identifiers and of the username the ghost's metadata keeps, which the encrypted profiles carry +// (ghost-identifiers.patch), nor does it say whether they are a bot. A valid ID the placeholder carries +// (igid, with its FBID) still goes in, as updateGhostIGID puts it: typing notifications find the person by +// it. A name of the ghost's own its Matrix side has not taken yet (a homeserver that failed the last time) +// goes there again, as bridgev2 sends it with any profile that gives a name, as the ghost holds it when it +// goes and under the lock any profile's push holds (ResendName, mautrix-ghost-profile.patch); contact +// information never set is left to bridgekit's fill, which gives a ghost made before the bridge kept +// identifiers those of the username its metadata keeps. A ghost without a name takes the placeholder as +// any profile, through bridgev2's UpdateInfo unchanged (ForGhost picks it), and any other profile goes as +// it came. The profile as returned is the one that leaves a named ghost as it is, which is what anything +// that reads it without a ghost sees. +func (ic *IGClient) keepNamedOnPlaceholder(username, fullName, igid string, fbid int64, info *bridgev2.UserInfo) *bridgev2.UserInfo { + if !placeholderProfile(username, fullName) { + return info + } + whole := *info + info.Name, info.Identifiers, info.IsBot = nil, nil, nil + info.ExtraUpdates = func(ctx context.Context, ghost *bridgev2.Ghost) bool { + changed := false + if igid != "" && igid != "0" { + changed = ic.updateGhostIGID(ghost.Metadata.(*metaid.GhostMetadata).Username, igid, fbid)(ctx, ghost) + } + return ghost.ResendName(ctx) || changed + } + info.ForGhost = func(_ context.Context, ghost *bridgev2.Ghost) *bridgev2.UserInfo { + if ghost.Name == "" { + return &whole + } + return nil + } + return info +} --- /dev/null +++ b/pkg/igconnector/xessenger_placeholder_test.go @@ -0,0 +1,337 @@ +package igconnector + +import ( + "context" + "database/sql" + "errors" + "path/filepath" + "slices" + "sync" + "testing" + "time" + + "github.com/rs/zerolog" + "go.mau.fi/util/dbutil" + "maunium.net/go/mautrix/bridgev2" + "maunium.net/go/mautrix/bridgev2/bridgeconfig" + "maunium.net/go/mautrix/bridgev2/networkid" + "maunium.net/go/mautrix/id" + + "go.mau.fi/mautrix-meta/pkg/instameow/slidetypes" + "go.mau.fi/mautrix-meta/pkg/metadb" + "go.mau.fi/mautrix-meta/pkg/metaid" +) + +// pushedProfile is what a ghost's profile held when its Matrix side was given it: the encrypted rooms take +// the ghost's name, identifiers and username as they are at that moment (bridgekit member profiles). +type pushedProfile struct { + name string + ids []string + username string +} + +// placeholderIntent records what a ghost's Matrix side is given: its names, how many times its extra profile +// fields, and the ghost's profile each time one went through (`pushed`). The next failNames names and failMetas +// extra profiles fail, as a homeserver that is down a moment does, and so do the next failAvatars avatars, each +// recorded in avatars. The next name given waits in hold, as one the homeserver is slow to take. +type placeholderIntent struct { + bridgev2.MatrixAPI + mu sync.Mutex + ghost *bridgev2.Ghost + names []string + metas int + avatars []id.ContentURIString + pushed []pushedProfile + failNames int + failMetas int + failAvatars int + hold func() +} + +func (p *placeholderIntent) push() { + p.pushed = append(p.pushed, pushedProfile{p.ghost.Name, slices.Clone(p.ghost.Identifiers), p.ghost.Metadata.(*metaid.GhostMetadata).Username}) +} + +func (p *placeholderIntent) SetDisplayName(_ context.Context, name string) error { + p.mu.Lock() + hold := p.hold + p.hold = nil + p.mu.Unlock() + if hold != nil { + hold() + } + p.mu.Lock() + defer p.mu.Unlock() + p.names = append(p.names, name) + if p.failNames > 0 { + p.failNames-- + return errors.New("homeserver unavailable") + } + p.push() + return nil +} + +func (p *placeholderIntent) SetAvatarURL(_ context.Context, avatarURL id.ContentURIString) error { + p.mu.Lock() + defer p.mu.Unlock() + p.avatars = append(p.avatars, avatarURL) + if p.failAvatars > 0 { + p.failAvatars-- + return errors.New("homeserver unavailable") + } + return nil +} + +func (p *placeholderIntent) SetExtraProfileMeta(context.Context, any) error { + p.mu.Lock() + defer p.mu.Unlock() + p.metas++ + if p.failMetas > 0 { + p.failMetas-- + return errors.New("homeserver unavailable") + } + p.push() + return nil +} + +// placeholderFixtureMatrix takes extra profile fields, as bridgekit says for Instagram, so the identifiers +// are kept, and gives every ghost the recording intent. +type placeholderFixtureMatrix struct { + fixtureMatrix + intent *placeholderIntent +} + +func (m *placeholderFixtureMatrix) GhostIntent(networkid.UserID) bridgev2.MatrixAPI { return m.intent } + +func (*placeholderFixtureMatrix) GetCapabilities() *bridgev2.MatrixCapabilities { + return &bridgev2.MatrixCapabilities{ExtraProfileMeta: true} +} + +// Instagram's placeholder for a person it does not show: a username no account can have, or the placeholder's +// name with no username. A person who calls themselves "Instagram User" has a username of their own. +func TestXessengerPlaceholderProfile(t *testing.T) { + for _, c := range []struct { + username, fullName string + want bool + }{ + {"Instagram User", "Instagram User", true}, + {"Instagram User", "", true}, + {"", "Instagram User", true}, + {"kim.minsu", "Instagram User", false}, + {"kim.minsu", "김민수", false}, + {"kim.minsu", "", false}, + {"", "김민수", false}, + {"", "", false}, + } { + if got := placeholderProfile(c.username, c.fullName); got != c.want { + t.Errorf("%q %q: %v", c.username, c.fullName, got) + } + } +} + +// bridgev2 UpdateInfo with Instagram's placeholder for the person leaves a ghost that has a name as it is: +// its name (the Matrix side's too), its identifiers, the username its metadata keeps and whether it is a bot, +// while a valid ID the placeholder carries still goes in (the IGID↔FBID mapping). Its name its Matrix side has +// not taken yet goes there again, as the ghost holds it under the lock any profile's push holds, its avatar +// left to the profile alone; contact information never set is left for bridgekit's fill. A ghost without a +// name takes the placeholder as before, its whole profile in every one its Matrix side is given, and a profile +// that is no placeholder goes as it came, one whose name is "Instagram User" too. +func TestXessengerPlaceholderKeepsNamedGhost(t *testing.T) { + ctx := context.Background() + raw, err := sql.Open("sqlite3", "file:"+filepath.Join(t.TempDir(), "bridge.db")+"?_foreign_keys=on") + if err != nil { + t.Fatal(err) + } + defer raw.Close() + db, err := dbutil.NewWithDB(raw, "sqlite3") + if err != nil { + t.Fatal(err) + } + intent := &placeholderIntent{} + br := bridgev2.NewBridge("", db, zerolog.Nop(), &bridgeconfig.BridgeConfig{}, &placeholderFixtureMatrix{intent: intent}, &fixtureNetwork{}, func(*bridgev2.Bridge) bridgev2.CommandProcessor { return nil }) + br.BackgroundCtx = ctx + if err = br.DB.Upgrade(ctx); err != nil { + t.Fatal(err) + } + ic := &IGClient{Main: &IGConnector{Config: Config{DisplaynameTemplate: `{{or .DisplayName .Username "Unknown user"}}`}}} + if err = ic.Main.Config.PostProcess(); err != nil { + t.Fatal(err) + } + // The IGID↔FBID mapping updateGhostIGID keeps, as the connector makes it. + ic.Main.DB = metadb.New(br.ID, br.DB.Database, zerolog.Nop()) + if err = ic.Main.DB.Upgrade(ctx); err != nil { + t.Fatal(err) + } + // A ghost as the bridge keeps one: a named one with its profile set on the Matrix side. + ghost := func(id networkid.UserID, name, username string) *bridgev2.Ghost { + g, err := br.GetGhostByID(ctx, id) + if err != nil { + t.Fatal(err) + } + if name != "" { + g.Name, g.NameSet, g.AvatarSet = name, true, true + g.Identifiers, g.ContactInfoSet = []string{"instagram:" + username}, true + g.Metadata.(*metaid.GhostMetadata).Username = username + } + intent.ghost, intent.names, intent.metas, intent.avatars, intent.pushed = g, nil, 0, nil, nil + return g + } + meta := func(g *bridgev2.Ghost) *metaid.GhostMetadata { return g.Metadata.(*metaid.GhostMetadata) } + placeholder := func() *bridgev2.UserInfo { + return ic.wrapUserInfo(&slidetypes.User{Username: "Instagram User", FullName: "Instagram User"}) + } + // A search result says nothing of the account being a bot: bridgev2 sends the ghost's identifiers only when + // the profile gives some, which the placeholder's no longer does. + search := func() *bridgev2.UserInfo { + return ic.wrapSearchResultInfo(&slidetypes.SearchResult{Username: "Instagram User", FullName: "Instagram User"}) + } + // Every profile the ghost's Matrix side was given held all of `want` (the rooms keep the last one they take), + // and there was one. + whole := func(what string, want pushedProfile) { + if len(intent.pushed) == 0 { + t.Errorf("%s: no profile given", what) + } + for _, got := range intent.pushed { + if got.name != want.name || !slices.Equal(got.ids, want.ids) || got.username != want.username { + t.Errorf("%s: a profile given without the rest of it: %+v", what, got) + } + } + } + thePlaceholder := pushedProfile{placeholderName, []string{"instagram:Instagram User"}, "Instagram User"} + + for what, given := range map[string]func() *bridgev2.UserInfo{"a profile": placeholder, "a search result": search} { + named := ghost(networkid.UserID("named "+what), "윤선", "yoonseon") + meta(named).IGID, named.IsBot = "777", true + named.UpdateInfo(ctx, given()) + if named.Name != "윤선" || !slices.Equal(named.Identifiers, []string{"instagram:yoonseon"}) || meta(named).Username != "yoonseon" || !named.IsBot || len(intent.names) != 0 || intent.metas != 0 { + t.Errorf("%s of the placeholder on a named ghost: %q %v %q bot %v %v %d", what, named.Name, named.Identifiers, meta(named).Username, named.IsBot, intent.names, intent.metas) + } + // A placeholder without an ID takes none away. + if meta(named).IGID != "777" { + t.Errorf("%s of the placeholder without an ID on a named ghost: IGID %q", what, meta(named).IGID) + } + + unnamed := ghost(networkid.UserID("unnamed "+what), "", "") + unnamed.UpdateInfo(ctx, given()) + if unnamed.Name != placeholderName || !slices.Equal(intent.names, []string{placeholderName}) || + !slices.Equal(unnamed.Identifiers, []string{"instagram:Instagram User"}) || meta(unnamed).Username != "Instagram User" { + t.Errorf("%s of the placeholder on a ghost without a name: %q %v %v %q", what, unnamed.Name, intent.names, unnamed.Identifiers, meta(unnamed).Username) + } + whole(what+" of the placeholder on a ghost without a name", thePlaceholder) + } + + // A named ghost whose ID came with no mapping yet (its name from a message's sender), then the placeholder + // with its ID: the mapping goes in, and the rest stays. + sender := ghost("sender", "윤선", "yoonseon") + sender.UpdateInfo(ctx, ic.wrapUserInfo(&slidetypes.User{ID: "4242", Username: "Instagram User", FullName: "Instagram User", InteropMessagingUserFBID: 100042})) + fbid, err := ic.Main.DB.GetFBIDForIGUser(ctx, "4242") + if err != nil || fbid != 100042 || meta(sender).IGID != "4242" { + t.Errorf("the placeholder with an ID on a named ghost: IGID %q, FBID %d %v", meta(sender).IGID, fbid, err) + } + if sender.Name != "윤선" || !slices.Equal(sender.Identifiers, []string{"instagram:yoonseon"}) || meta(sender).Username != "yoonseon" || len(intent.names) != 0 || intent.metas != 0 { + t.Errorf("the placeholder with an ID on a named ghost: %q %v %q %v %d", sender.Name, sender.Identifiers, meta(sender).Username, intent.names, intent.metas) + } + + // A ghost that took the placeholder while the homeserver was down: its name and its picture's removal go to + // the Matrix side the next time the placeholder comes, as bridgev2 sends again what it did not take, and its + // contact information is left for bridgekit's fill (whose extra profile fields never fail). + failed := ghost("failed", "", "") + intent.failNames, intent.failMetas, intent.failAvatars = 1, 1, 1 + failed.UpdateInfo(ctx, search()) + if failed.Name != placeholderName || failed.NameSet || failed.ContactInfoSet { + t.Fatalf("the placeholder while the homeserver failed: %q name set %v contact set %v", failed.Name, failed.NameSet, failed.ContactInfoSet) + } + if failed.AvatarSet { + t.Errorf("the placeholder while the homeserver failed: avatar set") + } + failed.UpdateInfo(ctx, search()) + if !slices.Equal(intent.names, []string{placeholderName, placeholderName}) || intent.metas != 1 || !failed.NameSet || failed.ContactInfoSet || + !slices.Equal(failed.Identifiers, []string{"instagram:Instagram User"}) || !slices.Equal(intent.avatars, []id.ContentURIString{"", ""}) || !failed.AvatarSet { + t.Errorf("the placeholder again: %v %d name set %v contact set %v %v avatars %q avatar set %v", intent.names, intent.metas, failed.NameSet, failed.ContactInfoSet, failed.Identifiers, intent.avatars, failed.AvatarSet) + } + whole("the placeholder again after the homeserver failed", thePlaceholder) + // One named whose name the Matrix side did not take: its own name goes again, not the placeholder's. + unsent := ghost("unsent", "윤선", "yoonseon") + unsent.NameSet, unsent.ContactInfoSet = false, false + unsent.UpdateInfo(ctx, search()) + if unsent.Name != "윤선" || !slices.Equal(intent.names, []string{"윤선"}) || intent.metas != 0 || !unsent.NameSet || unsent.ContactInfoSet || + !slices.Equal(unsent.Identifiers, []string{"instagram:yoonseon"}) || meta(unsent).Username != "yoonseon" { + t.Errorf("the placeholder on a named ghost not set on the Matrix side: %q %v %d %v %v %v %q", unsent.Name, intent.names, intent.metas, unsent.NameSet, unsent.ContactInfoSet, unsent.Identifiers, meta(unsent).Username) + } + whole("the placeholder on a named ghost not set on the Matrix side", pushedProfile{"윤선", []string{"instagram:yoonseon"}, "yoonseon"}) + // Its name sent again while a profile with a new name comes (a message's sender): the name goes again as any + // profile's does, holding the ghost's sync lock, so the new name is the last the Matrix side takes, as the + // bridge keeps it. + racing := ghost("racing", "윤선", "yoonseon") + racing.NameSet = false + held, release := make(chan struct{}), make(chan struct{}) + intent.hold = func() { close(held); <-release } + ended := func(done <-chan struct{}, what string) { + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("%s did not end", what) + } + } + placeholderDone, profileDone := make(chan struct{}), make(chan struct{}) + go func() { defer close(placeholderDone); racing.UpdateInfo(ctx, search()) }() + ended(held, "the name sent again") + go func() { + defer close(profileDone) + racing.UpdateInfo(ctx, ic.wrapUserInfo(&slidetypes.User{Username: "yoonseon", FullName: "윤선 새 이름"})) + }() + // Outside the lock the new name would go now, before the one sent again; under it, it waits for that one. + select { + case <-profileDone: + case <-time.After(300 * time.Millisecond): + } + close(release) + ended(placeholderDone, "the placeholder") + ended(profileDone, "the new profile") + last := "" + if n := len(intent.names); n > 0 { + last = intent.names[n-1] + } + if racing.Name != "윤선 새 이름" || !racing.NameSet || last != "윤선 새 이름" { + t.Errorf("a new name while the placeholder sent the name again: %q name set %v, the Matrix side's last %q of %v", racing.Name, racing.NameSet, last, intent.names) + } + // One made before the bridge kept identifiers, which bridgekit's fill has not reached yet (the placeholder + // right after a start): nothing of its contact information goes or is marked set, so the fill, which passes + // over a ghost once it is, still gives it those of the username its metadata keeps. + for what, given := range map[string]func() *bridgev2.UserInfo{"a profile": placeholder, "a search result": search} { + early := ghost(networkid.UserID("early "+what), "윤선", "yoonseon") + early.Identifiers, early.ContactInfoSet = nil, false + early.UpdateInfo(ctx, given()) + if early.Name != "윤선" || len(intent.names) != 0 || intent.metas != 0 || early.ContactInfoSet || + len(early.Identifiers) != 0 || meta(early).Username != "yoonseon" { + t.Errorf("%s of the placeholder on a named ghost made before identifiers were kept: %q %v %d contact set %v %v %q", what, early.Name, intent.names, intent.metas, early.ContactInfoSet, early.Identifiers, meta(early).Username) + } + } + // One with a picture whose name and contact information did not go yet, given the placeholder without a + // picture while the homeserver fails the removal: its name goes again and nothing marks the picture set, so + // the next placeholder removes it again. + pictured := ghost("pictured", "윤선", "yoonseon") + pictured.AvatarID, pictured.AvatarMXC, pictured.NameSet, pictured.ContactInfoSet = "old-picture", "mxc://example.com/old", false, false + intent.failAvatars = 1 + pictured.UpdateInfo(ctx, search()) + if pictured.AvatarMXC != "" || pictured.AvatarSet { + t.Errorf("the placeholder without a picture while the homeserver failed: %q avatar set %v", pictured.AvatarMXC, pictured.AvatarSet) + } + pictured.UpdateInfo(ctx, search()) + if !slices.Equal(intent.avatars, []id.ContentURIString{"", ""}) || !pictured.AvatarSet { + t.Errorf("the placeholder without a picture again: %q avatar set %v", intent.avatars, pictured.AvatarSet) + } + + real := ghost("real", "윤선", "yoonseon") + real.UpdateInfo(ctx, ic.wrapUserInfo(&slidetypes.User{Username: "kim.minsu", FullName: "김민수"})) + if real.Name != "김민수" || !slices.Equal(intent.names, []string{"김민수"}) || + !slices.Equal(real.Identifiers, []string{"instagram:kim.minsu"}) || meta(real).Username != "kim.minsu" { + t.Errorf("a profile that is no placeholder: %q %v %v %q", real.Name, intent.names, real.Identifiers, meta(real).Username) + } + // A person whose name is "Instagram User" changing their username: their profile goes as it came. + self := ghost("self-named", "Instagram User", "old.name") + self.UpdateInfo(ctx, ic.wrapUserInfo(&slidetypes.User{Username: "new.name", FullName: "Instagram User"})) + if !slices.Equal(self.Identifiers, []string{"instagram:new.name"}) || meta(self).Username != "new.name" { + t.Errorf("a person named Instagram User with a new username: %v %q", self.Identifiers, meta(self).Username) + } +}