-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathyoutube-base.js
93 lines (82 loc) · 2.48 KB
/
youtube-base.js
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
91
92
93
import Joi from 'joi'
import { BaseJsonService, NotFound } from '../index.js'
import { metric } from '../text-formatters.js'
import { nonNegativeInteger } from '../validators.js'
const documentation = `
<p>By using the YouTube badges provided by Shields.io, you are agreeing to be bound by the YouTube Terms of Service. These can be found here:
<code>https://www.youtube.com/t/terms</code></p>`
const schema = Joi.object({
pageInfo: Joi.object({
totalResults: nonNegativeInteger,
resultsPerPage: nonNegativeInteger,
}).required(),
items: Joi.array().items(
Joi.object({
statistics: Joi.alternatives(
Joi.object({
viewCount: nonNegativeInteger,
likeCount: nonNegativeInteger,
dislikeCount: nonNegativeInteger,
commentCount: nonNegativeInteger,
}),
Joi.object({
viewCount: nonNegativeInteger,
subscriberCount: nonNegativeInteger,
})
),
})
),
}).required()
class YouTubeBase extends BaseJsonService {
static category = 'social'
static auth = {
passKey: 'youtube_api_key',
authorizedOrigins: ['https://www.googleapis.com'],
isRequired: true,
}
static defaultBadgeData = {
label: 'youtube',
color: 'red',
namedLogo: 'youtube',
}
static renderSingleStat({ statistics, statisticName, id }) {
return {
label: `${statisticName}s`,
message: metric(statistics[`${statisticName}Count`]),
style: 'social',
link: `https://www.youtube.com/${this.type}/${encodeURIComponent(id)}`,
}
}
async fetch({ id }) {
return this._requestJson(
this.authHelper.withQueryStringAuth(
{ passKey: 'key' },
{
schema,
url: `https://www.googleapis.com/youtube/v3/${this.constructor.type}s`,
options: {
searchParams: { id, part: 'statistics' },
},
}
)
)
}
async handle({ channelId, videoId }, queryParams) {
const id = channelId || videoId
const json = await this.fetch({ id })
if (json.pageInfo.totalResults === 0) {
throw new NotFound({
prettyMessage: `${this.constructor.type} not found`,
})
}
const statistics = json.items[0].statistics
return this.constructor.render({ statistics, id }, queryParams)
}
}
class YouTubeVideoBase extends YouTubeBase {
static type = 'video'
}
class YouTubeChannelBase extends YouTubeBase {
static type = 'channel'
}
export { documentation, YouTubeVideoBase, YouTubeChannelBase }