-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsearch.js
More file actions
90 lines (75 loc) · 2.36 KB
/
Copy pathsearch.js
File metadata and controls
90 lines (75 loc) · 2.36 KB
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
const YOUTUBE_API_URL = 'https://www.googleapis.com/youtube/v3/search'
const youtubeAPI = async (query, options) => {
const params = {
q: query,
key: process.env.SUCHTUBE_YOUTUBE_DATA_API_V3,
maxResults: options.random ? 50 : 1,
part: 'snippet'
}
if (!params.key || params.key == "") {
console.error('Whoops! You should setup your YouTube Data API key')
}
// Build URL with query parameters
const url = new URL(YOUTUBE_API_URL)
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
const response = await fetch(url)
const data = await response.json()
return data.items.map(item => {
let id, link, linkEmbed, kind
switch (item.id.kind) {
case 'youtube#channel':
id = item.id.channelId
kind = 'channel'
link = `https://www.youtube.com/channel/${id}`
linkEmbed = null
break
case 'youtube#playlist':
id = item.id.playlistId
kind = 'playlist'
link = `https://www.youtube.com/playlist?list=${id}`
linkEmbed = `https://www.youtube.com/embed?listType=playlist&list=${id}`
break
default:
id = item.id.videoId
kind = 'video'
link = `https://www.youtube.com/watch?v=${id}`
linkEmbed = `https://www.youtube.com/embed/${id}`
break
}
return {
id: id,
kind: kind,
link: link,
linkEmbed: linkEmbed,
title: item.snippet.title,
description: item.snippet.description,
thumbnail: item.snippet.thumbnails.medium.url,
publishedAt: item.snippet.publishedAt,
channelTitle: item.snippet.channelTitle
}
})
}
// Create an API object that can be stubbed in tests
export const api = {
youtubeAPI
}
export const search = async (query, options = {}) => {
const videos = await api.youtubeAPI(query, options)
if (videos.length == 0) return
let video
if (options.random) {
let index = Math.floor(Math.random() * videos.length)
video = {...videos[index]}
} else {
video = {...videos[0]}
}
if (options.time && video.kind != 'channel') {
video.link = video.link + '&t=' + options.time
if (video.kind == 'video') {
video.linkEmbed = video.linkEmbed + '?start=' + options.time
} else {
video.linkEmbed = video.linkEmbed + '&start=' + options.time
}
}
return video
}