-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync.go
343 lines (299 loc) · 10.1 KB
/
sync.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// Copyright (C) 2018 denis4net
// Copyright (C) 2019 Evgeny Kuznetsov ([email protected])
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
photoslibrary "github.com/carstentrink/gphotoslibrary"
"github.com/carstentrink/gphotosync/internal/oauth"
"google.golang.org/api/googleapi"
)
type Library struct {
Path string
Deduplicator func(*photoslibrary.MediaItem) string
}
func DownloadFile(url string, path string) error {
// Create the file
out, err := os.Create(path)
if err != nil {
return err
}
defer out.Close()
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
func getDownloadUrl(mediaItem *photoslibrary.MediaItem) string {
if mediaItem.MediaMetadata.Photo == nil {
return fmt.Sprintf("%s=dv", mediaItem.BaseUrl)
}
return fmt.Sprintf("%s=d", mediaItem.BaseUrl)
}
func (lib *Library) GetTokenPath() string {
return path.Join(lib.Path, "USERNAME.token.json")
}
func (lib *Library) SyncMediaItem(mItem *photoslibrary.MediaItem) error {
remoteCreationTime, err := time.Parse(time.RFC3339, mItem.MediaMetadata.CreationTime)
if err != nil {
return err
}
mediaPath, err := getMediaPath(lib, mItem)
if err != nil {
return err
}
if err := os.MkdirAll(path.Dir(mediaPath), 0755); err != nil {
return err
}
// multiple items with same filename can exist in remote
// we try to mitigate it by adding timestamp to local filename
if stat, err := os.Stat(mediaPath); !os.IsNotExist(err) && stat.ModTime().UnixNano() != remoteCreationTime.UnixNano() {
// mediaPath, err = deduplicatePath(lib, mItem)
if err != nil {
return err
}
}
if _, err := os.Stat(mediaPath); os.IsNotExist(err) {
mediaURL := getDownloadUrl(mItem)
searchText1 := "ABCDE"
searchText2 := "ABCDE"
searchText3 := "ABCDE"
searchText4 := "ABCDE"
searchText5 := "ABCDE"
searchText6 := "ABCDE"
searchText7 := "ABCDE"
searchText8 := "ABCDE"
searchText9 := "ABCDE"
// current_time := time.Now().Local()
// fmt.Println("The Current time is ", time.Now().Local().Unix().Format("2006-01-02"))
// fmt.Println("File time is ", remoteCreationTime.Format("2006-01-02"))
// timestamp_now := time.Now().Local().Unix()
// filetimestamp := remoteCreationTime.Unix()
// fmt.Printf("unix NOW \"%d\" but file is \"%d\" \n", timestamp_now,filetimestamp)
// diff := timestamp_now - filetimestamp
// if diff > 10 {
// if diff > 99999999259200 {
// fmt.Printf("checking if newer than 48 hours \"%d\" \n", diff)
// fmt.Println("Unix %s---- ", timestamp)
// t2 := t.Add(time.Minute * 3600)
// fmt.Printf("CURRENT %s \n", start)
if strings.Contains(mediaPath, searchText1) {
fmt.Printf("Downloading \"%s\" \n", mediaPath)
err := DownloadFile(mediaURL, mediaPath)
if err != nil {
return err
}
err = os.Chtimes(mediaPath, remoteCreationTime, remoteCreationTime)
if err != nil {
return err
}
} else if strings.Contains(mediaPath, searchText2) {
fmt.Printf("Downloading \"%s\" \n", mediaPath)
err := DownloadFile(mediaURL, mediaPath)
if err != nil {
return err
}
err = os.Chtimes(mediaPath, remoteCreationTime, remoteCreationTime)
if err != nil {
return err
}
} else if strings.Contains(mediaPath, searchText3) {
fmt.Printf("Downloading \"%s\" \n", mediaPath)
err := DownloadFile(mediaURL, mediaPath)
if err != nil {
return err
}
err = os.Chtimes(mediaPath, remoteCreationTime, remoteCreationTime)
if err != nil {
return err
}
} else if strings.Contains(mediaPath, searchText4) {
fmt.Printf("Downloading \"%s\" \n", mediaPath)
err := DownloadFile(mediaURL, mediaPath)
if err != nil {
return err
}
err = os.Chtimes(mediaPath, remoteCreationTime, remoteCreationTime)
if err != nil {
return err
}
} else if strings.Contains(mediaPath, searchText5) {
fmt.Printf("Downloading \"%s\" \n", mediaPath)
err := DownloadFile(mediaURL, mediaPath)
if err != nil {
return err
}
err = os.Chtimes(mediaPath, remoteCreationTime, remoteCreationTime)
if err != nil {
return err
}
} else if strings.Contains(mediaPath, searchText6) {
fmt.Printf("Downloading \"%s\" \n", mediaPath)
err := DownloadFile(mediaURL, mediaPath)
if err != nil {
return err
}
err = os.Chtimes(mediaPath, remoteCreationTime, remoteCreationTime)
if err != nil {
return err
}
} else if strings.Contains(mediaPath, searchText7) {
fmt.Printf("Downloading \"%s\" \n", mediaPath)
err := DownloadFile(mediaURL, mediaPath)
if err != nil {
return err
}
err = os.Chtimes(mediaPath, remoteCreationTime, remoteCreationTime)
if err != nil {
return err
}
} else if strings.Contains(mediaPath, searchText8) {
fmt.Printf("Downloading \"%s\" \n", mediaPath)
err := DownloadFile(mediaURL, mediaPath)
if err != nil {
return err
}
err = os.Chtimes(mediaPath, remoteCreationTime, remoteCreationTime)
if err != nil {
return err
}
} else if strings.Contains(mediaPath, searchText9) {
fmt.Printf("Downloading \"%s\" \n", mediaPath)
err := DownloadFile(mediaURL, mediaPath)
if err != nil {
return err
}
err = os.Chtimes(mediaPath, remoteCreationTime, remoteCreationTime)
if err != nil {
return err
}
} else {
//fmt.Printf("%s is ignored %s\n", mItem.Filename, mItem.MediaMetadata.CreationTime)
//fmt.Printf("LIST %s\n", mItem.Filename)
}
// }
} else {
fmt.Printf("\"%s\"\n", mediaPath)
}
return nil
}
func getMediaPath(lib *Library, mItem *photoslibrary.MediaItem) (string, error) {
//remoteCreationTime, err := time.Parse(time.RFC3339, mItem.MediaMetadata.CreationTime)
//if err != nil {
// return "", err
//}
//return path.Join(lib.Path, strconv.Itoa(remoteCreationTime.Year()), fmt.Sprintf("%02d", remoteCreationTime.Month()), mItem.Filename), nil
return (mItem.Filename), nil
}
//func deduplicatePath(lib *Library, item *photoslibrary.MediaItem) (string, error) {
// p, err := getMediaPath(lib, item)
// if err != nil {
// return "", err
// }
// e := path.Ext(p)
// return strings.TrimSuffix(p, e) + "-gphotosync-" + lib.Deduplicator(item) + e, nil
//}
func dedupUnixHex(item *photoslibrary.MediaItem) string {
remoteCreationTime, err := time.Parse(time.RFC3339, item.MediaMetadata.CreationTime)
if err != nil {
return ""
}
return strconv.FormatInt(remoteCreationTime.UnixNano(), 16)
}
func dedupID(item *photoslibrary.MediaItem) string {
return item.Id
}
func (lib *Library) Sync(cred credentials) error {
ctx := context.Background()
oauthClient, err := oauth.NewClient(ctx, cred.ID, cred.Secret, cred.RedirectURL, lib.GetTokenPath())
if err != nil {
return err
}
photoslibraryService, err := photoslibrary.New(oauthClient)
if err != nil {
return err
}
mediaItemsService := photoslibrary.NewMediaItemsService(photoslibraryService)
pageToken := ""
waitTime := 1 * time.Minute
for {
res, err := mediaItemsService.Search(&photoslibrary.SearchMediaItemsRequest{PageToken: pageToken, PageSize: 100}).Do()
if err != nil {
if apiError, ok := err.(*googleapi.Error); ok {
/// If the quota of requests to the Library API is exceeded, the API returns an error code 429 and a message that the project has exceeded the quota.
switch apiError.Code {
case 429:
fmt.Printf("failed to get media items: %s\nwill wait and try again\n", apiError.Message)
time.Sleep(waitTime)
waitTime = waitTime * 2
continue
case 500:
fmt.Println("got error 500 from server, let's wait and see")
time.Sleep(time.Minute)
continue
case 502:
fmt.Println("got error 502 from Google API, will retry in 30 seconds")
time.Sleep(30 * time.Second)
continue
case 503:
fmt.Println("got error 503 from server, will wait for a minute and try again")
time.Sleep(time.Minute)
continue
default:
return err
}
}
}
// sometimes the library returns both err and res empty (yep, a bug in there)
if res == nil {
fmt.Println("looks like Google returned empty page...")
return nil
} else {
fmt.Printf("processing %d items\n", len(res.MediaItems))
for _, mItem := range res.MediaItems {
err = lib.SyncMediaItem(mItem)
if err != nil {
log.Printf("failed to sync item \"%s\": %s", mItem.Id, err)
}
}
}
// if NextPageToken is empty, we reached the last page of items list
if res.NextPageToken == "" {
//fmt.Println("syncing is done")
return nil
} else {
fmt.Println("requesting next page")
}
pageToken = res.NextPageToken
waitTime = 1 * time.Minute
}
}