2023-09-22 04:44:22 +00:00
|
|
|
package pkg
|
|
|
|
|
|
|
|
import (
|
|
|
|
"cli-go/pkg/model"
|
2023-09-22 08:20:50 +00:00
|
|
|
"context"
|
|
|
|
"encoding/base64"
|
2023-09-22 04:44:22 +00:00
|
|
|
"fmt"
|
|
|
|
bolt "go.etcd.io/bbolt"
|
|
|
|
"log"
|
|
|
|
)
|
|
|
|
|
2023-09-22 08:20:50 +00:00
|
|
|
func (c *ClICtrl) SyncAccount(account model.Account) error {
|
2023-09-22 16:15:01 +00:00
|
|
|
secretInfo, err := c.KeyHolder.LoadSecrets(account, c.CliKey)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-09-23 04:04:21 +00:00
|
|
|
ctx := c.buildRequestContext(context.Background(), account)
|
2023-09-22 16:15:01 +00:00
|
|
|
err = createDataBuckets(c.DB, account)
|
2023-09-22 08:20:50 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-09-22 16:15:01 +00:00
|
|
|
c.Client.AddToken(account.AccountKey(), base64.URLEncoding.EncodeToString(secretInfo.Token))
|
2023-09-25 06:44:41 +00:00
|
|
|
err = c.fetchRemoteCollections(ctx)
|
2023-09-25 04:28:15 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error fetching collections: %s", err)
|
|
|
|
}
|
2023-09-25 06:44:41 +00:00
|
|
|
err = c.fetchRemoteFiles(ctx)
|
2023-09-25 06:23:12 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("Error fetching files: %s", err)
|
|
|
|
}
|
2023-09-25 04:28:15 +00:00
|
|
|
return nil
|
2023-09-22 08:20:50 +00:00
|
|
|
}
|
|
|
|
|
2023-09-22 13:47:24 +00:00
|
|
|
func (c *ClICtrl) buildRequestContext(ctx context.Context, account model.Account) context.Context {
|
2023-09-22 08:20:50 +00:00
|
|
|
ctx = context.WithValue(ctx, "app", string(account.App))
|
|
|
|
ctx = context.WithValue(ctx, "account_id", account.AccountKey())
|
2023-09-23 04:04:21 +00:00
|
|
|
ctx = context.WithValue(ctx, "user_id", account.UserID)
|
2023-09-22 08:20:50 +00:00
|
|
|
return ctx
|
2023-09-22 04:44:22 +00:00
|
|
|
}
|
|
|
|
|
2023-09-22 08:20:50 +00:00
|
|
|
func createDataBuckets(db *bolt.DB, account model.Account) error {
|
2023-09-22 04:44:22 +00:00
|
|
|
return db.Update(func(tx *bolt.Tx) error {
|
2023-09-24 20:20:52 +00:00
|
|
|
dataBucket, err := tx.CreateBucketIfNotExists([]byte(account.AccountKey()))
|
2023-09-22 04:44:22 +00:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("create bucket: %s", err)
|
|
|
|
}
|
2023-09-24 20:20:52 +00:00
|
|
|
for _, subBucket := range []model.PhotosStore{model.KVConfig, model.RemoteAlbums, model.RemoteFiles} {
|
|
|
|
_, err := dataBucket.CreateBucketIfNotExists([]byte(subBucket))
|
2023-09-22 04:44:22 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
}
|