-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
175 lines (160 loc) · 5.99 KB
/
index.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
var CronJob = require('cron').CronJob;
const playlistConfig = require('./playlists.json');
// set up server logic
const bodyParser = require('body-parser');
const express = require('express');
var app = express();
app.set('port', (process.env.PORT || 61884))
app.use(bodyParser.json());
// create the youtube api object with credentials
const {
google
} = require('googleapis');
const OAuth2 = google.auth.OAuth2;
const credentials = (process.env.YOUTUBE_SECRET ? JSON.parse(process.env.YOUTUBE_SECRET) : require("./secrets/client_secret.json"));
const token = (process.env.YOUTUBE_TOKEN ? JSON.parse(process.env.YOUTUBE_TOKEN) : require("./secrets/leo_secret.json"));
const service = google.youtube('v3');
// yreate the spotify api object with credentials
var SpotifyWebApi = require('spotify-web-api-node');
const spotifyAuth = (process.env.SPOTIFY_SECRET ? JSON.parse(process.env.SPOTIFY_SECRET) : require("./secrets/spotify_secrets.json"));
var spotifyApi = new SpotifyWebApi(spotifyAuth);
async function authorizeSpotify() {
const data = await spotifyApi.clientCredentialsGrant();
console.log('The access token expires in ' + data.body['expires_in']);
console.log('The access token is ' + data.body['access_token']);
spotifyApi.setAccessToken(data.body['access_token']);
}
async function getSpotifyPlaylist(playlistId, offsetParam) {
const fullPlaylist = [];
let nextPageExists = true;
let offset = (offsetParam == null ? 0 : offsetParam);
while (nextPageExists) {
const response = await spotifyApi.getPlaylistTracks(playlistId, {
fields: 'items(added_at,track(name,artists)),next,tnotal',
offset: offset,
});
fullPlaylist.push(...response.body.items)
nextPageExists = (response.body.next !== null);
offset += 100;
if (nextPageExists) {
console.log("Loading... " + fullPlaylist.length + "/" + response.body.total);
} else {
console.log("Finished loading all " + fullPlaylist.length + " songs");
}
}
return fullPlaylist;
}
async function getOauthClient() {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);
oauth2Client.credentials = token;
return oauth2Client;
}
async function findBestVideo(artist, title) {
return new Promise(async (resolve, reject) => {
service.search.list({
auth: await getOauthClient(),
part: "id",
type: "video",
maxResults: 1,
q: artist + " " + title,
order: "relevance",
videoCategoryId: "10"
}, (error, response) => {
if (error) {
reject(error);
} else if (typeof response.data == undefined) {
reject(Error("Video search returned empty response"))
} else if (response.data.items.length < 1) {
reject(Error("No search results found for query " + artist + " " + title))
}
console.log("Found a suitable video!");
resolve(response.data.items[0]);
})
});
}
async function getYoutubePlaylistSize(playlistId) {
return new Promise(async (resolve, reject) => {
service.playlists.list({
"auth": await getOauthClient(),
"part": "contentDetails",
id: playlistId
}, (error, response) => {
if (error) {
reject(error);
} else if (typeof response.data == undefined) {
reject(Error("Playlist doesn't exist"))
}
console.log("Already have " + response.data.items[0].contentDetails.itemCount + " items in YT list");
resolve(response.data.items[0].contentDetails.itemCount);
});
});
}
async function updatePlaylist(playlistObj) {
const preloaded = await getYoutubePlaylistSize(playlistObj.youtube);
const newSongs = await getSpotifyPlaylist(playlistObj.spotify, preloaded);
for (const item of newSongs) {
const youtubeVideo = await findBestVideo(item.track.artists[0].name, item.track.name);
console.log("Found video for " + item.track.name + ": " + youtubeVideo.id.videoId);
try {
await addVideoToPlaylist(youtubeVideo.id.videoId, playlistObj.youtube);
} catch (err) {
console.error(err);
}
};
console.log("Added all new songs!");
}
async function addVideoToPlaylist(videoId, playlistId) {
return new Promise(async (resolve, reject) => {
service.playlistItems.insert({
"auth": await getOauthClient(),
"part": "snippet",
"resource": {
"snippet": {
"playlistId": playlistId,
"resourceId": {
"videoId": videoId,
"kind": "youtube#video"
}
}
}
}, (err, res) => {
if (err) {
reject(err);
}
console.log("Added " + res.data.id + " to the playlist!");
resolve();
})
});
}
async function updateAll() {
for (const name in playlistConfig) {
await updatePlaylist(playlistConfig[name]);
}
return;
}
app.get('/', (req, res) => {
res.send("How about a POST request instead?");
});
app.post('/', async (req, res) => {
// and finally...
authorizeSpotify().then(async () => {
await updateAll();
res.send("Refreshed all successfully!");
}).catch(err => {
console.error(err);
res.sendStatus(500);
})
})
app.listen(app.get("port"), async function () {
console.log("Listening on Port " + app.get("port"));
// run updateAll on every new commit
authorizeSpotify().then(async () => {
await updateAll();
console.log("Refreshed all successfully!");
}).catch(err => {
console.error(err);
})
});