-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsync.go
222 lines (190 loc) · 5.78 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
// 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 "evgenykuznetsov.org/go/gphotoslibrary"
"evgenykuznetsov.org/go/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) 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)
fmt.Printf("downloading \"%s\" to \"%s\"\n", mediaURL, 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\" exists\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
}
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) GetTokenPath() string {
return path.Join(lib.Path, ".token.json")
}
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
}
}