@@ 682,7 682,19 @@ func Login() *mautrix.Client {
func run() int {
client := Login()
defer client.Logout()
- return NewApp(client).Run()
+ if storer, err := loadStorer(client.UserID); err == nil {
+ client.Store = storer
+ } else {
+ fmt.Fprintln(os.Stderr, "failed to load cache: " + err.Error())
+ }
+ if code := NewApp(client).Run(); code != 0 {
+ return code
+ }
+ err := saveStorer(client.Store.(*mautrix.InMemoryStore), client.UserID)
+ if err != nil {
+ fatal(err.Error())
+ }
+ return 0
}
func main() {
@@ 0,0 1,73 @@
+package main
+
+import (
+ "bytes"
+ "encoding/gob"
+ "errors"
+ "maunium.net/go/mautrix"
+ "maunium.net/go/mautrix/id"
+ "os"
+ "path/filepath"
+)
+
+func init() {
+ gob.Register(map[string]interface{}{})
+ gob.Register([]interface{}{})
+}
+
+func loadStorer(user id.UserID) (*mautrix.InMemoryStore, error) {
+ dir, err := os.UserCacheDir()
+ if err != nil {
+ return mautrix.NewInMemoryStore(), err
+ }
+ dir = filepath.Join(dir, "sup", string(user))
+
+ if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) {
+ return mautrix.NewInMemoryStore(), nil
+ }
+
+ nb, err := os.ReadFile(filepath.Join(dir, "next_batch"))
+ if err != nil {
+ return mautrix.NewInMemoryStore(), err
+ }
+ rooms, err := os.ReadFile(filepath.Join(dir, "rooms.gob"))
+ if err != nil {
+ return mautrix.NewInMemoryStore(), err
+ }
+
+ storer := mautrix.NewInMemoryStore()
+ storer.SaveNextBatch(user, string(nb))
+ err = gob.NewDecoder(bytes.NewReader(rooms)).Decode(&storer.Rooms)
+ if err != nil {
+ return mautrix.NewInMemoryStore(), err
+ }
+ return storer, err
+}
+
+func saveStorer(storer *mautrix.InMemoryStore, user id.UserID) error {
+ dir, err := os.UserCacheDir()
+ if err != nil {
+ return err
+ }
+ dir = filepath.Join(dir, "sup", string(user))
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ return err
+ }
+
+ nb := storer.NextBatch[user]
+ err = os.WriteFile(filepath.Join(dir, "next_batch"), []byte(nb), 0600)
+ if err != nil {
+ return err
+ }
+
+ var rooms bytes.Buffer
+ err = gob.NewEncoder(&rooms).Encode(storer.Rooms)
+ if err != nil {
+ return err
+ }
+ err = os.WriteFile(filepath.Join(dir, "rooms.gob"), rooms.Bytes(), 0600)
+ if err != nil {
+ return err
+ }
+ return nil
+}