#!/usr/bin/env python3 """Gera o site do Wolff's Room a partir de content/posts/*/post.md. Uso: python tools/build.py # gera em _site/ python -m http.server -d _site # pré-visualiza em http://localhost:8000 Cada post é uma pasta em content/posts// com um post.md e as imagens ao lado. Veja COMO-POSTAR.md para o formato. """ import datetime import html import json import os import re import shutil import subprocess import sys import yaml sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from store import drive_direct # noqa: E402 ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CONTENT = os.path.join(ROOT, 'content', 'posts') OUT = os.path.join(ROOT, '_site') TEMPLATE = os.path.join(ROOT, 'tools', 'template.html') e = html.escape DF = "font-family: 'WR Start 2P', 'Press Start 2P', 'Pixelify Sans', monospace;" CATS = [('ports', 'Ports'), ('ferramentas', 'Ferramentas'), ('traducoes', 'Traduções'), ('reviews', 'Reviews')] CAT_NAMES = dict(CATS) GROUPS = ['Em andamento', 'Finalizado', 'Próximos', 'Outras equipes'] SLUG_RE = re.compile(r'^[a-z0-9][a-z0-9-]*$') WEB_GITHUB = 'https://github.com/WolffsRoom?tab=repositories' class PostError(Exception): pass def vita_github_url(url): """The website always opens GitHub proper; only the Vita app remaps links.""" return str(url) # ---------------------------------------------------------------- leitura def parse_markdown(body): """Read post prose and preserve inline media order inside content sections.""" about, secs, cur = [], [], None for line in body.splitlines(): text = line.strip() if text.startswith('## '): cur = {'title': text[3:].strip(), 'items': [], 'paras': [], 'blocks': []} secs.append(cur) elif not text: continue elif cur is None: about.append(text) elif re.match(r'^[-*] ', text): item = text[2:].strip() cur['items'].append(item) cur['blocks'].append(('li', item)) elif re.fullmatch(r'!\[[^\]]*\]\([A-Za-z0-9][A-Za-z0-9._-]*\)', text): match = re.fullmatch(r'!\[([^\]]*)\]\(([A-Za-z0-9][A-Za-z0-9._-]*)\)', text) cur['blocks'].append(('media', match.group(1), match.group(2))) else: cur['paras'].append(text) cur['blocks'].append(('p', text)) return ' '.join(about), secs def inline(text): """Escapa o texto e converte [texto](url) e **negrito**.""" out = e(text) out = re.sub(r'\[([^\]]+)\]\((https?://[^)\s]+)\)', lambda m: f'{m.group(1)}', out) out = re.sub(r'\*\*([^*]+)\*\*', r'\1', out) return out def parse_bars(raw): bars = [] for label, val in (raw or {}).items(): m = re.match(r'^\s*(\d{1,3})\s*%?\s*(?:\((.+)\))?\s*$', str(val)) if not m: raise PostError(f'barra "{label}": use um número de 0 a 100, ex.: 80 ou "89 (192/216)"') bars.append((str(label), max(0, min(100, int(m.group(1)))), m.group(2))) return bars TIPOS_DOWNLOAD = ('vpk', 'traducao', 'plugin', 'arquivo', 'dados', 'app_arquivos') def parse_downloads(raw): """Campo `downloads:` do post (para o app Wolff's Store). Ver COMO-POSTAR.md.""" if not raw: return [] if not isinstance(raw, list): raise PostError('downloads: use uma lista (cada item começa com "- tipo: ...")') out = [] for i, d in enumerate(raw, 1): if not isinstance(d, dict): raise PostError(f'downloads, item {i}: use campos como "tipo:" e "repo:" ou "url:"') tipo = str(d.get('tipo') or 'vpk').strip().lower().replace('ç', 'c').replace('ã', 'a') if tipo not in TIPOS_DOWNLOAD: raise PostError(f'downloads, item {i}: tipo "{d.get("tipo")}" inválido; use: ' + ', '.join(TIPOS_DOWNLOAD)) mirrors = d.get('alternativas') or [] if not isinstance(mirrors, list) or any(not isinstance(u, str) or not u.startswith('https://') for u in mirrors): raise PostError(f'downloads, item {i}: alternativas devem ser uma lista de URLs HTTPS') if d.get('senha') and tipo not in ('traducao', 'vpk', 'app_arquivos') and not d.get('app_pendente'): raise PostError(f'downloads, item {i}: tipo de pacote sem suporte a senha') if d.get('app_min') and not re.fullmatch(r'\d+\.\d+(?:\.\d+)?', str(d.get('app_min'))): raise PostError(f'downloads, item {i}: app_min requer versao numerica (ex.: 1.0)') if not d.get('url') and not d.get('repo'): raise PostError(f'downloads, item {i}: informe "repo:" (release do GitHub) ou "url:" (link direto)') if d.get('repo') and not re.fullmatch(r'[\w.-]+/[\w.-]+', str(d['repo'])): raise PostError(f'downloads, item {i}: repo deve ser "Dono/Repositorio"') tids = d.get('titleid') or [] if isinstance(tids, str): tids = [t.strip() for t in re.split(r'[,\s]+', tids) if t.strip()] for t in tids: if not re.fullmatch(r'[A-Z0-9]{9}', str(t)): raise PostError(f'downloads, item {i}: titleid "{t}" inválido (9 letras/números, ex.: PCSE00584 ou FILEMNGR1)') if tipo in ('traducao', 'app_arquivos') and not tids: raise PostError(f'downloads, item {i}: tradução precisa de "titleid:" (pasta do rePatch)') out.append({ 'tipo': tipo, 'nome': d.get('nome'), 'url': d.get('url'), 'repo': d.get('repo'), 'arquivo': d.get('arquivo'), 'tag': d.get('tag'), 'versao': d.get('versao'), 'tamanho': d.get('tamanho'), 'titleids': [str(t) for t in tids], 'alternativas': mirrors, 'senha': str(d.get('senha') or ''), 'app_pendente': bool(d.get('app_pendente')), 'app_min': str(d.get('app_min') or ''), 'precisa_dados': bool(d.get('precisa_dados')), 'instrucoes': vita_github_url(d.get('instrucoes')) if d.get('instrucoes') else None, 'plugin': d.get('plugin') or ('rePatch' if tipo == 'traducao' else None), 'aviso_plugin': str(d.get('aviso_plugin') or ''), }) return out def load_post(slug): folder = os.path.join(CONTENT, slug) path = os.path.join(folder, 'post.md') raw = open(path, encoding='utf-8').read() m = re.match(r'^---\s*\n(.*?)\n---\s*\n?(.*)$', raw, re.S) if not m: raise PostError('o arquivo precisa começar com um cabeçalho entre linhas ---') meta = yaml.safe_load(m.group(1)) or {} body = m.group(2) for req in ('titulo', 'categoria', 'grupo', 'data'): if not meta.get(req): raise PostError(f'campo obrigatório ausente: {req}') cat = str(meta['categoria']).strip().lower().replace('ç', 'c').replace('õ', 'o') if cat not in CAT_NAMES: raise PostError(f'categoria "{meta["categoria"]}" inválida; use: ' + ', '.join(CAT_NAMES)) group = str(meta['grupo']).strip() if group not in GROUPS: raise PostError(f'grupo "{group}" inválido; use: ' + ', '.join(GROUPS)) # data: 2026-11-13 ou 2026-11-13 23:40 (a hora desempata posts do mesmo dia) when = meta['data'] if isinstance(when, str): when = datetime.datetime.fromisoformat(when.strip()) if not isinstance(when, datetime.datetime): when = datetime.datetime.combine(when, datetime.time()) when = when.replace(tzinfo=None) date = when.date() about, secs = parse_markdown(body) def img(name): if not name: return None if not os.path.isfile(os.path.join(folder, name)): raise PostError(f'imagem não encontrada na pasta do post: {name}') return f'posts/{slug}/{name}' video = meta.get('video') vid = None if video: mv = re.search(r'(?:v=|youtu\.be/|embed/|shorts/)([A-Za-z0-9_-]{6,})', str(video)) if not mv: raise PostError('video: use um link do YouTube') vid = mv.group(1) progress = meta.get('progresso') if progress is not None and str(progress).strip() != '': progress = max(0, min(100, int(progress))) else: progress = None # Embedded media is distinct from the optional screenshot gallery. # Validate all local references before writing any public HTML. for sec in secs: for block in sec.get('blocks', []): if block[0] == 'media': img(block[2]) manual_updated = meta.get('atualizado_em') if manual_updated: if isinstance(manual_updated, str): manual_updated = datetime.date.fromisoformat(manual_updated[:10]) if isinstance(manual_updated, datetime.datetime): manual_updated = manual_updated.date() if not isinstance(manual_updated, datetime.date): raise PostError('atualizado_em: informe YYYY-MM-DD') if manual_updated < date: raise PostError('atualizado_em: não pode ser anterior à publicação') p = { 'slug': slug, 'title': str(meta['titulo']), 'cat': cat, 'group': group, 'date': date, 'when': when, 'updated': manual_updated or post_last_updated(slug, date), 'tag': str(meta.get('tag') or CAT_NAMES[cat]), 'status': str(meta.get('status') or group), 'author': str(meta.get('autor') or '').strip(), 'author_url': str(meta.get('autor_url') or '').strip(), 'version_label': str(meta.get('versao') or '').strip(), 'news_kind': str(meta.get('novidade') or '').strip(), 'desc': str(meta.get('resumo') or ''), 'about': about, 'secs': secs, 'progress': progress, 'bars': parse_bars(meta.get('barras')), 'meta': [(str(k), str(v)) for k, v in (meta.get('ficha') or {}).items()], 'links': [(str(k), vita_github_url(v)) for k, v in (meta.get('links') or {}).items()], 'sources': [(str(k), vita_github_url(v)) for k, v in (meta.get('fontes') or {}).items()], 'clock': [(str(k), str(v)) for k, v in (meta.get('clock') or {}).items()], # vídeo próprio (.mp4 na pasta do post ou link): toca no site e dentro do app 'video_file': (str(meta['video_arquivo']) if str(meta.get('video_arquivo') or '').startswith('http') else (img(str(meta['video_arquivo'])) if meta.get('video_arquivo') else '')), 'trophies': bool(meta.get('trofeus')), 'cover': img(meta.get('capa')), 'cover_style': str(meta.get('capa_estilo') or 'cobrir'), 'pixel': bool(meta.get('pixelado')), 'shots': [img(s) for s in (meta.get('capturas') or [])], 'video': vid, 'feature': bool(meta.get('destaque')), 'feature_text': str(meta.get('chamada') or meta.get('resumo') or ''), 'folder': folder, } if p['news_kind'] not in ('', 'Release', 'Update'): raise PostError('novidade: use Release ou Update (ou deixe vazio)') p['downloads'] = parse_downloads(meta.get('downloads')) p['video_label'] = str(meta.get('video_legenda') or '') p['bars_title'] = str(meta.get('titulo_barras') or '') p['en'] = load_english(folder, p) return p def load_english(folder, p): """post.en.md: mesmos campos de texto, em inglês. Tudo é opcional.""" path = os.path.join(folder, 'post.en.md') if not os.path.isfile(path): return None raw = open(path, encoding='utf-8').read() m = re.match(r'^---\s*\n(.*?)\n---\s*\n?(.*)$', raw, re.S) meta, body = (yaml.safe_load(m.group(1)) or {}, m.group(2)) if m else ({}, raw) about, secs = parse_markdown(body) for sec in secs: for block in sec.get('blocks', []): if block[0] == 'media' and not os.path.isfile(os.path.join(folder, block[2])): raise PostError(f'English media not found: {block[2]}') en = {'about': about, 'secs': secs} for src, dst in (('titulo', 'title'), ('tag', 'tag'), ('status', 'status'), ('resumo', 'desc'), ('video_legenda', 'video_label'), ('titulo_barras', 'bars_title')): if meta.get(src): en[dst] = str(meta[src]) if meta.get('chamada') or meta.get('resumo'): en['feature_text'] = str(meta.get('chamada') or meta.get('resumo')) if meta.get('barras'): en['bars'] = parse_bars(meta['barras']) if meta.get('ficha'): en['meta'] = [(str(k), str(v)) for k, v in meta['ficha'].items()] if meta.get('links'): en['links'] = [(str(k), vita_github_url(v)) for k, v in meta['links'].items()] if meta.get('clock'): en['clock'] = [(str(k), str(v)) for k, v in meta['clock'].items()] if meta.get('fontes'): en['sources'] = [(str(k), vita_github_url(v)) for k, v in meta['fontes'].items()] if not en['about']: del en['about'] if not en['secs']: del en['secs'] return en def load_all(): posts, errors = {}, [] for slug in sorted(os.listdir(CONTENT)): if not os.path.isfile(os.path.join(CONTENT, slug, 'post.md')): continue if not SLUG_RE.match(slug): errors.append(f'{slug}: o nome da pasta deve ter só letras minúsculas, números e hífen') continue try: posts[slug] = load_post(slug) except (PostError, ValueError, yaml.YAMLError) as ex: errors.append(f'{slug}/post.md: {ex}') if errors: sys.exit('Erros nos posts:\n - ' + '\n - '.join(errors)) order = sorted(posts, key=lambda k: (posts[k]['when'], k), reverse=True) return posts, order # ---------------------------------------------------------------- HTML UI = { 'pt': { 'cats': {'ports': 'Ports', 'ferramentas': 'Ferramentas', 'traducoes': 'Traduções', 'reviews': 'Reviews'}, 'groups': {g: g for g in GROUPS}, 'nothing': 'Nada por aqui ainda.', 'back': 'Voltar', 'back_home': 'Voltar ao início', 'repos': 'Todos os repositórios no GitHub', 'shots': 'Capturas de tela', 'video': 'Vídeo', 'watch': 'Assistir no YouTube', 'video_note': 'O vídeo abre no YouTube.', 'info': 'Detalhes', 'links': 'Downloads', 'sources': 'Source', 'clock': 'Clock recomendado', 'latest3': 'Confira as últimas três novidades...', 'trophies': 'Troféus nativos', 'total': 'Total', 'progress': 'Progresso', 'latest': 'Últimos em', 'see_all': 'Ver todos', 'details': 'Ver detalhes', 'github': 'Ver no GitHub', 'start': 'Pressione start', 'click': 'Clique para começar', 'kicker': 'O que será que o Wolff está fazendo...?', 'cover_of': 'Capa de', 'shot_of': 'Captura de tela de', 'open': 'Abrir', 'video_default': 'Vídeo do projeto', }, 'en': { 'cats': {'ports': 'Ports', 'ferramentas': 'Tools', 'traducoes': 'Translations', 'reviews': 'Reviews'}, 'groups': {'Em andamento': 'In progress', 'Finalizado': 'Finished', 'Próximos': 'Upcoming', 'Outras equipes': 'Other teams'}, 'nothing': 'Nothing here yet.', 'back': 'Back', 'back_home': 'Back to home', 'repos': 'All repositories on GitHub', 'shots': 'Screenshots', 'video': 'Video', 'watch': 'Watch on YouTube', 'video_note': 'The video opens on YouTube.', 'info': 'Details', 'links': 'Downloads', 'sources': 'Source', 'clock': 'Recommended clock', 'latest3': 'Check out the latest three updates...', 'trophies': 'Native trophies', 'total': 'Total', 'progress': 'Progress', 'latest': 'Latest in', 'see_all': 'See all', 'details': 'See details', 'github': 'View on GitHub', 'start': 'Press start', 'click': 'Click to begin', 'kicker': 'What could Wolff be up to...?', 'cover_of': 'Cover of', 'shot_of': 'Screenshot of', 'open': 'Open', 'video_default': 'Project video', }, } def T(pt, en): """Texto nos dois idiomas (já em HTML). O CSS mostra só o idioma ativo.""" if pt == en: return pt return f'{pt}{en}' def U(key): return T(e(UI['pt'][key]), e(UI['en'][key])) def V(p, lang): """Os campos do post no idioma pedido (inglês cai no português quando falta).""" if lang == 'pt' or not p.get('en'): return p q = dict(p) q.update({k: v for k, v in p['en'].items() if v not in (None, '', [])}) return q def F(p, field, fn=e): return T(fn(str(V(p, 'pt')[field])), fn(str(V(p, 'en')[field]))) def pic(p, lang='en'): alt = e(UI[lang]['cover_of'] + ' ' + V(p, lang)['title']) if not p['cover']: return f'
{F(p, "title")}
' if p['cover_style'] == 'logo': return f'
\n{alt}\n
' px = '; image-rendering: pixelated' if p['pixel'] else '' return f'{alt}' def news_flag(p): kind = p.get('news_kind') or '' return (f'{e(kind)}' if kind in ('Release', 'Update') else '') def card(p): by = (f'by: {e(p["author"])}\n' if p.get("author") else "") return ('\n' '
\n' + pic(p) + ('' + trophy_badge('pt', 2, False) + '' if p.get('trophies') else '') + '\n
\n' '
\n' f'{F(p, "tag")}\n' + f'{F(p, "title")}\n' + by + f'{F(p, "desc")}\n' f'{F(p, "status")}\n' '
\n
') def progress_color(pct): """Cores de avanço iguais ao Vita: baixo, intermediário e quase concluído.""" return '#e05a5a' if pct < 40 else '#f4c430' if pct < 80 else '#52c98c' def bar(label, pct, text=None): pct = max(0, min(100, int(pct))) text = text or f'{pct}%' return ('
\n' f'
{e(label)}{e(text)}
\n' f'\n
') BOX = 'border: 4px solid #5a5a5a; background: #0e0e0e; padding: 20px; display: flex; flex-direction: column; gap: 16px' H2 = f'margin: 0; {DF} font-size: 16px; line-height: 1.5; font-weight: 400; text-transform: uppercase' PLAY = ('') # troféu em pixel art (10x10): o jogo tem troféus nativos (com o plugin NoTrpDrm) _TROPHY_ROWS = ['.########.', '##.####.##', '#..####..#', '##.####.##', '..######..', '...####...', '....##....', '....##....', '..######..', '..######..'] def trophy_svg(px=3): rects = ''.join(f'' for y, r in enumerate(_TROPHY_ROWS) for x, c in enumerate(r) if c == '#') shine = '' return (f'') def trophy_badge(lang, px=3, label=True): """Só o ícone (sem moldura), com o texto ao lado quando label=True.""" t = UI[lang]['trophies'] txt = f'{e(t)}' if label else '' return (f'' f'{trophy_svg(px)}{txt}') # ---------------------------------------------------------------- Wolff's Store (modal do PS Vita) # Link do VPK do app (o QR Code aponta para ele). Ajustar quando a release estiver publicada. STORE_VPK_URL = 'https://github.com/WolffsRoom/WolffsStore/releases/latest/download/WolffsStore.vpk' # PS Vita em pixel art, a partir da arte assets/Vita.png da Wolff's Store (40x18) _VITA = ['.....##############################.....', '...##################################...', '..########....................########..', '.#########....................#########.', '####..####....................####..####', '####..####....................####..####', '##......##....................##..##..##', '##......##....................##..##..##', '####..####....................####..####', '####..####....................####..####', '##########....................##########', '##########....................##########', '####..####....................####..####', '####..####....................####..####', '.#########....................#########.', '..########....................########..', '...##################################...', '.....##############################.....'] # patinha do site (assets/paw4.png, 17x17), desenhada na tela em meio pixel _PAW = ['.....##...##.....', '....####.####....', '....####.####....', '.#..####.####..#.', '###.####.####.###', '###.####.####.###', '###..##...##..###', '###...........###', '.#....#####....#.', '.....#######.....', '....#########....', '...###########...', '..#############..', '..#############..', '..#############..', '..###.#####.###..', '...#...###...#...'] def _runs(rows, fill, dx=0, dy=0, k=1): out = [] for y, row in enumerate(rows): x = 0 while x < len(row): if row[x] == '#': x0 = x while x < len(row) and row[x] == '#': x += 1 out.append(f'') else: x += 1 return f'' + ''.join(out) + '' def vita_svg(width, anim=True): """O Vita grande da modal: corpo branco, a patinha na tela e os botões acendendo.""" lit = lambda x, y, w, h, cls: f'' parts = [ '', _runs(_VITA, '#ffffff'), # botões e analógicos (os recortes acendem em sequência) lit(4, 4, 2, 6, 'wr-vb0'), lit(2, 6, 6, 2, 'wr-vb0'), lit(4, 12, 2, 2, 'wr-vb5'), lit(34, 4, 2, 2, 'wr-vb1'), lit(36, 6, 2, 2, 'wr-vb2'), lit(34, 8, 2, 2, 'wr-vb3'), lit(32, 6, 2, 2, 'wr-vb4'), lit(34, 12, 2, 2, 'wr-vb5'), '' + _runs(_PAW, '#ffffff', dx=20 - 17 * .25, dy=9 - 17 * .25, k=.5) + '', ] cls = ' class="wr-vanim"' if anim else '' return (f'