Files
2026-11-11 00:08:35 +00:00

199 lines
7.3 KiB
JavaScript

'use strict';
// Talks to any standard MediaWiki site through its public api.php.
// Pure Node code (no Electron imports) so it can be tested on its own.
// A fetch function is passed in so the app can use Electron's network stack.
const UA = 'Swiftmark/1.0 (desktop wikitext editor)';
function normalizeInput(input) {
let s = String(input || '').trim();
if (!s) throw new Error('Enter your wiki address first.');
if (!/^https?:\/\//i.test(s)) s = 'https://' + s;
return new URL(s);
}
async function fetchText(fetchFn, url, init, timeoutMs) {
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), timeoutMs || 15000);
try {
const headers = Object.assign({ 'User-Agent': UA }, (init && init.headers) || {});
const opts = Object.assign({}, init, { headers, signal: ctl.signal });
const res = await fetchFn(url, opts);
const body = await res.text();
return { status: res.status, body };
} finally {
clearTimeout(timer);
}
}
function candidateApis(u, html) {
const out = [];
const add = (x) => {
try {
const s = new URL(x, u).toString();
if (!out.includes(s)) out.push(s);
} catch (e) { /* ignore bad candidate */ }
};
if (/api\.php$/i.test(u.pathname)) add(u.origin + u.pathname);
if (html) {
const m = html.match(/<link[^>]+rel=["']EditURI["'][^>]*href=["']([^"']+)["']/i) ||
html.match(/<link[^>]+href=["']([^"']+)["'][^>]*rel=["']EditURI["']/i);
if (m) add(m[1].replace(/&amp;/g, '&').split('?')[0]);
}
const p = u.pathname;
let base = p.replace(/\/+$/, '');
const i1 = p.search(/\/index\.php/i);
const i2 = p.search(/\/wiki\//i);
if (i1 >= 0) base = p.slice(0, i1);
else if (i2 >= 0) base = p.slice(0, i2);
add(base + '/api.php');
add(base + '/w/api.php');
add(u.origin + '/w/api.php');
add(u.origin + '/api.php');
add(u.origin + '/wiki/api.php');
add(u.origin + '/mediawiki/api.php');
add(base + '/mediawiki/api.php');
return out.slice(0, 9);
}
async function probe(fetchFn, api) {
try {
const url = api + '?action=query&meta=siteinfo&siprop=general&format=json&formatversion=2';
const r = await fetchText(fetchFn, url, {});
let j;
try { j = JSON.parse(r.body); } catch (e) {
if (r.status === 401 || r.status === 403) return { ok: false, kind: 'blocked', status: r.status };
if (r.status === 404) return { ok: false, kind: 'notfound', status: r.status };
return { ok: false, kind: 'notapi', status: r.status };
}
if (j.error) {
const code = j.error.code || '';
const priv = /^(readapidenied|permissiondenied|login-required)/.test(code);
return { ok: false, kind: priv ? 'private' : 'apierror', code, info: j.error.info || '' };
}
if (j.query && j.query.general) {
return { ok: true, name: j.query.general.sitename, generator: j.query.general.generator };
}
return { ok: false, kind: 'notapi' };
} catch (e) {
return { ok: false, kind: 'unreachable', message: e.message };
}
}
async function parseWiki(fetchFn, api, text, title) {
const params = new URLSearchParams({
action: 'parse',
format: 'json',
formatversion: '2',
contentmodel: 'wikitext',
text: String(text),
title: title || 'Preview',
prop: 'text|headhtml|categorieshtml|displaytitle',
disableeditsection: '1',
disablelimitreport: '1',
preview: '1',
pst: '1'
});
let r;
try {
r = await fetchText(fetchFn, api, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
body: params.toString()
}, 30000);
} catch (e) {
return { ok: false, kind: 'unreachable', message: e.message };
}
let j;
try { j = JSON.parse(r.body); } catch (e) {
return { ok: false, kind: (r.status === 401 || r.status === 403) ? 'blocked' : 'notapi', status: r.status };
}
if (j.error) {
const code = j.error.code || '';
const priv = /^(readapidenied|permissiondenied|login-required)/.test(code);
return { ok: false, kind: priv ? 'private' : 'apierror', code, info: j.error.info || '' };
}
if (!j.parse || typeof j.parse.text === 'undefined') {
return { ok: false, kind: 'apierror', code: 'noparse', info: 'Unexpected answer from the API.' };
}
return { ok: true, json: j };
}
function explain(f, u) {
const host = u ? u.host : 'the server';
switch (f.kind) {
case 'private':
return 'The API refused the request because ' + host + ' does not let logged out visitors read the wiki.';
case 'blocked':
return 'The server answered with HTTP ' + (f.status || '401 or 403') + ', so something (a firewall, a security plugin or CDN bot protection) is blocking API requests.';
case 'unreachable':
return 'Could not reach ' + host + (f.message ? ' (' + f.message + ').' : '.');
case 'apierror':
return 'The API answered with an error' + (f.code ? ' (' + f.code + ')' : '') + (f.info ? ': ' + f.info : '.');
default:
return 'Could not find api.php at any of the usual locations. The address may be wrong, or the API may be disabled or moved.';
}
}
async function connect(input, fetchFn) {
const u = normalizeInput(input);
let html = '';
let pageErr = null;
try {
const r = await fetchText(fetchFn, u.toString(), {});
html = r.body;
} catch (e) { pageErr = e; }
const rank = { private: 5, blocked: 4, apierror: 3, unreachable: 2, notapi: 1, notfound: 1 };
let worst = null;
const note = (f) => { if (!worst || (rank[f.kind] || 0) > (rank[worst.kind] || 0)) worst = f; };
for (const api of candidateApis(u, html)) {
const p = await probe(fetchFn, api);
if (!p.ok) { note(p); continue; }
const t = await parseWiki(fetchFn, api, "''test''", 'Test');
if (t.ok) return { ok: true, api, siteName: p.name || u.host, generator: p.generator || '' };
note(t);
}
if (!worst) worst = { kind: 'notfound' };
if (pageErr && (worst.kind === 'notfound' || worst.kind === 'notapi')) {
worst = { kind: 'unreachable', message: pageErr.message };
}
return { ok: false, kind: worst.kind, detail: explain(worst, u) };
}
function asString(x) {
if (typeof x === 'string') return x;
if (x && typeof x['*'] === 'string') return x['*'];
return '';
}
function escHtml(s) {
return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function buildLiveDoc(json, api, title) {
const p = json.parse;
const base = new URL(api).origin + '/';
let head = asString(p.headhtml);
if (!/<head[\s>]/i.test(head)) {
head = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>';
}
head = head.replace(/<script[\s\S]*?<\/script>/gi, '');
head = head.replace(/<head[^>]*>/i, (m) => m + '<base href="' + base + '" target="_blank">');
const titleHtml = asString(p.displaytitle) || escHtml(title || '');
const body =
'<div class="mw-body" id="content" role="main" style="margin:0;padding:16px 24px;border:0;max-width:none;min-height:0;background:transparent">' +
'<h1 id="firstHeading" class="firstHeading mw-first-heading">' + titleHtml + '</h1>' +
'<div id="bodyContent" class="vector-body mw-body-content">' +
'<div id="mw-content-text">' + asString(p.text) + '</div>' +
asString(p.categorieshtml) +
'</div></div></body></html>';
return head + body;
}
module.exports = { connect, parseWiki, buildLiveDoc, explain, normalizeInput, candidateApis };