1
0
mirror of https://github.com/SuperBFG7/ympd synced 2024-11-30 00:19:54 +00:00
ympd/htdocs/js/mpd.js

654 lines
24 KiB
JavaScript
Raw Normal View History

/* ympd
(c) 2013-2014 Andrew Karpow <andy@ndyk.de>
2014-01-17 18:41:41 +00:00
This project's homepage is: http://www.ympd.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
2014-01-17 18:41:41 +00:00
*/
2013-11-04 17:18:38 +00:00
var socket;
var last_state;
2015-04-28 09:08:21 +00:00
var last_outputs;
2013-11-07 12:47:31 +00:00
var current_app;
2014-02-22 01:11:45 +00:00
var pagination = 0;
var browsepath;
var lastSongTitle = "";
var current_song = new Object();
2014-02-22 01:11:45 +00:00
var MAX_ELEMENTS_PER_PAGE = 512;
2013-11-04 17:18:38 +00:00
2013-11-07 12:47:31 +00:00
var app = $.sammy(function() {
2014-02-22 01:11:45 +00:00
function runBrowse() {
current_app = 'queue';
2014-02-22 01:11:45 +00:00
$('#breadcrump').addClass('hide');
$('#salamisandwich').find("tr:gt(0)").remove();
2014-02-22 01:11:45 +00:00
socket.send('MPD_API_GET_QUEUE,'+pagination);
$('#panel-heading').text("Queue");
$('#queue').addClass('active');
2014-02-22 01:11:45 +00:00
}
function prepare() {
$('#nav_links > li').removeClass('active');
$('.page-btn').addClass('hide');
pagination = 0;
browsepath = '';
}
this.get(/\#\/(\d+)/, function() {
prepare();
pagination = parseInt(this.params['splat'][0]);
runBrowse();
});
2014-02-22 01:11:45 +00:00
this.get(/\#\/browse\/(\d+)\/(.*)/, function() {
prepare();
browsepath = this.params['splat'][1];
pagination = parseInt(this.params['splat'][0]);
current_app = 'browse';
2014-02-22 01:11:45 +00:00
$('#breadcrump').removeClass('hide').empty().append("<li><a href=\"#/browse/0/\">root</a></li>");
$('#salamisandwich').find("tr:gt(0)").remove();
2014-02-22 01:11:45 +00:00
socket.send('MPD_API_GET_BROWSE,'+pagination+','+(browsepath ? browsepath : "/"));
2014-02-22 01:11:45 +00:00
$('#panel-heading').text("Browse database: "+browsepath);
var path_array = browsepath.split('/');
var full_path = "";
$.each(path_array, function(index, chunk) {
if(path_array.length - 1 == index) {
$('#breadcrump').append("<li class=\"active\">"+ chunk + "</li>");
return;
}
full_path = full_path + chunk;
2014-02-22 01:11:45 +00:00
$('#breadcrump').append("<li><a href=\"#/browse/0/" + full_path + "\">"+chunk+"</a></li>");
full_path += "/";
});
$('#browse').addClass('active');
});
this.get(/\#\/search\/(.*)/, function() {
current_app = 'search';
$('#salamisandwich').find("tr:gt(0)").remove();
var searchstr = this.params['splat'][0];
$('#search > div > input').val(searchstr);
socket.send('MPD_API_SEARCH,' + searchstr);
$('#panel-heading').text("Search: "+searchstr);
});
this.get("/", function(context) {
2014-02-22 01:11:45 +00:00
context.redirect("#/0");
});
2013-11-07 12:47:31 +00:00
});
2013-11-07 09:09:40 +00:00
$(document).ready(function(){
webSocketConnect();
$("#volumeslider").slider(0);
$("#volumeslider").on('slider.newValue', function(evt,data){
socket.send("MPD_API_SET_VOLUME,"+data.val);
});
$('#progressbar').slider(0);
$("#progressbar").on('slider.newValue', function(evt,data){
2014-01-17 15:41:54 +00:00
if(current_song && current_song.currentSongId >= 0) {
var seekVal = Math.ceil(current_song.totalTime*(data.val/100));
socket.send("MPD_API_SET_SEEK,"+current_song.currentSongId+","+seekVal);
}
});
if(!notificationsSupported())
$('#btnnotify').addClass("disabled");
else
if ($.cookie("notification") === "true")
$('#btnnotify').addClass("active")
2013-11-07 09:09:40 +00:00
});
function webSocketConnect() {
if (typeof MozWebSocket != "undefined") {
2014-02-16 18:46:53 +00:00
socket = new MozWebSocket(get_appropriate_ws_url());
} else {
2014-02-16 18:46:53 +00:00
socket = new WebSocket(get_appropriate_ws_url());
}
try {
socket.onopen = function() {
2014-02-16 18:46:53 +00:00
console.log("connected");
$('.top-right').notify({
2014-01-17 15:26:26 +00:00
message:{text:"Connected to ympd"},
fadeOut: { enabled: true, delay: 500 }
}).show();
app.run();
2015-04-28 09:08:21 +00:00
/* emit initial request for output names */
socket.send("MPD_API_GET_OUTPUTS");
}
2014-02-22 01:11:45 +00:00
socket.onmessage = function got_packet(msg) {
if(msg.data === last_state || msg.data.length == 0)
return;
var obj = JSON.parse(msg.data);
switch (obj.type) {
case "queue":
if(current_app !== 'queue')
break;
$('#salamisandwich > tbody').empty();
for (var song in obj.data) {
var minutes = Math.floor(obj.data[song].duration / 60);
var seconds = obj.data[song].duration - minutes * 60;
$('#salamisandwich > tbody').append(
2014-01-17 15:26:26 +00:00
"<tr trackid=\"" + obj.data[song].id + "\"><td>" + (obj.data[song].pos + 1) + "</td>" +
"<td>"+ obj.data[song].title +"</td>" +
"<td>"+ minutes + ":" + (seconds < 10 ? '0' : '') + seconds +
2014-01-17 15:26:26 +00:00
"</td><td></td></tr>");
}
if(obj.data[obj.data.length-1].pos + 1 >= pagination + MAX_ELEMENTS_PER_PAGE)
2014-02-22 01:11:45 +00:00
$('#next').removeClass('hide');
if(pagination > 0)
$('#prev').removeClass('hide');
$('#salamisandwich > tbody > tr').on({
mouseover: function(){
if($(this).children().last().has("a").length == 0)
$(this).children().last().append(
"<a class=\"pull-right btn-group-hover\" href=\"#/\" " +
"onclick=\"socket.send('MPD_API_RM_TRACK," + $(this).attr("trackid") +"'); $(this).parents('tr').remove();\">" +
"<span class=\"glyphicon glyphicon-trash\"></span></a>")
.find('a').fadeTo('fast',1);
},
click: function() {
$('#salamisandwich > tbody > tr').removeClass('active');
socket.send('MPD_API_PLAY_TRACK,'+$(this).attr('trackid'));
$(this).addClass('active');
},
mouseleave: function(){
$(this).children().last().find("a").stop().remove();
}
});
break;
case "search":
2014-02-22 01:11:45 +00:00
$('#wait').modal('hide');
case "browse":
if(current_app !== 'browse' && current_app !== 'search')
break;
for (var item in obj.data) {
switch(obj.data[item].type) {
case "directory":
$('#salamisandwich > tbody').append(
"<tr uri=\"" + obj.data[item].dir + "\" class=\"dir\">" +
"<td><span class=\"glyphicon glyphicon-folder-open\"></span></td>" +
"<td><a>" + basename(obj.data[item].dir) + "</a></td>" +
"<td></td><td></td></tr>"
);
break;
case "playlist":
$('#salamisandwich > tbody').append(
"<tr uri=\"" + obj.data[item].plist + "\" class=\"plist\">" +
"<td><span class=\"glyphicon glyphicon-list\"></span></td>" +
"<td><a>" + basename(obj.data[item].plist) + "</a></td>" +
"<td></td><td></td></tr>"
);
break;
case "song":
var minutes = Math.floor(obj.data[item].duration / 60);
var seconds = obj.data[item].duration - minutes * 60;
$('#salamisandwich > tbody').append(
"<tr uri=\"" + obj.data[item].uri + "\" class=\"song\">" +
"<td><span class=\"glyphicon glyphicon-music\"></span></td>" +
"<td>" + obj.data[item].title +"</td>" +
"<td>"+ minutes + ":" + (seconds < 10 ? '0' : '') + seconds +
"</td><td></td></tr>"
);
break;
2014-02-22 01:11:45 +00:00
case "wrap":
if(current_app == 'browse') {
$('#next').removeClass('hide');
} else {
$('#salamisandwich > tbody').append(
"<tr><td><span class=\"glyphicon glyphicon-remove\"></span></td>" +
"<td>Too many results, please refine your search!</td>" +
"<td></td><td></td></tr>"
);
}
break;
}
2014-02-22 01:11:45 +00:00
if(pagination > 0)
$('#prev').removeClass('hide');
}
2014-01-17 15:26:26 +00:00
function appendClickableIcon(appendTo, onClickAction, glyphicon) {
$(appendTo).children().last().append(
"<a role=\"button\" class=\"pull-right btn-group-hover\">" +
"<span class=\"glyphicon glyphicon-" + glyphicon + "\"></span></a>")
.find('a').click(function(e) {
e.stopPropagation();
socket.send(onClickAction + "," + $(this).parents("tr").attr("uri"));
$('.top-right').notify({
message:{
text: $('td:nth-child(2)', $(this).parents("tr")).text() + " added"
} }).show();
}).fadeTo('fast',1);
}
$('#salamisandwich > tbody > tr').on({
2014-01-17 15:26:26 +00:00
mouseenter: function() {
if($(this).is(".dir"))
appendClickableIcon($(this), 'MPD_API_ADD_TRACK', 'plus');
else if($(this).is(".song"))
appendClickableIcon($(this), 'MPD_API_ADD_PLAY_TRACK', 'play');
},
click: function() {
2014-02-22 01:11:45 +00:00
switch($(this).attr('class')) {
case 'dir':
app.setLocation("#/browse/0/"+$(this).attr("uri"));
break;
case 'song':
socket.send("MPD_API_ADD_TRACK," + $(this).attr("uri"));
2014-02-22 01:11:45 +00:00
$('.top-right').notify({
message:{
text: $('td:nth-child(2)', this).text() + " added"
}
}).show();
break;
case 'plist':
socket.send("MPD_API_ADD_PLAYLIST," + $(this).attr("uri"));
2014-02-22 01:11:45 +00:00
$('.top-right').notify({
message:{
text: "Playlist " + $('td:nth-child(2)', this).text() + " added"
}
}).show();
break;
}
},
mouseleave: function(){
$(this).children().last().find("a").stop().remove();
}
});
break;
case "state":
updatePlayIcon(obj.data.state);
updateVolumeIcon(obj.data.volume);
if(JSON.stringify(obj) === JSON.stringify(last_state))
break;
current_song.totalTime = obj.data.totalTime;
current_song.currentSongId = obj.data.currentsongid;
var total_minutes = Math.floor(obj.data.totalTime / 60);
var total_seconds = obj.data.totalTime - total_minutes * 60;
var elapsed_minutes = Math.floor(obj.data.elapsedTime / 60);
var elapsed_seconds = obj.data.elapsedTime - elapsed_minutes * 60;
$('#volumeslider').slider(obj.data.volume);
var progress = Math.floor(100*obj.data.elapsedTime/obj.data.totalTime);
$('#progressbar').slider(progress);
$('#counter')
.text(elapsed_minutes + ":" +
(elapsed_seconds < 10 ? '0' : '') + elapsed_seconds + " / " +
total_minutes + ":" + (total_seconds < 10 ? '0' : '') + total_seconds);
$('#salamisandwich > tbody > tr').removeClass('active').css("font-weight", "");
$('#salamisandwich > tbody > tr[trackid='+obj.data.currentsongid+']').addClass('active').css("font-weight", "bold");
if(obj.data.random)
$('#btnrandom').addClass("active")
else
$('#btnrandom').removeClass("active");
if(obj.data.consume)
$('#btnconsume').addClass("active")
else
$('#btnconsume').removeClass("active");
if(obj.data.single)
$('#btnsingle').addClass("active")
else
$('#btnsingle').removeClass("active");
if(obj.data.crossfade)
$('#btncrossfade').addClass("active")
else
$('#btncrossfade').removeClass("active");
if(obj.data.repeat)
$('#btnrepeat').addClass("active")
else
$('#btnrepeat').removeClass("active");
last_state = obj;
break;
2015-04-28 09:08:21 +00:00
case "outputnames":
$('#btn-outputs-block button').remove();
$.each(obj.data, function(id, name){
var btn = $('<button id="btnoutput'+id+'" class="btn btn-default" onclick="toggleoutput(this, '+id+')"><span class="glyphicon glyphicon-volume-up"></span> '+name+'</button>');
btn.appendTo($('#btn-outputs-block'));
});
/* remove cache, since the buttons have been recreated */
last_outputs = '';
break;
case "outputs":
if(JSON.stringify(obj) === JSON.stringify(last_outputs))
break;
$.each(obj.data, function(id, enabled){
if (enabled)
$('#btnoutput'+id).addClass("active");
else
$('#btnoutput'+id).removeClass("active");
});
last_outputs = obj;
break;
case "disconnected":
if($('.top-right').has('div').length == 0)
$('.top-right').notify({
message:{text:"ympd lost connection to MPD "},
type: "danger",
fadeOut: { enabled: true, delay: 1000 },
}).show();
break;
case "update_queue":
if(current_app === 'queue')
2014-02-22 01:11:45 +00:00
socket.send('MPD_API_GET_QUEUE,'+pagination);
break;
2014-01-17 15:26:26 +00:00
case "song_change":
$('#currenttrack').text(" " + obj.data.title);
2014-01-17 15:26:26 +00:00
var notification = "<strong><h4>" + obj.data.title + "</h4></strong>";
if(obj.data.album) {
$('#album').text(obj.data.album);
2014-01-17 15:26:26 +00:00
notification += obj.data.album + "<br />";
}
if(obj.data.artist) {
$('#artist').text(obj.data.artist);
2014-01-17 15:26:26 +00:00
notification += obj.data.artist + "<br />";
}
if ($.cookie("notification") === "true")
songNotify(obj.data.title, obj.data.artist, obj.data.album );
else
$('.top-right').notify({
message:{html: notification},
type: "info",
}).show();
2014-02-04 16:58:10 +00:00
break;
case "mpdhost":
$('#mpdhost').val(obj.data.host);
$('#mpdport').val(obj.data.port);
2014-02-22 01:11:45 +00:00
if(obj.data.passwort_set)
$('#mpd_password_set').removeClass('hide');
2013-11-07 09:09:40 +00:00
break;
case "error":
$('.top-right').notify({
message:{text: obj.data},
type: "danger",
}).show();
default:
break;
}
2013-11-07 09:09:40 +00:00
}
socket.onclose = function(){
2014-02-16 18:46:53 +00:00
console.log("disconnected");
$('.top-right').notify({
message:{text:"Connection to ympd lost, retrying in 3 seconds "},
type: "danger",
onClose: function () {
webSocketConnect();
}
}).show();
}
} catch(exception) {
alert('<p>Error' + exception);
}
2013-11-04 17:18:38 +00:00
}
2013-11-04 23:17:28 +00:00
2013-11-04 17:18:38 +00:00
function get_appropriate_ws_url()
{
var pcol;
var u = document.URL;
/*
/* We open the websocket encrypted if this page came on an
/* https:// url itself, otherwise unencrypted
/*/
if (u.substring(0, 5) == "https") {
pcol = "wss://";
u = u.substr(8);
} else {
pcol = "ws://";
if (u.substring(0, 4) == "http")
u = u.substr(7);
}
u = u.split('#');
return pcol + u[0] + "/ws";
2013-11-04 17:18:38 +00:00
}
2013-11-04 23:17:28 +00:00
var updateVolumeIcon = function(volume)
2013-11-04 17:18:38 +00:00
{
$("#volume-icon").removeClass("glyphicon-volume-off");
$("#volume-icon").removeClass("glyphicon-volume-up");
$("#volume-icon").removeClass("glyphicon-volume-down");
if(volume == 0) {
$("#volume-icon").addClass("glyphicon-volume-off");
} else if (volume < 50) {
$("#volume-icon").addClass("glyphicon-volume-down");
} else {
$("#volume-icon").addClass("glyphicon-volume-up");
}
2013-11-04 17:18:38 +00:00
}
2013-11-04 23:17:28 +00:00
var updatePlayIcon = function(state)
{
$("#play-icon").removeClass("glyphicon-play")
.removeClass("glyphicon-pause");
$('#track-icon').removeClass("glyphicon-play")
.removeClass("glyphicon-pause")
.removeClass("glyphicon-stop");
if(state == 1) { // stop
$("#play-icon").addClass("glyphicon-play");
$('#track-icon').addClass("glyphicon-stop");
} else if(state == 2) { // pause
$("#play-icon").addClass("glyphicon-pause");
$('#track-icon').addClass("glyphicon-play");
} else { // play
$("#play-icon").addClass("glyphicon-play");
$('#track-icon').addClass("glyphicon-pause");
}
2013-11-04 23:17:28 +00:00
}
2014-01-17 15:26:26 +00:00
function updateDB() {
socket.send('MPD_API_UPDATE_DB');
$('.top-right').notify({
message:{text:"Updating MPD Database... "}
}).show();
2013-11-04 17:18:38 +00:00
}
2014-01-17 15:26:26 +00:00
function clickPlay() {
if($('#track-icon').hasClass('glyphicon-stop'))
socket.send('MPD_API_SET_PLAY');
else
socket.send('MPD_API_SET_PAUSE');
}
2013-11-13 14:30:54 +00:00
function basename(path) {
return path.split('/').reverse()[0];
2013-11-13 14:30:54 +00:00
}
2013-11-07 09:09:40 +00:00
$('#btnrandom').on('click', function (e) {
socket.send("MPD_API_TOGGLE_RANDOM," + ($(this).hasClass('active') ? 0 : 1));
2013-11-07 09:09:40 +00:00
});
$('#btnconsume').on('click', function (e) {
socket.send("MPD_API_TOGGLE_CONSUME," + ($(this).hasClass('active') ? 0 : 1));
2013-11-07 09:09:40 +00:00
});
$('#btnsingle').on('click', function (e) {
socket.send("MPD_API_TOGGLE_SINGLE," + ($(this).hasClass('active') ? 0 : 1));
2013-11-07 09:09:40 +00:00
});
$('#btncrossfade').on('click', function(e) {
socket.send("MPD_API_TOGGLE_CROSSFADE," + ($(this).hasClass('active') ? 0 : 1));
});
2013-11-07 09:09:40 +00:00
$('#btnrepeat').on('click', function (e) {
socket.send("MPD_API_TOGGLE_REPEAT," + ($(this).hasClass('active') ? 0 : 1));
2013-11-07 09:09:40 +00:00
});
2015-04-28 09:08:21 +00:00
function toggleoutput(button, id) {
socket.send("MPD_API_TOGGLE_OUTPUT,"+id+"," + ($(button).hasClass('active') ? 0 : 1));
}
$('#btnnotify').on('click', function (e) {
if($.cookie("notification") === "true") {
$.cookie("notification", false);
} else {
Notification.requestPermission(function (permission) {
if(!('permission' in Notification)) {
Notification.permission = permission;
}
if (permission === "granted") {
$.cookie("notification", true, { expires: 424242 });
$('btnnotify').addClass("active");
}
});
}
});
2014-02-04 16:58:10 +00:00
function getHost() {
socket.send('MPD_API_GET_MPDHOST');
function onEnter(event) {
2014-02-04 17:58:05 +00:00
if ( event.which == 13 ) {
2014-02-16 18:46:53 +00:00
confirmSettings();
2014-02-04 17:58:05 +00:00
}
2014-02-04 16:58:10 +00:00
}
$('#mpdhost').keypress(onEnter);
$('#mpdport').keypress(onEnter);
2014-02-16 18:46:53 +00:00
$('#mpd_pw').keypress(onEnter);
$('#mpd_pw_con').keypress(onEnter);
2014-02-04 16:58:10 +00:00
}
$('#search').submit(function () {
app.setLocation("#/search/"+$('#search > div > input').val());
2014-02-22 01:11:45 +00:00
$('#wait').modal('show');
setTimeout(function() {
$('#wait').modal('hide');
}, 10000);
return false;
});
2014-02-22 01:11:45 +00:00
$('.page-btn').on('click', function (e) {
switch ($(this).text()) {
case "Next":
pagination += MAX_ELEMENTS_PER_PAGE;
break;
case "Previous":
pagination -= MAX_ELEMENTS_PER_PAGE;
if(pagination <= 0)
pagination = 0;
break;
}
switch(current_app) {
case "queue":
app.setLocation('#/'+pagination);
break;
case "browse":
app.setLocation('#/browse/'+pagination+'/'+browsepath);
break;
}
e.preventDefault();
});
2015-03-06 11:40:14 +00:00
function addStream() {
if($('#streamurl').val().length > 0) {
socket.send('MPD_API_ADD_TRACK,'+$('#streamurl').val());
}
$('#addstream').modal('hide');
}
2014-02-16 18:46:53 +00:00
function confirmSettings() {
if($('#mpd_pw').val().length + $('#mpd_pw_con').val().length > 0) {
if ($('#mpd_pw').val() !== $('#mpd_pw_con').val())
{
$('#mpd_pw_con').popover('show');
setTimeout(function() {
$('#mpd_pw_con').popover('hide');
}, 2000);
return;
} else
socket.send('MPD_API_SET_MPDPASS,'+$('#mpd_pw').val());
}
2014-02-04 16:58:10 +00:00
socket.send('MPD_API_SET_MPDHOST,'+$('#mpdport').val()+','+$('#mpdhost').val());
2014-02-16 18:46:53 +00:00
$('#settings').modal('hide');
2014-02-04 16:58:10 +00:00
}
2014-03-08 19:33:22 +00:00
$('#mpd_password_set > button').on('click', function (e) {
socket.send('MPD_API_SET_MPDPASS,');
$('#mpd_pw').val("");
$('#mpd_pw_con').val("");
$('#mpd_password_set').addClass('hide');
})
function notificationsSupported() {
return "Notification" in window;
}
function songNotify(title, artist, album) {
/*var opt = {
type: "list",
title: title,
message: title,
items: []
}
if(artist.length > 0)
opt.items.push({title: "Artist", message: artist});
if(album.length > 0)
opt.items.push({title: "Album", message: album});
*/
//chrome.notifications.create(id, options, creationCallback);
var textNotification = "";
if(typeof artist != 'undefined' && artist.length > 0)
textNotification += " " + artist;
if(typeof album != 'undefined' && album.length > 0)
textNotification += "\n " + album;
var notification = new Notification(title, {icon: 'assets/favicon.ico', body: textNotification});
setTimeout(function(notification) {
notification.close();
}, 3000, notification);
}