pxt-core
Version:
Microsoft MakeCode provides Blocks / JavaScript / Python tools and editors
71 lines (64 loc) • 2.42 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderPlaylistsAsync = exports.GOOGLE_API_KEY = void 0;
const nodeutil = require("./nodeutil");
const path = require("path");
const fs = require("fs");
exports.GOOGLE_API_KEY = "GOOGLE_API_KEY";
function checkApiKey() {
if (!pxt.youtube.apiKey) {
const k = process.env[exports.GOOGLE_API_KEY];
if (!k) {
throw new Error(`Missing ${exports.GOOGLE_API_KEY} to access YouTube Apis. Use https://console.developers.google.com/ to generate a new API key.`);
}
pxt.youtube.apiKey = k;
}
}
async function renderPlaylistAsync(fn, id) {
fn = fn.replace(/\.md$/i, '');
const assets = `/static/${fn}`;
nodeutil.mkdirP("docs" + assets);
const playlist = await pxt.youtube.playlistInfoAsync(id);
const videos = await pxt.youtube.listPlaylistVideosAsync(id);
const playlistUrl = pxt.youtube.watchUrl(undefined, playlist.id);
let cards = videos.map(pxt.youtube.playlistItemToCodeCard);
// remove delete movies
cards = cards.filter(card => !!card.imageUrl);
// download images for cards
for (const card of cards) {
const cimg = `${assets}/${card.youTubeId}.jpg`;
const limg = `docs${cimg}`;
if (!nodeutil.fileExistsSync(limg)) {
const rimg = await pxt.Util.requestAsync({
url: card.imageUrl,
method: "GET",
responseArrayBuffer: true
});
fs.writeFileSync(limg, rimg.buffer, 'binary');
}
card.imageUrl = cimg;
}
// trailing card
cards.push({
"name": "PlayList",
"description": "See entire playlist on YouTube",
"url": playlistUrl,
"youTubePlaylistId": id,
"imageUrl": `${assets}/playlist.png`
});
const cardsMd = pxt.gallery.codeCardsToMarkdown(cards);
const md = `# ${playlist.snippet.title}
${playlist.snippet.description || ""}
## Videos
${cardsMd}
## See Also
[YouTube Playlist](${playlistUrl})
`;
nodeutil.writeFileSync(path.join('docs', fn + ".md"), md, { encoding: "utf8" });
}
function renderPlaylistsAsync(playlists) {
checkApiKey();
return Promise.all(Object.keys(playlists).map(fn => renderPlaylistAsync(fn, playlists[fn])))
.then(() => { pxt.log('playlists refreshed'); });
}
exports.renderPlaylistsAsync = renderPlaylistsAsync;