· 6 years ago · Feb 10, 2020, 07:48 PM
1var maxResults = 6;
2var nextPageToken, instanceid, ytapikey, InstanceStatus, ytapi_state = 0;
3
4function tplawesome(e, t) {
5 var res = e;
6 for (var n = 0; n < t.length; n++) {
7 res = res.replace(/\{\{(.*?)\}\}/g, function (e, r) {
8 return t[n][r];
9 });
10 }
11 return res;
12}
13
14function resetVideoHeight() {
15 $(".video").css("height", $("#results").width() * 9 / 16);
16}
17
18function ytinit() {
19 if (ytapi_state == 0) {
20 ytapi_state = 1; // loaded
21 }
22 if (typeof ytapikey != 'undefined') {
23 if (ytapikey.length == 39) {
24 gapi.client.setApiKey(ytapikey);
25 gapi.client.load("youtube", "v3", function () { });
26 ytapi_state = 2;
27 ytapikey = "";
28 console.log("youtube api enabled.");
29 } else {
30 console.log("invalid api key!");
31 sweetAlert('Failed...', "Be sure, that your API Key is correct, and you have no Server API Key instead of a Browser Key!", 'error');
32 }
33 } else {
34 // console.log("no api key set");
35 }
36}
37$(document).ready(function () {
38 var instanceList = $('#dropdown');
39 // Get the list of instances using the currently logged in user account
40 $.ajax({
41 url: '/api/v1/bot/instances',
42 headers: {
43 'Authorization': 'bearer ' + window.localStorage.token
44 },
45 statusCode: {
46 401: function () {
47 swal({
48 title: 'Error',
49 text: "In order for you to access this you have to be logged in.",
50 type: 'warning',
51 confirmButtonColor: '#D9230F',
52 confirmButtonText: 'Webinterface',
53 closeOnConfirm: false
54 }).then(function () {
55 window.location = getRootUrl();
56 });
57 }
58 }
59 }).done(function (data) {
60 data = data.sort(dynamicSort("name"));
61 // get instance from localstorage
62 if (window.localStorage.instanceId != undefined) {
63 if (window.localStorage.instanceId.length == 36) {
64 data.forEach(function (instance) {
65 if (instance.uuid == window.localStorage.instanceId) {
66 instanceid = instance.uuid;
67 getConfig(instance.uuid);
68 $("#dropdb1").html(instance.name ? instance.name : instance.nick);
69 }
70 });
71 }
72 }
73 data.forEach(function (instance) { // go through every instance
74 // append instance list
75 $('<li/>').appendTo(instanceList).html('<a href="#">' + (instance.name ? instance.name : instance.nick) + '</a>').click(function () {
76 window.localStorage.instanceId = instance.uuid;
77 getConfig(instance.uuid);
78 instanceid = instance.uuid;
79 getInstanceStatus();
80 });
81 });
82 getInstanceStatus();
83 setInterval(function () {
84 getInstanceStatus();
85 }, 5000);
86 $('.dropd1 > li > a').click(function () { // apply dropdown selection
87 $("#dropdb1").html($(this).text() + ' <span class="caret"></span>');
88 });
89 });
90 /* infinite scroll */
91 $(window).scroll(function () {
92 if ($(window).scrollTop() == $(document).height() - $(window).height()) {
93 if (typeof nextPageToken !== 'undefined') {
94 moreVideos();
95 }
96 }
97 });
98 /* load more button */
99 $("#loadmore").click(function () {
100 if (typeof nextPageToken !== 'undefined') {
101 moreVideos();
102 }
103 });
104 /* search button */
105 $("form").on("submit", function (e) {
106 e.preventDefault();
107 if (typeof instanceid != 'undefined') {
108 if (ytapi_state == 2) {
109 if ($("#search").val()) {
110 // prepare the request
111 var request = gapi.client.youtube.search.list({
112 part: "snippet",
113 type: "video",
114 q: $("#search").val().replace(" ", "+"),
115 maxResults: maxResults,
116 order: "relevance"
117 });
118 // execute the request
119 request.execute(function (response) {
120 var result = response.result;
121 nextPageToken = result.nextPageToken;
122 $("#results").html("");
123 $.each(result.items, function (index, item) {
124 $.get("src/templates/yt.html", function (data) {
125 $("#results").append(tplawesome(data, [{
126 title: decodeURIComponentSafe(item.snippet.title),
127 videoid: decodeURIComponentSafe(item.id.videoId),
128 channelname: decodeURIComponentSafe(item.snippet.channelTitle.substring(0, 40)),
129 thumbnail: decodeURIComponentSafe(item.snippet.thumbnails.high.url),
130 channelhref: "//www.youtube.com/channel/" + item.snippet.channelId
131 }]));
132 bindThumbEvent();
133 });
134 });
135 resetVideoHeight();
136 $("#loadmore").css("display", "block");
137 });
138 } else {
139 sweetAlert('Error', "You have to type something in the searchbar", 'error');
140 }
141 } else {
142 sweetAlert('YouTube Api Error', "Please make sure that you've set a valid api key in the config and <u>enabled the script on the selected instance</u>.", 'error');
143 }
144 } else {
145 sweetAlert('Error', "Please select an instance before searching", 'error');
146 }
147 });
148 $(window).on("resize", resetVideoHeight);
149 initVolumeBar();
150}); //Document Ready End
151/* get config from a instance */
152function getConfig(instance) {
153 $.ajax({
154 url: '/api/v1/bot/i/' + instance + '/event/ytwebconfig',
155 method: 'POST',
156 headers: {
157 'Content-Type': 'application/json',
158 'Authorization': 'bearer ' + window.localStorage.token
159 },
160 data: '{}'
161 }).done(function (data) {
162 var css;
163 if (!data || data.length == 0) {
164 css = '.play { display: none' + "}\n" + '.download { display: none' + "}\n" + '.enqueue { display: none' + "}\n" + '#spanover5px { display: none' + "}\n";
165 console.log("config not set");
166 } else {
167 ytapikey = data[0].data.ytapikey;
168 if (ytapi_state == 1) { // initialize ytapi if loaded but not already enabled
169 ytinit();
170 } else if (ytapi_state == 2) {
171 console.log("youtube api already enabled.")
172 }
173 css = '.play { display: ' + (data[0].data.play ? 'inline-block' : 'none') + "}\n" + '.download { display: ' + (data[0].data.download ? 'inline-block' : 'none') + "}\n" + '.enqueue { display: ' + (data[0].data.enqueue ? 'inline-block' : 'none') + "}\n";
174 }
175 $("#btn-style").html(css);
176 });
177}
178
179function endplay(url) {
180 if (typeof instanceid !== 'undefined') {
181 $.ajax({
182 url: '/api/v1/bot/i/' + instanceid + '/event/ytplay',
183 method: 'POST',
184 headers: {
185 'Content-Type': 'application/json',
186 'Authorization': 'bearer ' + window.localStorage.token
187 },
188 data: JSON.stringify(url)
189 }).done(function (data) {
190 if (data.length == 0) {
191 enablePlugin();
192 return;
193 }
194 // The result will be an array with answers from the script
195 var answerList = $('#answers');
196 answerList.html('');
197 data.forEach(function (answer) {
198 $('<li/>').appendTo(answerList).text(answer.script + ' returned ' + JSON.stringify(answer.data));
199 });
200 if (data[0].data.includes('not enabled')) {
201 createAlertBox('error', data[0].data);
202 } else {
203 createAlertBox('success', data[0].data);
204 }
205 });
206 } else {
207 selectInstance();
208 }
209}
210
211function endenqueue(url) {
212 if (typeof instanceid !== 'undefined') {
213 $.ajax({
214 url: '/api/v1/bot/i/' + instanceid + '/event/ytenq',
215 method: 'POST',
216 headers: {
217 'Content-Type': 'application/json',
218 'Authorization': 'bearer ' + window.localStorage.token
219 },
220 data: JSON.stringify(url)
221 }).done(function (data) {
222 if (data.length == 0) {
223 enablePlugin();
224 return;
225 }
226 // The result will be an array with answers from the script
227 var answerList = $('#answers');
228 answerList.html('');
229 data.forEach(function (answer) {
230 $('<li/>').appendTo(answerList).text(answer.script + ' returned ' + JSON.stringify(answer.data));
231 });
232 if (data[0].data.includes('not enabled')) {
233 createAlertBox('error', data[0].data);
234 } else {
235 createAlertBox('success', data[0].data);
236 }
237 });
238 } else {
239 selectInstance();
240 }
241}
242
243function enddownload(url) {
244 if (typeof instanceid !== 'undefined') {
245 $.ajax({
246 url: '/api/v1/bot/i/' + instanceid + '/event/ytdl',
247 method: 'POST',
248 headers: {
249 'Content-Type': 'application/json',
250 'Authorization': 'bearer ' + window.localStorage.token
251 },
252 data: JSON.stringify(url)
253 }).done(function (data) {
254 if (data.length == 0) {
255 enablePlugin();
256 return;
257 }
258 // The result will be an array with answers from the script
259 var answerList = $('#answers')
260 answerList.html('');
261 data.forEach(function (answer) {
262 $('<li/>').appendTo(answerList).text(answer.script + ' returned ' + JSON.stringify(answer.data));
263 });
264 if (data[0].data.includes('not enabled')) {
265 createAlertBox('error', data[0].data);
266 } else {
267 createAlertBox('success', data[0].data);
268 }
269 });
270 } else {
271 selectInstance();
272 }
273}
274
275function getRootUrl() {
276 return window.location.origin ? window.location.origin + '/' : window.location.protocol + '/' + window.location.host + '/';
277}
278
279function moreVideos() {
280 $("#loadmorecss").removeClass("none");
281 var request = gapi.client.youtube.search.list({
282 part: "snippet",
283 type: "video",
284 q: $("#search").val().replace(" ", "+"),
285 maxResults: maxResults,
286 pageToken: nextPageToken,
287 order: "relevance"
288 });
289 // execute the request
290 request.execute(function (response) {
291 var result = response.result;
292 nextPageToken = result.nextPageToken;
293 $.each(result.items, function (index, item) {
294 $.get("src/templates/yt.html", function (data) {
295 $("#results").append(tplawesome(data, [{
296 title: decodeURIComponentSafe(item.snippet.title),
297 videoid: decodeURIComponentSafe(item.id.videoId),
298 channelname: decodeURIComponentSafe(item.snippet.channelTitle.substring(0, 40)),
299 thumbnail: decodeURIComponentSafe(item.snippet.thumbnails.high.url),
300 channelhref: "//www.youtube.com/channel/" + item.snippet.channelId
301 }]));
302 bindThumbEvent();
303 });
304 });
305 resetVideoHeight();
306 $("#loadmorecss").addClass("none");
307 });
308}
309
310function dynamicSort(property) {
311 var sortOrder = 1;
312 if (property[0] === "-") {
313 sortOrder = -1;
314 property = property.substr(1);
315 }
316 return function (a, b) {
317 var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
318 return result * sortOrder;
319 }
320}
321
322function enablePlugin() {
323 sweetAlert('Failed...', "Be sure, that you've enabled the script in your Webinterface!", 'error');
324}
325
326function selectInstance() {
327 sweetAlert('Failed...', "Be sure, that you select an instance!", 'error');
328}
329
330function notEnoughPermissions() {
331 sweetAlert('Failed...', "Be sure, that you have enough permissions to execute that action!", 'error');
332}
333
334function createAlertBox(type, text) {
335 // reset classes
336 $('div > #alertscss').removeClass("alert-success");
337 $('div > #alertscss').removeClass("alert-danger");
338 $('div > #alertscss').removeClass("alert-warning");
339 if (type == 'success') {
340 $('div > #alertscss').addClass("alert-success");
341 $('#alertscss > #title').text("Success!");
342 } else if (type == 'error') {
343 $('div > #alertscss').addClass("alert-danger");
344 $('#alertscss > #title').text("Error!");
345 } else if (type == 'warning') {
346 $('div > #alertscss').addClass("alert-warning");
347 $('#alertscss > #title').text("Warning!");
348 } else {
349 return false;
350 }
351 // add text and animate
352 $('#alertscss > #text').text(text);
353 $('#alertscss').fadeIn(400).delay(2000).fadeOut(400);
354 return true;
355}
356
357function bindThumbEvent() {
358 // unbind previous event
359 $('.youtube-thumb, .play-button').unbind('click');
360 // load video when clicking on thumbnail
361 $('.youtube-thumb, .play-button').click(function () {
362 var parent = $(this).parent().parent();
363 var url = '//www.youtube.com/embed/' + parent.data('videoid') + '?autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&showinfo=0';
364 parent.html('<iframe src="' + url + '" frameborder="0" scrolling="no" id="youtube-iframe" allowfullscreen></iframe>');
365 });
366 var prevHeight = 0;
367 var prevElement;
368 var i = 0;
369 $('.videos > h3').each(function () {
370 if (i % 2 == 0) {
371 prevHeight = $(this).innerHeight();
372 prevElement = this;
373 } else {
374 var currHeight = $(this).innerHeight();
375 if (prevHeight > currHeight) {
376 $(this).innerHeight(prevHeight);
377 } else if (prevHeight < currHeight) {
378 $(prevElement).innerHeight(currHeight);
379 }
380 }
381 i++;
382 });
383}
384
385function getInstanceStatus() {
386 if (typeof instanceid != 'undefined') {
387 $.ajax({
388 url: '/api/v1/bot/i/' + instanceid + '/status',
389 method: 'GET',
390 headers: {
391 'Content-Type': 'application/json',
392 'Authorization': 'bearer ' + window.localStorage.token
393 },
394 statusCode: {
395 401: function () {
396 console.log("not enough permissions for getting the status");
397 }
398 }
399 }).done(function (data) {
400 InstanceStatus = data;
401 changeValBtn = document.querySelector('.v-slider');
402 inputRange = changeValBtn.parentNode.querySelector('input[type="range"]');
403 inputRange.value = data.volume;
404 inputRange.dispatchEvent(new Event('change'));
405 if (data.currentTrack != null && typeof data.currentTrack.title != 'undefined') {
406 $('#v-title').text(data.currentTrack.title ? data.currentTrack.title : '');
407 $('#v-artist').text(data.currentTrack.artist ? data.currentTrack.artist : '');
408 } else {
409 $('#v-title').text('');
410 $('#v-artist').text('');
411 }
412 if (data.repeat == true) {
413 $('#v-retweet').addClass('enabled')
414 } else {
415 $('#v-retweet').removeClass('enabled');
416 }
417 if (data.playlistTrack == -1) {
418 $('#v-random').addClass('enabled')
419 } else {
420 if (data.shuffle == true) {
421 nbr = 0;
422 $('#v-random').addClass('enabled')
423 } else {
424 nbr = 1;
425 $('#v-random').removeClass('enabled')
426 }
427 }
428 if (data.playing == true) {
429 $('#va-play').removeClass("glyphicon-play").addClass("glyphicon-stop");
430 } else {
431 $('#va-play').removeClass("glyphicon-stop").addClass("glyphicon-play");
432 }
433 });
434 }
435}
436
437function initVolumeBar() {
438 var selector = '[data-rangeSlider]',
439 elements = document.querySelectorAll(selector);
440 rangeSlider.create(elements, {
441 onInit: function () { },
442 onSlideEnd: function (value, percent, position) {
443 $.ajax({
444 url: '/api/v1/bot/i/' + instanceid + '/volume/set/' + value,
445 method: 'POST',
446 headers: {
447 'Content-Type': 'application/json',
448 'Authorization': 'bearer ' + window.localStorage.token
449 },
450 statusCode: {
451 401: function () {
452 notEnoughPermissions();
453 },
454 403: function () {
455 notEnoughPermissions();
456 }
457 }
458 }).done(function (data) {
459 getInstanceStatus();
460 });
461 }
462 });
463}
464// Control events
465function vforward() {
466 $.ajax({
467 url: '/api/v1/bot/i/' + instanceid + '/playNext',
468 method: 'POST',
469 headers: {
470 'Content-Type': 'application/json',
471 'Authorization': 'bearer ' + window.localStorage.token
472 },
473 statusCode: {
474 401: function () {
475 notEnoughPermissions();
476 },
477 403: function () {
478 notEnoughPermissions();
479 }
480 }
481 });
482 getInstanceStatus();
483}
484
485function vbackward() {
486 $.ajax({
487 url: '/api/v1/bot/i/' + instanceid + '/playPrevious',
488 method: 'POST',
489 headers: {
490 'Content-Type': 'application/json',
491 'Authorization': 'bearer ' + window.localStorage.token
492 },
493 statusCode: {
494 401: function () {
495 notEnoughPermissions();
496 },
497 403: function () {
498 notEnoughPermissions();
499 }
500 }
501 });
502 getInstanceStatus();
503}
504
505function vplay() {
506 if (InstanceStatus.playing == true) {
507 $('#va-play').removeClass("glyphicon-stop").addClass("glyphicon-play");
508 $.ajax({
509 url: '/api/v1/bot/i/' + instanceid + '/pause',
510 method: 'POST',
511 headers: {
512 'Content-Type': 'application/json',
513 'Authorization': 'bearer ' + window.localStorage.token
514 },
515 statusCode: {
516 401: function () {
517 notEnoughPermissions();
518 },
519 403: function () {
520 notEnoughPermissions();
521 }
522 }
523 });
524 } else {
525 $('#va-play').removeClass("glyphicon-play").addClass("glyphicon-stop");
526 $.ajax({
527 url: '/api/v1/bot/i/' + instanceid + '/play/byId/' + InstanceStatus.currentTrack.uuid,
528 method: 'POST',
529 headers: {
530 'Content-Type': 'application/json',
531 'Authorization': 'bearer ' + window.localStorage.token
532 },
533 statusCode: {
534 401: function () {
535 notEnoughPermissions();
536 },
537 403: function () {
538 notEnoughPermissions();
539 }
540 }
541 });
542 }
543 getInstanceStatus();
544}
545
546function vshuffle() {
547 if (InstanceStatus.playlistTrack == -1) {
548 $('#v-random').addClass('enabled')
549 } else {
550 if (InstanceStatus.shuffle == true) {
551 nbr = 0;
552 $('#v-random').addClass('enabled')
553 } else {
554 nbr = 1;
555 $('#v-random').removeClass('enabled')
556 }
557 }
558 if (InstanceStatus.playlistTrack != -1) {
559 $.ajax({
560 url: '/api/v1/bot/i/' + instanceid + '/shuffle/' + nbr,
561 method: 'POST',
562 headers: {
563 'Content-Type': 'application/json',
564 'Authorization': 'bearer ' + window.localStorage.token
565 },
566 statusCode: {
567 401: function () {
568 notEnoughPermissions();
569 },
570 403: function () {
571 notEnoughPermissions();
572 }
573 }
574 });
575 } else {
576 swal("Warning...", "Shuffle cannot be deactivated if no playlist is active.", "warning")
577 }
578 getInstanceStatus();
579}
580
581function vrepeat() {
582 if (InstanceStatus.repeat == true) {
583 nbr = 0;
584 $('#v-retweet').removeClass('enabled');
585 } else {
586 nbr = 1;
587 $('#v-retweet').addClass('enabled');
588 }
589 $.ajax({
590 url: '/api/v1/bot/i/' + instanceid + '/repeat/' + nbr,
591 method: 'POST',
592 headers: {
593 'Content-Type': 'application/json',
594 'Authorization': 'bearer ' + window.localStorage.token
595 },
596 statusCode: {
597 401: function () {
598 notEnoughPermissions();
599 },
600 403: function () {
601 notEnoughPermissions();
602 }
603 }
604 });
605 getInstanceStatus();
606}
607
608function decodeURIComponentSafe(uri) {
609 var out = new String(),
610 arr = uri.split(/(%(?:d0|d1)%.{2})/),
611 i = 0,
612 l,
613 x;
614 for (l = arr.length; i < l; i++) {
615 try {
616 x = decodeURIComponent(arr[i]);
617 } catch (err) {
618 x = arr[i];
619 }
620 out += x;
621 }
622 return out;
623}