mpd.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. /* ympd
  2. (c) 2013-2014 Andrew Karpow <andy@ndyk.de>
  3. This project's homepage is: https://www.ympd.org
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; version 2 of the License.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License along
  12. with this program; if not, write to the Free Software Foundation, Inc.,
  13. Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  14. */
  15. var socket;
  16. var last_state;
  17. var last_outputs;
  18. var current_app;
  19. var pagination = 0;
  20. var browsepath;
  21. var lastSongTitle = "";
  22. var current_song = new Object();
  23. var MAX_ELEMENTS_PER_PAGE = 512;
  24. var dirble_selected_cat = "";
  25. var dirble_catid = "";
  26. var dirble_page = 1;
  27. var isTouch = Modernizr.touch ? 1 : 0;
  28. var filter = undefined;
  29. var dirble_api_token = "";
  30. var dirble_stations = false;
  31. var app = $.sammy(function() {
  32. function runBrowse() {
  33. current_app = 'queue';
  34. $('#breadcrump').addClass('hide');
  35. $('#filter').addClass('hide');
  36. $('#salamisandwich').removeClass('hide').find("tr:gt(0)").remove();
  37. $('#dirble_panel').addClass('hide');
  38. socket.send('MPD_API_GET_QUEUE,'+pagination);
  39. $('#panel-heading').text("Queue");
  40. $('#queue').addClass('active');
  41. }
  42. function prepare() {
  43. $('#nav_links > li').removeClass('active');
  44. $('.page-btn').addClass('hide');
  45. $('#add-all-songs').hide();
  46. pagination = 0;
  47. browsepath = '';
  48. }
  49. this.get(/\#\/(\d+)/, function() {
  50. prepare();
  51. pagination = parseInt(this.params['splat'][0]);
  52. runBrowse();
  53. });
  54. this.get(/\#\/browse\/(\d+)\/(.*)/, function() {
  55. prepare();
  56. browsepath = this.params['splat'][1];
  57. pagination = parseInt(this.params['splat'][0]);
  58. current_app = 'browse';
  59. $('#breadcrump').removeClass('hide').empty().append("<li><a href=\"#/browse/0/\" onclick=\"set_filter()\">root</a></li>");
  60. $('#filter').removeClass('hide');
  61. $('#salamisandwich').removeClass('hide').find("tr:gt(0)").remove();
  62. $('#dirble_panel').addClass('hide');
  63. socket.send('MPD_API_GET_BROWSE,'+pagination+','+(browsepath ? browsepath : "/"));
  64. // Don't add all songs from root
  65. if (browsepath) {
  66. var add_all_songs = $('#add-all-songs');
  67. add_all_songs.off(); // remove previous binds
  68. add_all_songs.on('click', function() {
  69. socket.send('MPD_API_ADD_TRACK,'+browsepath);
  70. });
  71. add_all_songs.show();
  72. }
  73. $('#panel-heading').text("Browse database: "+browsepath);
  74. var path_array = browsepath.split('/');
  75. var full_path = "";
  76. $.each(path_array, function(index, chunk) {
  77. if(path_array.length - 1 == index) {
  78. $('#breadcrump').append("<li class=\"active\">"+ chunk + "</li>");
  79. return;
  80. }
  81. full_path = full_path + chunk;
  82. $('#breadcrump').append("<li><a href=\"#/browse/0/" + full_path + "\">"+chunk+"</a></li>");
  83. full_path += "/";
  84. });
  85. $('#browse').addClass('active');
  86. });
  87. this.get(/\#\/search\/(.*)/, function() {
  88. current_app = 'search';
  89. $('#salamisandwich').find("tr:gt(0)").remove();
  90. $('#dirble_panel').addClass('hide');
  91. var searchstr = this.params['splat'][0];
  92. $('#search > div > input').val(searchstr);
  93. socket.send('MPD_API_SEARCH,' + searchstr);
  94. $('#panel-heading').text("Search: "+searchstr);
  95. });
  96. this.get(/\#\/dirble\/(\d+)\/(\d+)/, function() {
  97. prepare();
  98. current_app = 'dirble';
  99. $('#breadcrump').removeClass('hide').empty().append("<li><a href=\"#/dirble/\">Categories</a></li><li>"+dirble_selected_cat+"</li>");
  100. $('#salamisandwich').addClass('hide');
  101. $('#dirble_panel').removeClass('hide');
  102. $('#dirble_loading').removeClass('hide');
  103. $('#dirble_left').find("tr:gt(0)").remove();
  104. $('#dirble_right').find("tr:gt(0)").remove();
  105. $('#panel-heading').text("Dirble");
  106. $('#dirble').addClass('active');
  107. $('#next').addClass('hide');
  108. if (this.params['splat'][1] > 1) $('#prev').removeClass('hide');
  109. else $('#prev').addClass('hide');
  110. dirble_catid = this.params['splat'][0];
  111. dirble_page = this.params['splat'][1];
  112. dirble_stations = true;
  113. if (dirble_api_token) { dirble_load_stations(); }
  114. });
  115. this.get(/\#\/dirble\//, function() {
  116. prepare();
  117. current_app = 'dirble';
  118. $('#breadcrump').removeClass('hide').empty().append("<li>Categories</li>");
  119. $('#salamisandwich').addClass('hide');
  120. $('#dirble_panel').removeClass('hide');
  121. $('#dirble_loading').removeClass('hide');
  122. $('#dirble_left').find("tr:gt(0)").remove();
  123. $('#dirble_right').find("tr:gt(0)").remove();
  124. $('#panel-heading').text("Dirble");
  125. $('#dirble').addClass('active');
  126. dirble_stations = false;
  127. if (dirble_api_token) { dirble_load_categories(); }
  128. });
  129. this.get("/", function(context) {
  130. context.redirect("#/0");
  131. });
  132. });
  133. $(document).ready(function(){
  134. webSocketConnect();
  135. $("#volumeslider").slider(0);
  136. $("#volumeslider").on('slider.newValue', function(evt,data){
  137. socket.send("MPD_API_SET_VOLUME,"+data.val);
  138. });
  139. $('#progressbar').slider(0);
  140. $("#progressbar").on('slider.newValue', function(evt,data){
  141. if(current_song && current_song.currentSongId >= 0) {
  142. var seekVal = Math.ceil(current_song.totalTime*(data.val/100));
  143. socket.send("MPD_API_SET_SEEK,"+current_song.currentSongId+","+seekVal);
  144. }
  145. });
  146. $('#addstream').on('shown.bs.modal', function () {
  147. $('#streamurl').focus();
  148. })
  149. $('#addstream form').on('submit', function (e) {
  150. addStream();
  151. });
  152. if(!notificationsSupported())
  153. $('#btnnotify').addClass("disabled");
  154. else
  155. if ($.cookie("notification") === "true")
  156. $('#btnnotify').addClass("active")
  157. add_filter();
  158. });
  159. function webSocketConnect() {
  160. if (typeof MozWebSocket != "undefined") {
  161. socket = new MozWebSocket(get_appropriate_ws_url());
  162. } else {
  163. socket = new WebSocket(get_appropriate_ws_url());
  164. }
  165. try {
  166. socket.onopen = function() {
  167. console.log("connected");
  168. $('.top-right').notify({
  169. message:{text:"Connected to ympd"},
  170. fadeOut: { enabled: true, delay: 500 }
  171. }).show();
  172. app.run();
  173. /* emit initial request for output names */
  174. socket.send('MPD_API_GET_OUTPUTS');
  175. /* emit initial request for dirble api token */
  176. socket.send('MPD_API_GET_DIRBLEAPITOKEN');
  177. }
  178. socket.onmessage = function got_packet(msg) {
  179. if(msg.data === last_state || msg.data.length == 0)
  180. return;
  181. var obj = JSON.parse(msg.data);
  182. switch (obj.type) {
  183. case 'queue':
  184. if(current_app !== 'queue')
  185. break;
  186. $('#salamisandwich > tbody').empty();
  187. for (var song in obj.data) {
  188. var minutes = Math.floor(obj.data[song].duration / 60);
  189. var seconds = obj.data[song].duration - minutes * 60;
  190. $('#salamisandwich > tbody').append(
  191. "<tr trackid=\"" + obj.data[song].id + "\"><td>" + (obj.data[song].pos + 1) + "</td>" +
  192. "<td>"+ obj.data[song].title +"</td>" +
  193. "<td>"+ minutes + ":" + (seconds < 10 ? '0' : '') + seconds +
  194. "</td><td></td></tr>");
  195. }
  196. if(obj.data.length && obj.data[obj.data.length-1].pos + 1 >= pagination + MAX_ELEMENTS_PER_PAGE)
  197. $('#next').removeClass('hide');
  198. if(pagination > 0)
  199. $('#prev').removeClass('hide');
  200. if ( isTouch ) {
  201. $('#salamisandwich > tbody > tr > td:last-child').append(
  202. "<a class=\"pull-right btn-group-hover\" href=\"#/\" " +
  203. "onclick=\"trash($(this).parents('tr'));\">" +
  204. "<span class=\"glyphicon glyphicon-trash\"></span></a>");
  205. } else {
  206. $('#salamisandwich > tbody > tr').on({
  207. mouseover: function(){
  208. var doomed = $(this);
  209. if ( $('#btntrashmodeup').hasClass('active') )
  210. doomed = $("#salamisandwich > tbody > tr:lt(" + ($(this).index() + 1) + ")");
  211. if ( $('#btntrashmodedown').hasClass('active') )
  212. doomed = $("#salamisandwich > tbody > tr:gt(" + ($(this).index() - 1) + ")");
  213. $.each(doomed, function(){
  214. if($(this).children().last().has("a").length == 0)
  215. $(this).children().last().append(
  216. "<a class=\"pull-right btn-group-hover\" href=\"#/\" " +
  217. "onclick=\"trash($(this).parents('tr'));\">" +
  218. "<span class=\"glyphicon glyphicon-trash\"></span></a>")
  219. .find('a').fadeTo('fast',1);
  220. });
  221. },
  222. mouseleave: function(){
  223. var doomed = $(this);
  224. if ( $('#btntrashmodeup').hasClass('active') )
  225. doomed = $("#salamisandwich > tbody > tr:lt(" + ($(this).index() + 1) + ")");
  226. if ( $('#btntrashmodedown').hasClass('active') )
  227. doomed = $("#salamisandwich > tbody > tr:gt(" + ($(this).index() - 1) + ")");
  228. $.each(doomed, function(){$(this).children().last().find("a").stop().remove();});
  229. }
  230. });
  231. };
  232. $('#salamisandwich > tbody > tr').on({
  233. click: function() {
  234. $('#salamisandwich > tbody > tr').removeClass('active');
  235. socket.send('MPD_API_PLAY_TRACK,'+$(this).attr('trackid'));
  236. $(this).addClass('active');
  237. },
  238. });
  239. //Helper function to keep table row from collapsing when being sorted
  240. var fixHelperModified = function(e, tr) {
  241. var $originals = tr.children();
  242. var $helper = tr.clone();
  243. $helper.children().each(function(index)
  244. {
  245. $(this).width($originals.eq(index).width())
  246. });
  247. return $helper;
  248. };
  249. //Make queue table sortable
  250. $("#salamisandwich > tbody").sortable({
  251. helper: fixHelperModified,
  252. stop: function(event,ui) {renumber_table('#salamisandwich',ui.item)}
  253. }).disableSelection();
  254. break;
  255. case 'search':
  256. $('#wait').modal('hide');
  257. case 'browse':
  258. if(current_app !== 'browse' && current_app !== 'search')
  259. break;
  260. /* The use of encodeURI() below might seem useless, but it's not. It prevents
  261. * some browsers, such as Safari, from changing the normalization form of the
  262. * URI from NFD to NFC, breaking our link with MPD.
  263. */
  264. if ($('#salamisandwich > tbody').is(':ui-sortable')) {
  265. $('#salamisandwich > tbody').sortable('destroy');
  266. }
  267. for (var item in obj.data) {
  268. switch(obj.data[item].type) {
  269. case 'directory':
  270. var clazz = 'dir';
  271. if (filter !== undefined) {
  272. var first = obj.data[item].dir[0];
  273. if (filter === "#" && isNaN(first)) {
  274. clazz += ' hide';
  275. } else if (filter >= "A" && filter <= "Z" && first.toUpperCase() !== filter) {
  276. clazz += ' hide';
  277. } else if (filter === "||") {
  278. clazz += ' hide';
  279. }
  280. }
  281. $('#salamisandwich > tbody').append(
  282. "<tr uri=\"" + encodeURI(obj.data[item].dir) + "\" class=\"" + clazz + "\">" +
  283. "<td><span class=\"glyphicon glyphicon-folder-open\"></span></td>" +
  284. "<td><a>" + basename(obj.data[item].dir) + "</a></td>" +
  285. "<td></td><td></td></tr>"
  286. );
  287. break;
  288. case 'playlist':
  289. var clazz = 'plist';
  290. if (filter !== "||") {
  291. clazz += ' hide';
  292. }
  293. $('#salamisandwich > tbody').append(
  294. "<tr uri=\"" + encodeURI(obj.data[item].plist) + "\" class=\"" + clazz + "\">" +
  295. "<td><span class=\"glyphicon glyphicon-list\"></span></td>" +
  296. "<td><a>" + basename(obj.data[item].plist) + "</a></td>" +
  297. "<td></td><td></td></tr>"
  298. );
  299. break;
  300. case 'song':
  301. var minutes = Math.floor(obj.data[item].duration / 60);
  302. var seconds = obj.data[item].duration - minutes * 60;
  303. $('#salamisandwich > tbody').append(
  304. "<tr uri=\"" + encodeURI(obj.data[item].uri) + "\" class=\"song\">" +
  305. "<td><span class=\"glyphicon glyphicon-music\"></span></td>" +
  306. "<td>" + obj.data[item].title +"</td>" +
  307. "<td>"+ minutes + ":" + (seconds < 10 ? '0' : '') + seconds +
  308. "</td><td></td></tr>"
  309. );
  310. break;
  311. case 'wrap':
  312. if(current_app == 'browse') {
  313. $('#next').removeClass('hide');
  314. } else {
  315. $('#salamisandwich > tbody').append(
  316. "<tr><td><span class=\"glyphicon glyphicon-remove\"></span></td>" +
  317. "<td>Too many results, please refine your search!</td>" +
  318. "<td></td><td></td></tr>"
  319. );
  320. }
  321. break;
  322. }
  323. if(pagination > 0)
  324. $('#prev').removeClass('hide');
  325. }
  326. function appendClickableIcon(appendTo, onClickAction, glyphicon) {
  327. $(appendTo).append(
  328. "<a role=\"button\" class=\"pull-right btn-group-hover\">" +
  329. "<span class=\"glyphicon glyphicon-" + glyphicon + "\"></span></a>")
  330. .find('a').click(function(e) {
  331. e.stopPropagation();
  332. socket.send(onClickAction + "," + decodeURI($(this).parents("tr").attr("uri")));
  333. $('.top-right').notify({
  334. message:{
  335. text: $('td:nth-child(2)', $(this).parents("tr")).text() + " added"
  336. } }).show();
  337. }).fadeTo('fast',1);
  338. }
  339. if ( isTouch ) {
  340. appendClickableIcon($("#salamisandwich > tbody > tr.dir > td:last-child"), 'MPD_API_ADD_TRACK', 'plus');
  341. appendClickableIcon($("#salamisandwich > tbody > tr.song > td:last-child"), 'MPD_API_ADD_TRACK', 'play');
  342. } else {
  343. $('#salamisandwich > tbody > tr').on({
  344. mouseenter: function() {
  345. if($(this).is(".dir"))
  346. appendClickableIcon($(this).children().last(), 'MPD_API_ADD_TRACK', 'plus');
  347. else if($(this).is(".song"))
  348. appendClickableIcon($(this).children().last(), 'MPD_API_ADD_PLAY_TRACK', 'play');
  349. },
  350. mouseleave: function(){
  351. $(this).children().last().find("a").stop().remove();
  352. }
  353. });
  354. };
  355. $('#salamisandwich > tbody > tr').on({
  356. click: function() {
  357. switch($(this).attr('class')) {
  358. case 'dir':
  359. pagination = 0;
  360. browsepath = $(this).attr("uri");
  361. $("#browse > a").attr("href", '#/browse/'+pagination+'/'+browsepath);
  362. app.setLocation('#/browse/'+pagination+'/'+browsepath);
  363. break;
  364. case 'song':
  365. socket.send("MPD_API_ADD_TRACK," + decodeURI($(this).attr("uri")));
  366. $('.top-right').notify({
  367. message:{
  368. text: $('td:nth-child(2)', this).text() + " added"
  369. }
  370. }).show();
  371. break;
  372. case 'plist':
  373. socket.send("MPD_API_ADD_PLAYLIST," + decodeURI($(this).attr("uri")));
  374. $('.top-right').notify({
  375. message:{
  376. text: "Playlist " + $('td:nth-child(2)', this).text() + " added"
  377. }
  378. }).show();
  379. break;
  380. }
  381. }
  382. });
  383. break;
  384. case 'state':
  385. updatePlayIcon(obj.data.state);
  386. updateVolumeIcon(obj.data.volume);
  387. if(JSON.stringify(obj) === JSON.stringify(last_state))
  388. break;
  389. current_song.totalTime = obj.data.totalTime;
  390. current_song.currentSongId = obj.data.currentsongid;
  391. var total_minutes = Math.floor(obj.data.totalTime / 60);
  392. var total_seconds = obj.data.totalTime - total_minutes * 60;
  393. var elapsed_minutes = Math.floor(obj.data.elapsedTime / 60);
  394. var elapsed_seconds = obj.data.elapsedTime - elapsed_minutes * 60;
  395. $('#volumeslider').slider(obj.data.volume);
  396. var progress = Math.floor(100*obj.data.elapsedTime/obj.data.totalTime);
  397. $('#progressbar').slider(progress);
  398. $('#counter')
  399. .text(elapsed_minutes + ":" +
  400. (elapsed_seconds < 10 ? '0' : '') + elapsed_seconds + " / " +
  401. total_minutes + ":" + (total_seconds < 10 ? '0' : '') + total_seconds);
  402. $('#salamisandwich > tbody > tr').removeClass('active').css("font-weight", "");
  403. $('#salamisandwich > tbody > tr[trackid='+obj.data.currentsongid+']').addClass('active').css("font-weight", "bold");
  404. if(obj.data.random)
  405. $('#btnrandom').addClass("active")
  406. else
  407. $('#btnrandom').removeClass("active");
  408. if(obj.data.consume)
  409. $('#btnconsume').addClass("active")
  410. else
  411. $('#btnconsume').removeClass("active");
  412. if(obj.data.single)
  413. $('#btnsingle').addClass("active")
  414. else
  415. $('#btnsingle').removeClass("active");
  416. if(obj.data.crossfade)
  417. $('#btncrossfade').addClass("active")
  418. else
  419. $('#btncrossfade').removeClass("active");
  420. if(obj.data.repeat)
  421. $('#btnrepeat').addClass("active")
  422. else
  423. $('#btnrepeat').removeClass("active");
  424. last_state = obj;
  425. break;
  426. case 'outputnames':
  427. $('#btn-outputs-block button').remove();
  428. if (obj.data.length > 1) {
  429. $.each(obj.data, function(id, name){
  430. var btn = $('<button id="btnoutput'+id+'" class="btn btn-default" onclick="toggleoutput(this, '+id+')"><span class="glyphicon glyphicon-volume-up"></span> '+name+'</button>');
  431. btn.appendTo($('#btn-outputs-block'));
  432. });
  433. } else {
  434. $('#btn-outputs-block').addClass('hide');
  435. }
  436. /* remove cache, since the buttons have been recreated */
  437. last_outputs = '';
  438. break;
  439. case 'outputs':
  440. if(JSON.stringify(obj) === JSON.stringify(last_outputs))
  441. break;
  442. $.each(obj.data, function(id, enabled){
  443. if (enabled)
  444. $('#btnoutput'+id).addClass("active");
  445. else
  446. $('#btnoutput'+id).removeClass("active");
  447. });
  448. last_outputs = obj;
  449. break;
  450. case 'disconnected':
  451. if($('.top-right').has('div').length == 0)
  452. $('.top-right').notify({
  453. message:{text:"ympd lost connection to MPD "},
  454. type: "danger",
  455. fadeOut: { enabled: true, delay: 1000 },
  456. }).show();
  457. break;
  458. case 'update_queue':
  459. if(current_app === 'queue')
  460. socket.send('MPD_API_GET_QUEUE,'+pagination);
  461. break;
  462. case 'song_change':
  463. $('#album').text("");
  464. $('#artist').text("");
  465. $('#btnlove').removeClass("active");
  466. $('#currenttrack').text(" " + obj.data.title);
  467. var notification = "<strong><h4>" + obj.data.title + "</h4></strong>";
  468. if(obj.data.album) {
  469. $('#album').text(obj.data.album);
  470. notification += obj.data.album + "<br />";
  471. }
  472. if(obj.data.artist) {
  473. $('#artist').text(obj.data.artist);
  474. notification += obj.data.artist + "<br />";
  475. }
  476. if ($.cookie("notification") === "true")
  477. songNotify(obj.data.title, obj.data.artist, obj.data.album );
  478. else
  479. $('.top-right').notify({
  480. message:{html: notification},
  481. type: "info",
  482. }).show();
  483. break;
  484. case 'mpdhost':
  485. $('#mpdhost').val(obj.data.host);
  486. $('#mpdport').val(obj.data.port);
  487. if(obj.data.passwort_set)
  488. $('#mpd_password_set').removeClass('hide');
  489. break;
  490. case 'dirbleapitoken':
  491. dirble_api_token = obj.data;
  492. if (dirble_api_token) {
  493. $('#dirble').removeClass('hide');
  494. if (dirble_stations) { dirble_load_stations(); }
  495. else { dirble_load_categories(); }
  496. } else {
  497. $('#dirble').addClass('hide');
  498. }
  499. break;
  500. case 'error':
  501. $('.top-right').notify({
  502. message:{text: obj.data},
  503. type: "danger",
  504. }).show();
  505. default:
  506. break;
  507. }
  508. }
  509. socket.onclose = function(){
  510. console.log("disconnected");
  511. $('.top-right').notify({
  512. message:{text:"Connection to ympd lost, retrying in 3 seconds "},
  513. type: "danger",
  514. onClose: function () {
  515. webSocketConnect();
  516. }
  517. }).show();
  518. }
  519. } catch(exception) {
  520. alert('<p>Error' + exception);
  521. }
  522. }
  523. function get_appropriate_ws_url()
  524. {
  525. var pcol;
  526. var u = document.URL;
  527. var separator;
  528. /*
  529. /* We open the websocket encrypted if this page came on an
  530. /* https:// url itself, otherwise unencrypted
  531. /*/
  532. if (u.substring(0, 5) == "https") {
  533. pcol = "wss://";
  534. u = u.substr(8);
  535. } else {
  536. pcol = "ws://";
  537. if (u.substring(0, 4) == "http")
  538. u = u.substr(7);
  539. }
  540. u = u.split('#');
  541. if (/\/$/.test(u[0])) {
  542. separator = "";
  543. } else {
  544. separator = "/";
  545. }
  546. return pcol + u[0] + separator + "ws";
  547. }
  548. var updateVolumeIcon = function(volume)
  549. {
  550. $("#volume-icon").removeClass("glyphicon-volume-off");
  551. $("#volume-icon").removeClass("glyphicon-volume-up");
  552. $("#volume-icon").removeClass("glyphicon-volume-down");
  553. if(volume == 0) {
  554. $("#volume-icon").addClass("glyphicon-volume-off");
  555. } else if (volume < 50) {
  556. $("#volume-icon").addClass("glyphicon-volume-down");
  557. } else {
  558. $("#volume-icon").addClass("glyphicon-volume-up");
  559. }
  560. }
  561. var updatePlayIcon = function(state)
  562. {
  563. $("#play-icon").removeClass("glyphicon-play")
  564. .removeClass("glyphicon-pause");
  565. $('#track-icon').removeClass("glyphicon-play")
  566. .removeClass("glyphicon-pause")
  567. .removeClass("glyphicon-stop");
  568. if(state == 1) { // stop
  569. $("#play-icon").addClass("glyphicon-play");
  570. $('#track-icon').addClass("glyphicon-stop");
  571. } else if(state == 2) { // pause
  572. $("#play-icon").addClass("glyphicon-pause");
  573. $('#track-icon').addClass("glyphicon-play");
  574. } else { // play
  575. $("#play-icon").addClass("glyphicon-play");
  576. $('#track-icon').addClass("glyphicon-pause");
  577. }
  578. }
  579. function updateDB() {
  580. socket.send('MPD_API_UPDATE_DB');
  581. $('.top-right').notify({
  582. message:{text:"Updating MPD Database... "}
  583. }).show();
  584. }
  585. function clickPlay() {
  586. if($('#track-icon').hasClass('glyphicon-stop'))
  587. socket.send('MPD_API_SET_PLAY');
  588. else
  589. socket.send('MPD_API_SET_PAUSE');
  590. }
  591. function trash(tr) {
  592. if ( $('#btntrashmodeup').hasClass('active') ) {
  593. socket.send('MPD_API_RM_RANGE,0,' + (tr.index() + 1));
  594. tr.remove();
  595. } else if ( $('#btntrashmodesingle').hasClass('active') ) {
  596. socket.send('MPD_API_RM_TRACK,' + tr.attr('trackid'));
  597. tr.remove();
  598. } else if ( $('#btntrashmodedown').hasClass('active') ) {
  599. socket.send('MPD_API_RM_RANGE,' + tr.index() + ',-1');
  600. tr.remove();
  601. };
  602. }
  603. function renumber_table(tableID,item) {
  604. was = item.children("td").first().text();//Check if first item exists!
  605. is = item.index() + 1;//maybe add pagination
  606. if (was != is) {
  607. socket.send("MPD_API_MOVE_TRACK," + was + "," + is);
  608. socket.send('MPD_API_GET_QUEUE,'+pagination);
  609. }
  610. }
  611. function basename(path) {
  612. return path.split('/').reverse()[0];
  613. }
  614. function clickLove() {
  615. socket.send("MPD_API_SEND_MESSAGE,mpdas," + ($('#btnlove').hasClass('active') ? "unlove" : "love"));
  616. if ( $('#btnlove').hasClass('active') )
  617. $('#btnlove').removeClass("active");
  618. else
  619. $('#btnlove').addClass("active");
  620. }
  621. $('#btnrandom').on('click', function (e) {
  622. socket.send("MPD_API_TOGGLE_RANDOM," + ($(this).hasClass('active') ? 0 : 1));
  623. });
  624. $('#btnconsume').on('click', function (e) {
  625. socket.send("MPD_API_TOGGLE_CONSUME," + ($(this).hasClass('active') ? 0 : 1));
  626. });
  627. $('#btnsingle').on('click', function (e) {
  628. socket.send("MPD_API_TOGGLE_SINGLE," + ($(this).hasClass('active') ? 0 : 1));
  629. });
  630. $('#btncrossfade').on('click', function(e) {
  631. socket.send("MPD_API_TOGGLE_CROSSFADE," + ($(this).hasClass('active') ? 0 : 1));
  632. });
  633. $('#btnrepeat').on('click', function (e) {
  634. socket.send("MPD_API_TOGGLE_REPEAT," + ($(this).hasClass('active') ? 0 : 1));
  635. });
  636. function toggleoutput(button, id) {
  637. socket.send("MPD_API_TOGGLE_OUTPUT,"+id+"," + ($(button).hasClass('active') ? 0 : 1));
  638. }
  639. $('#trashmode').children("button").on('click', function(e) {
  640. $('#trashmode').children("button").removeClass("active");
  641. $(this).addClass("active");
  642. });
  643. $('#btnnotify').on('click', function (e) {
  644. if($.cookie("notification") === "true") {
  645. $.cookie("notification", false);
  646. } else {
  647. Notification.requestPermission(function (permission) {
  648. if(!('permission' in Notification)) {
  649. Notification.permission = permission;
  650. }
  651. if (permission === "granted") {
  652. $.cookie("notification", true, { expires: 424242 });
  653. $('btnnotify').addClass("active");
  654. }
  655. });
  656. }
  657. });
  658. function getHost() {
  659. socket.send('MPD_API_GET_MPDHOST');
  660. function onEnter(event) {
  661. if ( event.which == 13 ) {
  662. confirmSettings();
  663. }
  664. }
  665. $('#mpdhost').keypress(onEnter);
  666. $('#mpdport').keypress(onEnter);
  667. $('#mpd_pw').keypress(onEnter);
  668. $('#mpd_pw_con').keypress(onEnter);
  669. }
  670. $('#search').submit(function () {
  671. app.setLocation("#/search/"+$('#search > div > input').val());
  672. $('#wait').modal('show');
  673. setTimeout(function() {
  674. $('#wait').modal('hide');
  675. }, 10000);
  676. return false;
  677. });
  678. $('.page-btn').on('click', function (e) {
  679. switch ($(this).text()) {
  680. case "Next":
  681. if (current_app == "dirble") dirble_page++;
  682. else pagination += MAX_ELEMENTS_PER_PAGE;
  683. break;
  684. case "Previous":
  685. if (current_app == "dirble") dirble_page--
  686. else {
  687. pagination -= MAX_ELEMENTS_PER_PAGE;
  688. if(pagination <= 0)
  689. pagination = 0;
  690. }
  691. break;
  692. }
  693. switch(current_app) {
  694. case "queue":
  695. app.setLocation('#/'+pagination);
  696. break;
  697. case "browse":
  698. app.setLocation('#/browse/'+pagination+'/'+browsepath);
  699. break;
  700. case "dirble":
  701. app.setLocation("#/dirble/"+dirble_catid+"/"+dirble_page);
  702. break;
  703. }
  704. e.preventDefault();
  705. });
  706. function addStream() {
  707. if($('#streamurl').val().length > 0) {
  708. socket.send('MPD_API_ADD_TRACK,'+$('#streamurl').val());
  709. }
  710. $('#streamurl').val("");
  711. $('#addstream').modal('hide');
  712. }
  713. function saveQueue() {
  714. if($('#playlistname').val().length > 0) {
  715. socket.send('MPD_API_SAVE_QUEUE,'+$('#playlistname').val());
  716. }
  717. $('#savequeue').modal('hide');
  718. }
  719. function confirmSettings() {
  720. if($('#mpd_pw').val().length + $('#mpd_pw_con').val().length > 0) {
  721. if ($('#mpd_pw').val() !== $('#mpd_pw_con').val())
  722. {
  723. $('#mpd_pw_con').popover('show');
  724. setTimeout(function() {
  725. $('#mpd_pw_con').popover('hide');
  726. }, 2000);
  727. return;
  728. } else
  729. socket.send('MPD_API_SET_MPDPASS,'+$('#mpd_pw').val());
  730. }
  731. socket.send('MPD_API_SET_MPDHOST,'+$('#mpdport').val()+','+$('#mpdhost').val());
  732. $('#settings').modal('hide');
  733. }
  734. $('#mpd_password_set > button').on('click', function (e) {
  735. socket.send('MPD_API_SET_MPDPASS,');
  736. $('#mpd_pw').val("");
  737. $('#mpd_pw_con').val("");
  738. $('#mpd_password_set').addClass('hide');
  739. })
  740. function notificationsSupported() {
  741. return "Notification" in window;
  742. }
  743. function songNotify(title, artist, album) {
  744. /*var opt = {
  745. type: "list",
  746. title: title,
  747. message: title,
  748. items: []
  749. }
  750. if(artist.length > 0)
  751. opt.items.push({title: "Artist", message: artist});
  752. if(album.length > 0)
  753. opt.items.push({title: "Album", message: album});
  754. */
  755. //chrome.notifications.create(id, options, creationCallback);
  756. var textNotification = "";
  757. if(typeof artist != 'undefined' && artist.length > 0)
  758. textNotification += " " + artist;
  759. if(typeof album != 'undefined' && album.length > 0)
  760. textNotification += "\n " + album;
  761. var notification = new Notification(title, {icon: 'assets/favicon.ico', body: textNotification});
  762. setTimeout(function(notification) {
  763. notification.close();
  764. }, 3000, notification);
  765. }
  766. $(document).keydown(function(e){
  767. if (e.target.tagName == 'INPUT') {
  768. return;
  769. }
  770. switch (e.which) {
  771. case 37: //left
  772. socket.send('MPD_API_SET_PREV');
  773. break;
  774. case 39: //right
  775. socket.send('MPD_API_SET_NEXT');
  776. break;
  777. case 32: //space
  778. clickPlay();
  779. break;
  780. default:
  781. return;
  782. }
  783. e.preventDefault();
  784. });
  785. function dirble_load_categories() {
  786. dirble_page = 1;
  787. $.getJSON( "https://api.dirble.com/v2/categories?token=" + dirble_api_token, function( data ) {
  788. $('#dirble_loading').addClass('hide');
  789. data = data.sort(function(a, b) {
  790. return (a.title > b.title) ? 1 : 0;
  791. });
  792. var max = data.length - data.length%2;
  793. for(i = 0; i < max; i+=2) {
  794. $('#dirble_left > tbody').append(
  795. "<tr><td catid=\""+data[i].id+"\">"+data[i].title+"</td></tr>"
  796. );
  797. $('#dirble_right > tbody').append(
  798. "<tr><td catid=\""+data[i+1].id+"\">"+data[i+1].title+"</td></tr>"
  799. );
  800. }
  801. if (max != data.length) {
  802. $('#dirble_left > tbody').append(
  803. "<tr><td catid=\""+data[max].id+"\">"+data[max].title+"</td></tr>"
  804. );
  805. }
  806. $('#dirble_left > tbody > tr > td').on({
  807. click: function() {
  808. dirble_selected_cat = $(this).text();
  809. dirble_catid = $(this).attr("catid");
  810. app.setLocation("#/dirble/"+dirble_catid+"/"+dirble_page);
  811. }
  812. });
  813. $('#dirble_right > tbody > tr > td').on({
  814. click: function() {
  815. dirble_selected_cat = $(this).text();
  816. dirble_catid = $(this).attr("catid");
  817. app.setLocation("#/dirble/"+dirble_catid+"/"+dirble_page);
  818. }
  819. });
  820. });
  821. }
  822. function dirble_load_stations() {
  823. $.getJSON( "https://api.dirble.com/v2/category/"+dirble_catid+"/stations?page="+dirble_page+"&per_page=20&token=" + dirble_api_token, function( data ) {
  824. $('#dirble_loading').addClass('hide');
  825. if (data.length == 20) $('#next').removeClass('hide');
  826. var max = data.length - data.length%2;
  827. for(i = 0; i < max; i+=2) {
  828. $('#dirble_left > tbody').append(
  829. "<tr><td radioid=\""+data[i].id+"\">"+data[i].name+"</td></tr>"
  830. );
  831. $('#dirble_right > tbody').append(
  832. "<tr><td radioid=\""+data[i+1].id+"\">"+data[i+1].name+"</td></tr>"
  833. );
  834. }
  835. if (max != data.length) {
  836. $('#dirble_left > tbody').append(
  837. "<tr><td radioid=\""+data[max].id+"\">"+data[max].name+"</td></tr>"
  838. );
  839. }
  840. $('#dirble_left > tbody > tr > td').on({
  841. click: function() {
  842. var _this = $(this);
  843. $.getJSON( "https://api.dirble.com/v2/station/"+$(this).attr("radioid")+"?token=" + dirble_api_token, function( data ) {
  844. socket.send("MPD_API_ADD_TRACK," + data.streams[0].stream);
  845. $('.top-right').notify({
  846. message:{
  847. text: _this.text() + " added"
  848. }
  849. }).show();
  850. });
  851. },
  852. mouseenter: function() {
  853. var _this = $(this);
  854. $(this).last().append(
  855. "<a role=\"button\" class=\"pull-right btn-group-hover\">" +
  856. "<span class=\"glyphicon glyphicon-play\"></span></a>").find('a').click(function(e) {
  857. e.stopPropagation();
  858. $.getJSON( "https://api.dirble.com/v2/station/"+_this.attr("radioid")+"?token=" + dirble_api_token, function( data ) {
  859. socket.send("MPD_API_ADD_PLAY_TRACK," + data.streams[0].stream);
  860. $('.top-right').notify({
  861. message:{
  862. text: _this.text() + " added"
  863. }
  864. }).show();
  865. });
  866. }).fadeTo('fast',1);
  867. },
  868. mouseleave: function(){
  869. $(this).last().find("a").stop().remove();
  870. }
  871. });
  872. $('#dirble_right> tbody > tr > td').on({
  873. click: function() {
  874. var _this = $(this);
  875. $.getJSON( "https://api.dirble.com/v2/station/"+$(this).attr("radioid")+"?token=" + dirble_api_token, function( data ) {
  876. socket.send("MPD_API_ADD_TRACK," + data.streams[0].stream);
  877. $('.top-right').notify({
  878. message:{
  879. text: _this.text() + " added"
  880. }
  881. }).show();
  882. });
  883. },
  884. mouseenter: function() {
  885. var _this = $(this);
  886. $(this).last().append(
  887. "<a role=\"button\" class=\"pull-right btn-group-hover\">" +
  888. "<span class=\"glyphicon glyphicon-play\"></span></a>").find('a').click(function(e) {
  889. e.stopPropagation();
  890. $.getJSON( "https://api.dirble.com/v2/station/"+_this.attr("radioid")+"?token=" + dirble_api_token, function( data ) {
  891. socket.send("MPD_API_ADD_PLAY_TRACK," + data.streams[0].stream);
  892. $('.top-right').notify({
  893. message:{
  894. text: _this.text() + " added"
  895. }
  896. }).show();
  897. });
  898. }).fadeTo('fast',1);
  899. },
  900. mouseleave: function(){
  901. $(this).last().find("a").stop().remove();
  902. }
  903. });
  904. });
  905. }
  906. function set_filter (c) {
  907. filter = c;
  908. $.each($('#salamisandwich > tbody > tr.dir'), function(i, line) {
  909. var first = $(line).attr('uri')[0];
  910. if (filter === undefined) {
  911. $(line).removeClass('hide');
  912. }
  913. else if (filter === "#") {
  914. if (!isNaN(first)) {
  915. $(line).removeClass('hide');
  916. } else {
  917. $(line).addClass('hide');
  918. }
  919. }
  920. else if (filter >= "A" && filter <= "Z") {
  921. if (first.toUpperCase() === filter) {
  922. $(line).removeClass('hide');
  923. } else {
  924. $(line).addClass('hide');
  925. }
  926. }
  927. else if (filter === "||") {
  928. $(line).addClass('hide');
  929. }
  930. });
  931. $.each($('#salamisandwich > tbody > tr.plist'), function(i, line) {
  932. if (filter === undefined) {
  933. $(line).removeClass('hide');
  934. } else if (filter === "||") {
  935. $(line).removeClass('hide');
  936. } else {
  937. $(line).addClass('hide');
  938. }
  939. });
  940. }
  941. function add_filter () {
  942. $('#filter').append('&nbsp;<a onclick="set_filter(\'#\')" href="#/browse/0/">#</a>');
  943. for (i = 65; i <= 90; i++) {
  944. var c = String.fromCharCode(i);
  945. $('#filter').append('&nbsp;<a onclick="set_filter(\'' + c + '\')" href="#/browse/0/">' + c + '</a>');
  946. }
  947. $('#filter').append('&nbsp;<a onclick="set_filter(\'||\')" href="#/browse/0/" class="glyphicon glyphicon-list"></a>');
  948. }