* chore(deps-dev): bump eslint-plugin-unicorn from 65.0.1 to 66.0.0 Bumps [eslint-plugin-unicorn](https://github.com/sindresorhus/eslint-plugin-unicorn) from 65.0.1 to 66.0.0. - [Release notes](https://github.com/sindresorhus/eslint-plugin-unicorn/releases) - [Commits](https://github.com/sindresorhus/eslint-plugin-unicorn/compare/v65.0.1...v66.0.0) --- updated-dependencies: - dependency-name: eslint-plugin-unicorn dependency-version: 66.0.0 dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> * style: fix unicorn-js/prefer-url-href * style: oxlint disable * style: fix unicorn-js/no-useless-else * style: no-unsafe-string-replacement * style: fix no-duplicate-loops * style: fix prefer-number-is-safe-integer * style: fix prefer-single-array-predicate * style: fix no-object-methods-with-collections * style: fix no-useless-boolean-cast * style: fix no-useless-template-literals * style: fix no-negated-array-predicate * style: fix prefer-direct-iteration * style: fix consistent-optional-chaining * style: fix prefer-simple-sort-comparator * style: fix prefer-global-number-constants * style: fix prefer-type-literal-last * style: fix require-array-sort-compare. * style: fix prefer-early-return * style: fix prefer-short-arrow-method * style: fix prefer-array-from-map * style: fix prefer-scoped-selector * style: fix no-global-object-property-assignment * style: fix no-unnecessary-global-this * style: fix no-unreadable-object-destructuring * style: fix no-invalid-argument-count * style: fix prefer-smaller-scope * style: fix prefer-iterator-to-array. * style: fix prefer-object-iterable-methods * style: fix typo * style: fix max-nested-calls * style: fix no-incorrect-template-string-interpolation * style: fix no-break-in-nested-loop * style: fix prefer-await * style: fix no-computed-property-existence-check * style: fix prefer-number-coercion * style: fix no-empty-file * style: update eslint unicorn v66 recommended preset * style: add unicorn/prefer-spread to oxlint-disable comments * style: fix no-array-reduce * style: delete github/no-then as it's covered by unicorn/prefer-await --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Tony <TonyRL@users.noreply.github.com>
209 lines
7.8 KiB
TypeScript
209 lines
7.8 KiB
TypeScript
import { APIErrorCode, Client, isNotionClientError } from '@notionhq/client';
|
|
import { load } from 'cheerio';
|
|
import MarkdownIt from 'markdown-it';
|
|
import { NotionToMarkdown } from 'notion-to-md';
|
|
|
|
import { config } from '@/config';
|
|
import ConfigNotFoundError from '@/errors/types/config-not-found';
|
|
import InvalidParameterError from '@/errors/types/invalid-parameter';
|
|
import type { Route } from '@/types';
|
|
import cache from '@/utils/cache';
|
|
import got from '@/utils/got';
|
|
import logger from '@/utils/logger';
|
|
import { parseDate } from '@/utils/parse-date';
|
|
|
|
const md = MarkdownIt({
|
|
html: true,
|
|
linkify: true,
|
|
});
|
|
|
|
export const route: Route = {
|
|
path: '/database/:databaseId',
|
|
categories: ['other'],
|
|
example: '/notion/database/a7cc133b68454f138011f1530a13531e',
|
|
parameters: { databaseId: 'Database ID' },
|
|
features: {
|
|
requireConfig: [
|
|
{
|
|
name: 'NOTION_TOKEN',
|
|
description: '',
|
|
},
|
|
],
|
|
requirePuppeteer: false,
|
|
antiCrawler: false,
|
|
supportBT: false,
|
|
supportPodcast: false,
|
|
supportScihub: false,
|
|
},
|
|
radar: [
|
|
{
|
|
source: ['notion.so/:id'],
|
|
target: '/database/:id',
|
|
},
|
|
],
|
|
name: 'Database',
|
|
maintainers: ['curly210102'],
|
|
handler,
|
|
description: `There is an optional query parameter called \`properties=\` that can be used to customize field mapping. There are three built-in fields: author, pubTime and link, which can be used to add additional information.
|
|
|
|
For example, if you have set up three properties in your database - "Publish Time", "Author", and "Original Article Link" - then execute the following JavaScript code to get the result for the properties parameter.
|
|
|
|
\`\`\`js
|
|
encodeURIComponent(JSON.stringify({"pubTime": "Publish Time", "author": "Author", "link": "Original Article Link"}))
|
|
\`\`\`
|
|
|
|
There is an optional query parameter called \`query=\` that can be used to customize the search rules for your database, such as custom sorting and filtering rules.
|
|
|
|
please refer to the [Notion API documentation](https://developers.notion.com/reference/post-database-query) and execute \`encodeURIComponent(JSON.stringify(custom rules))\` to provide the query parameter.`,
|
|
};
|
|
|
|
async function handler(ctx) {
|
|
if (!config.notion.key) {
|
|
throw new ConfigNotFoundError('Notion RSS is disabled due to the lack of NOTION_TOKEN(<a href="https://docs.rsshub.app/deploy/config#route-specific-configurations">relevant config</a>)');
|
|
}
|
|
|
|
const databaseId = ctx.req.param('databaseId');
|
|
const notion_api_key = config.notion.key;
|
|
|
|
const notion = new Client({
|
|
auth: notion_api_key,
|
|
});
|
|
|
|
try {
|
|
// Query database basic info
|
|
const database = await notion.databases.retrieve({ database_id: databaseId });
|
|
const title = database.title[0]?.plain_text;
|
|
const description = database.description[0]?.plain_text;
|
|
const link = database.url;
|
|
const image = database.cover?.external.url ?? database.icon?.emoji;
|
|
|
|
// List pages under the database
|
|
const databaseQuery = parseCustomQuery(ctx.req.query('query'));
|
|
const { results } = await notion.databases.query({
|
|
database_id: databaseId,
|
|
...databaseQuery,
|
|
});
|
|
const customProperties = parseCustomQuery(ctx.req.query('properties')) ?? {};
|
|
const properties = {
|
|
author: customProperties.author ?? 'Author',
|
|
link: customProperties.link ?? 'URL',
|
|
pubTime: customProperties.pubTime ?? 'Created time',
|
|
};
|
|
|
|
// Query page content
|
|
const n2m = new NotionToMarkdown({ notionClient: notion });
|
|
const pageList = results.filter((item) => Object.values(item.properties).find((property) => property.id === 'title')?.title[0]?.plain_text);
|
|
const items = await Promise.all(
|
|
pageList.map(async (page) => {
|
|
const titleProperty = Object.values(page.properties).find((property) => property.id === 'title');
|
|
const pageTitle = titleProperty.title[0].plain_text;
|
|
const pageLink = page.url;
|
|
const pageLastEditedTime = page.last_edited_time;
|
|
// If link property is empty, try to get url with linked title
|
|
const articleLink = (properties.link && notionText(page.properties[properties.link])) || titleProperty.title[0].href || '';
|
|
const pageAuthor = notionText(page.properties[properties.author]);
|
|
const pagePubTime = notionText(page.properties[properties.pubTime]);
|
|
|
|
// Convert Notion page blocks to markdown string
|
|
const articleContent = await cache.tryGet(`${pageLink}-${pageLastEditedTime}`, async () => {
|
|
const mdblocks = await n2m.pageToMarkdown(page.id);
|
|
const mdString = n2m.toMarkdownString(mdblocks);
|
|
return mdString.parent;
|
|
});
|
|
|
|
let author = pageAuthor;
|
|
let pubTime = pagePubTime || pageLastEditedTime;
|
|
// Try to get author info
|
|
if (articleLink && !pageAuthor) {
|
|
const { articleAuthor, articlePubTime } = await cache.tryGet(`${pageLink}-${articleLink}`, async () => {
|
|
try {
|
|
const response = await got({
|
|
method: 'get',
|
|
url: articleLink,
|
|
});
|
|
const $ = load(response.body);
|
|
const articleAuthor = $('meta[name="author"]').attr('content');
|
|
const articlePubTime = $('meta[name="publish_date"], meta[name="date"]').attr('content');
|
|
return {
|
|
articleAuthor,
|
|
articlePubTime,
|
|
};
|
|
} catch {
|
|
return {};
|
|
}
|
|
});
|
|
|
|
if (articleAuthor) {
|
|
author = articleAuthor;
|
|
}
|
|
|
|
if (articlePubTime) {
|
|
pubTime = articlePubTime;
|
|
}
|
|
}
|
|
|
|
return {
|
|
title: pageTitle,
|
|
author,
|
|
pubDate: parseDate(pubTime),
|
|
description: md.render(articleContent ?? ''),
|
|
link: articleLink || pageLink,
|
|
};
|
|
})
|
|
);
|
|
|
|
return {
|
|
title: `Notion - ${title}`,
|
|
link,
|
|
description,
|
|
image,
|
|
item: items,
|
|
allowEmpty: true,
|
|
};
|
|
} catch (error) {
|
|
logger.error(error);
|
|
|
|
if (isNotionClientError(error)) {
|
|
if (error.statusCode === APIErrorCode.ObjectNotFound) {
|
|
throw new InvalidParameterError('The database is not exist');
|
|
}
|
|
if (error.statusCode === APIErrorCode.Unauthorized) {
|
|
throw new ConfigNotFoundError('Please check the config of NOTION_TOKEN');
|
|
}
|
|
ctx.throw(error.statusCode, 'Notion API Error');
|
|
} else {
|
|
ctx.throw(error);
|
|
}
|
|
}
|
|
}
|
|
|
|
function parseCustomQuery(queryString) {
|
|
try {
|
|
if (queryString) {
|
|
return JSON.parse(decodeURIComponent(queryString));
|
|
}
|
|
} catch {
|
|
logger.error('Query Parse Error');
|
|
}
|
|
}
|
|
|
|
function notionText(property) {
|
|
if (!property) {
|
|
return '';
|
|
}
|
|
|
|
if (property.type === 'rich_text') {
|
|
return property.rich_text?.map((text) => text.plain_text).join('') ?? '';
|
|
}
|
|
|
|
if (property.type === 'select') {
|
|
return property.select.name;
|
|
}
|
|
|
|
if (property.type === 'url') {
|
|
return property.url;
|
|
}
|
|
|
|
return '';
|
|
}
|