forked from dfinity/portal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube.js
92 lines (77 loc) · 2.43 KB
/
youtube.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const logger = require("@docusaurus/logger");
const fetch = require("node-fetch-retry");
const fs = require("fs");
const path = require("path");
const dotenv = require("dotenv");
const isDev = (process.env.NODE_ENV || "development") === "development";
dotenv.config({ path: path.join(__dirname, "..", ".env.local") });
const { YOUTUBE_API_KEY } = process.env;
const DFINITY_CHANNEL_ID = "UCOyguKlTxoDK3HRzmGbLyAg";
async function getMostRecentVideo() {
const res = await fetch(
`https://www.googleapis.com/youtube/v3/search?key=${YOUTUBE_API_KEY}&channelId=${DFINITY_CHANNEL_ID}&part=snippet&order=date&maxResults=1`,
{
headers: {
Referer: "https://www.dfinity.org",
},
retry: 10,
pause: 5000,
}
).then((r) => r.json());
return res.items[0];
}
// find the first key with a thumbnal at least 480 px wide
function pickThumbnail(thumbnails) {
const keys = Object.keys(thumbnails);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (thumbnails[key].width >= 480) {
return thumbnails[key].url;
}
}
if (thumbnails.default === undefined) {
return "";
}
return thumbnails.default.url;
}
let cache;
/** @type {import('@docusaurus/types').PluginModule} */
const youtubePlugin = async function () {
return {
name: "youtube",
async loadContent() {
if (!cache) {
if (!YOUTUBE_API_KEY) {
logger.warn(
"Warning: no env variables found for Youtube integration. Using mock youtube data."
);
return require("./data/youtube-mock");
}
const mostRecentVideo = await getMostRecentVideo();
const thumbnal = pickThumbnail(mostRecentVideo.snippet.thumbnails);
cache = {
mostRecentVideo: {
id: mostRecentVideo.id.videoId,
title: mostRecentVideo.snippet.title,
description: mostRecentVideo.snippet.description,
thumbnail: thumbnal,
publishedAt: mostRecentVideo.snippet.publishedAt,
},
};
}
return cache;
},
async contentLoaded({ content, actions }) {
const { createData } = actions;
createData("youtube.json", JSON.stringify(content, null, 2));
if (isDev) {
// save mock file
fs.writeFileSync(
path.join(__dirname, "data", "youtube-mock.json"),
JSON.stringify(content, null, 2)
);
}
},
};
};
module.exports = youtubePlugin;