package migrate import ( "context" "errors" "fmt" "strings" "unicode" "unicode/utf16" "github.com/rs/zerolog" "maunium.net/go/mautrix" "maunium.net/go/mautrix/bridgev2/database" "maunium.net/go/mautrix/bridgev2/networkid" "maunium.net/go/mautrix/event" "maunium.net/go/mautrix/id" ) // A moved group whose portal has no name the app shows has a new room without one: an encrypted room is // named only in its metadata (bridgekit's com.xessenger.room_meta), and the app shows the group by its // people's names. The messenger named the group empty as the move asked for its info (moveChatInfo // keeps the bridge's name since), or the portal's name went around the move otherwise (Telegram's groups // had names of a few bytes as their new rooms were made, shown as none for some of them, and an Instagram // group's went short hours after, for reasons not yet found). // The old room keeps the name it had, which the portal gets again: as each move finishes // (fillNameAfterMove), at each start for what that missed (fillMovedNames), and before the old room is // let go of for deletion when no start looked at it, as the name's last copy goes with the room // (releasePortalRoom). // fillMovedNames gives each moved group whose portal has no name the app shows the name its old room // has, sends the new room's metadata again with it, and sends the metadata of a moved group whose // portal has a name as the portal has it (a group named in the bridge whose metadata went without it: // the metadata is sent again only where it changed since it last went). It runs once a start, once the // bridge's encryption runs, as the metadata goes encrypted (bridgekit's WhenEncrypting). Each moved // portal is looked at once (name_checked), whatever it then has: a name taken off on the messenger later // stays off, and a name given since the move is never replaced. A DM takes its contact's name, and is // left as it is. What did not go (the room's owner away, say) is not marked, and is looked at again with // the next start. Each portal's outcome but a DM's, with the names by their size and kind only // (nameLook.logged), and the counts are logged as warnings: the enclave's supervisor keeps no info lines. func (m *mover) fillMovedNames(ctx context.Context) { if !m.namesFilled.CompareAndSwap(false, true) { return } log := zerolog.Ctx(ctx).With().Str("action", "fill moved names").Logger() ctx = log.WithContext(ctx) rows, err := m.store.namesToCheck(ctx) if err != nil { log.Err(err).Msg("Failed to list the moved portals whose names were not looked at") return } counts := map[nameOutcome]int{} failed := 0 for _, row := range rows { if ctx.Err() != nil { log.Warn().Int("rooms", len(rows)).Msg("Stopped looking at the moved portals' names") return } look, err := m.fillMovedName(ctx, row, true) if err == nil { err = m.store.nameChecked(ctx, row.OldRoom) } if err != nil { // Looked at again with the next start. log.Warn().Err(err).Stringer("old_room_id", row.OldRoom).Stringer("room_id", row.NewRoom).Msg("Could not look at a moved portal's name; the next start looks again") failed++ continue } counts[look.outcome]++ if look.outcome != nameDM { look.logged(log.Warn()).Stringer("old_room_id", row.OldRoom).Stringer("room_id", row.NewRoom).Msg("Looked at a moved portal's name") } } if len(rows) > 0 { summary := log.Warn().Int("rooms", len(rows)).Int("failed", failed) for _, outcome := range nameOutcomes { summary = summary.Int(string(outcome), counts[outcome]) } summary.Msg("Looked at the moved portals' names") } } // fillNameAfterMove looks at the portal a move just finished as a start does (fillMovedName): the // bridge starts again only as it is deployed, and a group moved meanwhile would stay unnamed till then. // The portal is not marked looked at, so that the next start looks at it again, a name lost after the // move with it; what failed waits for that start, or for the old room to be let go of. func (m *mover) fillNameAfterMove(ctx context.Context, row *room) { log := zerolog.Ctx(ctx).With().Stringer("old_room_id", row.OldRoom).Stringer("room_id", row.NewRoom).Logger() if look, err := m.fillMovedName(ctx, row, true); err != nil { log.Warn().Err(err).Msg("Could not look at the moved portal's name; the next start looks again") } else if look.outcome == nameFilled || look.outcome == nameResent { look.logged(log.Warn()).Msg("Sent the moved group's name in its room's metadata") } } // nameOutcome is what looking at a moved portal's name came to (fillMovedName). type nameOutcome string const ( // nameFilled: the group had no name the app shows, and took its old room's, which went in the // metadata. nameFilled nameOutcome = "filled" // nameResent: the group had a name its metadata did not have, which went now. nameResent nameOutcome = "resent" // nameKept: the group had a name its metadata had already. nameKept nameOutcome = "kept" // nameNamed: the group has a name the app shows, and its metadata was not looked at // (releasePortalRoom). nameNamed nameOutcome = "named" // nameDM: a DM, which takes its contact's name. nameDM nameOutcome = "dm" // nameNoName: the group has no name the app shows, and neither had its old room. With resend, its // metadata went as the portal has it where the portal or the old room has a name of any kind // (fillMovedName). nameNoName nameOutcome = "no_name" // nameGone: the portal is gone, lives in a room of a later move, or is a space. nameGone nameOutcome = "gone" // namePlain: the new room is not encrypted (the move stopped there: errNotEncrypted). namePlain nameOutcome = "not_encrypted" ) // nameOutcomes are the outcomes in the order the counts are logged. var nameOutcomes = []nameOutcome{nameFilled, nameResent, nameKept, nameNamed, nameDM, nameNoName, nameGone, namePlain} // nameLook is what looking at a moved portal's name came to (fillMovedName): its outcome, the name the // group's metadata carries now (filled, resent, kept), and the name the portal had of its own before // (filled, no_name). type nameLook struct { outcome nameOutcome name string before string } // logged adds the look to a log line: its outcome, and its names by their size in bytes and their kind // (nameKind) only, never the names, which are the person's. func (l nameLook) logged(e *zerolog.Event) *zerolog.Event { e = e.Str("outcome", string(l.outcome)) if l.outcome == nameFilled || l.outcome == nameResent || l.outcome == nameKept { e = e.Int("name_bytes", len(l.name)).Str("name_kind", nameKind(l.name)) } if l.outcome == nameFilled || l.outcome == nameNoName { e = e.Int("portal_name_bytes", len(l.before)).Str("portal_name_kind", nameKind(l.before)) } return e } // maxShownName is the most UTF-16 code units of a name the app shows. const maxShownName = 255 // nameKind is what a group's name is to the app, told without the name: "empty", "whitespace" (white // space only), "unknown" ("unknown" or "unknown user"), "too_long", which the app shows as no name, or // "digits_symbols" (no letter in it) or "other", which it shows. The app's rule is senderDisplayName's // (apps/api/src/matrix/profiles.ts), which the desktop reads a room's metadata with (local-core room.ts): // the name trimmed as JavaScript trims, then nothing if empty, longer than maxShownName code units, or // "unknown" or "unknown user" in any case of its ASCII letters (the pattern's i flag). func nameKind(name string) string { trimmed := strings.TrimFunc(name, jsSpace) switch { case name == "": return "empty" case trimmed == "": return "whitespace" case unknownName(trimmed): return "unknown" case len(utf16.Encode([]rune(trimmed))) > maxShownName: return "too_long" case !strings.ContainsFunc(trimmed, unicode.IsLetter): return "digits_symbols" } return "other" } // shownName reports whether the app shows a group named name by that name (nameKind), rather than by its // people's names. func shownName(name string) bool { kind := nameKind(name) return kind == "other" || kind == "digits_symbols" } // unknownName reports whether a trimmed name is "unknown" or "unknown user" as the app's pattern // /^unknown(?: user)?$/i matches it: without the u flag, only ASCII letters match in another case. func unknownName(trimmed string) bool { lower := []byte(trimmed) for i, c := range lower { if 'A' <= c && c <= 'Z' { lower[i] = c + 'a' - 'A' } } return string(lower) == "unknown" || string(lower) == "unknown user" } // fillMovedName gives one moved portal its old room's name if it is a group without a name the app // shows (shownName), and sends its room's metadata again; with resend, a group with a name gets its // metadata sent as the portal has it (sent only where it changed since it last went), as does one whose // portal or old room has a name the app does not show, and neither one it shows. It reports what // it came to; an error leaves the portal with the name it had, in memory too, to be looked at with the // next start: metadata that did not go, the room's owner away for one, is an error, not a name filled in. func (m *mover) fillMovedName(ctx context.Context, row *room, resend bool) (nameLook, error) { portal, err := m.br.GetExistingPortalByKey(ctx, networkid.PortalKey{ID: row.PortalID, Receiver: row.PortalReceiver}) if err != nil { return nameLook{}, fmt.Errorf("failed to get the portal: %w", err) } else if portal == nil || portal.MXID != row.NewRoom || portal.RoomType == database.RoomTypeSpace { // Gone, or moved on to a room of a later move. return nameLook{outcome: nameGone}, nil } else if portal.RoomType == database.RoomTypeDM { return nameLook{outcome: nameDM}, nil } else if shownName(portal.Name) && !resend { return nameLook{outcome: nameNamed}, nil } sender, ok := m.kit.(RoomMetaSender) if !ok { return nameLook{}, errors.New("the bridge cannot send a room's metadata") } // Read as the bot without joining (its intent's reads join first), as the old room's name is. var encryption event.EncryptionEventContent if encrypted, err := encryptionOf(&encryption, m.conn.Bot.Client.StateEvent(ctx, row.NewRoom, event.StateEncryption, "", &encryption)); err != nil { return nameLook{}, err } else if !encrypted { // The move stopped there (errNotEncrypted): a person looks at it. return nameLook{outcome: namePlain}, nil } if shownName(portal.Name) { went, err := sender.SendRoomMeta(ctx, row.NewRoom) if err != nil { return nameLook{}, fmt.Errorf("failed to send the room's metadata: %w", err) } else if went { return nameLook{outcome: nameResent, name: portal.Name}, nil } return nameLook{outcome: nameKept, name: portal.Name}, nil } before := portal.Name name, err := m.oldRoomName(ctx, row.OldRoom) if err != nil { return nameLook{}, err } else if !shownName(name) { // A name the app would not show either leaves the portal's as it is. With resend, the metadata still // goes as the portal has it (where it changed since it last went) wherever the portal or its old room // has a name of any kind, as it went before such names were told apart (as a named portal's, or with // the old room's name filled in), so metadata that did not go before is not marked looked at unsent. if resend && (before != "" || name != "") { if _, err = sender.SendRoomMeta(ctx, row.NewRoom); err != nil { return nameLook{}, fmt.Errorf("failed to send the room's metadata: %w", err) } } return nameLook{outcome: nameNoName, before: before}, nil } // Set here, not through bridgev2's UpdateInfo: the m.room.name that would send goes into an encrypted // room only as its metadata (bridgekit), sent here with what failed, and UpdateInfo saves without // saying whether it could. The name is saved once the metadata went: a portal saved with a name // whose metadata did not go would not be looked at again. portal.Name = name if _, err = sender.SendRoomMeta(ctx, row.NewRoom); err != nil { portal.Name = before return nameLook{}, fmt.Errorf("failed to send the room's metadata: %w", err) } if err = portal.Save(ctx); err != nil { // Taken back too, as when the metadata did not go: a portal named in memory alone would be passed // over by the next look (the release's next try, which would then let the old room go with the // name's last copy) and saved by nothing. The metadata went with the name: the next look sends it // again, which sends nothing where it went last, and saves the name. portal.Name = before return nameLook{}, fmt.Errorf("failed to save the portal's name: %w", err) } return nameLook{outcome: nameFilled, name: name, before: before}, nil } // oldRoomName is the old room's name (m.room.name), as the bot reads it without joining: the bot left // the old room as the room was let go of (handleRelease), and the homeserver answers a room it left with // the room's state as it left. An old room without a name, or one the homeserver no longer shows the // bot, names nothing. func (m *mover) oldRoomName(ctx context.Context, oldRoom id.RoomID) (string, error) { var content event.RoomNameEventContent err := m.conn.Bot.Client.StateEvent(ctx, oldRoom, event.StateRoomName, "", &content) if isNotFound(err) || errors.Is(err, mautrix.MForbidden) { return "", nil } else if err != nil { return "", fmt.Errorf("failed to read the old room's name: %w", err) } return content.Name, nil }