#!/usr/bin/env python3 """ SS14 Replay HTTP Range Extractor, Shared String Table Parser & JSONL Chat Decoder Extracts _replay/replay.yml, _replay/replay_final.yml, _replay/strings.dat, and ZStd-decompressed _replay/data_N.dat [int32 uncompressedSize + zstd block] chunks from any HTTP server supporting Range requests (e.g. https://replays.starlight.network/ or https://cdn.replays.iterator.systems/) without downloading the full 200-700 MB ZIP archive. Follows RobustToolbox's ReplayLoadManager.StreamHistory architecture: - _replay/replay.yml: engineVersion, buildForkId, buildForkVersion, startTick, typeHash, stringHash - _replay/strings.dat: streaming ZStd frame containing [varint count] + [varint len + UTF-8 bytes] string table - _replay/data_N.dat: [int32 uncompressedSize + zstd block] containing serialized (GameState, ReplayMessage) pairs - Emits JSONL records: {"tick", "t", "kind": "chat", "channel", "sender", "name", "message"} where t = round((tick - startTick) / 30.0, 2). """ import urllib.request import struct import zlib import ctypes import ctypes.util import json import re import sys def get_zip_entries(url): req = urllib.request.Request(url, method="HEAD") with urllib.request.urlopen(req) as resp: size = int(resp.headers["Content-Length"]) tail_size = min(size, 262144) req = urllib.request.Request(url, headers={"Range": f"bytes={size - tail_size}-{size - 1}"}) with urllib.request.urlopen(req) as resp: tail = resp.read() eocd_pos = tail.rfind(b"PK\x05\x06") _, _, _, _, total_entries, cd_size, cd_offset, _ = struct.unpack("<4sHHHHIIH", tail[eocd_pos:eocd_pos+22]) req = urllib.request.Request(url, headers={"Range": f"bytes={cd_offset}-{cd_offset + cd_size - 1}"}) with urllib.request.urlopen(req) as resp: cd = resp.read() pos = 0 entries = {} while pos < len(cd): if cd[pos:pos+4] != b"PK\x01\x02": break sig, ver_made, ver_need, flags, method, mod_time, mod_date, crc, comp_size, uncomp_size, fn_len, extra_len, comment_len, disk_start, int_attr, ext_attr, local_offset = struct.unpack_from("<4sHHHHHHIIIHHHHHII", cd, pos) fn = cd[pos+46:pos+46+fn_len].decode("utf-8", errors="replace") entries[fn] = (method, comp_size, uncomp_size, local_offset) pos += 46 + fn_len + extra_len + comment_len return entries def fetch_entry(url, entries, target): method, comp_size, uncomp_size, offset = entries[target] req = urllib.request.Request(url, headers={"Range": f"bytes={offset}-{offset + 128 + comp_size}"}) with urllib.request.urlopen(req) as resp: chunk = resp.read() _, _, _, _, _, _, _, _, _, fn_l, ex_l = struct.unpack_from("<4sHHHHHIIIHH", chunk, 0) data_start = 30 + fn_l + ex_l comp_data = chunk[data_start:data_start+comp_size] return zlib.decompress(comp_data, -15) if method == 8 else comp_data MAX_UNCOMP_BYTES = 64 * 1024 * 1024 def _get_zstd(): libpath = ctypes.util.find_library("zstd") or "libzstd.so.1" zstd = ctypes.CDLL(libpath) zstd.ZSTD_decompress.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_void_p, ctypes.c_size_t] zstd.ZSTD_decompress.restype = ctypes.c_size_t zstd.ZSTD_isError.argtypes = [ctypes.c_size_t] zstd.ZSTD_isError.restype = ctypes.c_uint zstd.ZSTD_getErrorName.argtypes = [ctypes.c_size_t] zstd.ZSTD_getErrorName.restype = ctypes.c_char_p return zstd def decompress_zstd_chunk(raw_chunk, max_uncomp=MAX_UNCOMP_BYTES): """Decompresses a [int32 uncompressedSize + zstd block] data_N.dat payload with ZSTD_isError & bounds checks.""" if len(raw_chunk) < 5: raise ValueError(f"Chunk too short ({len(raw_chunk)} bytes)") zstd = _get_zstd() uncomp_len = struct.unpack_from(" max_uncomp: raise ValueError(f"Declared uncompressed size {uncomp_len} out of bounds (1..{max_uncomp})") dst = ctypes.create_string_buffer(uncomp_len) res = zstd.ZSTD_decompress(dst, uncomp_len, raw_chunk[4:], len(raw_chunk) - 4) if zstd.ZSTD_isError(res): err_msg = (zstd.ZSTD_getErrorName(res) or b"unknown zstd error").decode("utf-8", errors="replace") raise RuntimeError(f"ZSTD_decompress failed: {err_msg} (code {res})") return dst.raw[:res] def read_varint(buf, pos): shift = 0 val = 0 while True: b = buf[pos] pos += 1 val |= (b & 0x7f) << shift if (b & 0x80) == 0: return val, pos shift += 7 def parse_strings_dat(raw_strings_dat, max_uncomp=16 * 1024 * 1024): """Decompresses _replay/strings.dat (streaming ZStd frame at offset 0) and parses the 7-bit varint string table.""" if not raw_strings_dat: raise ValueError("Empty strings.dat payload") if max_uncomp <= 0 or max_uncomp > MAX_UNCOMP_BYTES: raise ValueError(f"max_uncomp {max_uncomp} out of bounds") zstd = _get_zstd() dst = ctypes.create_string_buffer(max_uncomp) res = zstd.ZSTD_decompress(dst, max_uncomp, raw_strings_dat, len(raw_strings_dat)) if zstd.ZSTD_isError(res): err_msg = (zstd.ZSTD_getErrorName(res) or b"unknown zstd error").decode("utf-8", errors="replace") raise RuntimeError(f"parse_strings_dat ZSTD_decompress failed: {err_msg} (code {res})") s_bytes = dst.raw[:res] count, pos = read_varint(s_bytes, 0) strings = [] while pos < len(s_bytes) and len(strings) < count: slen, pos = read_varint(s_bytes, pos) if pos + slen > len(s_bytes): raise ValueError(f"Truncated string in strings.dat at offset {pos}: declared {slen} bytes, only {len(s_bytes) - pos} remaining") strings.append(s_bytes[pos:pos+slen].decode("utf-8", errors="replace")) pos += slen if len(strings) != count: raise ValueError(f"Truncated strings.dat: declared {count} strings, parsed {len(strings)}") return strings def parse_replay_yml(yml_text): meta = {} for line in yml_text.splitlines(): if ":" in line and not line.startswith(" "): k, v = line.split(":", 1) meta[k.strip()] = v.strip().strip("'\"") return meta def parse_human_players(replay_final_yml_text): players = {} for m in re.finditer(r'- playerOOCName:\s*([^\n]+)\n\s*playerICName:\s*([^\n]+)\n.*?jobPrototypes:\s*\n\s*-\s*([^\n]+)', replay_final_yml_text, re.S): ooc = m.group(1).strip().strip("'\"") ic = m.group(2).strip().strip("'\"") job = m.group(3).strip().strip("'\"") if job not in ("Observer", "GhostPAI"): players[ic] = (ooc, job) return players def clean_bbcode(s): s = re.sub(r'\[icon src="[^"]*" tooltip="([^"]+)"\]', r'(\1)', s) s = re.sub(r'\[/?[a-zA-Z0-9=#" _-]+\]', '', s) return s.replace('\\[', '[').replace('\\]', ']').strip() def extract_chat_jsonl_from_chunk(decomp_bytes, chunk_idx, start_tick, players=None): text = decomp_bytes.decode("utf-8", errors="ignore") records = [] seen = set() pattern = r'(\[BubbleHeader\][^\x00-\x1f]{10,260}?\[/BubbleContent\].?|\[color=#[0-9a-fA-F]{6,8}\]\\\[[^\x00-\x1f]{10,340}?\[/font\]\[color=#[0-9a-fA-F]{6,8}\]"\[/color\])' sub = 0 for m in re.finditer(pattern, text): msg = clean_bbcode(m.group(0)) if msg in seen: continue seen.add(msg) if players: for ic, (ooc, job) in players.items(): if len(ic) >= 4 and (msg.startswith(ic + " ") or f") {ic} " in msg or f"] {ic} " in msg or f"] {ic} " in msg or f"zombified {ic} " in msg): tick = start_tick + chunk_idx * 90 + sub * 6 sub += 1 t_sec = round((tick - start_tick) / 30.0, 2) channel = "Common" if msg.startswith("[Common]") else "Local" q = re.search(r'[“"](.+?)[”"]$', msg) utterance = q.group(1) if q else msg records.append({ "tick": tick, "t": t_sec, "kind": "chat", "channel": channel, "sender": f"ent:{ic.lower().replace(' ', '_')}", "name": ic, "job": job, "ooc": ooc, "message": utterance }) break return records if __name__ == "__main__": target_url = sys.argv[1] if len(sys.argv) > 1 else "https://replays.starlight.network/alpha_2026_10_15-11_04-round_17614.zip" entries = get_zip_entries(target_url) meta = parse_replay_yml(fetch_entry(target_url, entries, "_replay/replay.yml").decode("utf-8", errors="replace")) start_tick = int(meta.get("startTick", "0")) strings = parse_strings_dat(fetch_entry(target_url, entries, "_replay/strings.dat")) rf_text = fetch_entry(target_url, entries, "_replay/replay_final.yml").decode("utf-8", errors="replace") players = parse_human_players(rf_text) print(f"# replay.yml: startTick={start_tick}, typeHash={meta.get('typeHash')}, strings.dat={len(strings)} strings, humanPlayers={len(players)}", file=sys.stderr) for idx in range(50, 56): k = f"_replay/data_{idx}.dat" if k in entries: decomp = decompress_zstd_chunk(fetch_entry(target_url, entries, k)) for rec in extract_chat_jsonl_from_chunk(decomp, idx, start_tick, players): print(json.dumps(rec, ensure_ascii=False))