Debian Codegraph @

beetsplug/web/static/beets.js

raw
1 // Format times as minutes and seconds.
2 var timeFormat = function(secs) {
3 if (secs == undefined || isNaN(secs)) {
4 return '0:00';
5 }
6 secs = Math.round(secs);
7 var mins = '' + Math.floor(secs / 60);
8 secs = '' + (secs % 60);
9 if (secs.length < 2) {
10 secs = '0' + secs;
11 }
12 return mins + ':' + secs;
13 }
14
15 // jQuery extension encapsulating event hookups for audio element controls.
16 $.fn.player = function(debug) {
17 // Selected element should contain an HTML5 Audio element.
18 var audio = $('audio', this).get(0);
19
20 // Control elements that may be present, identified by class.
21 var playBtn = $('.play', this);
22 var pauseBtn = $('.pause', this);
23 var disabledInd = $('.disabled', this);
24 var timesEl = $('.times', this);
25 var curTimeEl = $('.currentTime', this);
26 var totalTimeEl = $('.totalTime', this);
27 var sliderPlayedEl = $('.slider .played', this);
28 var sliderLoadedEl = $('.slider .loaded', this);
29
30 // Button events.
31 playBtn.click(function() {
32 audio.play();
33 });
34 pauseBtn.click(function(ev) {
35 audio.pause();
36 });
37
38 // Utilities.
39 var timePercent = function(cur, total) {
40 if (cur == undefined || isNaN(cur) ||
41 total == undefined || isNaN(total) || total == 0) {
42 return 0;
43 }
44 var ratio = cur / total;
45 if (ratio > 1.0) {
46 ratio = 1.0;
47 }
48 return (Math.round(ratio * 10000) / 100) + '%';
49 }
50
51 // Event helpers.
52 var dbg = function(msg) {
53 if (debug)
54 console.log(msg);
55 }
56 var showState = function() {
57 if (audio.duration == undefined || isNaN(audio.duration)) {
58 playBtn.hide();
59 pauseBtn.hide();
60 disabledInd.show();
61 timesEl.hide();
62 } else if (audio.paused) {
63 playBtn.show();
64 pauseBtn.hide();
65 disabledInd.hide();
66 timesEl.show();
67 } else {
68 playBtn.hide();
69 pauseBtn.show();
70 disabledInd.hide();
71 timesEl.show();
72 }
73 }
74 var showTimes = function() {
75 curTimeEl.text(timeFormat(audio.currentTime));
76 totalTimeEl.text(timeFormat(audio.duration));
77
78 sliderPlayedEl.css('width',
79 timePercent(audio.currentTime, audio.duration));
80
81 // last time buffered
82 var bufferEnd = 0;
83 for (var i = 0; i < audio.buffered.length; ++i) {
84 if (audio.buffered.end(i) > bufferEnd)
85 bufferEnd = audio.buffered.end(i);
86 }
87 sliderLoadedEl.css('width',
88 timePercent(bufferEnd, audio.duration));
89 }
90
91 // Initialize controls.
92 showState();
93 showTimes();
94
95 // Bind events.
96 $('audio', this).bind({
97 playing: function() {
98 dbg('playing');
99 showState();
100 },
101 pause: function() {
102 dbg('pause');
103 showState();
104 },
105 ended: function() {
106 dbg('ended');
107 showState();
108 },
109 progress: function() {
110 dbg('progress ' + audio.buffered);
111 },
112 timeupdate: function() {
113 dbg('timeupdate ' + audio.currentTime);
114 showTimes();
115 },
116 durationchange: function() {
117 dbg('durationchange ' + audio.duration);
118 showState();
119 showTimes();
120 },
121 loadeddata: function() {
122 dbg('loadeddata');
123 },
124 loadedmetadata: function() {
125 dbg('loadedmetadata');
126 }
127 });
128 }
129
130 // Simple selection disable for jQuery.
131 // Cut-and-paste from:
132 // https://stackoverflow.com/questions/2700000
133 $.fn.disableSelection = function() {
134 $(this).attr('unselectable', 'on')
135 .css('-moz-user-select', 'none')
136 .each(function() {
137 this.onselectstart = function() { return false; };
138 });
139 };
140
141 $(function() {
142
143 // Routes.
144 var BeetsRouter = Backbone.Router.extend({
145 routes: {
146 "item/query/:query": "itemQuery",
147 },
148 itemQuery: function(query) {
149 var queryURL = query.split(/\s+/).map(encodeURIComponent).join('/');
150 $.getJSON('item/query/' + queryURL, function(data) {
151 var models = _.map(
152 data['results'],
153 function(d) { return new Item(d); }
154 );
155 var results = new Items(models);
156 app.showItems(results);
157 });
158 }
159 });
160 var router = new BeetsRouter();
161
162 // Model.
163 var Item = Backbone.Model.extend({
164 urlRoot: 'item'
165 });
166 var Items = Backbone.Collection.extend({
167 model: Item
168 });
169
170 // Item views.
171 var ItemEntryView = Backbone.View.extend({
172 tagName: "li",
173 template: _.template($('#item-entry-template').html()),
174 events: {
175 'click': 'select',
176 'dblclick': 'play'
177 },
178 initialize: function() {
179 this.playing = false;
180 },
181 render: function() {
182 $(this.el).html(this.template(this.model.toJSON()));
183 this.setPlaying(this.playing);
184 return this;
185 },
186 select: function() {
187 app.selectItem(this);
188 },
189 play: function() {
190 app.playItem(this.model);
191 },
192 setPlaying: function(val) {
193 this.playing = val;
194 if (val)
195 this.$('.playing').show();
196 else
197 this.$('.playing').hide();
198 }
199 });
200 //Holds Title, Artist, Album etc.
201 var ItemMainDetailView = Backbone.View.extend({
202 tagName: "div",
203 template: _.template($('#item-main-detail-template').html()),
204 events: {
205 'click .play': 'play',
206 },
207 render: function() {
208 $(this.el).html(this.template(this.model.toJSON()));
209 return this;
210 },
211 play: function() {
212 app.playItem(this.model);
213 }
214 });
215 // Holds Track no., Format, MusicBrainz link, Lyrics, Comments etc.
216 var ItemExtraDetailView = Backbone.View.extend({
217 tagName: "div",
218 template: _.template($('#item-extra-detail-template').html()),
219 render: function() {
220 $(this.el).html(this.template(this.model.toJSON()));
221 return this;
222 }
223 });
224 // Main app view.
225 var AppView = Backbone.View.extend({
226 el: $('body'),
227 events: {
228 'submit #queryForm': 'querySubmit',
229 },
230 querySubmit: function(ev) {
231 ev.preventDefault();
232 router.navigate('item/query/' + encodeURIComponent($('#query').val()), true);
233 },
234 initialize: function() {
235 this.playingItem = null;
236 this.shownItems = null;
237
238 // Not sure why these events won't bind automatically.
239 this.$('audio').bind({
240 'play': _.bind(this.audioPlay, this),
241 'pause': _.bind(this.audioPause, this),
242 'ended': _.bind(this.audioEnded, this)
243 });
244 if ("mediaSession" in navigator) {
245 navigator.mediaSession.setActionHandler("nexttrack", () => {
246 this.playNext();
247 });
248 }
249 },
250 showItems: function(items) {
251 this.shownItems = items;
252 $('#results').empty();
253 items.each(function(item) {
254 var view = new ItemEntryView({model: item});
255 item.entryView = view;
256 $('#results').append(view.render().el);
257 });
258 },
259 selectItem: function(view) {
260 // Mark row as selected.
261 $('#results li').removeClass("selected");
262 $(view.el).addClass("selected");
263
264 // Show main and extra detail.
265 var mainDetailView = new ItemMainDetailView({model: view.model});
266 $('#main-detail').empty().append(mainDetailView.render().el);
267
268 var extraDetailView = new ItemExtraDetailView({model: view.model});
269 $('#extra-detail').empty().append(extraDetailView.render().el);
270 },
271 playItem: function(item) {
272 var url = 'item/' + item.get('id') + '/file';
273 $('#player audio').attr('src', url);
274 $('#player audio').get(0).play().then(() => {
275 this.updateMediaSession(item);
276 });
277
278 if (this.playingItem != null) {
279 this.playingItem.entryView.setPlaying(false);
280 }
281 item.entryView.setPlaying(true);
282 this.playingItem = item;
283 },
284
285 updateMediaSession: function (item) {
286 if ("mediaSession" in navigator) {
287 const album_id = item.get("album_id");
288 const album_art_url = "album/" + album_id + "/art";
289 navigator.mediaSession.metadata = new MediaMetadata({
290 title: item.get("title"),
291 artist: item.get("artist"),
292 album: item.get("album"),
293 artwork: [
294 { src: album_art_url, sizes: "96x96" },
295 { src: album_art_url, sizes: "128x128" },
296 { src: album_art_url, sizes: "192x192" },
297 { src: album_art_url, sizes: "256x256" },
298 { src: album_art_url, sizes: "384x384" },
299 { src: album_art_url, sizes: "512x512" },
300 ],
301 });
302 }
303 },
304
305 audioPause: function() {
306 this.playingItem.entryView.setPlaying(false);
307 },
308 audioPlay: function() {
309 if (this.playingItem != null)
310 this.playingItem.entryView.setPlaying(true);
311 },
312 audioEnded: function() {
313 this.playingItem.entryView.setPlaying(false);
314 this.playNext();
315 },
316 playNext: function(){
317 // Try to play the next track.
318 var idx = this.shownItems.indexOf(this.playingItem);
319 if (idx == -1) {
320 // Not in current list.
321 return;
322 }
323 var nextIdx = idx + 1;
324 if (nextIdx >= this.shownItems.size()) {
325 // End of list.
326 return;
327 }
328 this.playItem(this.shownItems.at(nextIdx));
329 }
330 });
331 var app = new AppView();
332
333 // App setup.
334 Backbone.history.start({pushState: false});
335
336 // Disable selection on UI elements.
337 $('#entities ul').disableSelection();
338 $('#header').disableSelection();
339
340 // Audio player setup.
341 $('#player').player();
342
343 });