feat(route/tumblr): Add Tumblr posts route (#19646)
* Add Tumblr posts route * Reorder based on name * Store refresh token longer * Remove radar route as it cannot match part of a path * Maintainer name case * Throw ConfigNotFoundError if minimum required config is not present * Camel case function name and reorder to be alphabetical * Keep refresh token for a year * Don't trust refactoring * Get limit from query params * Remove old doc * Retrieve post tags
This commit is contained in:
@@ -359,6 +359,11 @@ export type Config = {
|
||||
tsdm39: {
|
||||
cookie: string;
|
||||
};
|
||||
tumblr: {
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
refreshToken?: string;
|
||||
};
|
||||
twitter: {
|
||||
username?: string[];
|
||||
password?: string[];
|
||||
@@ -825,6 +830,11 @@ const calculateValue = () => {
|
||||
tsdm39: {
|
||||
cookie: envs.TSDM39_COOKIES,
|
||||
},
|
||||
tumblr: {
|
||||
clientId: envs.TUMBLR_CLIENT_ID,
|
||||
clientSecret: envs.TUMBLR_CLIENT_SECRET,
|
||||
refreshToken: envs.TUMBLR_REFRESH_TOKEN,
|
||||
},
|
||||
twitter: {
|
||||
username: envs.TWITTER_USERNAME?.split(','),
|
||||
password: envs.TWITTER_PASSWORD?.split(','),
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { Namespace } from '@/types';
|
||||
|
||||
export const namespace: Namespace = {
|
||||
name: 'Tumblr',
|
||||
url: 'tumblr.com',
|
||||
lang: 'en',
|
||||
description: `Register an application on \`https://www.tumblr.com/oauth/apps\`.
|
||||
|
||||
- \`TUMBLR_CLIENT_ID\`: The key is labelled as \`OAuth consumer Key\` in the info page of the registered application.
|
||||
- \`TUMBLR_CLIENT_SECRET\`: The key is labelled as \`OAuth consumer Secret\` in the info page of the registered application.
|
||||
- \`TUMBLR_REFRESH_TOKEN\`: Navigate to \`https://www.tumblr.com/oauth2/authorize?client_id=\${CLIENT_ID}&response_type=code&scope=basic%20offline_access&state=mystate\` in your browser and login. After doing so, you'll be redirected to the URL you defined when registering the application. Look for the \`code\` parameter in the URL. You can then call \`curl -F grant_type=authorization_code -F "code=\${CODE}" -F "client_id=\${CLIENT_ID}" -F "client_secret=\${CLIENT_SECRET}" "https://api.tumblr.com/v2/oauth2/token"\`
|
||||
|
||||
Two login methods are currently supported:
|
||||
|
||||
- \`TUMBLR_CLIENT_ID\`: The key never expires, however blogs that are "dashboard only" cannot be accessed.
|
||||
- \`TUMBLR_CLIENT_ID\` + \`TUMBLR_CLIENT_SECRET\` + \`TUMBLR_REFRESH_TOKEN\`: The refresh token will expire and will need to be regenerated, "dashboard only" blogs can be accessed.`,
|
||||
};
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Data, Route } from '@/types';
|
||||
import got from '@/utils/got';
|
||||
import utils from './utils';
|
||||
import type { Context } from 'hono';
|
||||
import { config } from '@/config';
|
||||
import ConfigNotFoundError from '@/errors/types/config-not-found';
|
||||
import { fallback, queryToInteger } from '@/utils/readable-social';
|
||||
|
||||
export const route: Route = {
|
||||
path: '/posts/:blog',
|
||||
categories: ['blog'],
|
||||
example: '/tumblr/posts/biketouring-nearby',
|
||||
parameters: {
|
||||
blog: 'Blog identifier (see `https://www.tumblr.com/docs/en/api/v2#blog-identifiers`)',
|
||||
},
|
||||
radar: [],
|
||||
features: {
|
||||
requireConfig: [
|
||||
{
|
||||
name: 'TUMBLR_CLIENT_ID',
|
||||
description: 'Please see above for details.',
|
||||
},
|
||||
{
|
||||
name: 'TUMBLR_CLIENT_SECRET',
|
||||
description: 'Please see above for details.',
|
||||
},
|
||||
{
|
||||
name: 'TUMBLR_REFRESH_TOKEN',
|
||||
description: 'Please see above for details.',
|
||||
},
|
||||
],
|
||||
requirePuppeteer: false,
|
||||
antiCrawler: false,
|
||||
supportBT: false,
|
||||
supportPodcast: false,
|
||||
supportScihub: false,
|
||||
},
|
||||
name: 'Posts',
|
||||
maintainers: ['Rakambda'],
|
||||
description: `::: tip
|
||||
Tumblr provides official RSS feeds for non "dashboard only" blogs, for instance [https://biketouring-nearby.tumblr.com](https://biketouring-nearby.tumblr.com/rss).
|
||||
:::`,
|
||||
handler,
|
||||
};
|
||||
|
||||
async function handler(ctx: Context): Promise<Data> {
|
||||
if (!config.tumblr || !config.tumblr.clientId) {
|
||||
throw new ConfigNotFoundError('Tumblr RSS is disabled due to the lack of <a href="https://docs.rsshub.app/deploy/config#route-specific-configurations">relevant config</a>');
|
||||
}
|
||||
|
||||
const blogIdentifier = ctx.req.param('blog');
|
||||
const limit = fallback(undefined, queryToInteger(ctx.req.query('limit')), 20);
|
||||
|
||||
const response = await got.get(`https://api.tumblr.com/v2/blog/${blogIdentifier}/posts`, {
|
||||
searchParams: {
|
||||
...utils.generateAuthParams(),
|
||||
limit,
|
||||
},
|
||||
headers: await utils.generateAuthHeaders(),
|
||||
});
|
||||
|
||||
const blog = response.data.response.blog;
|
||||
const posts = response.data.response.posts.map((post: any) => utils.processPost(post));
|
||||
|
||||
return {
|
||||
title: `Tumblr - ${blogIdentifier} - Posts`,
|
||||
author: blog?.name,
|
||||
link: blog?.url ?? `https://${blogIdentifier}/`,
|
||||
item: posts,
|
||||
allowEmpty: true,
|
||||
image: blog?.avatar?.slice(-1)?.url,
|
||||
description: blog?.description,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { parseDate } from '@/utils/parse-date';
|
||||
import { DataItem } from '@/types';
|
||||
import { config } from '@/config';
|
||||
import cache from '@/utils/cache';
|
||||
import logger from '@/utils/logger';
|
||||
import got from '@/utils/got';
|
||||
|
||||
const getAccessToken: () => Promise<string | null> = async () => {
|
||||
let accessToken: string | null = await cache.get('tumblr:accessToken', false);
|
||||
if (!accessToken) {
|
||||
try {
|
||||
const newAccessToken = await tokenRefresher();
|
||||
if (newAccessToken) {
|
||||
accessToken = newAccessToken;
|
||||
}
|
||||
} catch (error) {
|
||||
// Return the `accessToken=null` value to indicate that the token is not available. Calls will only use the `apiKey` as a fallback to maybe hit non "dashborad only" blogs.
|
||||
logger.error('Failed to refresh Tumblr token, using only client id as fallback', error);
|
||||
}
|
||||
}
|
||||
return accessToken;
|
||||
};
|
||||
|
||||
const generateAuthHeaders: () => Promise<{ Authorization?: string }> = async () => {
|
||||
const accessToken = await getAccessToken();
|
||||
if (!accessToken) {
|
||||
return {};
|
||||
}
|
||||
return {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
};
|
||||
};
|
||||
|
||||
const generateAuthParams: () => { apiKey?: string } = () => ({
|
||||
apiKey: config.tumblr.clientId,
|
||||
});
|
||||
|
||||
const processPost: (post: any) => DataItem = (post) => {
|
||||
let description = '';
|
||||
|
||||
switch (post.type) {
|
||||
case 'text':
|
||||
description = post.body;
|
||||
break;
|
||||
case 'photo':
|
||||
for (const photo of post.photos ?? []) {
|
||||
description += `<img src="${photo.original_size.url}"/><br/>`;
|
||||
}
|
||||
break;
|
||||
case 'link':
|
||||
description = post.url;
|
||||
break;
|
||||
case 'audio':
|
||||
description = post.embed;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return {
|
||||
id: post.id_string,
|
||||
title: post.summary ?? `New post from ${post.blog_name}`,
|
||||
link: post.post_url,
|
||||
pubDate: parseDate(post.timestamp * 1000),
|
||||
category: post.tags,
|
||||
description,
|
||||
};
|
||||
};
|
||||
|
||||
let tokenRefresher: () => Promise<string | null> = () => Promise.resolve(null);
|
||||
if (config.tumblr && config.tumblr.clientId && config.tumblr.clientSecret && config.tumblr.refreshToken) {
|
||||
tokenRefresher = async (): Promise<string | null> => {
|
||||
let refreshToken = config.tumblr.refreshToken;
|
||||
|
||||
// Restore already refreshed tokens
|
||||
const previousRefreshTokenSerialized = await cache.get('tumblr:refreshToken', false);
|
||||
if (previousRefreshTokenSerialized) {
|
||||
const previousRefreshToken = JSON.parse(previousRefreshTokenSerialized);
|
||||
if (previousRefreshToken.startToken === refreshToken) {
|
||||
refreshToken = previousRefreshToken.currentToken;
|
||||
}
|
||||
}
|
||||
const response = await got.post('https://api.tumblr.com/v2/oauth2/token', {
|
||||
form: {
|
||||
grant_type: 'refresh_token',
|
||||
client_id: config.tumblr.clientId,
|
||||
client_secret: config.tumblr.clientSecret,
|
||||
refresh_token: refreshToken,
|
||||
},
|
||||
});
|
||||
if (!response.data?.access_token || !response.data?.refresh_token) {
|
||||
return null;
|
||||
}
|
||||
const accessToken = response.data.access_token;
|
||||
const newRefreshToken = response.data.refresh_token;
|
||||
const expiresIn = response.data.expires_in;
|
||||
|
||||
// Access tokens expire after 42 minutes, remove 30 seconds to renew the token before it expires (to avoid making a request right when it ends).
|
||||
await cache.set('tumblr:accessToken', accessToken, (expiresIn ?? 2520) - 30);
|
||||
// Store the new refresh token associated with the one that was provided first.
|
||||
// We may be able to restore the new token if the app is restarted. This will avoid reusing the old token and have a failing request.
|
||||
// Keep it for a year (not clear how long the refresh token lasts).
|
||||
const cacheEntry = { startToken: config.tumblr.refreshToken, currentToken: newRefreshToken };
|
||||
await cache.set(`tumblr:refreshToken`, JSON.stringify(cacheEntry), 31_536_000);
|
||||
|
||||
return accessToken;
|
||||
};
|
||||
}
|
||||
|
||||
export default { processPost, generateAuthParams, generateAuthHeaders };
|
||||
Reference in New Issue
Block a user