From e953f9f456ee74148ae32833d07828fef1c7d006 Mon Sep 17 00:00:00 2001 From: Tony Date: Thu, 26 May 2022 07:37:12 -0500 Subject: [PATCH] feat(route): youtube subscriptions (#9824) --- assets/radar-rules.js | 8 -- docs/en/install/README.md | 23 ++-- docs/en/social-media.md | 10 +- docs/install/README.md | 27 +++-- docs/social-media.md | 4 + lib/config.js | 3 + lib/radar-rules.js | 23 ---- lib/router.js | 8 +- lib/routes/youtube/utils.js | 90 --------------- lib/{routes => v2}/youtube/channel.js | 14 ++- lib/v2/youtube/maintainer.js | 6 + lib/{routes => v2}/youtube/playlist.js | 16 +-- lib/v2/youtube/radar.js | 31 +++++ lib/v2/youtube/router.js | 6 + lib/v2/youtube/subscriptions.js | 56 +++++++++ lib/v2/youtube/templates/description.art | 7 ++ lib/{routes => v2}/youtube/user.js | 9 +- lib/v2/youtube/utils.js | 141 +++++++++++++++++++++++ 18 files changed, 314 insertions(+), 168 deletions(-) delete mode 100644 lib/routes/youtube/utils.js rename lib/{routes => v2}/youtube/channel.js (72%) create mode 100644 lib/v2/youtube/maintainer.js rename lib/{routes => v2}/youtube/playlist.js (56%) create mode 100644 lib/v2/youtube/radar.js create mode 100644 lib/v2/youtube/router.js create mode 100644 lib/v2/youtube/subscriptions.js create mode 100644 lib/v2/youtube/templates/description.art rename lib/{routes => v2}/youtube/user.js (74%) create mode 100644 lib/v2/youtube/utils.js diff --git a/assets/radar-rules.js b/assets/radar-rules.js index cb6e43829..28334d819 100644 --- a/assets/radar-rules.js +++ b/assets/radar-rules.js @@ -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', '.': [ diff --git a/docs/en/install/README.md b/docs/en/install/README.md index 307a2b307..14dea8653 100644 --- a/docs/en/install/README.md +++ b/docs/en/install/README.md @@ -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. diff --git a/docs/en/social-media.md b/docs/en/social-media.md index 0462d7175..0dd47ed38 100644 --- a/docs/en/social-media.md +++ b/docs/en/social-media.md @@ -412,7 +412,7 @@ Tiny Tiny RSS will add `sandbox="allow-scripts"` to all iframe elements, as a re ### User - + ### Channel @@ -422,8 +422,12 @@ YouTube provides official RSS feeds for channels, for instance + ### Playlist - + + +### Subscriptions + + diff --git a/docs/install/README.md b/docs/install/README.md index eb5590628..71daf4b96 100644 --- a/docs/install/README.md +++ b/docs/install/README.md @@ -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 支持使用访问密钥 / 码,白名单和黑名单三种方式进行 | | cloudflare | | | 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 全站十大 diff --git a/docs/social-media.md b/docs/social-media.md index 6b3c46ebc..7c7989e1d 100644 --- a/docs/social-media.md +++ b/docs/social-media.md @@ -800,6 +800,10 @@ YouTube 官方亦有提供频道 RSS,形如 +### 订阅列表 + + + ## 巴哈姆特 ### 个人小屋 diff --git a/lib/config.js b/lib/config.js index f20428a6a..fe11f8fb9 100644 --- a/lib/config.js +++ b/lib/config.js @@ -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, diff --git a/lib/radar-rules.js b/lib/radar-rules.js index 08c3f1017..048ebada5 100644 --- a/lib/radar-rules.js +++ b/lib/radar-rules.js @@ -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: [ diff --git a/lib/router.js b/lib/router.js index c424bd662..45db96263 100644 --- a/lib/router.js +++ b/lib/router.js @@ -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')); diff --git a/lib/routes/youtube/utils.js b/lib/routes/youtube/utils.js deleted file mode 100644 index 647c8f792..000000000 --- a/lib/routes/youtube/utils.js +++ /dev/null @@ -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, '
'), -}; - -module.exports = youtubeUtils; diff --git a/lib/routes/youtube/channel.js b/lib/v2/youtube/channel.js similarity index 72% rename from lib/routes/youtube/channel.js rename to lib/v2/youtube/channel.js index 9f304f910..aa712de45 100644 --- a/lib/routes/youtube/channel.js +++ b/lib/v2/youtube/channel.js @@ -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 /youtube/user/${id} 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 ? '' : '' - }${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}`, }; }), diff --git a/lib/v2/youtube/maintainer.js b/lib/v2/youtube/maintainer.js new file mode 100644 index 000000000..058159c6b --- /dev/null +++ b/lib/v2/youtube/maintainer.js @@ -0,0 +1,6 @@ +module.exports = { + '/channel/:id/:embed?': ['DIYgod'], + '/playlist/:id/:embed?': ['HenryQW'], + '/subscriptions/:embed?': ['TonyRL'], + '/user/:username/:embed?': ['DIYgod'], +}; diff --git a/lib/routes/youtube/playlist.js b/lib/v2/youtube/playlist.js similarity index 56% rename from lib/routes/youtube/playlist.js rename to lib/v2/youtube/playlist.js index 1b9ae7fc6..06afb05c4 100644 --- a/lib/routes/youtube/playlist.js +++ b/lib/v2/youtube/playlist.js @@ -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 ? '' : '' - } - ${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, }; }), }; diff --git a/lib/v2/youtube/radar.js b/lib/v2/youtube/radar.js new file mode 100644 index 000000000..7a52893b6 --- /dev/null +++ b/lib/v2/youtube/radar.js @@ -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', + }, + ], + }, +}; diff --git a/lib/v2/youtube/router.js b/lib/v2/youtube/router.js new file mode 100644 index 000000000..54fc0634c --- /dev/null +++ b/lib/v2/youtube/router.js @@ -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')); +}; diff --git a/lib/v2/youtube/subscriptions.js b/lib/v2/youtube/subscriptions.js new file mode 100644 index 000000000..3d95d43ba --- /dev/null +++ b/lib/v2/youtube/subscriptions.js @@ -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 relevant config'; + } + 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, + }; +}; diff --git a/lib/v2/youtube/templates/description.art b/lib/v2/youtube/templates/description.art new file mode 100644 index 000000000..29e50f16f --- /dev/null +++ b/lib/v2/youtube/templates/description.art @@ -0,0 +1,7 @@ +{{ if embed }} + +{{ else }} + +{{ /if }} +
+{{@ description }} diff --git a/lib/routes/youtube/user.js b/lib/v2/youtube/user.js similarity index 74% rename from lib/routes/youtube/user.js rename to lib/v2/youtube/user.js index 8c68f4556..4f450981f 100644 --- a/lib/routes/youtube/user.js +++ b/lib/v2/youtube/user.js @@ -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 ? '' : '' - }${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}`, }; }), diff --git a/lib/v2/youtube/utils.js b/lib/v2/youtube/utils.js new file mode 100644 index 000000000..55588afa3 --- /dev/null +++ b/lib/v2/youtube/utils.js @@ -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, '
'), + 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;