Files
sfhorizont/store/upload_listing.py
2026-10-25 07:11:03 +01:00

134 lines
6.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Upload the App Store listing (texts + screenshots) from store/metadata.json.
python3 store/upload_listing.py <screenshots_dir> [--locales en-US hu ...] [--texts-only]
[--privacy-url URL] [--support-url URL] [--marketing-url URL]
<screenshots_dir>/<locale>/0N-*.png are the 1290×2796 images made by
make_screenshots.mjs. Re-running replaces the screenshots and texts.
Works on the version in "Prepare for Submission".
"""
import argparse
import hashlib
import json
import sys
import time
import urllib.request
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'scripts'))
from asc_api import Asc, AscError # noqa: E402
HERE = Path(__file__).resolve().parent
DISPLAY_TYPE = 'APP_IPHONE_67' # 6.7"/6.9" iPhone, 1290×2796
EDITABLE = {'PREPARE_FOR_SUBMISSION', 'DEVELOPER_REJECTED', 'REJECTED', 'METADATA_REJECTED'}
def find(items, **attrs):
return next((i for i in items if all(i['attributes'].get(k) == v for k, v in attrs.items())), None)
def upsert_localization(a, kind, parent_rel, parent_id, existing, locale, fields):
loc = find(existing, locale=locale)
fields = {k: v for k, v in fields.items() if v is not None}
if loc:
a.call('PATCH', f'/v1/{kind}/{loc["id"]}', {'data': {'type': kind, 'id': loc['id'], 'attributes': fields}})
return loc['id']
res = a.call('POST', f'/v1/{kind}', {'data': {'type': kind, 'attributes': {'locale': locale, **fields},
'relationships': {parent_rel: {'data': {'type': parent_rel + 's' if not parent_rel.endswith('s') else parent_rel, 'id': parent_id}}}}})
return res['data']['id']
def upload_screenshot(a, set_id, path):
data = path.read_bytes()
res = a.call('POST', '/v1/appScreenshots', {'data': {'type': 'appScreenshots',
'attributes': {'fileName': path.name, 'fileSize': len(data)},
'relationships': {'appScreenshotSet': {'data': {'type': 'appScreenshotSets', 'id': set_id}}}}})
shot = res['data']
for op in shot['attributes']['uploadOperations']:
chunk = data[op['offset']:op['offset'] + op['length']]
req = urllib.request.Request(op['url'], data=chunk, method=op['method'],
headers={h['name']: h['value'] for h in op.get('requestHeaders', [])})
urllib.request.urlopen(req, timeout=180).read()
a.call('PATCH', f'/v1/appScreenshots/{shot["id"]}', {'data': {'type': 'appScreenshots', 'id': shot['id'],
'attributes': {'uploaded': True, 'sourceFileChecksum': hashlib.md5(data).hexdigest()}}})
return shot['id']
def screenshots(a, vloc_id, files):
sets = a.all(f'/v1/appStoreVersionLocalizations/{vloc_id}/appScreenshotSets')
s = next((x for x in sets if x['attributes']['screenshotDisplayType'] == DISPLAY_TYPE), None)
if s:
for old in a.all(f'/v1/appScreenshotSets/{s["id"]}/appScreenshots'):
a.call('DELETE', f'/v1/appScreenshots/{old["id"]}')
set_id = s['id']
else:
set_id = a.call('POST', '/v1/appScreenshotSets', {'data': {'type': 'appScreenshotSets',
'attributes': {'screenshotDisplayType': DISPLAY_TYPE},
'relationships': {'appStoreVersionLocalization': {'data': {'type': 'appStoreVersionLocalizations', 'id': vloc_id}}}}})['data']['id']
ids = [upload_screenshot(a, set_id, f) for f in files]
a.call('PATCH', f'/v1/appScreenshotSets/{set_id}/relationships/appScreenshots',
{'data': [{'type': 'appScreenshots', 'id': i} for i in ids]})
return len(ids)
def main():
ap = argparse.ArgumentParser()
ap.add_argument('shots')
ap.add_argument('--locales', nargs='*')
ap.add_argument('--privacy-url', default='https://sagifer.github.io/appdocuments/skycontour/privacy.html')
ap.add_argument('--support-url', default='https://sagifer.github.io/appdocuments/skycontour/support.html')
ap.add_argument('--marketing-url')
ap.add_argument('--texts-only', action='store_true', help='leave screenshots and build untouched')
ap.add_argument('--copyright', default='© 2026 Ferenc Sági')
args = ap.parse_args()
meta = {k: v for k, v in json.loads((HERE / 'metadata.json').read_text()).items() if not k.startswith('_')}
locales = args.locales or list(meta)
a = Asc()
app = a.app()
version = next(v for v in a.all(f'/v1/apps/{app["id"]}/appStoreVersions')
if v['attributes']['appStoreState'] in EDITABLE)
info = next(i for i in a.all(f'/v1/apps/{app["id"]}/appInfos')
if (i['attributes'].get('appStoreState') or i['attributes'].get('state')) in EDITABLE | {'PREPARE_FOR_SUBMISSION'})
print(f'version {version["attributes"]["versionString"]} ({version["attributes"]["appStoreState"]})')
# Version-level fields and category.
a.call('PATCH', f'/v1/appStoreVersions/{version["id"]}', {'data': {'type': 'appStoreVersions', 'id': version['id'],
'attributes': {'copyright': args.copyright}}})
a.call('PATCH', f'/v1/appInfos/{info["id"]}', {'data': {'type': 'appInfos', 'id': info['id'], 'relationships': {
'primaryCategory': {'data': {'type': 'appCategories', 'id': 'UTILITIES'}},
'secondaryCategory': {'data': {'type': 'appCategories', 'id': 'EDUCATION'}}}}})
iloc = a.all(f'/v1/appInfos/{info["id"]}/appInfoLocalizations')
for locale in locales:
m = meta[locale]
upsert_localization(a, 'appInfoLocalizations', 'appInfo', info['id'], iloc, locale,
{'name': 'SkyContour', 'subtitle': m['subtitle'], 'privacyPolicyUrl': args.privacy_url})
# Adding an app-info language also creates the version's localization: list it afresh.
vloc = a.all(f'/v1/appStoreVersions/{version["id"]}/appStoreVersionLocalizations')
vid = upsert_localization(a, 'appStoreVersionLocalizations', 'appStoreVersion', version['id'], vloc, locale,
{'description': m['description'], 'keywords': m['keywords'],
'promotionalText': m['promotionalText'], 'supportUrl': args.support_url,
'marketingUrl': args.marketing_url})
files = sorted((Path(args.shots) / locale).glob('0*.png'))
n = screenshots(a, vid, files) if files and not args.texts_only else 0
print(f'{locale:6} texts ok, {n} screenshots')
if args.texts_only:
return
# Newest processed build on the version.
builds = [b for b in a.all(f'/v1/builds?filter[app]={app["id"]}&filter[processingState]=VALID&sort=-uploadedDate&limit=10')]
if builds:
b = builds[0]
try:
a.call('PATCH', f'/v1/appStoreVersions/{version["id"]}/relationships/build',
{'data': {'type': 'builds', 'id': b['id']}})
print('build attached:', b['attributes']['version'])
except AscError as e:
print('build not attached yet:', str(e)[:200])
if __name__ == '__main__':
main()