aboutsummaryrefslogtreecommitdiff
path: root/client/js/radio_emulator.js
blob: 97b047466b208d04ff7e6eb30e1a1ad7f86c56b9 (plain)
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
// Radio Station Emulator
//
// Kaotisk Hund - 2024
//
// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL v3.0
//
// A simple co-mechanism to pretend playing a live radio as it would happen for
// a radio station that mostly plays prerecoded shows.
//
// Client side implementation
// Let's remind here the structures we are waiting for:
// 1. Hash
// 2. 0
// 3. audio/ogg file
// 4. application/json file
//
// 1. Hash
// Can be an SHA512sum or SHA256sum, we don't do checks, we only ask the hash
// accompanied by what do we think it is.
//
// 2. 0
// When nothing exists on the radio station we are visiting.
//
// 3. audio/ogg file
// An audio file to play.
//
// 4. application/json file
// Could be one of the following:
//   - list
//   - show_info
//
var debugMode = false;
const apiURL = "http://z.kaotisk-hund.com:8010/";
const version = "v0";
const listRequest = `${apiURL}${version}/list`
const jsonRequest = `${apiURL}${version}/application/json/`
const audioRequest = `${apiURL}${version}/audio/ogg/`

const documentTitle = "Radio Station Emulator";
const separator = " :: ";


placeholders = {
    currentTime: document.querySelector('.current-time'),
    listStarted: document.querySelector('.started-on'),
    currentShowHash : document.querySelector('.current-show-hash'),
    listHash : document.querySelector('.list-hash'),
    artist: document.querySelector('.artist'),
    title: document.querySelector('.title'),
    radioPlayer: document.querySelector('.radio-player'),
    youAreHere : document.querySelector('.you-are-here'),
    playProgress: document.querySelector('.play-progress'),
    startsOn: document.querySelector('.starts-on'),
    showDuration: document.querySelectorAll('.show-duration'),
    relativeTime: document.querySelector('.relative-time'),
    listeningAt: document.querySelector('.listening-at'),
    dlProgress: document.querySelector('.dl-progress'),
    minTimesPlayed: document.querySelector('.min-played'),
    maxTimesPlayed: document.querySelector('.max-played'),
    listDuration: document.querySelector('.list-duration'),
    previouslyPlayed: document.querySelector('.previously-played'),
    showInfo: document.querySelector('.show-info'),
    listInfo: document.querySelector('.list-info'),
    dt: document.querySelector('.d-t'),
    deltaTime: document.querySelector('.delta-time'),
    timeOfVisit: document.querySelector('.time-of-visit')
}

var values = {
    delta_time: 0,
    min_times_played: 0,
    maxTimesPlayed: 0,
    Dt: 0,
    now_on_sequence: 0,
    seconds_here: 0,
    current_time: 0
}

function debugLog(message)
{
    if ( debugMode ) console.log(message);
}

function setTitleSyncing(){
    document.title = "🔃Syncing" + separator + documentTitle;
}

function setTitleMessage(message){
    document.title = message + separator + documentTitle;
}

function updateComponentsAfterIncreaseSeconds()
{
    placeholders.youAreHere.innerText = values.seconds_here;
    placeholders.playProgress.value = values.current_time + values.seconds_here;
    placeholders.relativeTime.innerText = values.current_time + values.seconds_here;
    placeholders.listeningAt.innerText = Math.floor(audioElement.currentTime);
}

function increaseSeconds()
{
    values.seconds_here = values.seconds_here + 1;
    updateComponentsAfterIncreaseSeconds();
    return values.seconds_here;
}
function getSecondsHere()
{
    return values.seconds_here;
}

setInterval(increaseSeconds, 1000);


function FetchJSON( url, callback, params )
{
    setTitleSyncing();
    const request = new XMLHttpRequest();
    request.addEventListener("load", ()=>{
        var json = JSON.parse(request.response);
        if(request.status !== 404){
            callback(json, params);
        } else {
            debugLog(`ERROR ${request.status} while loading ${url}`);
        }
    });
    request.addEventListener("error", ()=>{
        debugLog("An error occured. While loading: "+url+" for "+callback+".");
    });
    request.addEventListener("abort", ()=>{
        debugLog("Request aborted: "+url+" for "+callback+".");
    });
    request.open("GET", url);
    request.send();
}

function FetchAudio(url, callback)
{
    const request = new XMLHttpRequest();
    request.responseType = 'blob';
    request.addEventListener("load", ()=>{
        if(request.status === 200){
            debugLog("Got it... trying!")
            placeholders.dlProgress.value = 100;
            audioElement.src = URL.createObjectURL(request.response);
            callback();
            //audioElement.play();
            debugLog("Tried... did it work?");
        } else {
            debugLog(`ERROR ${request.status} while loading ${url}`);
        }
    });
    request.addEventListener("progress", (event)=>{
        if (event.lengthComputable)
        {
            debugLog(`Fetching: ${event.total}`);
            placeholders.dlProgress.value = (event.loaded/event.total)*100;
        }
    });
    request.addEventListener("error", ()=>{
        debugLog("An error occured. While loading: "+url);
    });
    request.addEventListener("abort", ()=>{
        debugLog("Request aborted: "+url);
    });
    request.open("GET", url);
    request.send();
}

function genericCallback(json, params)
{
    debugLog('genericCallback');
    debugLog(json);
    debugLog(params);
}

var calledLoadShowCallback = 0;

function stopHereAndReflect()
{
    return 0;
}

function updateComponentsAfterLoadShowCallback(json, listItem)
{
    setTitleMessage ( "▶️ " + json.artist + " - " + json.title );
    placeholders.currentShowHash.innerText = listItem.hash;
    placeholders.artist.innerText = json.artist;
    placeholders.title.innerText = json.title;
    placeholders.showDuration.forEach((element)=>{element.innerText = Math.floor(listItem.duration/1000)});
    placeholders.startsOn.innerText = listItem.starts_on;
    placeholders.playProgress.max = Math.floor(listItem.duration/1000);
    placeholders.showInfo.innerText = JSON.stringify(json, null, 2);
    placeholders.currentTime.innerText = values.current_time;
}

function loadShowCallback(json, params)
{
    const [ list, now_on_sequence, listItem, hash_of_list ] = params;
    debugLog('loadShowCallback');
    debugLog(json);
    debugLog(listItem);
    //debugLog(params);
    audioElement.load();
    FetchAudio(`${audioRequest}${json.hash}`, sync_radio);
    audioElement.type = json.mimetype;
    values.current_time = Math.floor((values.now_on_sequence/1000)); // - listItem.starts_on)/1000);
    updateComponentsAfterLoadShowCallback(json, listItem);
    audioElement.addEventListener('ended', function(){
        values.current_time = 0;
        values.seconds_here = 0;
        placeholders.currentTime.value = 0;
        FetchJSON(`${listRequest}`, hashCallback, [ new Date().getTime() ]);
    });
}

function preciseIncreaseVolume(value)
{
    if ( value <= 1 ) audioElement.volume = value;
}

function fadeInAudio()
{
    var timeSpan = 1000;
    var timeStep = 100;
    for ( var i = 0; i <= 90; i++ )
    {
        timeSpan = timeSpan + timeStep;
        var newVolume = Math.sin(i*(Math.PI/180));
        setTimeout( preciseIncreaseVolume(newVolume), timeSpan);
    }
}

function sync_radio()
{
    var new_now = values.current_time + getSecondsHere();
    debugLog("Trying to sync @ "+ values.current_time + " + " + getSecondsHere() + " = " + new_now);
    audioElement.currentTime = new_now;
    audioElement.play();
    audioElement.muted = false;
    audioElement.volume = 0;
    fadeInAudio();
    return new_now;
}

function syncOnDOMfromListCallback(now, hash_of_list, json)
{
    placeholders.timeOfVisit.innerText = now;
    placeholders.listStarted.innerText = json.started_on;
    placeholders.listDuration.innerText = json.duration;
    placeholders.listHash.innerText = hash_of_list;
    placeholders.deltaTime.innerText = values.delta_time;
    placeholders.minTimesPlayed.innerText = values.min_times_played;
    placeholders.maxTimesPlayed.innerText = values.max_times_to_be_played;
    placeholders.dt.innerText = values.Dt;
    placeholders.currentTime.innerText = values.now_on_sequence;
    placeholders.listInfo.innerText = JSON.stringify(json, null, 2);
}

function infoShowCallback(json, params)
{
    var [ hash ] = params;
    if ( document.querySelector(`#d-${hash}`) !== null )
    {
        var parent = document.querySelector(`#d-${hash}`);
        var tableElement = {
            element:'div',
            id: `t-${hash}`,
            innerHTML:[
                {element:"div",innerText:`${json.artist}`},
                {element:"div",innerText:`${json.title}`}
            ]
        };
        makeElement(tableElement, parent);
    }
}

function appendPreviouslyPlayedShows(listItem){
    if ( document.querySelector(`#d-${listItem.hash}`) === null )
    {
        var tmp = {
            element:'div',
            style: 'flex-direction:row;align-items:center;',
            id: `d-${listItem.hash}`,
            innerHTML:[
                { element:"img", id: `i-${listItem.hash}` }
            ]
        }
        makeElement(tmp, placeholders.previouslyPlayed);
        document.querySelector(`#d-${listItem.hash}`).scrollIntoView();
        generateImage(listItem.hash, 'new');
        FetchJSON(`${jsonRequest}${listItem.hash}`, infoShowCallback, [listItem.hash]);
    }
}

function listCallback(json, params)
{
    debugLog('listCallback');
    debugLog(json);
    debugLog(params);
    var [ now, hash_of_list ] = params;
    values.delta_time = now - json.started_on;
    values.min_times_played = Math.floor( values.delta_time / json.duration );
    values.max_times_to_be_played = values.delta_time / json.duration;
    values.Dt = values.max_times_to_be_played - values.min_times_played