#!/usr/bin/env python3 """Build a private, opt-in timed-quiver proto/resource patch; never install it. Both archived server configurations must agree. Nonmatching base vnums require explicit hash-bound reconstruction. 79501 and server/shop files remain untouched. """ import argparse import hashlib import json from pathlib import Path import shutil import subprocess import tarfile import tempfile import make_items import quiver_assets IDS=set(make_items.QUIVER_DURATIONS) MEMBERS=('home/srv1/db/item_proto.txt','home/srv1/share/conf/item_proto.txt') def digest(data): return hashlib.sha256(data).hexdigest() def dump_proto(tool,raw): # Read a frozen snapshot, never a base file another build can rewrite. with tempfile.TemporaryDirectory(prefix='ch5-quiver-proto-') as folder: path=Path(folder)/'item_proto';path.write_bytes(raw) return subprocess.run([str(tool),'--dump',str(path)],capture_output=True,check=True).stdout def selected(raw): result={} for line in raw.splitlines(): c=line.split(b'\t') if not c[0].strip().isdigit() or int(c[0]) not in IDS:continue v=int(c[0]) if v in result:raise ValueError('duplicate quiver row: '+str(v)) if len(c)<33:raise ValueError('truncated quiver row') # Source name is replaced with a Chinese display name, never used as a rule. result[v]=[x.decode('latin1' if i==1 else 'ascii').strip() for i,x in enumerate(c[:33])] if set(result)!=IDS:raise ValueError('archive must contain all three timed quivers') return result def merge_text(raw,rows): output=[] for line in raw.splitlines(): key=line.split(b'\t',1)[0] if not key.isdigit() or int(key) not in IDS:output.append(line) return b'\n'.join(output+[rows[v] for v in sorted(rows)])+b'\n' def dump_rows(raw): rows={} for line in raw.splitlines(): fields=line.split(b'\t',1)[0].split() if len(fields)!=31:raise ValueError('invalid proto tool dump') key=int(fields[0]) if key in rows:raise ValueError('duplicate proto dump row') rows[key]=line return rows def verify_patch(before,after,expected): before=dump_rows(before);after=dump_rows(after) if set(after)!=set(before)|IDS:raise ValueError('proto patch changed unexpected IDs') for v,line in before.items(): if v not in IDS and after[v]!=line:raise ValueError('unrelated proto changed: '+str(v)) for v in IDS: if list(map(int,after[v].split(b'\t',1)[0].split()))!=expected[v]: raise ValueError('patched client numeric fields differ: '+str(v)) return len(set(before)-IDS) def validate_base(raw,expected,replace_existing=False,expected_base_sha256=None,base_sha256=None): if expected_base_sha256 is not None and expected_base_sha256!=base_sha256: raise ValueError('base proto SHA256 mismatch') if replace_existing and not expected_base_sha256: raise ValueError('replacing existing quivers requires expected base SHA256') conflicts={} for v,line in dump_rows(raw).items(): if v in IDS: fields=list(map(int,line.split(b'\t',1)[0].split())) if fields!=expected[v]:conflicts[v]={'before':fields,'after':expected[v]} if conflicts and not replace_existing: raise ValueError('base client vnum conflicts: '+','.join(map(str,sorted(conflicts)))) return conflicts def client_inputs(client_root,packer): config=(client_root/'locale.cfg').read_text().split() if len(config)!=3 or config[2] not in ('zh','newcibn'): raise ValueError('only verified zh/newcibn locale targets are supported') index_hash=digest((client_root/'pack/Index').read_bytes()) verified={};files={} with tempfile.TemporaryDirectory(prefix='ch5-quiver-effective-') as folder: for name in ('item_proto','item_list.txt','itemdesc.txt'): probe=Path(folder)/name;entry='locale/'+config[2]+'/'+name subprocess.run([str(packer),'--read-client',str(client_root),entry,str(probe)],check=True,capture_output=True) files[name]=probe.read_bytes();verified[entry]=digest(files[name]) if digest((client_root/'pack/Index').read_bytes())!=index_hash: raise ValueError('client Index changed during generation') return files,{'files':verified,'index_sha256':index_hash} def build(ava,reader,locale,output,proto_tool,packer,replace_existing=False,expected_base_sha256=None,client_root=None,with_motion_assets=False): output=output.resolve() if output.exists():raise ValueError('output must be a new directory') if client_root is None:raise ValueError('client root required to bind the effective catalogue') source=ava/'2. Backup SF+SRC and SQL/FILES+SRC.tgz' with tarfile.open(source,'r:gz') as archive: sources={name:archive.extractfile(name).read() for name in MEMBERS} sets=[selected(raw) for raw in sources.values()] for v in sorted(IDS): if sets[0][v][:1]+sets[0][v][2:]!=sets[1][v][:1]+sets[1][v][2:]: raise ValueError('archived quiver rules conflict: '+str(v)) enums=make_items.enums(reader) server_rows={};client_rows={};expected={};names={} for v in sorted(IDS): name='无限箭筒(%d天)'%(make_items.QUIVER_DURATIONS[v]//86400) s,c,kept=make_items.convert(sets[0][v],enums,IDS,enable_quiver=True) assert kept s[1]=name;names[v]=name server_rows[v]='\t'.join(s).encode('gbk') client_rows[v]=('\t'.join(map(str,c))+'\t'+name).encode('gbk') expected[v]=c # By default reject replacements. An explicit, hash-bound AVA2 reconstruction # may replace only these three IDs, recording their complete numeric delta. files,effective=client_inputs(client_root,packer) if locale is not None: for name,raw in files.items(): if digest((locale/name).read_bytes())!=digest(raw): raise ValueError('locale source does not match effective client pack: '+name) base_bytes=files['item_proto'];base_hash=digest(base_bytes) raw_text={name:files[name] for name in ('item_list.txt','itemdesc.txt')} dumped=dump_proto(proto_tool,base_bytes) conflicts=validate_base(dumped,expected,replace_existing,expected_base_sha256,base_hash) pack_maker=ava/'1. Client DEV/pack_maker' assets_index=make_items.pack_index(pack_maker) source_icon='icon/item/79501.tga' if source_icon not in assets_index or not assets_index[source_icon].is_file(): raise ValueError('verified quiver icon missing') motion_files={};motion_records={} if with_motion_assets: with tempfile.TemporaryDirectory(prefix='ch5-quiver-motion-') as folder: def current(path): probe=Path(folder)/'entry' if probe.exists():probe.unlink() result=subprocess.run([str(packer),'--read-client',str(client_root),path,str(probe)],capture_output=True) return probe.read_bytes() if result.returncode==0 else None def reference(path): source=assets_index.get(path) return source.read_bytes() if source and source.is_file() else None motion_files,motion_records=quiver_assets.collect(current,reference) if digest((client_root/'pack/Index').read_bytes())!=effective['index_sha256']: raise ValueError('client Index changed during motion discovery') output.mkdir(parents=True,exist_ok=False) frozen=output/'base-item-proto';frozen.write_bytes(base_bytes) (output/'items-server.tsv').write_bytes(b'\n'.join(server_rows.values())+b'\n') (output/'items-client.tsv').write_bytes(b'\n'.join(client_rows.values())+b'\n') assets=output/'assets' for name,raw in motion_files.items(): dest=assets/name;dest.parent.mkdir(parents=True,exist_ok=True);dest.write_bytes(raw) # Private path: updating three variants must not change 79501's shared icon. icon='icon/ch5_quiver/79501.tga' (assets/icon).parent.mkdir(parents=True) shutil.copy2(assets_index[source_icon],assets/icon) for code in ('zh','newcibn'): target=assets/'locale'/code;target.mkdir(parents=True) subprocess.run([str(proto_tool),str(frozen),str(output/'items-client.tsv'),str(target/'item_proto')],check=True) after=dump_proto(proto_tool,(target/'item_proto').read_bytes()) unchanged=verify_patch(dumped,after,expected) listing={v:('%d\tETC\t%s'%(v,icon)).encode() for v in sorted(IDS)} descriptions={v:('%d\t%s\t弓手箭槽弹药,射击不消耗数量;获得后按实时期限到期,离线也计时。'% (v,names[v])).encode('gbk') for v in sorted(IDS)} (target/'item_list.txt').write_bytes(merge_text(raw_text['item_list.txt'],listing)) (target/'itemdesc.txt').write_bytes(merge_text(raw_text['itemdesc.txt'],descriptions)) subprocess.run([str(packer),str(output/'quiver'),str(assets),''],check=True) report={'version':1,'items':sorted(IDS),'excluded':[79501],'installed':False, 'verified_unchanged_proto_records':unchanged, 'source_sha256':{p:digest(raw) for p,raw in sources.items()}, 'base_proto_sha256':base_hash,'proto_reader_sha256':digest(reader.read_bytes()), 'effective_client_base':effective, 'explicit_replacements':conflicts, 'motion_assets':motion_records, 'differences':['ANTI_WOLFMAN omitted like existing converter: Wolfman disabled; re-evaluate before enabling fifth job', 'Chinese names/descriptions; no price/duration invention'], 'requires':['matched client/server build','verified test-only proto install','live item lifecycle and Android acceptance'], 'files':{p.relative_to(output).as_posix():digest(p.read_bytes()) for p in sorted(output.rglob('*')) if p.is_file()}} (output/'manifest.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n') return report def main(): parser=argparse.ArgumentParser(description=__doc__) for name in ('ava','reader','output','proto_tool','packer'): parser.add_argument('--'+name.replace('_','-'),type=Path,required=True) parser.add_argument('--locale',type=Path,help='optional reference folder; every file must equal the effective runtime bytes') parser.add_argument('--replace-existing-quivers',action='store_true',help='replace only three timed variants using the verified AVA2 rules') parser.add_argument('--expected-base-sha256',help='required with replacement; must match the exact base proto') parser.add_argument('--client-root',type=Path,required=True,help='bind proto/list/description to actual registered runtime packs') parser.add_argument('--with-motion-assets',action='store_true',help='resolve quiver motion/effect closure; stage only files missing from registered packs') args=parser.parse_args() result=build(args.ava,args.reader,args.locale,args.output,args.proto_tool.resolve(),args.packer.resolve(), args.replace_existing_quivers,args.expected_base_sha256,args.client_root,args.with_motion_assets) print(json.dumps({'items':result['items'],'installed':False,'output':str(args.output)})) if __name__=='__main__':main()