summaly/built/index.js
Kagami Sascha Rosylight eab3766db9
feat: add oEmbed support (#6)
* feat: add oEmbed support

* more safelisted features

* fix the syntax

* Update README.md

* permissions

* names

* playerを使うように

* fix type error

* support width (for size ratio)

* test for type: video

* nullable width

* restore max height test

* ignored permissions

* restore autoplay

* Use WHATWG URL

---------

Co-authored-by: tamaina <tamaina@hotmail.co.jp>
2023-03-14 02:46:41 +09:00

69 lines
1.9 KiB
JavaScript

/**
* summaly
* https://github.com/syuilo/summaly
*/
import { URL } from 'node:url';
import tracer from 'trace-redirect';
import general from './general.js';
import { setAgent } from './utils/got.js';
import { plugins as builtinPlugins } from './plugins/index.js';
const defaultOptions = {
lang: null,
followRedirects: true,
plugins: [],
};
/**
* Summarize an web page
*/
export const summaly = async (url, options) => {
if (options?.agent)
setAgent(options.agent);
const opts = Object.assign(defaultOptions, options);
const plugins = builtinPlugins.concat(opts.plugins || []);
let actualUrl = url;
if (opts.followRedirects) {
// .catch(() => url)にすればいいけど、jestにtrace-redirectを食わせるのが面倒なのでtry-catch
try {
actualUrl = await tracer(url);
}
catch (e) {
actualUrl = url;
}
}
const _url = new URL(actualUrl);
// Find matching plugin
const match = plugins.filter(plugin => plugin.test(_url))[0];
// Get summary
const summary = await (match ? match.summarize : general)(_url, opts.lang || undefined);
if (summary == null) {
throw 'failed summarize';
}
return Object.assign(summary, {
url: actualUrl
});
};
export default function (fastify, options, done) {
fastify.get('/', async (req, reply) => {
const url = req.query.url;
if (url == null) {
return reply.status(400).send({
error: 'url is required'
});
}
try {
const summary = await summaly(url, {
lang: req.query.lang,
followRedirects: false,
...options,
});
return summary;
}
catch (e) {
return reply.status(500).send({
error: e
});
}
});
done();
}