package migrate import ( "bytes" "encoding/json" "errors" "strings" "maunium.net/go/mautrix/event" ) var errNotObject = errors.New("content is not a JSON object") // prepare turns an item into the content that is written: its relations point at the events moved // before it, and the marker says where it came from and carries the room's digest key (key, as // EncodeDigestKey writes it). A reaction whose message has no moved event is not written (false); a // reply or thread whose target was not moved keeps its message without the relation. func prepare(it item, moved map[string]string, key string) (map[string]any, bool, error) { content, err := decodeObject(it.Content) if err != nil { return nil, false, err } delete(content, "m.new_content") delete(content, MarkerKey) if relation, ok := content["m.relates_to"].(map[string]any); ok { if it.Reaction { target, _ := relation["event_id"].(string) newTarget, ok := moved[target] if !ok { return nil, false, nil } relation["event_id"] = newTarget } else { remapRelation(relation, moved) if len(relation) == 0 { delete(content, "m.relates_to") } } } else if it.Reaction { return nil, false, nil } content[MarkerKey] = map[string]any{"v": MarkerVersion, "from": it.Old.ID, "seq": it.Seq, "key": key} return content, true, nil } // remapRelation points a message's reply and thread at the moved events. A thread whose root was // not moved is dropped whole (with its reply fallback); a reply whose target was not moved loses // only the reply. func remapRelation(relation map[string]any, moved map[string]string) { if relType, _ := relation["rel_type"].(string); relType != "" { target, _ := relation["event_id"].(string) if newTarget, ok := moved[target]; ok { relation["event_id"] = newTarget } else { for key := range relation { delete(relation, key) } return } } if reply, ok := relation["m.in_reply_to"].(map[string]any); ok { target, _ := reply["event_id"].(string) if newTarget, ok := moved[target]; ok { reply["event_id"] = newTarget } else { delete(relation, "m.in_reply_to") delete(relation, "is_falling_back") } } } // mediaRef is a file a content points to: a plaintext mxc URL under urlKey, or an encrypted file // under fileKey. A move puts a fresh encrypted copy under fileKey and removes the URL. type mediaRef struct { container map[string]any urlKey string fileKey string } // mediaRefs finds the files a move copies: the file, its thumbnail and link preview pictures. func mediaRefs(content map[string]any) []mediaRef { refs := []mediaRef{{container: content, urlKey: "url", fileKey: "file"}} if info, ok := content["info"].(map[string]any); ok { refs = append(refs, mediaRef{container: info, urlKey: "thumbnail_url", fileKey: "thumbnail_file"}) } if previews, ok := content["com.beeper.linkpreviews"].([]any); ok { for _, value := range previews { if preview, ok := value.(map[string]any); ok { refs = append(refs, mediaRef{container: preview, urlKey: "og:image", fileKey: "beeper:image:encryption"}) } } } var found []mediaRef for _, ref := range refs { if source, _ := ref.source(); source != "" { found = append(found, ref) } } return found } // source is the file's mxc URI and, for a file that is already encrypted, its keys. func (r mediaRef) source() (string, *event.EncryptedFileInfo) { if raw, ok := r.container[r.fileKey].(map[string]any); ok { if url, ok := encryptedFileURL(raw); ok { data, err := json.Marshal(raw) if err == nil { var file event.EncryptedFileInfo if json.Unmarshal(data, &file) == nil { return url, &file } } } } if url, ok := r.container[r.urlKey].(string); ok && strings.HasPrefix(url, "mxc://") { return url, nil } return "", nil } // replace puts the encrypted copy in place of the file. func (r mediaRef) replace(file *event.EncryptedFileInfo) error { data, err := json.Marshal(file) if err != nil { return err } value, err := decodeObject(data) if err != nil { return err } delete(r.container, r.urlKey) r.container[r.fileKey] = value return nil } // drop removes a file that no longer exists: the message goes without it. func (r mediaRef) drop() { delete(r.container, r.urlKey) delete(r.container, r.fileKey) } // mimeType is the type the content gives its file, if any. func (r mediaRef) mimeType() string { if r.urlKey == "url" { if info, ok := r.container["info"].(map[string]any); ok { mime, _ := info["mimetype"].(string) return mime } } if r.urlKey == "thumbnail_url" { if info, ok := r.container["thumbnail_info"].(map[string]any); ok { mime, _ := info["mimetype"].(string) return mime } } if r.urlKey == "og:image" { mime, _ := r.container["og:image:type"].(string) return mime } return "" } // composeKey holds a mail sent from the app: its url (plaintext rooms, // apps/api/src/matrix/mail-compose.ts) or file (encrypted rooms, the app's contract for them) is // the mail's body, mail.json, which lists the mail's recipients and attachments. The event shows // the body text and the headers itself. const composeKey = "com.xessenger.email.compose" // composeRef finds a mail's body file, which a move copies after the attachments it lists // (rewriteMail). A move puts the encrypted copy under file, as for any file. func composeRef(content map[string]any) (mediaRef, bool) { compose, ok := content[composeKey].(map[string]any) if !ok { return mediaRef{}, false } ref := mediaRef{container: compose, urlKey: "url", fileKey: "file"} source, _ := ref.source() return ref, source != "" } // keepsOldBody says whether written content points at a mail's body (mail.json) in the old room, as // a mail an older bridge wrote does: a move copies the body and puts its encrypted copy under file // (copyCompose), or drops a body that is gone. func keepsOldBody(content json.RawMessage) bool { object, err := decodeObject(content) if err != nil { return false } ref, ok := composeRef(object) if !ok { return false } _, encrypted := ref.source() return encrypted == nil } // rewriteMail gives the attachments a mail's body lists ({url | file, name, type, size}) their // encrypted copies through carry, which says false for a file that is gone: the mail goes without // it. The rest of the body stays as written. A body that is no JSON object, or lists no file, goes // as it was. func rewriteMail(data []byte, carry func(ref mediaRef, mimeType string) (bool, error)) ([]byte, error) { mail, err := decodeObject(data) if err != nil { return data, nil } list, _ := mail["attachments"].([]any) kept := make([]any, 0, len(list)) changed := false for _, value := range list { attachment, ok := value.(map[string]any) if !ok { kept = append(kept, value) continue } ref := mediaRef{container: attachment, urlKey: "url", fileKey: "file"} if source, _ := ref.source(); source == "" { kept = append(kept, value) continue } mimeType, _ := attachment["type"].(string) present, err := carry(ref, mimeType) if err != nil { return nil, err } changed = true if present { kept = append(kept, attachment) } } if !changed { return data, nil } mail["attachments"] = kept // The body's HTML stays as it is written: escaping <, > and & would only make it longer. var out bytes.Buffer encoder := json.NewEncoder(&out) encoder.SetEscapeHTML(false) if err = encoder.Encode(mail); err != nil { return nil, fail(errStore, err) } return bytes.TrimSuffix(out.Bytes(), []byte("\n")), nil }