143 lines
6.1 KiB
Python
143 lines
6.1 KiB
Python
"""Minimal Google Play Developer API client (service-account JSON key in
|
|||
|
|
~/.googleplay/skycontour.json). Used by the Android release/metadata scripts.
|
||
|
|
|
||
|
|
python3 scripts/gplay_api.py check # verify access: tracks + listings
|
||
|
|
python3 scripts/gplay_api.py upload build/app/outputs/bundle/release/app-release.aab [track] [status]
|
||
|
|
"""
|
||
|
|
import base64
|
||
|
|
import json
|
||
|
|
import os
|
||
|
|
import sys
|
||
|
|
import time
|
||
|
|
import urllib.error
|
||
|
|
import urllib.parse
|
||
|
|
import urllib.request
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
from cryptography.hazmat.primitives import hashes, serialization
|
||
|
|
from cryptography.hazmat.primitives.asymmetric import padding
|
||
|
|
|
||
|
|
API = 'https://androidpublisher.googleapis.com/androidpublisher/v3/applications'
|
||
|
|
UPLOAD = 'https://androidpublisher.googleapis.com/upload/androidpublisher/v3/applications'
|
||
|
|
SCOPE = 'https://www.googleapis.com/auth/androidpublisher'
|
||
|
|
PACKAGE = 'com.sagifer.skycontour'
|
||
|
|
KEY_FILE = Path(os.environ.get('GPLAY_KEY', Path.home() / '.googleplay/skycontour.json'))
|
||
|
|
METADATA = Path(__file__).resolve().parent.parent / 'store/metadata.json'
|
||
|
|
# store/metadata.json uses App Store Connect locales; Play has its own language codes.
|
||
|
|
PLAY_LANG = {'en-US': 'en-US', 'es-ES': 'es-ES', 'ar-SA': 'ar', 'de-DE': 'de-DE', 'hu': 'hu-HU',
|
||
|
|
'pl': 'pl-PL', 'fr-FR': 'fr-FR', 'it': 'it-IT', 'sk': 'sk'}
|
||
|
|
|
||
|
|
|
||
|
|
def release_notes():
|
||
|
|
"""'What's new' texts per Play language from store/metadata.json (releaseNotes)."""
|
||
|
|
meta = json.loads(METADATA.read_text())
|
||
|
|
return [{'language': PLAY_LANG[k], 'text': m['releaseNotes']}
|
||
|
|
for k, m in meta.items() if not k.startswith('_') and m.get('releaseNotes')]
|
||
|
|
|
||
|
|
|
||
|
|
def _b64url(b):
|
||
|
|
return base64.urlsafe_b64encode(b).rstrip(b'=').decode()
|
||
|
|
|
||
|
|
|
||
|
|
class GplayError(RuntimeError):
|
||
|
|
pass
|
||
|
|
|
||
|
|
|
||
|
|
class Gplay:
|
||
|
|
def __init__(self, key_file=KEY_FILE, package=PACKAGE):
|
||
|
|
self.info = json.loads(Path(key_file).read_text())
|
||
|
|
self.key = serialization.load_pem_private_key(self.info['private_key'].encode(), None)
|
||
|
|
self.package = package
|
||
|
|
self._token, self._exp = None, 0
|
||
|
|
|
||
|
|
def token(self):
|
||
|
|
"""OAuth access token via the service-account JWT bearer grant."""
|
||
|
|
now = int(time.time())
|
||
|
|
if not self._token or now > self._exp - 60:
|
||
|
|
head = _b64url(json.dumps({'alg': 'RS256', 'typ': 'JWT',
|
||
|
|
'kid': self.info['private_key_id']}).encode())
|
||
|
|
body = _b64url(json.dumps({'iss': self.info['client_email'], 'scope': SCOPE,
|
||
|
|
'aud': self.info['token_uri'], 'iat': now, 'exp': now + 3600}).encode())
|
||
|
|
sig = self.key.sign(f'{head}.{body}'.encode(), padding.PKCS1v15(), hashes.SHA256())
|
||
|
|
form = urllib.parse.urlencode({'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
|
||
|
|
'assertion': f'{head}.{body}.{_b64url(sig)}'}).encode()
|
||
|
|
try:
|
||
|
|
with urllib.request.urlopen(self.info['token_uri'], form, timeout=60) as r:
|
||
|
|
res = json.loads(r.read())
|
||
|
|
except urllib.error.HTTPError as e:
|
||
|
|
raise GplayError(f'token → HTTP {e.code}: {e.read().decode()[:800]}') from None
|
||
|
|
self._token, self._exp = res['access_token'], now + int(res.get('expires_in', 3600))
|
||
|
|
return self._token
|
||
|
|
|
||
|
|
def call(self, method, path, body=None, data=None, content_type='application/json', base=API):
|
||
|
|
"""path is relative to applications/<package>; data = raw upload bytes."""
|
||
|
|
url = f'{base}/{self.package}{path}'
|
||
|
|
payload = data if data is not None else (json.dumps(body).encode() if body is not None else None)
|
||
|
|
req = urllib.request.Request(url, method=method, data=payload,
|
||
|
|
headers={'Authorization': f'Bearer {self.token()}',
|
||
|
|
'Content-Type': content_type})
|
||
|
|
try:
|
||
|
|
with urllib.request.urlopen(req, timeout=600) as r:
|
||
|
|
raw = r.read()
|
||
|
|
return json.loads(raw) if raw else {}
|
||
|
|
except urllib.error.HTTPError as e:
|
||
|
|
raise GplayError(f'{method} {path} → HTTP {e.code}: {e.read().decode()[:1500]}') from None
|
||
|
|
|
||
|
|
# Every change goes through an edit: open → modify → commit (or delete to discard).
|
||
|
|
def edit(self):
|
||
|
|
return self.call('POST', '/edits', {})['id']
|
||
|
|
|
||
|
|
def commit(self, edit_id):
|
||
|
|
return self.call('POST', f'/edits/{edit_id}:commit')
|
||
|
|
|
||
|
|
def discard(self, edit_id):
|
||
|
|
return self.call('DELETE', f'/edits/{edit_id}')
|
||
|
|
|
||
|
|
def upload_bundle(self, edit_id, aab_path):
|
||
|
|
return self.call('POST', f'/edits/{edit_id}/bundles?uploadType=media', data=Path(aab_path).read_bytes(),
|
||
|
|
content_type='application/octet-stream', base=UPLOAD)
|
||
|
|
|
||
|
|
|
||
|
|
def check():
|
||
|
|
g = Gplay()
|
||
|
|
print('service account:', g.info['client_email'])
|
||
|
|
g.token()
|
||
|
|
print('token: ok')
|
||
|
|
e = g.edit()
|
||
|
|
try:
|
||
|
|
for t in g.call('GET', f'/edits/{e}/tracks').get('tracks', []):
|
||
|
|
rel = [(r.get('status'), r.get('versionCodes')) for r in t.get('releases', [])]
|
||
|
|
print(f"track {t['track']}: {rel or 'empty'}")
|
||
|
|
langs = [l['language'] for l in g.call('GET', f'/edits/{e}/listings').get('listings', [])]
|
||
|
|
print('listings:', ', '.join(langs) or 'none')
|
||
|
|
finally:
|
||
|
|
g.discard(e)
|
||
|
|
|
||
|
|
|
||
|
|
def upload(aab_path, track='internal', status='draft'):
|
||
|
|
"""Upload an .aab and put it on a track. A never-published app only accepts
|
||
|
|
status 'draft'; roll it out from Play Console (or rerun with 'completed')."""
|
||
|
|
g = Gplay()
|
||
|
|
e = g.edit()
|
||
|
|
try:
|
||
|
|
code = g.upload_bundle(e, aab_path)['versionCode']
|
||
|
|
print('uploaded versionCode', code)
|
||
|
|
g.call('PUT', f'/edits/{e}/tracks/{track}',
|
||
|
|
{'track': track, 'releases': [{'versionCodes': [str(code)], 'status': status,
|
||
|
|
'releaseNotes': release_notes()}]})
|
||
|
|
g.commit(e)
|
||
|
|
print(f'{track}: versionCode {code} ({status})')
|
||
|
|
except Exception:
|
||
|
|
g.discard(e)
|
||
|
|
raise
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
args = sys.argv[1:]
|
||
|
|
if args == ['check']:
|
||
|
|
check()
|
||
|
|
elif args[:1] == ['upload'] and len(args) >= 2:
|
||
|
|
upload(*args[1:])
|
||
|
|
else:
|
||
|
|
print(__doc__)
|