/
photos.go
412 lines (384 loc) · 11.1 KB
/
photos.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package collect
import (
"context"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/jyothri/hdd/constants"
"github.com/jyothri/hdd/db"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"golang.org/x/time/rate"
)
var photosApiBaseUrl = "https://photoslibrary.googleapis.com/"
var throttler = rate.NewLimiter(150, 10)
var photosConfig *oauth2.Config
func init() {
photosConfig = &oauth2.Config{
ClientID: constants.OauthClientId,
ClientSecret: constants.OauthClientSecret,
Endpoint: google.Endpoint,
Scopes: []string{
"https://www.googleapis.com/auth/photoslibrary.readonly",
"https://www.googleapis.com/auth/photoslibrary.sharing"},
}
}
func getPhotosService(refreshToken string) *http.Client {
tokenSrc := oauth2.Token{
RefreshToken: refreshToken,
}
client := photosConfig.Client(context.Background(), &tokenSrc)
client.Timeout = 10 * time.Second
return client
}
func Photos(photosScan GPhotosScan) int {
photosMediaItem := make(chan db.PhotosMediaItem, 10)
scanId := db.LogStartScan("photos")
go db.SaveScanMetadata("", "", scanId)
go startPhotosScan(scanId, photosScan, photosMediaItem)
go db.SavePhotosMediaItemToDb(scanId, photosMediaItem)
return scanId
}
func startPhotosScan(scanId int, photosScan GPhotosScan, photosMediaItem chan<- db.PhotosMediaItem) {
lock.Lock()
defer lock.Unlock()
ticker := time.NewTicker(5 * time.Second)
done := make(chan bool)
go logProgressToConsole(done, ticker)
var wg sync.WaitGroup
if photosScan.AlbumId != "" {
listMediaItemsForAlbum(photosScan, photosMediaItem, &wg)
} else {
listMediaItems(photosScan, photosMediaItem, &wg)
}
wg.Wait()
done <- true
ticker.Stop()
close(photosMediaItem)
}
func processMediaItem(photosScan GPhotosScan, mediaItem MediaItem, photosMediaItem chan<- db.PhotosMediaItem, wg *sync.WaitGroup) {
defer wg.Done()
var size int64 = -1
var md5Hash string
if photosScan.FetchMd5Hash {
size, md5Hash = getContentSizeAndHash(mediaItem.BaseUrl, mediaItem.MimeType)
} else if photosScan.FetchSize {
size = getContentSize(mediaItem.BaseUrl, mediaItem.MimeType)
}
var cameraMake string
var cameraModel string
var fNumber float32
var exposureTime string
var focalLength float32
var iso int
var fps float32
if mediaItem.MimeType[:5] == "image" {
cameraMake = mediaItem.MediaMetadata.Photo.CameraMake
cameraModel = mediaItem.MediaMetadata.Photo.CameraModel
fNumber = mediaItem.MediaMetadata.Photo.ApertureFNumber
exposureTime = mediaItem.MediaMetadata.Photo.ExposureTime
focalLength = mediaItem.MediaMetadata.Photo.FocalLength
iso = mediaItem.MediaMetadata.Photo.IsoEquivalent
} else {
cameraMake = mediaItem.MediaMetadata.Video.CameraMake
cameraModel = mediaItem.MediaMetadata.Video.CameraModel
fps = mediaItem.MediaMetadata.Video.Fps
}
pmi := db.PhotosMediaItem{
MediaItemId: mediaItem.Id,
ProductUrl: mediaItem.ProductUrl,
MimeType: mediaItem.MimeType,
Filename: mediaItem.Filename,
Size: size,
ContributorDisplayName: mediaItem.ContributorInfo.DisplayName,
CameraMake: cameraMake,
CameraModel: cameraModel,
FocalLength: focalLength,
FNumber: fNumber,
Iso: iso,
ExposureTime: exposureTime,
Fps: fps,
Md5hash: md5Hash,
}
layout := "2006-01-02T15:04:05Z"
str := mediaItem.MediaMetadata.CreationTime
t, err := time.Parse(layout, str)
if err == nil {
pmi.FileModTime = t
} else {
fmt.Printf("err parsing time. err=%v\n", err)
}
photosMediaItem <- pmi
counter_processed += 1
counter_pending -= 1
}
func ListAlbums(refreshToken string) []Album {
albums := make([]Album, 0)
url := photosApiBaseUrl + "v1/albums"
nextPageToken := ""
hasNextPage := true
client := getPhotosService(refreshToken)
for hasNextPage {
err := throttler.Wait(context.Background())
checkError(err, fmt.Sprintf("Error with limiter: %s", err))
nextPageUrl := url + "?pageToken=" + nextPageToken
req, err := http.NewRequest("GET", nextPageUrl, nil)
checkError(err)
resp, err := client.Do(req)
checkError(err)
if resp.StatusCode != 200 {
fmt.Printf("Unexpected response status code %v\n", resp.StatusCode)
rb, _ := io.ReadAll(resp.Body)
fmt.Printf("Response %v\n", string(rb))
return albums
}
albumResponse := new(ListAlbumsResponse)
err = getJson(resp, albumResponse)
checkError(err)
nextPageToken = albumResponse.NextPageToken
albums = append(albums, albumResponse.Albums...)
if len(nextPageToken) == 0 {
hasNextPage = false
}
}
return albums
}
func listMediaItemsForAlbum(photosScan GPhotosScan, photosMediaItem chan<- db.PhotosMediaItem, wg *sync.WaitGroup) {
var retries int = 25
url := photosApiBaseUrl + "v1/mediaItems:search"
nextPageToken := ""
hasNextPage := true
client := getPhotosService(photosScan.RefreshToken)
for hasNextPage {
err := throttler.Wait(context.Background())
checkError(err, fmt.Sprintf("Error with limiter: %s", err))
nextPageUrl := url + "?pageToken=" + nextPageToken
request := &SearchMediaItemRequest{AlbumId: photosScan.AlbumId}
reqJson, err := json.Marshal(request)
checkError(err)
reqBody := strings.NewReader(string(reqJson))
req, err := http.NewRequest("POST", nextPageUrl, reqBody)
checkError(err)
resp, err := client.Do(req)
checkError(err)
if resp.StatusCode != 200 {
fmt.Printf("Unexpected response status code %v", resp.StatusCode)
rb, _ := io.ReadAll(resp.Body)
fmt.Printf("Response %v\n", string(rb))
if retries == 0 {
return
}
retries -= 1
continue
}
listMediaItemResponse := new(ListMediaItemResponse)
err = getJson(resp, listMediaItemResponse)
checkError(err)
nextPageToken = listMediaItemResponse.NextPageToken
wg.Add(len(listMediaItemResponse.MediaItems))
counter_pending += len(listMediaItemResponse.MediaItems)
for _, mediaItem := range listMediaItemResponse.MediaItems {
err := throttler.Wait(context.Background())
checkError(err, fmt.Sprintf("Error with limiter: %s", err))
processMediaItem(photosScan, mediaItem, photosMediaItem, wg)
}
if len(nextPageToken) == 0 {
hasNextPage = false
}
}
}
func listMediaItems(photosScan GPhotosScan, photosMediaItem chan<- db.PhotosMediaItem, wg *sync.WaitGroup) {
var retries int = 25
url := photosApiBaseUrl + "v1/mediaItems"
nextPageToken := ""
hasNextPage := true
client := getPhotosService(photosScan.RefreshToken)
for hasNextPage {
err := throttler.Wait(context.Background())
checkError(err, fmt.Sprintf("Error with limiter: %s", err))
nextPageUrl := url + "?pageToken=" + nextPageToken
req, err := http.NewRequest("GET", nextPageUrl, nil)
checkError(err)
resp, err := client.Do(req)
checkError(err)
if resp.StatusCode != 200 {
fmt.Printf("Unexpected response status code %v", resp.StatusCode)
rb, _ := io.ReadAll(resp.Body)
fmt.Printf("Response %v\n", string(rb))
if retries == 0 {
return
}
retries -= 1
continue
}
listMediaItemResponse := new(ListMediaItemResponse)
err = getJson(resp, listMediaItemResponse)
checkError(err)
nextPageToken = listMediaItemResponse.NextPageToken
wg.Add(len(listMediaItemResponse.MediaItems))
counter_pending += len(listMediaItemResponse.MediaItems)
for _, mediaItem := range listMediaItemResponse.MediaItems {
err := throttler.Wait(context.Background())
checkError(err, fmt.Sprintf("Error with limiter: %s", err))
processMediaItem(photosScan, mediaItem, photosMediaItem, wg)
}
if len(nextPageToken) == 0 {
hasNextPage = false
}
}
}
func getContentSizeAndHash(url string, mimeType string) (int64, string) {
var retries int = 5
var resp *http.Response
var err error
switch mimeType[:5] {
case "image":
//e.g. image/jpeg image/png image/gif
url = url + "=d"
case "video":
//e.g. video/mp4
url = url + "=dv"
default:
fmt.Printf("Unhandled mime type: %v\n", mimeType)
}
for retries > 0 {
resp, err = http.Get(url)
if err != nil {
fmt.Printf("Got error:%v. Will retry %v times\n", err, retries)
retries -= 1
continue
}
if resp.StatusCode != 200 {
fmt.Printf("Unexpected response status code %v", resp.StatusCode)
rb, _ := io.ReadAll(resp.Body)
fmt.Printf("Response %v\n", string(rb))
fmt.Printf("Will retry %v times\n", retries)
retries -= 1
}
break
}
if resp == nil || resp.StatusCode != 200 {
return 0, ""
}
defer resp.Body.Close()
contentLength, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
checkError(err)
hash := md5.New()
_, err = io.Copy(ioutil.Discard, io.TeeReader(resp.Body, hash))
checkError(err)
return contentLength, hex.EncodeToString(hash.Sum(nil))
}
func getContentSize(url string, mimeType string) int64 {
var retries int = 5
var resp *http.Response
var err error
switch mimeType[:5] {
case "image":
//e.g. image/jpeg image/png image/gif
url = url + "=d"
case "video":
//e.g. video/mp4
url = url + "=dv"
default:
fmt.Printf("Unhandled mime type: %v\n", mimeType)
}
for retries > 0 {
resp, err = http.Head(url)
if err != nil {
fmt.Printf("Got error:%v. Will retry %v times\n", err, retries)
retries -= 1
continue
}
if resp.StatusCode != 200 {
fmt.Printf("Unexpected response status code %v", resp.StatusCode)
rb, _ := io.ReadAll(resp.Body)
fmt.Printf("Response %v\n", string(rb))
fmt.Printf("Will retry %v times\n", retries)
retries -= 1
}
break
}
if resp == nil || resp.StatusCode != 200 {
return 0
}
defer resp.Body.Close()
contentLength, err := strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
checkError(err)
io.Copy(ioutil.Discard, resp.Body)
return contentLength
}
func getJson(r *http.Response, target interface{}) error {
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(target)
}
type Album struct {
Id string
Title string
ProductUrl string
MediaItemsCount string
CoverPhotoBaseUrl string
CoverPhotoMediaItemId string
}
type ListAlbumsResponse struct {
Albums []Album
NextPageToken string
}
type MediaItem struct {
Id string
Description string
ProductUrl string
BaseUrl string
MimeType string
Filename string
MediaMetadata MediaMetadata
ContributorInfo ContributorInfo
}
type MediaMetadata struct {
CreationTime string
Width string
Height string
// Union field metadata can be only one of the following:
Photo Photo
Video Video
}
type Photo struct {
CameraMake string
CameraModel string
FocalLength float32
ApertureFNumber float32
IsoEquivalent int
ExposureTime string
}
type Video struct {
CameraMake string
CameraModel string
Fps float32
}
type ContributorInfo struct {
ProfilePictureBaseUrl string
DisplayName string
}
type ListMediaItemResponse struct {
MediaItems []MediaItem
NextPageToken string
}
type SearchMediaItemRequest struct {
AlbumId string `json:"albumId"`
PageSize int `json:"pageSize"`
PageToken string `json:"pageToken"`
OrderBy string `json:"orderBy"`
}
type GPhotosScan struct {
AlbumId string
FetchSize bool
FetchMd5Hash bool
RefreshToken string
}