forked from kiwix/kiwix-android
-
Notifications
You must be signed in to change notification settings - Fork 1
/
update-play-store.py
executable file
·262 lines (203 loc) · 8.4 KB
/
update-play-store.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import logging
import sys
import os
import json
import requests
import tempfile
import shutil
from subprocess import call
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
# check for python version as google client api is broken on py2
if sys.version_info.major < 3:
print("You must run this script with python3 as "
"Google API Client is broken python2")
sys.exit(1)
try:
import httplib2
from apiclient.discovery import build
from oauth2client import client
except ImportError:
print("Missing Google API Client dependency.\n"
"Please install with: \n"
"apt-get install libffi-dev libssl-dev\n"
"pip install google-api-python-client PyOpenSSL\n"
"Install from github in case of oauth http errors.")
sys.exit(1)
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
for handler in logging.root.handlers:
handler.addFilter(logging.Filter('__main__'))
CURRENT_PATH = os.path.dirname(os.path.abspath(__file__))
def usage(arg0, exit=None):
print("Usage: {} <json_file>".format(arg0))
if exit is not None:
sys.exit(exit)
def syscall(args, shell=False, with_print=True):
''' execute an external command. Use shell=True if using bash specifics '''
args = args.split()
if with_print:
print(u"-----------\n" + u" ".join(args) + u"\n-----------")
if shell:
args = ' '.join(args)
call(args, shell=shell)
def get_remote_content(url):
''' file descriptor from remote file using GET '''
req = requests.get(url)
try:
req.raise_for_status()
except Exception as e:
logger.error("Failed to load data at `{}`".format(url))
logger.exception(e)
sys.exit(1)
return StringIO.StringIO(req.text)
def get_local_content(path):
''' file descriptor from local file '''
if not os.path.exists(path) or not os.path.isfile(path):
logger.error("Unable to find JSON file `{}`".format(path))
sys.exit(1)
try:
fd = open(path, 'r')
except Exception as e:
logger.error("Unable to open file `{}`".format(path))
logger.exception(e)
sys.exit(1)
return fd
def is_remote_path(path):
return path.startswith('http:')
def get_local_remote_fd(path):
''' file descriptor for a path (either local or remote) '''
if is_remote_path(path):
return get_remote_content(path)
else:
return get_local_content(path)
def copy_to(src, dst):
''' copy source content (local or remote) to local file '''
local = None
if is_remote_path(src):
local = tempfile.NamedTemporaryFile(delete=False)
download_remote_file(src, local.name)
src = local.name
shutil.copy(src, dst)
if local is not None:
os.remove(local.name)
def download_remote_file(url, path):
''' download url to path '''
syscall('wget -c -O {path} {url}'.format(path=path, url=url))
def main(json_path, *args):
jsdata = json.load(get_local_remote_fd(json_path))
logger.info("Updating Play Store Content for {}".format(jsdata['package']))
if not jsdata.get('play_store'):
logger.error("You have no data in the play_store container")
sys.exit(1)
if 'GOOGLE_API_KEY' not in os.environ:
logger.error("You need to set the GOOGLE_API_KEY environment variable "
"to use the Google API (using path to google-api.p12)")
return
GOOGLE_CLIENT_ID = '107823297044-nhoqv99cpr86vlfcronskirgib2g7tq' \
'9@developer.gserviceaccount.com'
service = build('androidpublisher', 'v2')
key = open(os.environ['GOOGLE_API_KEY'], 'rb').read()
credentials = client.SignedJwtAssertionCredentials(
GOOGLE_CLIENT_ID,
key,
scope='https://www.googleapis.com/auth/androidpublisher')
http = httplib2.Http()
http = credentials.authorize(http)
service = build('androidpublisher', 'v2', http=http)
package_name = jsdata['package']
ps = jsdata.get('play_store')
default_lang = None # for images
files_to_delete = []
try:
# another edit request
edit_request = service.edits().insert(body={},
packageName=package_name)
result = edit_request.execute()
edit_id = result['id']
logger.info("Starting Edit #{} for all updates…".format(edit_id))
if 'details' in ps:
logger.debug("Updating details")
details_fields = ['contactEmail', 'contactPhone',
'contactWebsite', 'defaultLanguage']
details_body = {k: v for k, v in ps['details'].items()
if k in details_fields and v is not None}
details_upd = service.edits().details().update(
editId=edit_id,
packageName=package_name,
body=details_body).execute()
logger.debug("updated with {} items.".format(len(details_upd)))
# update default_lang with the value we just submitted
default_lang = details_body.get('defaultLanguage', None)
if 'listings' in ps:
logger.debug("Updating listings (main texts)")
for lang in ps['listings']:
details_fields = ['fullDescription', 'shortDescription',
'title', 'video']
details_body = {k: v for k, v in ps['listings'][lang].items()
if k in details_fields and v is not None}
listing_upd = service.edits().listings().update(
editId=edit_id,
packageName=package_name,
language=lang,
body=details_body).execute()
logger.debug("updated {} with {} items"
.format(lang, len(listing_upd)))
if 'images' in ps:
logger.debug("Updating images")
# retrieve default language as important for images
if default_lang is None:
details_data = service.edits().details().get(
editId=edit_id, packageName=package_name,).execute()
default_lang = details_data['defaultLanguage']
# upload images to default lang
for image_type, images in ps['images'].items():
if not images:
continue
# delete images for that type
delete_upd = service.edits().images().deleteall(
editId=edit_id,
packageName=package_name,
imageType=image_type,
language=default_lang).execute()
logger.debug("Cleared {} images: {}".format(
image_type,
",".join([d['sha1'] for d in delete_upd['deleted']])))
for image in images:
img_file = tempfile.NamedTemporaryFile(suffix='.png').name
copy_to(image, img_file)
files_to_delete.append(img_file)
img_upd = service.edits().images().upload(
editId=edit_id,
packageName=package_name,
imageType=image_type,
language=default_lang,
media_body=img_file).execute()
logger.debug("Uploaded image for {}. sha1: {}"
.format(image_type, img_upd['image']['sha1']))
# commit *all* the changes on the Play Store
commit_request = service.edits().commit(
editId=edit_id, packageName=package_name).execute()
logger.debug("Edit `{}` has been committed. done."
.format(commit_request['id']))
except client.AccessTokenRefreshError:
logger.error("The credentials have been revoked or expired, "
"please re-run the application to re-authorize")
finally:
for f in files_to_delete:
os.remove(f)
if __name__ == '__main__':
# ensure we were provided a JSON file as first argument
if len(sys.argv) < 2:
usage(sys.argv[0], 1)
else:
jspath = sys.argv[1]
args = sys.argv[2:]
main(jspath, *args)