-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
315 lines (268 loc) · 9.3 KB
/
Copy pathscript.js
File metadata and controls
315 lines (268 loc) · 9.3 KB
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
/* TODO:
- Switch play button to a stop when playing
- Sort the tracks to ensure correct order
*/
// Store the number of tracks which have been added but have not yet loaded.
// - used to determine when the last track has loaded
let numLoading = undefined;
/** Local Storage key for the replay protector data. */
const LS_REPLAY_PROTECTOR = 'mainossoitin.wappuradio.fi-replay';
/** HTML attribute for storing the replay protector time. */
const ATTR_REPLAY_PROTECTOR = 'data-replay-time';
/**
* Loading breaks
* Expect a nginx server with JSON format autoindex enabled.
*
* Structure:
* katkot/
* 1400/
* 001 - Alkujingle.mp3
* 002 - Mainos - firmaA.flac
* 003 - Loppujingle.mp3
* 1500/
* 001 - Alkujingle.mp3
* 002 - Mainos - firmaB.flac
* 003 - Loppujingle.mp3
*/
async function getBreaks() {
const r = await fetch("/katkot/");
return (await r.json()).map((o) => {
return o['name']
});
}
/**
* Check if the URL contains an break override
* used to select a specific break instead of the closest one
*/
function getOverride() {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
return urlParams.get('break'); // may be null
}
/**
* Return the break with the time closest to current time. Does not
* handle times around midnight, which is accepted since ad breaks are
* limited to around office hours.
*/
function getClosest(breaks) {
let closestBreak = undefined;
let closestDistance = undefined;
const now = new Date();
breaks.forEach((breakTimeString) => {
const h = parseInt(breakTimeString.substring(0, 2));
const m = parseInt(breakTimeString.substring(2,4));
// Construct a new date/time today, but with a HH:MM:00.000
// timestamp from the given break time
let breakTime = new Date();
breakTime.setHours(h, m, 0, 0);
const distance = Math.abs(now - breakTime);
if (!closestBreak || distance < closestDistance) {
closestDistance = distance;
closestBreak = breakTimeString;
}
})
return closestBreak;
}
/**
* Fetch metadata about files related to a specific break
*
* Expects a JSON array with objects that have a `name` property
* which corresponds to the filename in the directory.
*/
async function getBreakContents(breakTime) {
const r = await fetch(`/katkot/${breakTime}/`);
const data = await r.json();
const breakContents = data.map((track) => {
track['url'] = `/katkot/${breakTime}/${track.name}`;
return track;
});
return { breakTime, breakContents };
}
/* Creating the DOM elements */
/**
* Create a new <audio> tag which loads the give track. The file is set to
* preload, and to trigger an event when loaded.
*/
function createTrack(track) {
const container = document.createElement('div');
const label = document.createElement('span');
label.innerText = track.name;
container.appendChild(label);
container.appendChild(document.createElement("br"));
const audio = document.createElement('audio');
audio.oncanplaythrough = (context) => {
numLoading -= 1;
// The numLoading was initialized to the number of tracks. Decrement the number here
// and if the counter reaches zero, we know that all tracks are loaded and we are ready for playback.
if (numLoading === 0) {
breakLoaded();
}
};
audio.src = track.url;
audio.title = track.name;
audio.preload = "auto";
audio.controls = true;
audio.onended = trackFinished;
audio.ontimeupdate = trackTimeUpdated;
container.appendChild(audio);
container.appendChild(document.createElement("br"));
document.getElementById("player").appendChild(container);
}
/**
* Event handler: Last track has loaded. Sum up the duration and update the UI.
*/
function breakLoaded() {
const totalDuration = getSumDuration();
document.getElementById('progress').innerText = formatTime(0);
document.getElementById('duration').innerText = formatTime(totalDuration);
document.getElementById('remaining').innerText = formatTime(totalDuration);
const playButton = document.getElementById('masterPlay');
playButton.onclick = startPlaying;
playButton.style.visibility = 'visible';
}
/* Playback */
/**
* Play button pressed. Start playback from the first track
*/
async function startPlaying(event) {
const tracks = document.getElementsByTagName("audio");
const firstTrack = tracks[0];
await firstTrack.play();
// Store that we played this break already.
const breakTime = event.target && event.target.getAttribute(ATTR_REPLAY_PROTECTOR);
if (breakTime) {
localStorage.setItem(LS_REPLAY_PROTECTOR, breakTime);
}
}
/**
* A track finished playing. Start the next track if such exists.
*/
async function trackFinished(event) {
const finishedTitle = event.target.title;
const nextTrack = findNext(finishedTitle);
if (nextTrack) {
await nextTrack.play();
} else {
// Show the replay protector once the current ad break has finished playing.
const replayWarning = document.getElementById('replay-protector');
replayWarning.style.display = 'block';
}
}
/**
* Find the track which is supposed to play after the given track
*/
function findNext(title) {
const tracks = document.getElementsByTagName("audio");
let passed = false;
for (const track of tracks) {
if (passed) {
return track;
}
if (track.title === title) {
passed = true;
}
}
}
/* Visualization */
/**
* Seconds to an MM:SS format
*/
function formatTime(timeSeconds) {
let wholeSeconds = Math.round(timeSeconds);
const m = Math.floor(wholeSeconds / 60).toString().padStart(2, '0');
const s = (wholeSeconds % 60).toString().padStart(2, '0');
return `${m}:${s}`
}
/**
* Sum up the durations of all the loaded tracks
*/
function getSumDuration() {
const tracks = document.getElementsByTagName("audio");
let totalDuration = 0;
for (const track of tracks) {
totalDuration += track.duration;
}
return totalDuration;
}
/**
* Sum up the progress of all the loaded tracks
*/
function getSumProgress() {
const tracks = document.getElementsByTagName("audio");
let totalProgress = 0;
for (const track of tracks) {
totalProgress += track.currentTime;
}
return totalProgress;
}
/**
* Event: The elapsed time on a track has been updated.
*/
async function trackTimeUpdated(event) {
const totalDuration = getSumDuration();
const totalProgress = getSumProgress();
const remaining = totalDuration - totalProgress;
document.getElementById('progress').innerText = formatTime(totalProgress);
document.getElementById('remaining').innerText = formatTime(remaining);
}
/**
* Check if the currently selected break is still relevant, or if a new one should be loaded
*/
function checkBreak(breaks, oldClosest) {
if(getClosest(breaks) != oldClosest) {
document.getElementById("oldBreak").style.visibility = "visible";
const dialog = document.getElementById("refreshDialog");
dialog.showModal();
}
}
/**
* Check if the replay protector should be displayed based on localstorage data,
* and store the timestamp into a HTML attribute for future use.
*/
function checkReplay(breakTime) {
const h = parseInt(breakTime.substring(0, 2));
const m = parseInt(breakTime.substring(2,4));
// Construct a new date/time today, but with a HH:MM:00.000
// timestamp from the given break time
let date = new Date();
date.setHours(h, m, 0, 0);
const dateString = date.toISOString();
const playButton = document.getElementById('masterPlay');
playButton.setAttribute(ATTR_REPLAY_PROTECTOR, dateString);
const lastTime = localStorage.getItem(LS_REPLAY_PROTECTOR);
if (lastTime === dateString) {
const replayWarning = document.getElementById('replay-protector');
replayWarning.style.display = 'block';
}
}
function main() {
// List the break times
getBreaks().then((breaks) => {
const closest = getOverride() || getClosest(breaks);
document.getElementById("selectedBreak").innerText = closest;
breakCheckIntervalId = setInterval(() => {
checkBreak(breaks, closest);
}, 2*60*1000);
// ... and get the tracks associated with the closest break
return getBreakContents(closest);
}).then(({ breakTime, breakContents }) => {
checkReplay(breakTime);
// initialize the counter which is used to determine when all tracks are loaded
numLoading = breakContents.length;
// And create <audio> elements which actually load the tracks.
for (const track of breakContents) {
createTrack(track);
}
// breakLoaded() is called when all tracks are loaded via the oncanplaythrough event and numLoading counter.
});
}
/*
* Check if we arrived at the page via back/forward history. The contents might not be up to date,
* so better reload the page to be sure we have up to date data.
*/
const perfEntries = performance.getEntriesByType("navigation");
if (perfEntries[0].type === "back_forward") {
console.log("History traversal detected, reloading to refresh data");
location.reload();
}
main();