#!/usr/bin/env python3 """Idempotently inject the HomeDash stylesheet and script into Dashy's index.html. Dashy's index.html does not always contain a `` tag. A naive `sed s##...#` therefore silently drops the injected script (and the `` marker itself). This script inserts before ``/`` when those exist, otherwise before ``, and restores a missing ``. """ import re import sys CSS_TAG = '' JS_TAG = '' # Dashy 自带的 logo(/web-icons/favicon-*.png)会被浏览器优先选中, # 于是站点标签栏显示上游 logo 而不是我们的纸飞机。 # 做法:删掉那些 ,再显式指向我们自己的 /favicon.svg。 # 为什么用“删掉”而不是“改路径”:index.html 来自上游镜像,每次重建可能被重置, # 删标签幂等,且不依赖上游将来还叫 web-icons。 ICON_LINK_RE = re.compile(r'[ \t]*]*rel=["\']icon["\'][^>]*>\s*', re.I) OUR_ICONS = ('\n' '') def patch(html: str) -> str: html = re.sub(r'[ \t]*\s*', '', html) html = re.sub(r'[ \t]*\s*', '', html) html = re.sub(r'[ \t]*' + re.escape(OUR_ICONS) + r'\s*', '', html) html = ICON_LINK_RE.sub('', html) if '' in html: html = html.replace('', CSS_TAG + OUR_ICONS + '', 1) if '' in html: html = html.replace('', JS_TAG + '', 1) elif '' in html: html = html.replace('', JS_TAG + '\n\n', 1) else: html = html + '\n' + JS_TAG + '\n' return html def main(path: str) -> int: with open(path, encoding='utf-8') as fh: original = fh.read() patched = patch(original) if 'href="/navi.css"' not in patched or 'src="/navi.js"' not in patched: print('patch failed: tags missing after patch', file=sys.stderr) return 1 if 'web-icons/favicon' in patched: print('patch failed: upstream Dashy icon links survived', file=sys.stderr) return 1 if '/favicon.svg' not in patched: print('patch failed: our icon link missing', file=sys.stderr) return 1 with open(path, 'w', encoding='utf-8') as fh: fh.write(patched) print('patched %s (%s)' % (path, 'changed' if patched != original else 'unchanged')) return 0 if __name__ == '__main__': raise SystemExit(main(sys.argv[1] if len(sys.argv) > 1 else '/app/dashy/index.html'))