-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathto-google
executable file
·134 lines (112 loc) · 4 KB
/
to-google
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
#!/usr/bin/env python2
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import json
import os
import click
from os import listdir
from os.path import isfile, join
from utils import readjson, writejson
import requests
def aggregate(data):
agg = data['title']
if not agg:
raise RuntimeError('Missing title')
if 'description' in data and data['description']:
agg = agg + '\n\n' + data['description']
if 'comments' in data:
agg += '\n\nKommentarer\n'
for comment in data['comments']:
agg += comment['authorname'] + ': ' + comment['text'] + '\n'
if len(agg) > 950:
raise RuntimeError('Aggregated description too long: ' + agg)
return agg
def is_photo_json(folder, f):
return isfile(join(folder, f)) and f.endswith('.json') and f != 'meta.json'
def full_prefix(folder, f):
return os.path.join(folder, f[:-5])
class GPhotos(object):
def __init__(self):
# Setup the Photo v1 API
SCOPES = 'https://www.googleapis.com/auth/photoslibrary'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
self._service = build('photoslibrary', 'v1', http=creds.authorize(Http()))
self._access_token = self._service._http.request.credentials.access_token
def upload(self, filename):
f = open(filename, 'rb').read()
url = 'https://photoslibrary.googleapis.com/v1/uploads'
headers = {
'Authorization': "Bearer " + self._access_token,
'Content-Type': 'application/octet-stream',
'X-Goog-Upload-File-Name': filename,
'X-Goog-Upload-Protocol': "raw",
}
r = requests.post(url, data=f, headers=headers)
print('Uploaded ' + filename)
return r.content
def create_album(self, title):
return self._service.albums().create(body={
'album': {'title': title}
}).execute()
def batch_create(self, albumId, description, token):
url = 'https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate'
headers = {
'Authorization': "Bearer " + self._access_token,
'Content-Type': 'application/json'
}
req = {
'albumId': albumId,
'newMediaItems': [
{
'description': description,
'simpleMediaItem': {
'uploadToken': token
}
}
],
'albumPosition': {
'position': 'LAST_IN_ALBUM'
}
}
return requests.post(url, data=json.dumps(req), headers=headers)
def upload(folder):
metapath = os.path.join(folder, 'meta.json')
meta = readjson(metapath)
gphotos = GPhotos()
print(meta['title'])
gmeta = meta.get('google', dict())
meta['google'] = gmeta
if 'albumId' in gmeta:
print('Using existing album')
albumId = gmeta['albumId']
else:
print('Creating album')
result = gphotos.create_album(meta['title'])
albumId = gmeta['albumId'] = result['id']
writejson(metapath, meta)
files = sorted([full_prefix(folder, f) for f in listdir(folder)
if is_photo_json(folder, f)])
for filename in files:
info = readjson(filename + '.json')
jpg = filename + '.jpg'
description = aggregate(info)
token = gphotos.upload(jpg)
print('TOKEN ' + token)
response = gphotos.batch_create(albumId, description, token)
print('RESPONSE CONTENT')
print(response.content)
@click.command()
@click.option(
'--folder',
required=True,
help='the folder containing meta.json and the photos')
def to_google(folder):
upload(folder)
if __name__ == '__main__':
to_google()