🎥 Search for youtube videos (with preview) 🔍

https://user-images.githubusercontent.com/2759340/190151639-b64651f1-6490-47ee-aa9b-513111535a6a.mov

Install on Script Kit


// Name: Search for YouTube Videos
// Description: Prompts for a search string and lists all youtube videos found (with preview)
// Author: Vogelino
// Twitter: @soyvogelino
// Shortcut: opt y
import "@johnlindquist/kit";
const apiKey = await env("YOUTUBE_API_KEY");
const previewAudioOn =
(await env(
"YOUTUBE_VIDEO_SEARCH_PREVIEW_AUDIO_ON",
"Would you like the video preview to run with sound? [y/n]"
)) === "y";
const previewAutoplayOn =
(await env(
"YOUTUBE_VIDEO_SEARCH_PREVIEW_AUTOPLAY_ON",
"Would you like the video preview to play automatically? [y/n]"
)) === "y";
const searchYoutubeVideos = async (searchString) => {
if (!searchString) throw new Error(`No search string entered`);
const ytUrl = new URL(`https://www.googleapis.com/youtube/v3/search`);
ytUrl.searchParams.set("key", apiKey);
ytUrl.searchParams.set("q", searchString);
ytUrl.searchParams.set("part", "snippet");
const { data } = await get(ytUrl.toString());
return data.items;
};
try {
let searchString = await arg("Enter your search");
let videos = await searchYoutubeVideos(searchString);
while (videos.length === 0) {
searchString = await arg("No results. Enter a new search");
videos = await searchYoutubeVideos(searchString);
}
const videoId = await arg(
"Select a video to open",
videos.map(({ snippet, id }) => ({
name: snippet.title,
description:
snippet.description.length > 50
? `${snippet.description.slice(0, 50)}...`
: snippet.description,
preview: () => `
<div style="padding: 16px">
<table style="margin-bottom: 8px;">
<tr>
<td width="96px">
<img
src="${snippet.thumbnails.default.url}"
width="80px"
style="float: left; margin-right: 16px"
/>
</td>
<td><h3>${snippet.title}</h3></td>
</tr>
</table>
<iframe
src="http://www.youtube.com/embed/${id.videoId}?autoplay=${
previewAudioOn ? 1 : 0
}"
width="560"
height="315"
frameborder="0"
${previewAutoplayOn && "autoplay"}
style="aspect-ratio: 16 / 9; width: 100%;"
></iframe>
</div>
`,
value: id.videoId,
}))
);
browse(`https://www.youtube.com/watch?v=${videoId}`);
} catch (err) {
console.log(err);
notify(err);
}