-
Notifications
You must be signed in to change notification settings - Fork 0
/
scripts.js
404 lines (339 loc) · 11.2 KB
/
scripts.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
/* ----------------------- */
/* ------GOOGLE INIT------ */
/* ----------------------- */
const CLIENT_ID = '865687982989-kv2vrmhsvs5484ebe8up2j8so7ralptg.apps.googleusercontent.com';
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
const SCOPES = 'https://www.googleapis.com/auth/drive.readonly';
let tokenClient;
let gapiInited = false;
let gisInited = false;
function gapiLoaded() {
gapi.load('client', initializeGapiClient);
}
async function initializeGapiClient() {
await gapi.client.init({
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
}
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '',
});
gisInited = true;
}
function handleAuthClick(folderId) {
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
// set parentfolder as root if nothing set
if ( localStorage.getItem("parentfolder") == "" || localStorage.getItem("parentfolder") == null ) {
localStorage.setItem("parentfolder", "root");
folderId = "root";
}
// only load initial contents on first auth
if ( !document.getElementById("contents").classList.contains("loaded") ) {
getContents(folderId, "initial");
}
// set user email and URL
gapi.client.drive.about.get({
'fields' : "user",
}).then(function(response) {
window.location.hash = '#~' + response.result.user.permissionId;
localStorage.setItem("email", response.result.user.emailAddress);
});
};
if ( gapi.client.getToken() === null ) {
tokenClient.requestAccessToken({prompt: '', login_hint: localStorage.getItem("email")});
} else {
tokenClient.requestAccessToken({prompt: '', login_hint: localStorage.getItem("email")});
}
// use to see token
//console.log( gapi.client.getToken() );
}
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
// can use this to simulate expired token
gapi.client.setToken('');
}
}
/* ----------------------- */
/* -------DRIVE API------- */
/* ----------------------- */
function changeImgSrc(detailsId, newSrc) {
var detailsElement = document.getElementById(detailsId);
if (detailsElement) {
var summaryElement = detailsElement.querySelector('summary');
var imgElement = summaryElement.querySelector('img');
if (imgElement) {
imgElement.src = newSrc;
}
}
}
function getArts() {
var albumartquery = "mimeType contains 'image/' and trashed = false and name contains 'folder.jpg' ";
gapi.client.drive.files.list({
'pageSize': 1000,
'q' : albumartquery,
'fields': "nextPageToken, files(id, name, webContentLink, parents)"
}).then(function(response) {
if (response.result.files && response.result.files.length > 0) {
//console.log(response);
for (var i = 0; i < response.result.files.length; i++) {
changeImgSrc(response.result.files[i].parents[0], response.result.files[i].webContentLink);
}
}
});
}
function getContents(id, type) {
var contentsQuery = "'" + id + "'" + " in parents and trashed = false ";
gapi.client.drive.files.list({
'pageSize': 1000,
'q' : contentsQuery,
'orderBy': 'name',
'fields': "nextPageToken, files(id, name, mimeType, webContentLink)"
}).then(function(response) {
// hide intro
document.getElementById('intro').style.display = 'none';
// set location
if ( type == "initial" ) {
var location = "contents";
} else {
var location = id;
// check for previous load
if ( document.getElementById(location).classList.contains("loaded") ) {
return;
}
}
var files = response.result.files;
if (files && files.length > 0) {
// loop folders
for (var i = 0; i < files.length; i++) {
var file = files[i];
if ( file.mimeType.includes("application/vnd.google-apps.folder") ) {
document.getElementById(location).innerHTML += `
<details id="${file.id}">
<summary onclick="getContents('${file.id}')"><img src=""/><span>${file.name}</span></summary>
</details>
`;
}
document.getElementById(location).classList.add("loaded");
}
//getArts();
// loop files
for (var i = 0; i < files.length; i++) {
var file = files[i];
if ( file.mimeType.includes("audio") ) {
document.getElementById(location).innerHTML += `
<button class="track" onclick="playTrack('${file.id}', this)"><i class="fas fa-play"></i> ${file.name}</button>
`;
}
document.getElementById(location).classList.add("loaded");
}
} else {
alert('No files found.');
}
document.getElementById(location).firstElementChild.focus();
}).catch(function(error) {
if (error.status === 401) {
alert("Sessions are only valid for 1 hour. Session will refresh automatically.");
tokenClient.requestAccessToken({prompt: '', login_hint: localStorage.getItem("email")});
}
});
}
/* ----------------------- */
/* ------USER FOLDER------ */
/* ----------------------- */
function submitFolderId(e) {
e.preventDefault();
localStorage.setItem("parentfolder", document.getElementById('parentfolder').value);
handleAuthClick(document.getElementById('parentfolder').value);
}
function getFolderId() {
document.getElementById('parentfolder').value = localStorage.getItem("parentfolder");
}
/* ----------------------- */
/* ---------AUDIO--------- */
/* ----------------------- */
audio = document.getElementById('audio');
source = document.getElementById('source');
if ( document.getElementsByClassName("playing")[0] ) {
playing = document.getElementsByClassName("playing")[0];
} else {
playing = false;
}
function playTrack(id, element, type) {
// remove spinner if load in progress
if ( document.getElementById("spinner") ) {
document.getElementById("spinner").remove();
}
// check if clicked track is already 'playing'
if ( element == playing ) {
if ( audio.paused ) {
audio.play();
} else {
audio.pause();
}
return;
}
// check for something already 'playing'
if ( playing ) {
resetIconToPlay();
playing.classList.remove("playing");
}
// set new track
element.classList.add("playing");
playing = document.getElementsByClassName("playing")[0];
audio.pause();
source.src = "";
audio.load();
spinner = `
<div id="spinner">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
`;
playing.innerHTML += spinner;
// user track
gapi.client.drive.files.get({
'fileId' : id,
'alt': 'media',
}).then(function(response) {
dataArr = Uint8Array.from(response.body.split('').map((chr) => chr.charCodeAt(0)));
file = new File([dataArr], 'audiofilename', { type: response.headers['Content-Type'] });
source.src = URL.createObjectURL(file);
source.type = response.headers['Content-Type'];
audio.load();
audio.oncanplay = audio.play();
if ( document.getElementById("spinner") ) {
document.getElementById("spinner").remove();
}
}).catch(function(error) {
if (error.status === 401) {
alert("Sessions are only valid for 1 hour. Session will refresh automatically.");
tokenClient.requestAccessToken({prompt: '', login_hint: localStorage.getItem("email")});
}
});
}
function prevTrack() {
if ( audio.currentTime > 3 || !playing.previousElementSibling.previousElementSibling ) {
audio.currentTime = 0;
audio.play();
} else if ( playing.previousElementSibling.previousElementSibling ) {
resetIconToPlay();
playing.previousElementSibling.click();
}
}
function nextTrack() {
if ( playing.nextElementSibling ) {
resetIconToPlay();
playing.nextElementSibling.click();
}
}
function resetIconToPlay() {
playing.firstChild.classList.remove("fa-pause");
playing.firstChild.classList.add("fa-play");
if ( document.getElementById("bars") ) {
document.getElementById("bars").remove();
}
}
function resetIconToPause() {
playing.firstChild.classList.remove("fa-play");
playing.firstChild.classList.add("fa-pause");
indicator = `
<div id="bars">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>
`;
playing.innerHTML += indicator;
}
audio.onended = function() {
if ( playing.nextElementSibling ) {
playing.nextElementSibling.focus();
}
nextTrack();
};
audio.onpause = function() {
resetIconToPlay();
}
audio.onplay = function() {
resetIconToPause();
}
/* ----------------------- */
/* -------PAGE LOAD------- */
/* ----------------------- */
document.getElementById('intro').style.display = 'block';
function changeFolder() {
// show intro with parentfolder form
document.getElementById('intro').style.display = 'block';
document.getElementById('parentfolder').focus();
// reset contents div
document.getElementById("contents").classList.remove("loaded");
document.getElementById("contents").innerHTML = "";
// reset localstorage
localStorage.removeItem("email");
}
/* ----------------------- */
/* ----------MENU--------- */
/* ----------------------- */
const menuButton = document.getElementById('menu-btn');
const menu = document.getElementById('menu');
menuButton.addEventListener('click', function() {
const expanded = this.getAttribute('aria-expanded') === 'true' || false;
this.setAttribute('aria-expanded', !expanded);
menu.hidden = !menu.hidden;
});
document.documentElement.addEventListener('click', function(event) {
if (menu.hidden) return;
const isClickInsideMenu = menu.contains(event.target);
const isClickInsideMenuButton = menuButton.contains(event.target);
if (!isClickInsideMenu && !isClickInsideMenuButton) {
menu.hidden = true;
menuButton.setAttribute('aria-expanded', 'false');
}
});
// gapless playback attempt
// the switch between two loaded audio elements still has a gap
// can start playing second track early, but gap will be inconsistent
/*
<audio id="audio2" controls style="display: none;">
<source id="source2" src="" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
*/
/*
audio2 = document.getElementById('audio2');
function lastSecond() {
if ( audio.currentTime > audio.duration - .2572 ) {
audio2.play();
audio.removeEventListener("timeupdate", lastSecond);
}
}
function lastTenSeconds() {
if ( audio.currentTime > audio.duration - 10 ) {
audio.removeEventListener("timeupdate", lastTenSeconds);
gapi.client.drive.files.get({
'fileId' : "1UcOF2cYttKyfKcNbwFzWVKDbcGov-rMn",
'alt': 'media',
}).then(function(response) {
dataArr = Uint8Array.from(response.body.split('').map((chr) => chr.charCodeAt(0)));
file = new File([dataArr], 'audiofilename', { type: response.headers['Content-Type'] });
source2.src = URL.createObjectURL(file);
audio2.load();
});
//[audio, audio2] = [audio2, audio];
}
}
audio.addEventListener("timeupdate", lastTenSeconds);
audio.addEventListener("timeupdate", lastSecond);
*/