Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Youtube: Cache requested video data #7593

Merged
merged 2 commits into from
Oct 27, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions server/chat-plugins/youtube.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {Utils} from '../../lib/utils';
const ROOT = 'https://www.googleapis.com/youtube/v3/';
const STORAGE_PATH = 'config/chat-plugins/youtube.json';

export const videoDataCache: Map<string, VideoData> = Chat.oldPlugins.youtube?.videoDataCache || new Map();

interface ChannelEntry {
name: string;
description: string;
Expand Down Expand Up @@ -148,13 +150,20 @@ export class YoutubeInterface {
return Promise.resolve({...this.data.channels[id]});
}
async getVideoData(id: string): Promise<VideoData | null> {
const raw = await Net(`${ROOT}videos`).get({
query: {part: 'snippet,statistics', id, key: Config.youtubeKey},
});
const cached = videoDataCache.get(id);
if (cached) return cached;
let raw;
try {
raw = await Net(`${ROOT}videos`).get({
query: {part: 'snippet,statistics', id, key: Config.youtubeKey},
});
} catch (e) {
throw new Chat.ErrorMessage(`Failed to retrieve video data: ${e.message}.`);
}
const res = JSON.parse(raw);
if (!res || !res.items || res.items.length < 1) return null;
const video = res.items[0];
return {
const data: VideoData = {
title: video.snippet.title,
id,
date: new Date(video.snippet.publishedAt).toString(),
Expand All @@ -166,6 +175,8 @@ export class YoutubeInterface {
likes: video.statistics.likeCount,
dislikes: video.statistics.dislikeCount,
};
videoDataCache.set(id, data);
return data;
}
channelSearch(search: string) {
let channel;
Expand Down