# -*- coding: utf-8 -*-
"""Compare CallingCode vs CountrySelect activities / intent extras."""
import re
import zipfile

APK = r"C:\Users\Administrator\Desktop\notiMessage\reverse\dumps\tng_base_scan.apk"


def near(data, needle, r=180, lim=12):
    out = []
    start = 0
    while len(out) < lim:
        i = data.find(needle, start)
        if i < 0:
            break
        chunk = re.sub(rb"[^\x20-\x7e]+", b".", data[max(0, i - r): i + len(needle) + r])
        out.append(chunk.decode("ascii", "ignore"))
        start = i + 1
    return out


def main():
    z = zipfile.ZipFile(APK)
    for dex in sorted(n for n in z.namelist() if n.endswith(".dex")):
        data = z.read(dex)
        if b"UserCountrySelectActivity" not in data and b"UserSearchCallingCodeActivity" not in data:
            continue
        print("\n====", dex, "====")
        for n in (b"UserCountrySelectActivity", b"AbsCountrySelectActivity",
                  b"newIntent", b"CallingListScreen"):
            if n in data:
                print("HAS", n.decode())
        for n in (b"UserSearchCallingCodeActivity", b"UserCountrySelectActivity"):
            if n not in data:
                continue
            print("--", n.decode(), "--")
            for c in near(data, n, 100, 6):
                if "Hilt_" in c and ".java" in c:
                    continue
                print(" ", c[:220])

    print("\n=== calling/country intent-like strings ===")
    seen = set()
    for dex in sorted(n for n in z.namelist() if n.endswith(".dex")):
        data = z.read(dex)
        if b"CallingCode" not in data and b"CountrySelect" not in data:
            continue
        for m in re.findall(
                rb"(?:EXTRA_|KEY_|arg_|ARG_)[A-Za-z0-9_]{2,40}|"
                rb"[A-Za-z0-9_]{0,15}(?:calling_code|CallingCode|country_code|CountryCode|countryList)[A-Za-z0-9_]{0,20}",
                data):
            s = m.decode("ascii", "ignore")
            if s not in seen and len(s) > 6:
                seen.add(s)
                print(" ", s)


if __name__ == "__main__":
    main()
