-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambada.js
224 lines (180 loc) · 7.01 KB
/
lambada.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
const dotenv = require('dotenv');
const axios = require('axios');
const fs = require('fs');
const loadEnvData = (key) => {
try {
if (process.env[key]) {
return process.env[key];
}
if (fs.existsSync('.env')) {
const envConfig = dotenv.parse(fs.readFileSync('.env'));
if (envConfig[key]) {
return envConfig[key];
}
}
throw new Error(`Environment variable ${key} not found!`);
} catch (e) {
throw new Error(`Error loading environment variable ${key}: ${e.message}`);
}
};
class YouTubeLambada {
#makeApiRequest = async (path, params) => {
params.key = loadEnvData('YOUTUBE_API_KEY');
const url = `https://www.googleapis.com/youtube/v3/${path}`;
const response = await axios.get(url, { params });
return response.data;
}
#parseDuration = (duration) => {
const pattern = /PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/;
const matches = duration.match(pattern);
const hours = matches[1] ? parseInt(matches[1]) : 0;
const minutes = matches[2] ? parseInt(matches[2]) : 0;
const seconds = matches[3] ? parseInt(matches[3]) : 0;
return hours * 3600 + minutes * 60 + seconds;
}
getChannelId = async (handle) => {
const response = await this.#makeApiRequest('channels', {
part: 'id',
forHandle: handle ?? loadEnvData('CHANNEL_HANDLE'),
});
return response.items?.[0]?.id ?? null;
}
getVideos = async (channelId) => {
const videos = {
normal: [],
shorts: [],
live: [],
};
let nextPageToken = null;
do {
const searchParams = {
part: 'id,snippet',
channelId: channelId,
maxResults: 50,
type: 'video',
order: 'date',
};
if (nextPageToken) {
searchParams.pageToken = nextPageToken;
}
const searchResponse = await this.#makeApiRequest('search', searchParams);
if (! searchResponse.items) {
break;
}
const videoIds = searchResponse.items.map(item => item.id.videoId);
const videoResponse = await this.#makeApiRequest('videos', {
part: 'contentDetails,liveStreamingDetails,snippet,statistics',
id: videoIds.join(','),
});
for (const video of videoResponse.items) {
const videoDuration = this.#parseDuration(video.contentDetails.duration);
const videoData = {
id: video.id,
title: video.snippet.title,
description: video.snippet.description,
url: `https://youtube.com/watch?v=${video.id}`,
published_at: video.snippet.publishedAt,
duration: videoDuration,
views: parseInt(video.statistics.viewCount ?? 0),
comments: parseInt(video.statistics.commentCount ?? 0),
likes: parseInt(video.statistics.likeCount ?? 0),
};
if (video.liveStreamingDetails) {
videos.live.push(videoData);
} else if (videoDuration <= 60) {
videos.shorts.push(videoData);
} else {
videos.normal.push(videoData);
}
}
nextPageToken = searchResponse.nextPageToken ?? null;
} while (nextPageToken);
return videos;
}
getStats = (videos) => {
const stats = {
total: {
normal: videos.normal.length,
shorts: videos.shorts.length,
live: videos.live.length,
},
stats: {
normal: {
views: 0,
comments: 0,
likes: 0,
avg_duration: 0,
},
shorts: {
views: 0,
comments: 0,
likes: 0,
avg_duration: 0,
},
live: {
views: 0,
comments: 0,
likes: 0,
avg_duration: 0,
}
}
};
for (const [type, videoList] of Object.entries(videos)) {
let totalDuration = 0;
for (const video of videoList) {
stats.stats[type].views += video.views;
stats.stats[type].comments += video.comments;
stats.stats[type].likes += video.likes;
totalDuration += video.duration;
}
if (videoList.length > 0) {
stats.stats[type].avg_duration = totalDuration / videoList.length;
}
}
return stats;
}
}
const main = async () => {
try {
const youTubeLambada = new YouTubeLambada();
// first we need the channel id
const channelId = await youTubeLambada.getChannelId();
// then we can fetch all videos from the channel
const videos = await youTubeLambada.getVideos(channelId);
// and finally get some stats
const stats = youTubeLambada.getStats(videos);
console.log('--- Stats by type ---\n');
for (const [type, result] of Object.entries(stats.stats)) {
console.log(`${type.toUpperCase()}:`);
console.log(`Total: ${stats.total[type]}`);
console.log(`Average duration: ${Math.round(result.avg_duration)} Seconds`);
console.log(`👀 Views: ${result.views.toLocaleString()}`);
console.log(`💬 Comments: ${result.comments.toLocaleString()}`);
console.log(`👍 Likes: ${result.likes.toLocaleString()}`);
if (stats.total[type] > 0) {
console.log(`Average views: ${Math.round(result.views / stats.total[type]).toLocaleString()}`);
}
console.log('\n');
}
console.log('\n--- Videos by type ---\n');
for (const [type, list] of Object.entries(videos)) {
console.log(`${type.toUpperCase()}:\n`);
for (const video of list) {
console.log(`Title: ${video.title}`);
//console.log(`Description: ${video.description}`);
console.log(`ID: ${video.id}`);
console.log(`URL: ${video.url}`);
console.log(`Published at: ${video.published_at}`);
console.log(`Duration: ${video.duration}`);
console.log(`👀 Views: ${video.views}`);
console.log(`💬 Comments: ${video.comments}`);
console.log(`👍 Likes: ${video.likes}`);
console.log('\n');
}
}
console.log('Done! Have a nice day.');
} catch (error) {
console.error('Oh no, something terrible happened:', error.message);
}
};
main();