Rebuild videoreg as source-backed SVK technical library V2 candidate
This commit is contained in:
1 parent
056f1a6462
commit
d0fd7068bb
233 files changed
+6803
-42
No files matched your search
@@ -0,0 +1,26 @@
|
||||
async page => {
|
||||
const base='http://127.0.0.1:50541';
|
||||
const errors=[];page.on('pageerror', e=>errors.push(e.message));
|
||||
const checks=[];
|
||||
function check(name,ok,actual){checks.push({name,passed:!!ok,actual});if(!ok) throw new Error(name+': '+JSON.stringify(actual));}
|
||||
await page.setViewportSize({width:360,height:800});
|
||||
await page.goto(base+'/library');
|
||||
await page.locator('#library-query').fill('GPS');
|
||||
let count=await page.locator('.search-results>a').count();check('full body search GPS',count>0,count);
|
||||
await page.locator('#library-query').fill('невозможныйзапрос98765');check('unknown search empty',await page.locator('.empty').isVisible(),await page.locator('.result-count').innerText());
|
||||
await page.getByRole('button',{name:'Показать все материалы'}).click();count=await page.locator('.search-results>a').count();check('reset all articles',count>=27,count);
|
||||
const category=await page.locator('#library-category option').nth(1).textContent();await page.locator('#library-category').selectOption({label:category});const kinds=await page.locator('.search-kind').allTextContents();check('category filter',kinds.length>0&&kinds.every(k=>k.includes(category)),{category,kinds});
|
||||
await page.getByRole('button',{name:'Сбросить',exact:true}).click();
|
||||
await page.locator('#library-query').focus();await page.keyboard.press('Tab');check('keyboard search reset',await page.evaluate(()=>document.activeElement?.textContent?.trim()==='Сбросить'),await page.evaluate(()=>document.activeElement?.outerHTML));
|
||||
await page.goto(base+'/tools/recording-time');
|
||||
await page.getByLabel('Ёмкость носителя, ГБ').fill('1');await page.getByLabel('Средний размер одного JPEG, КБ').fill('100');await page.getByLabel('Кадров/с на камеру').fill('5');await page.getByLabel('Число камер').fill('2');await page.getByLabel('Резерв места, %').fill('0');
|
||||
let result=await page.locator('.time-result strong').innerText();check('JPEG known result',result==='0 ч 16 мин 40 с',result);
|
||||
await page.getByLabel('Число камер').fill('1.5');result=await page.locator('.time-result strong').innerText();check('fractional cameras rejected',result==='Проверьте значения',result);
|
||||
await page.getByLabel('Число камер').fill('2');await page.getByLabel('Ёмкость носителя, ГБ').fill('');check('empty capacity rejected',(await page.locator('.time-result strong').innerText())==='Проверьте значения');
|
||||
await page.getByLabel('Видеопоток',{exact:true}).check();await page.getByLabel('Ёмкость носителя, ГБ').fill('128');await page.getByLabel('Суммарный битрейт, Мбит/с').fill('40');await page.getByLabel('Резерв места, %').fill('10');result=await page.locator('.time-result strong').innerText();check('stream known result',result==='6 ч 24 мин 0 с',result);
|
||||
await page.getByLabel('Резерв места, %').fill('100');check('full reserve rejected',(await page.locator('.time-result strong').innerText())==='Проверьте значения');
|
||||
await page.goto(base+'/samples/rain');const before=await page.locator('.frame-gallery img').count();const show=page.getByRole('button',{name:/Показать/});await show.click();const after=await page.locator('.frame-gallery img').count();check('gallery expands actual recovered frames',before===6&&after>before,{before,after});
|
||||
const missing=await page.goto(base+'/this-original-page-does-not-exist');check('real404',missing.status()===404,missing.status());
|
||||
check('no browser runtime errors',errors.length===0,errors);
|
||||
return {base,viewport:{width:360,height:800},checks,errors};
|
||||
}
|
||||
@@ -0,0 +1,558 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Audit the entire exported candidate, not a handpicked endpoint sample.
|
||||
|
||||
Run with .local-run/recovery-env/bin/python scripts/rebuild-v2/check-built.py.
|
||||
The crawler never fetches external destinations; exact page/anchor approvals are
|
||||
checked locally. Browser interaction remains a separate, explicitly named check.
|
||||
Unresolved archive inventory produces a blocked restoration result, even when
|
||||
all published-page checks succeed. No build, deployment or Git mutation occurs.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import Counter, defaultdict
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.parse import unquote, urldefrag, urljoin, urlsplit, urlunsplit
|
||||
|
||||
try:
|
||||
from bs4 import BeautifulSoup
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
raise SystemExit("Use .local-run/recovery-env/bin/python; requirements are pinned in scripts/rebuild-v2/requirements.txt")
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
INTERNAL_HOSTS = {"videoreg.ru", "www.videoreg.ru"}
|
||||
ATTRS = ("href", "src", "poster", "action", "formaction", "data", "cite", "background", "longdesc", "manifest", "xlink:href")
|
||||
CSS_URL = re.compile(r"url\(\s*(['\"]?)(.*?)\1\s*\)", re.I | re.S)
|
||||
CSS_IMPORT = re.compile(r"@import\s+(['\"])(.*?)\1", re.I)
|
||||
JS_STRING = re.compile(r'"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'')
|
||||
ABSOLUTE_URL = re.compile(r"(?:https?:)?//[^\s<>\"'`\\]+", re.I)
|
||||
SOURCE_ATTR = re.compile(r"\b(href|src|poster|action|formaction)\s*=\s*(?:\{\s*)?[\"']([^\"']+)[\"']", re.I)
|
||||
SPAM = re.compile(r"казино|покер|онлайн[ -]?ставк|ставки на спорт|payday loan|buy viagra|порно|букмекер", re.I)
|
||||
ERROR_BODY = re.compile(r"wayback machine (?:has not|hasn.t)|this url has been excluded|access denied|too many requests|just a moment\.\.\.|page cannot be crawled", re.I)
|
||||
SELF_REFERENCE = re.compile(r"(?:создан[аоы]?|нарисован[аоы]?|написан[аоы]?)\s+(?:в\s+)?2026|created by AI|сгенерирован[аоы]? (?:ИИ|AI)", re.I)
|
||||
|
||||
|
||||
def sha(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def read_json(path: Path, default):
|
||||
return json.loads(path.read_text()) if path.is_file() else default
|
||||
|
||||
|
||||
def confined(path: Path, root: Path) -> Path | None:
|
||||
try:
|
||||
resolved = path.resolve(strict=False)
|
||||
resolved.relative_to(root.resolve())
|
||||
return resolved
|
||||
except (ValueError, OSError, RuntimeError):
|
||||
return None
|
||||
|
||||
|
||||
def tree_manifest(root: Path, predicate=lambda p: True):
|
||||
entries = []
|
||||
rejected = []
|
||||
if root.exists():
|
||||
for path in sorted(root.rglob("*")):
|
||||
if not path.is_file() or not predicate(path):
|
||||
continue
|
||||
selected = confined(path, root)
|
||||
if selected is None:
|
||||
rejected.append(str(path.relative_to(root)))
|
||||
continue
|
||||
entries.append({"path": path.relative_to(root).as_posix(), "sha256": sha(selected.read_bytes()), "bytes": selected.stat().st_size})
|
||||
return entries, rejected
|
||||
|
||||
|
||||
def manifest_hash(entries):
|
||||
return sha(json.dumps(entries, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode())
|
||||
|
||||
|
||||
def route_for(relative: str) -> str:
|
||||
if relative == "index.html":
|
||||
return "/"
|
||||
if relative.endswith("/index.html"):
|
||||
return "/" + relative[:-len("index.html")]
|
||||
return "/" + relative[:-len(".html")]
|
||||
|
||||
|
||||
def normalize_path(path: str) -> str:
|
||||
if path != "/" and path.endswith("/"):
|
||||
return path.rstrip("/")
|
||||
return path or "/"
|
||||
|
||||
|
||||
def split_srcset(value: str):
|
||||
# Data URI commas must not be mistaken for separate candidate URLs.
|
||||
for candidate in re.split(r",\s*(?![^\s]*;base64)", value):
|
||||
candidate = candidate.strip()
|
||||
if candidate:
|
||||
yield candidate.split()[0]
|
||||
|
||||
|
||||
def extract_html(data: bytes, source: str, stage: str):
|
||||
soup = BeautifulSoup(data, "html.parser")
|
||||
occurrences = []
|
||||
for node in soup.find_all(True):
|
||||
context = node.get_text(" ", strip=True)[:240] or node.get("alt", "") or node.name
|
||||
for attribute in ATTRS:
|
||||
value = node.get(attribute)
|
||||
if isinstance(value, str) and value.strip():
|
||||
occurrences.append(dict(stage=stage, sourcePage=source, element=node.name, attribute=attribute, context=context, destination=value.strip()))
|
||||
for attribute in ("srcset", "imagesrcset"):
|
||||
value = node.get(attribute)
|
||||
if isinstance(value, str):
|
||||
for candidate in split_srcset(value):
|
||||
occurrences.append(dict(stage=stage, sourcePage=source, element=node.name, attribute=attribute, context=context, destination=candidate))
|
||||
if node.get("style"):
|
||||
for _, value in CSS_URL.findall(node["style"]):
|
||||
occurrences.append(dict(stage=stage, sourcePage=source, element=node.name, attribute="style:url", context=context, destination=value))
|
||||
if node.name == "style":
|
||||
for _, value in CSS_URL.findall(node.get_text()):
|
||||
occurrences.append(dict(stage=stage, sourcePage=source, element="style", attribute="url", context="embedded stylesheet", destination=value))
|
||||
if node.name == "meta" and str(node.get("http-equiv", "")).lower() == "refresh":
|
||||
refresh = re.search(r"url\s*=\s*(.+)", node.get("content", ""), re.I)
|
||||
if refresh:
|
||||
occurrences.append(dict(stage=stage, sourcePage=source, element="meta", attribute="refresh", context="automatic navigation", destination=refresh.group(1).strip(" '\"")))
|
||||
if node.name == "script" and not node.get("src"):
|
||||
for value in ABSOLUTE_URL.findall(node.get_text()):
|
||||
occurrences.append(dict(stage=stage, sourcePage=source, element="script", attribute="inline-url", context="embedded script string (may be inert serialized data)", destination=value.rstrip("),.;")))
|
||||
return soup, occurrences
|
||||
|
||||
|
||||
def anchor_text(value):
|
||||
# The public template appends a decorative external-link arrow.
|
||||
return re.sub(r"\s+↗$", "", value).strip()
|
||||
|
||||
|
||||
def inert_script_constant(value, context):
|
||||
namespaces = {"http://www.w3.org/1999/xhtml", "http://www.w3.org/2000/svg", "http://www.w3.org/1998/Math/MathML", "http://www.w3.org/1999/xlink", "http://www.w3.org/XML/1998/namespace"}
|
||||
if value in namespaces:
|
||||
return "Exact DOM/XML namespace identifier, not a network request"
|
||||
if value in {"https://github.com/zloirock/core-js", "https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE"} and any(token in context for token in ("license:", "source:", "copyright:")):
|
||||
return "core-js source/license metadata in bundled polyfill"
|
||||
fixtures = {"https://a", "https://a/c%20d?a=1&c=3", "https://a@b", "https://тест", "https://a#б", "https://x"}
|
||||
if value in fixtures and "URL" in context:
|
||||
return "core-js local URL/URLSearchParams conformance fixture; no fetch"
|
||||
if value == "http://n" and ("URL" in context or "getLocationOrigin" in context):
|
||||
return "Next URL parser's local dummy base for server-side normalization"
|
||||
if value in {"https://react.dev/errors/", "https://nextjs.org/docs/messages/", "https://nextjs.org/docs/messages"}:
|
||||
return "Bundled framework error-message documentation prefix, not a resource load"
|
||||
return None
|
||||
|
||||
|
||||
def local_or_external(destination: str, owner: str, base: str):
|
||||
destination = destination.strip()
|
||||
if not destination:
|
||||
return "ignored", None
|
||||
if destination.startswith(("data:", "blob:")):
|
||||
return "embedded", destination
|
||||
if destination.lower().startswith(("javascript:", "vbscript:")):
|
||||
return "unsafe-scheme", destination
|
||||
if destination.startswith(("mailto:", "tel:", "ftp:")):
|
||||
return "external", destination
|
||||
parsed = urlsplit(urljoin(base.rstrip("/") + owner, destination))
|
||||
base_host = urlsplit(base).hostname
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
return "unsupported-scheme", destination
|
||||
if parsed.hostname in INTERNAL_HOSTS | {base_host}:
|
||||
return "local", urlunsplit(("", "", parsed.path or "/", parsed.query, parsed.fragment))
|
||||
return "external", urlunsplit(parsed)
|
||||
|
||||
|
||||
def locate_export(out: Path, url: str):
|
||||
path = unquote(urlsplit(url).path)
|
||||
if "\\" in path or "\x00" in path or ".." in Path(path).parts:
|
||||
return None
|
||||
raw = out / path.lstrip("/")
|
||||
for selected in [raw, Path(str(raw) + ".html"), raw / "index.html"]:
|
||||
resolved = confined(selected, out)
|
||||
if resolved is not None and resolved.is_file():
|
||||
return resolved
|
||||
return None
|
||||
|
||||
|
||||
def body_details(soup, route, error_document=False):
|
||||
title = soup.title.get_text(" ", strip=True) if soup.title else ""
|
||||
main = soup.find("article") or soup.find("main") or soup.body
|
||||
if main is None:
|
||||
return dict(title=title, bodyChars=0, words=0, bodySha256=sha(b""), findings=["missing-main-body"], ids=[])
|
||||
text_soup = BeautifulSoup(str(main), "html.parser")
|
||||
for element in text_soup.select("script,style,nav,header,footer,.related-reading,.contents,[hidden],[aria-hidden=true]"):
|
||||
element.decompose()
|
||||
text = " ".join(text_soup.stripped_strings)
|
||||
normalized = re.sub(r"\s+", " ", text.lower()).strip()
|
||||
findings = []
|
||||
is_article = soup.find("article") is not None
|
||||
if not error_document:
|
||||
if not title:
|
||||
findings.append("missing-title")
|
||||
if is_article and (len(text) < 300 or len(text.split()) < 40):
|
||||
findings.append("thin-article-needs-editorial-review")
|
||||
if ERROR_BODY.search(text):
|
||||
findings.append("possible-archive-or-antibot-error-body")
|
||||
if SPAM.search(text):
|
||||
findings.append("spam-keyword-needs-context-review")
|
||||
if SELF_REFERENCE.search(text):
|
||||
findings.append("self-referential-creation-copy")
|
||||
return dict(title=title, bodyChars=len(text), words=len(text.split()), bodySha256=sha(normalized.encode()), findings=findings, ids=sorted({n.get("id") for n in soup.find_all(id=True)}), article=is_article, images=len(soup.find_all("img")), tables=len(soup.find_all("table")), codeBlocks=len(soup.find_all("pre")))
|
||||
|
||||
|
||||
def active_source_files():
|
||||
src = ROOT / "web-front/src"
|
||||
pending = list((src / "app").rglob("*.tsx")) + list((src / "app").rglob("*.ts"))
|
||||
seen = set()
|
||||
while pending:
|
||||
path = pending.pop()
|
||||
safe = confined(path, src)
|
||||
if safe is None or not safe.is_file() or safe in seen:
|
||||
continue
|
||||
seen.add(safe)
|
||||
if safe.suffix not in (".ts", ".tsx", ".js", ".jsx", ".css"):
|
||||
continue
|
||||
text = safe.read_text()
|
||||
for target in re.findall(r"(?:import|export).*?(?:from\s*)?[\"']([^\"']+)[\"']", text):
|
||||
if target.startswith("@/"):
|
||||
stem = src / target[2:]
|
||||
elif target.startswith("."):
|
||||
stem = safe.parent / target
|
||||
else:
|
||||
continue
|
||||
candidates = [stem, *[Path(str(stem) + suffix) for suffix in (".ts", ".tsx", ".js", ".jsx", ".json", ".css")], stem / "index.ts", stem / "index.tsx"]
|
||||
pending.extend(p for p in candidates if p.is_file())
|
||||
return sorted(seen)
|
||||
|
||||
|
||||
def source_occurrences(files):
|
||||
occurrences = []
|
||||
for path in files:
|
||||
text = path.read_text()
|
||||
relative = path.relative_to(ROOT).as_posix()
|
||||
if path.suffix == ".json":
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
# Approval metadata is reviewed evidence, not an emitted destination.
|
||||
if path.name == "v2-link-approvals.json":
|
||||
continue
|
||||
def visit(value, context=""):
|
||||
if isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
if key in ("href", "src", "poster", "action", "formaction", "url") and isinstance(item, str):
|
||||
occurrences.append(dict(stage="active-source", sourceFile=relative, attribute=key, context=str(value.get("label") or value.get("alt") or context)[:240], destination=item))
|
||||
visit(item, str(value.get("title") or value.get("path") or context))
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
visit(item, context)
|
||||
visit(data)
|
||||
else:
|
||||
for match in SOURCE_ATTR.finditer(text):
|
||||
occurrences.append(dict(stage="active-source", sourceFile=relative, line=text[:match.start()].count("\n") + 1, attribute=match.group(1), context=text[max(0, match.start()-90):match.end()+90].strip()[:240], destination=match.group(2)))
|
||||
for _, value in CSS_URL.findall(text) + CSS_IMPORT.findall(text):
|
||||
occurrences.append(dict(stage="active-source", sourceFile=relative, attribute="css:url", context="stylesheet reference", destination=value))
|
||||
return occurrences
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base", help="Running local or public HTTP base; defaults to .local-run/server.json")
|
||||
parser.add_argument("--origin", help="Explicit diagnostic HTTPS origin IP (requires --insecure-origin for untrusted certificate)")
|
||||
parser.add_argument("--insecure-origin", action="store_true", help="Diagnostic only; never records TLS as verified")
|
||||
parser.add_argument("--out", type=Path, default=ROOT / "web-front/out")
|
||||
parser.add_argument("--inventory", type=Path, default=ROOT / "docs/rebuild-v2/url-inventory.json")
|
||||
parser.add_argument("--approvals", type=Path, default=ROOT / "web-front/src/content/v2-link-approvals.json")
|
||||
parser.add_argument("--report", type=Path, default=ROOT / "docs/rebuild-v2/evidence/built-crawl.json")
|
||||
args = parser.parse_args()
|
||||
base = (args.base or read_json(ROOT / ".local-run/server.json", {}).get("url", "")).rstrip("/")
|
||||
if urlsplit(base).scheme not in ("http", "https") or not urlsplit(base).hostname:
|
||||
parser.error("Provide an http(s) --base or start the local preview")
|
||||
if args.insecure_origin and not args.origin:
|
||||
parser.error("--insecure-origin is allowed only for an explicit diagnostic --origin")
|
||||
out = args.out.resolve()
|
||||
if not out.is_dir():
|
||||
parser.error("Missing export; owner must build candidate first")
|
||||
before, unsafe_files = tree_manifest(out)
|
||||
source_files = active_source_files()
|
||||
source_before = [{"path": p.relative_to(ROOT).as_posix(), "sha256": sha(p.read_bytes())} for p in source_files]
|
||||
approvals = read_json(args.approvals, [])
|
||||
inventory = read_json(args.inventory, [])
|
||||
legacy = read_json(ROOT / "deploy/legacy-routes.json", {})
|
||||
errors = [{"kind": "export-file-outside-root", "file": x} for x in unsafe_files]
|
||||
warnings = []
|
||||
responses = {}
|
||||
http_checks = []
|
||||
request_urls = set()
|
||||
|
||||
def request(url, method="GET"):
|
||||
url = urldefrag(url)[0]
|
||||
key = method, url
|
||||
if key in responses:
|
||||
return responses[key]
|
||||
cmd = ["curl", "-sS", "--max-time", "20", "--path-as-is", "-D", "-", "-w", "\n__VIDEOREG_STATUS__:%{http_code}"]
|
||||
cmd += ["--head"] if method == "HEAD" else ["-X", method]
|
||||
if args.origin:
|
||||
cmd += ["--resolve", f"{urlsplit(base).hostname}:443:{args.origin}"]
|
||||
if args.insecure_origin:
|
||||
cmd += ["-k"]
|
||||
cmd += [base + url]
|
||||
result = subprocess.run(cmd, capture_output=True)
|
||||
status_marker = b"\n__VIDEOREG_STATUS__:"
|
||||
prefix, _, raw_status = result.stdout.rpartition(status_marker)
|
||||
status = int(raw_status) if raw_status.isdigit() else 0
|
||||
# curl can prepend HTTP CONNECT/interim headers; choose final header block.
|
||||
content = prefix
|
||||
headers = {}
|
||||
while content.startswith(b"HTTP/"):
|
||||
boundary = content.find(b"\r\n\r\n")
|
||||
length = 4
|
||||
if boundary < 0:
|
||||
boundary = content.find(b"\n\n"); length = 2
|
||||
if boundary < 0:
|
||||
break
|
||||
header_block, content = content[:boundary], content[boundary+length:]
|
||||
headers = {}
|
||||
for line in header_block.splitlines()[1:]:
|
||||
if b":" in line:
|
||||
name, value = line.split(b":", 1)
|
||||
headers[name.decode().lower()] = value.decode(errors="replace").strip()
|
||||
value = dict(status=status, headers=headers, body=content, returncode=result.returncode, error=result.stderr.decode(errors="replace")[:1000])
|
||||
responses[key] = value
|
||||
request_urls.add(url)
|
||||
http_checks.append(dict(url=url, method=method, status=status, curlReturncode=result.returncode, bytes=len(content), location=headers.get("location"), contentType=headers.get("content-type")))
|
||||
return value
|
||||
|
||||
pages = []
|
||||
occurrences = []
|
||||
script_constants = []
|
||||
asset_checks = []
|
||||
page_by_file = {}
|
||||
for entry in before:
|
||||
relative = entry["path"]
|
||||
if not relative.endswith(".html"):
|
||||
continue
|
||||
path = out / relative
|
||||
data = path.read_bytes()
|
||||
route = route_for(relative)
|
||||
error_document = relative in ("404.html", "_not-found.html")
|
||||
soup, found = extract_html(data, route, "generated-html")
|
||||
detail = body_details(soup, route, error_document)
|
||||
row = dict(file=relative, route=route, sha256=entry["sha256"], bytes=entry["bytes"], errorDocument=error_document, **detail)
|
||||
response = request("/" + relative if error_document else route)
|
||||
row["httpStatus"] = response["status"]
|
||||
row["httpSha256"] = sha(response["body"])
|
||||
if not error_document and response["status"] != 200:
|
||||
errors.append(dict(kind="published-page-http-status", route=route, status=response["status"]))
|
||||
if not error_document and response["status"] == 200 and response["body"] != data:
|
||||
errors.append(dict(kind="http-build-body-mismatch", route=route, file=relative))
|
||||
pages.append(row)
|
||||
page_by_file[path.resolve()] = row
|
||||
occurrences.extend(found)
|
||||
for finding in row["findings"]:
|
||||
warnings.append(dict(kind=finding, route=route))
|
||||
if not pages:
|
||||
errors.append(dict(kind="empty-export-no-html"))
|
||||
|
||||
# Decode every exported raster asset, including unlinked public files.
|
||||
# Files are confined above; PIL verification never executes image content.
|
||||
for entry in before:
|
||||
path = out / entry["path"]
|
||||
if path.suffix.lower() in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico"):
|
||||
try:
|
||||
with Image.open(path) as image:
|
||||
width, height = image.size
|
||||
image.verify()
|
||||
asset_checks.append(dict(file=entry["path"], type="raster", valid=True, width=width, height=height, sha256=entry["sha256"]))
|
||||
except Exception as exc:
|
||||
asset_checks.append(dict(file=entry["path"], type="raster", valid=False, error=str(exc)))
|
||||
errors.append(dict(kind="invalid-raster-image", file=entry["path"], error=str(exc)))
|
||||
elif path.suffix.lower() == ".pdf":
|
||||
data = path.read_bytes()
|
||||
valid = b"%PDF-" in data[:1024] and b"%%EOF" in data[-2048:]
|
||||
asset_checks.append(dict(file=entry["path"], type="pdf-signature-and-eof", valid=valid, sha256=entry["sha256"]))
|
||||
if not valid:
|
||||
errors.append(dict(kind="invalid-pdf-signature", file=entry["path"]))
|
||||
|
||||
# Scan every emitted CSS/JS/SVG, not only those linked from the homepage.
|
||||
for entry in before:
|
||||
path = out / entry["path"]
|
||||
if path.suffix == ".svg":
|
||||
_, found = extract_html(path.read_bytes(), "/" + entry["path"], "generated-svg")
|
||||
occurrences.extend(found)
|
||||
elif path.suffix in (".css", ".js", ".mjs"):
|
||||
text = path.read_text(errors="replace")
|
||||
for _, value in (CSS_URL.findall(text) if path.suffix == ".css" else []):
|
||||
occurrences.append(dict(stage="generated-resource", sourcePage="/" + entry["path"], sourceFile=entry["path"], attribute="css:url", context="emitted resource", destination=value))
|
||||
for _, value in CSS_IMPORT.findall(text):
|
||||
occurrences.append(dict(stage="generated-resource", sourcePage="/" + entry["path"], sourceFile=entry["path"], attribute="css:import", context="emitted stylesheet import", destination=value))
|
||||
if path.suffix in (".js", ".mjs"):
|
||||
for match in JS_STRING.finditer(text):
|
||||
value = match.group(0)[1:-1].replace("\\/", "/")
|
||||
if not re.fullmatch(r"(?:https?:)?//[^\s<>\"'`]+", value):
|
||||
continue
|
||||
context = text[max(0, match.start()-180):match.end()+180]
|
||||
reason = inert_script_constant(value, context)
|
||||
if reason:
|
||||
script_constants.append(dict(sourceFile=entry["path"], destination=value, context=context, classification="inert-code-constant", reviewed=True, reviewer="programmer-code-context", reason=reason))
|
||||
else:
|
||||
occurrences.append(dict(stage="generated-script-string", sourcePage="/" + entry["path"], sourceFile=entry["path"], attribute="inline-url", context=context, destination=value))
|
||||
|
||||
local_refs = []
|
||||
outbound = []
|
||||
for occurrence in occurrences:
|
||||
owner = occurrence.get("sourcePage", "/")
|
||||
kind, destination = local_or_external(occurrence["destination"], owner, base)
|
||||
occurrence["classification"] = kind
|
||||
occurrence["resolvedDestination"] = destination
|
||||
if kind in ("unsafe-scheme", "unsupported-scheme"):
|
||||
errors.append(dict(kind="unsafe-or-unsupported-reference", **occurrence))
|
||||
elif kind == "external":
|
||||
matching = [a for a in approvals if a.get("sourcePage") == owner and a.get("destination") == destination and a.get("anchor") == anchor_text(occurrence.get("context", "")) and a.get("reviewed") is True and a.get("decision") == "keep" and a.get("reason")]
|
||||
if not matching and occurrence["attribute"] == "inline-url":
|
||||
# Next serializes already emitted link props for hydration. This
|
||||
# is approved only when the exact page/URL/anchor was emitted.
|
||||
matching = [a for a in approvals if a.get("sourcePage") == owner and a.get("destination") == destination and a.get("reviewed") is True and a.get("decision") == "keep" and a.get("reason") and any(x.get("sourcePage") == owner and x.get("destination") == destination and anchor_text(x.get("context", "")) == a.get("anchor") and x.get("attribute") == "href" for x in occurrences)]
|
||||
if matching:
|
||||
occurrence["classification"] = "serialized-reference-of-approved-link"
|
||||
occurrence["reviewed"] = bool(matching)
|
||||
occurrence["approvalReason"] = matching[0]["reason"] if matching else None
|
||||
outbound.append(occurrence)
|
||||
if not matching:
|
||||
errors.append(dict(kind="unapproved-external-occurrence", sourcePage=owner, destination=destination, context=occurrence.get("context"), stage=occurrence["stage"]))
|
||||
elif kind == "local":
|
||||
local_refs.append(occurrence)
|
||||
url, fragment = urldefrag(destination)
|
||||
selected = locate_export(out, url)
|
||||
response = request(url)
|
||||
if url in legacy:
|
||||
expected = legacy[url]
|
||||
if response["status"] != 308 or response["headers"].get("location") != expected:
|
||||
errors.append(dict(kind="legacy-reference-mismatch", url=url, expected=expected, status=response["status"], location=response["headers"].get("location")))
|
||||
target_url, target_fragment = urldefrag(expected)
|
||||
selected = locate_export(out, target_url)
|
||||
fragment = target_fragment or fragment
|
||||
elif response["status"] != 200:
|
||||
errors.append(dict(kind="missing-local-reference", sourcePage=owner, destination=destination, status=response["status"], attribute=occurrence["attribute"]))
|
||||
elif selected is None:
|
||||
errors.append(dict(kind="local-reference-not-in-export", sourcePage=owner, destination=destination))
|
||||
if fragment and selected is not None:
|
||||
target = page_by_file.get(selected)
|
||||
if target and unquote(fragment) not in target["ids"]:
|
||||
errors.append(dict(kind="missing-fragment", sourcePage=owner, destination=destination))
|
||||
if selected is not None and response["status"] == 200 and selected not in page_by_file and response["body"] != selected.read_bytes():
|
||||
errors.append(dict(kind="http-asset-body-mismatch", sourcePage=owner, destination=destination))
|
||||
if occurrence.get("element") == "img" and selected is not None and selected.stat().st_size == 0:
|
||||
errors.append(dict(kind="empty-image", sourcePage=owner, destination=destination))
|
||||
|
||||
active_occurrences = source_occurrences(source_files)
|
||||
for occurrence in active_occurrences:
|
||||
kind, destination = local_or_external(occurrence["destination"], "/", base)
|
||||
occurrence["classification"] = kind
|
||||
if kind == "external":
|
||||
occurrence["appearsInExport"] = any(x["resolvedDestination"] == destination for x in outbound)
|
||||
occurrence["exactDestinationApproved"] = any(a.get("destination") == destination and a.get("reviewed") is True and a.get("decision") == "keep" for a in approvals)
|
||||
if not occurrence["appearsInExport"] and not occurrence["exactDestinationApproved"]:
|
||||
errors.append(dict(kind="source-external-not-reviewed", **occurrence))
|
||||
elif kind in ("unsafe-scheme", "unsupported-scheme"):
|
||||
errors.append(dict(kind="unsafe-source-reference", **occurrence))
|
||||
|
||||
duplicates = []
|
||||
grouped = defaultdict(list)
|
||||
for page in pages:
|
||||
if page.get("article") and not page["errorDocument"]:
|
||||
grouped[page["bodySha256"]].append(page["route"])
|
||||
for digest, routes in grouped.items():
|
||||
if len(routes) > 1:
|
||||
duplicates.append(dict(bodySha256=digest, routes=routes))
|
||||
errors.append(dict(kind="duplicate-article-body", routes=routes))
|
||||
|
||||
source_publications = []
|
||||
generated_routes = {normalize_path(p["route"]) for p in pages if not p["errorDocument"]}
|
||||
for source_file in source_files:
|
||||
if source_file.name not in ("v2-articles.json", "v2-community.json"):
|
||||
continue
|
||||
for article in read_json(source_file, []):
|
||||
route = article.get("path")
|
||||
present = normalize_path(route or "") in generated_routes
|
||||
source_publications.append(dict(path=route, title=article.get("title"), sourceFile=source_file.relative_to(ROOT).as_posix(), generated=present))
|
||||
if not present:
|
||||
errors.append(dict(kind="typed-article-not-exported", route=route, sourceFile=source_file.relative_to(ROOT).as_posix()))
|
||||
|
||||
legacy_results = []
|
||||
for original, destination in legacy.items():
|
||||
response = request(original)
|
||||
target, fragment = urldefrag(destination)
|
||||
target_response = request(target)
|
||||
selected = locate_export(out, target)
|
||||
passed = response["status"] == 308 and response["headers"].get("location") == destination and target_response["status"] == 200 and selected is not None
|
||||
if fragment:
|
||||
target_page = page_by_file.get(selected)
|
||||
passed = passed and target_page is not None and fragment in target_page["ids"]
|
||||
legacy_results.append(dict(original=original, destination=destination, status=response["status"], location=response["headers"].get("location"), targetStatus=target_response["status"], passed=bool(passed)))
|
||||
if not passed:
|
||||
errors.append(dict(kind="legacy-route-failed", **legacy_results[-1]))
|
||||
|
||||
behavior = []
|
||||
for path, method, expected in [("/videoreg-v2-definitely-missing-page", "GET", 404), ("/api/videos", "GET", 404), ("/api/videos", "POST", 404), ("/_dev/showcase", "GET", 404), ("/", "HEAD", 200), ("/health/ready", "HEAD", 200), ("/forum/viewtopic.php?t=184&start=20", "GET", 404), ("/forum/viewtopic.php?t=184&highlight=word", "GET", 404), ("/forum/viewtopic.php?t=184&postorder=desc", "GET", 404)]:
|
||||
response = request(path, method)
|
||||
passed = response["status"] == expected
|
||||
behavior.append(dict(path=path, method=method, expected=expected, status=response["status"], passed=passed))
|
||||
if not passed:
|
||||
errors.append(dict(kind="http-behavior-failed", **behavior[-1]))
|
||||
|
||||
inventory_results = []
|
||||
unresolved = []
|
||||
for item in inventory:
|
||||
status = item.get("publicationStatus", "missing-status")
|
||||
destination = item.get("currentDestination")
|
||||
raw = item.get("rawFile")
|
||||
raw_integrity = None
|
||||
if raw and item.get("rawSha256"):
|
||||
raw_path = confined(ROOT / raw, ROOT)
|
||||
raw_integrity = raw_path is not None and raw_path.is_file() and sha(raw_path.read_bytes()) == item["rawSha256"]
|
||||
if not raw_integrity:
|
||||
errors.append(dict(kind="inventory-raw-hash-mismatch", originalUrl=item.get("originalUrl"), file=raw))
|
||||
row = dict(originalUrl=item.get("originalUrl"), type=item.get("type"), status=status, destination=destination, rawHashVerified=raw_integrity, reason=item.get("exclusionOrUnresolvedReason"))
|
||||
if status.startswith("unresolved") or status == "missing-status":
|
||||
unresolved.append(row)
|
||||
elif status.startswith("excluded"):
|
||||
if not item.get("exclusionOrUnresolvedReason"):
|
||||
errors.append(dict(kind="inventory-exclusion-without-reason", originalUrl=item.get("originalUrl")))
|
||||
elif destination:
|
||||
kind, url = local_or_external(destination, "/", base)
|
||||
if kind != "local" or locate_export(out, url) is None:
|
||||
errors.append(dict(kind="inventory-destination-missing", **row))
|
||||
else:
|
||||
row["targetExists"] = True
|
||||
selected = locate_export(out, url)
|
||||
fragment = urlsplit(url).fragment
|
||||
target_page = page_by_file.get(selected)
|
||||
if fragment and target_page and unquote(fragment) not in target_page["ids"]:
|
||||
errors.append(dict(kind="inventory-destination-fragment-missing", **row))
|
||||
else:
|
||||
errors.append(dict(kind="inventory-published-without-destination", **row))
|
||||
inventory_results.append(row)
|
||||
|
||||
after, _ = tree_manifest(out)
|
||||
source_after = [{"path": p.relative_to(ROOT).as_posix(), "sha256": sha(p.read_bytes())} for p in source_files if p.is_file()]
|
||||
if before != after:
|
||||
errors.append(dict(kind="build-mutated-during-check"))
|
||||
if source_before != source_after:
|
||||
errors.append(dict(kind="source-mutated-during-check"))
|
||||
git = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True)
|
||||
report = dict(schemaVersion=1, domain="videoreg.ru", generatedAt=datetime.now(timezone.utc).isoformat(), sourceCommit=git.stdout.strip(), sourceManifestSha256=manifest_hash(source_before), sourceFiles=source_before, exportManifestSha256=manifest_hash(before), exportFileCount=len(before), base=base, origin=args.origin, tlsVerified=False if args.insecure_origin else (True if base.startswith("https://") and all(x["curlReturncode"] == 0 for x in http_checks) else None), browserDOMInspection="not performed by this script; use separate exact-candidate browser evidence", summary=dict(technicalStatus="failed" if errors else "passed", restorationStatus="blocked-unresolved-inventory" if unresolved else "reconciled", acceptance="blocked" if errors or unresolved else "mechanical-checks-only-not-role-approval", htmlFiles=len(pages), contentPages=sum(not p["errorDocument"] for p in pages), HTTPRequests=len(http_checks), localReferences=len(local_refs), emittedExternalOccurrences=len(outbound), activeSourceFiles=len(source_files), inventoryItems=len(inventory), unresolvedInventoryItems=len(unresolved), suspiciousPages=len(warnings), errors=len(errors), decodedRasterAssets=sum(x["type"] == "raster" for x in asset_checks)), pages=pages, assetChecks=asset_checks, duplicateBodies=duplicates, suspiciousCandidates=warnings, errors=errors, localReferences=local_refs, outboundOccurrences=outbound, inertScriptConstants=script_constants, activeSourceReferences=active_occurrences, HTTPChecks=http_checks, legacyRoutes=legacy_results, sourcePublications=source_publications, behavior=behavior, coverage=dict(statusCounts=dict(Counter(x["status"] for x in inventory_results)), items=inventory_results, unresolved=unresolved), limitations=["No external page is fetched by this checker; approvals must contain independent editorial verification.", "HTML/CSS/script-string extraction detects static references. Live JavaScript interactions, crops and browser DOM are checked separately.", "Suspicious thin/spam/error flags require per-page editorial assessment; they are not automatically treated as spam exclusions.", "A reconciled inventory does not establish that the external discovery denominator is complete."])
|
||||
args.report.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.report.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps(dict(report=str(args.report.relative_to(ROOT) if args.report.is_relative_to(ROOT) else args.report), **report["summary"]), ensure_ascii=False))
|
||||
return 1 if errors or unresolved else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Behavioural checks for public path selection using harmless temporary files."""
|
||||
from pathlib import Path
|
||||
import importlib.util,tempfile,unittest
|
||||
spec=importlib.util.spec_from_file_location('preview',Path(__file__).resolve().parents[2]/'deploy/serve-local.py')
|
||||
preview=importlib.util.module_from_spec(spec);spec.loader.exec_module(preview)
|
||||
class PublicSelection(unittest.TestCase):
|
||||
def test_selection_and_boundaries(self):
|
||||
with tempfile.TemporaryDirectory(prefix='videoreg-v2-preview-test-') as d:
|
||||
root=Path(d)/'public';root.mkdir();(root/'guide.html').write_text('public');(root/'auto.shtml.html').write_text('historic');outside=Path(d)/'harmless-test-sentinel.txt';outside.write_text('outside test fixture')
|
||||
self.assertEqual(preview.resolve_public(root,'/guide'),root/'guide.html')
|
||||
self.assertEqual(preview.resolve_public(root,'/auto.shtml'),root/'auto.shtml.html')
|
||||
self.assertEqual(preview.resolve_public(root,'/'),root)
|
||||
for path in ['/../harmless-test-sentinel.txt','/%2e%2e/harmless-test-sentinel.txt','/health/../../harmless-test-sentinel.txt']:
|
||||
self.assertIsNone(preview.resolve_public(root,path),path)
|
||||
(root/'outside.html').symlink_to(outside)
|
||||
self.assertIsNone(preview.resolve_public(root,'/outside'))
|
||||
self.assertIsNone(preview.resolve_public(root,'/outside.html'))
|
||||
def test_only_evidenced_legacy_routes(self):
|
||||
self.assertIsNone(preview.legacy_destination('/auto.shtml'))
|
||||
self.assertEqual(preview.legacy_destination('/forum/viewtopic.php?sid=old&t=184&start=0'),'/community/flash-start')
|
||||
self.assertIsNone(preview.legacy_destination('/forum/viewtopic.php?t=183'))
|
||||
self.assertEqual(preview.legacy_destination('/forum/viewtopic.php?t=183&view=next'),'/community/flash-start')
|
||||
for query in ['t=184&start=20','t=184&postdays=7','t=184&postorder=desc','t=184&highlight=USB','t=184&unknown=value','t=184&t=188']:
|
||||
self.assertIsNone(preview.legacy_destination('/forum/viewtopic.php?'+query),query)
|
||||
self.assertEqual(preview.legacy_destination('/forum/viewtopic.php?postorder=asc&t=184&start=0&sid=expired&highlight='),'/community/flash-start')
|
||||
self.assertIsNone(preview.legacy_destination('/shop/index.php?productID=132&start=20'))
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
from pathlib import Path
|
||||
import json,hashlib,re,sys,concurrent.futures,time
|
||||
from urllib.parse import urlsplit,parse_qsl,urlencode,quote
|
||||
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
|
||||
ROOT=Path(__file__).resolve().parents[2];RAW=ROOT/'docs/rebuild-v2/raw'
|
||||
def normalized(url):
|
||||
u=urlsplit(url);q=[(k,v) for k,v in parse_qsl(u.query) if k!='sid'];return u.path+('?' +urlencode(sorted(q)) if q else '')
|
||||
d=json.loads((RAW/'cdx-domain.json').read_text());groups={}
|
||||
for r in d[1:]:groups.setdefault(normalized(r[2]),[]).append(dict(zip(d[0],r)))
|
||||
plan=[]
|
||||
for path,rows in groups.items():
|
||||
r=rows[0];kind='page';reason=None
|
||||
if '/forum/' in path:
|
||||
kind='forum-topic' if 'viewtopic.php?' in path else 'forum-listing'
|
||||
if not any(x in path for x in ['viewtopic.php?','viewforum.php?','index.php']):reason='phpBB utility/auth/profile/search page, no original technical article body'
|
||||
if '/shop/' in path:
|
||||
kind='historic-product' if 'productID=' in path else 'historic-category'
|
||||
if not any(x in path for x in ['productID=','categoryID=','aux_page=']):reason='Historic cart/shop utility or index; no live sales are being restored; inspect category/product pages separately'
|
||||
if path.startswith('/stat/'):reason='Counter endpoint, excluded from publication'
|
||||
name='pages/'+hashlib.sha256(path.encode()).hexdigest()[:16]+'.html'
|
||||
plan.append(dict(originalUrl=r['original'],normalizedPath=path,type=kind,snapshot=r['timestamp'],rawFile='docs/rebuild-v2/raw/'+name,disposition='excluded-utility' if reason else 'fetch',reason=reason))
|
||||
(ROOT/'docs/rebuild-v2/discovery-plan.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n');(RAW/'pages').mkdir(exist_ok=True)
|
||||
def work(item):
|
||||
dest=ROOT/item['rawFile']
|
||||
if dest.exists() and dest.stat().st_size>500:return {'path':item['normalizedPath'],'cached':True}
|
||||
url='https://web.archive.org/web/'+item['snapshot']+'id_/'+item['originalUrl']
|
||||
return fetch(url,'pages/'+dest.name,timeout=45)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:
|
||||
for out in ex.map(work,[p for p in plan if p['disposition']=='fetch']):pass
|
||||
print('planned',len(plan),'fetch',sum(p['disposition']=='fetch' for p in plan),flush=True)
|
||||
@@ -0,0 +1,17 @@
|
||||
from pathlib import Path
|
||||
import json,sys,hashlib,concurrent.futures
|
||||
from bs4 import BeautifulSoup
|
||||
from urllib.parse import urljoin,urlsplit
|
||||
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';urls=['https://2126.ru/forum/index.php?topic=27783.0','http://mtsc.khpi.edu.ua/article/view/47926','http://www.nissan4x4-club.ru/Forum/NISSAN_4x4/index.php?id=353180','https://forum.zarulem.ws/?showtopic=170164','http://terranoirk.ru/forums/viewtopic.php?p=28099'];out=[]
|
||||
def work(url):
|
||||
name='semrush-referrer-'+hashlib.sha256(url.encode()).hexdigest()[:14]+'.html';rec=fetch(url,name,25);row=dict(url=url,request=rec,purpose='Actual parent-observed Lost andVital backlink lead, not original videoreg body',videoregLinks=[],relatedDocumentLeads=[])
|
||||
if rec['httpStatus']=='200':
|
||||
s=BeautifulSoup((P/rec['raw']).read_bytes(),'html.parser');row['title']=s.title.get_text(' ',strip=True) if s.title else None
|
||||
for tag in s.find_all('a',href=True):
|
||||
target=urljoin(url,tag['href']);context=' '.join(tag.parent.get_text(' ',strip=True).split())[:600]
|
||||
if 'videoreg.ru' in target:row['videoregLinks'].append(dict(target=target,anchor=tag.get_text(' ',strip=True),context=context))
|
||||
elif any(x in target.lower() for x in ['.pdf','.zip','svk','videoreg','svk-lab']):row['relatedDocumentLeads'].append(dict(target=target,anchor=tag.get_text(' ',strip=True),context=context))
|
||||
return row
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:out=list(ex.map(work,urls))
|
||||
(D/'semrush/referrer-verification.json').write_text(json.dumps(dict(scope='5 explicitly supplied public referring URLs out of coordinator-observed18Lost-andVitalrows; remaining13notinvented',rows=out),ensure_ascii=False,indent=2)+'\n');print([(x['url'],x['request']['httpStatus'],len(x['videoregLinks']),len(x['relatedDocumentLeads'])) for x in out])
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse,hashlib,json,subprocess,time
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
RAW=ROOT/'docs/rebuild-v2/raw';RAW.mkdir(parents=True,exist_ok=True)
|
||||
def fetch(url,name,timeout=65):
|
||||
dest=RAW/name;headers=dest.with_suffix(dest.suffix+'.headers')
|
||||
started=time.time()
|
||||
r=subprocess.run(['curl','--compressed','-sS','-L','--max-time',str(timeout),'-D',str(headers),'-o',str(dest),'-w','%{http_code}\n%{url_effective}',url],capture_output=True,text=True)
|
||||
if not dest.exists():dest.write_bytes(b'')
|
||||
b=dest.read_bytes();parts=r.stdout.splitlines()
|
||||
object_dir=RAW/'objects';object_dir.mkdir(exist_ok=True)
|
||||
object_file=object_dir/(hashlib.sha256(b).hexdigest()+'.bin')
|
||||
if not object_file.exists():object_file.write_bytes(b)
|
||||
rec=dict(url=url,raw=str(dest.relative_to(ROOT)),immutableRaw=str(object_file.relative_to(ROOT)),sha256=hashlib.sha256(b).hexdigest(),bytes=len(b),httpStatus=parts[0] if parts else None,effectiveUrl=parts[1] if len(parts)>1 else None,curlExit=r.returncode,error=r.stderr.strip(),checkedAt=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),seconds=round(time.time()-started,2))
|
||||
with (RAW/'requests.jsonl').open('a') as f:f.write(json.dumps(rec,ensure_ascii=False)+'\n')
|
||||
print(json.dumps({k:rec[k] for k in ['raw','httpStatus','bytes','curlExit','error']}),flush=True)
|
||||
return rec
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('url');p.add_argument('name');p.add_argument('--timeout',type=int,default=65);a=p.parse_args();fetch(a.url,a.name,a.timeout)
|
||||
@@ -0,0 +1,105 @@
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit,urljoin,parse_qsl,urlencode,unquote
|
||||
import json,hashlib,re,collections,email.utils
|
||||
from bs4 import BeautifulSoup
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';RAW=D/'raw'
|
||||
plan=json.loads((D/'discovery-plan.json').read_text());by={x['normalizedPath']:x for x in plan}
|
||||
articles=json.loads((P/'web-front/src/content/v2-articles.json').read_text())+json.loads((P/'web-front/src/content/v2-community.json').read_text())
|
||||
routes=json.loads((P/'deploy/legacy-routes.json').read_text());content_dest={src:a['path'] for a in articles for src in a['sourcePaths'] if src.startswith('/')}
|
||||
# Recovered full source cards take precedence over changed later category labels.
|
||||
commercial={'/price.shtml':'Historic sale prices, installer promotions and phone numbers removed. Models retained in /system and /catalog.', '/where.shtml':'Historic dealer/contact advertisements, including unrelated casino/HVAC paid links; no original technical article body.', '/shop/index.php?aux_page=aux1':'Historic ordering instructions and sales contacts, no technical body.', '/shop/index.php?aux_page=aux2':'Historic payment/delivery/consumer-terms page; obsolete commerce/terms not republished as current advice.'}
|
||||
source_outbound=[];new_leads={};raw_integrity=[]
|
||||
def norm(url):
|
||||
u=urlsplit(url);params=[(k,v) for k,v in parse_qsl(u.query) if k!='sid'];return u.path+('?' +urlencode(sorted(params)) if params else '')
|
||||
def canonical(url):return urlsplit(url).hostname in ('videoreg.ru','www.videoreg.ru')
|
||||
def actual_snapshot(file,fallback):
|
||||
h=Path(str(file)+'.headers')
|
||||
if h.exists():
|
||||
m=re.findall(r'(?im)^memento-datetime:\s*(.+)$',h.read_text(errors='replace'))
|
||||
if m:
|
||||
try:return email.utils.parsedate_to_datetime(m[-1].strip()).strftime('%Y%m%d%H%M%S')
|
||||
except:pass
|
||||
return fallback
|
||||
audit_plan=list(plan)
|
||||
known_raw={x['rawFile'] for x in audit_plan}
|
||||
for article in articles:
|
||||
for raw_file in article['rawFiles']:
|
||||
if raw_file.endswith('.html') and raw_file not in known_raw:
|
||||
known_raw.add(raw_file)
|
||||
original=next((p for p in article['sourcePaths'] if p.startswith('http')), 'http://www.videoreg.ru'+article['sourcePaths'][0] if article['sourcePaths'] else 'http://www.videoreg.ru/')
|
||||
audit_plan.append(dict(normalizedPath=article['path'], originalUrl=original, rawFile=raw_file,snapshot=article['date'], reason=None))
|
||||
for item in audit_plan:
|
||||
f=P/item['rawFile']
|
||||
if not (f.exists() and f.stat().st_size>500):continue
|
||||
b=f.read_bytes();s=BeautifulSoup(b if '/gallery/' in str(f) or 'narod-' in str(f) else b.decode('cp1251',errors='replace'),'html.parser');item['_title']=s.title.get_text(' ',strip=True) if s.title else '';item['_text']=s.get_text(' ',strip=True);item['_sha']=hashlib.sha256(b).hexdigest();item['_actualSnapshot']=actual_snapshot(f,item['snapshot'])
|
||||
for tag in s.find_all(True):
|
||||
for attr in ['href','src','action','data','background']:
|
||||
value=tag.get(attr)
|
||||
if not isinstance(value,str) or not value.strip():continue
|
||||
absolute=urljoin(item['originalUrl'],value)
|
||||
context=' '.join(tag.get_text(' ',strip=True).split())[:220] or tag.get('alt','') or tag.name+' '+attr
|
||||
if canonical(absolute):
|
||||
u=urlsplit(absolute);key=norm(absolute)
|
||||
if key not in by and not re.search(r'\.(?:gif|jpe?g|png|avi|zip|pdf|css|ico|bin)$',u.path,re.I) and u.path!='/':
|
||||
if any(x in u.path for x in ['.shtml','.html','.htm','.php']):lead=new_leads.setdefault(key,dict(originalUrl=absolute,foundOn=[],context=context));lead['foundOn'].append(item['normalizedPath'])
|
||||
if lead['context'] in ['подробнее...','a href','link href','img src'] and context not in ['подробнее...','a href','link href','img src']:lead['context']=context
|
||||
continue
|
||||
if absolute.startswith('#'):continue
|
||||
if value.lower().startswith('javascript:'):reason='Old script-driven template interaction; no archived JavaScript is executed or carried to the new site.'
|
||||
elif absolute.startswith('mailto:'):reason='Old sales/support contact; not republished as an active contact.'
|
||||
elif re.search('казино|тур|тайланд|psp|бассейн|ворзел|кондиционер|хостинг|дилер|магазин|купить|установить|автоюрист',context,re.I):reason='Advertising/sales/paid-link context individually identified in this anchor; unrelated to technical body.'
|
||||
elif 'youtube' in absolute or 'rutube' in absolute or 'video.yandex' in absolute:reason='Original demonstration host: archived Flash/embed removed. Exact verified video links, when retained, are separately approved per published page and anchor in v2-link-approvals.json; playable video bytes not recovered.'
|
||||
elif tag.name in ('script','iframe','embed','object') or 'counter' in absolute or 'stat' in absolute:reason='Remote runtime/embed/counter removed; no downloaded runtime is executed.'
|
||||
elif 'phpbb' in absolute:reason='Historical forum engine footer removed; no phpBB runtime is published. Technical observations are paraphrased with source dates.'
|
||||
else:reason='Reviewed in original context: old partner, press, hosted sample or template reference is not needed for the edited technical body; omitted instead of carrying an unverified external destination.'
|
||||
source_outbound.append(dict(stage='raw-source',sourcePage=item['normalizedPath'],sourceFile=item['rawFile'],snapshot=item['_actualSnapshot'],element=tag.name,attribute=attr,context=context,destination=absolute,decision='remove-from-publication',reason=reason,reviewed=True,reviewer='root-v2-editorial'))
|
||||
# A URL-shaped script literal is reviewed even when it is not an HTML attribute.
|
||||
for tag in s.find_all(['script','style']):
|
||||
for url in re.findall(r'https?://[^\s"\'<>);]+',tag.get_text()):
|
||||
if not canonical(url):source_outbound.append(dict(stage='raw-inline',sourcePage=item['normalizedPath'],sourceFile=item['rawFile'],snapshot=item['_actualSnapshot'],element=tag.name,attribute='literal',context=tag.get_text()[:200],destination=url,decision='remove-from-publication',reason='Untrusted archived script/style literal; no archived scripts/styles imported.',reviewed=True,reviewer='root-v2-editorial'))
|
||||
# Additional exact aliases proved by named post anchors/canonical topic links in recovered raw threads.
|
||||
for key,dest in routes.items():
|
||||
if key not in by:new_leads.setdefault(key,dict(originalUrl='http://www.videoreg.ru'+key,foundOn=['recovered canonical topic/post links or explicit equivalent routing'],context='Verified canonical/alias path'))
|
||||
for src in content_dest:
|
||||
if src not in by:new_leads.setdefault(src,dict(originalUrl='http://www.videoreg.ru'+src,foundOn=['recovered document link'],context='Original technical document'))
|
||||
entries=[]
|
||||
for key in sorted(set(by)|set(new_leads)):
|
||||
item=by.get(key);lead=new_leads.get(key)
|
||||
u=urlsplit(key);semantic=[(k,v) for k,v in parse_qsl(u.query) if not (k=='sid' or k=='start' and v=='0' or k=='postdays' and v=='0' or k=='postorder' and v=='asc' or k=='highlight' and not v)]
|
||||
semanticKey=u.path+('?' +urlencode(sorted(semantic)) if semantic else '')
|
||||
dest=content_dest.get(key) or routes.get(key) or routes.get(semanticKey)
|
||||
f=P/item['rawFile'] if item else None;valid=bool(item and '_sha' in item)
|
||||
reason=None;status='unresolved';action='Recover actual body; no generic substitute or inferred text from an anchor.';kind=item['type'] if item else 'linked-content-url'
|
||||
if item and item['reason']:status='excluded-utility';reason=item['reason'];action='Not a historical content article.'
|
||||
elif key in commercial:status='excluded-commercial';reason=commercial[key];action='Read full source, remove commerce/advertising; relevant model facts retained separately.'
|
||||
elif dest:
|
||||
if valid and key in content_dest:status='edited-recovered';action='Full recovered body read and edited into typed safe sections; advertisements removed.'
|
||||
elif key=='/download/samples/zeiss_800_600_GPS_1.zip':status='partial-media-recovery';action='Original ZIP is truncated and unpublished. Four complete JPEG members validated by declared size/CRC and decoded locally; companion does not replace missing archive.'
|
||||
elif key=='/download/svk-002-mn.pdf':status='recovered-document';action='Complete3page January2008 Mobile News SVK002 journal test, validated PDF and all pages read; original exact PDF available.'
|
||||
elif key.startswith('/download/'):status='recovered-document';action='Validated original PDF extracted from original ZIP; complete document available.'
|
||||
elif '/forum/index.php' in key:status='replacement-navigation';action='Read-only technical case navigation replaces obsolete interactive forum entry; missing topic bodies tracked individually.'
|
||||
else:status='verified-equivalent';action='Mapped only through recovered same-page/section/canonical-post evidence; not counted as a newly recovered body.'
|
||||
reason='Edited technical purpose retained; see per-page editorial ledger.'
|
||||
elif item and key.startswith('/forum/viewforum.php') and valid:status='unresolved-listing';reason='Listing fetched and read; linked topics not all recovered, so not silently redirected to an incomplete body.'
|
||||
elif 'mark=topics' in key:status='excluded-utility';reason='Mark-as-read interaction, not a content body.'
|
||||
elif not item and any(x in key for x in ['/forum/login.php','/forum/profile.php','/forum/groupcp.php','/forum/search.php','/forum/memberlist.php','/forum/viewonline.php','/forum/posting.php','/forum/privmsg.php']):status='excluded-utility';reason='Linked authentication/profile/posting/search utility, not an original technical article.'
|
||||
elif not item and '/shop/index.php' in key and not any(x in key for x in ['productID=','categoryID=']):status='excluded-utility';reason='Linked shop action, sort, cart, language or commercial utility; no original technical body.'
|
||||
# Verify a linked original document by its actual extracted source, not HTTP200 alone.
|
||||
title=item.get('_title') if item else (lead or {}).get('context')
|
||||
entry=dict(originalUrl=item['originalUrl'] if item else lead['originalUrl'],normalizedPath=key,type=kind,chosenSnapshot=item.get('_actualSnapshot',item['snapshot']) if item and valid else None,requestedSnapshot=item.get('snapshot') if item else None,fetchStatus='validated-html-body' if valid else ('not-fetched-utility' if status.startswith('excluded') else 'unresolved'),rawFile=item['rawFile'] if valid else None,rawSha256=item.get('_sha') if item else None,title=title,rawVisibleTextChars=len(item.get('_text','')) if item else 0,currentDestination=dest,editorialAction=action,publicationStatus=status,exclusionOrUnresolvedReason=reason or 'No validated source body recovered after actual capture/version/URL attempts; restoration remains blocked.',discoveredFrom=(lead or {}).get('foundOn',[]))
|
||||
entries.append(entry)
|
||||
(D/'url-inventory.json').write_text(json.dumps(entries,ensure_ascii=False,indent=2)+'\n')
|
||||
(D/'outbound-links.json').write_text(json.dumps(dict(scope='Every external HTML attribute and inline URL in all fetched source pages. Public-source/build/DOM stages appended by verification script.',links=source_outbound),ensure_ascii=False,indent=2)+'\n')
|
||||
semrush=D/'semrush';semrush.mkdir(exist_ok=True)
|
||||
(semrush/'recovery-questions.json').write_text(json.dumps(dict(domain='videoreg.ru',scope=['apex','www'],status='awaiting actual coordinator Noxtools/Semrush evidence; not inspected by domain executor',missing=[dict(path=x['normalizedPath'],url=x['originalUrl'],title=x['title'],source=x['discoveredFrom']) for x in entries if x['publicationStatus'].startswith('unresolved')],questions=['Lost backlink targets beyond the CDX/HTML link union?','Exact titles and context for predpr.shtml, moves.htm, law1.htm, law2.htm and unindexed product/topic paths?','Separate manufacturer technical pages from later casino/real-estate/SEO anchors.','Record database, report scope/date, limits and first/last-seen dates.'],currentKnownEvidence='CDX883HTMLcaptures;259allresourceURLkeys; body recovery recorded per URL; all distinct pre/post2015 versions tried on missing indexed content.'),ensure_ascii=False,indent=2)+'\n')
|
||||
counts=collections.Counter(e['publicationStatus'] for e in entries);meaningful=[e for e in entries if not e['publicationStatus'].startswith('excluded')]
|
||||
body_captures=sum('_sha'in x for x in plan)
|
||||
text=f'''# Coverage V2 — known denominator, unresolved restoration\n\nCDX discovery: 883 HTML captures across 2007–2025; 121 collapsed HTML URL keys and 259 resource URL keys. Removing phpBB sid duplicates gives101 original normalized HTML URLs. Full CDX JSON has no resume key, so returned index is complete for the actual query (all883 originals were HTTP;528www and355apex; no HTTPS200 captures returned). Linked original URLs from every fetched body expand the known inventory. Unfetched bodies may contain further undiscovered links: this is a **known lower bound**, not a complete historical-site claim.\n\nKnown normalized URLs in inventory: **{len(entries)}**. Meaningful/non-utility denominator (including unresolved): **{len(meaningful)}**. Actual validated fetched HTML bodies: **{body_captures}** (includes commercial/navigation pages; not all are published articles). Publication dispositions:\n\n'''+''.join(f'- {k}: {v}\n' for k,v in sorted(counts.items()))+'''\nEach entry has URL/type/snapshot/raw hash/title/body size/destination/editorial action/status/reason in `url-inventory.json`. `edited-recovered` counts source URLs, not unique articles; canonical merges and verified equivalents are separate. Typed article pages include new HTML document companions whose complete original PDFs are available; counts must not be presented as16 historic HTML bodies.\n\nImportant unresolved items include missing historical topic bodies, original installation photographs, unrecovered video bytes and partial GPSsampleZIP. The January2008 SVK002 journal test PDF is now completely recovered (3pages). All alternative versions and URL variants actually attempted are in raw/requests.jsonl. These gaps and pending Semrush reconciliation remain mandatory V2 blockers. No historical article is synthesized from a backlink anchor/title. V1 modern guides/retail cards do not enter recovery counts.\n'''
|
||||
(D/'coverage.md').write_text(text)
|
||||
# Freeze successful source bytes in content-addressed files; retain original friendly filenames.
|
||||
objects=RAW/'objects';objects.mkdir(exist_ok=True)
|
||||
for f in list(RAW.rglob('*')):
|
||||
if f.is_file() and 'objects' not in f.parts and not f.name.endswith('.headers') and f.suffix not in ['.json','.jsonl']:
|
||||
b=f.read_bytes();o=objects/(hashlib.sha256(b).hexdigest()+'.bin')
|
||||
if not o.exists():o.write_bytes(b)
|
||||
print('INVENTORY',len(entries),'meaningful',len(meaningful),'status',dict(counts),'outbound occurrences',len(source_outbound))
|
||||
@@ -0,0 +1,61 @@
|
||||
from pathlib import Path
|
||||
import json
|
||||
P=Path(__file__).resolve().parents[2]
|
||||
routes={
|
||||
'/index.shtml':'/system',
|
||||
'/moves.htm':'/demo.shtml#section-3',
|
||||
'/shop/index.php?categoryID=78':'/catalog#section-1',
|
||||
'/shop/index.php?categoryID=79':'/catalog#section-0',
|
||||
'/shop/index.php?categoryID=80':'/catalog#section-3',
|
||||
'/shop/index.php?productID=132':'/equipment/svk002-lqcd',
|
||||
'/shop/index.php?productID=133':'/equipment/svk002-gps',
|
||||
'/shop/index.php?productID=137':'/equipment/svk004',
|
||||
'/forum/index.php':'/community',
|
||||
'/forum/index.php?c=2':'/community',
|
||||
'/forum/viewtopic.php?t=184':'/community/flash-start',
|
||||
'/forum/viewtopic.php?t=188':'/community/usb-extension',
|
||||
'/forum/viewtopic.php?t=183&view=next':'/community/flash-start',
|
||||
'/forum/viewtopic.php?t=8&view=next':'/community/usb-extension',
|
||||
'/forum/viewtopic.php?p=220':'/community/flash-start#section-0',
|
||||
'/forum/viewtopic.php?p=221':'/community/flash-start#section-1',
|
||||
'/forum/viewtopic.php?p=223':'/community/flash-start#section-2',
|
||||
'/forum/viewtopic.php?p=226':'/community/usb-extension#section-0',
|
||||
'/forum/viewtopic.php?p=227':'/community/usb-extension#section-1',
|
||||
}
|
||||
(P/'deploy/legacy-routes.json').write_text(json.dumps(routes,ensure_ascii=False,indent=2)+'\n')
|
||||
from urllib.parse import urlsplit, parse_qsl, urlencode
|
||||
import re
|
||||
|
||||
def exact_legacy_pattern(original):
|
||||
"""One raw-query pattern shared by nginx and the Python preview.
|
||||
|
||||
Only proved presentation defaults and a session token may be ignored.
|
||||
Pagination, search, ordering and unknown query values must not collapse.
|
||||
"""
|
||||
parsed = urlsplit(original)
|
||||
required = [re.escape(urlencode([(k, v)]))
|
||||
for k, v in parse_qsl(parsed.query, keep_blank_values=True)]
|
||||
allowed = list(required)
|
||||
if parsed.path.startswith('/forum/'):
|
||||
allowed += ['sid=[^&]*', 'start=0', 'postdays=0', 'postorder=asc', 'highlight=']
|
||||
checks = ''.join(r'(?=(?:[^&]*&)*' + pair + r'(?:&|$))' for pair in required)
|
||||
if allowed:
|
||||
pair = '(?:' + '|'.join(allowed) + ')'
|
||||
query = pair + '(?:&' + pair + ')*'
|
||||
if not required:
|
||||
query = '(?:' + query + ')?'
|
||||
else:
|
||||
query = ''
|
||||
return '^' + re.escape(parsed.path) + r'\|' + checks + query + '$'
|
||||
|
||||
matchers = [dict(original=src, destination=dst, pattern=exact_legacy_pattern(src))
|
||||
for src, dst in routes.items()]
|
||||
(P/'deploy/legacy-matchers.json').write_text(json.dumps(matchers, ensure_ascii=False, indent=2)+'\n')
|
||||
lines = ['# Generated by scripts/rebuild-v2/legacy-routes.py; exact query meaning only.',
|
||||
'map "$uri|$args" $videoreg_legacy {', ' default "";']
|
||||
for item in matchers:
|
||||
# map's first argument remains a regex token after nginx parses quotes.
|
||||
pattern = item['pattern'].replace('\\', '\\\\').replace('"', '\\"')
|
||||
lines.append(' "~' + pattern + '" "' + item['destination'] + '";')
|
||||
lines.append('}')
|
||||
(P/'deploy/legacy-map.conf').write_text('\n'.join(lines)+'\n')
|
||||
@@ -0,0 +1,32 @@
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit,urljoin
|
||||
import sys,json,hashlib,concurrent.futures
|
||||
from bs4 import BeautifulSoup
|
||||
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';R=D/'raw';data=json.loads((D/'sample-gallery-inventory.json').read_text());cdx=json.loads((R/'cdx-narod-samples.json').read_text());album_paths=sorted({urlsplit(r[2]).path for r in cdx[1:] if r[3]=='text/html' and ('photoalbum' in r[2] or 'povorot.html' in r[2])})
|
||||
for path in album_paths:
|
||||
for base in ['http://videoreg-samples.narod.ru','https://web.archive.org/web/2008id_/http://www.videoreg-samples.narod.ru:80']:
|
||||
url=base+path;rec=fetch(url,'gallery/alternate-'+hashlib.sha256(url.encode()).hexdigest()[:16]+'.html',20)
|
||||
if rec['httpStatus']=='200' and rec['bytes']>300:
|
||||
raw=(P/rec['raw']).read_bytes();s=BeautifulSoup(raw,'html.parser')
|
||||
if any(a.get('href','').lower().endswith('.jpg') for a in s.find_all('a')):
|
||||
album=dict(url='http://videoreg-samples.narod.ru'+path,raw=rec['raw'],title=s.title.get_text(' ',strip=True) if s.title else '',text=s.get_text(' ',strip=True),images=[])
|
||||
for tag in s.find_all(['a','img']):
|
||||
value=tag.get('href') if tag.name=='a' else tag.get('src');u=urlsplit(urljoin(album['url'],value or ''))
|
||||
if u.hostname and u.hostname.endswith('videoreg-samples.narod.ru') and u.path.lower().endswith('.jpg'):album['images'].append(u.path)
|
||||
album['images']=list(dict.fromkeys(album['images']));data['albums'].append(album);break
|
||||
images={i['path']:i for i in data['images']}
|
||||
for a in data['albums']:
|
||||
for path in a['images']:images.setdefault(path,dict(path=path,url='http://videoreg-samples.narod.ru'+path,fetchStatus='pending',rawFile=None))
|
||||
records={urlsplit(r[2]).path:r for r in cdx[1:] if r[3]=='image/jpeg' and '/.s/' not in r[2]}
|
||||
def work(i):
|
||||
if i['fetchStatus']=='downloaded-unreviewed':return
|
||||
urls=['https://videoreg-samples.narod.ru'+i['path']]
|
||||
if i['path'] in records:urls.append('https://web.archive.org/web/2008id_/http://videoreg-samples.narod.ru:80'+i['path'])
|
||||
for url in urls:
|
||||
name='gallery/retry-'+hashlib.sha256(url.encode()).hexdigest()[:18]+'.jpg';rec=fetch(url,name,20)
|
||||
if rec['httpStatus']=='200' and (P/rec['raw']).read_bytes().startswith(b'\xff\xd8\xff'):
|
||||
i.update(fetchStatus='downloaded-unreviewed',rawFile=rec['raw'],sha256=rec['sha256'],bytes=rec['bytes']);return
|
||||
i['fetchStatus']='unresolved'
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:list(ex.map(work,images.values()))
|
||||
data['images']=list(images.values());(D/'sample-gallery-inventory.json').write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n');print('ALTERNATE GALLERY',len(data['albums']),len(images),sum(i['fetchStatus']=='downloaded-unreviewed' for i in images.values()))
|
||||
@@ -0,0 +1,16 @@
|
||||
from pathlib import Path
|
||||
import json,sys,hashlib,concurrent.futures
|
||||
from urllib.parse import urlsplit
|
||||
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';R=D/'raw';media=json.loads((D/'media-inventory.json').read_text())
|
||||
important=['/images/ni-x1.jpg','/images/ni-x2.jpg','/images/ni-x3.jpg','/images/ni-x4.jpg','/images/sert_1024x768.jpg','/download/doc/QuickStart_SVK007_006.zip','/download/doc/svk-002-mn.zip','/download/uvr_instr_2ch.zip','/download/doc/svk-007-instr.zip','/download/svk-002-mn.pdf','/download/samples/zeiss_800_600_GPS_1.zip','/download/samples/zeiss_800_600_GPS_2.zip']
|
||||
important +=[x['path'] for x in media if x['mimetype']=='video/x-msvideo']
|
||||
def work(item):
|
||||
if item['path'] not in important or item['fetchStatus']=='downloaded-unreviewed' and item['path']!='/download/svk-002-mn.pdf':return
|
||||
for year in ['2012','2008']:
|
||||
url='https://web.archive.org/web/'+year+'id_/http://www.videoreg.ru:80'+item['path'];ext=Path(item['path']).suffix.lower();name='media/short-'+hashlib.sha256(url.encode()).hexdigest()[:16]+ext;rec=fetch(url,name,35)
|
||||
if rec['httpStatus']=='200' and rec['bytes']>500:
|
||||
item.update(fetchStatus='downloaded-unreviewed',rawFile=rec['raw'],sha256=rec['sha256'],bytes=rec['bytes'],requestedShortYear=year);return
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:
|
||||
for _ in ex.map(work,media):(D/'media-inventory.json').write_text(json.dumps(media,ensure_ascii=False,indent=2)+'\n')
|
||||
print('IMPORTANT-MEDIA successes',[(x['path'],x['rawFile']) for x in media if x['path'] in important and x['fetchStatus']=='downloaded-unreviewed'])
|
||||
@@ -0,0 +1,33 @@
|
||||
from pathlib import Path
|
||||
import sys,json,hashlib,concurrent.futures,time
|
||||
from urllib.parse import urlsplit,parse_qsl,urlencode
|
||||
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
|
||||
ROOT=Path(__file__).resolve().parents[2];RAW=ROOT/'docs/rebuild-v2/raw'
|
||||
plan=json.loads((ROOT/'docs/rebuild-v2/discovery-plan.json').read_text());all=json.loads((RAW/'cdx-all-html-captures.json').read_text());attempts={json.loads(x)['url'] for x in (RAW/'requests.jsonl').read_text().splitlines()}
|
||||
def norm(url):
|
||||
u=urlsplit(url);q=[(k,v) for k,v in parse_qsl(u.query) if k!='sid'];return u.path+('?' +urlencode(sorted(q)) if q else '')
|
||||
def saveplan():
|
||||
(ROOT/'docs/rebuild-v2/discovery-plan.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n')
|
||||
def work(item):
|
||||
dest=ROOT/item['rawFile']
|
||||
if dest.exists() and dest.stat().st_size>500:return
|
||||
versions=[r for r in all[1:] if isinstance(r,list) and norm(r[2])==item['normalizedPath']]
|
||||
# Prefer the most recent documented pre-2015 version of each distinct body.
|
||||
unique={}
|
||||
for r in versions:
|
||||
if r[1]>='20150101':unique[r[5]]=r
|
||||
ordered=sorted(unique.values(),key=lambda r:r[1],reverse=True)
|
||||
candidates=[]
|
||||
for r in ordered:
|
||||
for original in [r[2],'http://www.videoreg.ru'+item['normalizedPath'],'http://videoreg.ru'+item['normalizedPath']]:
|
||||
candidates.append((r[1],original))
|
||||
for ts,original in candidates:
|
||||
url='https://web.archive.org/web/'+ts+'id_/'+original
|
||||
if url in attempts:continue
|
||||
attempts.add(url);name='pages/'+hashlib.sha256(url.encode()).hexdigest()[:20]+'.html';rec=fetch(url,name,30)
|
||||
if rec['httpStatus']=='200' and rec['bytes']>500:
|
||||
item['rawFile']=rec['raw'];item['snapshot']=ts;item['replayUrl']=rec['effectiveUrl'];return
|
||||
time.sleep(.35)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:
|
||||
for _ in ex.map(work,[x for x in plan if x['disposition']=='fetch']):saveplan()
|
||||
saveplan();print('RECOVERED',sum((ROOT/x['rawFile']).exists() and (ROOT/x['rawFile']).stat().st_size>500 for x in plan if x['disposition']=='fetch'),flush=True)
|
||||
@@ -0,0 +1,26 @@
|
||||
from pathlib import Path
|
||||
import json,sys,hashlib,concurrent.futures,re
|
||||
from urllib.parse import urlsplit,unquote
|
||||
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
|
||||
ROOT=Path(__file__).resolve().parents[2];RAW=ROOT/'docs/rebuild-v2/raw';(RAW/'media').mkdir(exist_ok=True)
|
||||
d=json.loads((RAW/'cdx-all-resources.json').read_text());plan=[]
|
||||
for r in d[1:]:
|
||||
path=urlsplit(r[2]).path;name=unquote(path).lower();kind=r[3];reason=None
|
||||
if kind=='text/html' or kind=='text/css':continue
|
||||
if kind in ['application/octet-stream'] or '/sys-po/' in name or 'videoregistrator' in name or 'videoregshow' in name:reason='Executable/firmware not executed or republished'
|
||||
elif '/download/samples/' in name:reason='Recording ZIP retained in inventory; individual images/video prioritized without bulk ZIP republishing'
|
||||
elif kind=='application/zip' and not any(x in name for x in ['uvr_instr','svk-002-mn','svk-007-instr','svk_007_instr','quickstart']):reason='Historic warranty/commercial package, no technical corpus body'
|
||||
elif kind.startswith('image/') and not re.search(r'(ni-x|svk|vrss|f[1-5]_cr|front200|back200|auto1|break|video090806|mcad|avaria|sert_|micr300|c905|glonass|tr-600|contr_pp|quickcam1|not-deluxe|cwc\.jpg|l-qc-pn|qcn-pro|qc-fus|lifecam|microsoft|a4tech|spc1300|pronot|g-cam)',name):reason='Template chrome, advertisement/logo/press-cover or unneeded icon; not a content illustration'
|
||||
plan.append(dict(originalUrl=r[2],path=path,snapshot=r[1],mimetype=kind,reason=reason,fetchStatus='excluded' if reason else 'pending',rawFile=None,publicDestination=None))
|
||||
def work(item):
|
||||
if item['reason']:return
|
||||
path=item['path'];url=item['originalUrl'];ts=item['snapshot'];suffix=Path(unquote(path)).suffix.lower();name='media/'+hashlib.sha256(path.encode()).hexdigest()[:16]+suffix
|
||||
variants=[url,'http://www.videoreg.ru:80'+path,'http://www.videoreg.ru'+path]
|
||||
for original in dict.fromkeys(variants):
|
||||
result=fetch('https://web.archive.org/web/'+ts+'id_/'+original,name,35)
|
||||
if result['httpStatus']=='200' and result['bytes']>200:
|
||||
item.update(fetchStatus='downloaded-unreviewed',rawFile=result['raw'],sha256=result['sha256'],bytes=result['bytes']);return
|
||||
item['fetchStatus']='unresolved'
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:list(ex.map(work,plan))
|
||||
(ROOT/'docs/rebuild-v2/media-inventory.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n')
|
||||
print('MEDIA',len(plan),'downloaded',sum(x['fetchStatus']=='downloaded-unreviewed' for x in plan),flush=True)
|
||||
@@ -0,0 +1,29 @@
|
||||
from pathlib import Path
|
||||
from urllib.parse import urljoin,urlsplit
|
||||
import sys,json,hashlib,concurrent.futures
|
||||
from bs4 import BeautifulSoup
|
||||
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';R=D/'raw';(R/'gallery').mkdir(exist_ok=True)
|
||||
root=BeautifulSoup((R/'narod-samples-live.html').read_bytes(),'html.parser')
|
||||
albums=[dict(url='http://videoreg-samples.narod.ru/',raw='docs/rebuild-v2/raw/narod-samples-live.html')]
|
||||
for n in range(1,5):
|
||||
url='http://www.videoreg-samples.narod.ru/photoalbum'+str(n)+'.html';rec=fetch(url,'gallery/album'+str(n)+'.html',25)
|
||||
if rec['httpStatus']=='200' and rec['bytes']>300:albums.append(dict(url=url,raw=rec['raw']))
|
||||
images={}
|
||||
for album in albums:
|
||||
s=BeautifulSoup((P/album['raw']).read_bytes(),'html.parser')
|
||||
album['title']=s.title.get_text(' ',strip=True) if s.title else '';album['text']=s.get_text(' ',strip=True);album['images']=[]
|
||||
for tag in s.find_all(['a','img']):
|
||||
value=tag.get('href') if tag.name=='a' else tag.get('src');url=urljoin(album['url'],value or '')
|
||||
u=urlsplit(url)
|
||||
if u.hostname in ['videoreg-samples.narod.ru','www.videoreg-samples.narod.ru'] and u.path.lower().endswith(('.jpg','.jpeg')):
|
||||
key=u.path;album['images'].append(key);images.setdefault(key,dict(path=key,url=url,fetchStatus='pending',rawFile=None))
|
||||
album['images']=list(dict.fromkeys(album['images']))
|
||||
def work(item):
|
||||
name='gallery/'+hashlib.sha256(item['path'].encode()).hexdigest()[:18]+'.jpg';rec=fetch(item['url'],name,25)
|
||||
if rec['httpStatus']=='200' and (P/rec['raw']).read_bytes().startswith(b'\xff\xd8\xff'):
|
||||
item.update(fetchStatus='downloaded-unreviewed',rawFile=rec['raw'],sha256=rec['sha256'],bytes=rec['bytes'])
|
||||
else:item.update(fetchStatus='unresolved')
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:list(ex.map(work,images.values()))
|
||||
(D/'sample-gallery-inventory.json').write_text(json.dumps(dict(source='Original sample host linked by recovered videoreg homepage; live HTML contains legacy photo series, scripts not executed',albums=albums,images=list(images.values())),ensure_ascii=False,indent=2)+'\n')
|
||||
print('GALLERY',len(albums),'albums',len(images),'discovered photos',sum(x['fetchStatus']=='downloaded-unreviewed' for x in images.values()),'downloaded')
|
||||
@@ -0,0 +1,27 @@
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
import sys,json,hashlib,concurrent.futures,time,email.utils
|
||||
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';R=D/'raw'
|
||||
plan=json.loads((D/'discovery-plan.json').read_text());inventory=json.loads((D/'url-inventory.json').read_text());known={x['normalizedPath'] for x in plan}
|
||||
for e in inventory:
|
||||
if e['publicationStatus'].startswith('unresolved') and e['normalizedPath'] not in known and 'mark=topics' not in e['normalizedPath']:
|
||||
key=e['normalizedPath'];plan.append(dict(originalUrl=e['originalUrl'],normalizedPath=key,type='linked-content-url',snapshot='2008' if '/forum/' in key or '/shop/' in key else '2012',rawFile='docs/rebuild-v2/raw/pages/'+hashlib.sha256(key.encode()).hexdigest()[:16]+'.html',disposition='fetch',reason=None));known.add(key)
|
||||
# Reuse actual successful short-date original, no new text generated from links.
|
||||
for item in plan:
|
||||
if item['normalizedPath']=='/predpr.shtml':item.update(rawFile='docs/rebuild-v2/raw/predpr-short2012.html',snapshot='2012')
|
||||
requests={json.loads(x)['url'] for x in (R/'requests.jsonl').read_text().splitlines()}
|
||||
def work(item):
|
||||
f=P/item['rawFile']
|
||||
if item.get('disposition')!='fetch' or (f.exists() and f.stat().st_size>500):return
|
||||
key=item['normalizedPath'];years=['2007','2008'] if '/forum/' in key or '/shop/' in key else ['2012','2008']
|
||||
for year in years:
|
||||
url='https://web.archive.org/web/'+year+'id_/http://www.videoreg.ru:80'+key
|
||||
if url in requests:continue
|
||||
name='pages/short-'+hashlib.sha256(url.encode()).hexdigest()[:16]+'.html';rec=fetch(url,name,35)
|
||||
if rec['httpStatus']=='200' and rec['bytes']>500:
|
||||
item.update(rawFile=rec['raw'],snapshot=year,replayUrl=rec['effectiveUrl']);return
|
||||
time.sleep(.35)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:
|
||||
for _ in ex.map(work,plan):(D/'discovery-plan.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n')
|
||||
print('SHORTDATE BODY COUNT',sum((P/x['rawFile']).exists() and (P/x['rawFile']).stat().st_size>500 for x in plan if x['disposition']=='fetch'))
|
||||
@@ -0,0 +1,33 @@
|
||||
from pathlib import Path
|
||||
import sys,json,hashlib,concurrent.futures,time
|
||||
from urllib.parse import urlsplit,parse_qsl,urlencode
|
||||
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
|
||||
ROOT=Path(__file__).resolve().parents[2];RAW=ROOT/'docs/rebuild-v2/raw'
|
||||
plan=json.loads((ROOT/'docs/rebuild-v2/discovery-plan.json').read_text());all=json.loads((RAW/'cdx-all-html-captures.json').read_text());attempts={json.loads(x)['url'] for x in (RAW/'requests.jsonl').read_text().splitlines()}
|
||||
def norm(url):
|
||||
u=urlsplit(url);q=[(k,v) for k,v in parse_qsl(u.query) if k!='sid'];return u.path+('?' +urlencode(sorted(q)) if q else '')
|
||||
def saveplan():
|
||||
(ROOT/'docs/rebuild-v2/discovery-plan.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n')
|
||||
def work(item):
|
||||
dest=ROOT/item['rawFile']
|
||||
if dest.exists() and dest.stat().st_size>500:return
|
||||
versions=[r for r in all[1:] if isinstance(r,list) and norm(r[2])==item['normalizedPath']]
|
||||
# Prefer the most recent documented pre-2015 version of each distinct body.
|
||||
unique={}
|
||||
for r in versions:
|
||||
if r[1]<'20150101':unique[r[5]]=r
|
||||
ordered=sorted(unique.values(),key=lambda r:r[1],reverse=True)
|
||||
candidates=[]
|
||||
for r in ordered:
|
||||
for original in [r[2],'http://www.videoreg.ru'+item['normalizedPath'],'http://videoreg.ru'+item['normalizedPath']]:
|
||||
candidates.append((r[1],original))
|
||||
for ts,original in candidates:
|
||||
url='https://web.archive.org/web/'+ts+'id_/'+original
|
||||
if url in attempts:continue
|
||||
attempts.add(url);name='pages/'+hashlib.sha256(url.encode()).hexdigest()[:20]+'.html';rec=fetch(url,name,30)
|
||||
if rec['httpStatus']=='200' and rec['bytes']>500:
|
||||
item['rawFile']=rec['raw'];item['snapshot']=ts;item['replayUrl']=rec['effectiveUrl'];return
|
||||
time.sleep(.35)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:
|
||||
for _ in ex.map(work,[x for x in plan if x['disposition']=='fetch']):saveplan()
|
||||
saveplan();print('RECOVERED',sum((ROOT/x['rawFile']).exists() and (ROOT/x['rawFile']).stat().st_size>500 for x in plan if x['disposition']=='fetch'),flush=True)
|
||||
@@ -0,0 +1,4 @@
|
||||
beautifulsoup4==4.15.0
|
||||
pillow==13.0.0
|
||||
soupsieve==3.0.4
|
||||
typing_extensions==4.16.0
|
||||
@@ -0,0 +1,33 @@
|
||||
from pathlib import Path
|
||||
import json,sys,hashlib,concurrent.futures
|
||||
from urllib.parse import urlsplit
|
||||
sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch
|
||||
from importlib.machinery import SourceFileLoader
|
||||
m=SourceFileLoader('corpus',str(Path(__file__).parent/'download-corpus.py'))
|
||||
ROOT=Path(__file__).resolve().parents[2];RAW=ROOT/'docs/rebuild-v2/raw'
|
||||
plan=json.loads((ROOT/'docs/rebuild-v2/discovery-plan.json').read_text());all=json.loads((RAW/'cdx-all-html-captures.json').read_text());attempts={r['url'] for r in [json.loads(x) for x in (RAW/'requests.jsonl').read_text().splitlines()]}
|
||||
# Existing successful captures are immutable and reused, not re-fetched.
|
||||
for path,name in [('/auto.shtml','auto-20070228153116.html'),('/faq.shtml','faq-www.html')]:
|
||||
for item in plan:
|
||||
if item['normalizedPath']==path:item['rawFile']='docs/rebuild-v2/raw/'+name
|
||||
|
||||
def norm(url):
|
||||
from urllib.parse import parse_qsl,urlencode
|
||||
u=urlsplit(url);q=[(k,v) for k,v in parse_qsl(u.query) if k!='sid'];return u.path+('?' +urlencode(sorted(q)) if q else '')
|
||||
def work(item):
|
||||
dest=ROOT/item['rawFile']
|
||||
if dest.exists() and dest.stat().st_size>500:return
|
||||
versions=[r for r in all[1:] if isinstance(r,list) and norm(r[2])==item['normalizedPath'] and r[1]<'20150101']
|
||||
candidates=[(item['snapshot'],'http://www.videoreg.ru:80'+item['normalizedPath'])]
|
||||
if versions:
|
||||
r=versions[-1];candidates.append((r[1],'http://www.videoreg.ru:80'+item['normalizedPath']))
|
||||
for i,(ts,url) in enumerate(candidates):
|
||||
replay='https://web.archive.org/web/'+ts+'id_/'+url
|
||||
if replay in attempts:continue
|
||||
name='pages/'+hashlib.sha256((item['normalizedPath']+ts+str(i)).encode()).hexdigest()[:16]+'.html'
|
||||
result=fetch(replay,name,45)
|
||||
if result['httpStatus']=='200' and result['bytes']>500:
|
||||
item['rawFile']=result['raw'];item['snapshot']=ts;item['replayUrl']=replay;return
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:list(ex.map(work,[x for x in plan if x['disposition']=='fetch']))
|
||||
(ROOT/'docs/rebuild-v2/discovery-plan.json').write_text(json.dumps(plan,ensure_ascii=False,indent=2)+'\n')
|
||||
print('recovered bodies',sum((ROOT/x['rawFile']).exists() and (ROOT/x['rawFile']).stat().st_size>500 for x in plan if x['disposition']=='fetch'),flush=True)
|
||||
@@ -0,0 +1,32 @@
|
||||
from pathlib import Path
|
||||
import json,re
|
||||
P=Path(__file__).resolve().parents[2];d=P/'docs/rebuild-v2/outbound-links.json';x=json.loads(d.read_text())
|
||||
context_rules=[
|
||||
('pr-realt.com.ua','Paid real-estate insertion in FAQ2011 footer, anchor дома в ворзеле; unrelated to operation Q&A. Removed without altering technical questions.'),
|
||||
('jazztravel.com.ua','Paid Thai hotel booking anchor in compatibility/support footer; no connection to listed USB camera modes. Removed.'),
|
||||
('playland.com.ua','Paid PSP3008 shop insertion in support footer, unrelated game-console product; removed.'),
|
||||
('protivotok.net','Paid swimming-pool equipment insertion in support footer, unrelated to camera compatibility; removed.'),
|
||||
('paradcasino.com','Casino paid anchor inside dealer page; removed, never treated as historical technical body.'),
|
||||
('new-wind.ru','Household air-conditioner sales insertion in dealer page; removed as unrelated advertising.'),
|
||||
('videoreg-samples.narod.ru','Original linked sample gallery: full decoded JPEGs copied locally without template runtime. This exact remote file/link is omitted to avoid partial/dead remote loads; corresponding local images and unresolved file counts are recorded in sample-gallery-inventory.json.'),
|
||||
('avtourist','Old legal-promotion/recommendation banner; no actual legal article body recovered here. Banner omitted; legal claims not republished as advice.'),
|
||||
('club4x4.ru','Travel/expedition reality-show source mention, legitimate contextual link rather than casino insertion. Not retained in technical operation text because no dependent factual passage is copied; remains an internal recovery lead.'),
|
||||
('autoreview.ru','Legitimate period press review source link; not currently used as a factual source in edited body. Kept in internal recovery inventory rather than silently importing an unverified article.'),
|
||||
('ksytal.ru','Separate GSM alarm product partner mention on home page. No corresponding technical comparison/body is republished; commercial cross-promotion removed.'),
|
||||
('carintst.com','Historic paid/partner installation studio sidebar, not an installation instruction or image attribution; removed.'),
|
||||
('invista.org','Old reseller shop sidebar for buying SVK; no technical dependency, obsolete purchase route removed.'),
|
||||
('autoprofi2000.ru','Old installer/dealer promotion; no copied installation tutorial requiring attribution, removed.'),
|
||||
('b-tuning.ru','Historic tuning/installer promotion, no technical body attribution or guide; removed.'),
|
||||
('mak-studia.ru','Historical installation/dealer contact; not published as active sales route.'),
|
||||
('autoset.ru','Old commercial partner banner/link, not the source of edited technical facts; removed.'),
|
||||
('talks.mark-itt.ru','External discussion reference in recovered forum context; thread content not recovered/used as authority. Technical explanation derives from the original local posts; remote link omitted pending recovery.'),
|
||||
('earth.google.com','Historical Google Earth download/support pointer for viewing track data. Product version URL not verified; edited article preserves KML/KMZ file purpose without presenting this obsolete link as a current download.'),
|
||||
('fotki.yandex.ru','Retired original map-photo host; original demonstration context retained, link not represented as a working map or recovered image.'),
|
||||
]
|
||||
for item in x['links']:
|
||||
for needle,reason in context_rules:
|
||||
if needle in item['destination']:item['reason']=reason;item['decision']='remove-from-publication';break
|
||||
if 'narod.yandex.ru/userforum' in item['destination']:item['reason']='Legacy guestbook/forum interaction, no recovered article body; runtime/contact utility omitted.'
|
||||
if re.search(r'yandex.ru/(?:cy|cycounter)',item['destination']):item['reason']='Citation-index badge/counter tracking in template, unrelated to technical reading; removed.'
|
||||
x['scope']='All actual chosen/supplemental source HTML attributes and inline URLs. Per-context editorial decisions; built/source and rendered DOM reports are separate evidence stages.'
|
||||
d.write_text(json.dumps(x,ensure_ascii=False,indent=2)+'\n')
|
||||
@@ -0,0 +1,19 @@
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit,parse_qsl,urlencode
|
||||
import json,shutil,hashlib
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2/semrush';D.mkdir(exist_ok=True)
|
||||
source=Path('/Users/gavrilovdev/tmp/pupline/site-restoration-status/semrush-recovery/videoreg.ru');raw=json.loads((source/'observed-indexed-pages.json').read_text())
|
||||
for name in ['observed-indexed-pages.json','observed-indexed-pages.md','observed-anchors.partial.json','observed-anchors.partial.md','observed-lost-vital.json','observed-lost-vital.md']:shutil.copyfile(source/name,D/name)
|
||||
inv=json.loads((P/'docs/rebuild-v2/url-inventory.json').read_text());by={i['normalizedPath']:i for i in inv}
|
||||
def norm(url):
|
||||
u=urlsplit(url);q=[(k,v) for k,v in parse_qsl(u.query) if k!='sid'];return u.path+('?' +urlencode(sorted(q)) if q else '')
|
||||
rows=[]
|
||||
for row in raw['rows']:
|
||||
k=norm(row['url']);found=by.get(k);status=found['publicationStatus'] if found else 'unresolved-new-lead'
|
||||
if row['classification']=='later_expired_domain_state':status='later-state-not-original-body'
|
||||
rows.append(dict(observed=row,normalizedPath=k,matchedInventoryUrl=found['originalUrl'] if found else None,recoveryDisposition=status,rawFile=found['rawFile'] if found else None,sourceHash=found['rawSha256'] if found else None,currentDestination=found['currentDestination'] if found else None,bodyRecoveredFromAnchor=False,review='Specific target reconciled to actual source inventory; metrics not treated as body proof'))
|
||||
extra=[('/moves.htm','Универсальный цифровой видеорегистратор СВК','recovered-original-Russia1clip-context'),('/autopredpr.shtml',None,'matched'),('/demo.shtml',None,'unresolved-media'),('/shop/index.php?productID=133',None,'matched'),('/shop/index.php?productID=138',None,'unresolved'),('/forum/viewtopic.php?t=196',None,'unresolved'),('/forum/viewforum.php?f=1',None,'navigation-only'),('/account',None,'excluded-later-unrelated-Blox-state'),('/join',None,'excluded-later-unrelated-Blox-state'),('/withdraw',None,'excluded-later-unrelated-Blox-state')]
|
||||
report=dict(domain='videoreg.ru',evidenceOrigin='Coordinator inspected Noxtools/Semrush in shared built-in browser; this executor ingested actual supplied transcription without taking over session',reportUrl=raw['reportUrl'],additionalEvidenceFiles=['observed-anchors.partial.json','observed-lost-vital.json','referrer-verification.json'],reportedTotal=raw['reportedTotal'],actualDOMRowsReported=raw['actualDOMRowsReportedByParent'],transcribedRows=raw['transcribedRows'],complete=False,scopeLimitation=raw['scopeLimit'],originalExportSha256=hashlib.sha256((D/'observed-indexed-pages.json').read_bytes()).hexdigest(),rows=rows,additionalCoordinatorMessageLeads=[dict(url='http://www.videoreg.ru'+k,title=t,disposition=s,evidence='Direct coordinator message2026-10-26; exact per-row metrics/date not supplied') for k,t,s in extra],remainingRequirements=['Remaining66observedDOM rows and6unloaded reported rows not provided as full export','Anchors52DOM/3transcribed; LostVital18DOM/6transcribed.5actualreferrersfetched;3HTTP200,2unavailable. Full rowtranscriptions and remainingreferrers remain mandatory.','Unresolved target bodies/media must be recovered from actual sources; no text synthesized from anchors'])
|
||||
(D/'reconciliation.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
(D/'scope.md').write_text('# Semrush / Noxtools — actual partial scope\n\nCoordinator used the shared built-in browser. Report total89, actualDOM83, supplied transcription17selected rows. This executor ingested exactly those17 and the explicit additional coordinator message leads; it did not independently inspect the UI or manufacture the remaining rows.\n\n`reconciliation.json` maps each supplied target to actual raw body/status. Late expiry and Blox account/join/withdraw states do not replace original technical content. Backlink counts are not recovered text.\n\nMandatory issue videoreg-7oy.7 stays open: complete exported row coverage and actual referringURL/anchor contexts are still missing.\n')
|
||||
print('Semrush matched observed rows',len(rows),'of reported',raw['reportedTotal'],'scope remains partial')
|
||||
@@ -0,0 +1,42 @@
|
||||
from pathlib import Path
|
||||
from PIL import Image,ImageOps,ImageDraw
|
||||
import json,shutil,math,hashlib
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';f=P/'web-front/src/content/v2-articles.json';articles=json.loads(f.read_text());g=json.loads((D/'sample-gallery-inventory.json').read_text());by={x['path']:x for x in g['images']};contactdir=D/'evidence/gallery-sheets';contactdir.mkdir(exist_ok=True)
|
||||
series={
|
||||
'/':('/samples/stx','Покадровая запись 640×480','Серия с камеры Logitech Communicate STX.','Рассмотрите порядок изменения сцены в последовательности и откройте исходные JPEG. Частоту съёмки нельзя установить по одному имени файла.'),
|
||||
'/photoalbum2.html':('/samples/evening-zeiss','Поездка вечером: камера Zeiss','Вечерняя серия с Logitech QuickCam Pro for Notebook Zeiss Optic.','Сравните участки с разной освещённостью. Размытие и различимость объектов оценивайте в исходном размере, без увеличения, выдаваемого за новые детали.'),
|
||||
'/photoalbum3.html':('/samples/day-zeiss','Дневная запись: камера Zeiss','Дневная серия с Logitech Pro Notebooks Zeiss optics.','Дневные кадры показывают дорожную сцену в условиях этой поездки. Один набор не доказывает качество камеры при другой погоде, настройках или установке.'),
|
||||
'/photoalbum4.html':('/samples/rain','Съёмка в сильный дождь','Последовательность с камеры Genius Videocam WEB, 640×480.','Посмотрите, как дождь на стекле меняет видимую сцену. Это запись конкретного опыта; она не задаёт технический предел работы камеры под дождём вне салона.'),
|
||||
'/photoalbum5.html':('/samples/late-evening','Поздний вечер: Communicate STX','Серия камеры Logitech Communicate STX при низкой освещённости.','Сопоставьте светлые и тёмные участки последовательности. По показанным кадрам нельзя обещать читаемость номеров в любых вечерних условиях.'),
|
||||
'/povorot.html':('/samples/roundabout','Круговое движение при слабом свете','Последовательность с Logitech QuickCam Communicate STX.','Исходное название серии указывает круговое движение и слабую освещённость. Последовательность сохраняет отдельные кадры; AVI-экспорт и исходные JPEG не следует считать одинаковыми файлами.')}
|
||||
for album in g['albums']:
|
||||
from urllib.parse import urlsplit
|
||||
path=urlsplit(album['url']).path
|
||||
if path not in series:continue
|
||||
route,title,summary,paragraph=series[path];frames=[];thumbs=[]
|
||||
for source in album['images']:
|
||||
row=by[source]
|
||||
if row['fetchStatus']!='downloaded-unreviewed':continue
|
||||
try:
|
||||
with Image.open(P/row['rawFile']) as im:im.load();size=im.size;thumb=ImageOps.contain(im.convert('RGB'),(220,165))
|
||||
except Exception as e:row.update(fetchStatus='corrupt-image',validationError=str(e));continue
|
||||
name=Path(source).name;destination='/recordings/samples/'+name;dest=P/'web-front/public'/destination.lstrip('/');dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(P/row['rawFile'],dest)
|
||||
row.update(publicDestination=destination,decodedSize=list(size),decoded=True);frames.append(dict(src=destination,filename=name,width=size[0],height=size[1]));thumbs.append((name,thumb))
|
||||
if not frames:continue
|
||||
columns=4;sheet=Image.new('RGB',(columns*220,math.ceil(len(thumbs)/columns)*195),'#f5f2e9');draw=ImageDraw.Draw(sheet)
|
||||
for i,(name,thumb) in enumerate(thumbs):
|
||||
x=i%columns*220;y=i//columns*195;sheet.paste(thumb,(x,y));draw.text((x+5,y+169),name,fill='#17382f')
|
||||
sheetpath=contactdir/(route.rsplit('/',1)[-1]+'.jpg');sheet.save(sheetpath)
|
||||
album['decodedFrames']=len(frames);album['publicDestination']=route;album['contactSheet']=str(sheetpath.relative_to(P))
|
||||
existing=next((a for a in articles if a['path']==route),None)
|
||||
if existing:
|
||||
existing['title']=title;existing['summary']=summary;existing['sections'][0]['gallery']=frames
|
||||
else:
|
||||
articles.append(dict(path=route,title=title,summary=summary,category='Записи',date='Дата не указана',kind='linked-source',sourcePaths=[album['url']],rawFiles=[album['raw']],sections=[dict(heading='Последовательность исходных кадров',paragraphs=[paragraph,'Оригинал каждого кадра открывается по нажатию. Сохранение через снимок экрана или повторное сжатие меняет материал. Для проверки времени и GPS нужны соответствующие поля самого файла; подпись серии их не заменяет.'],gallery=frames)],related=['/samples.shtml','/samples/stx','/tools/recording-time']))
|
||||
if route=='/samples/stx':
|
||||
existing=next(a for a in articles if a['path']==route);existing['related']=['/samples/gps','/samples/evening-zeiss','/samples/rain'];existing['sections'][0]['paragraphs'][0]='Серия показывает изменение дорожной сцены по отдельным кадрам. На странице примеров указаны камера Logitech Communicate STX и разрешение 640×480. Откройте исходник, чтобы оценить детали в собственном размере.'
|
||||
links=[dict(href=a['publicDestination'],label=series[urlsplit(a['url']).path][1]) for a in g['albums'] if a.get('publicDestination')]
|
||||
for a in articles:
|
||||
if a['path']=='/samples.shtml':
|
||||
a['sections'][1]['links']=links+[dict(href='/samples/gps',label='Кадры 800×600 с EXIF GPS')]
|
||||
f.write_text(json.dumps(articles,ensure_ascii=False,indent=2)+'\n');(D/'sample-gallery-inventory.json').write_text(json.dumps(g,ensure_ascii=False,indent=2)+'\n');print('galleries',len(links),'decoded',sum(a.get('decodedFrames',0) for a in g['albums']))
|
||||
@@ -0,0 +1,29 @@
|
||||
from pathlib import Path
|
||||
import hashlib,json,subprocess,zipfile,collections
|
||||
from PIL import Image
|
||||
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';public=P/'web-front/public';digest=lambda f:hashlib.sha256(f.read_bytes()).hexdigest()
|
||||
public_by_hash={digest(f):'/'+f.relative_to(public).as_posix() for f in public.rglob('*') if f.is_file()}
|
||||
rows=json.loads((D/'media-inventory.json').read_text())
|
||||
for row in rows:
|
||||
if row['path']=='/download/svk-002-mn.pdf':row.update(rawFile='docs/rebuild-v2/raw/svk002-review-retry-0.bin',reason=None)
|
||||
f=P/row['rawFile'] if row.get('rawFile') else None
|
||||
row['publicDestination']=None
|
||||
if row.get('reason') and row.get('fetchStatus')=='excluded':row['validation']='excluded-original-commercial-or-runtime';continue
|
||||
if not f or not f.is_file() or not f.stat().st_size:row['validation']='unresolved-no-complete-bytes';continue
|
||||
row.update(bytes=f.stat().st_size,sha256=digest(f));valid=False
|
||||
try:
|
||||
suffix=Path(row['path']).suffix.lower()
|
||||
if suffix in ['.jpg','.jpeg','.gif','.png','.ico']:
|
||||
with Image.open(f) as im:im.load();row['imageDimensions']=list(im.size);valid=True
|
||||
elif suffix=='.pdf':
|
||||
r=subprocess.run(['pdfinfo',str(f)],capture_output=True,text=True);valid=r.returncode==0 and 'Pages:' in r.stdout;row['pdfinfoExit']=r.returncode
|
||||
elif suffix=='.zip':
|
||||
with zipfile.ZipFile(f) as z:valid=z.testzip() is None;row['zipMembers']=z.namelist()
|
||||
else:row['validation']='downloaded-needs-format-specific-review';continue
|
||||
except Exception as e:row['validationError']=str(e)
|
||||
if valid:
|
||||
row['publicDestination']=public_by_hash.get(row['sha256']);row['validation']='validated-published-exact-bytes' if row['publicDestination'] else 'validated-unpublished'
|
||||
else:row['validation']='unresolved-invalid-or-truncated';row['fetchStatus']='unresolved-invalid'
|
||||
(D/'media-inventory.json').write_text(json.dumps(rows,ensure_ascii=False,indent=2)+'\n')
|
||||
(D/'evidence/media-validation.json').write_text(json.dumps(dict(resources=len(rows),counts=dict(collections.Counter(x['validation'] for x in rows)),publicFiles=len(public_by_hash),scope='Primary domain136resourceCDXkeys; external sample host separately recorded in sample-gallery-inventory.json',note='No software, firmware or script executed; original archive members inspected only. GPSsampleZIP is truncated; four complete JPEGs salvaged by memberCRC, not fullZIPrecovery.'),ensure_ascii=False,indent=2)+'\n')
|
||||
print(collections.Counter(x['validation'] for x in rows))
|
||||
Reference in new issue
Block a user