aboutsummaryrefslogtreecommitdiff
path: root/web/client.html
blob: 91ce11d61637d36cf515d8c4d038f28bd4f529cc (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
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
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>WRMS</title>

    <style>
      .vote {
        display: inline-block;
        cursor: pointer;
        color: #687074
      } 

      .vote.on {
        color: #f48024
      }

      .searchResult:hover {
        background-color: #999;
      }
    </style>

    <script>
      /*
      @licstart  The following is the entire license notice for the 
      JavaScript code in this page.

      Copyright (C) 2022  Florian Fischer

      The JavaScript code in this page is free software: you can
      redistribute it and/or modify it under the terms of the GNU
      General Public License (GNU GPL) as published by the Free Software
      Foundation, either version 3 of the License, or (at your option)
      any later version.  The code is distributed WITHOUT ANY WARRANTY;
      without even the implied warranty of MERCHANTABILITY or FITNESS
      FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.

      As additional permission under GNU GPL version 3 section 7, you
      may distribute non-source (e.g., minimized or compacted) forms of
      that code without the copy of the GNU GPL normally required by
      section 4, provided you include this license notice and a URL
      through which recipients can access the Corresponding Source.   


      @licend  The above is the entire license notice
      for the JavaScript code in this page.
      */
    </script>

    <script>
      let HttpClient = function() {
        function newRequest(callback) {
          let request = new XMLHttpRequest();
          request.onreadystatechange = function() { 
            if (request.readyState == 4 && request.status == 200)
              callback(request.responseText);
          }
          return request;
        }

        this.get = function(url, callback) {
          let request = newRequest(callback);
          request.open("GET", url, true);            
          request.send(null);
        }

        this.post = function(url, data, callback) {
          let request = newRequest(callback);
          request.open("POST", url, true);            
          request.send(data);
        }
      }

      let isAdmin = false;
      let searchId = 0;
      let songs = [];
      let playing = {};
      let votes = new Map();

      function formatSong(song) {
        if (song.artist)
          return song.artist + ' - ' + song.title
        return song.title
      }

      function newSourceLabel(song) {
         const sourceLabel = document.createElement("SMALL");
         sourceLabel.appendChild(document.createTextNode(" (" + song.source + ")"));
         return sourceLabel;
      }

      function renderPlaylist() {
        playlist = document.getElementById("playlist");
        playlist.innerHTML = "";

        songs.sort(function(a, b) {return b.weight - a.weight});

        for (const song of songs) {
          let listItem = document.createElement("li");

          const btnHTML = "<svg width='36' height='36'><path d='M2 10h32L18 26 2 10z' fill='currentColor'></path></svg>";
          let upvoteBtn = document.createElement("span");
          let downvoteBtn = document.createElement("span");

          upvoteBtn.innerHTML = downvoteBtn.innerHTML = btnHTML;
          upvoteBtn.className = downvoteBtn.className = "vote";
          upvoteBtn.style.transform = 'rotate(180deg)';

          if (votes.has(song.uri)) {
            if (votes.get(song.uri) == "up")
              upvoteBtn.classList.toggle("on");
            else
              downvoteBtn.classList.toggle("on");
          }

          function onVote(event) {
            const btn = event.currentTarget;
            btn.classList.toggle("on");
            const isUpvoteBtn = btn == upvoteBtn;
            const isVote = btn.classList.contains("on");
            let url = "";
            
            if (isVote) {
              if (isUpvoteBtn) {
                downvoteBtn.classList.remove("on")
                votes.set(song.uri, "up")
              } else {
                upvoteBtn.classList.remove("on")
                votes.set(song.uri, "down")
              }

              url = "/" + (isUpvoteBtn ? "up" : "down") + "?song=" + encodeURIComponent(song.uri);
            } else {
              votes.delete(song.uri);
              url = "/unvote?song=" + encodeURIComponent(song.uri);
            }

            console.log("Get " + url);
            new HttpClient().get(url, console.log);
          }
          upvoteBtn.addEventListener("click", onVote);
          downvoteBtn.addEventListener("click", onVote);

          listItem.appendChild(upvoteBtn);
          listItem.appendChild(downvoteBtn);

          listItem.appendChild(document.createTextNode(song.weight + ' ' + formatSong(song)));
          listItem.appendChild(newSourceLabel(song));
          {{if .IsAdmin}}
          let delBtn = document.createElement("button");
          delBtn.style.marginLeft = 10 + "px";
          delBtn.appendChild(document.createTextNode("delete"));
          delBtn.addEventListener("click", function() {
            const params = new URLSearchParams();
            params.append("song", song.uri)
            new HttpClient().get("/delete?" + params.toString(), console.log);
          });
          listItem.appendChild(delBtn);
          {{end}}
          playlist.appendChild(listItem);
        }
      }

      function handleAdd(added) {
        songs = songs.concat(added);
        renderPlaylist();
      }

      function handleDelete(deleted) {
        for (const deletedSong of deleted) {
          const index = songs.findIndex(function(s) {return s.uri == deletedSong.uri});
          if (index > -1) { songs.splice(index, 1); }
        }
        renderPlaylist();
      }

      function handleVotes(direction, votedSongs) {
        for (const song of votedSongs) {
          votes.set(song.uri, direction)
        }
        renderPlaylist();
      }

      function handleUpdate(updated) {
        for (const updated_song of updated) {
          songs[songs.findIndex(function(s) {return s.uri == updated_song.uri})] = updated_song;
        }
        renderPlaylist();
      }

      function handlePause() {
        {{if .IsAdmin}} document.getElementById("ppbutton").innerHTML = 'Play'; {{end}}
      }

      function handleStop() {
        // The stop event is only emmited if WRMS is Playing and runs out of songs.
        // Therefore, we can safely change the button label to Pause since WRMS is playing.
        // Seeing a stop event before a play event can occur when an admin calls /playpause
        // with an empty playlist.
        {{if .IsAdmin}} document.getElementById("ppbutton").innerHTML = 'Pause'; {{end}}
        playing = document.getElementById("playing").innerHTML = "";
      }

      function handlePlay(currentSong) {
        {{if .IsAdmin}} document.getElementById("ppbutton").innerHTML = 'Pause'; {{end}}

        idx = -1;
        songs.forEach(function(s, i, a) { if (s.uri == currentSong.uri) idx = i; });
        if (idx != -1) {
          songs.splice(idx, 1);
          renderPlaylist();
        }

        const songLabel = document.createTextNode(formatSong(currentSong));

        playing = document.getElementById("playing");
        playing.innerHTML = "";
        playing.appendChild(songLabel);
      }

      let socket_url = "ws://"+location.hostname + (location.port ? ":" + location.port: "") + "/ws";
      let socket = new WebSocket(socket_url);
      console.log("Attempting Connection...");

      socket.onopen = () => {
        console.log("Successfully Connected");
      };
      
      socket.onclose = event => {
        console.log("Socket Closed Connection: ", event);
      };

      socket.onmessage = message => {
        console.log("Socket Received Message: ", message);
        const cmd = JSON.parse(message.data);
        switch (cmd.cmd) {
          case "add":
            handleAdd(cmd.songs)
            break;
          case "delete":
            handleDelete(cmd.songs)
            break;
          case "update":
            handleUpdate(cmd.songs)
            break;
          case "pause":
            handlePause()
            break;
          case "stop":
            handleStop()
            break;
          case "play":
            handlePlay(cmd.songs[0])
            break;
          case "upvoted":
            handleVotes("up", cmd.songs)
            break;
          case "downvoted":
            handleVotes("down", cmd.songs)
            break;
          case "search":
            handleSearch(cmd.id, cmd.songs)
            break;
          case "finish-search":
            handleFinishSearch(cmd.id)
            break;
        }
      };

      socket.onerror = error => {
        console.log("Socket Error: ", error);
      };

      function submitSearch() {
        resetSearch();

        let searchingIndicator = document.getElementById("searching");
        searchingIndicator.style.display = "block";
        let searchResultsOverlay = document.getElementById("searchResultsOverlay");
        searchResultsOverlay['aria-busy'] = true;

        const form = new FormData(document.getElementById("searchForm"));
        const urlParams = new URLSearchParams(form);
        urlParams.append("id", searchId);
        new HttpClient().get("/search?" + urlParams.toString(), console.log);
        return false;
      }

      {{if .Config.HasUpload}}
      function submitUpload() {
        const form = new FormData(document.getElementById("uploadForm"));
        const file = form.get("song");
        const params = new URLSearchParams();
        params.append("song", file.name);
        const song = params.toString();
        new HttpClient().post("/upload?" + song, file, console.log);
        return false;
      }
      {{end}}

      function addSong(song) {
        new HttpClient().post("/add", JSON.stringify(song), console.log);
      }

      function handleFinishSearch(id) {
        // Ignore stale finish search notifications
        if (id < searchId) { return; }

        let searchingIndicator = document.getElementById("searching");
        searchingIndicator.style.display = "none";
        let searchResultsOverlay = document.getElementById("searchResultsOverlay");
        searchResultsOverlay['aria-busy'] = false;
        searchId += 1;
      }

      function handleSearch(id, songs) {
        // Ignore stale search results
        if (id < searchId) { return; }

        let searchResultsOverlay = document.getElementById("searchResultsOverlay");
        let searchResults = document.getElementById("searchResults");
        for (const song of songs) {
          let listItem = document.createElement("li");
          listItem.addEventListener("click", function() {
            addSong(song);
          });

          listItem.classList.add("searchResult")
          listItem.appendChild(document.createTextNode(formatSong(song)));
          listItem.appendChild(newSourceLabel(song));
          searchResults.appendChild(listItem);
        }

        // Show search result overlay
        searchResultsOverlay.style.display = "block";
      }

      function resetSearch() {
        // Clear search Results
        let searchResults = document.getElementById("searchResults");
        searchResults.innerHTML = "";

        searchId += 1;
      }

      window.onload = function() {
        {{if .IsAdmin}}
        document.getElementById("ppbutton").addEventListener("click", function() {
          new HttpClient().get("/playpause", console.log);
        });

        document.getElementById("nextbutton").addEventListener("click", function() {
          new HttpClient().get("/next", console.log);
        });
        {{end}}
      }
    </script>
  </head>

  <body>
    <h2>Add your song</h2>
    <div id="add">
      <form id="searchForm" onsubmit="return submitSearch()">
        <input id="searchInput" name="pattern" type="text" value="Title/Artist/Album/...", onclick="this.select();">
        <button id="searchButton">Search</button>
      </form>

      {{if .Config.HasUpload}}
      <form id="uploadForm" onsubmit="return submitUpload()">
        <input id="uploadInput" name="song" type="file", accept="audio/*">
        <button id="uploadButton", type="submit">Upload</button>
      </form>
      {{end}}
    </div>

    <progress id="searching" aria-label="Searching" style="display: none;"></progress>
    <div id="searchResultsOverlay" style="display: none;" aria-busy="true" aria-describedby="searching">
      <details>
        <summary>Search Results</summary>
        <ul id="searchResults">
        </ul>
      </details>
    </div>

    <h2>Playing</h2>
    <p id='playing'></p>
    {{if .IsAdmin}}
    <div id='controls'>
      <button id="ppbutton">Play</button>
      <button id="nextbutton">Next</button>
    </div>
    {{end}}

    <h2>Playlist</h2>
    <ul id='playlist'></ul>
  </body>
</html>