~geb/sup

a7d36bffd53c3897ff73d2f1cd87748c0e93db85 — John Gebbie 1 year, 10 months ago c2aa982
cache read receipts
2 files changed, 46 insertions(+), 3 deletions(-)

M main.go
M storage.go
M main.go => main.go +12 -3
@@ 761,7 761,12 @@ func run() int {
		if directChats, err := loadDirectChats(client.UserID); err == nil {
			app.DirectChats = directChats
		} else {
			fmt.Fprintln(os.Stderr, "failed to direct chats: " + err.Error())
			fmt.Fprintln(os.Stderr, "failed to load direct chats: " + err.Error())
		}
		if readReceipts, err := loadReadReceipts(client.UserID); err == nil {
			app.ReadReceipts = readReceipts
		} else {
			fmt.Fprintln(os.Stderr, "failed to load read receipts: " + err.Error())
		}
	} else {
		fmt.Fprintln(os.Stderr, "failed to load cache: " + err.Error())


@@ 772,11 777,15 @@ func run() int {
	}
	err := saveStorer(client.Store.(*mautrix.InMemoryStore), client.UserID)
	if err != nil {
		fatal(err.Error())
		fatal("failed to cache: " + err.Error())
	}
	err = saveDirectChats(app.DirectChats, client.UserID)
	if err != nil {
		fatal(err.Error())
		fmt.Fprintln(os.Stderr, "failed to cache direct chats: " + err.Error())
	}
	err = saveReadReceipts(app.ReadReceipts, client.UserID)
	if err != nil {
		fmt.Fprintln(os.Stderr, "failed to cache read receipts: " + err.Error())
	}
	return 0
}

M storage.go => storage.go +34 -0
@@ 106,3 106,37 @@ func saveDirectChats(directChats map[id.RoomID]id.UserID, user id.UserID) error 
	}
	return os.WriteFile(filepath.Join(dir, "direct_chats.json"), data, 0600)
}

func loadReadReceipts(user id.UserID) (map[id.RoomID]id.EventID, error) {
	dir, err := os.UserCacheDir()
	if err != nil {
		return nil, err
	}
	dir = filepath.Join(dir, "sup", string(user))

	if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
		return nil, nil
	}

	data, err := os.ReadFile(filepath.Join(dir, "read_receipts.json"))
	if err != nil {
		return nil, err
	}
	var readReceipts map[id.RoomID]id.EventID
	json.Unmarshal(data, &readReceipts)
	return readReceipts, nil
}

func saveReadReceipts(readReceipts map[id.RoomID]id.EventID, user id.UserID) error {
	dir, err := os.UserCacheDir()
	if err != nil {
		return err
	}
	dir = filepath.Join(dir, "sup", string(user))

	data, err := json.Marshal(readReceipts)
	if err != nil {
		return err
	}
	return os.WriteFile(filepath.Join(dir, "read_receipts.json"), data, 0600)
}