#!/usr/bin/env python3
"""
sms2db.py: shrink a huge SMS Backup & Restore file for Chat Analyzer
https://localscriptbox.com/tools/chat-analyzer

Reads one or more sms-XXXXXXXX.xml backups and writes a small .db file with only
the message text, times, who sent each message and whether it had a picture or video.
The pictures and videos themselves are skipped without being read, so a 5 GB backup
usually becomes a few megabytes in well under a minute. Drop the .db file into
Chat Analyzer and it opens in seconds, every time.

Nothing is uploaded anywhere. Only Python's standard library is used, so there's
nothing to pip install.

Usage:
    python sms2db.py sms-20250101.xml
    python sms2db.py backup1.xml backup2.xml -o all-my-texts.db
On Windows you can also drag the .xml file onto run-sms2db.bat.
"""
import os
import re
import sqlite3
import sys
import time

ME = "Me"
ATTR = re.compile(r'([\w:-]+)="([^"]*)"')
ENT = re.compile(r"&(#[xX][0-9a-fA-F]+|#\d+|amp|lt|gt|quot|apos);")
NAMED = {"amp": "&", "lt": "<", "gt": ">", "quot": '"', "apos": "'"}


def unent(v):
    """Undo XML escapes. SMS Backup & Restore writes emojis as two numbered codes
    (&#55357;&#56834;), so the halves are glued back together into the real emoji."""
    if "&" not in v:
        return v

    def rep(m):
        e = m.group(1)
        if e[0] == "#":
            n = int(e[2:], 16) if e[1] in "xX" else int(e[1:])
            return chr(n) if 0 < n <= 0x10FFFF else ""
        return NAMED[e]

    s = ENT.sub(rep, v)
    return s.encode("utf-16", "surrogatepass").decode("utf-16", "replace")


def attrs(raw):
    return {k: unent(v) for k, v in ATTR.findall(raw.decode("utf-8", "replace"))}


def norm_phone(a):
    d = re.sub(r"\D", "", a or "")
    return d[-10:] if len(d) >= 7 else (a or "").strip().lower()


def scan(path, on_sms, on_mms, progress):
    """Walk the file as raw bytes. Only the small tags are turned into text; the base64
    picture and video data inside <part data="..."> is jumped over without decoding."""
    CH = 1 << 23
    P_SMS, P_MMS, P_END, P_PART, P_ADDR, P_DATA = b"<sms ", b"<mms ", b"</mms>", b"<part ", b"<addr ", b' data="'
    buf, i, state, mm = b"", 0, 0, None
    with open(path, "rb") as f:
        while True:
            chunk = f.read(CH)
            eof = not chunk
            buf = buf[i:] + chunk
            i = 0
            nxt = {}

            def find(key, pat):
                v = nxt.get(key)
                if v is None or (v != -2 and v < i):
                    v = buf.find(pat, i)
                    v = -2 if v < 0 else v
                    nxt[key] = v
                return None if v == -2 else v

            while True:
                if state == 2:                       # inside data="...": base64 has no quotes
                    q = buf.find(b'"', i)
                    if q < 0:
                        i = len(buf)
                        break
                    i, state = q + 1, 1
                    continue
                if state == 1:                       # inside an <mms>
                    cands = [x for x in (find("part", P_PART), find("addr", P_ADDR), find("end", P_END)) if x is not None]
                    if not cands:
                        i = max(i, len(buf) - 8)
                        break
                    nx = min(cands)
                    if nx == nxt.get("end"):
                        on_mms(mm)
                        mm, state, i = None, 0, nx + len(P_END)
                        continue
                    gt = buf.find(b">", nx)
                    if nx == nxt.get("part"):
                        dd = buf.find(P_DATA, nx, gt if gt >= 0 else len(buf))
                        if dd >= 0:
                            mm["parts"].append(attrs(buf[nx:dd]))
                            i, state = dd + len(P_DATA), 2
                            continue
                    if gt < 0:
                        i = nx
                        break
                    (mm["parts"] if nx == nxt.get("part") else mm["addrs"]).append(attrs(buf[nx:gt + 1]))
                    i = gt + 1
                    continue
                s, m = find("sms", P_SMS), find("mms", P_MMS)
                if s is None and m is None:
                    i = max(i, len(buf) - 8)
                    break
                if m is None or (s is not None and s < m):
                    e = buf.find(b"/>", s)
                    if e < 0:
                        i = s
                        break
                    on_sms(attrs(buf[s:e]))
                    i = e + 2
                    continue
                gt = buf.find(b">", m)
                if gt < 0:
                    i = m
                    break
                mm = {"st": attrs(buf[m:gt + 1]), "parts": [], "addrs": []}
                i, state = gt + 1, 1
                if buf[gt - 1:gt] == b"/":
                    on_mms(mm)
                    mm, state = None, 0
            progress(f.tell())
            if eof:
                break


def convert(paths, out_path):
    threads = {}   # key -> {"title", "group", "msgs": [(t, sender, text, media)]}
    names = {}     # normalised number -> contact name
    total = sum(os.path.getsize(p) for p in paths)
    state = {"done": 0, "count": 0, "last": 0.0}
    started = time.time()

    def thread(key, title, group):
        t = threads.get(key)
        if t is None:
            t = threads[key] = {"title": title, "group": group, "msgs": []}
        elif title and (not t["title"] or re.fullmatch(r"\+?\d[\d\s-]*", t["title"])):
            t["title"] = title
        return t

    def on_sms(a):
        typ = a.get("type")
        if typ not in ("1", "2"):
            return
        addr, cn = a.get("address", ""), a.get("contact_name", "")
        has_name = cn and cn != "(Unknown)"
        key = norm_phone(addr)
        if has_name:
            names[key] = cn
        name = cn if has_name else addr
        body = a.get("body", "")
        thread(key, name, False)["msgs"].append((int(a.get("date") or 0), ME if typ == "2" else name, "" if body == "null" else body, 0))
        state["count"] += 1

    def on_mms(mm):
        a = mm["st"]
        box = a.get("msg_box")
        if box not in ("1", "2"):
            return
        addrs = [x.strip() for x in a.get("address", "").split("~") if x.strip()]
        cns = a.get("contact_name", "").split(", ")
        if len(cns) == len(addrs):
            for num, cn in zip(addrs, cns):
                if cn and cn != "(Unknown)":
                    names[norm_phone(num)] = cn
        text, media, sender = [], 0, ""
        for part in mm["parts"]:
            ct = part.get("ct", "")
            if ct == "text/plain":
                tx = part.get("text", "")
                if tx and tx != "null":
                    text.append(tx)
            elif ct.startswith(("image/", "video/", "audio/")):
                media = 1
        for ad in mm["addrs"]:
            if ad.get("type") == "137":
                sender = ad.get("address", "")
        # RCS group chats from Google Messages use one long id like xxxx@rcs.google.com instead of everyone's numbers
        rcs = len(addrs) == 1 and "@" in addrs[0]
        gname = a.get("contact_name", "")
        if rcs:
            key = addrs[0].lower()
            title = gname if gname and gname != "(Unknown)" and "@" not in gname else ""
        else:
            key = "+".join(sorted(norm_phone(x) for x in addrs))
            title = ", ".join(names.get(norm_phone(x), x) for x in addrs)
        t = thread(key, title, rcs or len(addrs) > 1)
        if rcs:
            t["rcs"] = True
            members = t.setdefault("members", {})
            for ad in mm["addrs"]:
                num = ad.get("address", "")
                if num and num != "insert-address-token" and "@" not in num:
                    members[norm_phone(num)] = num
        who = ME if box == "2" else (names.get(norm_phone(sender)) or sender or title or "Someone")
        t["msgs"].append((int(a.get("date") or 0), who, " ".join(text), media))
        state["count"] += 1

    for path in paths:
        def progress(pos):
            now = time.time()
            if now - state["last"] > 0.5:
                state["last"] = now
                pct = min(100, (state["done"] + pos) * 100 // max(1, total))
                print(f"\r  {state['count']:,} messages, {pct}% ...   ", end="", flush=True)
        scan(path, on_sms, on_mms, progress)
        state["done"] += os.path.getsize(path)

    count = state["count"]
    print(f"\r  {count:,} messages read in {time.time() - started:.0f} s. Writing {out_path} ...")
    if os.path.exists(out_path):
        os.remove(out_path)
    db = sqlite3.connect(out_path)
    db.executescript("""
        CREATE TABLE ca_info (key TEXT, value TEXT);
        CREATE TABLE ca_chats (id INTEGER PRIMARY KEY, title TEXT, source TEXT, is_group INTEGER);
        CREATE TABLE ca_messages (chat_id INTEGER, t INTEGER, sender TEXT, text TEXT, media INTEGER);
    """)
    db.executemany("INSERT INTO ca_info VALUES (?, ?)", [("format", "chat-analyzer-1"), ("made_by", "sms2db.py"), ("messages", str(count))])
    for cid, (key, t) in enumerate(threads.items(), start=1):
        if t.get("rcs") and (not t["title"] or "@" in t["title"]):
            sent = {m[1] for m in t["msgs"]}
            who = [n for n in (names.get(k) or raw for k, raw in t.get("members", {}).items()) if n in sent]
            t["title"] = (", ".join(who[:3]) + (f" + {len(who) - 3} more" if len(who) > 3 else "")) if who else "Group chat"
        solo_name = None if t["group"] else names.get(key)
        db.execute("INSERT INTO ca_chats VALUES (?, ?, ?, ?)", (cid, solo_name or t["title"] or key, "SMS backup", 1 if t["group"] else 0))
        db.executemany("INSERT INTO ca_messages VALUES (?, ?, ?, ?, ?)", [(cid, ts, (solo_name if solo_name and who != ME else who), text, media) for ts, who, text, media in t["msgs"]])
    db.commit()
    db.execute("VACUUM")
    db.close()
    print(f"Done: {len(threads):,} chats, {count:,} messages, {os.path.getsize(out_path) / 1e6:.1f} MB.")
    print("Now drop that .db file into Chat Analyzer: https://localscriptbox.com/tools/chat-analyzer")


def main(argv):
    try:
        sys.stdout.reconfigure(errors="replace")
    except Exception:
        pass
    args, out, i = [], None, 0
    while i < len(argv):
        if argv[i] in ("-o", "--out") and i + 1 < len(argv):
            out = argv[i + 1]
            i += 2
            continue
        args.append(argv[i])
        i += 1
    if not args:
        print(__doc__)
        return 1
    missing = [p for p in args if not os.path.isfile(p)]
    if missing:
        print("Can't find: " + ", ".join(missing))
        return 1
    convert(args, out or os.path.splitext(args[0])[0] + ".chat.db")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
