--- a/pkg/connector/connector.go +++ b/pkg/connector/connector.go @@ -97,17 +97,20 @@ } func (lc *LineConnector) GetConfig() (example string, data any, upgrader configupgrade.Upgrader) { - const base = "qr_login: false\n" + const base = "qr_login: false\ninitial_sync_days: 0\n" return base, &lc.Config, &configupgrade.StructUpgrader{ Base: base, SimpleUpgrader: func(helper configupgrade.Helper) { helper.Copy(configupgrade.Bool, "qr_login") + helper.Copy(configupgrade.Int, "initial_sync_days") }, } } type Config struct { QRLogin bool `yaml:"qr_login"` + // Xessenger: how far back a chat without a room gets one when connecting (xessenger_sync_scope.go). + InitialSyncDays int `yaml:"initial_sync_days"` } func (lc *LineConnector) GetDBMetaTypes() database.MetaTypes { --- a/pkg/connector/sync.go +++ b/pkg/connector/sync.go @@ -287,7 +287,7 @@ if strings.HasPrefix(lowerMid, "c") || strings.HasPrefix(lowerMid, "r") { continue } - if lc.isUserBlocked(mid) { + if lc.isUserBlocked(mid) || lc.xessengerSkipDMResync(ctx, mid) { continue } @@ -696,12 +696,13 @@ func (lc *LineClient) prefetchMessages(ctx context.Context) { defer lc.wg.Done() + readStarted := time.Now() // Xessenger: before the live stream can bring anything (xessenger_sync_scope.go) opts := line.MessageBoxesOptions{ ActiveOnly: true, MessageBoxCountLimit: messageBoxPageLimit, WithUnreadCount: true, - LastMessagesPerMessageBoxCount: 0, + LastMessagesPerMessageBoxCount: lc.xessengerLastMessagesPerBox(), } messageBoxes, err := lc.fetchAllMessageBoxes(ctx, opts) @@ -718,6 +719,7 @@ chatMIDs := collectStartupBackfillChatMIDs(messageBoxes, lc.getKnownMemberChatMIDs(), func(mid string) bool { return lc.isUserBlocked(mid) || lc.shouldSkipDeletedChat(mid, latestMessageIDs[mid]) }) + chatMIDs = lc.xessengerChatsToRead(ctx, chatMIDs, messageBoxes, readStarted) workerCount := prefetchMessagesConcurrency if len(chatMIDs) < workerCount { @@ -910,7 +912,11 @@ continue } + oldGroups := lc.xessengerOldGroupsWithoutRoom(ctx, chatsResp.Chats, memberChatMids) for _, chat := range chatsResp.Chats { + if oldGroups[chat.ChatMid] { + continue + } portalKey := networkid.PortalKey{ID: makePortalID(chat.ChatMid), Receiver: lc.UserLogin.ID} existingPortal, err := lc.UserLogin.Bridge.GetExistingPortalByKey(ctx, portalKey) --- /dev/null +++ b/pkg/connector/xessenger_sync_scope.go @@ -0,0 +1,177 @@ +package connector + +import ( + "context" + "encoding/json" + "time" + + "maunium.net/go/mautrix/bridgev2/networkid" + + "github.com/beeper/line/pkg/line" +) + +// Xessenger: what a connect reads, with network.initial_sync_days above zero (zero keeps upstream's +// reading of every chat on every connect). +// +// - A chat without a room gets one only when its last activity is within initial_sync_days: a group +// from the chat sync, a 1:1 chat from the recent-message read. An older chat gets its room when a +// new message arrives, the way a live message makes any missing room. +// - A chat with a room has its recent messages read again unless its last message was bridged +// before this read started. LINE doesn't replay what was missed while disconnected, so those are +// read; a chat whose last message was already here has nothing newer. + +// xessengerMessageBoxesByIDs is replaced in tests. +var xessengerMessageBoxesByIDs = func(lc *LineClient, ctx context.Context, mids []string) (map[string]line.MessageBox, error) { + _, boxes, err := callLineResult(lc, ctx, func(client *line.Client) (map[string]line.MessageBox, error) { + return client.GetMessageBoxesByIDsContext(ctx, mids) + }) + return boxes, err +} + +func (lc *LineClient) xessengerInitialSyncDays() int { + if network, ok := lc.UserLogin.Bridge.Network.(*LineConnector); ok { + return network.Config.InitialSyncDays + } + return 0 +} + +// xessengerLastMessagesPerBox asks the recent-message read's message boxes for their last message, +// whose time is each chat's last activity. +func (lc *LineClient) xessengerLastMessagesPerBox() int { + if lc.xessengerInitialSyncDays() > 0 { + return 1 + } + return 0 +} + +// xessengerLiveStreamMargin: how long before the read started a chat's last message must be for the +// read to take it as bridged earlier. The live stream starts with the read, so a message from then on +// may be in the database already while one missed before it isn't. The margin also covers LINE's +// clock being ahead of this one. +const xessengerLiveStreamMargin = 10 * time.Minute + +// xessengerChatsToRead narrows the chats whose recent messages a connect, or a full sync LINE asks +// for, reads (prefetchMessages). readStarted is when that read began. +func (lc *LineClient) xessengerChatsToRead(ctx context.Context, chatMIDs []string, boxes []line.MessageBox, readStarted time.Time) []string { + days := lc.xessengerInitialSyncDays() + if days <= 0 { + return chatMIDs + } + byID := make(map[string]line.MessageBox, len(boxes)) + for _, box := range boxes { + byID[box.ID] = box + } + now := time.Now() + read := chatMIDs[:0:0] + for _, mid := range chatMIDs { + box, ok := byID[mid] + if lc.xessengerHasRoom(ctx, mid) { + if ok && !lc.xessengerCaughtUp(ctx, box, readStarted) { + read = append(read, mid) + } + } else if ok && xessengerRecent(xessengerBoxActivity(box), days, now) { + read = append(read, mid) + } + } + lc.UserLogin.Bridge.Log.Debug().Int("chat_count", len(chatMIDs)).Int("read_count", len(read)).Msg("Reading only chats that may have changed") + return read +} + +// xessengerSkipDMResync leaves out a 1:1 chat without a room: its resync can't make one, and the +// contact lookup it does first would only cost a LINE call. +func (lc *LineClient) xessengerSkipDMResync(ctx context.Context, mid string) bool { + return lc.xessengerInitialSyncDays() > 0 && !lc.xessengerHasRoom(ctx, mid) +} + +// xessengerOldGroupsWithoutRoom is the chat sync's member groups that have no room and whose last +// activity, or creation when they have no messages, is older than initial_sync_days. Groups the account +// is only invited to keep upstream's rule. If their message boxes can't be read, none of the batch's +// groups without a room gets one now: the recent-message read still makes the recent ones from their +// messages, and the next connect looks again. +func (lc *LineClient) xessengerOldGroupsWithoutRoom(ctx context.Context, chats []line.Chat, members map[string]struct{}) map[string]bool { + days := lc.xessengerInitialSyncDays() + if days <= 0 { + return nil + } + var mids []string + created := make(map[string]time.Time) + for _, chat := range chats { + if _, member := members[chat.ChatMid]; member && !lc.xessengerHasRoom(ctx, chat.ChatMid) { + mids = append(mids, chat.ChatMid) + created[chat.ChatMid] = xessengerMillis(chat.CreatedTime) + } + } + if len(mids) == 0 { + return nil + } + old := make(map[string]bool, len(mids)) + boxes, err := xessengerMessageBoxesByIDs(lc, ctx, mids) + if err != nil { + lc.UserLogin.Bridge.Log.Warn().Err(err).Int("chat_count", len(mids)).Msg("Failed to read the last activity of groups without a room") + for _, mid := range mids { + old[mid] = true + } + return old + } + now := time.Now() + for _, mid := range mids { + activity := xessengerBoxActivity(boxes[mid]) + if activity.IsZero() { + activity = created[mid] + } + old[mid] = !xessengerRecent(activity, days, now) + } + return old +} + +func (lc *LineClient) xessengerHasRoom(ctx context.Context, mid string) bool { + portal, err := lc.UserLogin.Bridge.GetExistingPortalByKey(ctx, networkid.PortalKey{ID: makePortalID(mid), Receiver: lc.UserLogin.ID}) + return err == nil && portal != nil && portal.MXID != "" +} + +// xessengerCaughtUp: the box has no messages, or its last message was bridged before the read started. +// A last message from around the start or later may have come in through the live stream, which +// doesn't bring what was missed before it, so that chat is read; so is one whose time is unknown. +func (lc *LineClient) xessengerCaughtUp(ctx context.Context, box line.MessageBox, readStarted time.Time) bool { + last := box.LastDeliveredMessageID + if last == nil || last.MessageID == "" || last.MessageID == "-1" { + return true + } + if activity := xessengerBoxActivity(box); activity.IsZero() || !activity.Before(readStarted.Add(-xessengerLiveStreamMargin)) { + return false + } + existing, err := lc.UserLogin.Bridge.DB.Message.GetPartByID(ctx, lc.UserLogin.ID, networkid.MessageID(last.MessageID), "") + return err == nil && existing != nil +} + +// xessengerBoxActivity is a chat's last activity: the later of its last message's time and its last +// delivery's. Zero when the box tells neither. +func xessengerBoxActivity(box line.MessageBox) time.Time { + var activity time.Time + if len(box.LastMessages) > 0 { + activity = xessengerMillis(box.LastMessages[0].CreatedTime) + } + if box.LastDeliveredMessageID != nil && box.LastDeliveredMessageID.MessageID != "-1" { + if delivered := xessengerMillis(box.LastDeliveredMessageID.DeliveredTime); delivered.After(activity) { + activity = delivered + } + } + return activity +} + +// xessengerMillis reads a LINE time. LINE counts milliseconds; a value too small for that is taken as +// seconds, so a unit mistake can't push a chat back to 1970. +func xessengerMillis(value json.Number) time.Time { + n, err := value.Int64() + if err != nil || n <= 0 { + return time.Time{} + } + if n < 100_000_000_000 { + return time.Unix(n, 0) + } + return time.UnixMilli(n) +} + +func xessengerRecent(activity time.Time, days int, now time.Time) bool { + return !activity.IsZero() && !activity.Before(now.AddDate(0, 0, -days)) +} --- /dev/null +++ b/pkg/connector/xessenger_sync_scope_test.go @@ -0,0 +1,220 @@ +package connector + +import ( + "context" + "encoding/json" + "errors" + "path/filepath" + "slices" + "strconv" + "testing" + "time" + + _ "github.com/mattn/go-sqlite3" + "github.com/rs/zerolog" + "go.mau.fi/util/configupgrade" + "go.mau.fi/util/dbutil" + "gopkg.in/yaml.v3" + "maunium.net/go/mautrix/bridgev2" + "maunium.net/go/mautrix/bridgev2/bridgeconfig" + "maunium.net/go/mautrix/bridgev2/database" + "maunium.net/go/mautrix/bridgev2/networkid" + "maunium.net/go/mautrix/id" + + "github.com/beeper/line/pkg/line" +) + +func millis(t time.Time) json.Number { return json.Number(strconv.FormatInt(t.UnixMilli(), 10)) } + +type scopeTestMatrix struct{ bridgev2.MatrixConnector } + +func (scopeTestMatrix) Init(*bridgev2.Bridge) {} +func (scopeTestMatrix) BotIntent() bridgev2.MatrixAPI { return nil } + +// scopeTestClient is a LINE client on a bridge database whose rooms are the given chats, each with the +// given bridged message. +func scopeTestClient(t *testing.T, days int, rooms map[string]string, roomless ...string) *LineClient { + t.Helper() + ctx := context.Background() + raw, err := dbutil.NewWithDialect("file:"+filepath.ToSlash(filepath.Join(t.TempDir(), "bridge.db")), "sqlite3") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = raw.Close() }) + br := bridgev2.NewBridge("line", raw, zerolog.Nop(), &bridgeconfig.BridgeConfig{SplitPortals: true}, scopeTestMatrix{}, + &LineConnector{Config: Config{InitialSyncDays: days}}, func(*bridgev2.Bridge) bridgev2.CommandProcessor { return nil }) + br.BackgroundCtx = ctx + if err = br.DB.Upgrade(ctx); err != nil { + t.Fatal(err) + } + login := &bridgev2.UserLogin{UserLogin: &database.UserLogin{ID: "login"}, Bridge: br} + insert := func(mid string, room id.RoomID) networkid.PortalKey { + key := networkid.PortalKey{ID: makePortalID(mid), Receiver: login.ID} + if err := br.DB.Portal.Insert(ctx, &database.Portal{BridgeID: br.ID, PortalKey: key, MXID: room}); err != nil { + t.Fatal(err) + } + return key + } + for mid, message := range rooms { + key := insert(mid, id.RoomID("!"+mid+":test")) + if message != "" { + err := br.DB.Message.Insert(ctx, &database.Message{ID: networkid.MessageID(message), MXID: id.EventID("$" + message), Room: key, SenderID: "u2", Timestamp: time.Now(), Metadata: &MessageMetadata{}}) + if err != nil { + t.Fatal(err) + } + } + } + // A chat a dropped event left a portal row for, without a room. + for _, mid := range roomless { + insert(mid, "") + } + return &LineClient{UserLogin: login} +} + +func box(mid, lastMessage string, last time.Time) line.MessageBox { + b := line.MessageBox{ID: mid} + if lastMessage != "" { + b.LastDeliveredMessageID = &line.MessageIDWrapper{MessageID: lastMessage, DeliveredTime: millis(last)} + b.LastMessages = []line.Message{{ID: lastMessage, CreatedTime: millis(last)}} + } + return b +} + +func TestXessengerBoxActivityIsTheLastMessageOrDelivery(t *testing.T) { + at := time.Date(2026, 11, 10, 9, 30, 0, 0, time.UTC) + for _, c := range []struct { + name string + box line.MessageBox + want time.Time + }{ + {"last message", line.MessageBox{LastMessages: []line.Message{{CreatedTime: millis(at)}}}, at}, + {"later delivery", line.MessageBox{LastMessages: []line.Message{{CreatedTime: millis(at)}}, + LastDeliveredMessageID: &line.MessageIDWrapper{MessageID: "9", DeliveredTime: millis(at.Add(time.Minute))}}, at.Add(time.Minute)}, + {"delivery only, in seconds", line.MessageBox{LastDeliveredMessageID: &line.MessageIDWrapper{MessageID: "9", + DeliveredTime: json.Number(strconv.FormatInt(at.Unix(), 10))}}, at}, + {"no messages", line.MessageBox{LastDeliveredMessageID: &line.MessageIDWrapper{MessageID: "-1", DeliveredTime: millis(at)}}, time.Time{}}, + {"nothing", line.MessageBox{}, time.Time{}}, + } { + if got := xessengerBoxActivity(c.box); !got.Equal(c.want) { + t.Errorf("%s: activity %v, want %v", c.name, got, c.want) + } + } + now := at.AddDate(0, 0, 90) + if !xessengerRecent(at, 90, now) || xessengerRecent(at.Add(-time.Second), 90, now) || xessengerRecent(time.Time{}, 90, now) { + t.Fatal("recent means at most 90 days before now, and an unknown time is not recent") + } +} + +func TestXessengerConnectReadsOnlyRecentOrChangedChats(t *testing.T) { + ctx := context.Background() + now := time.Now() + rooms := map[string]string{"u-bridged": "m1", "u-changed": "m2-old", "c-room-without-box": "", "c-quiet-room": "m5", "u-live": "m7"} + boxes := []line.MessageBox{ + box("u-bridged", "m1", now.Add(-time.Hour)), + // Bridged by the live stream as the read started: a message missed before it may be missing. + box("u-live", "m7", now.Add(-time.Minute)), + box("u-changed", "m2", now.Add(-time.Minute)), + box("c-quiet-room", "m5", now.AddDate(-2, 0, 0)), + box("u-recent", "m3", now.AddDate(0, 0, -89)), + box("u-old", "m4", now.AddDate(0, 0, -91)), + box("u-unknown", "", time.Time{}), + box("c-roomless-row", "m6", now.Add(-time.Hour)), + } + all := []string{"u-bridged", "u-live", "u-changed", "c-quiet-room", "u-recent", "u-old", "u-unknown", "c-roomless-row", "c-room-without-box", "c-member-without-box"} + + lc := scopeTestClient(t, 90, rooms, "c-roomless-row") + // A room is read again unless its last message was bridged before the read; a chat without one + // only when recent. + want := []string{"u-live", "u-changed", "u-recent", "c-roomless-row"} + if got := lc.xessengerChatsToRead(ctx, all, boxes, now); !slices.Equal(got, want) { + t.Fatalf("read %v, want %v", got, want) + } + // The same message, bridged a while before the read started, needs no read. + if got := lc.xessengerChatsToRead(ctx, []string{"u-live"}, boxes, now.Add(time.Hour)); len(got) != 0 { + t.Fatalf("read %v, want nothing", got) + } + if lc.xessengerLastMessagesPerBox() != 1 { + t.Fatal("the message boxes don't bring each chat's last message") + } + // A 1:1 chat without a room is not resynced: the resync can't make one. + if lc.xessengerSkipDMResync(ctx, "u-bridged") || !lc.xessengerSkipDMResync(ctx, "u-old") || !lc.xessengerSkipDMResync(ctx, "c-roomless-row") { + t.Fatal("the DM resync skips the wrong chats") + } + + upstream := scopeTestClient(t, 0, rooms) + if got := upstream.xessengerChatsToRead(ctx, all, boxes, now); !slices.Equal(got, all) { + t.Fatalf("initial_sync_days 0 read %v, want every chat as upstream", got) + } + if upstream.xessengerLastMessagesPerBox() != 0 || upstream.xessengerSkipDMResync(ctx, "u-old") { + t.Fatal("initial_sync_days 0 changed upstream's requests") + } +} + +func TestXessengerChatSyncMakesRoomsOnlyForRecentGroups(t *testing.T) { + ctx := context.Background() + now := time.Now() + members := map[string]struct{}{"c-recent": {}, "c-old": {}, "c-new-empty": {}, "c-old-empty": {}, "c-room": {}} + chats := []line.Chat{ + {ChatMid: "c-recent", CreatedTime: millis(now.AddDate(-3, 0, 0))}, + {ChatMid: "c-old", CreatedTime: millis(now.AddDate(-3, 0, 0))}, + {ChatMid: "c-new-empty", CreatedTime: millis(now.AddDate(0, 0, -10))}, + {ChatMid: "c-old-empty", CreatedTime: millis(now.AddDate(-2, 0, 0))}, + {ChatMid: "c-room", CreatedTime: millis(now.AddDate(-3, 0, 0))}, + {ChatMid: "c-invited", CreatedTime: millis(now.AddDate(-3, 0, 0))}, + } + var asked [][]string + var failure error + previous := xessengerMessageBoxesByIDs + t.Cleanup(func() { xessengerMessageBoxesByIDs = previous }) + xessengerMessageBoxesByIDs = func(_ *LineClient, _ context.Context, mids []string) (map[string]line.MessageBox, error) { + asked = append(asked, mids) + return map[string]line.MessageBox{ + "c-recent": box("c-recent", "m1", now.Add(-time.Hour)), + "c-old": box("c-old", "m2", now.AddDate(0, 0, -200)), + "c-room": box("c-room", "m3", now.AddDate(0, 0, -200)), + }, failure + } + + lc := scopeTestClient(t, 90, map[string]string{"c-room": "m3"}) + old := lc.xessengerOldGroupsWithoutRoom(ctx, chats, members) + want := map[string]bool{"c-recent": false, "c-old": true, "c-new-empty": false, "c-old-empty": true} + if len(old) != len(want) { + t.Fatalf("judged %v, want %v", old, want) + } + for mid, skip := range want { + if old[mid] != skip { + t.Errorf("%s: skipped %v, want %v", mid, old[mid], skip) + } + } + // One LINE call per batch, only for member groups without a room. + if len(asked) != 1 || !slices.Equal(asked[0], []string{"c-recent", "c-old", "c-new-empty", "c-old-empty"}) { + t.Fatalf("asked LINE for %v", asked) + } + + failure = errors.New("unavailable") + if old = lc.xessengerOldGroupsWithoutRoom(ctx, chats, members); !old["c-recent"] || !old["c-new-empty"] || old["c-room"] || old["c-invited"] { + t.Fatalf("without message boxes, every member group without a room waits: %v", old) + } + + asked = nil + if old = scopeTestClient(t, 0, nil).xessengerOldGroupsWithoutRoom(ctx, chats, members); old != nil || asked != nil { + t.Fatal("initial_sync_days 0 skipped groups or asked LINE") + } +} + +func TestXessengerConfigKeepsInitialSyncDays(t *testing.T) { + connector := &LineConnector{} + _, _, upgrader := connector.GetConfig() + // The bridge upgrades its config on every start, dropping any key the example config lacks. + upgraded, err := configupgrade.DoBytes([]byte("qr_login: true\ninitial_sync_days: 90\n"), upgrader.(configupgrade.BaseUpgrader)) + if err != nil { + t.Fatal(err) + } + var config Config + if err = yaml.Unmarshal(upgraded, &config); err != nil { + t.Fatal(err) + } + if config != (Config{QRLogin: true, InitialSyncDays: 90}) { + t.Fatalf("config after the upgrade: %+v", config) + } +}