-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsfd-compare.js
2622 lines (2268 loc) · 96.2 KB
/
csfd-compare.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name ČSFD Compare
// @version 0.6.0.1
// @namespace csfd.cz
// @description Show your own ratings on other users ratings list
// @author Jan Verner <[email protected]>
// @license GNU GPLv3
// @match http*://www.csfd.cz/*
// @match http*://www.csfd.sk/*
// @icon http://img.csfd.cz/assets/b1733/images/apple_touch_icon.png
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_listValues
// @run-at document-start
// ==/UserScript==
const VERSION = 'v0.6.0.1';
const SCRIPTNAME = 'CSFD-Compare';
const SETTINGSNAME = 'CSFD-Compare-settings';
const GREASYFORK_URL = 'https://greasyfork.org/cs/scripts/425054-%C4%8Dsfd-compare';
const SETTINGSNAME_HIDDEN_BOXES = 'CSFD-Compare-hiddenBoxes';
const NUM_RATINGS_PER_PAGE = 50; // Was 100, now it's 50...
let defaultSettings = {
// HOME PAGE
hiddenSections: [],
// GLOBAL
showControlPanelOnHover: true,
clickableHeaderBoxes: true,
clickableMessages: true,
addStars: true,
// USER
displayMessageButton: true,
displayFavoriteButton: true,
hideUserControlPanel: true,
compareUserRatings: true,
// FILM/SERIES
addRatingsDate: false,
showLinkToImage: true,
ratingsEstimate: true,
ratingsFromFavorites: true,
addRatingsComputedCount: true,
hideSelectedUserReviews: false,
hideSelectedUserReviewsList: [],
// ACTORS
showOnOneLine: false,
// EXPERIMENTAL
loadComputedRatings: false,
addChatReplyButton: false,
};
class Api {
async getCurrentPageRatings(url) {
const response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
},
body: JSON.stringify({
Ids: [9499, 563036, 123],
}),
});
console.log("response", response);
const data = await response.json();
console.log("data", data);
return data;
}
}
/**
* Check if settings are valid. If not, reset them.
* Return either unmodified or modified settings
* @param {*} settings - LocalStorage settings current value
* @param {string} settingsName - Settings Name
*/
async function checkSettingsValidity(settings, settingsName) {
if (settingsName === SETTINGSNAME_HIDDEN_BOXES) {
const isArray = Array.isArray(settings);
let keysValid = true;
settings.forEach(element => {
const keys = Object.keys(element);
if (keys.length !== 2) {
keysValid = false;
}
});
if (!isArray || !keysValid) {
settings = defaultSettings.hiddenSections;
localStorage.setItem(SETTINGSNAME_HIDDEN_BOXES, JSON.stringify(settings));
}
}
return settings;
}
/**
* This function returns a promise that will resolve after "t" milliseconds
*/
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
async function getSettings(settingsName = SETTINGSNAME) {
if (!localStorage[settingsName]) {
if (settingsName === SETTINGSNAME_HIDDEN_BOXES) {
defaultSettings = [];
}
console.log(`ADDDING DEFAULTS: ${defaultSettings}`);
localStorage.setItem(settingsName, JSON.stringify(defaultSettings));
return defaultSettings;
} else {
return JSON.parse(localStorage[settingsName]);
}
}
async function refreshTooltips() {
try {
tippy('[data-tippy-content]', {
// interactive: true,
popperOptions: { modifiers: { computeStyle: { gpuAcceleration: false } } }
});
} catch (err) {
console.log("Error: refreshTooltips():", err);
}
}
/**
* Take a list of dictionaries and return merged dictionary
* @param {*} list
* @returns
*/
async function mergeDict(list) {
const merged = list.reduce(function (r, o) {
Object.keys(o).forEach(function (k) { r[k] = o[k]; });
return r;
}, {});
return merged;
}
async function onHomepage() {
let check = false;
if (document.location.pathname === '/') {
check = true;
}
return check;
}
(async () => {
"use strict";
/* globals jQuery, $, waitForKeyElements */
/* jshint -W069 */
/* jshint -W083 */
/* jshint -W075 */
class Csfd {
constructor(csfdPage) {
this.csfdPage = csfdPage;
this.stars = {};
this.storageKey = undefined;
this.userUrl = undefined;
this.endPageNum = 0;
this.userRatingsCount = 0;
this.userRatingsUrl = undefined;
this.localStorageRatingsCount = 0;
this.settings = undefined;
this.RESULT = {};
// Ignore the ads... Make 'hodnoceni' table wider.
// TODO: Toto do hodnoceni!
$('.column.column-80').attr('class', '.column column-90');
}
async isLoggedIn() {
const $profile = $('.profile.initialized');
return $profile.length > 0;
}
/**
* @async
* @returns {Promise<string>} - User URL (e.g. /uzivatel/123456-adam-strong/)
*/
async getCurrentUser() {
let loggedInUser = $('.profile.initialized').attr('href');
if (loggedInUser !== undefined) {
if (loggedInUser.length == 1) {
loggedInUser = loggedInUser[0];
}
}
if (typeof loggedInUser === 'undefined') {
console.log("Trying again...");
// [OLD Firefox] workaround (the first returns undefined....?)
let profile = document.querySelectorAll('.profile');
if (profile.length == 0) {
return undefined;
}
loggedInUser = profile[0].getAttribute('href');
if (typeof loggedInUser === 'undefined') {
console.error(`${SCRIPTNAME}: Can't find logged in username...`);
throw (`${SCRIPTNAME}: exit`); // TODO: Popup informing user
}
}
return loggedInUser;
}
/**
* @async
* @returns {Promise<string>} - Username (e.g. adam-strong)
*/
async getUsername() {
const userHref = await this.getCurrentUser();
if (userHref === undefined) {
return undefined;
}
// get 'songokussj' from '/uzivatel/78145-songokussj/' with regex
// get 'sans-sourire' from '/uzivatel/714142-sans-sourire/' with regex
const foundMatch = userHref.match(new RegExp(/\/(\d+-(.*)+)\//));
if (foundMatch.length == 3) {
return foundMatch[2];
}
return undefined;
}
getStars() {
// TODO: remove this function and use getLocalStorageRatings() instead
if (!localStorage[this.storageKey] || localStorage[this.storageKey] === 'undefined') {
return {};
}
return JSON.parse(localStorage[this.storageKey]);
}
async getLocalStorageRatings() {
if (!localStorage[this.storageKey] || localStorage[this.storageKey] === 'undefined') {
return {};
}
return JSON.parse(localStorage[this.storageKey]);
}
/**
* Get ratings from LocalStorage and return the count of:
* - normally rated (user clicked on rating)
* - and computed ratings (not shown in user ratings)
*
* @returns {Promise<Object<string, number>>} `{ computed: int, rated: int }`
*/
async getLocalStorageRatingsCount() {
const ratings = await this.getLocalStorageRatings();
const computedCount = Object.values(ratings).filter(rating => rating.computed).length;
const ratedCount = Object.keys(ratings).length - computedCount;
return {
computed: computedCount,
rated: ratedCount,
};
}
/**
*
* @returns {str} Current movie: `<MovieId>-<MovieUrlTitle>`
*
* Example:
* - https://www.csfd.sk/film/739784-star-trek-lower-decks/prehlad/ --> `739784-star-trek-lower-decks`
* - https://www.csfd.cz/film/1032817-naomi/1032819-don-t-believe-everything-you-think/recenze/ --> `1032819-don-t-believe-everything-you-think`
*/
getCurrentFilmUrl() {
const foundMatch = $('meta[property="og:url"]').attr('content').match(/\d+-[\w-]+/ig);
// TODO: getCurrentFilmUrl by melo vrátit film URL ne jen cast... ne?
if (!foundMatch) {
console.error("TODO: getCurrentFilmUrl() Film URL wasn't found...");
throw (`${SCRIPTNAME} Exiting...`);
}
return foundMatch[foundMatch.length - 1];
}
/**
*
* @returns {str} Current movie: https://www.csfd.sk/film/739784-star-trek-lower-decks/recenze/
*
*/
getCurrentFilmFullUrl() {
const foundMatch = $('meta[property="og:url"]').attr('content');
// TODO: getCurrentFilmFullUrl by melo vrátit film URL ne jen cast... ne?
if (!foundMatch) {
console.error("TODO: getCurrentFilmFullUrl() Film URL wasn't found...");
return "";
}
return foundMatch;
}
/**
* Return current movie Type (film, serial, episode)
*
* @returns {str} Current movie type: film, serial, episode, movie, ...
*/
getCurrentFilmType() {
const foundTypes = $(".film-header span.type");
let foundMatch = "";
// No "type" found
if (foundTypes.length === 0) {
return "movie";
// One span.type found ... (film), (serial), ...
} else if (foundTypes.length === 1) {
foundMatch = $(foundTypes).text();
// Multiple span.type found, get the one containing "(" and ")"
} else if (foundTypes.length > 1) {
foundTypes.each(function (index, element) {
if ($(element).text().includes("(")) {
foundMatch = $(element).text().toLowerCase();
}
});
}
// Strip foundMatch from "(" and ")"
foundMatch = foundMatch.replace(/[\(\)]/g, '');
// Convert to english (film, serial, movie, series, ...)
foundMatch = this.getShowTypeFromType(foundMatch);
return foundMatch;
}
/**
* from property `og:title` extract the movie year `'Movie Title (2019)' --> 2019`
*
* @returns {str} Current movie year
*/
getCurrentFilmYear() {
const match = $('meta[property="og:title"]').attr('content').match(/\((\d+)\)/);
if (match.length === 2) {
const year = match[1];
return year;
}
return "";
}
/**
*
* @param {html} content
* @returns {bool} `true` if current movie rating is computed, `false` otherwise
*/
async isCurrentFilmComputed(content = null) {
const $computedStars = content === null ? $('.star.active.computed') : $(content).find('.star.active.computed');
if ($computedStars.length > 0) {
return true;
}
const secondTry = await this.isCurrentFilmRatingComputed();
if (secondTry) {
return true;
}
return false;
}
async isCurrentFilmRatingComputed() {
const $computedStars = this.csfdPage.find(".current-user-rating .star-rating.computed");
if ($computedStars.length !== 0) { return true; }
return false;
}
getCurrentFilmComputedCount(content = null) {
const $curUserRating = content === null ? this.csfdPage.find('li.current-user-rating') : content.find('li.current-user-rating');
const countedText = $($curUserRating).find('span[title]').attr('title');
// split by :
const counted = countedText?.split(':')[1]?.trim();
return counted;
}
async getCurrentFilmComputed() {
const result = await this.getComputedRatings(this.csfdPage);
return result;
}
async updateInLocalStorage(ratingsObject) {
// Check if film is in LocalStorage
const filmUrl = this.getCurrentFilmUrl();
const filmId = await this.getMovieIdFromHref(filmUrl);
const myRating = this.stars[filmId] || undefined;
// Item not in LocalStorage, add it then!
if (myRating === undefined) {
// Item not in LocalStorage, add
this.stars[filmId] = ratingsObject;
localStorage.setItem(this.storageKey, JSON.stringify(this.stars));
return true;
}
if (myRating.rating !== ratingsObject.rating || myRating.computedCount !== ratingsObject.computedCount) {
console.log(`⚙️ ~ Csfd ~ updateInLocalStorage ~ Updating item...`);
this.stars[filmId] = ratingsObject;
localStorage.setItem(this.storageKey, JSON.stringify(this.stars));
return true;
}
// Item in LocalStorage, everything is fine
// console.log(`✅ ~ Csfd ~ updateInLocalStorage ~ Item in LocalStorage, everything is fine`);
return false;
}
async removeFromLocalStorage() {
// Check if film is in LocalStorage
const filmUrl = this.getCurrentFilmUrl();
const filmId = await this.getMovieIdFromHref(filmUrl);
const item = this.stars[filmId];
// Item not in LocalStorage, everything is fine
if (item === undefined) {
return false;
}
// Item in LocalStorage, delete it from local dc
delete this.stars[filmId];
// And resave it to LocalStorage
localStorage.setItem(this.storageKey, JSON.stringify(this.stars));
return true;
}
/**
* Get movie rating from current or given page
* @param {html} content
* @returns {Promise<{rating: string, computedFrom: string, computed: boolean}>}
*/
async getCurrentFilmRating(content = null) {
const currentRatingIsComputed = await this.isCurrentFilmComputed(content);
if (currentRatingIsComputed) {
const { ratingCount, computedFromText } = content === null ? await this.getCurrentFilmComputed() : await this.getComputedRatings(content);
return {
rating: ratingCount,
computedFrom: computedFromText,
computed: true,
};
}
const $activeStars = this.csfdPage.find(".star.active");
// No rating
if ($activeStars.length === 0) {
return {
rating: "",
computedFrom: "",
computed: false,
};
}
// Rating "odpad" or "1"
if ($activeStars.length === 1) {
if ($activeStars.attr('data-rating') === "0") {
return {
rating: "0",
computedFrom: "",
computed: false,
};
}
}
// Rating "1" to "5"
return {
rating: $activeStars.length,
computedFrom: "",
computed: false,
};
}
async getCurrentUserRatingsCount() {
return $.get(this.userRatingsUrl)
.then(function (data) {
const count = $(data).find('.box-user-rating span.count').text().replace(/[\s()]/g, '');
if (count) {
return parseInt(count);
}
return 0;
});
}
async fillMissingSettingsKeys() {
let settings = await getSettings();
let currentKeys = Object.keys(settings);
let defaultKeys = Object.keys(defaultSettings);
for (const defaultKey of defaultKeys) {
let exists = currentKeys.includes(defaultKey);
if (!exists) {
settings[defaultKey] = defaultSettings[defaultKey];
}
}
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
}
async checkForOldLocalstorageRatingKeys() {
const ratings = this.getStars();
const keys = Object.keys(ratings);
for (const key of keys) {
if (key.includes("/")) {
alert(`
CSFD-Compare
Byl nalezen starý způsob ukládání hodnocení do LocalStorage!
Prosím, smažte staré hodnocení a znovu je nahrajte.
CC -> Smazat Uložená hodnocení`
);
return null;
}
}
}
/**
* $content should be URL with computed star ratings. Not manualy rated. \
* Then, it will return dict with `computed stars` and text `"computed from episodes: X"`
*
* @param {str} $content HTML content of a page
* @returns {Promise<{'ratingCount': int, 'computedFromText': str}>}
*
* Example: \
* `{ ratingCount: 4, computedFromText: 'spocteno z episod': 2 }`
*/
async getComputedRatings($content) {
// Get current user rating
const $curUserRating = $($content).find('li.current-user-rating');
const $starsSpan = $($curUserRating).find('span.stars');
const starCount = await csfd.getStarCountFromSpanClass($starsSpan);
// Get 'Spocteno z episod' text
const $countedText = $($curUserRating).find('span[title]').attr('title');
// // Get this movieId and possible parentId
// const filmUrl = await csfd.getFilmUrlFromHtml($content);
// let [movieId, parentId] = await csfd.getMovieIdParentIdFromUrl(filmUrl);
// Resulting dictionary
const result = {
'ratingCount': starCount,
'computedFromText': $countedText,
// 'movieId': movieId,
// 'parentId': parentId
};
return result;
}
async loadInitialSettings() {
// GLOBAL
$('#chkControlPanelOnHover').attr('checked', settings.showControlPanelOnHover);
$('#chkClickableHeaderBoxes').attr('checked', settings.clickableHeaderBoxes);
$('#chkClickableMessages').attr('checked', settings.clickableMessages);
$('#chkAddStars').attr('checked', settings.addStars);
// USER
$('#chkDisplayMessageButton').attr('checked', settings.displayMessageButton);
$('#chkDisplayFavoriteButton').attr('checked', settings.displayFavoriteButton);
$('#chkHideUserControlPanel').attr('checked', settings.hideUserControlPanel);
$('#chkCompareUserRatings').attr('checked', settings.compareUserRatings);
// FILM/SERIES
$('#chkAddRatingsDate').attr('checked', settings.addRatingsDate);
$('#chkShowLinkToImage').attr('checked', settings.showLinkToImage);
$('#chkRatingsEstimate').attr('checked', settings.ratingsEstimate);
$('#chkRatingsFromFavorites').attr('checked', settings.ratingsFromFavorites);
$('#chkAddRatingsComputedCount').attr('checked', settings.addRatingsComputedCount);
$('#chkHideSelectedUserReviews').attr('checked', settings.hideSelectedUserReviews);
settings.hideSelectedUserReviews || $('#txtHideSelectedUserReviews').parent().hide();
// if (settings.hideSelectedUserReviews === false) { $('#txtHideSelectedUserReviews').parent().hide(); }
if (settings.hideSelectedUserReviewsList !== undefined) { $('#txtHideSelectedUserReviews').val(settings.hideSelectedUserReviewsList.join(', ')); }
// ACTORS
$('#chkShowOnOneLine').attr('checked', settings.showOnOneLine);
// EXPERIMENTAL
$('#chkLoadComputedRatings').attr('checked', settings.loadComputedRatings);
$('#chkAddChatReplyButton').attr('checked', settings.addChatReplyButton);
}
async addSettingsEvents() {
// HOME PAGE
// GLOBAL
$('#chkControlPanelOnHover').on('change', function () {
settings.showControlPanelOnHover = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkClickableHeaderBoxes').on('change', function () {
settings.clickableHeaderBoxes = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkClickableMessages').on('change', function () {
settings.clickableMessages = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkAddStars').on('change', function () {
settings.addStars = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
// USER
$('#chkDisplayMessageButton').on('change', function () {
settings.displayMessageButton = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkDisplayFavoriteButton').on('change', function () {
settings.displayFavoriteButton = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkHideUserControlPanel').on('change', function () {
settings.hideUserControlPanel = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkCompareUserRatings').on('change', function () {
settings.compareUserRatings = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
// FILM/SERIES
$('#chkShowLinkToImage').on('change', function () {
settings.showLinkToImage = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkRatingsEstimate').on('change', function () {
settings.ratingsEstimate = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkRatingsFromFavorites').on('change', function () {
settings.ratingsFromFavorites = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkAddRatingsDate').on('change', function () {
settings.addRatingsDate = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkAddRatingsComputedCount').on('change', function () {
settings.addRatingsComputedCount = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkHideSelectedUserReviews').on('change', function () {
settings.hideSelectedUserReviews = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
$('#txtHideSelectedUserReviews').parent().toggle();
});
$('#txtHideSelectedUserReviews').on('change', function () {
let ignoredUsers = this.value.replace(/\s/g, '').split(",");
settings.hideSelectedUserReviewsList = ignoredUsers;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup(`Ignorovaní uživatelé:\n${ignoredUsers.join(', ')}`, 4);
});
// ACTORS
$('#chkShowOnOneLine').on('change', function () {
settings.showOnOneLine = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
// EXPERIMENTAL
$('#chkLoadComputedRatings').on('change', function () {
settings.loadComputedRatings = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
$('#chkAddChatReplyButton').on('change', function () {
settings.addChatReplyButton = this.checked;
localStorage.setItem(SETTINGSNAME, JSON.stringify(settings));
Glob.popup("Nastavení uloženo (obnovte stránku)", 2);
});
}
async onPageOtherUserHodnoceni() {
if ((location.href.includes('/hodnoceni') || location.href.includes('/hodnotenia')) && location.href.includes('/uzivatel/')) {
if (!location.href.includes(this.userUrl)) {
return true;
}
}
return false;
}
async onPageOtherUser() {
if (location.href.includes('/uzivatel/')) {
if (!location.href.includes(this.userUrl)) {
return true;
}
}
return false;
}
async onPageDiskuze() {
if (location.href.includes('/diskuze/') || location.href.includes('/diskusie')) {
return true;
}
return false;
}
async onPersonalFavorite() {
if (location.href.includes('/soukromne/oblubene/') || location.href.includes('/soukrome/oblibene/')) {
if (!location.href.includes(this.userUrl)) {
return true;
}
}
return false;
}
async notOnUserPage() {
if (location.href.includes('/uzivatel/') && location.href.includes(this.userUrl)) {
return false;
}
return true;
}
exportRatings() {
localStorage.setItem(this.storageKey, JSON.stringify(this.stars));
}
async addStars() {
if (location.href.includes('/zebricky/') || location.href.includes('/rebricky/')) {
return;
}
let starsCss = { marginLeft: "5px" };
// On UserPage or PersonalFavorite page, modify the CSS by adding solid red border outline
if (await this.onPageOtherUser() || await this.onPersonalFavorite()) {
starsCss = {
marginLeft: "5px",
borderWidth: "1px",
borderStyle: "solid",
borderColor: "#c78888",
borderRadius: "5px",
padding: "0px 5px",
};
}
let $links = $('a.film-title-name');
for (const $link of $links) {
const href = $($link).attr('href');
const movieId = await this.getMovieIdFromHref(href);
const res = this.stars[movieId];
if (res === undefined) {
continue;
}
const $sibl = $($link).closest('td').siblings('.rating,.star-rating-only');
if ($sibl.length !== 0) {
continue;
}
const starClass = res.rating !== 0 ? `stars-${res.rating}` : `trash`;
const starText = res.rating !== 0 ? "" : "odpad!";
const className = res.computed ? "star-rating computed" : "star-rating";
const title = res.computed ? res.computedFromText : res.date;
// Construct the HTML
const $starSpan = $("<span>", {
'class': className,
html: `<span class="stars ${starClass}" title="${title}">${starText}</span>`
}).css(starsCss);
// Add the HTML
$($link).after($starSpan);
// If the rating is computed, add SUP element indicating from how many ratings it was computed
if (res.computed) {
const $numSpan = $("<span>", {
'html': `<sup> (${res.computedCount})</sup>`
}).css({
'font-size': '13px',
'color': '#7b7b7b'
});
$starSpan.find('span').after($numSpan);
}
}
}
/**
* Adds a column to another user's ratings page with the user's rating
*
* @returns {None}
*/
addRatingsColumn() {
const starsDict = this.getStars();
const lcRatingsCount = Object.keys(starsDict).length;
// No ratings in LocalStorage, do nothing
if (lcRatingsCount === 0) { return; }
const $page = this.csfdPage;
const $tbl = $page.find('#snippet--ratings table tbody');
$tbl.find('tr').each(async function () {
const $row = $(this);
const href = $row.find('a.film-title-name').attr('href');
const movieId = await csfd.getMovieIdFromHref(href);
const myRating = starsDict[movieId];
let $span = "";
if (myRating?.rating === 0) {
$span = `<span class="stars trash">odpad!</span>`;
} else {
if (myRating?.computed) {
$span = `<span class="stars stars-${myRating?.rating}" title="${myRating?.computedFromText}"></span>`;
} else {
$span = `<span class="stars stars-${myRating?.rating}" title="${myRating?.date}"></span>`;
}
}
// Color the rating to red (star-rating) or black (star-rating computed) if computed
const className = myRating?.computed ? "star-rating computed" : "star-rating";
// Build the HTML for computed rating SUP element: e.g. (3)
const $computedSup = `
<span style="position: relative;">
<sup style="position: absolute; top: -1px; left: -2px; color: var(--color-grey-light2)">
(${myRating?.computedCount})
</sup>
</span>
`;
const $currentUserSpan = `
<span class="${className}">
${$span}
${myRating?.computed ? $computedSup : ""}
</span>
`;
const $currentUserTd = $row.find('td:nth-child(2)')
$currentUserTd.after(`
<td class="star-rating-only">
${$currentUserSpan}
</td>
`);
});
}
async openControlPanelOnHover() {
const btn = $('.button-control-panel');
const panel = $('#dropdown-control-panel');
$(btn).on('mouseover', () => {
if (!panel.hasClass('active')) {
panel.addClass('active');
let windowWidth = $(window).width();
if (windowWidth <= 635) {
panel.appendTo(document.body);
panel.css("top", "133px");
panel.css("right", "15px");
}
}
});
$(btn).on('mouseleave', () => {
if (panel.hasClass('active')) panel.removeClass('active');
});
$(panel).on('mouseover', () => {
if (!panel.hasClass('active')) panel.addClass('active');
});
$(panel).on('mouseleave', () => {
if (panel.hasClass('active')) panel.removeClass('active');
});
}
async addWarningToUserProfile() {
const ratingCountOk = this.isRatingCountOk();
if (ratingCountOk) return;
$(".csfd-compare-menu").append(`
<div class='counter'>
<span><b>!</b></span>
</div>
`);
}
async refreshButtonNew(ratingsInLS, curUserRatings) {
const ratingCountOk = await this.isRatingCountOk();
if (ratingCountOk) return;
const $button = $('<button>', {
id: 'refr-ratings-button',
"class": 'csfd-compare-reload',
html: `<center>
<b> >> Načíst hodnocení (new) << </b> <br />
</center>`,
}).css({
textTransform: "initial",
fontSize: "0.9em",
padding: "5px",
border: "4px solid whitesmoke",
borderRadius: "8px",
width: "-moz-available",
width: "-webkit-fill-available",
width: "100%",
});
const $div = $('<div>', {
html: $button,
});
$('.csfd-compare-settings').after($div);
let forceUpdate = ratingsInLS > curUserRatings ? true : false;
$($button).on("click", async function () {
console.debug("refreshing ratings");
const csfd = new Csfd($('div.page-content'));
if (forceUpdate === true) {
if (!confirm(`Pro jistotu bych obnovil VŠECHNA hodnocení... Důvod: počet tvých je [${ratingsInLS}], ale v databázi je uloženo více: [${curUserRatings}]. Souhlasíš?`)) {
forceUpdate = false;
}
}
csfd.refreshAllRatingsNew(csfd, forceUpdate);
});
}
async badgesComponent(ratingsInLS, curUserRatings, computedRatings) {
// TODO" Tohle už teď bude fungovat, jen to zakomponovat...
return "<b>ahoj</b>";
}
displayMessageButton() {
let userHref = $('#dropdown-control-panel li a.ajax').attr('href');
if (userHref === undefined) {
console.log("fn displayMessageButton(): can't find user href, exiting function...");
return;
}
let button = document.createElement("button");
button.setAttribute("data-tippy-content", $('#dropdown-control-panel li a.ajax')[0].text);
button.setAttribute("style", "float: right; border-radius: 5px;");
button.innerHTML = `
<a class="ajax"
rel="contentModal"
data-mfp-src="#panelModal"
href="${userHref}"><i class="icon icon-messages"></i></a>
`;
$(".user-profile-content > h1").append(button);
}
async displayFavoriteButton() {
let favoriteButton = $('#snippet--menuFavorite > a');
if (favoriteButton.length !== 1) {
console.log("fn displayFavoriteButton(): can't find user href, exiting function...");
return;
}
let tooltipText = favoriteButton[0].text;
let addRemoveIndicator = "+";
if (tooltipText.includes("Odebrat") || tooltipText.includes("Odobrať")) {
addRemoveIndicator = "-";
}
let button = document.createElement("button");
button.setAttribute("style", "float: right; border-radius: 5px; margin: 0px 5px;");
button.setAttribute("data-tippy-content", tooltipText);
button.innerHTML = `
<a class="ajax"
rel="contentModal"
data-mfp-src="#panelModal"
href="${favoriteButton.attr('href')}">