Skip to content

Instantly share code, notes, and snippets.

@qianlifeng
Last active September 21, 2026 03:02
Show Gist options
  • Select an option

  • Save qianlifeng/04a9609de66eaa582a473f5852450ede to your computer and use it in GitHub Desktop.

Select an option

Save qianlifeng/04a9609de66eaa582a473f5852450ede to your computer and use it in GitHub Desktop.
Wox.Plugin.YouTube
// {
// "Id": "a0d52aa9-0401-492a-aeda-7a64e16ac2e9",
// "Name": "i18n:plugin_name",
// "Author": "qianlifeng",
// "Version": "1.1.0",
// "MinWoxVersion": "2.4.2",
// "Runtime": "NODEJS",
// "Description": "i18n:plugin_description",
// "Icon": "svg:<svg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'><rect width='48' height='48' rx='12' fill='#0f0f0f'/><path fill='#FF0000' d='M40.2 16.4c-.5-1.8-1.9-3.2-3.7-3.7C33.3 12 24 12 24 12s-9.3 0-12.5.7c-1.8.5-3.2 1.9-3.7 3.7C7 19.6 7 24 7 24s0 4.4.8 7.6c.5 1.8 1.9 3.2 3.7 3.7C14.7 36 24 36 24 36s9.3 0 12.5-.7c1.8-.5 3.2-1.9 3.7-3.7C41 28.4 41 24 41 24s0-4.4-.8-7.6z'/><path fill='#fff' d='M20 30.5v-13l11 6.5-11 6.5z'/></svg>",
// "TriggerKeywords": ["yt", "youtube"],
// "SupportedOS": ["Windows", "Linux", "Macos"],
// "Features": [
// { "Name": "debounce", "Params": { "IntervalMs": 300 } },
// { "Name": "ignoreAutoScore" },
// { "Name": "mru", "Params": { "HashBy": "scoreKey" } }
// ],
// "SettingDefinitions": [
// {
// "Type": "textbox",
// "Value": {
// "Key": "api_key",
// "Label": "i18n:setting_api_key",
// "Tooltip": "i18n:setting_api_key_tip",
// "DefaultValue": "",
// "MaxLines": 1,
// "Validators": [{ "Type": "not_empty", "Value": {} }],
// "Style": { "Width": 520 }
// },
// "IsPlatformSpecific": false
// }
// ],
// "QueryRequirements": {
// "AnyQuery": [
// {
// "SettingKey": "api_key",
// "Validators": [{ "Type": "not_empty", "Value": {} }],
// "Message": "i18n:setting_api_key_required"
// }
// ],
// "QueryWithoutCommand": [],
// "QueryWithCommand": {}
// },
// "I18n": {
// "en_US": {
// "plugin_name": "YouTube",
// "plugin_description": "Search YouTube videos and open them in the browser",
// "setting_api_key": "API Key",
// "setting_api_key_tip": "Create an API key at [https://console.cloud.google.com/apis/credentials](https://console.cloud.google.com/apis/credentials), enable YouTube Data API v3, then paste it here. Here is the sample:\n1. Open [Google Cloud Console](https://console.cloud.google.com/)\n2. **Create or select a project**\n3. Open **APIs & Services → Library**, search **YouTube Data API v3**, click **Enable**\n4. Open **APIs & Services → Credentials**\n5. Click **Create credentials → API key**\n6. Copy the key and paste it here",
// "setting_api_key_required": "Configure a YouTube Data API v3 key first",
// "usage_title": "Search YouTube",
// "usage_sub": "Type a keyword after yt, or paste a video link",
// "empty_title": "No videos found",
// "empty_sub": "Press Enter to search on YouTube",
// "error_title": "YouTube search failed",
// "error_sub": "Press Enter to search on YouTube",
// "error_invalid_key": "API key is invalid. Check plugin settings",
// "error_quota": "YouTube API quota is exhausted for today",
// "error_api_disabled": "Enable YouTube Data API v3 for this Google Cloud project",
// "action_open": "Open",
// "action_copy_url": "Copy URL",
// "action_open_channel": "Open channel",
// "action_search_web": "Search on YouTube",
// "notify_copied": "Copied to clipboard",
// "notify_copy_failed": "Failed to copy URL",
// "notify_open_failed": "Failed to open in browser",
// "tool_search": "Search YouTube videos",
// "date_locale": "en",
// "sort": "Sort",
// "sort_relevance": "Relevance",
// "sort_date": "Date",
// "views_count": "{n} views"
// },
// "zh_CN": {
// "plugin_name": "YouTube",
// "plugin_description": "搜索 YouTube 视频并在浏览器中打开",
// "setting_api_key": "API Key",
// "setting_api_key_tip": "在 [https://console.cloud.google.com/apis/credentials](https://console.cloud.google.com/apis/credentials) 创建 API 密钥,启用 YouTube Data API v3,然后粘贴到这里。步骤如下:\n1. 打开 [Google Cloud Console](https://console.cloud.google.com/)\n2. **创建或选择一个项目**\n3. 打开 **API 和服务 → 库**,搜索 **YouTube Data API v3**,点击 **启用**\n4. 打开 **API 和服务 → 凭据**\n5. 点击 **创建凭据 → API 密钥**\n6. 复制密钥并粘贴到这里",
// "setting_api_key_required": "请先配置 YouTube Data API v3 密钥",
// "usage_title": "搜索 YouTube",
// "usage_sub": "在 yt 后面输入关键词,或粘贴视频链接",
// "empty_title": "没有找到视频",
// "empty_sub": "按回车在 YouTube 网站搜索",
// "error_title": "YouTube 搜索失败",
// "error_sub": "按回车在 YouTube 网站搜索",
// "error_invalid_key": "API Key 无效,请检查插件设置",
// "error_quota": "今日 YouTube API 配额已用完",
// "error_api_disabled": "请在 Google Cloud 项目中启用 YouTube Data API v3",
// "action_open": "打开",
// "action_copy_url": "复制链接",
// "action_open_channel": "打开频道",
// "action_search_web": "在 YouTube 搜索",
// "notify_copied": "已复制到剪贴板",
// "notify_copy_failed": "复制链接失败",
// "notify_open_failed": "无法在浏览器中打开",
// "tool_search": "搜索 YouTube 视频",
// "date_locale": "zh-CN",
// "sort": "排序",
// "sort_relevance": "相关度",
// "sort_date": "时间",
// "views_count": "{n} 次观看"
// }
// }
// }
/**
* YouTube — single-file Node.js SDK plugin.
*
* Searches via the official YouTube Data API v3. An API key is required
* at query time (QueryRequirements). Results open in the default browser. MRU restores
* recently opened videos. Plugin Tools register when Wox exposes them (2.4.5+).
*/
const { spawn } = require("child_process")
const SETTING_API_KEY = "api_key"
const SEARCH_URL = "https://www.googleapis.com/youtube/v3/search"
const VIDEOS_URL = "https://www.googleapis.com/youtube/v3/videos"
const YOUTUBE_HOME = "https://www.youtube.com/"
const USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
const MAX_RESULTS = 10
const REQUEST_TIMEOUT_MS = 8000
const VIDEO_ID_RE = /^[A-Za-z0-9_-]{11}$/
const SORT_REFINEMENT_ID = "sort"
const SORT_RELEVANCE = "relevance"
const SORT_DATE = "date"
const PLUGIN_ICON_SVG = "<svg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'><rect width='48' height='48' rx='12' fill='#0f0f0f'/><path fill='#FF0000' d='M40.2 16.4c-.5-1.8-1.9-3.2-3.7-3.7C33.3 12 24 12 24 12s-9.3 0-12.5.7c-1.8.5-3.2 1.9-3.7 3.7C7 19.6 7 24 7 24s0 4.4.8 7.6c.5 1.8 1.9 3.2 3.7 3.7C14.7 36 24 36 24 36s9.3 0 12.5-.7c1.8-.5 3.2-1.9 3.7-3.7C41 28.4 41 24 41 24s0-4.4-.8-7.6z'/><path fill='#fff' d='M20 30.5v-13l11 6.5-11 6.5z'/></svg>"
const RESULT_ICON = {
ImageType: "svg",
ImageData: PLUGIN_ICON_SVG
}
const ACTION_OPEN_ICON = {
ImageType: "svg",
ImageData: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--wox-theme-icon-color)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M14 5h5v5M19 5l-9 9\"/><path d=\"M13 7H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2v-7\"/></svg>"
}
const ACTION_COPY_ICON = {
ImageType: "svg",
ImageData: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--wox-theme-icon-color)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"8\" y=\"8\" width=\"12\" height=\"12\" rx=\"2\"/><path d=\"M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2\"/></svg>"
}
class YoutubeApiError extends Error {
constructor(reason, message) {
super(message)
this.name = "YoutubeApiError"
this.reason = reason
}
}
function videoUrl(videoId) {
return `https://www.youtube.com/watch?v=${videoId}`
}
function thumbnailUrl(videoId) {
return `https://i.ytimg.com/vi/${videoId}/hqdefault.jpg`
}
function youtubeSearchUrl(query) {
return `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`
}
function channelUrl(channelId) {
return channelId ? `https://www.youtube.com/channel/${channelId}` : ""
}
function primaryHotkey(key) {
return (process.platform === "darwin" ? "cmd+" : "ctrl+") + key
}
function parseSortOrder(query) {
const refinements = (query && (query.Refinements || query.refinements)) || {}
return refinements[SORT_REFINEMENT_ID] === SORT_DATE ? SORT_DATE : SORT_RELEVANCE
}
function sortRefinement(titles = {}) {
return {
Id: SORT_REFINEMENT_ID,
Title: titles.sort || "Sort",
Type: "sort",
Hotkey: primaryHotkey("s"),
DefaultValue: [SORT_RELEVANCE],
Persist: false,
Options: [
{ Value: SORT_RELEVANCE, Title: titles.relevance || "Relevance" },
{ Value: SORT_DATE, Title: titles.date || "Date" }
]
}
}
function formatViewsLabel(formattedCount, template) {
if (!formattedCount) {
return ""
}
return String(template || "{n} views").replaceAll("{n}", formattedCount)
}
function languageCode(locale) {
return String(locale || "en").replace("_", "-").split("-")[0] || "en"
}
function normalizeLocale(value) {
const raw = String(value || "").trim()
if (!raw || raw === "date_locale" || raw.startsWith("i18n:")) {
return "en"
}
return raw.replace(/_/g, "-")
}
function clampLimit(value) {
const n = Number(value)
if (!Number.isFinite(n)) {
return MAX_RESULTS
}
return Math.min(20, Math.max(1, Math.floor(n)))
}
function pad2(value) {
return String(value).padStart(2, "0")
}
// formatIsoDuration turns YouTube contentDetails.duration (ISO 8601) into 3:34.
function formatIsoDuration(iso) {
const match = /^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$/.exec(String(iso || ""))
if (!match) {
return ""
}
const hours = Number(match[1] || 0) * 24 + Number(match[2] || 0)
const minutes = Number(match[3] || 0)
const seconds = Number(match[4] || 0)
if (hours > 0) {
return `${hours}:${pad2(minutes)}:${pad2(seconds)}`
}
return `${minutes}:${pad2(seconds)}`
}
function formatViewCount(value, locale = "en") {
const n = Number(value)
if (!Number.isFinite(n)) {
return ""
}
try {
return new Intl.NumberFormat(languageCode(locale)).format(n)
} catch {
return String(n)
}
}
function formatPublishedAt(iso, locale = "en") {
const then = Date.parse(iso)
if (!Number.isFinite(then)) {
return ""
}
const deltaSec = Math.round((then - Date.now()) / 1000)
const abs = Math.abs(deltaSec)
try {
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" })
if (abs < 60) {
return rtf.format(deltaSec, "second")
}
if (abs < 3600) {
return rtf.format(Math.round(deltaSec / 60), "minute")
}
if (abs < 86400) {
return rtf.format(Math.round(deltaSec / 3600), "hour")
}
if (abs < 86400 * 30) {
return rtf.format(Math.round(deltaSec / 86400), "day")
}
if (abs < 86400 * 365) {
return rtf.format(Math.round(deltaSec / (86400 * 30)), "month")
}
return rtf.format(Math.round(deltaSec / (86400 * 365)), "year")
} catch {
return String(iso).slice(0, 10)
}
}
function thumbnailFromSnippet(snippet, videoId) {
const thumbs = snippet && snippet.thumbnails
const chosen = thumbs && (thumbs.high || thumbs.medium || thumbs.default)
if (chosen && chosen.url) {
return chosen.url
}
return videoId ? thumbnailUrl(videoId) : ""
}
// parseVideoId extracts an 11-character video id from a raw id or YouTube URL.
function parseVideoId(input) {
const text = String(input || "").trim()
if (!text) {
return ""
}
if (VIDEO_ID_RE.test(text)) {
return text
}
let url
try {
url = new URL(text)
} catch {
try {
url = new URL(`https://${text}`)
} catch {
return ""
}
}
const host = url.hostname.replace(/^www\./i, "").replace(/^m\./i, "").replace(/^music\./i, "").toLowerCase()
if (host === "youtu.be") {
const id = url.pathname.split("/").filter(Boolean)[0] || ""
return VIDEO_ID_RE.test(id) ? id : ""
}
if (host === "youtube.com" || host === "youtube-nocookie.com") {
const fromQuery = url.searchParams.get("v") || ""
if (VIDEO_ID_RE.test(fromQuery)) {
return fromQuery
}
const parts = url.pathname.split("/").filter(Boolean)
if (parts[0] === "embed" || parts[0] === "shorts" || parts[0] === "live" || parts[0] === "v") {
const id = parts[1] || ""
if (VIDEO_ID_RE.test(id)) {
return id
}
}
}
return ""
}
function looksLikeYoutubeUrl(input) {
const text = String(input || "").trim()
if (!text) {
return false
}
try {
const url = new URL(text.includes("://") ? text : `https://${text}`)
const host = url.hostname.replace(/^www\./i, "").replace(/^m\./i, "").replace(/^music\./i, "").toLowerCase()
return host === "youtu.be" || host === "youtube.com" || host === "youtube-nocookie.com"
} catch {
return false
}
}
function videoFromSearchItem(item, locale = "en") {
const id = item && item.id && item.id.videoId
if (!VIDEO_ID_RE.test(id || "")) {
return null
}
const snippet = item.snippet || {}
return {
id,
title: snippet.title || id,
channel: snippet.channelTitle || "",
channelUrl: channelUrl(snippet.channelId),
duration: "",
views: "",
publishedAt: snippet.publishedAt || "",
published: formatPublishedAt(snippet.publishedAt, locale),
description: snippet.description || "",
thumbnail: thumbnailFromSnippet(snippet, id)
}
}
// parseSearchItems maps a YouTube Data API search.list payload to videos.
function parseSearchItems(payload, locale = "en") {
const items = payload && Array.isArray(payload.items) ? payload.items : []
const videos = []
const seen = new Set()
for (const item of items) {
const video = videoFromSearchItem(item, locale)
if (!video || seen.has(video.id)) {
continue
}
seen.add(video.id)
videos.push(video)
}
return videos
}
function videoFromDetailsItem(item, locale = "en") {
const id = item && item.id
if (!VIDEO_ID_RE.test(id || "")) {
return null
}
const snippet = item.snippet || {}
const details = item.contentDetails || {}
const stats = item.statistics || {}
return {
id,
title: snippet.title || id,
channel: snippet.channelTitle || "",
channelUrl: channelUrl(snippet.channelId),
duration: formatIsoDuration(details.duration),
views: formatViewCount(stats.viewCount, locale),
publishedAt: snippet.publishedAt || "",
published: formatPublishedAt(snippet.publishedAt, locale),
description: snippet.description || "",
thumbnail: thumbnailFromSnippet(snippet, id)
}
}
// parseVideoDetails maps a videos.list payload keyed by video id.
function parseVideoDetails(payload, locale = "en") {
const map = new Map()
const items = payload && Array.isArray(payload.items) ? payload.items : []
for (const item of items) {
const video = videoFromDetailsItem(item, locale)
if (video) {
map.set(video.id, video)
}
}
return map
}
function applyVideoDetails(video, details) {
if (!details) {
return video
}
return {
...video,
title: details.title || video.title,
channel: details.channel || video.channel,
channelUrl: details.channelUrl || video.channelUrl,
duration: details.duration || video.duration,
views: details.views || video.views,
publishedAt: details.publishedAt || video.publishedAt,
published: details.published || video.published,
description: details.description || video.description,
thumbnail: details.thumbnail || video.thumbnail
}
}
function youtubeErrorFromPayload(status, payload) {
const error = payload && payload.error
const first = error && Array.isArray(error.errors) && error.errors[0]
const reason = (first && first.reason) || ""
const message = (error && error.message) || (first && first.message) || `YouTube API failed (${status})`
if (reason === "keyInvalid" || /API key not valid/i.test(message)) {
return new YoutubeApiError("keyInvalid", message)
}
if (reason === "quotaExceeded" || reason === "dailyLimitExceeded") {
return new YoutubeApiError("quotaExceeded", message)
}
if (reason === "accessNotConfigured") {
return new YoutubeApiError("accessNotConfigured", message)
}
return new YoutubeApiError(reason || `http_${status}`, message)
}
function errorSubtitleKey(err) {
const reason = err && err.reason
if (reason === "keyInvalid") {
return "i18n:error_invalid_key"
}
if (reason === "quotaExceeded") {
return "i18n:error_quota"
}
if (reason === "accessNotConfigured") {
return "i18n:error_api_disabled"
}
return "i18n:error_sub"
}
async function youtubeGet(url) {
const response = await fetch(String(url), {
headers: {
Accept: "application/json",
"User-Agent": USER_AGENT
},
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
})
let payload = null
try {
payload = await response.json()
} catch {
payload = null
}
if (!response.ok) {
throw youtubeErrorFromPayload(response.status, payload)
}
return payload
}
function requireApiKey(apiKey) {
const key = String(apiKey || "").trim()
if (!key) {
throw new YoutubeApiError("missing_key", "YouTube API key is not configured")
}
return key
}
async function fetchVideoDetails(ids, apiKey, httpGet, locale = "en") {
const unique = [...new Set((ids || []).filter((id) => VIDEO_ID_RE.test(id)))]
if (!unique.length) {
return new Map()
}
const url = new URL(VIDEOS_URL)
url.searchParams.set("part", "snippet,contentDetails,statistics")
url.searchParams.set("id", unique.join(","))
url.searchParams.set("key", apiKey)
const payload = await httpGet(url)
return parseVideoDetails(payload, locale)
}
// searchYoutubeVideos queries YouTube Data API v3 search.list, then videos.list for duration/views.
async function searchYoutubeVideos(query, options = {}) {
const apiKey = requireApiKey(options.apiKey)
const httpGet = options.httpGet || youtubeGet
const limit = clampLimit(options.limit)
const url = new URL(SEARCH_URL)
url.searchParams.set("part", "snippet")
url.searchParams.set("type", "video")
url.searchParams.set("q", query)
url.searchParams.set("maxResults", String(limit))
url.searchParams.set("key", apiKey)
const order = options.order === SORT_DATE ? SORT_DATE : SORT_RELEVANCE
url.searchParams.set("order", order)
const locale = normalizeLocale(options.locale || options.hl)
const lang = languageCode(options.hl || locale)
if (lang) {
url.searchParams.set("relevanceLanguage", lang)
}
const payload = await httpGet(url)
const videos = parseSearchItems(payload, locale).slice(0, limit)
if (!videos.length) {
return videos
}
try {
const details = await fetchVideoDetails(videos.map((video) => video.id), apiKey, httpGet, locale)
return videos.map((video) => applyVideoDetails(video, details.get(video.id)))
} catch (err) {
if (err && (err.reason === "keyInvalid" || err.reason === "quotaExceeded" || err.reason === "accessNotConfigured")) {
throw err
}
return videos
}
}
async function resolveYoutubeVideo(videoId, options = {}) {
const apiKey = requireApiKey(options.apiKey)
const httpGet = options.httpGet || youtubeGet
const details = await fetchVideoDetails([videoId], apiKey, httpGet, normalizeLocale(options.locale || options.hl))
const video = details.get(videoId)
if (!video) {
throw new YoutubeApiError("not_found", "Video not found")
}
return video
}
function stubVideo(videoId) {
return {
id: videoId,
title: videoId,
channel: "",
channelUrl: "",
duration: "",
views: "",
publishedAt: "",
published: "",
description: "",
thumbnail: thumbnailUrl(videoId)
}
}
function videoFromContext(data) {
const videoId = data && data.videoId
if (!VIDEO_ID_RE.test(videoId || "")) {
return null
}
return {
id: videoId,
title: data.title || videoId,
channel: data.channel || "",
channelUrl: data.channelUrl || "",
duration: data.duration || "",
views: data.views || "",
publishedAt: data.publishedAt || "",
published: data.published || "",
description: data.description || "",
thumbnail: data.thumbnail || thumbnailUrl(videoId)
}
}
function videoContext(video) {
return {
videoId: video.id,
title: video.title || "",
channel: video.channel || "",
channelUrl: video.channelUrl || "",
duration: video.duration || "",
views: video.views || "",
publishedAt: video.publishedAt || "",
published: video.published || "",
description: (video.description || "").slice(0, 500),
thumbnail: video.thumbnail || thumbnailUrl(video.id)
}
}
function joinMeta(parts) {
return parts.filter(Boolean).join(" · ")
}
function oneLine(text) {
return String(text || "").replace(/\s+/g, " ").trim()
}
function escapeMarkdown(text) {
return String(text ?? "").replace(/([\\`*_{}\[\]()#+\-.!|>~])/g, "\\$1")
}
function markdownParagraph(text) {
return escapeMarkdown(text).replace(/\r\n/g, "\n").replace(/\n/g, " \n")
}
function markdownImageUrl(url) {
return String(url || "").replace(/[()\s]/g, encodeURIComponent)
}
function videoPreviewMarkdown(video) {
const title = oneLine(video.title || video.id)
const thumb = markdownImageUrl(video.thumbnail || thumbnailUrl(video.id))
const meta = joinMeta([video.channel, video.views, video.published])
const lines = [`![${escapeMarkdown(title)}](${thumb})`, "", `# ${escapeMarkdown(title)}`]
if (meta) {
lines.push("", escapeMarkdown(meta))
}
if (video.description) {
lines.push("", markdownParagraph(video.description))
}
return lines.join("\n")
}
function videoPreview(video) {
const tags = []
if (video.duration) {
tags.push({ Label: video.duration, Tooltip: "" })
}
return {
PreviewType: "markdown",
PreviewData: videoPreviewMarkdown(video),
PreviewTags: tags
}
}
// openExternal opens a URL in the system default browser.
function openExternal(target) {
if (process.platform === "win32") {
spawn("cmd", ["/c", "start", "", target], { detached: true, stdio: "ignore", windowsHide: true }).unref()
return
}
const command = process.platform === "darwin" ? "open" : "xdg-open"
spawn(command, [target], { detached: true, stdio: "ignore" }).unref()
}
function queryText(query) {
return String((query && query.Search) || "").trim()
}
function resultIconFor(video) {
if (video && video.thumbnail) {
return { ImageType: "url", ImageData: video.thumbnail }
}
if (video && video.id) {
return { ImageType: "url", ImageData: thumbnailUrl(video.id) }
}
return RESULT_ICON
}
class YoutubePlugin {
constructor(options = {}) {
this.api = null
this.apiKey = String(options.apiKey || "").trim()
this.searchVideos = options.searchVideos || searchYoutubeVideos
this.resolveVideo = options.resolveVideo || resolveYoutubeVideo
this.openExternal = options.openExternal || openExternal
this.init = this.init.bind(this)
this.query = this.query.bind(this)
}
async init(ctx, params) {
this.api = params && params.API
await this.loadSettings(ctx)
if (this.api && typeof this.api.OnSettingChanged === "function") {
await this.api.OnSettingChanged(ctx, async (_ctx, key, value) => {
if (key === SETTING_API_KEY) {
this.apiKey = String(value || "").trim()
}
})
}
if (this.api && typeof this.api.OnMRURestore === "function") {
await this.api.OnMRURestore(ctx, async (_ctx, mruData) => {
const video = videoFromContext(mruData && mruData.ContextData)
if (!video) {
return null
}
const locale = await this.uiLocale(_ctx)
const viewsTemplate = await this.translate(_ctx, "views_count")
return this.videoResult(video, 100, locale, viewsTemplate)
})
}
await this.registerTools(ctx)
}
async loadSettings(ctx) {
if (!this.api || typeof this.api.GetSetting !== "function") {
return
}
this.apiKey = String(await this.api.GetSetting(ctx, SETTING_API_KEY) || "").trim()
}
requestOptions(extra = {}) {
return {
apiKey: this.apiKey,
...extra
}
}
async uiLocale(ctx) {
return normalizeLocale(await this.translate(ctx, "date_locale"))
}
async sortTitles(ctx) {
return {
sort: await this.translate(ctx, "sort"),
relevance: await this.translate(ctx, "sort_relevance"),
date: await this.translate(ctx, "sort_date")
}
}
async registerTools(ctx) {
if (!this.api || typeof this.api.RegisterPluginTool !== "function") {
return
}
try {
await this.api.RegisterPluginTool(ctx, {
Tool: {
Name: "search_youtube",
Description: "i18n:tool_search",
InputSchema: {
type: "object",
properties: {
query: { type: "string", description: "Search keyword" },
limit: { type: "integer", minimum: 1, maximum: 20 }
},
required: ["query"]
},
OutputSchema: {
type: "object",
properties: {
videos: {
type: "array",
items: {
type: "object",
properties: {
id: { type: "string" },
title: { type: "string" },
channel: { type: "string" },
url: { type: "string" },
duration: { type: "string" },
views: { type: "string" },
published: { type: "string" }
},
required: ["id", "title", "url"]
}
}
},
required: ["videos"]
},
Annotations: { ReadOnly: true, Destructive: false, Idempotent: true, RequiresUI: false }
},
Handler: async (ctx, option) => this.handleSearchTool(ctx, option && option.Arguments)
})
} catch (err) {
await this.log(ctx, "Debug", `register search_youtube skipped: ${err && err.message ? err.message : err}`)
}
}
async handleSearchTool(ctx, args) {
const query = String((args && args.query) || "").trim()
if (!query) {
return { Error: { Code: "INVALID_ARGUMENTS", Message: "query is required" } }
}
try {
const locale = await this.uiLocale(ctx)
const videos = await this.searchVideos(query, this.requestOptions({
limit: args && args.limit,
locale,
hl: languageCode(locale)
}))
return {
Output: {
videos: videos.map((video) => ({
id: video.id,
title: video.title,
channel: video.channel || "",
url: videoUrl(video.id),
duration: video.duration || "",
views: video.views || "",
published: video.published || ""
}))
}
}
} catch (err) {
return { Error: { Code: "EXECUTION_FAILED", Message: err && err.message ? err.message : String(err) } }
}
}
async query(ctx, query) {
const text = queryText(query)
if (!text) {
return {
Results: [this.usageResult()],
Layout: { ResultPreviewWidthRatio: 0.4 }
}
}
const locale = await this.uiLocale(ctx)
const viewsTemplate = await this.translate(ctx, "views_count")
const titles = await this.sortTitles(ctx)
const order = parseSortOrder(query)
const options = this.requestOptions({ locale, hl: languageCode(locale), order })
const fromUrl = looksLikeYoutubeUrl(text)
const videoId = parseVideoId(text)
if (videoId && (fromUrl || VIDEO_ID_RE.test(text))) {
try {
const video = await this.resolveVideo(videoId, options)
return {
Results: [this.videoResult(video, 2000, locale, viewsTemplate)],
Layout: { ResultPreviewWidthRatio: 0.42 }
}
} catch (err) {
await this.log(ctx, "Warning", `resolve ${videoId} failed: ${err && err.message ? err.message : err}`)
if (fromUrl && !(err && err.reason === "keyInvalid")) {
return {
Results: [this.videoResult(stubVideo(videoId), 2000, locale, viewsTemplate)],
Layout: { ResultPreviewWidthRatio: 0.42 }
}
}
return {
Results: [this.errorResult(text, errorSubtitleKey(err))],
Layout: { ResultPreviewWidthRatio: 0.35 }
}
}
}
try {
const videos = await this.searchVideos(text, this.requestOptions({
limit: MAX_RESULTS, locale, hl: languageCode(locale), order
}))
if (!videos.length) {
return {
Results: [this.emptyResult(text)],
Refinements: [sortRefinement(titles)],
Layout: { ResultPreviewWidthRatio: 0.35 }
}
}
return {
Results: videos.map((video, index) => this.videoResult(video, 2000 - index, locale, viewsTemplate)),
Refinements: [sortRefinement(titles)],
Layout: { ResultPreviewWidthRatio: 0.42 }
}
} catch (err) {
await this.log(ctx, "Error", `search failed: ${err && err.message ? err.message : err}`)
return {
Results: [this.errorResult(text, errorSubtitleKey(err))],
Refinements: [sortRefinement(titles)],
Layout: { ResultPreviewWidthRatio: 0.35 }
}
}
}
usageResult() {
return {
Title: "i18n:usage_title",
SubTitle: "i18n:usage_sub",
Icon: RESULT_ICON,
Score: 100,
Actions: [
this.openAction({
id: "open-home",
name: "i18n:action_open",
url: YOUTUBE_HOME,
isDefault: true
})
]
}
}
emptyResult(query) {
return {
Title: "i18n:empty_title",
SubTitle: "i18n:empty_sub",
Icon: RESULT_ICON,
Score: 100,
Actions: [
this.openAction({
id: "search-web",
name: "i18n:action_search_web",
url: youtubeSearchUrl(query),
isDefault: true
})
]
}
}
errorResult(query, subtitle) {
return {
Title: "i18n:error_title",
SubTitle: subtitle || "i18n:error_sub",
Icon: RESULT_ICON,
Score: 100,
Actions: [
this.openAction({
id: "search-web-error",
name: "i18n:action_search_web",
url: youtubeSearchUrl(query),
isDefault: true
})
]
}
}
videoResult(video, score, locale = "en", viewsTemplate = "{n} views") {
const presented = {
...video,
published: formatPublishedAt(video.publishedAt, locale) || video.published,
views: formatViewsLabel(video.views, viewsTemplate)
}
const url = videoUrl(presented.id)
const context = videoContext(presented)
const actions = [
this.openAction({
id: `open-${video.id}`,
name: "i18n:action_open",
url,
isDefault: true,
context
}),
this.copyAction({
id: `copy-${video.id}`,
url,
context
})
]
if (presented.channelUrl) {
actions.push(this.openAction({
id: `channel-${presented.id}`,
name: "i18n:action_open_channel",
url: presented.channelUrl,
isDefault: false,
context
}))
}
return {
Id: `yt-${presented.id}`,
Title: presented.title,
SubTitle: joinMeta([presented.channel, presented.published]),
Icon: resultIconFor(presented),
Score: score,
ScoreKey: presented.id,
Preview: videoPreview(presented),
Tails: presented.duration ? [{ Type: "text", Text: presented.duration }] : [],
Actions: actions
}
}
openAction(item) {
return {
Id: item.id,
Name: item.name,
Icon: ACTION_OPEN_ICON,
IsDefault: Boolean(item.isDefault),
ContextData: item.context,
Action: async (ctx) => {
try {
this.openExternal(item.url)
} catch (err) {
await this.log(ctx, "Error", `open failed: ${err && err.message ? err.message : err}`)
await this.notify(ctx, "notify_open_failed")
}
}
}
}
copyAction(item) {
return {
Id: item.id,
Name: "i18n:action_copy_url",
Icon: ACTION_COPY_ICON,
IsDefault: false,
ContextData: item.context,
Action: async (ctx) => {
try {
await this.api.Copy(ctx, { type: "text", text: item.url })
await this.notify(ctx, "notify_copied")
} catch (err) {
await this.log(ctx, "Error", `copy failed: ${err && err.message ? err.message : err}`)
await this.notify(ctx, "notify_copy_failed")
}
}
}
}
async translate(ctx, key) {
if (this.api && typeof this.api.GetTranslation === "function") {
try {
const value = await this.api.GetTranslation(ctx, key)
if (value && value !== key && value !== `i18n:${key}`) {
return value
}
} catch {
// Fall through to the English copy below.
}
}
const fallback = {
notify_copied: "Copied to clipboard",
notify_copy_failed: "Failed to copy URL",
notify_open_failed: "Failed to open in browser",
date_locale: "en",
sort: "Sort",
sort_relevance: "Relevance",
sort_date: "Date",
views_count: "{n} views"
}
return fallback[key] || key
}
async notify(ctx, key) {
if (!this.api || typeof this.api.Notify !== "function") {
return
}
await this.api.Notify(ctx, await this.translate(ctx, key))
}
async log(ctx, level, message) {
if (this.api && typeof this.api.Log === "function") {
await this.api.Log(ctx, level, message)
}
}
}
const plugin = new YoutubePlugin()
module.exports = {
plugin,
YoutubePlugin,
YoutubeApiError,
parseVideoId,
parseSearchItems,
parseVideoDetails,
formatIsoDuration,
formatViewCount,
formatPublishedAt,
youtubeErrorFromPayload,
errorSubtitleKey,
videoUrl,
thumbnailUrl,
youtubeSearchUrl,
queryText,
videoFromContext,
videoContext,
stubVideo,
searchYoutubeVideos,
resolveYoutubeVideo,
videoPreview,
videoPreviewMarkdown,
parseSortOrder,
sortRefinement,
SORT_REFINEMENT_ID,
SORT_RELEVANCE,
SORT_DATE,
SETTING_API_KEY,
MAX_RESULTS,
VIDEO_ID_RE
}
@qianlifeng

Copy link
Copy Markdown
Author
logo

@qianlifeng

Copy link
Copy Markdown
Author
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment