Show article authors and forum links on canonical news pages (372)
This commit is contained in:
parent
625e20e38b
commit
8a768869b1
7 changed files with 34 additions and 10 deletions
|
|
@ -22,3 +22,6 @@ This checkpoint is staged only. Merge/deployment, backup paths, live existing-to
|
|||
|
||||
Native subject compatibility follow-up: MyBB limits subjects to85characters while website titles allow120. Forum subjects are truncated with MyBB's Unicode-aware helper, the full long title is retained at the start of the post, and the Archived prefix also stays within85characters. The native temporary-table test now covers long-title editing, archive and republish without losing the full title.
|
||||
|
||||
|
||||
Canonical article follow-up: browser verification found that the server-rendered /news/ route still omitted author attribution and the confirmed forum link. It now shares the public forum-link resolver, escapes the public author name, shows the shared category label and provides Go to forum post only after confirmed delivery.23focused Node checks pass. Native Markdown-style headings and bullet lists are safely translated to a small BBCode subset; user brackets remain escaped. Rendering version2 triggers reconciliation without creating duplicate topics. The actual MyBB temporary-table test also validates formatting, full long-title retention and reply preservation.
|
||||
|
||||
|
|
|
|||
|
|
@ -34,12 +34,19 @@ try{
|
|||
if($saved&&!$mapping)throw new Exception('Revision mapping requires reconciliation');
|
||||
if($saved&&$saved['revision']===$revision&&$saved['state']===$state){$reply($mapping['tid']);exit;}
|
||||
$safe=fn($s)=>str_replace(['[',']'],['[',']'],(string)$s);$url='https://www.dunerealms.com/news-archive.html?post='.$input['id'];
|
||||
$formatBody=function($body)use($safe){
|
||||
$out=[];$list=false;foreach(preg_split('/\r\n|\r|\n/',$body)as$line){
|
||||
if(preg_match('/^#{1,3}\s+(.+)$/u',trim($line),$heading)){if($list){$out[]='[/list]';$list=false;}$out[]='[b]'.$safe($heading[1]).'[/b]';}
|
||||
elseif(preg_match('/^[-*]\s+(.+)$/u',trim($line),$bullet)){if(!$list){$out[]='[list]';$list=true;}$out[]='[*]'.$safe($bullet[1]);}
|
||||
else{if($list){$out[]='[/list]';$list=false;}$out[]=$safe($line);}
|
||||
}if($list)$out[]='[/list]';return implode("\n",$out);
|
||||
};
|
||||
if($status==='published'){
|
||||
$labels=['world'=>'World','news'=>'NEWS','maintenance'=>'Maintenance','changelogs'=>'Changelogs','events'=>'Events','community'=>'Community','unis_blog'=>"Uni’s Blog"];$label=$labels[$input['category']??'news']??'NEWS';$prefix=$db->fetch_array($db->simple_select('threadprefixes','pid',"prefix='".$db->escape_string($label)."' AND forums='14'"));
|
||||
if(!$prefix){$prefix=['pid'=>$db->insert_query('threadprefixes',['prefix'=>$label,'displaystyle'=>'<span class="dune-news-tag">'.htmlspecialchars_uni($label).'</span>','forums'=>'14','groups'=>'-1'])];$cache->update_threadprefixes();}
|
||||
// MyBB's native validator limits subjects to85 characters; website titles allow120.
|
||||
$subject=my_substr($input['title'],0,85);$prefix_id=(int)$prefix['pid'];
|
||||
$message='[b]'.$safe($label).'[/b]'."\n".'Written by '.$safe($input['author_name']??'DuneRealms')."\n".'Originally published '.gmdate('j F Y, H:i',(int)($input['published_at']/1000))." UTC\n\n".$safe($input['body'])."\n\n[url=".$url."]Read the original article[/url]\n\n[size=x-small]".$marker.'[/size]';
|
||||
$message='[b]'.$safe($label).'[/b]'."\n".'Written by '.$safe($input['author_name']??'DuneRealms')."\n".'Originally published '.gmdate('j F Y, H:i',(int)($input['published_at']/1000))." UTC\n\n".$formatBody($input['body'])."\n\n[url=".$url."]Read the original article[/url]\n\n[size=x-small]".$marker.'[/size]';
|
||||
if(my_strlen($input['title'])>85)$message='[b]'.$safe($input['title'])."[/b]\n\n".$message;
|
||||
}else{
|
||||
$subject=my_substr('[Archived] '.preg_replace('/^\[Archived\] /','',$thread['subject']),0,85);$prefix_id=(int)$thread['prefix'];
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ const nativeSend=post=>new Promise((resolve,reject)=>{const child=execFile('/usr
|
|||
export function forumNewsRevision(row,time){
|
||||
// Withdrawal payloads deliberately contain no current draft/private/future content.
|
||||
const post=row.status==='published'&&row.published_at!=null&&Number.isFinite(Number(row.published_at))&&Number(row.published_at)<=time
|
||||
?{id:row.id,status:'published',title:row.title,body:row.body,category:row.category,published_at:Number(row.published_at),author_name:row.author_name||'DuneRealms'}
|
||||
?{id:row.id,status:'published',title:row.title,body:row.body,category:row.category,published_at:Number(row.published_at),author_name:row.author_name||'DuneRealms',format_version:2}
|
||||
:{id:row.id,status:'archived'};
|
||||
return {...post,revision:createHash('sha256').update(JSON.stringify(post)).digest('hex')};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ export async function initializeNews(db){
|
|||
await db.prepare('INSERT INTO website_posts(id,source_key,category,title,body,status,author_id,created_at,updated_at,published_at,version) VALUES(?,?,?,?,?,?,?,?,?,?,1) ON CONFLICT(source_key) DO UPDATE SET source_key=excluded.source_key').bind(randomUUID(),key,'changelogs',String(release.title||release.version).slice(0,120),body,'published','release-register',date,date,date).run();
|
||||
}
|
||||
}
|
||||
async function forumLinks(db,posts){try{if(!posts.length)return posts;const{results}=await db.prepare('SELECT post_id,thread_id FROM forum_news_delivery WHERE post_id IN ('+posts.map(()=>'?').join(',')+") AND thread_id>0 AND state='sent'").bind(...posts.map(p=>p.id)).all();const links=new Map(results.filter(r=>Number.isSafeInteger(Number(r.thread_id))&&Number(r.thread_id)>0).map(r=>[r.post_id,'https://forums.dunerealms.com/showthread.php?tid='+Number(r.thread_id)]));return posts.map(p=>({...p,forum_url:links.get(p.id)||null}));}catch{return posts.map(p=>({...p,forum_url:null}));}}
|
||||
export async function forumLinks(db,posts){try{if(!posts.length)return posts;const{results}=await db.prepare('SELECT post_id,thread_id FROM forum_news_delivery WHERE post_id IN ('+posts.map(()=>'?').join(',')+") AND thread_id>0 AND state='sent'").bind(...posts.map(p=>p.id)).all();const links=new Map(results.filter(r=>Number.isSafeInteger(Number(r.thread_id))&&Number(r.thread_id)>0).map(r=>[r.post_id,'https://forums.dunerealms.com/showthread.php?tid='+Number(r.thread_id)]));return posts.map(p=>({...p,forum_url:links.get(p.id)||null}));}catch{return posts.map(p=>({...p,forum_url:null}));}}
|
||||
export function createPublicNews(db){return async request=>{
|
||||
const url=new URL(request.url);if(request.method!=='GET')return json({message:'Method not allowed'},405);
|
||||
if(url.pathname==='/api/home/forum'){
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {renderNewsBody} from './news-format.mjs';
|
||||
import {forumLinks,NEWS_CATEGORIES} from './news.mjs';
|
||||
import {SHARED_HEADER,SHARED_HEAD} from '../scripts/portal-navigation.mjs';
|
||||
const base='https://www.dunerealms.com';
|
||||
const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
|
|
@ -12,7 +13,7 @@ const pages={
|
|||
'/staff.html':['DuneRealms Staff & Contributors','Meet the DuneRealms community staff and project contributors.']
|
||||
};
|
||||
export const newsPath=p=>'/news/'+p.title.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'').slice(0,75)+'-'+p.id;
|
||||
const published="SELECT id,title,body,category,published_at,updated_at FROM website_posts WHERE status='published' AND published_at<=?";
|
||||
const published="SELECT p.id,p.title,p.body,p.category,p.published_at,p.updated_at,COALESCE(a.display_name,a.username,'DuneRealms') author_name FROM website_posts p LEFT JOIN site_accounts a ON a.id=p.author_id WHERE p.status='published' AND p.published_at<=?";
|
||||
const ld=data=>'<script type="application/ld+json">'+JSON.stringify(data).replaceAll('<','\\u003c')+'</script>';
|
||||
function metadata(html,{title,description,canonical,type='website',image=base+'/assets/dunerealms-season-logo-v2.png',structured}){
|
||||
html=html.replace(/<title>[\s\S]*?<\/title>/i,'').replace(/<meta\b(?=[^>]*(?:name=["'](?:description|robots|twitter:[^"']+)["']|property=["']og:[^"']+["']))[^>]*>/gi,'').replace(/<link\b(?=[^>]*rel=["']canonical["'])[^>]*>/gi,'');
|
||||
|
|
@ -20,7 +21,7 @@ function metadata(html,{title,description,canonical,type='website',image=base+'/
|
|||
return html.replace(/<\/head>/i,head+'</head>');
|
||||
}
|
||||
export function createSearchVisibility(db){
|
||||
const getPosts=async(limit=50000)=> (await db.prepare(published+' ORDER BY published_at DESC,id DESC LIMIT ?').bind(Date.now(),limit).all()).results;
|
||||
const getPosts=async(limit=50000)=> (await db.prepare(published+' ORDER BY p.published_at DESC,p.id DESC LIMIT ?').bind(Date.now(),limit).all()).results;
|
||||
return{
|
||||
async route(request){
|
||||
const u=new URL(request.url);if(!['GET','HEAD'].includes(request.method))return null;
|
||||
|
|
@ -33,11 +34,12 @@ export function createSearchVisibility(db){
|
|||
const legacy=u.pathname==='/news-archive.html'&&u.searchParams.has('post'),match=u.pathname.match(/^\/news\/(?:[a-z0-9-]*-)?([a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12})$/i);
|
||||
if(!legacy&&!match)return null;
|
||||
const id=legacy?u.searchParams.get('post'):match[1];if(!/^[a-f0-9-]{36}$/i.test(id||''))return new Response('News post not found',{status:404});
|
||||
const p=await db.prepare(published+' AND id=?').bind(Date.now(),id).first();if(!p)return new Response('News post not found',{status:404,headers:{'X-Robots-Tag':'noindex'}});
|
||||
const p=await db.prepare(published+' AND p.id=?').bind(Date.now(),id).first();if(!p)return new Response('News post not found',{status:404,headers:{'X-Robots-Tag':'noindex'}});
|
||||
const path=newsPath(p);if(legacy||u.pathname!==path)return Response.redirect(base+path,301);
|
||||
const description=p.body.replace(/\s+/g,' ').slice(0,160),date=new Date(Number(p.published_at)).toISOString();
|
||||
const art='/assets/news-'+(['world','news','maintenance','changelogs','events','community'].includes(p.category)?p.category:'news')+'.webp';
|
||||
let html='<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="/styles.css"><link rel="stylesheet" href="/home-news.css?v=article-20261102">'+SHARED_HEAD+'</head><body class="home-news news-article-page">'+SHARED_HEADER+'<main id="main"><article id="news-full-post" class="dispatch-full"><a class="article-back" href="/news-archive.html">← News archive</a><div class="article-heading"><div><div class="article-meta"><span class="article-category">'+esc(p.category)+'</span><time datetime="'+date+'">'+esc(new Date(Number(p.published_at)).toLocaleDateString('en-GB',{dateStyle:'long'}))+'</time></div><h1>'+esc(p.title)+'</h1></div><img src="'+art+'" alt="Imperial dispatch artwork" width="360" height="240"></div><div class="dispatch-full-body article-body">'+renderNewsBody(p.body)+'</div></article></main><footer><a href="/">DuneRealms</a> · <a href="/wiki.html">Disclaimer & contact</a></footer></body></html>';
|
||||
const linked=(await forumLinks(db,[p]))[0],byline='<p class="dispatch-byline">Written by '+esc(p.author_name)+'</p>',discussion=linked.forum_url?'<p><a class="dispatch-read-more" href="'+esc(linked.forum_url)+'">Go to forum post →</a></p>':'';
|
||||
let html='<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="/styles.css"><link rel="stylesheet" href="/home-news.css?v=article-20261102">'+SHARED_HEAD+'</head><body class="home-news news-article-page">'+SHARED_HEADER+'<main id="main"><article id="news-full-post" class="dispatch-full"><a class="article-back" href="/news-archive.html">← News archive</a><div class="article-heading"><div><div class="article-meta"><span class="article-category">'+esc(NEWS_CATEGORIES[p.category]||NEWS_CATEGORIES.news)+'</span><time datetime="'+date+'">'+esc(new Date(Number(p.published_at)).toLocaleDateString('en-GB',{dateStyle:'long'}))+'</time></div><h1>'+esc(p.title)+'</h1>'+byline+'</div><img src="'+art+'" alt="Imperial dispatch artwork" width="360" height="240"></div><div class="dispatch-full-body article-body">'+renderNewsBody(p.body)+'</div>'+discussion+'</article></main><footer><a href="/">DuneRealms</a> · <a href="/wiki.html">Disclaimer & contact</a></footer></body></html>';
|
||||
html=metadata(html,{title:p.title+' | DuneRealms',description,canonical:base+path,type:'article',structured:{'@context':'https://schema.org','@type':'NewsArticle',headline:p.title,datePublished:date,dateModified:new Date(Number(p.updated_at||p.published_at)).toISOString(),mainEntityOfPage:base+path,image:[base+'/assets/dunerealms-season-logo-v2.png'],publisher:{'@type':'Organization',name:'DuneRealms',url:base}}});
|
||||
return new Response(request.method==='HEAD'?null:html,{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'public,max-age=60'}});
|
||||
},
|
||||
|
|
@ -45,10 +47,12 @@ export function createSearchVisibility(db){
|
|||
const u=new URL(request.url),path=u.pathname==='/'?'/':u.pathname,config=pages[path];if(!config)return html;
|
||||
html=metadata(html,{title:config[0],description:config[1],canonical:path==='/manual.html'?'https://wiki.dunerealms.com/':base+path,structured:path==='/'?{'@context':'https://schema.org','@type':'WebSite',name:'DuneRealms',url:base+'/'}:null});
|
||||
if(path==='/'||path==='/news-archive.html'){
|
||||
const posts=await getPosts(path==='/'?9:25),cards='<div class="dispatch-grid" data-server-news>'+posts.map(p=>'<article class="dispatch-card"><img src="/assets/nav-discord-full-v2.webp" width="1672" height="941" alt="" loading="lazy"><div class="dispatch-copy"><span>'+esc(p.category)+'</span><h3><a href="'+newsPath(p)+'">'+esc(p.title)+'</a></h3><p>'+esc(p.body.slice(0,180))+'</p><a class="dispatch-read-more" href="'+newsPath(p)+'">Read more →</a></div></article>').join('')+'</div>';
|
||||
const posts=await getPosts(path==='/'?9:25),cards='<div class="dispatch-grid" data-server-news>'+posts.map(p=>'<article class="dispatch-card"><img src="/assets/nav-discord-full-v2.webp" width="1672" height="941" alt="" loading="lazy"><div class="dispatch-copy"><span>'+esc(NEWS_CATEGORIES[p.category]||NEWS_CATEGORIES.news)+'</span><h3><a href="'+newsPath(p)+'">'+esc(p.title)+'</a></h3><p>'+esc(p.body.slice(0,180))+'</p><a class="dispatch-read-more" href="'+newsPath(p)+'">Read more →</a></div></article>').join('')+'</div>';
|
||||
html=html.replace(/(<div\s+data-news-module="news"[^>]*>)/, '$1'+cards);
|
||||
}
|
||||
return html;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -15,9 +15,10 @@ def run(payload,reply=False):
|
|||
if result.returncode:raise RuntimeError('Native fixture failed: '+str(result.returncode)+' '+result.stdout[:300]+' '+result.stderr[:600])
|
||||
output=json.loads(result.stdout);assert output['revision']==payload['revision'];state=json.loads((qa/'state.json').read_text());return output,state
|
||||
initial,state=run(post);tid=initial['thread_id'];pid=state['threads'][0]['firstpost'];date=state['posts'][0]['dateline'];assert len(state['threads'])==len(state['posts'])==1
|
||||
post.update(title='Corrected isolated announcement',body='Corrected article body',category='maintenance')
|
||||
post.update(title='Corrected isolated announcement',body='## Release notes\n\n- Corrected article body\n- [url=https://example.invalid]escaped[/url]',category='maintenance')
|
||||
edited,state=run(post,True);assert edited['thread_id']==tid and len(state['posts'])==2 and len(state['threads'])==1
|
||||
assert state['posts'][0]['pid']==pid and state['posts'][0]['dateline']==date and 'Corrected article body' in state['posts'][0]['message']
|
||||
assert '[b]Release notes[/b]' in state['posts'][0]['message'] and '[list]' in state['posts'][0]['message'] and '[url=' in state['posts'][0]['message'] and '[url=https://example.invalid]' not in state['posts'][0]['message']
|
||||
reply=next(p for p in state['posts'] if str(p['pid'])=='100');reply_bytes=json.dumps(reply,sort_keys=True)
|
||||
post['title']='A complete website announcement title longer than the native forum subject limit of eighty-five characters'
|
||||
long_title,state=run(post);assert len(state['threads'][0]['subject'])==85 and post['title'] in state['posts'][0]['message']
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import test from 'node:test';
|
|||
import assert from 'node:assert/strict';
|
||||
import {LocalD1} from './d1-adapter.mjs';
|
||||
import {createSearchVisibility,newsPath} from '../node/search-visibility.mjs';
|
||||
function setup(){const db=new LocalD1('CREATE TABLE website_posts(id TEXT,title TEXT,body TEXT,category TEXT,status TEXT,published_at INTEGER,updated_at INTEGER);');return db;}
|
||||
function setup(){const db=new LocalD1('CREATE TABLE website_posts(id TEXT,title TEXT,body TEXT,category TEXT,status TEXT,published_at INTEGER,updated_at INTEGER,author_id TEXT);CREATE TABLE site_accounts(id TEXT,display_name TEXT,username TEXT);CREATE TABLE forum_news_delivery(post_id TEXT,thread_id INTEGER,state TEXT);');return db;}
|
||||
const post={id:'40c67ad3-3814-4702-9b25-14edf5ca2a80',title:'Alpha update & community',body:'A published update.\n\n<script>alert(1)</script>',category:'changelogs',published_at:Date.now()-10000,updated_at:Date.now()-5000};
|
||||
async function insert(db,p,status='published'){await db.prepare('INSERT INTO website_posts(id,title,body,category,status,published_at,updated_at) VALUES(?,?,?,?,?,?,?)').bind(p.id,p.title,p.body,p.category,status,p.published_at,p.updated_at).run();}
|
||||
test('published news is crawlable and escaped, legacy links redirect permanently, drafts stay absent',async()=>{const db=setup();try{
|
||||
|
|
@ -14,3 +14,12 @@ test('published news is crawlable and escaped, legacy links redirect permanently
|
|||
assert.equal((await seo.route(req('/news/00000000-0000-4000-8000-000000000001'))).status,404);
|
||||
const home=await seo.html(req('/'),'<html><head><title>Old</title></head><body><div data-news-module="news"></div></body></html>');assert(home.includes('data-server-news'));assert(home.includes(newsPath(post)));assert.equal((home.match(/<title>/g)||[]).length,1);
|
||||
}finally{db.close();}});
|
||||
test('canonical full article shows escaped public author and confirmed forum link only',async()=>{const db=setup();try{
|
||||
await insert(db,post);await db.prepare("INSERT INTO site_accounts VALUES('author','Writer <script>','writer')").run();await db.prepare("UPDATE website_posts SET author_id='author' WHERE id=?").bind(post.id).run();
|
||||
const seo=createSearchVisibility(db),request=new Request('https://www.dunerealms.com'+newsPath(post));
|
||||
let html=await(await seo.route(request)).text();assert(html.includes('Written by Writer <script>'));assert(!html.includes('Go to forum post'));assert(!html.includes('Written by Writer <script>'));
|
||||
await db.prepare("INSERT INTO forum_news_delivery VALUES(?,13,'sent')").bind(post.id).run();html=await(await seo.route(request)).text();assert(html.includes('https://forums.dunerealms.com/showthread.php?tid=13'));assert(html.includes('Go to forum post'));
|
||||
await db.prepare("UPDATE forum_news_delivery SET state='uncertain'").run();html=await(await seo.route(request)).text();assert(!html.includes('Go to forum post'));
|
||||
await db.prepare("UPDATE site_accounts SET display_name=NULL").run();html=await(await seo.route(request)).text();assert(html.includes('Written by writer'));
|
||||
await db.prepare("UPDATE website_posts SET category='unis_blog'").run();html=await(await seo.route(request)).text();assert(html.includes('Uni’s Blog'));assert(!html.includes('>unis_blog<'));
|
||||
}finally{db.close();}});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff