-
Notifications
You must be signed in to change notification settings - Fork 0
/
drive.go
184 lines (152 loc) · 4.11 KB
/
drive.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package google
import (
"context"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
"github.com/masudur-rahman/expense-tracker-bot/infra/logr"
"golang.org/x/oauth2/google"
"google.golang.org/api/drive/v3"
"google.golang.org/api/option"
)
const (
dbFileName = "expense-tracker.db"
dbFolderName = ".expense-tracker"
)
func DatabasePath() string {
if err := os.MkdirAll(dbFolderName, os.ModePerm); err != nil {
log.Fatalln(err)
}
return filepath.Join(dbFolderName, dbFileName)
}
func getDriveService() (*drive.Service, error) {
creds, err := google.FindDefaultCredentials(context.Background(), drive.DriveScope)
if err != nil {
return nil, err
}
return drive.NewService(context.Background(), option.WithCredentials(creds))
}
func readFileFromDrive(svc *drive.Service, upstreamFilePath string) ([]byte, error) {
ff := strings.Split(upstreamFilePath, "/")
folderID, err := getFolderID(svc, ff[0])
if err != nil {
return nil, err
}
fileQuery := fmt.Sprintf("name='%s' and '%s' in parents", ff[1], folderID)
fileList, err := svc.Files.List().Q(fileQuery).Do()
if err != nil {
return nil, err
}
if len(fileList.Files) == 0 {
return nil, fmt.Errorf("file '%s' not found in folder '%s'", ff[1], ff[0])
}
fileID := fileList.Files[0].Id
resp, err := svc.Files.Get(fileID).Download()
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
func uploadFileToDrive(svc *drive.Service, upstreamFilePath string, localFilePath string) error {
ff := strings.Split(upstreamFilePath, "/")
folderID, err := getFolderID(svc, ff[0])
if err != nil {
return err
}
fileMetadata := &drive.File{
Name: filepath.Base(ff[1]),
Parents: []string{folderID},
MimeType: "application/octet-stream",
}
file, err := os.Open(localFilePath)
if err != nil {
return err
}
defer file.Close()
gf, err := svc.Files.Create(fileMetadata).Media(file).Do()
if err != nil {
return err
}
//_, err = svc.Files.Update(existingFiles.Files[0].Id, fileMetadata).Media(file).Do()
//return err
return removePreviousFiles(svc, ff[1], gf.Id, folderID)
}
func removePreviousFiles(svc *drive.Service, fileName, newFileID string, folderID string) error {
fileQuery := fmt.Sprintf("'%s' in parents and name='%s'", folderID, fileName)
fileList, err := svc.Files.List().Q(fileQuery).Do()
if err != nil {
return err
}
for _, file := range fileList.Files {
if file.Id != newFileID {
if err = svc.Files.Delete(file.Id).Do(); err != nil {
return err
}
}
}
return nil
}
func getFolderID(svc *drive.Service, folderName string) (string, error) {
folderQuery := fmt.Sprintf("name='%s' and mimeType='application/vnd.google-apps.folder'", folderName)
folderList, err := svc.Files.List().Q(folderQuery).Do()
if err != nil {
return "", err
}
if len(folderList.Files) == 0 {
parentFolder := &drive.File{
Name: folderName,
MimeType: "application/vnd.google-apps.folder",
}
parentFolder, err = svc.Files.Create(parentFolder).Do()
if err != nil {
return "", err
}
return parentFolder.Id, nil
}
return folderList.Files[0].Id, nil
}
func SyncDatabaseFromDrive() error {
svc, err := getDriveService()
if err != nil {
return err
}
data, err := readFileFromDrive(svc, DatabasePath())
if err != nil {
return err
}
return os.WriteFile(DatabasePath(), data, 0666)
}
func SyncDatabaseToDrive() error {
svc, err := getDriveService()
if err != nil {
return err
}
dbPath := DatabasePath()
return uploadFileToDrive(svc, dbPath, dbPath)
}
func SyncDatabaseToDrivePeriodically(interval time.Duration) {
if interval == time.Duration(0) {
interval = time.Hour
}
if err := SyncDatabaseToDrive(); err != nil {
logr.DefaultLogger.Errorw("Sync database to drive failed", "error", err.Error())
return
}
logr.DefaultLogger.Infof("SQLite database synced to google drive")
ticker := time.NewTicker(interval)
for {
select {
case <-ticker.C:
if err := SyncDatabaseToDrive(); err != nil {
logr.DefaultLogger.Errorw("Sync database to drive failed", "error", err.Error())
return
}
logr.DefaultLogger.Infof("SQLite database synced to google drive")
}
}
}