feat(route): youtube subscriptions (#9824)

This commit is contained in:
Tony
2022-05-26 20:37:12 +08:00
committed by GitHub
parent 5a46d1edaf
commit e953f9f456
18 changed files with 314 additions and 168 deletions
-8
View File
@@ -105,14 +105,6 @@
{ title: '关键词', docs: 'https://docs.rsshub.app/social-media.html#twitter', source: '/search', target: (params, url) => `/twitter/keyword/${new URL(url).searchParams.get('q')}` },
],
},
'youtube.com': {
_name: 'YouTube',
www: [
{ title: '用户', docs: 'https://docs.rsshub.app/social-media.html#youtube', source: '/user/:username', target: '/youtube/user/:username' },
{ title: '频道', docs: 'https://docs.rsshub.app/social-media.html#youtube', source: '/channel/:id', target: '/youtube/channel/:id' },
{ title: '播放列表', docs: 'https://docs.rsshub.app/social-media.html#youtube', source: '/playlist', target: (params, url) => `/youtube/playlist/${new URL(url).searchParams.get('list')}` },
],
},
'github.com': {
_name: 'GitHub',
'.': [
+14 -9
View File
@@ -643,20 +643,20 @@ See docs of the specified route and `lib/config.js` for detailed information.
- `SCIHUB_HOST`: The Sci-hub mirror address that is accessible from your location, default to `https://sci-hub.se`.
- spotify: [API key registration](https://developer.spotify.com)
- Spotify: [API key registration](https://developer.spotify.com)
- `SPOTIFY_CLIENT_ID`:Client ID of the application
- `SPOTIFY_CLIENT_SECRET`:Client secret of the application
- `SPOTIFY_CLIENT_ID`: Client ID of the application
- `SPOTIFY_CLIENT_SECRET`: Client secret of the application
- spotify (user data related routes):
- Spotify (user data related routes):
- `SPOTIFY_REFRESHTOKEN`:The refresh token of the user from the Spotify application. Check [this gist](https://gist.github.com/outloudvi/d1bbeb5e989db5385384a223a7263744) for detailed information.
- `SPOTIFY_REFRESHTOKEN`: The refresh token of the user from the Spotify application. Check [this gist](https://gist.github.com/outloudvi/d1bbeb5e989db5385384a223a7263744) for detailed information.
- telegram: [Bot application](https://telegram.org/blog/bot-revolution)
- Telegram: [Bot application](https://telegram.org/blog/bot-revolution)
- `TELEGRAM_TOKEN`: Telegram bot token
- twitter: [Application creation](https://apps.twitter.com)
- Twitter: [Application creation](https://apps.twitter.com)
- `TWITTER_CONSUMER_KEY`: Twitter Developer API key, support multiple keys, split them with `,`
- `TWITTER_CONSUMER_SECRET`: Twitter Developer API key secret, support multiple keys, split them with `,`
@@ -675,6 +675,11 @@ See docs of the specified route and `lib/config.js` for detailed information.
| https://cors.netnr.workers.dev/ | cloudflare |
| https://netnr-proxy.openode.io/ | digitalocean |
- youtube: [API Key application](https://console.developers.google.com/)
- YouTube: [API Key application](https://console.developers.google.com/)
- `YOUTUBE_KEY`: YouTube API Key, support multiple keys, split them with `,`
- All routes:
- `YOUTUBE_KEY`: YouTube API Key, support multiple keys, split them with `,`
- Extra requirements for subscriptions route:
- `YOUTUBE_CLIENT_ID`: YouTube API OAuth 2.0 client ID
- `YOUTUBE_CLIENT_SECRET`: YouTube API OAuth 2.0 client secret
- `YOUTUBE_REFRESH_TOKEN`: YouTube API OAuth 2.0 refresh token. Check [this gist](https://gist.github.com/Kurukshetran/5904e8cb2361623498481f4a9a1338aa) for detailed instructions.
+7 -3
View File
@@ -412,7 +412,7 @@ Tiny Tiny RSS will add `sandbox="allow-scripts"` to all iframe elements, as a re
### User
<RouteEn path="/youtube/user/:username/:embed?" example="/youtube/user/JFlaMusic" :paramsDesc="['YouTuber id', 'Default to embed the video, set to any value to disable embedding']" radar="1" rssbud="1"/>
<RouteEn author="DIYgod" path="/youtube/user/:username/:embed?" example="/youtube/user/JFlaMusic" :paramsDesc="['YouTuber id', 'Default to embed the video, set to any value to disable embedding']" radar="1" rssbud="1"/>
### Channel
@@ -422,8 +422,12 @@ YouTube provides official RSS feeds for channels, for instance <https://www.yout
:::
<RouteEn path="/youtube/channel/:id/:embed?" example="/youtube/channel/UCDwDMPOZfxVV0x_dz0eQ8KQ" :paramsDesc="['YouTube channel id', 'Default to embed the video, set to any value to disable embedding']" radar="1" rssbud="1"/>
<RouteEn author="DIYgod" path="/youtube/channel/:id/:embed?" example="/youtube/channel/UCDwDMPOZfxVV0x_dz0eQ8KQ" :paramsDesc="['YouTube channel id', 'Default to embed the video, set to any value to disable embedding']" radar="1" rssbud="1"/>
### Playlist
<RouteEn path="/youtube/playlist/:id/:embed?" example="/youtube/playlist/PLqQ1RwlxOgeLTJ1f3fNMSwhjVgaWKo_9Z" :paramsDesc="['YouTube playlist id', 'Default to embed the video, set to any value to disable embedding']" radar="1" rssbud="1"/>
<RouteEn author="HenryQW" path="/youtube/playlist/:id/:embed?" example="/youtube/playlist/PLqQ1RwlxOgeLTJ1f3fNMSwhjVgaWKo_9Z" :paramsDesc="['YouTube playlist id', 'Default to embed the video, set to any value to disable embedding']" radar="1" rssbud="1"/>
### Subscriptions
<RouteEn author="TonyRL" path="/youtube/subscriptions/:embed?" example="/youtube/subscriptions" :paramsDesc="['Default to embed the video, set to any value to disable embedding']" selfhost="1" radar="1" rssbud="1"/>
+16 -11
View File
@@ -631,7 +631,7 @@ RSSHub 支持使用访问密钥 / 码,白名单和黑名单三种方式进行
- `GOOGLE_FONTS_API_KEY`: API key
- Instagram:
- Instagram:
- `IG_USERNAME`: Instagram 用户名。
- `IG_PASSWORD`: Instagram 密码。
@@ -659,12 +659,12 @@ RSSHub 支持使用访问密钥 / 码,白名单和黑名单三种方式进行
- `NGA_PASSPORT_UID`: 对应 cookie 中的 `ngaPassportUid`.
- `NGA_PASSPORT_CID`: 对应 cookie 中的 `ngaPassportCid`.
- nhentai torrent: [注册地址](https://nhentai.net/register/)
- nhentai torrent:[注册地址](https://nhentai.net/register/)
- `NHENTAI_USERNAME`: nhentai 用户名或邮箱
- `NHENTAI_PASSWORD`: nhentai 密码
- pianyuan 全部路由: [注册地址](https://pianyuan.org)
- pianyuan 全部路由:[注册地址](https://pianyuan.org)
- `PIANYUAN_COOKIE`: 对应 cookie 中的 `py_loginauth`, 例: PIANYUAN_COOKIE='py_loginauth=xxxxxxxxxx'
@@ -684,20 +684,20 @@ RSSHub 支持使用访问密钥 / 码,白名单和黑名单三种方式进行
- `SCIHUB_HOST`: 可访问的 sci-hub 镜像地址,默认为 `https://sci-hub.se`。
- spotify 全部路由: [注册地址](https://developer.spotify.com)
- Spotify 全部路由:[注册地址](https://developer.spotify.com)
- `SPOTIFY_CLIENT_ID`:Spotify 应用的 client ID
- `SPOTIFY_CLIENT_SECRET`:Spotify 应用的 client secret
- `SPOTIFY_CLIENT_ID`: Spotify 应用的 client ID
- `SPOTIFY_CLIENT_SECRET`: Spotify 应用的 client secret
- spotify 用户相关路由
- Spotify 用户相关路由
- `SPOTIFY_REFRESHTOKEN`:用户在此 Spotify 应用的 refresh token。可以利用 [此 gist](https://gist.github.com/outloudvi/d1bbeb5e989db5385384a223a7263744) 获取。
- telegram - 贴纸包路由:[Telegram 机器人](https://telegram.org/blog/bot-revolution)
- Telegram - 贴纸包路由:[Telegram 机器人](https://telegram.org/blog/bot-revolution)
- `TELEGRAM_TOKEN`: Telegram 机器人 token
- twitter 全部路由:[申请地址](https://apps.twitter.com)
- Twitter 全部路由:[申请地址](https://apps.twitter.com)
- `TWITTER_CONSUMER_KEY`: Twitter Developer API key,支持多个 key,用英文逗号 `,` 隔开
- `TWITTER_CONSUMER_SECRET`: Twitter Developer API key secret,支持多个 key,用英文逗号 `,` 隔开,顺序与 key 对应
@@ -716,9 +716,14 @@ RSSHub 支持使用访问密钥 / 码,白名单和黑名单三种方式进行
| <https://cors.netnr.workers.dev/> | cloudflare |
| <https://netnr-proxy.openode.io/> | digitalocean |
- youtube 全部路由:[申请地址](https://console.developers.google.com/)
- YouTube:[申请地址](https://console.developers.google.com/)
- `YOUTUBE_KEY`: YouTube API Key,支持多个 key,用英文逗号 `,` 隔开
- 全部路由
- `YOUTUBE_KEY`: YouTube API Key,支持多个 key,用英文逗号 `,` 隔开
- 订阅列表路由额外设置
- `YOUTUBE_CLIENT_ID`: YouTube API 的 OAuth 2.0 客户端 ID
- `YOUTUBE_CLIENT_SECRET`: YouTube API 的 OAuth 2.0 客户端 Secret
- `YOUTUBE_REFRESH_TOKEN`: YouTube API 的 OAuth 2.0 客户端 Refresh Token。可以按照[此 gist](https://gist.github.com/Kurukshetran/5904e8cb2361623498481f4a9a1338aa) 获取。
- 北大未名 BBS 全站十大
+4
View File
@@ -800,6 +800,10 @@ YouTube 官方亦有提供频道 RSS,形如 <https://www.youtube.com/feeds/vid
<Route author="HenryQW" example="/youtube/playlist/PLqQ1RwlxOgeLTJ1f3fNMSwhjVgaWKo_9Z" path="/youtube/playlist/:id/:disableEmbed?" :paramsDesc="['播放列表 id', '默认为开启内嵌视频, 任意值为关闭']" radar="1" rssbud="1"/>
### 订阅列表
<Route author="TonyRL" path="/youtube/subscriptions/:embed?" example="/youtube/subscriptions" :paramsDesc="['默认为开启内嵌视频, 任意值为关闭']" selfhost="1" radar="1" rssbud="1"/>
## 巴哈姆特
### 个人小屋
+3
View File
@@ -251,6 +251,9 @@ const calculateValue = () => {
},
youtube: {
key: envs.YOUTUBE_KEY,
clientId: envs.YOUTUBE_CLIENT_ID,
clientSecret: envs.YOUTUBE_CLIENT_SECRET,
refreshToken: envs.YOUTUBE_REFRESH_TOKEN,
},
yuque: {
token: envs.YUQUE_TOKEN,
-23
View File
@@ -131,29 +131,6 @@ module.exports = {
},
],
},
'youtube.com': {
_name: 'YouTube',
www: [
{
title: '用户',
docs: 'https://docs.rsshub.app/social-media.html#youtube',
source: '/user/:username',
target: '/youtube/user/:username',
},
{
title: '频道',
docs: 'https://docs.rsshub.app/social-media.html#youtube',
source: '/channel/:id',
target: '/youtube/channel/:id',
},
{
title: '播放列表',
docs: 'https://docs.rsshub.app/social-media.html#youtube',
source: '/playlist',
target: (params, url) => `/youtube/playlist/${new URL(url).searchParams.get('list')}`,
},
],
},
'smzdm.com': {
_name: '什么值得买',
www: [
+4 -4
View File
@@ -160,10 +160,10 @@ router.get('/twitter/keyword/:keyword/:routeParams?/:limit?', lazyloadRouteHandl
router.get('/twitter/trends/:woeid?', lazyloadRouteHandler('./routes/twitter/trends'));
router.get('/twitter/media/:id/:routeParams?', lazyloadRouteHandler('./routes/twitter/media'));
// YouTube
router.get('/youtube/user/:username/:embed?', lazyloadRouteHandler('./routes/youtube/user'));
router.get('/youtube/channel/:id/:embed?', lazyloadRouteHandler('./routes/youtube/channel'));
router.get('/youtube/playlist/:id/:embed?', lazyloadRouteHandler('./routes/youtube/playlist'));
// YouTube migrated to v2
// router.get('/youtube/user/:username/:embed?', lazyloadRouteHandler('./routes/youtube/user'));
// router.get('/youtube/channel/:id/:embed?', lazyloadRouteHandler('./routes/youtube/channel'));
// router.get('/youtube/playlist/:id/:embed?', lazyloadRouteHandler('./routes/youtube/playlist'));
// 极客时间
router.get('/geektime/column/:cid', lazyloadRouteHandler('./routes/geektime/column'));
-90
View File
@@ -1,90 +0,0 @@
const { google } = require('googleapis');
const config = require('@/config').value;
let count = 0;
const youtube = {};
if (config.youtube.key) {
const keys = config.youtube.key.split(',');
keys.forEach((key, index) => {
if (key) {
youtube[index] = google.youtube({
version: 'v3',
auth: key,
});
count = index + 1;
}
});
}
let index = -1;
const exec = async (func) => {
let result;
for (let i = 0; i < count; i++) {
index++;
try {
// eslint-disable-next-line no-await-in-loop
result = await func(youtube[index % count]);
break;
} catch (error) {
// console.error(error);
}
}
return result;
};
const youtubeUtils = {
getPlaylistItems: async (id, part) => {
const res = await exec((youtube) =>
youtube.playlistItems.list({
part,
playlistId: id,
maxResults: 50, // youtube api param value default is 5
})
);
return res;
},
getPlaylist: (id, part, cache) =>
cache.tryGet('getPlaylist' + id, async () => {
const res = await exec((youtube) =>
youtube.playlists.list({
part,
id,
})
);
return res;
}),
getChannelWithId: (id, part, cache) =>
cache.tryGet('getChannelWithId' + id, async () => {
const res = await exec((youtube) =>
youtube.channels.list({
part,
id,
})
);
return res;
}),
getChannelWithUsername: (username, part, cache) =>
cache.tryGet('getPlaylist' + username, async () => {
const res = await exec((youtube) =>
youtube.channels.list({
part,
forUsername: username,
})
);
return res;
}),
getVideoAuthor: async (id, part) => {
const res = await exec((youtube) =>
youtube.videos.list({
part,
id,
})
);
return res;
},
getThumbnail: (thumbnails) => thumbnails.maxres || thumbnails.standard || thumbnails.high || thumbnails.medium || thumbnails.default,
formatDescription: (description) => description.replace(/(?:\r\n|\r|\n)/g, '<br>'),
};
module.exports = youtubeUtils;
@@ -1,5 +1,6 @@
const utils = require('./utils');
const config = require('@/config').value;
const { parseDate } = require('@/utils/parse-date');
module.exports = async (ctx) => {
if (!config.youtube || !config.youtube.key) {
@@ -8,9 +9,14 @@ module.exports = async (ctx) => {
const id = ctx.params.id;
const embed = !ctx.params.embed;
// taken from https://webapps.stackexchange.com/a/101153
if (!/^UC[\w-]{21}[AQgw]$/.test(id)) {
throw `Invalid YouTube channel ID. \nYou may want to use <a href="/youtube/user/${id}">/youtube/user/${id}</a> instead.`;
}
const playlistId = (await utils.getChannelWithId(id, 'contentDetails', ctx.cache)).data.items[0].contentDetails.relatedPlaylists.uploads;
const data = (await utils.getPlaylistItems(playlistId, 'snippet,contentDetails')).data.items;
const data = (await utils.getPlaylistItems(playlistId, 'snippet', ctx.cache)).data.items;
ctx.state.data = {
title: `${data[0].snippet.channelTitle} - YouTube`,
@@ -24,10 +30,8 @@ module.exports = async (ctx) => {
const img = utils.getThumbnail(snippet.thumbnails);
return {
title: snippet.title,
description: `${
embed ? '<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube-nocookie.com/embed/' + videoId + '" frameborder="0" allowfullscreen></iframe>' : '<img src="' + img.url + '">'
}${utils.formatDescription(snippet.description)}`,
pubDate: new Date(snippet.publishedAt).toUTCString(),
description: utils.renderDescription(embed, videoId, img, utils.formatDescription(snippet.description)),
pubDate: parseDate(snippet.publishedAt),
link: `https://www.youtube.com/watch?v=${videoId}`,
};
}),
+6
View File
@@ -0,0 +1,6 @@
module.exports = {
'/channel/:id/:embed?': ['DIYgod'],
'/playlist/:id/:embed?': ['HenryQW'],
'/subscriptions/:embed?': ['TonyRL'],
'/user/:username/:embed?': ['DIYgod'],
};
@@ -1,5 +1,6 @@
const utils = require('./utils');
const config = require('@/config').value;
const { parseDate } = require('@/utils/parse-date');
module.exports = async (ctx) => {
if (!config.youtube || !config.youtube.key) {
@@ -10,27 +11,22 @@ module.exports = async (ctx) => {
const playlistTitle = (await utils.getPlaylist(id, 'snippet', ctx.cache)).data.items[0].snippet.title;
const data = (await utils.getPlaylistItems(id, 'snippet')).data.items.filter((d) => d.snippet.title !== 'Private video' && d.snippet.title !== 'Deleted video');
const ids = data.map((item) => item.snippet.resourceId.videoId).join(',');
const authors = (await utils.getVideoAuthor(ids, 'snippet')).data.items;
const data = (await utils.getPlaylistItems(id, 'snippet', ctx.cache)).data.items.filter((d) => d.snippet.title !== 'Private video' && d.snippet.title !== 'Deleted video');
ctx.state.data = {
title: `${playlistTitle} by ${data[0].snippet.channelTitle} - YouTube`,
link: `https://www.youtube.com/playlist?list=${id}`,
description: `YouTube playlist ${playlistTitle} by ${data[0].snippet.channelTitle}`,
item: data.map((item, index) => {
item: data.map((item) => {
const snippet = item.snippet;
const videoId = snippet.resourceId.videoId;
const img = utils.getThumbnail(snippet.thumbnails);
return {
title: snippet.title,
description: `${
embed ? '<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube-nocookie.com/embed/' + videoId + '" frameborder="0" allowfullscreen></iframe>' : '<img src="' + img.url + '">'
}
${utils.formatDescription(snippet.description)}`,
pubDate: new Date(snippet.publishedAt).toUTCString(),
description: utils.renderDescription(embed, videoId, img, utils.formatDescription(snippet.description)),
pubDate: parseDate(snippet.publishedAt),
link: `https://www.youtube.com/watch?v=${videoId}`,
author: authors[index].snippet.channelTitle,
author: snippet.videoOwnerChannelTitle,
};
}),
};
+31
View File
@@ -0,0 +1,31 @@
module.exports = {
'youtube.com': {
_name: 'YouTube',
www: [
{
title: '用户',
docs: 'https://docs.rsshub.app/social-media.html#youtube',
source: '/user/:username',
target: '/youtube/user/:username',
},
{
title: '频道',
docs: 'https://docs.rsshub.app/social-media.html#youtube',
source: '/channel/:id',
target: '/youtube/channel/:id',
},
{
title: '播放列表',
docs: 'https://docs.rsshub.app/social-media.html#youtube',
source: '/playlist',
target: (params, url) => `/youtube/playlist/${new URL(url).searchParams.get('list')}`,
},
{
title: '订阅列表',
docs: 'https://docs.rsshub.app/social-media.html#youtube',
source: ['/feed/subscriptions', '/feed/channels'],
target: '/youtube/subscriptions',
},
],
},
};
+6
View File
@@ -0,0 +1,6 @@
module.exports = (router) => {
router.get('/channel/:id/:embed?', require('./channel'));
router.get('/playlist/:id/:embed?', require('./playlist'));
router.get('/subscriptions/:embed?', require('./subscriptions'));
router.get('/user/:username/:embed?', require('./user'));
};
+56
View File
@@ -0,0 +1,56 @@
const config = require('@/config').value;
const utils = require('./utils');
const { parseDate } = require('@/utils/parse-date');
const asyncPool = require('tiny-async-pool');
module.exports = async (ctx) => {
if (!config.youtube || !config.youtube.key || !config.youtube.clientId || !config.youtube.clientSecret || !config.youtube.refreshToken) {
throw 'YouTube RSS is disabled due to the lack of <a href="https://docs.rsshub.app/install/#pei-zhi-bu-fen-rss-mo-kuai-pei-zhi">relevant config</a>';
}
const embed = !ctx.params.embed;
const channelIds = (await utils.getSubscriptions('snippet', ctx.cache)).data.items.map((item) => item.snippet.resourceId.channelId);
const playlistIds = [];
for await (const playlistId of asyncPool(30, channelIds, async (channelId) => (await utils.getChannelWithId(channelId, 'contentDetails', ctx.cache)).data.items[0].contentDetails.relatedPlaylists.uploads)) {
playlistIds.push(playlistId);
}
let items = [];
for await (const item of asyncPool(30, playlistIds, async (playlistId) => (await utils.getPlaylistItems(playlistId, 'snippet', ctx.cache))?.data.items)) {
items.push(item);
}
// https://measurethat.net/Benchmarks/Show/7223
// concat > reduce + concat >>> flat
items = [].concat(...items);
items = items
.filter((i) => i && !i.error && i.snippet.title !== 'Private video' && i.snippet.title !== 'Deleted video')
.map((item) => {
const snippet = item.snippet;
const videoId = snippet.resourceId.videoId;
const img = utils.getThumbnail(snippet.thumbnails);
return {
title: snippet.title,
description: utils.renderDescription(embed, videoId, img, utils.formatDescription(snippet.description)),
pubDate: parseDate(snippet.publishedAt),
link: `https://www.youtube.com/watch?v=${videoId}`,
author: snippet.videoOwnerChannelTitle,
};
});
ctx.state.data = {
title: 'Subscriptions - YouTube',
description: 'YouTube Subscriptions',
item: items,
};
ctx.state.json = {
title: 'Subscriptions - YouTube',
description: 'YouTube Subscriptions',
channelIds,
playlistIds,
item: items,
};
};
+7
View File
@@ -0,0 +1,7 @@
{{ if embed }}
<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube-nocookie.com/embed/{{ videoId }}" frameborder="0" allowfullscreen></iframe>
{{ else }}
<img src="{{ img.url }}">
{{ /if }}
<br>
{{@ description }}
@@ -1,5 +1,6 @@
const utils = require('./utils');
const config = require('@/config').value;
const { parseDate } = require('@/utils/parse-date');
module.exports = async (ctx) => {
if (!config.youtube || !config.youtube.key) {
@@ -10,7 +11,7 @@ module.exports = async (ctx) => {
const playlistId = (await utils.getChannelWithUsername(username, 'contentDetails', ctx.cache)).data.items[0].contentDetails.relatedPlaylists.uploads;
const data = (await utils.getPlaylistItems(playlistId, 'snippet,contentDetails')).data.items;
const data = (await utils.getPlaylistItems(playlistId, 'snippet', ctx.cache)).data.items;
ctx.state.data = {
title: `${username} - YouTube`,
@@ -24,10 +25,8 @@ module.exports = async (ctx) => {
const img = utils.getThumbnail(snippet.thumbnails);
return {
title: snippet.title,
description: `${
embed ? '<iframe id="ytplayer" type="text/html" width="640" height="360" src="https://www.youtube-nocookie.com/embed/' + videoId + '" frameborder="0" allowfullscreen></iframe>' : '<img src="' + img.url + '">'
}${utils.formatDescription(snippet.description)}`,
pubDate: new Date(snippet.publishedAt).toUTCString(),
description: utils.renderDescription(embed, videoId, img, utils.formatDescription(snippet.description)),
pubDate: parseDate(snippet.publishedAt),
link: `https://www.youtube.com/watch?v=${videoId}`,
};
}),
+141
View File
@@ -0,0 +1,141 @@
const { google } = require('googleapis');
const { OAuth2 } = google.auth;
const { art } = require('@/utils/render');
const path = require('path');
const config = require('@/config').value;
let count = 0;
const youtube = {};
if (config.youtube && config.youtube.key) {
const keys = config.youtube.key.split(',');
keys.forEach((key, index) => {
if (key) {
youtube[index] = google.youtube({
version: 'v3',
auth: key,
});
count = index + 1;
}
});
}
let index = -1;
const exec = async (func) => {
let result;
for (let i = 0; i < count; i++) {
index++;
try {
// eslint-disable-next-line no-await-in-loop
result = await func(youtube[index % count]);
break;
} catch (error) {
// console.error(error);
}
}
return result;
};
let youtubeOAuth2Client;
if (config.youtube && config.youtube.clientId && config.youtube.clientSecret && config.youtube.refreshToken) {
youtubeOAuth2Client = new OAuth2(config.youtube.clientId, config.youtube.clientSecret, 'https://developers.google.com/oauthplayground');
youtubeOAuth2Client.setCredentials({ refresh_token: config.youtube.refreshToken });
}
const youtubeUtils = {
getPlaylistItems: (id, part, cache) =>
cache.tryGet(
`youtube:getPlaylistItems:${id}`,
async () => {
const res = await exec((youtube) =>
youtube.playlistItems.list({
part,
playlistId: id,
maxResults: 50, // youtube api param value default is 5
})
);
return res;
},
config.cache.routeExpire,
false
),
getPlaylist: (id, part, cache) =>
cache.tryGet(`youtube:getPlaylist:${id}`, async () => {
const res = await exec((youtube) =>
youtube.playlists.list({
part,
id,
})
);
return res;
}),
getChannelWithId: (id, part, cache) =>
cache.tryGet(`youtube:getChannelWithId:${id}`, async () => {
const res = await exec((youtube) =>
youtube.channels.list({
part,
id,
})
);
return res;
}),
getChannelWithUsername: (username, part, cache) =>
cache.tryGet(`youtube:getChannelWithUsername:${username}`, async () => {
const res = await exec((youtube) =>
youtube.channels.list({
part,
forUsername: username,
})
);
return res;
}),
// not in use
// getVideoAuthor: async (id, part) => {
// const res = await exec((youtube) =>
// youtube.videos.list({
// part,
// id,
// })
// );
// return res;
// },
getThumbnail: (thumbnails) => thumbnails.maxres || thumbnails.standard || thumbnails.high || thumbnails.medium || thumbnails.default,
formatDescription: (description) => description.replace(/(?:\r\n|\r|\n)/g, '<br>'),
renderDescription: (embed, videoId, img, description) =>
art(path.join(__dirname, 'templates/description.art'), {
embed,
videoId,
img,
description,
}),
getSubscriptions: async (part, cache) => {
// access tokens expire after one hour
let accessToken = await cache.get('youtube:accessToken', false);
if (!accessToken) {
const data = await youtubeOAuth2Client.getAccessToken();
accessToken = data.token;
await cache.set('youtube:accessToken', accessToken, ~~((data.res.data.expiry_date - Date.now()) / 1000)); // ~3600s
}
youtubeOAuth2Client.setCredentials({ access_token: accessToken, refresh_token: config.youtube.refreshToken });
return cache.tryGet('youtube:getSubscriptions', () => youtubeUtils.getSubscriptionsRecusive(part), config.cache.routeExpire, false);
},
getSubscriptionsRecusive: async (part, nextPageToken = undefined) => {
const res = await google.youtube('v3').subscriptions.list({
auth: youtubeOAuth2Client,
part,
mine: true,
maxResults: 50,
pageToken: nextPageToken ? nextPageToken : undefined,
});
// recursively get next page
if (res.data.nextPageToken) {
const next = await youtubeUtils.getSubscriptionsRecusive(part, res.data.nextPageToken);
res.data.items = [...res.data.items, ...next.data.items];
}
return res;
},
};
module.exports = youtubeUtils;