mpd.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. /* libmpdclient
  2. (c) 2013-2014 Andrew Karpow <andy@ympd.org>
  3. This project's homepage is: http://www.ympd.org
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions
  6. are met:
  7. - Redistributions of source code must retain the above copyright
  8. notice, this list of conditions and the following disclaimer.
  9. - Redistributions in binary form must reproduce the above copyright
  10. notice, this list of conditions and the following disclaimer in the
  11. documentation and/or other materials provided with the distribution.
  12. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  13. ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  14. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  15. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
  16. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  17. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  18. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  19. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  22. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. var socket;
  25. var last_state;
  26. var current_app;
  27. var lastSongTitle = "";
  28. var current_song = new Object();
  29. var app = $.sammy(function() {
  30. this.before('/', function(e, data) {
  31. $('#nav_links > li').removeClass('active');
  32. });
  33. this.get('#/', function() {
  34. current_app = 'playlist';
  35. $('#breadcrump').addClass('hide');
  36. $('#salamisandwich').find("tr:gt(0)").remove();
  37. $.get( "/api/get_playlist", socket.onmessage);
  38. $('#panel-heading').text("Playlist");
  39. $('#playlist').addClass('active');
  40. });
  41. this.get(/\#\/browse\/(.*)/, function() {
  42. current_app = 'browse';
  43. $('#breadcrump').removeClass('hide').empty().append("<li><a href=\"#/browse/\">root</a></li>");
  44. $('#salamisandwich').find("tr:gt(0)").remove();
  45. var path = this.params['splat'][0];
  46. $.get( "/api/get_browse/" + encodeURIComponent(path), socket.onmessage);
  47. $('#panel-heading').text("Browse database: "+path+"");
  48. var path_array = path.split('/');
  49. var full_path = "";
  50. $.each(path_array, function(index, chunk) {
  51. if(path_array.length - 1 == index) {
  52. $('#breadcrump').append("<li class=\"active\">"+ chunk + "</li>");
  53. return;
  54. }
  55. full_path = full_path + chunk;
  56. $('#breadcrump').append("<li><a href=\"#/browse/" + full_path + "\">"+chunk+"</a></li>");
  57. full_path += "/";
  58. });
  59. $('#browse').addClass('active');
  60. });
  61. this.get("/", function(context) {
  62. context.redirect("#/");
  63. });
  64. });
  65. $(document).ready(function(){
  66. webSocketConnect();
  67. $("#volumeslider").slider(0);
  68. $("#volumeslider").on('slider.newValue', function(evt,data){
  69. socket.send("MPD_API_SET_VOLUME,"+data.val);
  70. });
  71. $('#progressbar').slider(0);
  72. $("#progressbar").on('slider.newValue', function(evt,data){
  73. if(current_song && current_song.currentSongId >= 0) {
  74. var seekVal = Math.ceil(current_song.totalTime*(data.val/100));
  75. socket.send("MPD_API_SET_SEEK,"+current_song.currentSongId+","+seekVal);
  76. }
  77. });
  78. if(!notificationsSupported())
  79. $('#btnnotify').addClass("disabled");
  80. else
  81. if ($.cookie("notification") === "true")
  82. $('#btnnotify').addClass("active")
  83. });
  84. function webSocketConnect() {
  85. if (typeof MozWebSocket != "undefined") {
  86. socket = new MozWebSocket(get_appropriate_ws_url(), "ympd-client");
  87. } else {
  88. socket = new WebSocket(get_appropriate_ws_url(), "ympd-client");
  89. }
  90. try {
  91. socket.onopen = function() {
  92. $('.top-right').notify({
  93. message:{text:"Connected to ympd"},
  94. fadeOut: { enabled: true, delay: 500 }
  95. }).show();
  96. app.run();
  97. }
  98. socket.onmessage =function got_packet(msg) {
  99. if(msg instanceof MessageEvent) {
  100. if(msg.data === last_state)
  101. return;
  102. var obj = JSON.parse(msg.data);
  103. } else {
  104. var obj = msg;
  105. }
  106. switch (obj.type) {
  107. case "playlist":
  108. if(current_app !== 'playlist')
  109. break;
  110. $('#salamisandwich > tbody').empty();
  111. for (var song in obj.data) {
  112. var minutes = Math.floor(obj.data[song].duration / 60);
  113. var seconds = obj.data[song].duration - minutes * 60;
  114. $('#salamisandwich > tbody').append(
  115. "<tr trackid=\"" + obj.data[song].id + "\"><td>" + (obj.data[song].pos + 1) + "</td>" +
  116. "<td>"+ obj.data[song].title +"</td>" +
  117. "<td>"+ minutes + ":" + (seconds < 10 ? '0' : '') + seconds +
  118. "</td><td></td></tr>");
  119. }
  120. $('#salamisandwich > tbody > tr').on({
  121. mouseover: function(){
  122. if($(this).children().last().has("a").length == 0)
  123. $(this).children().last().append(
  124. "<a class=\"pull-right btn-group-hover\" href=\"#/\" " +
  125. "onclick=\"socket.send('MPD_API_RM_TRACK," + $(this).attr("trackid") +"'); $(this).parents('tr').remove();\">" +
  126. "<span class=\"glyphicon glyphicon-trash\"></span></a>")
  127. .find('a').fadeTo('fast',1);
  128. },
  129. click: function() {
  130. $('#salamisandwich > tbody > tr').removeClass('active');
  131. socket.send('MPD_API_PLAY_TRACK,'+$(this).attr('trackid'));
  132. $(this).addClass('active');
  133. },
  134. mouseleave: function(){
  135. $(this).children().last().find("a").stop().remove();
  136. }
  137. });
  138. break;
  139. case "browse":
  140. if(current_app !== 'browse')
  141. break;
  142. for (var item in obj.data) {
  143. switch(obj.data[item].type) {
  144. case "directory":
  145. $('#salamisandwich > tbody').append(
  146. "<tr uri=\"" + obj.data[item].dir + "\" class=\"dir\">" +
  147. "<td><span class=\"glyphicon glyphicon-folder-open\"></span></td>" +
  148. "<td><a>" + basename(obj.data[item].dir) + "</a></td>" +
  149. "<td></td><td></td></tr>");
  150. break;
  151. case "song":
  152. var minutes = Math.floor(obj.data[item].duration / 60);
  153. var seconds = obj.data[item].duration - minutes * 60;
  154. $('#salamisandwich > tbody').append(
  155. "<tr uri=\"" + obj.data[item].uri + "\" class=\"song\">" +
  156. "<td><span class=\"glyphicon glyphicon-music\"></span></td>" +
  157. "<td>" + obj.data[item].title +"</td>" +
  158. "<td>"+ minutes + ":" + (seconds < 10 ? '0' : '') + seconds +"</td><td></td></tr>");
  159. break;
  160. case "playlist":
  161. break;
  162. }
  163. }
  164. function appendClickableIcon(appendTo, onClickAction, glyphicon) {
  165. $(appendTo).children().last().append(
  166. "<a role=\"button\" class=\"pull-right btn-group-hover\">" +
  167. "<span class=\"glyphicon glyphicon-" + glyphicon + "\"></span></a>")
  168. .find('a').click(function(e) {
  169. e.stopPropagation();
  170. socket.send(onClickAction + "," + $(this).parents("tr").attr("uri"));
  171. $('.top-right').notify({
  172. message:{
  173. text: $('td:nth-child(2)', $(this).parents("tr")).text() + " added"
  174. } }).show();
  175. }).fadeTo('fast',1);
  176. }
  177. $('#salamisandwich > tbody > tr').on({
  178. mouseenter: function() {
  179. if($(this).is(".dir"))
  180. appendClickableIcon($(this), 'MPD_API_ADD_TRACK', 'plus');
  181. else if($(this).is(".song"))
  182. appendClickableIcon($(this), 'MPD_API_ADD_PLAY_TRACK', 'play');
  183. },
  184. click: function() {
  185. if($(this).is(".song")) {
  186. socket.send("MPD_API_ADD_TRACK," + $(this).attr("uri"));
  187. $('.top-right').notify({
  188. message:{
  189. text: $('td:nth-child(2)', this).text() + " added"
  190. }
  191. }).show();
  192. } else
  193. app.setLocation("#/browse/"+$(this).attr("uri"));
  194. },
  195. mouseleave: function(){
  196. $(this).children().last().find("a").stop().remove();
  197. }
  198. });
  199. break;
  200. case "state":
  201. updatePlayIcon(obj.data.state);
  202. updateVolumeIcon(obj.data.volume);
  203. if(JSON.stringify(obj) === JSON.stringify(last_state))
  204. break;
  205. current_song.totalTime = obj.data.totalTime;
  206. current_song.currentSongId = obj.data.currentsongid;
  207. var total_minutes = Math.floor(obj.data.totalTime / 60);
  208. var total_seconds = obj.data.totalTime - total_minutes * 60;
  209. var elapsed_minutes = Math.floor(obj.data.elapsedTime / 60);
  210. var elapsed_seconds = obj.data.elapsedTime - elapsed_minutes * 60;
  211. $('#volumeslider').slider(obj.data.volume);
  212. var progress = Math.floor(100*obj.data.elapsedTime/obj.data.totalTime);
  213. $('#progressbar').slider(progress);
  214. $('#counter')
  215. .text(elapsed_minutes + ":" +
  216. (elapsed_seconds < 10 ? '0' : '') + elapsed_seconds + " / " +
  217. total_minutes + ":" + (total_seconds < 10 ? '0' : '') + total_seconds);
  218. $('#salamisandwich > tbody > tr').removeClass('active').css("font-weight", "");
  219. $('#salamisandwich > tbody > tr[trackid='+obj.data.currentsongid+']').addClass('active').css("font-weight", "bold");
  220. if(obj.data.random)
  221. $('#btnrandom').addClass("active")
  222. else
  223. $('#btnrandom').removeClass("active");
  224. if(obj.data.consume)
  225. $('#btnconsume').addClass("active")
  226. else
  227. $('#btnconsume').removeClass("active");
  228. if(obj.data.single)
  229. $('#btnsingle').addClass("active")
  230. else
  231. $('#btnsingle').removeClass("active");
  232. if(obj.data.repeat)
  233. $('#btnrepeat').addClass("active")
  234. else
  235. $('#btnrepeat').removeClass("active");
  236. last_state = obj;
  237. break;
  238. case "disconnected":
  239. if($('.top-right').has('div').length == 0)
  240. $('.top-right').notify({
  241. message:{text:"ympd lost connection to MPD "},
  242. type: "danger",
  243. fadeOut: { enabled: true, delay: 1000 },
  244. }).show();
  245. break;
  246. case "update_playlist":
  247. if(current_app === 'playlist')
  248. $.get( "/api/get_playlist", socket.onmessage);
  249. break;
  250. case "song_change":
  251. $('#currenttrack').text(" " + obj.data.title);
  252. var notification = "<strong><h4>" + obj.data.title + "</h4></strong>";
  253. if(obj.data.album) {
  254. $('#album').text(obj.data.album);
  255. notification += obj.data.album + "<br />";
  256. }
  257. if(obj.data.artist) {
  258. $('#artist').text(obj.data.artist);
  259. notification += obj.data.artist + "<br />";
  260. }
  261. if ($.cookie("notification") === "true")
  262. songNotify(obj.data.title, obj.data.artist + " " + obj.data.album );
  263. else
  264. $('.top-right').notify({
  265. message:{html: notification},
  266. type: "info",
  267. }).show();
  268. break;
  269. case "mpdhost":
  270. $('#mpdhost').val(obj.data.host);
  271. $('#mpdport').val(obj.data.port);
  272. break;
  273. case "error":
  274. $('.top-right').notify({
  275. message:{text: obj.data},
  276. type: "danger",
  277. }).show();
  278. default:
  279. break;
  280. }
  281. }
  282. socket.onclose = function(){
  283. $('.top-right').notify({
  284. message:{text:"Connection to ympd lost, retrying in 3 seconds "},
  285. type: "danger",
  286. onClose: function () {
  287. webSocketConnect();
  288. }
  289. }).show();
  290. }
  291. } catch(exception) {
  292. alert('<p>Error' + exception);
  293. }
  294. }
  295. function get_appropriate_ws_url()
  296. {
  297. var pcol;
  298. var u = document.URL;
  299. /*
  300. /* We open the websocket encrypted if this page came on an
  301. /* https:// url itself, otherwise unencrypted
  302. /*/
  303. if (u.substring(0, 5) == "https") {
  304. pcol = "wss://";
  305. u = u.substr(8);
  306. } else {
  307. pcol = "ws://";
  308. if (u.substring(0, 4) == "http")
  309. u = u.substr(7);
  310. }
  311. u = u.split('/');
  312. return pcol + u[0];
  313. }
  314. var updateVolumeIcon = function(volume)
  315. {
  316. $("#volume-icon").removeClass("glyphicon-volume-off");
  317. $("#volume-icon").removeClass("glyphicon-volume-up");
  318. $("#volume-icon").removeClass("glyphicon-volume-down");
  319. if(volume == 0) {
  320. $("#volume-icon").addClass("glyphicon-volume-off");
  321. } else if (volume < 50) {
  322. $("#volume-icon").addClass("glyphicon-volume-down");
  323. } else {
  324. $("#volume-icon").addClass("glyphicon-volume-up");
  325. }
  326. }
  327. var updatePlayIcon = function(state)
  328. {
  329. $("#play-icon").removeClass("glyphicon-play")
  330. .removeClass("glyphicon-pause");
  331. $('#track-icon').removeClass("glyphicon-play")
  332. .removeClass("glyphicon-pause")
  333. .removeClass("glyphicon-stop");
  334. if(state == 1) { // stop
  335. $("#play-icon").addClass("glyphicon-play");
  336. $('#track-icon').addClass("glyphicon-stop");
  337. } else if(state == 2) { // pause
  338. $("#play-icon").addClass("glyphicon-pause");
  339. $('#track-icon').addClass("glyphicon-play");
  340. } else { // play
  341. $("#play-icon").addClass("glyphicon-play");
  342. $('#track-icon').addClass("glyphicon-pause");
  343. }
  344. }
  345. function updateDB() {
  346. socket.send('MPD_API_UPDATE_DB');
  347. $('.top-right').notify({
  348. message:{text:"Updating MPD Database... "}
  349. }).show();
  350. }
  351. function clickPlay() {
  352. if($('#track-icon').hasClass('glyphicon-stop'))
  353. socket.send('MPD_API_SET_PLAY');
  354. else
  355. socket.send('MPD_API_SET_PAUSE');
  356. }
  357. function basename(path) {
  358. return path.split('/').reverse()[0];
  359. }
  360. $('#btnrandom').on('click', function (e) {
  361. socket.send("MPD_API_TOGGLE_RANDOM," + ($(this).hasClass('active') ? 0 : 1));
  362. });
  363. $('#btnconsume').on('click', function (e) {
  364. socket.send("MPD_API_TOGGLE_CONSUME," + ($(this).hasClass('active') ? 0 : 1));
  365. });
  366. $('#btnsingle').on('click', function (e) {
  367. socket.send("MPD_API_TOGGLE_SINGLE," + ($(this).hasClass('active') ? 0 : 1));
  368. });
  369. $('#btnrepeat').on('click', function (e) {
  370. socket.send("MPD_API_TOGGLE_REPEAT," + ($(this).hasClass('active') ? 0 : 1));
  371. });
  372. $('#btnnotify').on('click', function (e) {
  373. if($.cookie("notification") === "true")
  374. $.cookie("notification", false);
  375. else {
  376. window.webkitNotifications.requestPermission();
  377. if (window.webkitNotifications.checkPermission() == 0)
  378. {
  379. $.cookie("notification", true);
  380. $('btnnotify').addClass("active");
  381. }
  382. }
  383. });
  384. function getVersion()
  385. {
  386. $.get( "/api/get_version", function(response) {
  387. $('#ympd_version').text(response.data.ympd_version);
  388. $('#mpd_version').text(response.data.mpd_version);
  389. });
  390. }
  391. function getHost() {
  392. socket.send('MPD_API_GET_MPDHOST');
  393. function onEnter(event) {
  394. if ( event.which == 13 ) {
  395. setHost();
  396. $('#settings').modal('hide');
  397. }
  398. }
  399. $('#mpdhost').keypress(onEnter);
  400. $('#mpdport').keypress(onEnter);
  401. }
  402. function setHost() {
  403. socket.send('MPD_API_SET_MPDHOST,'+$('#mpdport').val()+','+$('#mpdhost').val());
  404. }
  405. function notificationsSupported() {
  406. return "webkitNotifications" in window;
  407. }
  408. function songNotify(artist, title) {
  409. if (!notificationsSupported())
  410. return;
  411. if (window.webkitNotifications.checkPermission() == 0) {
  412. var notification = window.webkitNotifications.createNotification("assets/favicon.ico", artist, title);
  413. notification.show();
  414. setTimeout(function(notification) {
  415. notification.cancel();
  416. }, 3000, notification);
  417. } else {
  418. window.webkitNotifications.requestPermission();
  419. }
  420. }