fix
[wolnelektury.git] / src / catalogue / static / player / player.js
1 (function($) {
2     $(function() {
3
4         $(".book-right-column").remove();
5
6         if ($("#player-bar").length) {
7             $("#book-text-buttons").append(
8                 $("<a class='enable-player-bar'><i class='icon icon-play'></i> zacznij słuchać</a>")
9             ).show();
10         }
11         
12         $(".enable-player-bar").click(function() {
13             
14             $('body').addClass('with-player-bar');
15             $('.jp-play').click();
16             return false;
17         })
18
19                                       
20         var smil = $("#smil").text();
21         if (smil) {
22             smil = $.parseJSON(smil);
23
24             $.each(smil, function(i, e) {
25                 $('#' + e).addClass('syncable');
26             })
27         }
28
29
30         scrolling = false;
31         /*$(window).on('scroll', function() {
32             if (!scrolling) {
33                 $("#locator").removeClass('snap');
34             }
35         });*/
36
37         lastscroll = null;
38         
39         scrollTo = function() {
40             if (!scrolling && $('.playing-highlight').length && $('.playing-highlight')[0] != lastscroll) {
41                 lastscroll = $('.playing-highlight')[0];
42                 scrolling = true;
43                 $("html").animate({
44                     scrollTop: $('.playing-highlight').offset().top,
45                 }, {
46                     duration: 2000,
47                     done: function() {
48                         scrolling = false;
49                         
50                     },
51                 });
52             }
53         }
54
55         
56         $.jPlayer.timeFormat.showHour = true;
57
58         $(".jp-jplayer").each(function() {
59             var $self = $(this);
60             
61             var $root = $self.parent();
62             var $currentMedia = null
63             var currentDuration = 0;
64             var speed = 1;
65             var totalDurationLeft = 0;
66             var totalDurationBefore = 0;
67             var lastUpdate = 0;
68             var player = null;
69             var doesUpdateSynchro = true;
70
71             // TODO: will need class for attach
72             // may be added from sync data
73
74
75             $(".zakladka-tool_sluchaj").click(function() {
76                 $('body').addClass('with-player-bar');
77                 let id = $(this).data('sync');
78                 if (!id) return;
79                 for (let i=0; i<smil.length; ++i) {
80                     if (smil[i][0] == id) {
81                         setMediaFromTime(smil[i][1], 'play');
82                         //player.jPlayer('play');
83                         return;
84                     }
85                 }
86             });
87
88             var setMediaFromTime = function(time, cmd='pause') {
89                 $('.jp-playlist li', $root).each((i, e) => {
90                     d = parseFloat($(e).data('duration'));
91                     if (time < d) {
92                         setMedia($(e), time, cmd);
93                         return false
94                     } else {
95                         time -= d;
96                     }
97                 })
98             }
99             
100             var setMedia = function(elem, time=0, cmd='pause') {
101                 var media = {}
102
103                 media['mp3'] = elem.attr('data-mp3');
104                 media['oga'] = elem.attr('data-ogg');
105                 media['id'] = elem.attr('data-media-id');
106
107                 $(".c-player__head", $root).html(
108                     $(".attribution", elem).html())
109                 ;
110                 $(".c-player__info", $root).html(
111                     $(".title", elem).html()
112                 );
113                 $(".c-media__caption .content", $root).html($(".project-description", elem).html());
114                 $(".c-media__caption .license", $root).html($(".license", elem).html());
115                 $(".c-media__caption .project-logo", $root).html($(".project-icon", elem).html());
116
117                 console.log('sm 1');
118                 doesUpdateSynchro = false;
119                 if (!$currentMedia || $currentMedia[0] != elem[0]) {
120                     console.log('set', player.jPlayer("setMedia", media))
121                     player.jPlayer("option", "playbackRate", speed);
122                 }
123                 doesUpdateSynchro = true;
124                 player.jPlayer(cmd, time);
125
126                 $currentMedia = elem;
127                 $(".play-next", $root).prop("disabled", !elem.next().length);
128
129                 let du = parseFloat(elem.data('duration'));
130                 currentDuration = du;
131                 elem.nextAll().each(function() {
132                     du += parseFloat($(this).data('duration'));
133                 });
134                 totalDurationLeft = du;
135
136                 let pdu = 0;
137                 elem.prevAll().each(function() {
138                     pdu += parseFloat($(this).data('duration'));
139                 });
140                 totalDurationBefore = pdu;
141                 console.log('sm 3', du, pdu);
142
143                 return player;
144             };
145
146
147             var updateSynchrotext = function(position) {
148                 if (!doesUpdateSynchro) return;
149                 
150                 let curElemId = null;
151                 for (let i=0; i<smil.length; ++i) {
152                     // can faster
153                     if (smil[i][1] <= position) curElemId = smil[i][0];
154                     else break;
155                 }
156                 $(".playing-highlight").removeClass("playing-highlight");
157                 if (curElemId !== null) {
158                     let curElem = $("#" + curElemId);
159                     curElem.addClass("playing-highlight");
160
161                     let miny = window.scrollY;
162                     let maxy = miny + window.innerHeight;
163                     let y = curElem.offset().top;
164
165                     let locator = $("#locator");
166                     // TODO: if snap then roll
167                     locator.removeClass('up').removeClass('down');
168                     if (locator.hasClass('snap')) {
169                         console.log('SCROLL!');
170                         scrollTo();
171                     } else {
172                         if (y < miny) {
173                             locator.addClass('up');
174                         }
175                         if (y > maxy) {
176                             locator.addClass('down');
177                         }
178                     }
179                 }
180             }
181             
182         $self.jPlayer({
183             swfPath: "/static/js/contrib/jplayer/",
184             solution: "html,flash",
185             supplied: 'oga,mp3',
186             cssSelectorAncestor: "#" + $self.attr("data-player"),
187             useStateClassSkin: true,
188
189             ready: function() {
190                 player = $(this);
191
192                 let selectItem = $('.c-select li');
193                 selectItem.on('click', function() {
194                     let speedStr = $(this).data('speed');
195                     speed = parseFloat(speedStr);
196                     player.jPlayer("option", "playbackRate", speed);
197                     localStorage['audiobook-speed'] = speedStr;
198                     _paq.push(['trackEvent', 'audiobook', 'speed', speedStr]);
199                 });
200                 
201                 $('.jp-play', $root).click(function() {
202                     _paq.push(['trackEvent', 'audiobook', 'play']);
203                 });
204                 $('.jp-seek-bar', $root).click(function() {
205                     _paq.push(['trackEvent', 'audiobook', 'seek']);
206                 });
207                 $('.jp-mute', $root).click(function() {
208                     _paq.push(['trackEvent', 'audiobook', 'mute']);
209                 });
210                 $('.jp-volume-bar', $root).click(function() {
211                     _paq.push(['trackEvent', 'audiobook', 'volume']);
212                 });
213
214                 $('.play-next', $root).click(function() {
215                     let p = $currentMedia.next();
216                     if (p.length) {
217                         setMedia(p).jPlayer("play");
218                         _paq.push(['trackEvent', 'audiobook', 'next']);
219                     }
220                 });
221                 $('.play-prev', $root).click(function() {
222                     let p = $currentMedia.prev();
223                     if (p.length) {
224                         setMedia(p).jPlayer("play");
225                         _paq.push(['trackEvent', 'audiobook', 'prev']);
226                     } else {
227                         // If in first part, restart it.
228                         setMedia($currentMedia).jPlayer("play");
229                         _paq.push(['trackEvent', 'audiobook', 'rewind']);
230                     }
231                 });
232
233                 $('.jp-playlist li', $root).click(function() {
234                     setMedia($(this)).jPlayer("play");
235                     $('.c-player__chapters').removeClass('is-active');
236                     _paq.push(['trackEvent', 'audiobook', 'chapter']);
237                 });
238
239                 console.log('READY 3!');
240                 var initialElem = $('.jp-playlist li', $root).first();
241                 var initialTime = 0;
242                 console.log('READY 4!');
243                 if (true || Modernizr.localstorage) {
244                     try {
245                         let speedStr = localStorage['audiobook-speed'];
246                         if (speedStr) {
247                             speed = parseFloat(speedStr);
248                             $(".speed .is-active").removeClass("is-active");
249                             $(".speed [data-speed='" + speedStr + "']").addClass("is-active");
250                         }
251                     } catch {}
252
253                     try {
254                         audiobooks = JSON.parse(localStorage["audiobook-history"]);
255                     } catch {
256                         audiobooks = {};
257                     }
258                     last = audiobooks[$root.attr("data-book-slug")]
259                     // Fallback for book id;
260                     if (!last) {
261                         last = audiobooks[$root.attr("data-book-id")]
262                     }
263
264                     if (last) {
265                         initialElem = $('[data-media-id="' + last[1] + '"]', $root).first();
266                         initialTime = last[2];
267                     }
268                 }
269                 console.log('READY 5!', initialElem, initialTime);
270                 setMedia($(initialElem), initialTime);
271                 console.log('READY 6!');
272             },
273
274             timeupdate: function(event) {
275                 t = event.jPlayer.status.currentTime;
276
277                 updateSynchrotext(totalDurationBefore + t);
278                 
279                 
280                 ttl = (totalDurationLeft - t) / speed;
281                 ttl = $.jPlayer.convertTime(ttl);
282                 $(".total-time-left").text('Czas do końca: ' + ttl);
283
284                 $(".time-left").text('– ' + $.jPlayer.convertTime(
285                     currentDuration - t,
286                 ));
287                 
288                 
289                 if (Math.abs(t - lastUpdate) > 3) {
290                     try {
291                         audiobooks = JSON.parse(localStorage["audiobook-history"]);
292                     } catch {
293                         audiobooks = {};
294                     }
295                     if (t && event.jPlayer.status.duration - t > 10) {
296                         audiobooks[$root.attr("data-book-slug")] = [
297                             Date.now(),
298                             event.jPlayer.status.media.id,
299                             event.jPlayer.status.currentTime
300                         ];
301                     } else {
302                         delete audiobooks[$root.attr("data-book-slug")];
303                     }
304                     // Remove old book id, if present.
305                     delete audiobooks[$root.attr("data-book-id")];
306                     localStorage["audiobook-history"] = JSON.stringify(audiobooks);
307                     lastUpdate = t;
308                 }
309             },
310
311
312             ended: function(event) {
313                 let p = $currentMedia.next();
314                 if (p.length) {
315                     setMedia(p).jPlayer("play");
316                 }
317             }
318         });
319       });
320
321
322    $('#locator').on('click', function() {
323        $(this).toggleClass('snap');
324        lastscroll = null;
325    });
326
327         
328
329     });
330 })(jQuery)