from pathlib import Path from bs4 import BeautifulSoup from urllib.parse import unquote,urlsplit,quote,urljoin import json,urllib.request,urllib.error,hashlib,sys,collections r=Path(__file__).resolve().parents[1] if Path(__file__).parent.name=='deploy' else Path('/Users/gavrilovdev/tmp/progcode.ru');out=r/'web/out';base=sys.argv[1].rstrip('/');inv=json.load(open(r/'docs/rebuild-v2/url-inventory.json'));articles=json.load(open(r/'web/data/articles.json'));results=[];links=set();missing=[];unreviewed=[];bodies={};suspicious=[] htmlfiles=sorted(out.rglob('*.html')) def request(path): url=base+quote(unquote(path),safe='/%?=&:#') try: with urllib.request.urlopen(url,timeout=20) as response:return response.status,response.read() except urllib.error.HTTPError as e:return e.code,e.read() for p in htmlfiles: rel=str(p.relative_to(out));route='/'+rel[:-10] if rel.endswith('index.html') else '/'+rel status,body=request(route);assert status==200,(route,status) s=BeautifulSoup(body,'html.parser');article=s.select_one('.article-content');chars=len(article.get_text(' ',strip=True)) if article else None if article and chars<80:missing.append({'path':route,'reason':'thin/empty article body','chars':chars}) for a in s.select('[href],[src],form[action]'): for k in ['href','src','action']: v=a.get(k,'');u=urlsplit(v) if u.netloc and u.hostname not in ['progcode.ru','www.progcode.ru','127.0.0.1','localhost']:continue if v.startswith(('mailto:','tel:')):continue if v.startswith('/') or not u.scheme: actual=urlsplit(urljoin(base+route,v));dest=actual.path if actual.fragment: target=s if unquote(dest)==unquote(route) else BeautifulSoup(request(dest)[1],'html.parser') if not target.find(id=unquote(actual.fragment)):missing.append({'path':route,'fragment':v}) links.add(dest) for tag in s.find_all(True): if any(k.lower().startswith('on') for k in tag.attrs):suspicious.append({'path':route,'tag':str(tag)[:160]}) text=s.get_text(' ',strip=True) if any(word in text.lower() for word in ['costofcial','cialissverige','не удалось восстановить встроенные','иллюстрация из архивного снимка','данный вирус практически никакой угрозы']):suspicious.append({'path':route,'reason':'spam/process/unsafe assertion'}) if route.startswith('/articles/'): slug=unquote(route.strip('/').split('/')[-1]);bodies[slug]=hashlib.sha256(str(article).encode()).hexdigest() if article else None results.append({'path':route,'status':status,'htmlSha256':hashlib.sha256(body).hexdigest(),'bodyChars':chars,'images':len(s.select('img'))}) for path in sorted(links): status,b=request(path) if status!=200:missing.append({'path':path,'status':status}) reconciled=[] for item in inv['urls']: if item['publicationStatus']=='excluded':continue dest=item['currentDestination'];status,b=request(dest) if status!=200:missing.append({'inventory':item['originalURL'],'destination':dest,'status':status}) # Also verify the original path for useful dated/taxonomy/standalone pages. path=item['normalizedPath'] if item['type'] not in ['wordpress-shortlink','article-modern-alias']: status,b=request(path+'/') if path!='/' else request('/') if status!=200:missing.append({'originalPath':path,'status':status}) reconciled.append(item['originalURL']) status,b=request('/unknown/nested/progcode-v2-not-a-page/');assert status==404 and b'ProgCode' in b or status==404 and b'progcode' in b assert len(set(bodies.values()))==len(bodies)==14,'Duplicate/missing canonical bodies' result={'base':base,'generatedHTML':len(results),'uniqueInternalTargets':len(links),'inventoryRowsChecked':len(reconciled),'canonicalArticleBodies':len(bodies),'missing':missing,'suspicious':suspicious,'branded404':status==404,'pages':results} print(json.dumps(result,ensure_ascii=False,indent=2));assert not missing and not suspicious