-
Notifications
You must be signed in to change notification settings - Fork 2
/
moodSing.js
485 lines (439 loc) · 15.6 KB
/
moodSing.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// GLOBAL VARIABLES
// ==================================================================================
let GLOBAL_DEV_MODE = false; // TODO: On Deploy, change this to false
let GLOBAL_SPOTIFY_ENABLED = true;
// Client fields
let userForecast,
userMood,
userGenre;
let songsLeftToLoad = 0;
// Closure for the Access Token to keep it from being directly accessed by user
function makeAccessToken(accessToken) {
let aT = accessToken;
const getAccessToken = () => {
return aT;
}
return getAccessToken;
}
let getAccessToken = () => { return null };
// Spotify API
// ==================================================================================
// Get the authorization token from moodSingCure for this session
const getSpotifyAuthorization = (devMode = false) => {
console.log("Getting authorization!");
// Fetch the encoded authorization token from moodSingCure, or localhost if devMode is true
fetch(
devMode ? "http://localhost:5000/accessToken" :
"https://mood-sing-cure.herokuapp.com/accessToken", { mode: ("cors") })
.then(response => {
console.log("Response retrieved!");
return response.json()
}).then(data => {
if (!data.accessToken) throw new Error("No Spotify Token found!");
console.log(data);
if (data.accessToken != "null" && data.accessToken != null) {
console.log("Access Token successfully retrieved!");
getAccessToken = makeAccessToken(data.accessToken);
} else {
throw new Error("Could not access Spotify Token! Null Token found");
}
}).catch(error => {
GLOBAL_DEV_MODE = true;
GLOBAL_SPOTIFY_ENABLED = false;
console.error("Null token found!")
})
}
// Returns the track id of a song that matches the passed genre and keyword
const getSong = (genre, keyword) => {
return new Promise((resolve, reject) => {
fetch(`https://api.spotify.com/v1/search?q=${keyword} genre: ${genre}&type=track&market=US&limit=1`, {
headers: { "Authorization": "Bearer " + getAccessToken() }
})
.then(response => {
return response.json();
}).then(data => {
if (data.tracks.items[0]) {
let id = data.tracks.items[0].id;
console.log("SONG GET: GENRE - " + genre + " KEYWORD - " + keyword + " ID - " + id)
resolve(id);
} else {
reject("No Song Found");
}
})
});
}
// Generates seed songs for the recommendations based on chosen genre, weather, and mood
const getSeedMusic = (genre, weather, mood) => {
trimmedWeather = weather.split(" ")[0];
return new Promise(async(resolve, reject) => {
let finalWeatherSong = "";
await getSong(genre, trimmedWeather).then(weatherSong => {
finalWeatherSong = weatherSong;
}).catch(async error => {
await getSong(genre, "").then(genreSong => {
finalWeatherSong = genreSong;
}).catch(error => {
finalWeatherSong = "03UrZgTINDqvnUMbbIMhql"; // Don't Stop Believin'
})
})
await getSong(genre, mood).then(moodSong => {
resolve([finalWeatherSong, moodSong]);
}).catch(async error => {
await getSong(genre, "").then(genreSong => {
resolve[finalWeatherSong, "4bHsxqR3GMrXTxEPLuK5ue"]; // Gangnam Style
})
})
})
}
// Gets the list of recommended songs based on the passed-in seed music and mood params
const getMoodSingRecommendations = (genre, weather, mood) => {
const backupIDs = ["6Z34YgqCJkdrliDmbcaJgy", "6kyiWsforDWCq1VBCm4BNZ", "2Cu5ExXidcoE4vF5hIYict", "2VBYFWgwIlJjyzidPTHQqp", "6cd1yCz5aapoeauiLH9dcU", "4c2W3VKsOFoIg2SFaO6DY5", "1nmeX39rjGxyaoSkPxSHwr", "38iCfXPXqyeEHsNtlxjtSG", "50PU05RTGva8laKDwxED9Y", "63w0QA1wiV7QhF9jeiHETF"];
let trackIDs = [];
let recPromise = new Promise(async(resolve, reject) => {
// Use default track listing if Spotify API is disabled
if (!GLOBAL_SPOTIFY_ENABLED) resolve(backupIDs);
// Get the seed music and moof parameters to build the query
let seedMusic = null;
await getSeedMusic(genre, weather, mood)
.then(seed => {
if (seed.length == 1)
seedMusic = [seed[0], "03UrZgTINDqvnUMbbIMhql"]
else
seedMusic = seed
})
.catch(error => {
seedMusic = ["03UrZgTINDqvnUMbbIMhql", "4bHsxqR3GMrXTxEPLuK5ue"]
});
let moodParams = moodMatcher(mood);
let query = `seed_tracks=${seedMusic[0]},${seedMusic[1]}` +
`&seed_genres=${genre}` +
`&target_valence=${moodParams.valence}` +
`&target_energy=${moodParams.energy}` +
`&target_tempo=${moodParams.tempo}` +
`&target_loudness=${moodParams.loudness}` +
`&target_danceability=${moodParams.danceability}`;
let authorization = "Bearer " + getAccessToken();
// Get the recommendations, then pass their IDs in the resolution
fetch(`https://api.spotify.com/v1/recommendations?${query}`, {
headers: { "Authorization": authorization }
})
.then(response => {
console.log(authorization);
return response.json();
}).then(data => {
console.log(data);
data.tracks.forEach(track => {
trackIDs.push(track.id);
})
resolve(trackIDs);
}).catch(error => {
reject(error);
});
});
return recPromise;
}
// Mood Mapping
// ==================================================================================
// Gets the spotify parameters tied to a given mood
function moodMatcher(userMood) {
const moodMatch = mood.find(moodObject => moodObject.moodType = userMood.toLowerCase());
console.log(moodMatch);
let valence = moodMatch.valence,
energy = moodMatch.energy,
tempo = moodMatch.tempo,
loudness = moodMatch.loudness,
danceability = moodMatch.danceability;
return {
valence: valence,
energy: energy,
tempo: tempo,
loudness: loudness,
danceability: danceability
};
}
// Weather and Geolocation APIs
// ==================================================================================
// location api
function browserSupportsGeolocation() {
if (navigator.geolocation) {
$("#weather-approval").show();
} else {
// Latitude and longitude of UW Campus
$("#weather-approval").hide();
console.log("Does not support geo");
console.log(47.655548, -122.303200);
}
}
function weatherForecast() {
$("#loadingbar").show();
let positionStart,
geoSuccess = function(position) {
$("#weather-approval").hide();
positionStart = position;
let lat = positionStart.coords.latitude,
lon = positionStart.coords.longitude;
gridLocater(lat, lon);
},
geoError = function(error) {
$("#weather-approval").hide();
switch (error.code) {
case error.TIMEOUT:
console.log("Timed Out Reload");
locationPrompt();
break;
case error.PERMISSION_DENIED:
console.log("USER SAID NO");
console.log(47.655548, -122.303200);
gridLocater(47.655548, -122.303200);
M.toast({ html: "Sorry you don't want to share your location. We will set it to UW Campus!" })
break;
case error.POSITION_UNAVAILABLE:
console.log("Unable to grab users location");
console.log(47.655548, -122.303200);
gridLocater(47.655548, -122.303200);
M.toast({ html: "We can't find your location so we are setting your location to UW Campus!" })
}
},
geoOptions = {
maximumAge: 0,
timeout: 50000,
enableHighAccuracy: true
};
navigator.geolocation.getCurrentPosition(geoSuccess, geoError, geoOptions);
}
// weather api
// get request with location variable for current weather
function gridLocater(lat, lon) {
$.get(`https://api.weather.gov/points/${lat},${lon}`, function(grid) {
localForecast(grid);
});
}
function localForecast(grid) {
$.get(`https://api.weather.gov/gridpoints/${grid.properties.gridId}/${grid.properties.gridX},${grid.properties.gridY}/forecast`, function(forecast) {
console.log("Weather: "+forecast.properties.periods[0].shortForecast);
$("#loadingbar").hide();
$("#mood-prompt").show()
userForecast = forecast.properties.periods[0].shortForecast
renderWeatherTheme(forecast.properties.periods[0].icon)
});
}
// DOM Manipulation
// ==================================================================================
// Function to initialize page
function init() {
startHide()
browserSupportsGeolocation()
}
// Background/Theme change
// Adds the given theme class to all theme-enabled elements, then removes all others
function applyTheme(theme = "default") {
$(".default").addClass(theme)
$(".fewClouds").addClass(theme)
$(".sunny").addClass(theme)
$(".rain").addClass(theme)
$(".partlyCloudy").addClass(theme)
$(".thunderstorm").addClass(theme)
$(".mist").addClass(theme)
$(".snow").addClass(theme)
removeThemes(theme)
}
// Removes all theme classes except the one given in the parameter
function removeThemes(exception = "") {
let classString = "default fewClouds sunny rain partlyCloudy thunderstorm mist snow";
let splitClassString = classString.split(exception)
if (splitClassString.length > 1) {
classString = splitClassString[0] + splitClassString[1]
} else {
classString = splitClassString[0]
}
splitClassString = classString.split(/ +/);
$("*").removeClass(splitClassString)
}
// Applies the theme appropriate to the weather given in the forecast
function renderWeatherTheme(imageUrl) {
if (imageUrl == null) {
applyTheme("default")
return;
}
// Extract the image file name from the forecast for easy weather/theme mapping
let splitUrl = imageUrl.split("?")[0].split("/");
let imageFileName = splitUrl[splitUrl.length - 1].split(",")[0];
switch (imageFileName) {
case "few":
case "nfew":
case "sct":
case "nsct":
case "wind_few":
case "nwind_few":
case "wind_sct":
case "nwind_sct":
applyTheme("fewClouds");
break;
case "skc":
case "nskc":
case "wind_skc":
case "nwind_skc":
case "hot":
applyTheme("sunny");
break;
case "rain_sleet":
case "rain_fzra":
case "sleet":
case "rain":
case "rain_showers":
case "rain_showers_hi":
case "shra":
case "nshra":
case "hi_shwrs":
case "hi_nshwrs":
case "ra":
case "nra":
case "minus_ra":
case "nra":
case "raip":
case "nraip":
case "fzra":
case "nfzra":
case "ra_fzra":
case "nra_fzra":
applyTheme("rain");
break;
case "bkn":
case "nbkn":
case "ovc":
case "novc":
case "wind_bkn":
case "nwind_bkn":
case "wind_ovc":
case "nwind_ovc":
applyTheme("partlyCloudy");
break;
case "tsra":
case "tsra_sct":
case "tsra_hi":
case "tornado":
case "hurricane":
case "tropical_storm":
case "ntsra":
case "scttsra":
case "nscttsra":
case "hi_tsra":
case "hi_ntsra":
case "fc":
case "nfc":
case "tor":
case "ntor":
case "hur_warn":
case "hur_watch":
case "ts_warn":
case "ts_watch":
case "ts_nowarn":
applyTheme("thunderstorm");
break;
case "du":
case "dust":
case "smoke":
case "haze":
case "fog":
case "ndu":
case "fu":
case "nfu":
case "hz":
applyTheme("mist");
break;
case "snow":
case "cold":
case "rain_snow":
case "snow_sleet":
case "snow_fzra":
case "ra_sn":
case "nra_sn":
case "fzra_sn":
case "nfzra_sn":
case "ip":
case "nip":
case "snip":
case "nsnip":
case "cold":
case "ncold":
case "blizzard":
case "nblizzard":
case "fg":
case "nfg":
applyTheme("snow");
break;
default:
applyTheme("default");
}
}
// Hides all the elements not needed at the initialization of the page
function startHide() {
$("#loadingbar").hide()
$("#weather-approval").hide()
$("#mood-prompt").hide()
$("#genre-prompt").hide()
$("#playListLoading").hide()
$("#playList").hide()
$("#userForecast").hide()
}
// Generates the spotify widgets given an array of track IDs
function genSpot(trackArray) {
$("#playListLoading").show();
songsLeftToLoad = trackArray.length;
trackArray.forEach(track => {
let spotify = $("<div>").addClass("col m6 s12").html(`<iframe src="https://open.spotify.com/embed/track/${track}" width="100%" height="80" frameborder="0" allowtransparency="true" allow="encrypted-media"></iframe>`)
$("#playList").append(spotify)
// When all widgets are done loading, show the playlist
spotify.find("iframe").on("load", event=>{
songsLeftToLoad --;
if(songsLeftToLoad==0){
$("#playListLoading").hide();
$("#playList").show();
}
})
});
}
// Events
// ==================================================================================
$("#accept-weather-btn").on("click", function(event) {
event.preventDefault();
weatherForecast();
})
$("#mood-form").on("submit", function(event) {
event.preventDefault();
if (mood.some(function(el) { return el.moodType === $("#mood-input").val().toLowerCase() })) {
userMood = $("#mood-input").val()
$("#mood-prompt").hide()
console.log("Mood: "+userMood);
$("#genre-prompt").show()
} else {
M.toast({ html: "Please enter a mood we have mapped" })
return
}
})
$("#genre-form").on("submit", async function(event) {
event.preventDefault();
if (genreList.some(function(el) { return el.genreType === $("#genre-input").val().toLowerCase() })) {
userGenre = $("#genre-input").val()
$("#genre-prompt").hide()
console.log("Genre: "+userGenre);
getMoodSingRecommendations(userGenre, userForecast, userMood).then(recs => genSpot(recs));
} else {
M.toast({ html: "Please enter a genre we have mapped" })
return
}
})
$("#smile-btn").on("click", function (event) {
event.preventDefault();
if(userForecast == null){
M.toast({ html: "Please click accept!" })
return
} else {
startHide()
$("#mood-prompt").show()
}
})
// Main Script Execution
// ==================================================================================
getSpotifyAuthorization(GLOBAL_DEV_MODE);
init();