package migrate import ( "encoding/json" "regexp" "sort" ) // Event is a room event as Synapse's /messages returns it, to the bridge bot or to the admin. type Event struct { ID string `json:"event_id"` Type string `json:"type"` StateKey *string `json:"state_key,omitempty"` Sender string `json:"sender"` Timestamp int64 `json:"origin_server_ts"` Content json.RawMessage `json:"content"` Unsigned struct { RedactedBecause json.RawMessage `json:"redacted_because,omitempty"` } `json:"unsigned"` } // Counts is what a plaintext room holds that a move takes along. A move writes one event for // each message and reaction, so Messages+Reactions is also what it writes. Undigestable counts the // events whose content canonical JSON cannot write (a fraction, an integer beyond 2^53-1), which // the app could not hash as the bridge does; Synapse refuses those in room versions 6 and later. type Counts struct { Messages int `json:"messages"` Reactions int `json:"reactions"` Files int `json:"files"` Undigestable int `json:"undigestable"` } // messageTypes are the events a move writes again as messages. var messageTypes = map[string]bool{ "m.room.message": true, "m.sticker": true, "m.poll.start": true, "org.matrix.msc3381.poll.start": true, } var mxcPattern = regexp.MustCompile(`^mxc://([a-zA-Z0-9.:-]+)/([a-zA-Z0-9_-]{5,200})$`) // Counter counts a plaintext room page by page, in any order. Encrypted events, state events and // deleted (redacted) events count for nothing; an edit counts as no message of its own, but the // files it points to are the room's files all the same. type Counter struct { // Server is this homeserver's name: only its files are the room's to delete. Server string // SharedFiles leaves out the files a bridge hands every room alike (Telegram's stickers and // GIFs come from its file cache): other rooms still show them, so they are neither counted // nor deleted. SharedFiles bool messages map[string]bool reactions map[string]string files map[string]bool undigestable map[string]bool } func NewCounter(server string, sharedFiles bool) *Counter { return &Counter{ Server: server, SharedFiles: sharedFiles, messages: map[string]bool{}, reactions: map[string]string{}, files: map[string]bool{}, undigestable: map[string]bool{}, } } type relation struct { RelType string `json:"rel_type"` EventID string `json:"event_id"` } type messageContent struct { RelatesTo *relation `json:"m.relates_to"` } // Add counts one event. func (c *Counter) Add(evt Event) { if evt.StateKey != nil || evt.Type == "m.room.encrypted" || isRedacted(evt) { return } if messageTypes[evt.Type] || evt.Type == "m.reaction" { if _, err := Canonical(evt.Content); err != nil { c.undigestable[evt.ID] = true } } var content messageContent _ = json.Unmarshal(evt.Content, &content) switch { case messageTypes[evt.Type]: for _, id := range c.FileIDs(evt) { c.files[id] = true } if content.RelatesTo != nil && content.RelatesTo.RelType == "m.replace" { return } c.messages[evt.ID] = true case evt.Type == "m.reaction": if content.RelatesTo != nil && content.RelatesTo.RelType == "m.annotation" && content.RelatesTo.EventID != "" { c.reactions[evt.ID] = content.RelatesTo.EventID } } } // Result is what was counted so far. A reaction counts once the message it is on has counted: // one on a deleted message, or on anything that is not a message, is not moved. func (c *Counter) Result() Counts { result := Counts{Messages: len(c.messages), Files: len(c.files), Undigestable: len(c.undigestable)} for _, target := range c.reactions { if c.messages[target] { result.Reactions++ } } return result } // MediaIDs are the media IDs of the counted files, sorted. func (c *Counter) MediaIDs() []string { ids := make([]string, 0, len(c.files)) for id := range c.files { ids = append(ids, id) } sort.Strings(ids) return ids } func isRedacted(evt Event) bool { raw := evt.Unsigned.RedactedBecause return len(raw) > 0 && string(raw) != "null" } // FileIDs are the media IDs of this homeserver an event's content points to: the file, its // thumbnail, an edit's new file and thumbnail, and the preview pictures of its links. func (c *Counter) FileIDs(evt Event) []string { if !messageTypes[evt.Type] { return nil } var top map[string]json.RawMessage if json.Unmarshal(evt.Content, &top) != nil { return nil } sources := []map[string]json.RawMessage{top} if raw, ok := top["m.new_content"]; ok { var next map[string]json.RawMessage if json.Unmarshal(raw, &next) == nil && next != nil { sources = append(sources, next) } } if c.SharedFiles { if evt.Type == "m.sticker" { return nil } for _, source := range sources { info := object(source["info"]) if truthy(info["fi.mau.gif"]) || truthy(info["fi.mau.bridged_sticker"]) { return nil } } } var ids []string seen := map[string]bool{} add := func(raw json.RawMessage) { var uri string if json.Unmarshal(raw, &uri) != nil { return } if id, ok := c.localMediaID(uri); ok && !seen[id] { seen[id] = true ids = append(ids, id) } } for _, source := range sources { add(source["url"]) add(object(source["file"])["url"]) info := object(source["info"]) add(info["thumbnail_url"]) add(object(info["thumbnail_file"])["url"]) if !c.SharedFiles { var previews []json.RawMessage if json.Unmarshal(source["com.beeper.linkpreviews"], &previews) == nil { for _, raw := range previews { preview := object(raw) add(preview["og:image"]) add(object(preview["beeper:image:encryption"])["url"]) } } } } return ids } func (c *Counter) localMediaID(uri string) (string, bool) { match := mxcPattern.FindStringSubmatch(uri) if match == nil || match[1] != c.Server { return "", false } return match[2], true } func object(raw json.RawMessage) map[string]json.RawMessage { var value map[string]json.RawMessage if len(raw) == 0 || json.Unmarshal(raw, &value) != nil { return nil } return value } // truthy follows JavaScript: the API's counter decides the same way (privacy/synapse.ts). func truthy(raw json.RawMessage) bool { if len(raw) == 0 { return false } var value any if json.Unmarshal(raw, &value) != nil { return false } switch v := value.(type) { case nil: return false case bool: return v case float64: return v != 0 case string: return v != "" default: return true } }