@sugarcube/plugin-youtube
Version:
A SugarCube plugin to fetch videos from Youtube.
81 lines (58 loc) • 2.77 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.normalizeYoutubeChannelUrl = exports.normalizeYoutubeVideoUrl = exports.isYoutubeChannel = exports.isYoutubeVideo = exports.parseYoutubeChannel = exports.parseYoutubeVideo = exports.assertCredentials = void 0;
var _url = require("url");
var _core = require("@sugarcube/core");
const {
assertCfg
} = _core.utils.assertions;
const assertCredentials = assertCfg(["youtube.api_key"]);
exports.assertCredentials = assertCredentials;
const parseYoutubeVideo = query => {
// e.g. o0tjic523cg
if (!query.startsWith("http")) return query;
const u = new _url.URL(query); // e.g. http://youtu.be/o0tjic523cg
if (u.hostname.startsWith("youtu.be")) return u.pathname.split("/").filter(segment => segment.length > 0)[0]; // e.g. https://www.youtube.com/watch?v=tcCBtSjKEzI
if (u.searchParams.has("v")) return u.searchParams.get("v"); // e.g. https://www.youtube.com/embed/iq_XLq5ONtE?version
if (u.pathname.startsWith("/embed")) return u.pathname.split("/").filter(x => x !== "")[1];
return query;
};
exports.parseYoutubeVideo = parseYoutubeVideo;
const parseYoutubeChannel = query => {
if (query.startsWith("http")) {
const u = new _url.URL(query);
return u.pathname.replace(/^\//, "").replace(/\/$/, "").split("/")[1];
}
return query;
};
exports.parseYoutubeChannel = parseYoutubeChannel;
const isYoutubeVideo = url => {
const u = new _url.URL(url); // e.g. https://www.youtube.com/watch?v=tcCBtSjKEzI
if (/youtube\.com/.test(u.hostname) && u.searchParams.get("v") != null) return true; // e.g. http://youtu.be/o0tjic523cg
if (/youtu\.be/.test(u.hostname) && u.pathname.split("/").filter(x => x !== "").length === 1) return true; // e.g. https://www.youtube.com/embed/iq_XLq5ONtE?version
if (/youtube\.com/.test(u.hostname) && u.pathname.split("/").filter(x => x !== "").length === 2 && u.pathname.split("/").filter(x => x !== "")[0] === "embed") return true;
return false;
};
exports.isYoutubeVideo = isYoutubeVideo;
const isYoutubeChannel = url => {
const u = new _url.URL(url);
if (/youtube\.com/.test(u.hostname) && /channel/.test(u.pathname)) return true;
return false;
};
exports.isYoutubeChannel = isYoutubeChannel;
const normalizeYoutubeVideoUrl = url => {
const videoId = parseYoutubeVideo(url);
return `https://www.youtube.com/watch?v=${videoId}`;
};
exports.normalizeYoutubeVideoUrl = normalizeYoutubeVideoUrl;
const normalizeYoutubeChannelUrl = url => {
const channelId = parseYoutubeChannel(url);
return `https://www.youtube.com/channel/${channelId}`;
};
exports.normalizeYoutubeChannelUrl = normalizeYoutubeChannelUrl;
var _default = {
assertCredentials
};
exports.default = _default;