playlist/metadata: do not crash whilst connecting
[chrome-ext/music-player-client.git] / main.js
1 // Written by Mike Frysinger <vapier@gmail.com>. Released into the public domain. Suck it.
2
3 /* Globals to allow easy manipulation via javascript console */
4 var mpc;
5 var tcpclient;
6 var refresh_id = NaN;
7
8 function TcpClientSender(tcpclient) {
9 this.tcpclient = tcpclient;
10 }
11 TcpClientSender.prototype.send = function(data, cb) {
12 this.tcpclient.sendMessage(data, cb);
13 }
14 TcpClientSender.prototype.poll = function() {
15 this.tcpclient.poll();
16 }
17 TcpClientSender.prototype.reconnect = function() {
18 this.tcpclient.disconnect();
19 this.tcpclient.connect();
20 }
21
22 function tramp_mpc_recv(data) {
23 mpc.recv(data);
24 }
25
26 function sync_storage(sync) {
27 return sync ? chrome.storage.sync : chrome.storage.local;
28 }
29
30 window.onload = function() {
31 var local_keys = [
32 'sync',
33 ];
34 var sync_keys = [
35 'host', 'port', 'refresh',
36 ];
37 var options = {
38 'host': '192.168.0.2',
39 'port': 6600,
40 'sync': true,
41 'refresh': 5,
42 };
43
44 chrome.storage.local.get(local_keys, function(settings) {
45 local_keys.forEach(function(key) {
46 if (key in settings)
47 options[key] = settings[key]
48 });
49
50 var storage = sync_storage(options['sync']);
51 storage.get(sync_keys, function(settings) {
52 sync_keys.forEach(function(key) {
53 if (key in settings)
54 options[key] = settings[key];
55 });
56
57 init_ui(local_keys, sync_keys, options);
58 mpc_connect();
59 });
60 });
61 };
62
63 window.onkeypress = function(e) {
64 switch (e.keyCode) {
65 case 49: // 1
66 show_page('controls');
67 break;
68 case 50: // 1
69 show_page('metadata');
70 break;
71 case 51: // 1
72 show_page('playlist');
73 break;
74 case 52: // 1
75 show_page('options');
76 break;
77 }
78 };
79
80 function mpc_refresh() {
81 mpc.status();
82 }
83
84 function mpc_connect(host, port) {
85 if (typeof(host) != 'string') {
86 host = window['opts_host'].value;
87 port = parseInt(window['opts_port'].value);
88 }
89
90 if (mpc != undefined) {
91 console.log('disconnecting');
92 update_ui('disconnect');
93 delete mpc;
94 tcpclient.disconnect();
95 delete tcpclient;
96 }
97
98 update_ui('init');
99 tcpclient = new TcpClient(host, port);
100 tcpclient.connect(function() {
101 var mpc_sender = new TcpClientSender(tcpclient);
102 tcpclient.addResponseListener(tramp_mpc_recv);
103 mpc = new Mpc(mpc_sender, update_ui);
104 console.log('connected to ' + host + ':' + port);
105 console.log('protip: use the "mpc" object to poke mpd directly.\n' +
106 'you can also do mpc.set_debug(3) to see traffic');
107 mpc_refresh();
108 update_refresh_timer();
109 });
110 }
111
112 function tramp_mpc_consume() {
113 var val = zo(!getToggleButton(this));
114 mpc.consume(val);
115 setToggleButton(this, val);
116 }
117 function tramp_mpc_deleteid() { mpc.deleteid(this.title); }
118 function tramp_mpc_next() { mpc.next(); }
119 function tramp_mpc_pause() { mpc.pause(); }
120 function tramp_mpc_play() { mpc.play(); }
121 function tramp_mpc_previous() { mpc.previous(); }
122 function tramp_mpc_random() {
123 var val = zo(!getToggleButton(this));
124 mpc.random(val);
125 setToggleButton(this, val);
126 }
127 function tramp_mpc_repeat() {
128 var val = zo(!getToggleButton(this));
129 mpc.repeat(val);
130 setToggleButton(this, val);
131 }
132 function tramp_mpc_seekcur() { mpc.seekcur(this.value); }
133 function tramp_mpc_setvol() { mpc.setvol(this.value); }
134 function tramp_mpc_single() {
135 var val = zo(!getToggleButton(this));
136 mpc.single(val);
137 setToggleButton(this, val);
138 }
139 function tramp_mpc_stop() { mpc.stop(); }
140
141 function zo(val) {
142 return val ? 1 : 0;
143 }
144 function szo(val) {
145 return val == '0' ? 0 : 1;
146 }
147 function getToggleButton(btn) {
148 return btn.style.borderStyle == 'inset';
149 }
150 function setToggleButton(btn, val) {
151 if (val === undefined)
152 val = !getToggleButton(btn);
153 btn.style.borderStyle = val ? 'inset' : '';
154 }
155
156 function show_page(page) {
157 if (typeof(page) != 'string')
158 page = this.id.split('.')[1];
159
160 // We might not be connected in which case 'mpc' will be undefined.
161 switch (page) {
162 case 'playlist':
163 if (mpc)
164 mpc.playlistinfo();
165 // Fallthrough.
166 case 'metadata':
167 if (mpc)
168 mpc.currentsong();
169 break;
170 }
171
172 var eles = document.getElementsByClassName('main');
173 for (var i = 0; i < eles.length; ++i) {
174 var ele = eles[i];
175 var dis = 'none';
176 var cls = '';
177 if (ele.id == 'main.' + page) {
178 dis = '';
179 cls = 'selected';
180 }
181 ele.style.display = dis;
182 document.getElementById('tab.' + ele.id.split('.')[1]).className = cls;
183 }
184 }
185
186 function do_refresh() {
187 mpc_refresh();
188 refresh_id = window.setTimeout(do_refresh, window['opts_refresh'].value * 1000);
189 }
190
191 function update_refresh_timer() {
192 if (!isNaN(refresh_id))
193 window.clearTimeout(refresh_id);
194 var rate = window['opts_refresh'].value * 1000;
195 if (rate > 0)
196 refresh_id = window.setTimeout(do_refresh, rate);
197 }
198
199 function update_local_settings() {
200 var setting = {};
201 setting[this.id] = this.checked;
202 chrome.storage.local.set(setting);
203 }
204
205 function update_sync_settings() {
206 var setting = {};
207 setting[this.id] = this.value;
208 var storage = sync_storage(window['opts_sync'].checked);
209 storage.set(setting);
210
211 switch (this.id) {
212 case 'refresh':
213 update_refresh_timer();
214 break;
215 }
216 }
217
218 function init_ui(local_keys, sync_keys, options) {
219 var ele, i;
220
221 /* Setup footer */
222 i = 1;
223 [
224 'controls', 'metadata', 'playlist', 'options',
225 ].forEach(function(id) {
226 var ele = document.getElementById('tab.' + id);
227 ele.onclick = show_page;
228 ele.title = id + ' [' + i + ']';
229 ++i;
230 });
231
232 /* Setup control tab */
233 ui_mpc_status = document.getElementById('status');
234 [
235 'consume', 'next', 'pause', 'play', 'previous', 'random', 'repeat',
236 'seekcur', 'setvol', 'single', 'stop',
237 ].forEach(function(id) {
238 var ele = window['ui_mpc_' + id] = document.getElementById(id);
239 ele.onchange = ele.onclick = window['tramp_mpc_' + id];
240 ele.title = id;
241 if (ele.accessKey)
242 ele.title += ' [' + ele.accessKey + ']'
243 });
244 window['ui_mpc_currtime'] = document.getElementById('currtime');
245
246 /* Setup metadata tab */
247 [
248 'album', 'artist', 'date', 'file', 'title',
249 ].forEach(function(id) {
250 window['ui_mpc_metadata_' + id] = document.getElementById('metadata.' + id);
251 });
252
253 /* Setup playlist tab */
254 window['ui_mpc_playlist'] = document.getElementById('playlist');
255
256 /* Setup options tab */
257 document.getElementById('connect').onclick = mpc_connect;
258 local_keys.forEach(function(id) {
259 var ele = window['opts_' + id] = document.getElementById(id);
260 ele.checked = options[id];
261 ele.onchange = update_local_settings;
262 });
263 sync_keys.forEach(function(id) {
264 var ele = window['opts_' + id] = document.getElementById(id);
265 ele.value = options[id];
266 ele.oninput = update_sync_settings;
267 });
268 }
269
270 function pretty_time(time) {
271 var sec, min, hrs, ret = '';
272 time = parseInt(time);
273 sec = time % 60;
274 min = parseInt((time / 60) % 60);
275 hrs = parseInt((time / 3600) % 3600);
276 if (hrs)
277 ret = hrs + ':' + ("00" + min).substr(-2) + ':';
278 else
279 ret = min + ':';
280 return ret + ("00" + sec).substr(-2);
281 }
282
283 function playlist_del() {
284 mpc.deleteid(this.song_id);
285 this.parentNode.remove();
286 }
287
288 function playlist_play() {
289 mpc.playid(this.song_id);
290 this.parentNode.style.fontWeight = 'bold';
291 }
292
293 function update_ui(state, cmd) {
294 if (typeof(state) == 'string') {
295 ui_mpc_status.innerText = ({
296 'disconnect': 'Disconnecting...',
297 'init': 'Connecting...',
298 })[state];
299 return;
300 }
301
302 if (Array.isArray(state)) {
303 /*
304 switch (cmd[0]) {
305 case 'setvol':
306 case 'seekcur':
307 break;
308 default:
309 mpc_refresh();
310 }
311 */
312 return;
313 }
314
315 /* Update the metadata tab only when things have changed. */
316 var currentsong;
317 if ('Currentsong' in state) {
318 currentsong = state.Currentsong;
319 if (ui_mpc_metadata_file.lastUpdate != state.Currentsong.lastUpdate) {
320 ui_mpc_metadata_album.innerText = currentsong.Album;
321 ui_mpc_metadata_artist.innerText = currentsong.Artist;
322 ui_mpc_metadata_title.innerText = currentsong.Title;
323 ui_mpc_metadata_date.innerText = currentsong.Date;
324 ui_mpc_metadata_file.innerText = currentsong.file;
325 }
326 }
327
328 /* Update the playlist tab only when things have changed. */
329 if ('Playlist' in state && ui_mpc_playlist.lastUpdate != state.Playlist.lastUpdate) {
330 var playlist = state.Playlist;
331
332 ui_mpc_playlist.innerHTML = '';
333 playlist.forEach(function(song) {
334 var cell, row = ui_mpc_playlist.insertRow(-1);
335 if (currentsong && song.Pos == currentsong.Pos)
336 row.style.fontWeight = 'bold';
337
338 cell = row.insertCell(-1);
339 cell.id = 'playlist_del';
340 cell.innerHTML = '&#164;';
341 cell.song_id = song.Id;
342 cell.title = 'delete';
343 cell.onclick = playlist_del;
344
345 cell = row.insertCell(-1);
346 cell.innerText = song.Pos;
347 cell.style.textAlign = 'right';
348 cell.song_id = song.Id;
349 cell.title = 'play';
350 cell.onclick = playlist_play;
351
352 if ('Artist' in song) {
353 row.insertCell(-1).innerText = song.Artist;
354 row.insertCell(-1).innerText = song.Album;
355 row.insertCell(-1).innerText = song.Title;
356 } else {
357 cell = row.insertCell(-1);
358 cell.innerText = song.file;
359 cell.colSpan = 3;
360 }
361 row.insertCell(-1).innerText = pretty_time(song.Time);
362 });
363
364 ui_mpc_playlist.lastUpdate = playlist.lastUpdate;
365 }
366
367 /* Update the status tab. */
368 var time, percent;
369 if ('time' in state) {
370 // When stopped, there is no time field at all.
371 time = state.time.split(':');
372 percent = Math.floor((0.0 + time[0]) * 100 / (0.0 + time[1]));
373 } else {
374 time = [0, 0];
375 percent = 0;
376 }
377 ui_mpc_seekcur.max = time[1];
378 ui_mpc_seekcur.value = time[0];
379 ui_mpc_seekcur.title = 'seekcur (' + percent + '%)';
380 ui_mpc_currtime.innerText = [pretty_time(time[0]), pretty_time(time[1]), percent + '%'].join(' / ');
381
382 ui_mpc_setvol.title = 'setvol';
383 if ('volume' in state) {
384 ui_mpc_setvol.value = state.volume;
385 ui_mpc_setvol.title += ' (' + state.volume + '%)';
386 }
387
388 [
389 'consume', 'random', 'repeat', 'single',
390 ].forEach(function(id) {
391 setToggleButton(window['ui_mpc_' + id], szo(state[id]));
392 });
393
394 ui_mpc_status.innerText = ({
395 'play': 'Playing',
396 'pause': 'Paused',
397 'stop': 'Stopped',
398 })[state.state];
399 }