-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathshuffler.js
73 lines (63 loc) · 1.76 KB
/
shuffler.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
const { google } = require('googleapis');
const shuffle = require('shuffle-array');
const youtube = google.youtube({ version: 'v3' });
async function shuffleItems(items) {
shuffle(items);
let position = 0;
for (const item of items) {
const params = {
part: 'snippet',
requestBody: {
id: item.id,
snippet: {
playlistId: item.snippet.playlistId,
position,
resourceId: {
kind: item.snippet.resourceId.kind,
videoId: item.snippet.resourceId.videoId,
},
},
},
};
const updateResp = await youtube.playlistItems.update(params);
console.log(`shuffled ${position + 1} of ${items.length}`);
if (updateResp.status !== 200) {
throw new Error(updateResp);
}
position += 1;
}
}
async function playlistItemsListByPlaylistId(playlistId) {
let items = [];
const params = { maxResults: '50', part: 'snippet', playlistId };
let itemsResp;
do {
if (itemsResp && itemsResp.data.nextPageToken) {
params.pageToken = itemsResp.data.nextPageToken;
}
itemsResp = await youtube.playlistItems.list(params);
items = items.concat(itemsResp.data.items);
} while (itemsResp.data.nextPageToken);
return items;
}
async function getPlaylists() {
const playlistsResp = await youtube.playlists.list({
part: 'snippet',
mine: true,
maxResults: 25,
});
return playlistsResp.data.items;
}
async function shufflePlaylist(playlistId) {
console.log('Shuffling playlist ID', playlistId);
const items = await playlistItemsListByPlaylistId(playlistId);
return shuffleItems(items);
}
async function setAuth(oAuth2Client) {
google.options({ auth: oAuth2Client });
}
module.exports = {
getPlaylists,
setAuth,
shufflePlaylist,
};