mpd.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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) {
  114. dirble_load_stations();
  115. } else {
  116. getDirbleApiToken();
  117. }
  118. });
  119. this.get(/\#\/dirble\//, function() {
  120. prepare();
  121. current_app = 'dirble';
  122. $('#breadcrump').removeClass('hide').empty().append("<li>Categories</li>");
  123. $('#salamisandwich').addClass('hide');
  124. $('#dirble_panel').removeClass('hide');
  125. $('#dirble_loading').removeClass('hide');
  126. $('#dirble_left').find("tr:gt(0)").remove();
  127. $('#dirble_right').find("tr:gt(0)").remove();
  128. $('#panel-heading').text("Dirble");
  129. $('#dirble').addClass('active');
  130. dirble_stations = false;
  131. if(dirble_api_token) {
  132. dirble_load_categories();
  133. } else {
  134. getDirbleApiToken();
  135. }
  136. });
  137. this.get("/", function(context) {
  138. context.redirect("#/0");
  139. });
  140. });
  141. $(document).ready(function(){
  142. webSocketConnect();
  143. $("#volumeslider").slider(0);
  144. $("#volumeslider").on('slider.newValue', function(evt,data){
  145. socket.send("MPD_API_SET_VOLUME,"+data.val);
  146. });
  147. $('#progressbar').slider(0);
  148. $("#progressbar").on('slider.newValue', function(evt,data){
  149. if(current_song && current_song.currentSongId >= 0) {
  150. var seekVal = Math.ceil(current_song.totalTime*(data.val/100));
  151. socket.send("MPD_API_SET_SEEK,"+current_song.currentSongId+","+seekVal);
  152. }
  153. });
  154. $('#addstream').on('shown.bs.modal', function () {
  155. $('#streamurl').focus();
  156. })
  157. $('#addstream form').on('submit', function (e) {
  158. addStream();
  159. });
  160. if(!notificationsSupported())
  161. $('#btnnotify').addClass("disabled");
  162. else
  163. if ($.cookie("notification") === "true")
  164. $('#btnnotify').addClass("active")
  165. add_filter();
  166. });
  167. function webSocketConnect() {
  168. if (typeof MozWebSocket != "undefined") {
  169. socket = new MozWebSocket(get_appropriate_ws_url());
  170. } else {
  171. socket = new WebSocket(get_appropriate_ws_url());
  172. }
  173. try {
  174. socket.onopen = function() {
  175. console.log("connected");
  176. $('.top-right').notify({
  177. message:{text:"Connected to ympd"},
  178. fadeOut: { enabled: true, delay: 500 }
  179. }).show();
  180. app.run();
  181. /* emit initial request for output names */
  182. socket.send("MPD_API_GET_OUTPUTS");
  183. }
  184. socket.onmessage = function got_packet(msg) {
  185. if(msg.data === last_state || msg.data.length == 0)
  186. return;
  187. var obj = JSON.parse(msg.data);
  188. switch (obj.type) {
  189. case "queue":
  190. if(current_app !== 'queue')
  191. break;
  192. $('#salamisandwich > tbody').empty();
  193. for (var song in obj.data) {
  194. var minutes = Math.floor(obj.data[song].duration / 60);
  195. var seconds = obj.data[song].duration - minutes * 60;
  196. $('#salamisandwich > tbody').append(
  197. "<tr trackid=\"" + obj.data[song].id + "\"><td>" + (obj.data[song].pos + 1) + "</td>" +
  198. "<td>"+ obj.data[song].title +"</td>" +
  199. "<td>"+ minutes + ":" + (seconds < 10 ? '0' : '') + seconds +
  200. "</td><td></td></tr>");
  201. }
  202. if(obj.data.length && obj.data[obj.data.length-1].pos + 1 >= pagination + MAX_ELEMENTS_PER_PAGE)
  203. $('#next').removeClass('hide');
  204. if(pagination > 0)
  205. $('#prev').removeClass('hide');
  206. if ( isTouch ) {
  207. $('#salamisandwich > tbody > tr > td:last-child').append(
  208. "<a class=\"pull-right btn-group-hover\" href=\"#/\" " +
  209. "onclick=\"trash($(this).parents('tr'));\">" +
  210. "<span class=\"glyphicon glyphicon-trash\"></span></a>");
  211. } else {
  212. $('#salamisandwich > tbody > tr').on({
  213. mouseover: function(){
  214. var doomed = $(this);
  215. if ( $('#btntrashmodeup').hasClass('active') )
  216. doomed = $("#salamisandwich > tbody > tr:lt(" + ($(this).index() + 1) + ")");
  217. if ( $('#btntrashmodedown').hasClass('active') )
  218. doomed = $("#salamisandwich > tbody > tr:gt(" + ($(this).index() - 1) + ")");
  219. $.each(doomed, function(){
  220. if($(this).children().last().has("a").length == 0)
  221. $(this).children().last().append(
  222. "<a class=\"pull-right btn-group-hover\" href=\"#/\" " +
  223. "onclick=\"trash($(this).parents('tr'));\">" +
  224. "<span class=\"glyphicon glyphicon-trash\"></span></a>")
  225. .find('a').fadeTo('fast',1);
  226. });
  227. },
  228. mouseleave: function(){
  229. var doomed = $(this);
  230. if ( $('#btntrashmodeup').hasClass('active') )
  231. doomed = $("#salamisandwich > tbody > tr:lt(" + ($(this).index() + 1) + ")");
  232. if ( $('#btntrashmodedown').hasClass('active') )
  233. doomed = $("#salamisandwich > tbody > tr:gt(" + ($(this).index() - 1) + ")");
  234. $.each(doomed, function(){$(this).children().last().find("a").stop().remove();});
  235. }
  236. });
  237. };
  238. $('#salamisandwich > tbody > tr').on({
  239. click: function() {
  240. $('#salamisandwich > tbody > tr').removeClass('active');
  241. socket.send('MPD_API_PLAY_TRACK,'+$(this).attr('trackid'));
  242. $(this).addClass('active');
  243. },
  244. });
  245. //Helper function to keep table row from collapsing when being sorted
  246. var fixHelperModified = function(e, tr) {
  247. var $originals = tr.children();
  248. var $helper = tr.clone();
  249. $helper.children().each(function(index)
  250. {
  251. $(this).width($originals.eq(index).width())
  252. });
  253. return $helper;
  254. };
  255. //Make queue table sortable
  256. $("#salamisandwich > tbody").sortable({
  257. helper: fixHelperModified,
  258. stop: function(event,ui) {renumber_table('#salamisandwich',ui.item)}
  259. }).disableSelection();
  260. break;
  261. case "search":
  262. $('#wait').modal('hide');
  263. case "browse":
  264. if(current_app !== 'browse' && current_app !== 'search')
  265. break;
  266. /* The use of encodeURI() below might seem useless, but it's not. It prevents
  267. * some browsers, such as Safari, from changing the normalization form of the
  268. * URI from NFD to NFC, breaking our link with MPD.
  269. */
  270. if ($('#salamisandwich > tbody').is(':ui-sortable')) {
  271. $('#salamisandwich > tbody').sortable('destroy');
  272. }
  273. for (var item in obj.data) {
  274. switch(obj.data[item].type) {
  275. case "directory":
  276. var clazz = 'dir';
  277. if (filter !== undefined) {
  278. var first = obj.data[item].dir[0];
  279. if (filter === "#" && isNaN(first)) {
  280. clazz += ' hide';
  281. } else if (filter >= "A" && filter <= "Z" && first.toUpperCase() !== filter) {
  282. clazz += ' hide';
  283. } else if (filter === "||") {
  284. clazz += ' hide';
  285. }
  286. }
  287. $('#salamisandwich > tbody').append(
  288. "<tr uri=\"" + encodeURI(obj.data[item].dir) + "\" class=\"" + clazz + "\">" +
  289. "<td><span class=\"glyphicon glyphicon-folder-open\"></span></td>" +
  290. "<td><a>" + basename(obj.data[item].dir) + "</a></td>" +
  291. "<td></td><td></td></tr>"
  292. );
  293. break;
  294. case "playlist":
  295. var clazz = 'plist';
  296. if (filter !== "||") {
  297. clazz += ' hide';
  298. }
  299. $('#salamisandwich > tbody').append(
  300. "<tr uri=\"" + encodeURI(obj.data[item].plist) + "\" class=\"" + clazz + "\">" +
  301. "<td><span class=\"glyphicon glyphicon-list\"></span></td>" +
  302. "<td><a>" + basename(obj.data[item].plist) + "</a></td>" +
  303. "<td></td><td></td></tr>"
  304. );
  305. break;
  306. case "song":
  307. var minutes = Math.floor(obj.data[item].duration / 60);
  308. var seconds = obj.data[item].duration - minutes * 60;
  309. $('#salamisandwich > tbody').append(
  310. "<tr uri=\"" + encodeURI(obj.data[item].uri) + "\" class=\"song\">" +
  311. "<td><span class=\"glyphicon glyphicon-music\"></span></td>" +
  312. "<td>" + obj.data[item].title +"</td>" +
  313. "<td>"+ minutes + ":" + (seconds < 10 ? '0' : '') + seconds +
  314. "</td><td></td></tr>"
  315. );
  316. break;
  317. case "wrap":
  318. if(current_app == 'browse') {
  319. $('#next').removeClass('hide');
  320. } else {
  321. $('#salamisandwich > tbody').append(
  322. "<tr><td><span class=\"glyphicon glyphicon-remove\"></span></td>" +
  323. "<td>Too many results, please refine your search!</td>" +
  324. "<td></td><td></td></tr>"
  325. );
  326. }
  327. break;
  328. }
  329. if(pagination > 0)
  330. $('#prev').removeClass('hide');
  331. }
  332. function appendClickableIcon(appendTo, onClickAction, glyphicon) {
  333. $(appendTo).append(
  334. "<a role=\"button\" class=\"pull-right btn-group-hover\">" +
  335. "<span class=\"glyphicon glyphicon-" + glyphicon + "\"></span></a>")
  336. .find('a').click(function(e) {
  337. e.stopPropagation();
  338. socket.send(onClickAction + "," + decodeURI($(this).parents("tr").attr("uri")));
  339. $('.top-right').notify({
  340. message:{
  341. text: $('td:nth-child(2)', $(this).parents("tr")).text() + " added"
  342. } }).show();
  343. }).fadeTo('fast',1);
  344. }
  345. if ( isTouch ) {
  346. appendClickableIcon($("#salamisandwich > tbody > tr.dir > td:last-child"), 'MPD_API_ADD_TRACK', 'plus');
  347. appendClickableIcon($("#salamisandwich > tbody > tr.song > td:last-child"), 'MPD_API_ADD_TRACK', 'play');
  348. } else {
  349. $('#salamisandwich > tbody > tr').on({
  350. mouseenter: function() {
  351. if($(this).is(".dir"))
  352. appendClickableIcon($(this).children().last(), 'MPD_API_ADD_TRACK', 'plus');
  353. else if($(this).is(".song"))
  354. appendClickableIcon($(this).children().last(), 'MPD_API_ADD_PLAY_TRACK', 'play');
  355. },
  356. mouseleave: function(){
  357. $(this).children().last().find("a").stop().remove();
  358. }
  359. });
  360. };
  361. $('#salamisandwich > tbody > tr').on({
  362. click: function() {
  363. switch($(this).attr('class')) {
  364. case 'dir':
  365. pagination = 0;
  366. browsepath = $(this).attr("uri");
  367. $("#browse > a").attr("href", '#/browse/'+pagination+'/'+browsepath);
  368. app.setLocation('#/browse/'+pagination+'/'+browsepath);
  369. break;
  370. case 'song':
  371. socket.send("MPD_API_ADD_TRACK," + decodeURI($(this).attr("uri")));
  372. $('.top-right').notify({
  373. message:{
  374. text: $('td:nth-child(2)', this).text() + " added"
  375. }
  376. }).show();
  377. break;
  378. case 'plist':
  379. socket.send("MPD_API_ADD_PLAYLIST," + decodeURI($(this).attr("uri")));
  380. $('.top-right').notify({
  381. message:{
  382. text: "Playlist " + $('td:nth-child(2)', this).text() + " added"
  383. }
  384. }).show();
  385. break;
  386. }
  387. }
  388. });
  389. break;
  390. case "state":
  391. updatePlayIcon(obj.data.state);
  392. updateVolumeIcon(obj.data.volume);
  393. if(JSON.stringify(obj) === JSON.stringify(last_state))
  394. break;
  395. current_song.totalTime = obj.data.totalTime;
  396. current_song.currentSongId = obj.data.currentsongid;
  397. var total_minutes = Math.floor(obj.data.totalTime / 60);
  398. var total_seconds = obj.data.totalTime - total_minutes * 60;
  399. var elapsed_minutes = Math.floor(obj.data.elapsedTime / 60);
  400. var elapsed_seconds = obj.data.elapsedTime - elapsed_minutes * 60;
  401. $('#volumeslider').slider(obj.data.volume);
  402. var progress = Math.floor(100*obj.data.elapsedTime/obj.data.totalTime);
  403. $('#progressbar').slider(progress);
  404. $('#counter')
  405. .text(elapsed_minutes + ":" +
  406. (elapsed_seconds < 10 ? '0' : '') + elapsed_seconds + " / " +
  407. total_minutes + ":" + (total_seconds < 10 ? '0' : '') + total_seconds);
  408. $('#salamisandwich > tbody > tr').removeClass('active').css("font-weight", "");
  409. $('#salamisandwich > tbody > tr[trackid='+obj.data.currentsongid+']').addClass('active').css("font-weight", "bold");
  410. if(obj.data.random)
  411. $('#btnrandom').addClass("active")
  412. else
  413. $('#btnrandom').removeClass("active");
  414. if(obj.data.consume)
  415. $('#btnconsume').addClass("active")
  416. else
  417. $('#btnconsume').removeClass("active");
  418. if(obj.data.single)
  419. $('#btnsingle').addClass("active")
  420. else
  421. $('#btnsingle').removeClass("active");
  422. if(obj.data.crossfade)
  423. $('#btncrossfade').addClass("active")
  424. else
  425. $('#btncrossfade').removeClass("active");
  426. if(obj.data.repeat)
  427. $('#btnrepeat').addClass("active")
  428. else
  429. $('#btnrepeat').removeClass("active");
  430. last_state = obj;
  431. break;
  432. case "outputnames":
  433. $('#btn-outputs-block button').remove();
  434. $.each(obj.data, function(id, name){
  435. var btn = $('<button id="btnoutput'+id+'" class="btn btn-default" onclick="toggleoutput(this, '+id+')"><span class="glyphicon glyphicon-volume-up"></span> '+name+'</button>');
  436. btn.appendTo($('#btn-outputs-block'));
  437. });
  438. /* remove cache, since the buttons have been recreated */
  439. last_outputs = '';
  440. break;
  441. case "outputs":
  442. if(JSON.stringify(obj) === JSON.stringify(last_outputs))
  443. break;
  444. $.each(obj.data, function(id, enabled){
  445. if (enabled)
  446. $('#btnoutput'+id).addClass("active");
  447. else
  448. $('#btnoutput'+id).removeClass("active");
  449. });
  450. last_outputs = obj;
  451. break;
  452. case "disconnected":
  453. if($('.top-right').has('div').length == 0)
  454. $('.top-right').notify({
  455. message:{text:"ympd lost connection to MPD "},
  456. type: "danger",
  457. fadeOut: { enabled: true, delay: 1000 },
  458. }).show();
  459. break;
  460. case "update_queue":
  461. if(current_app === 'queue')
  462. socket.send('MPD_API_GET_QUEUE,'+pagination);
  463. break;
  464. case "song_change":
  465. $('#album').text("");
  466. $('#artist').text("");
  467. $('#btnlove').removeClass("active");
  468. $('#currenttrack').text(" " + obj.data.title);
  469. var notification = "<strong><h4>" + obj.data.title + "</h4></strong>";
  470. if(obj.data.album) {
  471. $('#album').text(obj.data.album);
  472. notification += obj.data.album + "<br />";
  473. }
  474. if(obj.data.artist) {
  475. $('#artist').text(obj.data.artist);
  476. notification += obj.data.artist + "<br />";
  477. }
  478. if ($.cookie("notification") === "true")
  479. songNotify(obj.data.title, obj.data.artist, obj.data.album );
  480. else
  481. $('.top-right').notify({
  482. message:{html: notification},
  483. type: "info",
  484. }).show();
  485. break;
  486. case "mpdhost":
  487. $('#mpdhost').val(obj.data.host);
  488. $('#mpdport').val(obj.data.port);
  489. if(obj.data.passwort_set)
  490. $('#mpd_password_set').removeClass('hide');
  491. break;
  492. case "dirbleapitoken":
  493. dirble_api_token = obj.data;
  494. if(dirble_stations) {
  495. dirble_load_stations();
  496. } else {
  497. dirble_load_categories();
  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. function getDirbleApiToken() {
  671. socket.send('MPD_API_GET_DIRBLEAPITOKEN');
  672. }
  673. $('#search').submit(function () {
  674. app.setLocation("#/search/"+$('#search > div > input').val());
  675. $('#wait').modal('show');
  676. setTimeout(function() {
  677. $('#wait').modal('hide');
  678. }, 10000);
  679. return false;
  680. });
  681. $('.page-btn').on('click', function (e) {
  682. switch ($(this).text()) {
  683. case "Next":
  684. if (current_app == "dirble") dirble_page++;
  685. else pagination += MAX_ELEMENTS_PER_PAGE;
  686. break;
  687. case "Previous":
  688. if (current_app == "dirble") dirble_page--
  689. else {
  690. pagination -= MAX_ELEMENTS_PER_PAGE;
  691. if(pagination <= 0)
  692. pagination = 0;
  693. }
  694. break;
  695. }
  696. switch(current_app) {
  697. case "queue":
  698. app.setLocation('#/'+pagination);
  699. break;
  700. case "browse":
  701. app.setLocation('#/browse/'+pagination+'/'+browsepath);
  702. break;
  703. case "dirble":
  704. app.setLocation("#/dirble/"+dirble_catid+"/"+dirble_page);
  705. break;
  706. }
  707. e.preventDefault();
  708. });
  709. function addStream() {
  710. if($('#streamurl').val().length > 0) {
  711. socket.send('MPD_API_ADD_TRACK,'+$('#streamurl').val());
  712. }
  713. $('#streamurl').val("");
  714. $('#addstream').modal('hide');
  715. }
  716. function saveQueue() {
  717. if($('#playlistname').val().length > 0) {
  718. socket.send('MPD_API_SAVE_QUEUE,'+$('#playlistname').val());
  719. }
  720. $('#savequeue').modal('hide');
  721. }
  722. function confirmSettings() {
  723. if($('#mpd_pw').val().length + $('#mpd_pw_con').val().length > 0) {
  724. if ($('#mpd_pw').val() !== $('#mpd_pw_con').val())
  725. {
  726. $('#mpd_pw_con').popover('show');
  727. setTimeout(function() {
  728. $('#mpd_pw_con').popover('hide');
  729. }, 2000);
  730. return;
  731. } else
  732. socket.send('MPD_API_SET_MPDPASS,'+$('#mpd_pw').val());
  733. }
  734. socket.send('MPD_API_SET_MPDHOST,'+$('#mpdport').val()+','+$('#mpdhost').val());
  735. $('#settings').modal('hide');
  736. }
  737. $('#mpd_password_set > button').on('click', function (e) {
  738. socket.send('MPD_API_SET_MPDPASS,');
  739. $('#mpd_pw').val("");
  740. $('#mpd_pw_con').val("");
  741. $('#mpd_password_set').addClass('hide');
  742. })
  743. function notificationsSupported() {
  744. return "Notification" in window;
  745. }
  746. function songNotify(title, artist, album) {
  747. /*var opt = {
  748. type: "list",
  749. title: title,
  750. message: title,
  751. items: []
  752. }
  753. if(artist.length > 0)
  754. opt.items.push({title: "Artist", message: artist});
  755. if(album.length > 0)
  756. opt.items.push({title: "Album", message: album});
  757. */
  758. //chrome.notifications.create(id, options, creationCallback);
  759. var textNotification = "";
  760. if(typeof artist != 'undefined' && artist.length > 0)
  761. textNotification += " " + artist;
  762. if(typeof album != 'undefined' && album.length > 0)
  763. textNotification += "\n " + album;
  764. var notification = new Notification(title, {icon: 'assets/favicon.ico', body: textNotification});
  765. setTimeout(function(notification) {
  766. notification.close();
  767. }, 3000, notification);
  768. }
  769. $(document).keydown(function(e){
  770. if (e.target.tagName == 'INPUT') {
  771. return;
  772. }
  773. switch (e.which) {
  774. case 37: //left
  775. socket.send('MPD_API_SET_PREV');
  776. break;
  777. case 39: //right
  778. socket.send('MPD_API_SET_NEXT');
  779. break;
  780. case 32: //space
  781. clickPlay();
  782. break;
  783. default:
  784. return;
  785. }
  786. e.preventDefault();
  787. });
  788. function dirble_load_categories() {
  789. dirble_page = 1;
  790. $.getJSON( "https://api.dirble.com/v2/categories?token=" + dirble_api_token, function( data ) {
  791. $('#dirble_loading').addClass('hide');
  792. data = data.sort(function(a, b) {
  793. return (a.title > b.title) ? 1 : 0;
  794. });
  795. var max = data.length - data.length%2;
  796. for(i = 0; i < max; i+=2) {
  797. $('#dirble_left > tbody').append(
  798. "<tr><td catid=\""+data[i].id+"\">"+data[i].title+"</td></tr>"
  799. );
  800. $('#dirble_right > tbody').append(
  801. "<tr><td catid=\""+data[i+1].id+"\">"+data[i+1].title+"</td></tr>"
  802. );
  803. }
  804. if (max != data.length) {
  805. $('#dirble_left > tbody').append(
  806. "<tr><td catid=\""+data[max].id+"\">"+data[max].title+"</td></tr>"
  807. );
  808. }
  809. $('#dirble_left > tbody > tr > td').on({
  810. click: function() {
  811. dirble_selected_cat = $(this).text();
  812. dirble_catid = $(this).attr("catid");
  813. app.setLocation("#/dirble/"+dirble_catid+"/"+dirble_page);
  814. }
  815. });
  816. $('#dirble_right > tbody > tr > td').on({
  817. click: function() {
  818. dirble_selected_cat = $(this).text();
  819. dirble_catid = $(this).attr("catid");
  820. app.setLocation("#/dirble/"+dirble_catid+"/"+dirble_page);
  821. }
  822. });
  823. });
  824. }
  825. function dirble_load_stations() {
  826. $.getJSON( "https://api.dirble.com/v2/category/"+dirble_catid+"/stations?page="+dirble_page+"&per_page=20&token=" + dirble_api_token, function( data ) {
  827. $('#dirble_loading').addClass('hide');
  828. if (data.length == 20) $('#next').removeClass('hide');
  829. var max = data.length - data.length%2;
  830. for(i = 0; i < max; i+=2) {
  831. $('#dirble_left > tbody').append(
  832. "<tr><td radioid=\""+data[i].id+"\">"+data[i].name+"</td></tr>"
  833. );
  834. $('#dirble_right > tbody').append(
  835. "<tr><td radioid=\""+data[i+1].id+"\">"+data[i+1].name+"</td></tr>"
  836. );
  837. }
  838. if (max != data.length) {
  839. $('#dirble_left > tbody').append(
  840. "<tr><td radioid=\""+data[max].id+"\">"+data[max].name+"</td></tr>"
  841. );
  842. }
  843. $('#dirble_left > tbody > tr > td').on({
  844. click: function() {
  845. var _this = $(this);
  846. $.getJSON( "https://api.dirble.com/v2/station/"+$(this).attr("radioid")+"?token=" + dirble_api_token, function( data ) {
  847. socket.send("MPD_API_ADD_TRACK," + data.streams[0].stream);
  848. $('.top-right').notify({
  849. message:{
  850. text: _this.text() + " added"
  851. }
  852. }).show();
  853. });
  854. },
  855. mouseenter: function() {
  856. var _this = $(this);
  857. $(this).last().append(
  858. "<a role=\"button\" class=\"pull-right btn-group-hover\">" +
  859. "<span class=\"glyphicon glyphicon-play\"></span></a>").find('a').click(function(e) {
  860. e.stopPropagation();
  861. $.getJSON( "https://api.dirble.com/v2/station/"+_this.attr("radioid")+"?token=" + dirble_api_token, function( data ) {
  862. socket.send("MPD_API_ADD_PLAY_TRACK," + data.streams[0].stream);
  863. $('.top-right').notify({
  864. message:{
  865. text: _this.text() + " added"
  866. }
  867. }).show();
  868. });
  869. }).fadeTo('fast',1);
  870. },
  871. mouseleave: function(){
  872. $(this).last().find("a").stop().remove();
  873. }
  874. });
  875. $('#dirble_right> tbody > tr > td').on({
  876. click: function() {
  877. var _this = $(this);
  878. $.getJSON( "https://api.dirble.com/v2/station/"+$(this).attr("radioid")+"?token=" + dirble_api_token, function( data ) {
  879. socket.send("MPD_API_ADD_TRACK," + data.streams[0].stream);
  880. $('.top-right').notify({
  881. message:{
  882. text: _this.text() + " added"
  883. }
  884. }).show();
  885. });
  886. },
  887. mouseenter: function() {
  888. var _this = $(this);
  889. $(this).last().append(
  890. "<a role=\"button\" class=\"pull-right btn-group-hover\">" +
  891. "<span class=\"glyphicon glyphicon-play\"></span></a>").find('a').click(function(e) {
  892. e.stopPropagation();
  893. $.getJSON( "https://api.dirble.com/v2/station/"+_this.attr("radioid")+"?token=" + dirble_api_token, function( data ) {
  894. socket.send("MPD_API_ADD_PLAY_TRACK," + data.streams[0].stream);
  895. $('.top-right').notify({
  896. message:{
  897. text: _this.text() + " added"
  898. }
  899. }).show();
  900. });
  901. }).fadeTo('fast',1);
  902. },
  903. mouseleave: function(){
  904. $(this).last().find("a").stop().remove();
  905. }
  906. });
  907. });
  908. }
  909. function set_filter (c) {
  910. filter = c;
  911. $.each($('#salamisandwich > tbody > tr.dir'), function(i, line) {
  912. var first = $(line).attr('uri')[0];
  913. if (filter === undefined) {
  914. $(line).removeClass('hide');
  915. }
  916. else if (filter === "#") {
  917. if (!isNaN(first)) {
  918. $(line).removeClass('hide');
  919. } else {
  920. $(line).addClass('hide');
  921. }
  922. }
  923. else if (filter >= "A" && filter <= "Z") {
  924. if (first.toUpperCase() === filter) {
  925. $(line).removeClass('hide');
  926. } else {
  927. $(line).addClass('hide');
  928. }
  929. }
  930. else if (filter === "||") {
  931. $(line).addClass('hide');
  932. }
  933. });
  934. $.each($('#salamisandwich > tbody > tr.plist'), function(i, line) {
  935. if (filter === undefined) {
  936. $(line).removeClass('hide');
  937. } else if (filter === "||") {
  938. $(line).removeClass('hide');
  939. } else {
  940. $(line).addClass('hide');
  941. }
  942. });
  943. }
  944. function add_filter () {
  945. $('#filter').append('&nbsp;<a onclick="set_filter(\'#\')" href="#/browse/0/">#</a>');
  946. for (i = 65; i <= 90; i++) {
  947. var c = String.fromCharCode(i);
  948. $('#filter').append('&nbsp;<a onclick="set_filter(\'' + c + '\')" href="#/browse/0/">' + c + '</a>');
  949. }
  950. $('#filter').append('&nbsp;<a onclick="set_filter(\'||\')" href="#/browse/0/" class="glyphicon glyphicon-list"></a>');
  951. }