txtdot/packages/server/src/distributor.ts

141 lines
3.7 KiB
TypeScript
Raw Normal View History

import axios, { oaxios } from './types/axios';
import micromatch from 'micromatch';
import { Readable } from 'stream';
import { NotHtmlMimetypeError } from './errors/main';
import { decodeStream, parseEncodingName } from './utils/http';
import replaceHref from './utils/replace-href';
2024-05-15 16:09:01 +03:00
import { Engine, EngineOutput, Middleware } from '@txtdot/sdk';
2024-05-13 13:30:47 +03:00
import { HandlerInput, HandlerOutput } from '@txtdot/sdk';
import config from './config';
2024-05-13 16:35:36 +03:00
import { parseHTML } from 'linkedom';
import { html2text } from './utils/html2text';
import DOMPurify from 'isomorphic-dompurify';
interface IEngineId {
[key: string]: number;
}
export class Distributor {
engines_id: IEngineId = {};
2024-05-15 16:09:01 +03:00
engines_fallback: Engine[] = [];
engines_list: string[] = [];
middles_id: IEngineId = {};
middles_fallback: Middleware[] = [];
middles_list: string[] = [];
constructor() {}
engine(engine: Engine) {
2024-05-15 16:09:01 +03:00
this.engines_id[engine.name] = this.engines_list.length;
this.engines_fallback.push(engine);
this.engines_list.push(engine.name);
}
middleware(middleware: Middleware) {
this.middles_id[middleware.name] = this.middles_list.length;
this.middles_fallback.push(middleware);
this.middles_list.push(middleware.name);
}
async handlePage(
remoteUrl: string, // remote URL
requestUrl: URL, // proxy URL
engineName?: string,
redirectPath: string = 'get'
2024-05-13 13:30:47 +03:00
): Promise<HandlerOutput> {
const urlObj = new URL(remoteUrl);
const webder_url = config.env.third_party.webder_url;
const response = webder_url
? await oaxios.get(
`${webder_url}/render?url=${encodeURIComponent(remoteUrl)}`
)
: await axios.get(remoteUrl);
const data: Readable = response.data;
const mime: string | undefined =
response.headers['content-type']?.toString();
if (mime && mime.indexOf('text/html') === -1) {
throw new NotHtmlMimetypeError();
}
const engine = this.getFallbackEngine(urlObj.hostname, engineName);
2024-05-13 16:35:36 +03:00
2024-05-15 16:09:01 +03:00
const input = new HandlerInput(
await decodeStream(data, parseEncodingName(mime)),
remoteUrl
);
let output = await engine.handle(input);
// Sanitize output before middlewares, because middlewares can add unsafe tags
output = {
...output,
content: DOMPurify.sanitize(output.content),
};
output = await this.processMiddlewares(urlObj.hostname, input, output);
2024-05-15 16:09:01 +03:00
2024-05-13 16:35:36 +03:00
const dom = parseHTML(output.content);
2024-05-14 13:34:25 +03:00
// Get text content before link replacement, because in text format we need original links
const stdTextContent = dom.document.documentElement.textContent;
// post-process
2024-05-13 13:30:47 +03:00
replaceHref(
2024-05-13 16:35:36 +03:00
dom.document,
2024-05-13 13:30:47 +03:00
requestUrl,
new URL(remoteUrl),
engineName,
redirectPath
);
const title = output.title || dom.document.title;
const lang = output.lang || dom.document.documentElement.lang;
2024-05-14 13:11:59 +03:00
const textContent =
html2text(stdTextContent, output, title) ||
2024-05-14 13:11:59 +03:00
'Text output cannot be generated.';
2024-05-13 13:30:47 +03:00
return {
content: output.content,
2024-05-14 13:11:59 +03:00
textContent,
title,
lang,
2024-05-13 13:30:47 +03:00
};
}
getFallbackEngine(host: string, specified?: string): Engine {
if (specified) {
2024-05-15 16:09:01 +03:00
return this.engines_fallback[this.engines_id[specified]];
}
2024-03-07 14:49:54 +03:00
2024-05-15 16:09:01 +03:00
for (const engine of this.engines_fallback) {
if (micromatch.isMatch(host, engine.domains)) {
return engine;
}
}
2024-05-15 16:09:01 +03:00
return this.engines_fallback[0];
}
async processMiddlewares(
host: string,
input: HandlerInput,
output: EngineOutput
): Promise<EngineOutput> {
let processed_output = output;
for (const middle of this.middles_fallback) {
if (micromatch.isMatch(host, middle.domains)) {
processed_output = await middle.handle(input, processed_output);
}
}
return processed_output;
}
}