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