// Copyright (c) 2026 Xessenger // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. package bridgekit import ( "context" "errors" "fmt" "slices" "time" "github.com/rs/zerolog" "maunium.net/go/mautrix/bridgev2" "maunium.net/go/mautrix/bridgev2/networkid" ) // A contact's identifiers (tel:+82..., instagram:name) are the handle its encrypted profile events // carry (meta.go handleOf), which the app shows beside the name and searches by. bridgev2 keeps them // only for a homeserver that takes extra profile fields (ghost.go prepareContactInfo), which Synapse // does not, so the bridge says it does where it keeps them: they go into the encrypted profile events // alone, never a homeserver profile (ghost.go SetExtraProfileMeta). // handleNetworks are the networks whose contacts' handles the app shows, as the server did from a DM's // bridge info (peer-profile.patch, directPeerHandle): the Instagram username and the WhatsApp number. var handleNetworks = map[string]bool{"instagram": true, "whatsapp": true} // keepsIdentifiers reports whether the bridge keeps its contacts' identifiers. func (k *Kit) keepsIdentifiers() bool { return handleNetworks[k.network] } // keepIdentifiers has bridgev2 keep the phone numbers among them too (phone_numbers_in_profile), which // it would otherwise drop before they reach SetExtraProfileMeta. func (k *Kit) keepIdentifiers() { if k.keepsIdentifiers() && k.br.Config != nil { k.br.Config.PhoneNumbersInProfile = true } } // GetCapabilities says the homeserver takes extra profile fields where the bridge keeps its contacts' // identifiers, so that bridgev2 keeps them and passes their changes to SetExtraProfileMeta. func (c *connector) GetCapabilities() *bridgev2.MatrixCapabilities { caps := c.Connector.GetCapabilities() if !c.kit.keepsIdentifiers() || (caps != nil && caps.ExtraProfileMeta) { return caps } kept := bridgev2.MatrixCapabilities{} if caps != nil { kept = *caps } kept.ExtraProfileMeta = true return &kept } // GhostIdentifiers is what a network connector implements to name a ghost's identifiers from what the // bridge stored of it (a username in its metadata, the phone number its ID is), for the ghosts made // before the bridge kept them (fillIdentifiers). Nil when it knows none; an error when what it stored // could not be read, and the ghost goes again. type GhostIdentifiers interface { GhostIdentifiers(ctx context.Context, ghost *bridgev2.Ghost) ([]string, error) } // fillRetries are the waits before a start's fill goes again over the ghosts it left: those whose // identifiers could not be read or whose profiles did not all go, as when the homeserver is starting // again with the bridge. What is still left after the last goes again on the next start. var fillRetries = []time.Duration{time.Minute, 5 * time.Minute, 30 * time.Minute} // fillIdentifiers gives the ghosts bridgev2 holds no contact information for (contact_info_set, false // for every ghost made before the bridge kept identifiers) those their network names from what the // bridge stored, and sends their encrypted profiles again with the handle, one ghost after another. A // ghost counts as done (contact_info_set) once its profile went into every room that held another // (sendEncryptedStateOnce sends nothing where the room already has it): bridgev2 tells what changes // after. It runs once a start, in the background, once encryption runs, and goes again over what it // left (fillRetries). func (k *Kit) fillIdentifiers(ctx context.Context) { named, ok := k.br.Network.(GhostIdentifiers) if !ok || !k.keepsIdentifiers() || !k.identifiersFilled.CompareAndSwap(false, true) { return } log := zerolog.Ctx(ctx).With().Str("action", "fill ghost identifiers").Logger() for pass := 0; ; pass++ { left := k.fillPass(ctx, named, &log) if left == 0 || ctx.Err() != nil { return } else if pass == len(fillRetries) { // The next start goes over them again, as would a fill started again here with encryption. k.identifiersFilled.Store(false) return } select { case <-ctx.Done(): return case <-time.After(fillRetries[pass]): } } } // fillPass goes once over the ghosts without contact information, and returns how many it left. func (k *Kit) fillPass(ctx context.Context, named GhostIdentifiers, log *zerolog.Logger) int { ghostIDs, err := k.ghostsWithoutContactInfo(ctx) if err != nil { log.Err(err).Msg("Failed to list the ghosts without contact information") return 1 } filled, left := 0, 0 for _, ghostID := range ghostIDs { if ctx.Err() != nil { return left + 1 } filledIn, err := k.fillGhost(ctx, named, ghostID) if err != nil { log.Err(err).Str("ghost_id", string(ghostID)).Msg("Failed to fill in the ghost's identifiers") left++ } else if filledIn { filled++ } } log.Info().Int("ghosts", len(ghostIDs)).Int("filled", filled).Int("left", left).Msg("Filled in the ghosts' identifiers") return left } // fillGhost fills in one ghost: it saves the identifiers its network names if they changed, sends its // profiles with them, and marks it done. What fails leaves it as it was, to go again; identifiers saved // by then go out again with it, as it is still not done. It reports whether the ghost has identifiers // now, or had those it held cleared. func (k *Kit) fillGhost(ctx context.Context, named GhostIdentifiers, ghostID networkid.UserID) (bool, error) { // The ghost bridgev2 holds, so that what it sends next has them too. ghost, err := k.br.GetExistingGhostByID(ctx, ghostID) if err != nil { return false, fmt.Errorf("failed to get the ghost: %w", err) } else if ghost == nil || ghost.ContactInfoSet { return false, nil } identifiers, err := named.GhostIdentifiers(ctx, ghost) if err != nil { return false, fmt.Errorf("failed to read what the bridge stored of the ghost: %w", err) } identifiers = slices.Clone(identifiers) slices.Sort(identifiers) changed := !slices.Equal(identifiers, ghost.Identifiers) if changed { // Saved before the profiles go, which carry them (sendMemberProfile reads the ghost). The ghost bridgev2 // holds keeps what it had if they could not be saved, so that the next try saves them first again. kept := ghost.Identifiers ghost.Identifiers = identifiers if err = k.br.DB.Ghost.Update(ctx, ghost.Ghost); err != nil { ghost.Identifiers = kept return false, fmt.Errorf("failed to save the ghost's identifiers: %w", err) } } // Sent even when nothing changed: an earlier try may have sent identifiers since taken back into some // of the rooms before it failed, and those rooms keep them until the profile without them goes. if err = k.sendGhostProfiles(ctx, ghostID); err != nil { return false, err } ghost.ContactInfoSet = true if err = k.br.DB.Ghost.Update(ctx, ghost.Ghost); err != nil { ghost.ContactInfoSet = false return false, fmt.Errorf("failed to save the ghost as done: %w", err) } return changed || len(identifiers) > 0, nil } // sendGhostProfiles sends a ghost's profile into the encrypted rooms of its hashed ghost that their // owner reads, and returns what did not go. A ghost in no encrypted room has nothing to send: its // profile goes as it joins one (ghost.go EnsureJoined), with what the ghost holds then. func (k *Kit) sendGhostProfiles(ctx context.Context, ghostID networkid.UserID) error { hashed := k.ghosts.hashed(ghostID) if hashed == "" { return nil } rooms, err := k.store.roomsOf(ctx, hashed, true) if err != nil { return fmt.Errorf("failed to list the hashed ghost's rooms: %w", err) } var errs []error for _, roomID := range rooms { if !k.isEncrypted(ctx, roomID) || !k.ownerPresent(ctx, roomID) { continue } if err = k.sendMemberProfile(ctx, roomID, ghostID); err != nil { errs = append(errs, fmt.Errorf("failed to send the profile into %s: %w", roomID, err)) } } return errors.Join(errs...) } // ghostsWithoutContactInfo lists this bridge's ghosts whose contact information bridgev2 never set. func (k *Kit) ghostsWithoutContactInfo(ctx context.Context) ([]networkid.UserID, error) { rows, err := k.db.Query(ctx, `SELECT id FROM ghost WHERE bridge_id=$1 AND NOT contact_info_set`, k.br.ID) if err != nil { return nil, err } defer rows.Close() var ghostIDs []networkid.UserID for rows.Next() { var ghostID networkid.UserID if err = rows.Scan(&ghostID); err != nil { return nil, err } ghostIDs = append(ghostIDs, ghostID) } return ghostIDs, rows.Err() }