#!/usr/bin/env python3 """Generates the landing page of pkgs.r4ven.me: index.html with the package list, download links and setup blocks. Usage: gen_index.py [output index.html] Reads /catalog.json (written by scripts/sign_repo.sh) and /apk/catalog.json (written by scripts/sign_apk.sh) and lists the newest version of each package. Descriptions in two languages are in DESCRIPTIONS below; a package that is not listed there uses its own summary. The style follows the maintainer's sites (Nord theme, light and dark). """ import html import json import re import sys from pathlib import Path BASE = 'https://pkgs.r4ven.me' FORMATS = ('deb', 'rpm', 'arch', 'apk') DESCRIPTIONS = { 'korterm': ('Терминал с GPU-рендерингом, вкладками, сплитами и плагинами', 'Terminal emulator with GPU rendering, tabs, splits and plugins'), 'luci-app-ocserv-r4ven-me': ('Интерфейс LuCI для сервера OpenConnect VPN (ocserv)', 'LuCI interface for the OpenConnect VPN server (ocserv)'), 'kmod-amneziawg-r4ven-me': ('Модуль ядра AmneziaWG (под ядро OpenWrt 25.12.6)', 'AmneziaWG kernel module (for the OpenWrt 25.12.6 kernel)'), 'amneziawg-tools-r4ven-me': ('Утилиты AmneziaWG: awg и помощник протокола netifd', 'AmneziaWG tools: awg and the netifd protocol helper'), 'luci-proto-amneziawg-r4ven-me': ('Поддержка протокола AmneziaWG в LuCI', 'AmneziaWG protocol support for LuCI'), 'luci-app-amneziawg-r4ven-me': ('Интерфейс LuCI для управления пирами AmneziaWG', 'LuCI interface for AmneziaWG peers'), 'luci-i18n-amneziawg-ru-r4ven-me': ('Русский перевод интерфейса AmneziaWG', 'Russian translation of the AmneziaWG interface'), 'luci-theme-kornord-r4ven-me': ('Тема LuCI Kornord в цветах Nord', 'Kornord LuCI theme in Nord colors'), } def _order(ch): if ch == '~': return -1 if ch.isalpha(): return ord(ch) return ord(ch) + 256 def _compare_part(a, b): """Compares two parts of a Debian version the way dpkg does.""" while a or b: da = re.match(r'\D*', a).group() db = re.match(r'\D*', b).group() a, b = a[len(da):], b[len(db):] for x, y in zip(da.ljust(len(db), '\0'), db.ljust(len(da), '\0')): ox = 0 if x == '\0' else _order(x) oy = 0 if y == '\0' else _order(y) if ox != oy: return -1 if ox < oy else 1 na = re.match(r'\d*', a).group() nb = re.match(r'\d*', b).group() a, b = a[len(na):], b[len(nb):] ia, ib = int(na or 0), int(nb or 0) if ia != ib: return -1 if ia < ib else 1 return 0 def version_key(version): """A sort key for Debian versions: epoch, upstream version, revision.""" from functools import cmp_to_key epoch, _, rest = version.rpartition(':') upstream, _, revision = rest.rpartition('-') if '-' in rest else (rest, '', '') parts = (int(epoch or 0), upstream, revision) def compare(x, y): if x[0] != y[0]: return -1 if x[0] < y[0] else 1 return _compare_part(x[1], y[1]) or _compare_part(x[2], y[2]) return cmp_to_key(compare)(parts) def human(n): """Size as a two-language span: the unit depends on the page language.""" units = (('Б', 'B'), ('КБ', 'KB'), ('МБ', 'MB')) k = 0 while n >= 1024 and k < len(units) - 1: n /= 1024 k += 1 num = f'{n:.0f}' if k == 0 else f'{n:.1f}' return f'{num} {units[k][0]}{units[k][1]}' SETUPS = { 'deb': """sudo install -d -m 0755 /etc/apt/keyrings sudo curl -fsSL {{BASE}}/{{KEY}} -o /etc/apt/keyrings/r4ven-pkgs.asc sudo tee /etc/apt/sources.list.d/r4ven.sources << EOF Types: deb URIs: {{BASE}}/deb Suites: stable Components: main Signed-By: /etc/apt/keyrings/r4ven-pkgs.asc EOF sudo apt update sudo apt install {{FIRST}}""", 'rpm': """sudo tee /etc/yum.repos.d/r4ven.repo << 'EOF' [r4ven] name=r4ven.me packages baseurl={{BASE}}/rpm/$basearch enabled=1 gpgcheck=1 repo_gpgcheck=1 gpgkey={{BASE}}/{{KEY}} EOF sudo dnf install {{FIRST}}""", 'arch': """curl -fsSL {{BASE}}/{{KEY}} | sudo pacman-key --add - sudo pacman-key --lsign-key {{FP}} sudo tee -a /etc/pacman.conf << 'EOF' [r4ven] Server = {{BASE}}/arch/$arch EOF sudo pacman -Sy {{FIRST}}""", 'apk': """wget -O /etc/apk/keys/r4ven-apk.pub {{BASE}}/apk/r4ven-apk.pub echo {{BASE}}/{{APKDIR}}/packages.adb > /etc/apk/repositories.d/r4ven.list apk update apk add {{FIRST}}""", } LABELS = {'deb': 'deb · Debian, Ubuntu, Mint', 'rpm': 'rpm · Fedora, RHEL', 'arch': 'pacman · Arch', 'apk': 'apk · OpenWrt, Alpine'} TOKEN = re.compile( r'(?Phttps?://[^\s"\']+)' r'|(?P(?(?<=\s)--?[A-Za-z][\w-]*)' r'|(?P\b0[0-7]{3}\b)' r'|(?P[A-Za-z][\w.-]*)' r'|(?P<<)' ) def _span(cls, text): return f'{html.escape(text)}' def _shell_line(line): """One shell line: sudo and the heredoc are keywords, the command after sudo stands out.""" out, pos, expect_cmd = [], 0, True for m in TOKEN.finditer(line): out.append(html.escape(line[pos:m.start()])) kind, text = m.lastgroup, m.group() if kind == 'word': if text == 'sudo' and expect_cmd: out.append(_span('kw', text)) elif text == 'EOF': out.append(_span('kw', text)) elif expect_cmd: out.append(_span('cmd', text)) expect_cmd = False else: out.append(html.escape(text)) expect_cmd = False elif kind == 'url' or kind == 'path': out.append(_span('str', text)) expect_cmd = False elif kind == 'op': out.append(_span('kw', text)) else: out.append(_span(kind, text)) expect_cmd = False pos = m.end() out.append(html.escape(line[pos:])) return ''.join(out) def highlight(code): """Highlights shell commands; the body of a heredoc is one colour, as a string. Plain regular expressions, no scripts on the page.""" lines, in_heredoc = [], False for line in code.splitlines(): if in_heredoc: if line.strip() == 'EOF': in_heredoc = False lines.append(_span('kw', line)) continue lines.append(_span('str', line)) continue lines.append(_shell_line(line)) if re.search(r"<<\s*'?EOF'?", line): in_heredoc = True return '\n'.join(lines) def sha_of(site, file): """The SHA-256 from the .sha256 next to a package, or an empty string.""" path = site / (file + '.sha256') parts = path.read_text(encoding='utf-8').split() if path.exists() else [] return parts[0] if parts and re.fullmatch(r'[0-9a-f]{64}', parts[0]) else '' def main(): site = Path(sys.argv[1]) out = Path(sys.argv[2]) if len(sys.argv) > 2 else site / 'index.html' catalog_file = site / 'catalog.json' catalog = json.loads(catalog_file.read_text(encoding='utf-8')) if catalog_file.exists() else {} apk_file = site / 'apk' / 'catalog.json' apk_entries = json.loads(apk_file.read_text(encoding='utf-8'))['packages'] if apk_file.exists() else [] entries = catalog.get('packages', []) + apk_entries catalog.setdefault('key', 'r4ven-pkgs.asc') catalog.setdefault('fingerprint', '') if not entries: sys.exit('no packages in catalog.json') for e in entries: if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9+._-]*', e['name']): sys.exit(f'invalid package name in catalog.json: {e["name"]!r}') # the newest version of each package per format and architecture newest = {} for e in entries: key = (e['name'], e['format'], e['arch']) if key not in newest or version_key(e['version']) > version_key(newest[key]['version']): newest[key] = e names = {} for e in newest.values(): names.setdefault(e['name'], []).append(e) order = list(DESCRIPTIONS) ordered = sorted(names, key=lambda n: (order.index(n) if n in order else 99, n)) formats = [f for f in FORMATS if any(e['format'] == f for e in entries)] rows = [] for name in ordered: items = sorted(names[name], key=lambda e: (FORMATS.index(e['format']), e['arch'])) ru, en = DESCRIPTIONS.get(name, (items[0]['summary'], items[0]['summary'])) home = next((e['url'] for e in items if re.match(r'https?://', e['url'] or '')), '') link = f' · web' if home else '' sums = ''.join( f'{e["format"]} {html.escape(e["arch"])} {html.escape(sha_of(site, e["file"]))} ' f'.sha256' for e in items if sha_of(site, e['file'])) chips = ''.join( f'{e["format"]} {html.escape(e["arch"])}' for e in items) version = max((e['version'] for e in items), key=version_key) rows.append( '
  • ' f'{html.escape(name)}' f'{html.escape(ru)}{html.escape(en)}' f'{chips}{sums}
    ' f'{html.escape(version)}{link}
  • ' ) radios = ''.join(f'' for i, f in enumerate(formats)) labels = ''.join(f'' for f in formats) blocks = [] for f in formats: first = next(n for n in ordered if any(e['format'] == f for e in names[n])) apk_dir = next((e['file'].rsplit('/', 1)[0] for e in entries if e['format'] == 'apk'), 'apk/25.12/x86_64') code = (SETUPS[f].replace('{{BASE}}', BASE).replace('{{KEY}}', catalog['key']) .replace('{{FP}}', catalog['fingerprint']).replace('{{FIRST}}', first) .replace('{{APKDIR}}', apk_dir)) blocks.append(f'
    {highlight(code)}
    ') tab_css = ''.join(f'#t-{f}:checked~#p-{f}{{display:block}}#t-{f}:checked~.tab-labels label[for=t-{f}]{{border-color:var(--primary);color:var(--fg)}}' for f in formats) page = (TEMPLATE.replace('{{PACKAGES}}', '\n'.join(rows)) .replace('{{TABS}}', radios + f'
    {labels}
    ' + ''.join(blocks)) .replace('{{TABCSS}}', tab_css) .replace('{{FORMATS}}', ', '.join(formats)) .replace('{{APKKEY}}', ' · apk: r4ven-apk.pub' if 'apk' in formats else '') .replace('{{KEYBIN}}', re.sub(r'\.asc$', '.gpg', catalog['key'])) .replace('{{KEY}}', catalog['key']) .replace('{{FP}}', catalog['fingerprint'])) out.write_text(page, encoding='utf-8') print(f'{out}: {len(ordered)} package(s)') TEMPLATE = ''' Репозитории пакетов | Вороний блог

    Репозитории пакетовPackage repositories

    Форматы: {{FORMATS}}. Все пакеты и индексы подписаны ключомFormats: {{FORMATS}}. All packages and indexes are signed with the key r4ven-pkgs.asc / .gpg ({{FP}}){{APKKEY}}.

    ПодключениеSetup

    {{TABS}}

    ПакетыPackages

      {{PACKAGES}}
    Подпись. Для .sources нужен Debian 12+ или Ubuntu 22.04+. Для pacman ключ нужно один раз доверить командой pacman-key --lsign-key.Signing. The .sources file needs Debian 12+ or Ubuntu 22.04+. pacman needs the key to be trusted once with pacman-key --lsign-key.
    Обновления приходят обычнымUpdates come with the usual apt upgrade, dnf upgrade, pacman -Syu. ИсходникиSource
    ''' if __name__ == '__main__': main()