-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathsmugmug.go
372 lines (318 loc) · 9.96 KB
/
smugmug.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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package smugmug
import (
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"text/template"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
// Conf is the configuration of the smugmug worker
type Conf struct {
ApiKey string // API key
ApiSecret string // API secret
UserToken string // User token
UserSecret string // User secret
Destination string // Backup destination folder
Filenames string // Template for files naming
UseMetadataTimes bool // When true, the last update timestamp will be retrieved from metadata
ForceMetadataTimes bool // When true, then the last update timestamp is always retrieved and overwritten, also for existing files
WriteCSV bool // When true, a CSV file including downloaded files metadata is written
ForceVideoDownload bool // When true, download videos also if marked as under processing
ConcurrentDownloads int // number of concurrent downloads of images and videos, default is 1
ConcurrentAlbums int // number of concurrent albums analyzed via API calls
HTTPBaseUrl string // Smugmug API URL, defaults to https://api.smugmug.com
HTTPMaxRetries int // Max number of retries for HTTP calls, defaults to 3
username string
metadataFile string
}
// overrideEnvConf overrides any configuration value if the
// corresponding environment variables is set
func (cfg *Conf) overrideEnvConf() {
if os.Getenv("SMGMG_BK_API_KEY") != "" {
cfg.ApiKey = os.Getenv("SMGMG_BK_API_KEY")
}
if os.Getenv("SMGMG_BK_API_SECRET") != "" {
cfg.ApiSecret = os.Getenv("SMGMG_BK_API_SECRET")
}
if os.Getenv("SMGMG_BK_USER_TOKEN") != "" {
cfg.UserToken = os.Getenv("SMGMG_BK_USER_TOKEN")
}
if os.Getenv("SMGMG_BK_USER_SECRET") != "" {
cfg.UserSecret = os.Getenv("SMGMG_BK_USER_SECRET")
}
if os.Getenv("SMGMG_BK_DESTINATION") != "" {
cfg.Destination = os.Getenv("SMGMG_BK_DESTINATION")
}
if os.Getenv("SMGMG_BK_FILE_NAMES") != "" {
cfg.Filenames = os.Getenv("SMGMG_BK_FILE_NAMES")
}
}
func (cfg *Conf) validate() error {
if cfg.ApiKey == "" {
return errors.New("ApiKey can't be empty")
}
if cfg.ApiSecret == "" {
return errors.New("ApiSecret can't be empty")
}
if cfg.UserToken == "" {
return errors.New("UserToken can't be empty")
}
if cfg.UserSecret == "" {
return errors.New("UserSecret can't be empty")
}
if cfg.Destination == "" {
return errors.New("destination can't be empty")
}
// Check exising and writeability of destination folder
if err := checkDestFolder(cfg.Destination); err != nil {
return fmt.Errorf("can't find in the destination folder %s: %v", cfg.Destination, err)
}
return nil
}
// ReadConf produces a configuration object for the Smugmug worker.
//
// It reads the configuration from ./config.toml or "$HOME/.smgmg/config.toml"
func ReadConf(cfgPath string) (*Conf, error) {
viper.SetConfigName("config")
viper.SetConfigType("toml")
if cfgPath != "" {
viper.AddConfigPath(cfgPath)
}
viper.AddConfigPath("$HOME/.smgmg")
viper.AddConfigPath(".")
// defaults
viper.SetDefault("http.base_url", "https://api.smugmug.com")
viper.SetDefault("http.max_retries", 3)
viper.SetDefault("store.file_names", "{{.FileName}}")
viper.SetDefault("store.concurrent_downloads", 1)
viper.SetDefault("store.concurrent_albums", 1)
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
return nil, errors.New("configuration file not found in ./config.toml or $HOME/.smgmg/config.toml")
} else {
return nil, err
}
}
if viper.GetString("authentication.username") != "" {
log.Warnf("[DEPRECATION] Username configuration value is ignored. It is now retrieved automatically from SmugMug based on the authentication credentials.")
}
cfg := &Conf{
ApiKey: viper.GetString("authentication.api_key"),
ApiSecret: viper.GetString("authentication.api_secret"),
UserToken: viper.GetString("authentication.user_token"),
UserSecret: viper.GetString("authentication.user_secret"),
Destination: viper.GetString("store.destination"),
Filenames: viper.GetString("store.file_names"),
UseMetadataTimes: viper.GetBool("store.use_metadata_times"),
ForceMetadataTimes: viper.GetBool("store.force_metadata_times"),
WriteCSV: viper.GetBool("store.write_csv"),
ForceVideoDownload: viper.GetBool("store.force_video_download"),
ConcurrentDownloads: viper.GetInt("store.concurrent_downloads"),
ConcurrentAlbums: viper.GetInt("store.concurrent_albums"),
HTTPBaseUrl: viper.GetString("http.base_url"),
HTTPMaxRetries: viper.GetInt("http.max_retries"),
}
cfg.overrideEnvConf()
if !cfg.UseMetadataTimes && cfg.ForceMetadataTimes {
return nil, errors.New("cannot use store.force_metadata_times without store.use_metadata_times")
}
return cfg, nil
}
type FileMetadata struct {
FileName string
ArchivedUri string
Caption string
Keywords string
}
type downloadInfo struct {
image albumImage
folder string
}
// Worker actually implements the backup logic
type Worker struct {
req requestsHandler
cfg *Conf
errors int
downloadFn func(string, string, int64) (bool, error) // defined in struct for better testing
filenameTmpl *template.Template
downloadsCh chan *downloadInfo
downloadsWorkers int
downloadWg sync.WaitGroup
stopCh chan struct{}
quitting bool
albumCh chan album
albumsWorkers int
albumWg sync.WaitGroup
csvLock sync.Mutex
}
// New return a SmugMug backup configuration. It returns an error if it fails parsing
// the command line arguments
func New(cfg *Conf) (*Worker, error) {
if err := cfg.validate(); err != nil {
return nil, err
}
handler := newHTTPHandler(cfg.HTTPBaseUrl, cfg.HTTPMaxRetries, cfg.ApiKey, cfg.ApiSecret, cfg.UserToken, cfg.UserSecret)
tmpl, err := buildFilenameTemplate(cfg.Filenames)
if err != nil {
return nil, err
}
if cfg.WriteCSV {
cfg.metadataFile = filepath.Join(cfg.Destination, METADATA_FNAME)
createMetadataCSV(cfg.metadataFile)
}
return &Worker{
cfg: cfg,
req: handler,
downloadFn: handler.download,
filenameTmpl: tmpl,
downloadsCh: make(chan *downloadInfo),
downloadsWorkers: cfg.ConcurrentDownloads,
downloadWg: sync.WaitGroup{},
stopCh: make(chan struct{}),
albumCh: make(chan album),
albumsWorkers: cfg.ConcurrentAlbums,
albumWg: sync.WaitGroup{},
}, nil
}
func (w *Worker) albumWorker(id int) {
log.Debugf("Running albumWorker %d", id)
for {
select {
case <-w.stopCh:
log.Debugf("Stopping albumWorker %d", id)
return
case album, ok := <-w.albumCh:
if !ok {
// Channel is closed
log.Debugf("Quitting albumWorker %d", id)
return
}
folder := filepath.Join(w.cfg.Destination, album.URLPath)
if err := createFolder(folder); err != nil {
log.WithError(err).Errorf("cannot create the destination folder %s", folder)
w.errors++
continue
}
log.Debugf("[ALBUM IMAGES] %s", album.Uris.AlbumImages.URI)
images, err := w.albumImages(album.Uris.AlbumImages.URI, album.URLPath)
if err != nil {
log.WithError(err).Errorf("cannot get album images for %s", album.Uris.AlbumImages.URI)
w.errors++
continue
}
log.Debugf("Got album images for %s", album.Uris.AlbumImages.URI)
// log.Debugf("%+v", images)
w.saveImages(images, folder)
if w.cfg.WriteCSV {
w.writeToCSV(images, folder)
}
}
}
}
func (w *Worker) downloader(id int) {
log.Debugf("Running downloader %d", id)
for {
select {
case <-w.stopCh:
log.Debugf("Stopping downloader %d", id)
return
case info, ok := <-w.downloadsCh:
if !ok {
log.Debugf("Quitting downloader %d", id)
return
}
if info.image.IsVideo {
if err := w.saveVideo(info.image, info.folder); err != nil {
log.Warnf("Error: %v", err)
}
continue
}
if err := w.saveImage(info.image, info.folder); err != nil {
log.Warnf("Error: %v", err)
}
}
}
}
func buildFilenameTemplate(filenameTemplate string) (*template.Template, error) {
// Use FileName as default
if filenameTemplate == "" {
filenameTemplate = "{{.FileName}}"
}
tmpl, err := template.New("image_filename").Option("missingkey=error").Parse(filenameTemplate)
if err != nil {
return nil, err
}
return tmpl, nil
}
// Run performs the backup of the provided SmugMug account.
//
// The workflow is the following:
//
// - Get user albums
// - Iterate over all albums and:
// - create folder
// - iterate over all images and videos
// - if existing and with the same size, then skip
// - if not, download
func (w *Worker) Run() error {
var err error
w.cfg.username, err = w.currentUser()
if err != nil {
return fmt.Errorf("error checking credentials: %v", err)
}
w.albumWg.Add(w.albumsWorkers)
for i := 0; i < w.albumsWorkers; i++ {
go func(i int) {
defer w.albumWg.Done()
w.albumWorker(i)
}(i)
}
w.downloadWg.Add(w.downloadsWorkers)
for i := 0; i < w.downloadsWorkers; i++ {
go func(i int) {
defer w.downloadWg.Done()
w.downloader(i)
}(i)
}
// Get user albums
log.Infof("Getting albums for user %s...\n", w.cfg.username)
albums, err := w.userAlbums()
if err != nil {
return fmt.Errorf("error getting user albums: %v", err)
}
log.Infof("Found %d albums\n", len(albums))
for _, album := range albums {
if w.quitting {
break
}
w.albumCh <- album
}
w.Wait()
if w.errors > 0 {
return fmt.Errorf("completed with %d errors, please check logs", w.errors)
}
if w.quitting {
log.Info("Quit worker!")
return nil
}
log.Info("Backup completed.")
return nil
}
func (w *Worker) Stop() {
log.Info("Quitting worker...")
close(w.stopCh)
w.quitting = true
}
func (w *Worker) Wait() {
close(w.albumCh)
log.Debug("waiting albumWg...")
w.albumWg.Wait()
log.Debug("albumWg done.")
close(w.downloadsCh)
log.Debug("waiting downloadWg...")
w.downloadWg.Wait()
log.Debug("downloadWg done.")
}