-
Notifications
You must be signed in to change notification settings - Fork 0
/
dropbox.go
91 lines (76 loc) · 2.13 KB
/
dropbox.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package dropbox
import (
"context"
"fmt"
"os"
"path/filepath"
"log/slog"
"github.com/abekoh/radiko-archiver/internal/config"
sdk "github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox"
"github.com/dropbox/dropbox-sdk-go-unofficial/v6/dropbox/files"
"github.com/fsnotify/fsnotify"
)
func RunSyncer(ctx context.Context, cnf *config.Config) {
logger := slog.Default().With("job", "dropbox-uploader")
go func() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(fmt.Errorf("failed to create watcher: %w", err))
}
defer watcher.Close()
if err := watcher.Add(cnf.OutDirPath); err != nil {
panic(fmt.Errorf("failed to add watcher: %w", err))
}
logger.Info("start watching")
for {
select {
case event := <-watcher.Events:
if event.Has(fsnotify.Create & fsnotify.Write & fsnotify.Remove) {
sync(ctx, cnf, event.Name, event)
}
case <-ctx.Done():
return
}
}
}()
}
func sync(ctx context.Context, cnf *config.Config, path string, event fsnotify.Event) {
logger := slog.Default().With("job", "dropbox-sync")
logger.Debug("start sync", "op", event.Op, "path", path)
client := files.New(sdk.Config{
Token: cnf.Dropbox.Token,
})
if event.Has(fsnotify.Create) || event.Has(fsnotify.Write) {
logger.Info("uploading", "path", path)
f, err := os.Open(path)
if err != nil {
logger.Error("failed to open file", "error", err)
return
}
defer f.Close()
commitInfo := files.NewCommitInfo("/" + filepath.Base(path))
commitInfo.Mode.Tag = "overwrite"
_, err = client.Upload(&files.UploadArg{
CommitInfo: *commitInfo,
ContentHash: "", // TODO: calculate hash
}, f)
if err != nil {
logger.Error("failed to upload into dropbox", "error", err)
return
}
logger.Info("uploaded", "path", path)
} else if event.Has(fsnotify.Remove) {
logger.Info("deleting", "path", path)
_, err := client.DeleteV2(&files.DeleteArg{
Path: "/" + filepath.Base(path),
})
if err != nil {
logger.Error("failed to delete from dropbox", "error", err)
return
}
logger.Info("deleted", "path", path)
} else {
logger.Error("unknown operation", "op", event.Op)
return
}
}