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