Files

247 lines
14 KiB
Python

"""Inventory named UI files decoded from the release, without executing client Lua."""
import argparse
import csv
import hashlib
import posixpath
import re
import struct
import subprocess
from collections import Counter
from pathlib import Path
from lxml import etree
# Symbols include callback references (e.g. XML function attributes) and selected
# intermediate producers. Each lane describes evidence, not an assumed destination.
GROUPS = {
'system-opener': r'(?<![\w.])(?:LoadURLIndex|LaunchURL|VisitPromotionURL)\b|C_ExternalEventURL\.LaunchURL|C_StoreSecure\.OpenNydusLink|\bOpenExternalLink\b',
'embedded-browser': r'\b(?:PhotoSharingBrowser(?:Popup)?:(?:NavigateTo|NavigateHome)|self:OpenCheckout|C_PhotoSharing\.BeginAuthorizationFlow)\b',
'native-link-action': r'C_CatalogShop\.OnLegal(?:DisclaimerClicked|PersonalizedOptOutClicked)',
'purchase-branch': r'\b(?:C_StoreSecure\.(?:PurchaseVASProduct|PurchaseProduct(?:Confirm)?)|C_CatalogShop\.(?:PurchaseProduct|StartHousingVCPurchaseConfirmation|ConfirmHousingPurchase))\b',
'url-wrapper': r'\b(?:GetURLIndexAndLoadURL(?:WithSound)?|StoreFrameErrorWebsiteButton_OnClick|PromotionFrame_LaunchUpgradeURL|ExternalEventClickCallback|OpenBnetLink|AccountLogin_LaunchCommunitySite|AccountLogin_ManageAccount|CharacterSelect_ManageAccount|CharacterSelect_TechSupport|StoreInterfaceUtil\.OpenToSubscriptionProduct|UpgradeAccount|StoreNydusLinkButtonMixin|NydusLinkButtonTemplate|GetFaqNydusLink|StoreFrame_SelectSubscriptionProduct|SubscriptionRequestDialog_Open|AccountReactivate_ReactivateNow|WoWLabsSubscribeButtonMixin|SubscriptionInterstitialSubscribeButtonBaseMixin|LinkTypes\.URLIndex|EXTERNAL_EVENT_LAUNCH_URL_FAILED|GAMEMENU_EXTERNALEVENT_FAILURE|BACKPACK_INCREASE_SIZE|GROUP_FINDER_AUTHENTICATOR_POPUP|CONFIRM_LAUNCH_URL|OKAY_WITH_GENERIC_URL|OKAY_WITH_URL(?:_INDEX)?|OKAY_LEGAL_REDIRECT|ACCOUNT_SAVE_SUCCESS)\b',
'checkout-entry': r'\b(?:STORE_OPEN_SIMPLE_CHECKOUT|CATALOG_SHOP_OPEN_SIMPLE_CHECKOUT|OnExternalLink|ToggleStoreUI|StoreFrame_BeginPurchase|StoreFrameBuyButton_OnClick|OpenCatalogShopForProduct|OpenGamesCategory|StoreFrame_OpenGamesCategory|opengamescategory|GAMEMENU_EXTERNALEVENT|LinkTypes\.StoreCategory|SelectSubscriptionProduct|SelectGameTimeProduct|OnLegalDisclaimerClicked|OnLegalPersonalizedOptOutClicked|SetStoreShown|ToggleAccountStore|CATALOG_SHOP_DISCLAIMER_ALL_PRODUCTS|FRAME_ACTION_BATTLE_NET|OnInfoButton_OnClick|LegalDisclaimerText|CatalogShopSectionHeaderOptOutLinkMixin|PurchaseProduct|StoreFrame_SelectGameTimeProduct|SetShownOrSelectSpecificProduct|OpenCatalogShopInteractionFromHouse|OpenCatalogShopInteractionFromShop)\b',
'support': r'\b(?:ToggleHelpFrame|HelpFrame:ShowFrame|HelpFrameMixin:ShowFrame|HelpFrameMixin:OnShow|EnsureOctoSupportPanel|GetWebTicket|HelpOpenWebTicketButton|EXTERNAL_LINK|HelpBrowser|DIALOG_HELP_MORE_INFO)\b',
'social-copy': r'C_RecruitAFriend\.GenerateRecruitmentLink|recruitmentInfo\.recruitmentURL|ClubTicketUtil\.FormatTicket|COMMUNITIES_INVITE_MANAGER_TICKET_FORMAT\w*|\bSOCIAL_ITEM_ARMORY_LINK\b',
'social-event': r'\b(?:PHOTO_SHARING_AUTHORIZATION_NEEDED|SIMPLE_BROWSER_POPUP|SIMPLE_BROWSER_SOCIAL_CALLBACK_INVOKED|PhotoSharingBrowserMixin|PhotoSharingBrowserPopupMixin)\b',
'internal-control': r'\b(?:C_AccountStore\.BeginPurchase|C_PerksProgram\.RequestCartCheckout|SourceStore_BeginPurchase|CatalogShopMixin:WebsiteError|C_Texture\.SetURLTexture)\b',
}
MATCHERS = [(key, re.compile(pattern)) for key, pattern in GROUPS.items()]
URL = re.compile(r"""(?:https?://|www\.)[^\s<>"'\\|]+""", re.I)
TAG = re.compile(r'\[(AllowLoadGameType|ExcludeLoadGameType)\s+([^\]]+)\]', re.I)
GAME = {'mainline', 'camelot'}
TREATMENT = {
'system-opener': 'remove-launch-branch',
'embedded-browser': 'disable-owned-browser-entry',
'native-link-action': 'remove-legal-action',
'purchase-branch': 'isolate-paid-checkout',
'url-wrapper': 'remove-link-at-origin',
'checkout-entry': 'isolate-paid-checkout',
'support': 'preserve-copy-only-support',
'social-copy': 'remove-web-invite-control',
'social-event': 'disable-owned-browser-entry',
'internal-control': 'review-internal-path',
'url-literal': 'review-display-text',
'localized-link': 'review-localized-link-producer',
}
def allows(kind, values):
selected = bool(GAME.intersection(re.findall(r'[a-z]+', values.lower())))
return selected if kind.lower().startswith('allow') else not selected
def strip_xml_comments(text):
return re.sub(r'<!--.*?-->', lambda m: '\n' * m[0].count('\n'), text, flags=re.S)
def closure(files):
"""Trace TOC and XML file= includes only. A reachable addon may be load-on-demand."""
seen = set()
todo = []
for key, path in files.items():
if path.suffix.lower() != '.toc' or path.stem.lower() != path.parent.name.lower():
continue
content = path.read_text(errors='replace')
gates = re.findall(r'^##\s*(AllowLoadGameType|ExcludeLoadGameType):([^\n]*)', content, re.I | re.M)
if all(allows(kind, values) for kind, values in gates):
todo.append(key)
while todo:
key = todo.pop()
if key in seen:
continue
seen.add(key)
ext = files[key].suffix.lower()
if ext not in {'.toc', '.xml'}:
continue
content = files[key].read_text(errors='replace')
if ext == '.toc':
refs = []
for line in content.splitlines():
if line.strip().startswith('#') or not all(allows(kind, val) for kind, val in TAG.findall(line)):
continue
refs.append(TAG.sub('', line).strip().split('\t')[0].strip())
else:
refs = re.findall(r'<(?:Include|Script)\b[^>]*?\sfile\s*=\s*["\']([^"\']+)["\']', strip_xml_comments(content), re.I)
for ref in refs:
name = ref.lower().replace('\\','/').replace('[family]', 'mainline').replace('[game]', 'camelot')
resolved = posixpath.normpath(name if name.startswith('interface/') else posixpath.join(posixpath.dirname(key), name))
if resolved in files and resolved not in seen:
todo.append(resolved)
return seen
def location_builder(path, lines, content):
if path.suffix.lower() == '.xml':
parser = etree.XMLParser(recover=True, no_network=True, resolve_entities=False, huge_tree=True)
root = etree.fromstring(content, parser)
nodes = [node for node in root.iter() if isinstance(node.tag, str)]
def describe(number):
node = next((n for n in reversed(nodes) if n.sourceline and n.sourceline <= number), root)
labels = []
for item in [node, *node.iterancestors()]:
label = item.get('name') or item.get('parentKey') or item.get('mixin')
tag = etree.QName(item.tag).localname
if label or tag.startswith('On'):
labels.append(label or tag)
if len(labels) == 3:
break
return ' / '.join(reversed(labels)) or path.stem
return describe
# The compiler emits lexical line spans including anonymous handlers and closures.
# Anonymous table handlers use the nearest dialog or named outer function.
proc = subprocess.run(['luac5.1', '-p', '-l', str(path)], capture_output=True, errors='replace')
spans = [] if proc.returncode else [(int(a),int(b)) for a,b in re.findall(r'^function <.*?:(\d+),(\d+)>', proc.stdout, re.M)]
def describe(number):
found = []
for a,b in sorted(((a,b) for a,b in spans if a<=number<=b), key=lambda s:s[1]-s[0]):
line = lines[a-1].strip()
match = re.search(r'function\s+([\w.:]+)|\b([\w.]+)\s*=\s*function\b|RegisterLinkHandler\((LinkTypes\.\w+)|RegisterCallback\(["\']([^"\']+)', line)
if match:
found.append(next(v for v in match.groups() if v))
context = lines[max(0, number-35):number]
joined = '\n'.join(context)
dialog = re.findall(r'StaticPopupDialogs\[["\']([^"\']+)["\']\]',joined)
if dialog and (not found or found[0].startswith('On')):
found.append(dialog[-1])
return ' / '.join(dict.fromkeys(reversed(found))) or path.stem
return describe
def emit(path, headings, rows):
with path.open('w', newline='') as f:
w=csv.writer(f, delimiter='\t', lineterminator='\n', quoting=csv.QUOTE_ALL)
w.writerow(headings)
w.writerows(rows)
def dbstrings(path):
data = path.read_bytes()
header = struct.unpack_from('<4I2I3I2H7I',data,136)
assert data[:4] == b'WDC5' and header[1:3] == (3,9) and header[-1] == 1
key,off,rows,size,_,ids,*_ = struct.unpack_from('<Q8I',data,204)
assert key == 0 and ids == rows * 4
start = off + 9 * rows
end = start + size
result=[]
for i in range(rows):
fields=[]
for j in (0,4):
pos = off + 9*i + j
relative = struct.unpack_from('<i',data,pos)[0]
if not relative:
fields.append('')
continue
pos += relative
assert start <= pos < end
fields.append(data[pos:data.index(b'\x00',pos,end)].decode())
name, value = fields
urls = URL.findall(value)
links = re.findall(r'\|H(?:urlIndex:\d+|codelink)\b',value,re.I)
if urls or links or name.startswith('VISITABLE_URL') or 'shop.battle.net' in value:
rid = struct.unpack_from('<I',data,end+i*4)[0]
result.append((rid,name,' | '.join(dict.fromkeys(urls)),' | '.join(dict.fromkeys(links))))
return result
def main():
p=argparse.ArgumentParser(description=__doc__)
for field in ('decoded','addons','listfile','globalstrings','out'):
p.add_argument('--'+field,required=True,type=Path)
args=p.parse_args()
files = {p.relative_to(args.decoded).as_posix().lower():p for p in args.decoded.rglob('*') if p.is_file()}
stock=set(files)
for path in args.addons.rglob('*'):
if path.is_file() and path.suffix.lower() in {'.toc','.lua','.xml'}:
key='interface/addons/'+path.relative_to(args.addons).as_posix().lower()
files[key]=path
sources = {key:('CASC' if path.is_relative_to(args.decoded) else 'loose') for key,path in files.items()}
eligible = closure(files)
fdids = {}
with args.listfile.open() as f:
for line in f:
fid,_,name=line.rstrip().partition(';')
if name.lower() in stock:
fdids[name.lower()] = fid
strings=dbstrings(args.globalstrings)
localized_links = {row[1] for row in strings}
identifier = re.compile(r'\b[A-Z][A-Z_0-9]+\b')
records=[]
manifest=[]
for key,path in sorted(files.items()):
if path.suffix.lower() not in {'.lua','.xml'} or '/blizzard_apidocumentationgenerated/' in key:
continue
raw=path.read_bytes()
text=raw.decode('utf-8-sig',errors='replace')
lines=text.splitlines()
scan=strip_xml_comments(text) if path.suffix.lower()=='.xml' else text
location = None
hits=0
for n,line in enumerate(scan.splitlines(),1):
if line.lstrip().startswith(('--','<!--')) or 'xmlns=' in line or 'schemaLocation=' in line:
continue
# Actual symbols precede ordinary line comments in the corpus.
code=line.split('--', 1)[0]
groups=[(k,s[0]) for k,pattern in MATCHERS for s in pattern.finditer(code)]
groups += [('localized-link', word) for word in identifier.findall(code) if word in localized_links]
if not any(k=='system-opener' for k,_ in groups):
groups += [('url-literal',url.rstrip('.,);')) for url in URL.findall(code)]
if not groups:
continue
if location is None:
location = location_builder(path, lines, raw)
for group,symbol in dict.fromkeys(groups):
treatment=TREATMENT[group]
if 'blizzard_gluexml/' in key or 'blizzard_glueparent/' in key or 'blizzard_staticpopup_glue/' in key:
if symbol == 'LaunchURL' and 'octowow.st' in code:
treatment='replace-octo-launch-with-copy'
if symbol == 'C_Texture.SetURLTexture':
treatment='asset-reference'
if symbol in ('C_AccountStore.BeginPurchase', 'C_PerksProgram.RequestCartCheckout', 'SourceStore_BeginPurchase'):
treatment='preserve-in-game-purchase'
if 'C_StoreSecure.PurchaseProductConfirm(false)' in code:
treatment='preserve-cancel'
if 'blizzard_accountsaveui/' in key and symbol=='LaunchURL':
treatment='preserve-local-file-action'
if 'blizzard_helpframe/' in key and symbol in ('EXTERNAL_LINK','OnExternalLink'):
treatment='preserve-copy-only-support'
records.append((key,n,sources[key],'TOC-linked' if key in eligible else 'unresolved-or-excluded',location(n),group,symbol,treatment))
hits+=1
if hits:
manifest.append((key,fdids.get(key,'') if sources[key]=='CASC' else '', hash_file(raw), hits))
args.out.mkdir(parents=True,exist_ok=True)
emit(args.out/'ui.tsv', ('path','line','source','load_path','button_frame_or_handler','evidence','symbol','treatment'),records)
emit(args.out/'files.tsv', ('path','release_fdid','sha256','evidence_rows'),manifest)
emit(args.out/'globalstrings.tsv',('record_id','base_tag','literal_destinations','encoded_link_types'),strings)
print(f'{len(stock)} archived UI files, {sum(v=="loose" for v in sources.values())} loose, {len(eligible)} TOC-linked, {len(records)} evidence rows in {len(manifest)} files, {len(strings)} data rows')
print(Counter(r[5] for r in records))
def hash_file(data):
return hashlib.sha256(data).hexdigest()
if __name__=='__main__':
main()