1
0
mirror of https://github.com/danbee/mpd-client synced 2025-03-04 08:39:09 +00:00

Realtime updates via Server-Sent Events.

This commit is contained in:
Dan Barber 2013-12-06 13:46:58 +00:00
parent 8936d366db
commit e190e97a01
4 changed files with 31 additions and 10 deletions

View File

@ -11,12 +11,19 @@ $(document).ready(function() {
status: status
}),
events: new EventSource('/api/stream'),
queue: new Queue('#queue', {
queueSongs: queueSongs,
status: status
})
};
mpdClient.events.onmessage = function(e) {
newStatus = JSON.parse(e.data);
status.attr(newStatus);
}
status.bind('change', function(event, attr, how, newVal, oldVal) {
if (attr == 'song') {
mpdClient.queueSongs.updatePlaying(oldVal, newVal);

View File

@ -13,10 +13,7 @@ var Transport = can.Control.extend({
var self = this;
can.ajax({
url: '/api/control/' + command,
type: 'PUT',
success: function(status) {
self.updateStatus(status);
}
type: 'PUT'
});
},

View File

@ -1,6 +1,6 @@
class MPDConnection
def self.mpd
@mpd ||= MPD.new
@mpd ||= MPD.new('localhost', 6600, { callbacks: true })
@mpd.connect unless @mpd.connected?
@mpd
end

View File

@ -15,6 +15,8 @@ require './models/song'
class MPDClient < Sinatra::Base
set server: 'thin', connections: []
set :assets_precompile, %w(app.js app.css *.png *.jpg *.svg *.eot *.ttf *.woff)
set :assets_prefix, 'assets'
register Sinatra::AssetPipeline
@ -25,21 +27,34 @@ class MPDClient < Sinatra::Base
erb :index
end
namespace '/api' do
def self.send_status
status = JSON MPDConnection.status
settings.connections.each { |out| out << "data: #{status}\n\n" }
end
before do
content_type 'application/json'
end
MPDConnection.mpd.on(:song) { |song| send_status }
MPDConnection.mpd.on(:state) { |state| send_status }
namespace '/api' do
get '/status' do
JSON MPDConnection.status
end
get '/stream', provides: 'text/event-stream' do
stream :keep_open do |out|
settings.connections << out
out.callback { settings.connections.delete(out) }
end
end
get '/albums' do
content_type 'application/json'
JSON Album.all.map(&:to_h)
end
get '/artists/:artist' do
content_type 'application/json'
JSON Album.by_artist(CGI.unescape(params[:artist])).sort.map(&:to_h)
end
@ -52,23 +67,25 @@ class MPDClient < Sinatra::Base
#end
get '/artists' do
content_type 'application/json'
JSON Artist.all.map(&:to_h)
end
get '/queue' do
content_type 'application/json'
JSON({ data: Song.queue.map(&:to_h) })
end
put '/control/:action' do
if Control.controls.include?(params[:action].to_sym)
Control.send(params[:action])
JSON MPDConnection.status
else
not_found
end
end
put '/control/volume/:value' do
content_type 'application/json'
Control.volume(params[:value])
end