-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
316 lines (288 loc) · 8.11 KB
/
app.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
// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split("&")
.reduce(function(initial, item) {
if (item) {
var parts = item.split("=");
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = "";
// Set token
let _token = hash.access_token;
const authEndpoint = "https://accounts.spotify.com/authorize";
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = "753819e3242f444aabc7cadacd11de5b";
const redirectUri = "http://localhost:5500";
const scopes = ["user-top-read"];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join(
"%20"
)}&response_type=token&show_dialog=true`;
}
const url = "https://api.spotify.com/v1/me/playlists?limit=50";
const options = {
headers: {
Authorization: `Bearer ${_token}`
}
};
const output = document.querySelector("#test1 .output");
// Fetch Call
fetch(url, options)
.then(response => response.json())
.then(data => getData(data));
// Get the data
const getData = data => {
const items = data.items;
items.reduce((accumulator, item) => {
// console.log(item);
const holder =
accumulator +
`
<div class="col s12 m6 l4 xl4">
<div class="card">
<div class="card-image">
<img src="${item.images[0].url}">
</div>
<div class="card-content">
<a class="black-text playlist-name">${truncate(`${item.name}`, 20)}</a>
</div>
<div class="card-action ">
<a href="#modal1" class="right-align track btn black white-text modal-trigger" data-link="${
item.tracks.href
}" data-title="${item.name}">Tracks list</a>
<a href="#" class="select yellow darken-1 btn white-text" data-link="${
item.tracks.href
}">Select</a>
</div>
</div>
</div>
`;
return (output.innerHTML = holder);
}, "");
// Function get Track List
function getTracks() {
//Append playlist name to modal header
const modalTitle = document.querySelector("h4.title");
const buttons = document.querySelectorAll("a.track");
buttons.forEach(button => {
button.addEventListener("click", e => {
// Append Playlist name to modal title
modalTitle.innerHTML = button.dataset.title;
// Get the playlist url
const url = button.dataset.link;
const options = {
headers: {
Authorization: `Bearer ${_token}`
}
};
// Fetch playlist url
fetch(url, options)
.then(response => response.json())
.then(data => appendToModal(data));
});
});
}
getTracks();
select();
};
// Function select playlist
function select() {
const buttons = document.querySelectorAll(".select");
buttons.forEach(button => {
button.addEventListener("click", e => {
const url = button.dataset.link;
const options = {
headers: {
Authorization: `Bearer ${_token}`
}
};
// Fetch playlist url
fetch(url, options)
.then(response => response.json())
.then(data => saveToFirebase(data.items));
});
});
}
// Function save to firebase
function saveToFirebase(params) {
// Loop data
params.map(async (val, index) => {
const { track } = val;
const artistName = track.artists[0].name;
const trackName = track.name;
const releaseDate = track.album.release_date;
const duration = msToMinutesSecond(track.duration_ms);
const tempoId = track.id;
const tempoResult = await tempo(`${tempoId}`);
// console.log(
// `${tempoResult}${artistName}${trackName}${releaseDate}${duration}`
// );
const id = split(artistName, trackName);
const obj = {
artist: artistName,
title: trackName,
release: releaseDate,
category: category(releaseDate),
duration: duration,
tempo: tempoResult
};
// Add data
db.collection("playlist")
.doc(id)
.set(obj)
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
});
}
// Function append tracks to modal content
function appendToModal(params) {
const rows = document.querySelector("tbody");
const data = params.items;
// Loop the data
const rowsArr = data.map(async (val, index) => {
const { track } = val;
const trackName = track.name;
const artistName = track.artists[0].name;
// const href = track.artists[0].href;
// const options = {
// headers: {
// Authorization: `Bearer ${_token}`
// }
// };
// fetch(href, options)
// .then(data => data.json())
// .then(res => console.log(res.genres));
const releaseDate = track.album.release_date;
const duration = track.duration_ms;
const tempoId = track.id;
const tempoResult = await tempo(`${tempoId}`);
// Assign to html
return `
<tr>
<td>${index + 1}</td>
<td>${artistName}</td>
<td>${truncate(`${trackName}`, 16)}</td>
<td>${releaseDate}</td>
<td>${category(`${releaseDate}`)}</td>
<td>${msToMinutesSecond(`${duration}`)}</td>
<td>${tempoResult}</td>
</tr>
`;
});
Promise.all(rowsArr).then(result => {
// console.log(result);
rows.innerHTML = result.join("");
});
}
// Function to get tempo
async function tempo(params) {
const url = `https://api.spotify.com/v1/audio-features/${params}`;
const options = {
headers: {
Authorization: `Bearer ${_token}`
}
};
const data = await fetch(url, options);
const json = await data.json();
const final = Math.round(json.tempo);
// console.log(final)
return `${final} BPM`;
}
// Function set category
function category(str) {
const getYear = parseInt(str.substring(0, 4));
const today = new Date();
const year = today.getFullYear();
const substract = year - getYear;
let category = "";
if (getYear === year) {
return (category = "Top 40");
}
if (substract === 1) {
category = "Current";
} else if (substract >= 2 && substract < 10) {
category = "Recurrent";
} else {
category = "Oldies";
}
return category;
}
// Function change ms to Minutes and second
function msToMinutesSecond(ms) {
var minutes = Math.floor(ms / 60000);
var seconds = ((ms % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}
// Function truncate text
const truncate = (str, length) => {
return str.length >= length ? `${str.substring(0, length)} ....` : str;
};
// Get Songs method
const song = document.querySelector("a.songs");
song.addEventListener("click", e => {
// alert("Clicked");
db.collection("playlist")
.orderBy("artist")
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
const id = doc.id;
const {
artist,
title,
release,
category,
duration,
tempo
} = doc.data();
// doc.data() is never undefined for query doc snapshots
console.log(`${artist} - ${title}`);
});
});
});
// function trim 'the'
function split(artist, title) {
let finalID = [];
let splitArtist = artist.split(" ");
if (splitArtist[0] == "The" || splitArtist[0] == "A") {
finalID.push(splitArtist[1]);
} else {
finalID.push(splitArtist[0]);
}
let splitTitle = title.split(" ");
if (splitTitle[0] == "The" || splitTitle[0] == "A") {
finalID.push(splitTitle[1]);
} else {
finalID.push(splitTitle[0]);
}
splitTitle.find(val => {
if (val == "Live") {
finalID.push(val);
}
});
const result = finalID.join("-").toUpperCase();
console.log(result);
return result;
}
// Init modal
document.addEventListener("DOMContentLoaded", function() {
var elems = document.querySelectorAll(".modal");
var modal = M.Modal.init(elems, {
endingTop: "50%",
preventScrolling: false,
inDuration: 500,
outDuration: 600
});
var tabs = document.querySelectorAll(".tabs");
var instance = M.Tabs.init(tabs, {
duration: 750
});
});