Skip to content

Native Android client for Spotify, built with Jetpack Compose

5.0 KB
Raw Blame
#!/usr/bin/env python3
"""Official Spotify UI strings, per locale, from an `aapt2 dump resources` of the APK.

usage:
  apkstrings.py DUMP find "English text"        -> resource names whose default value matches
  apkstrings.py DUMP export KEYS.txt RES_DIR    -> RES_DIR/values[-xx]/spotify_strings.xml
                                                 (+ spotify_plurals.xml for "plurals/" keys)
KEYS.txt: one official resource name per line (# comments allowed); plurals as "plurals/name".
"""
import re, sys, os
from xml.sax.saxutils import escape

def parse(path):
    strings, name = {}, None
    res_re = re.compile(r'^\s+resource 0x[0-9a-f]+ string/(\S+)')
    val_re = re.compile(r'^\s+\(([^)]*)\) "(.*)"\s*$')
    other_re = re.compile(r'^\s+resource 0x[0-9a-f]+ ')
    with open(path, encoding='utf-8', errors='replace') as f:
        for line in f:
            m = res_re.match(line)
            if m: name = m.group(1); strings.setdefault(name, {}); continue
            if other_re.match(line): name = None; continue
            if name:
                v = val_re.match(line)
                if v: strings[name].setdefault(v.group(1), v.group(2))
    return strings

def parse_plurals(path):
    """plurals/name -> {config: {quantity: text}}"""
    out, name, cfg = {}, None, None
    res_re = re.compile(r'^\s+resource 0x[0-9a-f]+ plurals/(\S+)')
    cfg_re = re.compile(r'^\s+\(([^)]*)\) \(plurals\)')
    item_re = re.compile(r'^\s+(zero|one|two|few|many|other)="(.*)"\s*$')
    other_re = re.compile(r'^\s+resource 0x[0-9a-f]+ ')
    with open(path, encoding='utf-8', errors='replace') as f:
        for line in f:
            m = res_re.match(line)
            if m: name = m.group(1); out.setdefault(name, {}); cfg = None; continue
            if other_re.match(line): name = None; continue
            if not name: continue
            c = cfg_re.match(line)
            if c: cfg = c.group(1); out[name].setdefault(cfg, {}); continue
            i = item_re.match(line)
            if i and cfg is not None: out[name][cfg].setdefault(i.group(1), i.group(2))
    return out

def android_qualifier(cfg):
    # aapt2 configs: "" default, "fr", "pt-rBR", "b+sr+Latn", "zh-rTW"...
    if cfg == '': return 'values'
    if not re.fullmatch(r'[a-z]{2,3}(-r[A-Z]{2})?|b\+[A-Za-z0-9+]+', cfg): return None
    return 'values-' + cfg

def xml_value(v):
    v = v.replace('\\"', '"')
    v = escape(v).replace("'", "\\'").replace('"', '\\"')
    return v

if __name__ == '__main__':
    dump, cmd = sys.argv[1], sys.argv[2]
    s = parse(dump)
    if cmd == 'find':
        q = sys.argv[3].lower()
        for k, loc in s.items():
            d = loc.get('', '')
            if q == d.lower() or (len(sys.argv) > 4 and q in d.lower()):
                print(k, '=', d, '|fr:', loc.get('fr', ''))
    elif cmd == 'export':
        allkeys = [l.split('#')[0].strip() for l in open(sys.argv[3]) if l.split('#')[0].strip()]
        keys = [k for k in allkeys if not k.startswith('plurals/')]
        pkeys = [k[len('plurals/'):] for k in allkeys if k.startswith('plurals/')]
        if pkeys:
            pl = parse_plurals(dump); pout = {}
            for k in pkeys:
                if k not in pl: print('missing plurals', k, file=sys.stderr); continue
                for cfg, items in pl[k].items():
                    q = android_qualifier(cfg)
                    if q: pout.setdefault(q, {})[k] = items
            for q, kv in pout.items():
                d = os.path.join(sys.argv[4], q); os.makedirs(d, exist_ok=True)
                with open(os.path.join(d, 'spotify_plurals.xml'), 'w', encoding='utf-8') as f:
                    f.write('<?xml version="1.0" encoding="utf-8"?>\n<!-- Generated by tools/apkstrings.py from the official app (labels only). -->\n<resources>\n')
                    for k in pkeys:
                        if k not in kv: continue
                        f.write(f'    <plurals name="{k}">\n')
                        for qty in ('zero', 'one', 'two', 'few', 'many', 'other'):
                            if qty in kv[k]: f.write(f'        <item quantity="{qty}">{xml_value(kv[k][qty])}</item>\n')
                        f.write('    </plurals>\n')
                    f.write('</resources>\n')
        out = {}
        for k in keys:
            if k not in s: print('missing', k, file=sys.stderr); continue
            for cfg, v in s[k].items():
                q = android_qualifier(cfg)
                if q: out.setdefault(q, {})[k] = v
        for q, kv in out.items():
            d = os.path.join(sys.argv[4], q); os.makedirs(d, exist_ok=True)
            with open(os.path.join(d, 'spotify_strings.xml'), 'w', encoding='utf-8') as f:
                f.write('<?xml version="1.0" encoding="utf-8"?>\n<!-- Generated by tools/apkstrings.py from the official app (labels only). -->\n<resources>\n')
                for k in keys:
                    if k in kv: f.write(f'    <string name="{k}" formatted="false">{xml_value(kv[k])}</string>\n')
                f.write('</resources>\n')
        print(len(out), 'locales')