2026-11-12-https-link-cleanup.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. #!/usr/bin/env python3
  2. """Safely normalize school-domain HTTP links to HTTPS.
  3. The script never rewrites third-party HTTP URLs automatically. It writes a report
  4. with external hosts so they can be reviewed separately.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import collections
  9. import hashlib
  10. import json
  11. import os
  12. import re
  13. import shutil
  14. import stat
  15. import tempfile
  16. from pathlib import Path
  17. TEXT_SUFFIXES = {
  18. ".css",
  19. ".htm",
  20. ".html",
  21. ".jsp",
  22. ".jspf",
  23. ".js",
  24. ".json",
  25. ".properties",
  26. ".txt",
  27. ".vue",
  28. ".xml",
  29. }
  30. MAX_BYTES = 32 * 1024 * 1024
  31. SCHOOL_URL = re.compile(
  32. r"http://(?P<host>(?:[A-Za-z0-9-]+\.)*gzhxtc\.edu\.cn)(?::(?P<port>\d+))?",
  33. re.IGNORECASE,
  34. )
  35. SPECIAL_REWRITES = (
  36. (re.compile(r"http://xg\.gzhxtc\.edu\.cn:4106/", re.IGNORECASE), "https://xg.gzhxtc.edu.cn/"),
  37. )
  38. ANY_HTTP_URL = re.compile(r"http://(?P<host>[^/\s\"'<>?#]+)", re.IGNORECASE)
  39. def decode_text(data: bytes) -> tuple[str, str]:
  40. if data.startswith(b"\xef\xbb\xbf"):
  41. return data.decode("utf-8-sig"), "utf-8-sig"
  42. if data.startswith((b"\xff\xfe", b"\xfe\xff")):
  43. return data.decode("utf-16"), "utf-16"
  44. for encoding in ("utf-8", "gb18030"):
  45. try:
  46. return data.decode(encoding), encoding
  47. except UnicodeDecodeError:
  48. continue
  49. raise UnicodeDecodeError("unknown", b"", 0, 1, "unsupported text encoding")
  50. def rewrite_school_urls(text: str) -> tuple[str, int]:
  51. count = 0
  52. for pattern, replacement in SPECIAL_REWRITES:
  53. text, special_count = pattern.subn(replacement, text)
  54. count += special_count
  55. def replace(match: re.Match[str]) -> str:
  56. nonlocal count
  57. port = match.group("port")
  58. if port and port not in {"80", "443"}:
  59. return match.group(0)
  60. count += 1
  61. suffix = ":443" if port == "443" else ""
  62. return f"https://{match.group('host')}{suffix}"
  63. return SCHOOL_URL.sub(replace, text), count
  64. def collect_external_hosts(text: str, host_counts: collections.Counter[str], samples: dict[str, str]) -> None:
  65. for match in ANY_HTTP_URL.finditer(text):
  66. host = match.group("host").lower()
  67. host_name = host.rsplit(":", 1)[0] if ":" in host else host
  68. if host_name.endswith(".gzhxtc.edu.cn") or host_name == "gzhxtc.edu.cn":
  69. continue
  70. host_counts[host] += 1
  71. samples.setdefault(host, match.group(0))
  72. def phase_roots(root: Path, phase: str) -> list[Path]:
  73. if phase == "templates":
  74. candidates = [
  75. "web/subassembly/website",
  76. "web/upload/ffkj-template",
  77. "main",
  78. "WEB-INF",
  79. "apps",
  80. "js",
  81. "css",
  82. ]
  83. elif phase == "content":
  84. candidates = ["web/upload"]
  85. else:
  86. candidates = phase_roots(root, "templates") + phase_roots(root, "content")
  87. return [root / candidate for candidate in candidates if (root / candidate).exists()]
  88. def iter_text_files(roots: list[Path], phase: str, root: Path) -> list[Path]:
  89. seen: set[Path] = set()
  90. files: list[Path] = []
  91. template_upload = (root / "web/upload/ffkj-template").resolve()
  92. for base in roots:
  93. for path in base.rglob("*"):
  94. if not path.is_file() or path.suffix.lower() not in TEXT_SUFFIXES:
  95. continue
  96. if path.name.startswith("._") or any(
  97. part.lower() == "backup" or part == ".zq-quarantine" or part.startswith(".zq-stage-")
  98. for part in path.parts
  99. ):
  100. continue
  101. resolved = path.resolve()
  102. if phase == "content" and (resolved == template_upload or template_upload in resolved.parents):
  103. continue
  104. try:
  105. if path.stat().st_size > MAX_BYTES:
  106. continue
  107. except OSError:
  108. continue
  109. if resolved not in seen:
  110. seen.add(resolved)
  111. files.append(path)
  112. return sorted(files)
  113. def apply_file(path: Path, root: Path, backup_root: Path, manifest) -> tuple[int, bool, str | None]:
  114. original = path.read_bytes()
  115. try:
  116. text, encoding = decode_text(original)
  117. except UnicodeDecodeError:
  118. return 0, False, "unsupported-encoding"
  119. rewritten, count = rewrite_school_urls(text)
  120. if count == 0 or rewritten == text:
  121. return 0, False, None
  122. rel = path.relative_to(root)
  123. backup_path = backup_root / rel
  124. backup_path.parent.mkdir(parents=True, exist_ok=True)
  125. shutil.copy2(path, backup_path)
  126. new_data = rewritten.encode(encoding)
  127. mode = stat.S_IMODE(path.stat().st_mode)
  128. fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
  129. try:
  130. with os.fdopen(fd, "wb") as handle:
  131. handle.write(new_data)
  132. os.chmod(temp_name, mode)
  133. os.replace(temp_name, path)
  134. finally:
  135. if os.path.exists(temp_name):
  136. os.unlink(temp_name)
  137. manifest.write(
  138. json.dumps(
  139. {
  140. "path": str(rel),
  141. "replacements": count,
  142. "old_sha256": hashlib.sha256(original).hexdigest(),
  143. "new_sha256": hashlib.sha256(new_data).hexdigest(),
  144. "backup": str(backup_path),
  145. },
  146. ensure_ascii=False,
  147. )
  148. + "\n"
  149. )
  150. return count, True, None
  151. def main() -> int:
  152. parser = argparse.ArgumentParser()
  153. parser.add_argument("--root", required=True)
  154. parser.add_argument("--phase", choices=("templates", "content", "all"), default="all")
  155. parser.add_argument("--apply", action="store_true")
  156. parser.add_argument("--backup-root")
  157. parser.add_argument("--manifest")
  158. parser.add_argument("--report")
  159. args = parser.parse_args()
  160. root = Path(args.root).resolve()
  161. roots = phase_roots(root, args.phase)
  162. files = iter_text_files(roots, args.phase, root)
  163. host_counts: collections.Counter[str] = collections.Counter()
  164. host_samples: dict[str, str] = {}
  165. changed_files = 0
  166. files_with_school_http = 0
  167. school_http_files: list[dict[str, object]] = []
  168. replacements = 0
  169. skipped: collections.Counter[str] = collections.Counter()
  170. manifest_handle = None
  171. if args.apply:
  172. if not args.backup_root or not args.manifest:
  173. parser.error("--apply requires --backup-root and --manifest")
  174. Path(args.backup_root).mkdir(parents=True, exist_ok=True)
  175. Path(args.manifest).parent.mkdir(parents=True, exist_ok=True)
  176. manifest_handle = Path(args.manifest).open("w", encoding="utf-8")
  177. try:
  178. for path in files:
  179. try:
  180. text, _ = decode_text(path.read_bytes())
  181. except (OSError, UnicodeDecodeError) as exc:
  182. skipped[type(exc).__name__] += 1
  183. continue
  184. collect_external_hosts(text, host_counts, host_samples)
  185. try:
  186. if args.apply:
  187. count, changed, reason = apply_file(path, root, Path(args.backup_root), manifest_handle)
  188. else:
  189. _, count = rewrite_school_urls(text)
  190. changed, reason = False, None
  191. except OSError as exc:
  192. skipped[type(exc).__name__] += 1
  193. continue
  194. if reason:
  195. skipped[reason] += 1
  196. replacements += count
  197. if count:
  198. files_with_school_http += 1
  199. school_http_files.append({"path": str(path.relative_to(root)), "count": count})
  200. if changed:
  201. changed_files += 1
  202. finally:
  203. if manifest_handle:
  204. manifest_handle.close()
  205. report = {
  206. "root": str(root),
  207. "phase": args.phase,
  208. "apply": args.apply,
  209. "scanned_files": len(files),
  210. "changed_files": changed_files,
  211. "files_with_school_http": files_with_school_http,
  212. "school_http_files": school_http_files,
  213. "school_http_replacements": replacements,
  214. "skipped": dict(skipped),
  215. "external_http_hosts": [
  216. {"host": host, "count": count, "sample": host_samples.get(host, "")}
  217. for host, count in host_counts.most_common()
  218. ],
  219. }
  220. output = json.dumps(report, ensure_ascii=False, indent=2)
  221. if args.report:
  222. Path(args.report).parent.mkdir(parents=True, exist_ok=True)
  223. Path(args.report).write_text(output + "\n", encoding="utf-8")
  224. print(output)
  225. return 0
  226. if __name__ == "__main__":
  227. raise SystemExit(main())