diff --git a/README.md b/README.md index f172b2e..7148589 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,11 @@ A natív app a webes buildet futtatja WebView-ban; előtte mindig: `./scripts/bu ./scripts/build_web.sh && flutter build apk --debug # build/app/outputs/flutter-apk/app-debug.apk ``` +- **Play-kiadás:** emeld a build-számot a `pubspec.yaml`-ban (`version: 1.0.0+N`), majd + `./scripts/build_web.sh && flutter build appbundle --release && python3 scripts/gplay_api.py upload build/app/outputs/bundle/release/app-release.aab internal draft` + (track: `internal`/`alpha`/`beta`/`production`; státusz: `draft` vagy `completed` – amíg az app nincs kiadva, csak `draft` megy). Hozzáférés-ellenőrzés: `python3 scripts/gplay_api.py check`. +- A repón kívül, `~/.googleplay/` alatt: `skycontour.json` (service account `skycontour-publisher@skycontour.iam.gserviceaccount.com`, jogot a Play Console › Users and permissions alatt kapott), `upload-keystore.jks` + `key.properties` (upload kulcs és jelszava; a Gradle innen olvassa, hiányában debug kulccsal ír alá). **A keystore-ról és a jelszóról legyen mentés.** + ### Ikon és nyitókép Forrás: `assets/branding/make_icons.py` (A · Skyline koncepció a design-vászonról; a webes `AppIcon.jsx` ugyanezt rajzolja). diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 1cb3d8f..99abb64 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -1,3 +1,5 @@ +import java.util.Properties + plugins { id("com.android.application") id("kotlin-android") @@ -5,6 +7,11 @@ plugins { id("dev.flutter.flutter-gradle-plugin") } +// Play upload key lives outside the repo (see README). Without it, release +// builds fall back to the debug key so `flutter run --release` still works. +val uploadKeyFile = File(System.getProperty("user.home"), ".googleplay/key.properties") +val uploadKey = Properties().apply { if (uploadKeyFile.exists()) uploadKeyFile.inputStream().use { load(it) } } + android { namespace = "com.example.sfzenith" compileSdk = flutter.compileSdkVersion @@ -29,11 +36,20 @@ android { versionName = flutter.versionName } + signingConfigs { + if (uploadKeyFile.exists()) { + create("release") { + storeFile = file(uploadKey.getProperty("storeFile")) + storePassword = uploadKey.getProperty("storePassword") + keyAlias = uploadKey.getProperty("keyAlias") + keyPassword = uploadKey.getProperty("keyPassword") + } + } + } + buildTypes { release { - // TODO: Add your own signing config for the release build. - // Signing with the debug keys for now, so `flutter run --release` works. - signingConfig = signingConfigs.getByName("debug") + signingConfig = signingConfigs.findByName("release") ?: signingConfigs.getByName("debug") } } } diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 04a17b6..75f8b5e 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -13,8 +13,33 @@ + + + + + + + + with WidgetsBindingObserver { bool _recovering = false; int _loadRetries = 0; + /// Watchdog: the page reports its first screen through the `route` handler. + /// No report within [_readyTimeout] → fresh WebView; after + /// [_maxWatchdogRestarts] in a row the error screen with Try again shows. + static const _readyTimeout = Duration(seconds: 6); + static const _maxWatchdogRestarts = 3; + bool _pageReady = false; + Timer? _readyTimer; + int _watchdogRestarts = 0; + + /// After a long time in the background start from a fresh page anyway: + /// iOS often leaves a WebView behind that no longer draws. + static const _staleAfter = Duration(minutes: 30); + DateTime? _backgroundSince; + /// Selected tab while the bar is shown; null = hidden (survey flow, welcome). int? _tab; @@ -129,19 +144,29 @@ class _WebShellState extends State with WidgetsBindingObserver { @override void dispose() { WidgetsBinding.instance.removeObserver(this); + _readyTimer?.cancel(); _server.stop(); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { - if (state == AppLifecycleState.resumed && _ready) _recover(); + if (state == AppLifecycleState.paused || state == AppLifecycleState.hidden) { + _backgroundSince ??= DateTime.now(); + } else if (state == AppLifecycleState.resumed) { + final since = _backgroundSince; + _backgroundSince = null; + if (!_ready) return; + final stale = since != null && DateTime.now().difference(since) > _staleAfter; + // Give the WebView a moment to come back to the screen before probing it. + Future.delayed(const Duration(milliseconds: 600), () => _recover(forceNewWebView: stale)); + } } /// Back from the background: iOS may have taken the server's socket and - /// killed the page's process while the app was suspended. + /// killed (or frozen) the page's process while the app was suspended. Future _recover({bool forceNewWebView = false}) async { - if (_recovering) return; + if (_recovering || !mounted) return; _recovering = true; try { await _server.ensureRunning(); @@ -154,14 +179,20 @@ class _WebShellState extends State with WidgetsBindingObserver { } } + /// Alive = the page runs script AND draws: it answers after an animation + /// frame and has content. A WebView that lost its renderer never answers. Future _pageAlive() async { final c = _controller; - if (c == null) return false; + if (c == null || !_pageReady) return false; try { - final n = await c - .evaluateJavascript(source: "(document.getElementById('root') || {}).childElementCount || 0") - .timeout(const Duration(seconds: 2)); - return n is num && n > 0; + final res = await c + .callAsyncJavaScript( + functionBody: "return await new Promise((resolve) => requestAnimationFrame(() => " + "resolve((document.getElementById('root') || {}).childElementCount || 0)));", + ) + .timeout(const Duration(seconds: 3)); + final n = res?.value; + return res?.error == null && n is num && n > 0; } catch (_) { return false; } @@ -171,10 +202,31 @@ class _WebShellState extends State with WidgetsBindingObserver { if (!mounted) return; setState(() { _controller = null; + _pageReady = false; _webKey = UniqueKey(); }); } + /// Started with every WebView: no first screen in time → start a fresh one. + void _armWatchdog() { + _readyTimer?.cancel(); + _readyTimer = Timer(_readyTimeout, () { + if (!mounted || _pageReady || _error != null) return; + if (_watchdogRestarts >= _maxWatchdogRestarts) { + setState(() => _error = 'SkyContour could not load its screen.'); + return; + } + _watchdogRestarts++; + _recover(forceNewWebView: true); + }); + } + + /// A tap on the native tab bar must change the page; if the page is dead, restart it. + Future _probeAfterTap() async { + await Future.delayed(const Duration(milliseconds: 300)); + if (mounted && _ready && !await _pageAlive()) _recover(forceNewWebView: true); + } + /// The page itself failed to load (server not answering): bind again, retry a few times. void _onMainFrameError() { if (_loadRetries >= 3) return; @@ -241,6 +293,10 @@ class _WebShellState extends State with WidgetsBindingObserver { /// The web app reports its screen: {name, tab: 'sites'|'settings'|null}. Future _handleRoute(List args) async { + // First report = the page is up and drawing (watchdog satisfied). + _pageReady = true; + _watchdogRestarts = 0; + _readyTimer?.cancel(); final info = args.isNotEmpty && args[0] is Map ? args[0] as Map : const {}; final index = _tabs.indexWhere((t) => t.id == info['tab']); final labels = info['labels'] is Map @@ -285,6 +341,7 @@ class _WebShellState extends State with WidgetsBindingObserver { HapticFeedback.selectionClick(); final id = _tabs[index].id; _controller?.evaluateJavascript(source: "window.__sfzNav && window.__sfzNav('$id')"); + _probeAfterTap(); } /// Kept for older web builds that saved the raw panorama PNG to the gallery. @@ -313,6 +370,7 @@ class _WebShellState extends State with WidgetsBindingObserver { style: FilledButton.styleFrom(backgroundColor: _accent, foregroundColor: Colors.black), onPressed: () { _loadRetries = 0; + _watchdogRestarts = 0; if (_ready) { _recover(forceNewWebView: true); } else { @@ -366,6 +424,7 @@ class _WebShellState extends State with WidgetsBindingObserver { ), onWebViewCreated: (controller) { _controller = controller; + _armWatchdog(); controller.addJavaScriptHandler(handlerName: 'route', callback: _handleRoute); controller.addJavaScriptHandler(handlerName: 'keepAwake', callback: _handleKeepAwake); controller.addJavaScriptHandler(handlerName: 'haptic', callback: _handleHaptic); diff --git a/pubspec.yaml b/pubspec.yaml index 0c49146..5490cfb 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.0.0+5 +version: 1.0.0+6 environment: sdk: ^3.11.1 diff --git a/scripts/gplay_api.py b/scripts/gplay_api.py new file mode 100644 index 0000000..2fa4975 --- /dev/null +++ b/scripts/gplay_api.py @@ -0,0 +1,142 @@ +"""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/; 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__) diff --git a/store/README.md b/store/README.md index 7ab1a0c..6f9dc65 100644 --- a/store/README.md +++ b/store/README.md @@ -26,3 +26,20 @@ python3 store/upload_listing.py $W # privacy/support URLs default to sagifer.g ``` Not covered by the API and set in App Store Connect by hand: App Privacy answers, age rating, price and availability. + +## Google Play + +`make_screenshots.mjs` also writes Play versions (1440×2560, 9:16, no iPhone frame) to `//play/`. `FRAMES_ONLY=1` re-frames existing raw screens without running the app. + +| File | What | +|---|---| +| `make_play_graphics.py` | 512×512 icon (`/play-icon.png`) and a 1024×500 feature graphic per locale (`//play/feature.png`) | +| `upload_play_listing.py` | Uploads title, short description (`playShortDescription`), full description (`description`), icon, feature graphic and screenshots via the Play Developer API (`scripts/gplay_api.py`); sets contact email (`sagiferdev@gmail.com`, public) and website | + +```bash +# after the App Store steps above (same $W) +python3 store/make_play_graphics.py $W +python3 store/upload_play_listing.py $W # --locales hu de-DE … / --texts-only +``` + +Set in Play Console by hand: privacy policy URL, app category, Data safety, content rating, target audience, ads declaration. diff --git a/store/make_play_graphics.py b/store/make_play_graphics.py new file mode 100644 index 0000000..ec0977b --- /dev/null +++ b/store/make_play_graphics.py @@ -0,0 +1,83 @@ +"""Google Play graphics: 512×512 icon and a 1024×500 feature graphic per locale. + + python3 store/make_play_graphics.py + +Needs /profile.json from store/scene.py (the demo horizon drawn along the +bottom). Writes /play-icon.png and //play/feature.png. +""" +import json +import subprocess +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parent +CHROME = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' +FONTS = (ROOT / 'wasm/frontend/node_modules/@fontsource/barlow/files').as_uri() +ICON = ROOT / 'assets/branding/icon-1024.png' +W, H = 1024, 500 + + +def horizon_path(profile): + """Profile (360 altitudes, degrees) → SVG area path along the bottom third.""" + base, gain = H, 6.0 # 1° altitude → 6 px + pts = [(i * W / 359, base - 70 - alt * gain) for i, alt in enumerate(profile)] + line = ' '.join(f'{x:.1f},{y:.1f}' for x, y in pts) + return f'M0,{base} L{line} L{W},{base} Z', f'M{line.replace(" ", " L")}' + + +def html(subtitle, rtl, profile): + area, line = horizon_path(profile) + return f'''
+

SkyContour

{subtitle}

+ + + +''' + + +def render(src, png, w, h): + for _ in range(3): # headless Chrome occasionally exits non-zero + r = subprocess.run([CHROME, '--headless=new', '--hide-scrollbars', '--allow-file-access-from-files', + '--force-device-scale-factor=1', f'--window-size={w},{h}', f'--screenshot={png}', + src.as_uri()], capture_output=True) + if r.returncode == 0: + return + raise RuntimeError(f'render failed: {png}') + + +def main(): + work = Path(sys.argv[1]) + meta = json.loads((HERE / 'metadata.json').read_text()) + profile = json.loads((work / 'profile.json').read_text()) + subprocess.run(['sips', '-z', '512', '512', str(ICON), '--out', str(work / 'play-icon.png')], + check=True, capture_output=True) + for locale, m in meta.items(): + if locale.startswith('_'): + continue + out = work / locale / 'play' + out.mkdir(parents=True, exist_ok=True) + page = out / 'feature.html' + page.write_text(html(m['subtitle'], m['app'] == 'ar', profile)) + render(page, out / 'feature.png', W, H) + print(locale, 'ok') + + +if __name__ == '__main__': + main() diff --git a/store/make_screenshots.mjs b/store/make_screenshots.mjs index 74fcc80..ccf2c02 100644 --- a/store/make_screenshots.mjs +++ b/store/make_screenshots.mjs @@ -215,11 +215,19 @@ async function importLocale(app) { const fontDir = pathToFileURL(join(ROOT, 'wasm/frontend/node_modules/@fontsource/barlow/files')).href -function frameHtml({ raw, caption, rtl, tabs }) { - const W = 1290, H = 2796, scale = 0.79 +// App Store: 1290×2796 with an iPhone frame. Play: 1440×2560 (9:16; Play rejects +// images longer than 2:1) with a generic phone outline and no Dynamic Island. +const FRAME = { + appstore: { W: 1290, H: 2796, scale: 0.79, bottom: 60, h1Top: 150, h1Size: 92, island: true }, + play: { W: 1440, H: 2560, scale: 0.68, bottom: 70, h1Top: 120, h1Size: 84, island: false }, +} + +function frameHtml({ raw, caption, rtl, tabs, kind = 'appstore' }) { + const { W, H, scale, bottom, h1Top, h1Size, island } = FRAME[kind] const sw = Math.round(1290 * scale), sh = Math.round(2796 * scale) - const left = Math.round((W - sw) / 2), top = H - sh - 60 + const left = Math.round((W - sw) / 2), top = H - sh - bottom const px = (v) => Math.round(v * 3 * scale) // app points → frame pixels + const r = (v) => Math.round(v * scale / 0.79) // radii tuned for the App Store frame const tabBar = tabs ? `
${tabs.map((t, i) => `
@@ -235,12 +243,13 @@ function frameHtml({ raw, caption, rtl, tabs }) { radial-gradient(2px 2px at 120px 160px, #fff8, transparent), radial-gradient(2px 2px at 980px 90px, #fff9, transparent), radial-gradient(1.5px 1.5px at 400px 320px, #fff6, transparent), radial-gradient(2px 2px at 1180px 420px, #fff7, transparent), radial-gradient(1.5px 1.5px at 760px 250px, #fff5, transparent), radial-gradient(2.5px 2.5px at 230px 470px, #FFE9C7aa, transparent); } - h1 { position: absolute; left: 90px; right: 90px; top: 150px; margin: 0; color: #E8ECF2; font-weight: 700; - font-size: 92px; line-height: 1.12; text-align: center; letter-spacing: -0.01em; } + h1 { position: absolute; left: 90px; right: 90px; top: ${h1Top}px; margin: 0; color: #E8ECF2; font-weight: 700; + font-size: ${h1Size}px; line-height: 1.12; text-align: center; letter-spacing: -0.01em; } h1 em { color: #F5B544; font-style: normal; } + ${kind === 'play' ? `h1 { top: 0; height: ${top - 18}px; display: flex; align-items: center; justify-content: center; }` : ''} .device { position: absolute; left: ${left - 18}px; top: ${top - 18}px; width: ${sw + 36}px; height: ${sh + 36}px; - border-radius: 120px; background: #1A2130; box-shadow: 0 40px 120px #000a, inset 0 0 0 3px #2B3446; } - .screen { position: absolute; left: ${left}px; top: ${top}px; width: ${sw}px; height: ${sh}px; border-radius: 104px; overflow: hidden; background: #000; } + border-radius: ${r(120)}px; background: #1A2130; box-shadow: 0 40px 120px #000a, inset 0 0 0 3px #2B3446; } + .screen { position: absolute; left: ${left}px; top: ${top}px; width: ${sw}px; height: ${sh}px; border-radius: ${r(104)}px; overflow: hidden; background: #000; } .screen img { width: 100%; height: 100%; display: block; } .status { position: absolute; left: 0; right: 0; top: 0; height: ${px(54)}px; display: flex; align-items: center; justify-content: space-between; padding: 0 ${px(34)}px; color: #fff; font: 600 ${px(17)}px -apple-system, system-ui, sans-serif; direction: ltr; } @@ -260,7 +269,7 @@ function frameHtml({ raw, caption, rtl, tabs }) {
-
+ ${island ? '
' : ''} ${tabBar}
` @@ -285,21 +294,31 @@ async function frames(locale) { ? ['sites', 'new', 'settings'].map((k, j) => ({ label: msgs[`tab.${k}`], icon: TAB_ICONS[j] })) : null const tabsOrdered = tabs && rtl ? [...tabs] : tabs // dir=rtl on mirrors the flex row - const html = join(out, `frame-${name}.html`) - writeFileSync(html, frameHtml({ raw: pathToFileURL(raw).href, caption: m.captions[i], rtl, tabs: tabsOrdered })) - const png = join(out, `${String(i + 1).padStart(2, '0')}-${name}.png`) - await new Promise((res, rej) => { - const p = spawn(CHROME, ['--headless=new', '--hide-scrollbars', '--allow-file-access-from-files', - '--force-device-scale-factor=1', '--window-size=1290,2796', `--screenshot=${png}`, pathToFileURL(html).href], { stdio: 'ignore' }) - p.on('exit', (c) => (c === 0 ? res() : rej(new Error(`frame render failed: ${png}`)))) - }) + // App Store images in /, Google Play images in /play/. + for (const kind of ['appstore', 'play']) { + const dir = kind === 'play' ? join(out, 'play') : out + mkdirSync(dir, { recursive: true }) + const html = join(dir, `frame-${name}.html`) + writeFileSync(html, frameHtml({ raw: pathToFileURL(raw).href, caption: m.captions[i], rtl, tabs: tabsOrdered, kind })) + const png = join(dir, `${String(i + 1).padStart(2, '0')}-${name}.png`) + const { W, H } = FRAME[kind] + const render = () => new Promise((res) => { + const p = spawn(CHROME, ['--headless=new', '--hide-scrollbars', '--allow-file-access-from-files', + '--force-device-scale-factor=1', `--window-size=${W},${H}`, `--screenshot=${png}`, pathToFileURL(html).href], { stdio: 'ignore' }) + p.on('exit', (c) => res(c === 0)) + }) + let ok = false + for (let attempt = 0; attempt < 3 && !ok; attempt++) ok = await render() // headless Chrome occasionally exits non-zero + if (!ok) throw new Error(`frame render failed: ${png}`) + } } } +// FRAMES_ONLY=1 re-frames existing raw-*.png without re-running the app. let port = 9400 for (const locale of locales) { process.stdout.write(`${locale}: screens… `) - await rawScreens(locale, port++) + if (!process.env.FRAMES_ONLY) await rawScreens(locale, port++) process.stdout.write('frames… ') await frames(locale) console.log('done') diff --git a/store/metadata.json b/store/metadata.json index 7877bc5..4c232e6 100644 --- a/store/metadata.json +++ b/store/metadata.json @@ -1,10 +1,12 @@ { - "_comment": "App Store listing per App Store Connect locale. Limits: subtitle 30, keywords 100, promotionalText 170, description 4000 characters. 'captions' are the screenshot headlines (welcome, capture, nina, pano, export, sites); 'sites' are the demo site names in the screenshots.", + "_comment": "App Store listing per App Store Connect locale. Limits: subtitle 30, keywords 100, promotionalText 170, description 4000 characters. 'captions' are the screenshot headlines (welcome, capture, nina, pano, export, sites); 'sites' are the demo site names in the screenshots. 'playShortDescription' is the Google Play short description (80 characters); Play reuses 'description' as the full description. 'releaseNotes' is the Google Play \"What's new\" text of the next upload (500 characters).", "en-US": { "app": "en", "subtitle": "Horizon for NINA & Stellarium", "keywords": "horizon,astrophotography,telescope,obstruction,tree,hrz,landscape,astronomy,observatory,mount,sky", "promotionalText": "Turn once around your telescope and get a custom horizon for N.I.N.A. and a Stellarium landscape. No tripod, no tape measure, no guesswork.", + "playShortDescription": "Your horizon in one turn: custom horizon for N.I.N.A., Stellarium landscape", + "releaseNotes": "First release of SkyContour: trace your horizon in one turn and export it as a N.I.N.A. custom horizon (.hrz) and a Stellarium landscape.", "description": "SkyContour maps the trees, rooftops and hills around your telescope and turns them into an artificial horizon your astronomy software understands.\n\nStand where your telescope stands, hold your phone upright and turn once around. SkyContour takes the photos automatically, stitches them into a 360° panorama and finds the edge between sky and obstruction.\n\nSurvey in daylight or at dusk: the app needs a bright sky to find the edge.\n\nWHAT YOU GET\n• N.I.N.A. custom horizon (.hrz) with an adjustable safety margin, so targets stay clear of tree tips\n• Stellarium landscape: a 360° photo panorama with transparent sky, or just the outline\n• Your site's location written into the Stellarium landscape\n\nMADE FOR THE FIELD\n• Guided capture: a target dot shows where to point next, and frames are taken when the phone is steady\n• Review the horizon as a chart and as a panorama, and paint sky or ground with your finger where branches or wires fool the detection\n• North offset to correct the compass\n• One-time camera field-of-view calibration for accurate stitching\n• Import an existing .hrz file\n• Dark interface for use next to the telescope at dusk\n• Works offline. Your photos and locations stay on your phone; nothing is uploaded.\n\nShare or save the files, then load the .hrz in N.I.N.A. (Options › General › Astrometry › Custom Horizon) or install the .zip in Stellarium (Sky and viewing options › Landscape).", "captions": [ "Your horizon, traced in one turn", @@ -24,6 +26,8 @@ "subtitle": "Horizonte para NINA/Stellarium", "keywords": "horizonte,astrofotografía,telescopio,obstáculo,árbol,hrz,paisaje,astronomía,observatorio,cielo", "promotionalText": "Da una vuelta alrededor de tu telescopio y obtén un horizonte personalizado para N.I.N.A. y un paisaje de Stellarium. Sin trípode, sin cinta métrica, sin conjeturas.", + "playShortDescription": "Traza tu horizonte en una vuelta: horizonte para N.I.N.A. y paisaje Stellarium", + "releaseNotes": "Primera versión de SkyContour: traza tu horizonte en una vuelta y expórtalo como horizonte personalizado de N.I.N.A. (.hrz) y paisaje de Stellarium.", "description": "SkyContour registra los árboles, tejados y colinas alrededor de tu telescopio y los convierte en un horizonte artificial que tu software de astronomía entiende.\n\nColócate donde está tu telescopio, sujeta el teléfono en vertical y gira una vuelta completa. SkyContour toma las fotos automáticamente, las une en un panorama de 360° y encuentra el borde entre el cielo y los obstáculos.\n\nHaz la medición de día o al atardecer: la app necesita un cielo claro para encontrar el borde.\n\nLO QUE OBTIENES\n• Horizonte personalizado de N.I.N.A. (.hrz) con margen de seguridad ajustable, para que los objetivos queden lejos de las copas de los árboles\n• Paisaje de Stellarium: un panorama fotográfico de 360° con cielo transparente, o solo el contorno\n• La ubicación de tu lugar, guardada en el paisaje de Stellarium\n\nPENSADA PARA EL CAMPO\n• Captura guiada: un punto indica hacia dónde apuntar y las fotos se toman cuando el teléfono está quieto\n• Revisa el horizonte como gráfico y como panorama, y pinta cielo o suelo con el dedo donde las ramas o los cables confundan la detección\n• Desfase del norte para corregir la brújula\n• Calibración única del campo de visión de la cámara para una unión precisa\n• Importa un archivo .hrz existente\n• Interfaz oscura para usarla junto al telescopio al anochecer\n• Funciona sin conexión. Tus fotos y ubicaciones se quedan en tu teléfono; no se sube nada.\n\nComparte o guarda los archivos y carga el .hrz en N.I.N.A. (Options › General › Astrometry › Custom Horizon) o instala el .zip en Stellarium (Opciones de cielo y visualización › Paisaje).", "captions": [ "Tu horizonte, trazado en una vuelta", @@ -43,6 +47,8 @@ "subtitle": "أفق لـ NINA و Stellarium", "keywords": "أفق,تصوير فلكي,تلسكوب,عوائق,أشجار,hrz,فلك,مرصد,سماء,بانوراما", "promotionalText": "استدر دورة واحدة حول تلسكوبك واحصل على أفق مخصّص لـ N.I.N.A. ومشهد لـ Stellarium. بلا حامل ثلاثي، بلا شريط قياس، بلا تخمين.", + "playShortDescription": "ارسم أفقك في دورة واحدة: أفق مخصّص لـ N.I.N.A. ومشهد لـ Stellarium", + "releaseNotes": "الإصدار الأول من SkyContour: ارسم أفقك في دورة واحدة وصدّره كأفق مخصّص لـ N.I.N.A. (‎.hrz) ومشهد لـ Stellarium.", "description": "يرسم SkyContour الأشجار وأسطح المنازل والتلال حول تلسكوبك ويحوّلها إلى أفق اصطناعي يفهمه برنامج الفلك لديك.\n\nقف حيث يقف تلسكوبك، وأمسك الهاتف قائمًا، واستدر دورة كاملة. يلتقط SkyContour الصور تلقائيًا، ويدمجها في بانوراما بزاوية 360°، ويكتشف الحافة بين السماء والعوائق.\n\nقِس في ضوء النهار أو عند الغسق: يحتاج التطبيق إلى سماء ساطعة ليجد الحد.\n\nما تحصل عليه\n• أفق مخصّص لـ N.I.N.A. (ملف ‎.hrz) مع هامش أمان قابل للتعديل لإبقاء الأهداف بعيدة عن قمم الأشجار\n• مشهد Stellarium: بانوراما صور بزاوية 360° مع سماء شفافة، أو المخطط فقط\n• موقع مكان الرصد مكتوب في مشهد Stellarium\n\nمصمَّم للعمل الميداني\n• تصوير موجَّه: نقطة توضّح أين توجّه الهاتف، وتُلتقط الصور عندما يكون الهاتف ثابتًا\n• راجع الأفق كمخطط وكبانوراما، ولوّن السماء أو الأرض بإصبعك حيث تُربك الأغصان أو الأسلاك الاكتشاف\n• إزاحة الشمال لتصحيح البوصلة\n• معايرة لمرة واحدة لمجال رؤية الكاميرا لدمج دقيق\n• استيراد ملف ‎.hrz موجود\n• واجهة داكنة للاستخدام بجانب التلسكوب عند الغسق\n• يعمل دون اتصال. تبقى صورك ومواقعك على هاتفك، ولا يُرفع أي شيء.\n\nشارك الملفات أو احفظها، ثم حمّل ملف ‎.hrz في N.I.N.A. ‏(Options › General › Astrometry › Custom Horizon) أو ثبّت ملف ‎.zip في Stellarium ‏(خيارات السماء والعرض › المشهد).", "captions": [ "أفقك، مرسوم في دورة واحدة", @@ -62,6 +68,8 @@ "subtitle": "Horizont für NINA & Stellarium", "keywords": "Horizont,Astrofotografie,Teleskop,Hindernis,Baum,hrz,Landschaft,Astronomie,Sternwarte,Himmel", "promotionalText": "Einmal ums Teleskop drehen und du hast einen Custom Horizon für N.I.N.A. und eine Stellarium-Landschaft. Ohne Stativ, ohne Maßband, ohne Raten.", + "playShortDescription": "Horizont in einer Drehung: Custom Horizon für N.I.N.A., Stellarium-Landschaft", + "releaseNotes": "Erste Version von SkyContour: Horizont in einer Drehung erfassen und als N.I.N.A. Custom Horizon (.hrz) und Stellarium-Landschaft exportieren.", "description": "SkyContour erfasst die Bäume, Dächer und Hügel rund um dein Teleskop und macht daraus einen künstlichen Horizont, den deine Astronomie-Software versteht.\n\nStell dich dorthin, wo dein Teleskop steht, halte das Telefon aufrecht und dreh dich einmal im Kreis. SkyContour nimmt die Fotos automatisch auf, setzt sie zu einem 360°-Panorama zusammen und findet die Kante zwischen Himmel und Hindernis.\n\nMiss bei Tageslicht oder in der Dämmerung: Die App braucht einen hellen Himmel, um die Kante zu finden.\n\nDAS BEKOMMST DU\n• N.I.N.A. Custom Horizon (.hrz) mit einstellbarem Sicherheitsabstand, damit Ziele nicht an Baumspitzen hängen bleiben\n• Stellarium-Landschaft: ein 360°-Fotopanorama mit transparentem Himmel oder nur der Umriss\n• Die Position deines Standorts in der Stellarium-Landschaft\n\nGEMACHT FÜR DRAUSSEN\n• Geführte Aufnahme: ein Punkt zeigt, wohin als Nächstes, und die Bilder entstehen, sobald das Telefon ruhig ist\n• Prüfe den Horizont als Diagramm und als Panorama und male Himmel oder Boden mit dem Finger, wo Äste oder Leitungen die Erkennung täuschen\n• Nordversatz zur Korrektur des Kompasses\n• Einmalige Kalibrierung des Kamera-Bildwinkels für genaues Zusammensetzen\n• Import vorhandener .hrz-Dateien\n• Dunkle Oberfläche für den Einsatz am Teleskop in der Dämmerung\n• Funktioniert offline. Deine Fotos und Standorte bleiben auf deinem Telefon; nichts wird hochgeladen.\n\nTeile oder speichere die Dateien und lade die .hrz in N.I.N.A. (Options › General › Astrometry › Custom Horizon) oder installiere die .zip in Stellarium (Himmels- und Ansichtsoptionen › Landschaft).", "captions": [ "Dein Horizont, mit einer Drehung erfasst", @@ -81,6 +89,8 @@ "subtitle": "Horizont: NINA és Stellarium", "keywords": "horizont,asztrofotó,távcső,akadály,fa,hrz,tájkép,csillagászat,obszervatórium,égbolt,mechanika", "promotionalText": "Fordulj körbe egyszer a távcsöved mellett, és kész az egyéni horizont a N.I.N.A.-hoz meg a Stellarium-tájkép. Állvány, mérőszalag és találgatás nélkül.", + "playShortDescription": "Egy körbefordulással kész a horizont: N.I.N.A.-horizont és Stellarium-tájkép", + "releaseNotes": "A SkyContour első kiadása: egy körbefordulással felveheted a horizontot, és exportálhatod N.I.N.A.-horizontként (.hrz) és Stellarium-tájképként.", "description": "A SkyContour felméri a távcsöved körüli fákat, háztetőket és dombokat, és olyan mesterséges horizontot készít belőlük, amit a csillagászati szoftvered megért.\n\nÁllj oda, ahol a távcsöved áll, tartsd a telefont függőlegesen, és fordulj körbe egyszer. A SkyContour magától készíti a képeket, 360°-os panorámává fűzi őket, és megtalálja a határt az ég és az akadályok között.\n\nNappal vagy szürkületben mérj: az appnak világos égre van szüksége, hogy megtalálja a határt.\n\nAMIT KAPSZ\n• N.I.N.A. egyéni horizont (.hrz) állítható biztonsági ráhagyással, hogy a célpontok távol maradjanak a fák csúcsától\n• Stellarium-tájkép: 360°-os fotópanoráma átlátszó éggel, vagy csak a körvonal\n• A helyszíned koordinátái a Stellarium-tájképben\n\nTEREPRE TERVEZVE\n• Vezetett felvétel: egy pont mutatja, merre célozz, és a kép akkor készül el, amikor a telefon nyugalomban van\n• Nézd át a horizontot diagramként és panorámaként, és fesd át ujjal az eget vagy a talajt, ahol ágak vagy vezetékek megtévesztik a felismerést\n• Észak-eltolás az iránytű javítására\n• A kamera látószögének egyszeri kalibrálása a pontos illesztéshez\n• Meglévő .hrz fájl importálása\n• Sötét felület a távcső melletti használathoz szürkületben\n• Offline is működik. A fotóid és helyszíneid a telefonodon maradnak, semmi nem kerül feltöltésre.\n\nOszd meg vagy mentsd el a fájlokat, majd töltsd be a .hrz-t a N.I.N.A.-ba (Options › General › Astrometry › Custom Horizon), vagy telepítsd a .zip-et a Stellariumban (Égbolt és nézet beállításai › Tájkép).", "captions": [ "A horizontod egyetlen fordulattal", @@ -100,6 +110,8 @@ "subtitle": "Horyzont dla NINA i Stellarium", "keywords": "horyzont,astrofotografia,teleskop,przeszkoda,drzewa,hrz,krajobraz,astronomia,obserwatorium,niebo", "promotionalText": "Obróć się raz wokół teleskopu, a dostaniesz własny horyzont dla N.I.N.A. i krajobraz Stellarium. Bez statywu, bez miarki, bez zgadywania.", + "playShortDescription": "Horyzont w jeden obrót: własny horyzont dla N.I.N.A. i krajobraz Stellarium", + "releaseNotes": "Pierwsza wersja SkyContour: zmierz horyzont w jeden obrót i wyeksportuj go jako własny horyzont N.I.N.A. (.hrz) oraz krajobraz Stellarium.", "description": "SkyContour odwzorowuje drzewa, dachy i wzgórza wokół twojego teleskopu i zamienia je w sztuczny horyzont, który rozumie twoje oprogramowanie astronomiczne.\n\nStań tam, gdzie stoi teleskop, trzymaj telefon pionowo i obróć się raz dookoła. SkyContour sam robi zdjęcia, łączy je w panoramę 360° i znajduje granicę między niebem a przeszkodami.\n\nMierz za dnia lub o zmierzchu: aplikacja potrzebuje jasnego nieba, aby znaleźć krawędź.\n\nCO OTRZYMUJESZ\n• Własny horyzont N.I.N.A. (.hrz) z regulowanym marginesem bezpieczeństwa, aby cele omijały wierzchołki drzew\n• Krajobraz Stellarium: panorama zdjęć 360° z przezroczystym niebem albo sam kontur\n• Lokalizacja miejsca zapisana w krajobrazie Stellarium\n\nSTWORZONY DO PRACY W TERENIE\n• Prowadzone nagrywanie: punkt pokazuje, gdzie celować, a zdjęcie powstaje, gdy telefon jest nieruchomy\n• Przeglądaj horyzont jako wykres i jako panoramę, a niebo lub grunt maluj palcem tam, gdzie gałęzie lub przewody mylą wykrywanie\n• Przesunięcie północy do korekty kompasu\n• Jednorazowa kalibracja pola widzenia aparatu dla dokładnego łączenia\n• Import istniejącego pliku .hrz\n• Ciemny interfejs do pracy przy teleskopie o zmierzchu\n• Działa offline. Zdjęcia i lokalizacje zostają w telefonie; nic nie jest wysyłane.\n\nUdostępnij lub zapisz pliki, a potem wczytaj .hrz w N.I.N.A. (Options › General › Astrometry › Custom Horizon) lub zainstaluj .zip w Stellarium (Opcje nieba i widoku › Krajobraz).", "captions": [ "Twój horyzont w jednym obrocie", @@ -119,6 +131,8 @@ "subtitle": "Horizon pour NINA & Stellarium", "keywords": "horizon,astrophotographie,télescope,obstacle,arbre,hrz,paysage,astronomie,observatoire,ciel", "promotionalText": "Faites un tour autour de votre télescope et obtenez un horizon personnalisé pour N.I.N.A. et un paysage Stellarium. Sans trépied, sans mètre, sans approximation.", + "playShortDescription": "Votre horizon en un tour : horizon personnalisé N.I.N.A., paysage Stellarium", + "releaseNotes": "Première version de SkyContour : relevez votre horizon en un tour et exportez-le en horizon personnalisé N.I.N.A. (.hrz) et en paysage Stellarium.", "description": "SkyContour relève les arbres, les toits et les collines autour de votre télescope et en fait un horizon artificiel que votre logiciel d’astronomie comprend.\n\nPlacez-vous à l’emplacement du télescope, tenez le téléphone droit et faites un tour complet. SkyContour prend les photos automatiquement, les assemble en un panorama à 360° et trouve la limite entre le ciel et les obstacles.\n\nFaites le relevé de jour ou au crépuscule : l’app a besoin d’un ciel clair pour trouver la limite.\n\nCE QUE VOUS OBTENEZ\n• Horizon personnalisé N.I.N.A. (.hrz) avec une marge de sécurité réglable, pour que les cibles évitent la cime des arbres\n• Paysage Stellarium : un panorama photo à 360° avec ciel transparent, ou seulement le contour\n• La position de votre site inscrite dans le paysage Stellarium\n\nCONÇU POUR LE TERRAIN\n• Capture guidée : un point indique où viser, et la photo est prise quand le téléphone est stable\n• Vérifiez l’horizon en graphique et en panorama, et peignez le ciel ou le sol du doigt là où des branches ou des câbles trompent la détection\n• Décalage du nord pour corriger la boussole\n• Calibration unique du champ de vision de la caméra pour un assemblage précis\n• Import d’un fichier .hrz existant\n• Interface sombre pour l’utiliser près du télescope au crépuscule\n• Fonctionne hors ligne. Vos photos et positions restent sur votre téléphone ; rien n’est envoyé.\n\nPartagez ou enregistrez les fichiers, puis chargez le .hrz dans N.I.N.A. (Options › General › Astrometry › Custom Horizon) ou installez le .zip dans Stellarium (Options du ciel et de la vue › Paysage).", "captions": [ "Votre horizon, tracé en un tour", @@ -138,6 +152,8 @@ "subtitle": "Orizzonte NINA e Stellarium", "keywords": "orizzonte,astrofotografia,telescopio,ostacolo,alberi,hrz,paesaggio,astronomia,osservatorio,cielo", "promotionalText": "Fai un giro intorno al telescopio e ottieni un orizzonte personalizzato per N.I.N.A. e un paesaggio per Stellarium. Senza treppiede, senza metro, senza tentativi.", + "playShortDescription": "Il tuo orizzonte in un giro: orizzonte per N.I.N.A. e paesaggio Stellarium", + "releaseNotes": "Prima versione di SkyContour: rileva il tuo orizzonte in un giro ed esportalo come orizzonte personalizzato N.I.N.A. (.hrz) e paesaggio Stellarium.", "description": "SkyContour rileva gli alberi, i tetti e le colline intorno al tuo telescopio e li trasforma in un orizzonte artificiale che il tuo software di astronomia comprende.\n\nMettiti dove si trova il telescopio, tieni il telefono in verticale e fai un giro completo. SkyContour scatta le foto automaticamente, le unisce in un panorama a 360° e trova il bordo tra cielo e ostacoli.\n\nFai il rilievo di giorno o al crepuscolo: l’app ha bisogno di un cielo chiaro per trovare il confine.\n\nCOSA OTTIENI\n• Orizzonte personalizzato N.I.N.A. (.hrz) con margine di sicurezza regolabile, così i bersagli restano lontani dalle cime degli alberi\n• Paesaggio Stellarium: un panorama fotografico a 360° con cielo trasparente, oppure solo il contorno\n• La posizione del tuo luogo scritta nel paesaggio di Stellarium\n\nPENSATA PER IL CAMPO\n• Ripresa guidata: un punto indica dove puntare e la foto viene scattata quando il telefono è fermo\n• Controlla l’orizzonte come grafico e come panorama, e dipingi cielo o suolo con il dito dove rami o cavi ingannano il rilevamento\n• Scostamento del nord per correggere la bussola\n• Calibrazione una tantum del campo visivo della fotocamera per un’unione precisa\n• Importazione di un file .hrz esistente\n• Interfaccia scura per l’uso accanto al telescopio al crepuscolo\n• Funziona offline. Foto e posizioni restano sul telefono; non viene caricato nulla.\n\nCondividi o salva i file, poi carica il .hrz in N.I.N.A. (Options › General › Astrometry › Custom Horizon) o installa lo .zip in Stellarium (Opzioni cielo e visualizzazione › Paesaggio).", "captions": [ "Il tuo orizzonte, tracciato in un giro", @@ -157,6 +173,8 @@ "subtitle": "Horizont pre NINA a Stellarium", "keywords": "horizont,astrofotografia,ďalekohľad,prekážka,stromy,hrz,krajina,astronómia,observatórium,obloha", "promotionalText": "Otoč sa raz okolo ďalekohľadu a získaš vlastný horizont pre N.I.N.A. aj krajinu pre Stellarium. Bez statívu, bez metra, bez hádania.", + "playShortDescription": "Horizont na jedno otočenie: vlastný horizont pre N.I.N.A. a krajina Stellarium", + "releaseNotes": "Prvé vydanie SkyContour: zmeraj horizont jedným otočením a exportuj ho ako vlastný horizont pre N.I.N.A. (.hrz) a krajinu pre Stellarium.", "description": "SkyContour zmapuje stromy, strechy a kopce okolo tvojho ďalekohľadu a premení ich na umelý horizont, ktorému rozumie tvoj astronomický softvér.\n\nPostav sa tam, kde stojí ďalekohľad, drž telefón zvisle a raz sa otoč dokola. SkyContour sám nasníma fotky, spojí ich do 360° panorámy a nájde hranicu medzi oblohou a prekážkami.\n\nMeraj cez deň alebo za súmraku: aplikácia potrebuje svetlú oblohu, aby našla hranicu.\n\nČO ZÍSKAŠ\n• Vlastný horizont N.I.N.A. (.hrz) s nastaviteľnou bezpečnostnou rezervou, aby sa ciele vyhli vrcholom stromov\n• Krajina Stellarium: 360° fotografická panoráma s priehľadnou oblohou alebo len obrys\n• Poloha miesta zapísaná do krajiny Stellarium\n\nNAVRHNUTÝ DO TERÉNU\n• Vedené snímanie: bod ukazuje, kam mieriť, a snímka sa urobí, keď je telefón v pokoji\n• Skontroluj horizont ako graf aj ako panorámu a prstom domaľuj oblohu alebo terén tam, kde konáre či drôty pomýlia rozpoznávanie\n• Posun severu na opravu kompasu\n• Jednorazová kalibrácia zorného poľa kamery pre presné spájanie\n• Import existujúceho súboru .hrz\n• Tmavé rozhranie na použitie pri ďalekohľade za súmraku\n• Funguje offline. Fotky a polohy zostávajú v telefóne; nič sa neodosiela.\n\nZdieľaj alebo ulož súbory a potom načítaj .hrz v N.I.N.A. (Options › General › Astrometry › Custom Horizon) alebo nainštaluj .zip v Stellariu (Možnosti oblohy a zobrazenia › Krajina).", "captions": [ "Tvoj horizont jedným otočením", diff --git a/store/upload_play_listing.py b/store/upload_play_listing.py new file mode 100644 index 0000000..3298bbb --- /dev/null +++ b/store/upload_play_listing.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Upload the Google Play store listing (texts + graphics) from store/metadata.json. + + python3 store/upload_play_listing.py [--locales en-US hu ...] [--texts-only] + [--website URL] [--email ADDRESS] + + is the folder used by make_screenshots.mjs and make_play_graphics.py: +//play/0N-*.png (1440×2560 phone screenshots), +//play/feature.png (1024×500) and /play-icon.png (512×512). +Re-running replaces the texts and images of the uploaded languages. +""" +import argparse +import json +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'scripts')) +from gplay_api import PLAY_LANG, UPLOAD, Gplay # noqa: E402 + +HERE = Path(__file__).resolve().parent +TITLE = 'SkyContour' + + +def upload_image(g, edit, lang, kind, path): + g.call('POST', f'/edits/{edit}/listings/{lang}/{kind}?uploadType=media', data=path.read_bytes(), + content_type='image/png', base=UPLOAD) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('work') + ap.add_argument('--locales', nargs='*') + ap.add_argument('--texts-only', action='store_true') + ap.add_argument('--website', default='https://sagifer.github.io/appdocuments/skycontour/support.html') + ap.add_argument('--email', default='sagiferdev@gmail.com', help='public contact address on the listing') + args = ap.parse_args() + + meta = json.loads((HERE / 'metadata.json').read_text()) + locales = args.locales or [k for k in meta if not k.startswith('_')] + work = Path(args.work) + if not args.texts_only: # check every file before touching the listing + need = [work / 'play-icon.png'] + [work / l / 'play/feature.png' for l in locales] + missing = [str(p) for p in need if not p.exists()] + missing += [l for l in locales if len(sorted((work / l / 'play').glob('0*.png'))) < 2] + if missing: + sys.exit(f'missing graphics: {missing}') + + g = Gplay() + edit = g.edit() + try: + g.call('PATCH', f'/edits/{edit}/details', + {'defaultLanguage': 'en-US', 'contactWebsite': args.website, 'contactEmail': args.email}) + for locale in locales: + m, lang = meta[locale], PLAY_LANG[locale] + g.call('PUT', f'/edits/{edit}/listings/{lang}', + {'language': lang, 'title': TITLE, + 'shortDescription': m['playShortDescription'], 'fullDescription': m['description']}) + line = f'{lang}: texts' + if not args.texts_only: + play = work / locale / 'play' + for kind in ('icon', 'featureGraphic', 'phoneScreenshots'): + g.call('DELETE', f'/edits/{edit}/listings/{lang}/{kind}') + upload_image(g, edit, lang, 'icon', work / 'play-icon.png') + upload_image(g, edit, lang, 'featureGraphic', play / 'feature.png') + shots = sorted(play.glob('0*.png')) + for s in shots: + upload_image(g, edit, lang, 'phoneScreenshots', s) + line += f', icon, feature graphic, {len(shots)} screenshots' + print(line) + g.commit(edit) + except BaseException: + g.discard(edit) + raise + print('committed') + + +if __name__ == '__main__': + main()