-
Notifications
You must be signed in to change notification settings - Fork 1
/
mal_highlighter.js
584 lines (525 loc) · 21.9 KB
/
mal_highlighter.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
// ==UserScript==
// @name MAL Highlighter
// @namespace http://keittokilta.fi
// @version 2.2.4
// @description Highlights MAL titles with different colors.
// @author Borsas
// @match https://myanimelist.net/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
/** Main functionality of the script */
class Highlighter {
/**
* What type of data and from which user.
* @param {string} type - Either 'anime' or 'manga'
* @param {string} username - MAL username
*/
constructor(type, username){
this.type = type;
this.username = username;
}
/**
* Gets the data from MAL's JSON handler every 3600000ms (1h) or if the session storage is empty.
* Otherwise from the session storage.
* @returns {JSON} User data (anime, manga)
*/
async getData() {
const timestamp = new TimeStamp();
const sessionStorageItem = sessionStorage.getItem(this.type);
if (sessionStorageItem && Date.now() < (timestamp.getTimeStamp() + 3600000)){
console.log(`Loaded ${this.type} from memory`);
timestamp.setTimeStamp()
return JSON.parse(sessionStorageItem);
} else {
let dataCombined = await (
await fetch(`https://myanimelist.net/${this.type}list/${this.username}/load.json?status=7`)
).json();
// Aas MAL only gives 300 objects per request,
// the data from MAL's JSON handler has to be pulled in batches using offset
let offset = 300;
while (true) {
const data = await (
await fetch(`https://myanimelist.net/${this.type}list/${this.username}/load.json?offset=${offset}&status=7`)
).json()
offset += 300
if (data.length === 0) break;
dataCombined = dataCombined.concat(data)
}
sessionStorage.setItem(this.type, JSON.stringify(dataCombined));
console.log(`Loaded ${this.type} from MAL API`);
timestamp.setTimeStamp()
return dataCombined;
}
}
/**
* Adds attributes to the correct elements.
* @param {string} id - A numerical id
* @param {string} element - HTML element
*/
addAttributes(id, element){
if (this.statusType.watching.includes(parseInt(id))) {
element.classList.add('HL-watching');
} else if (this.statusType.completed.includes(parseInt(id))) {
element.classList.add('HL-completed');
} else if (this.statusType.onHold.includes(parseInt(id))) {
element.classList.add('HL-onHold');
} else if (this.statusType.dropped.includes(parseInt(id))) {
element.classList.add('HL-dropped');
} else if (this.statusType.planToWatch.includes(parseInt(id))) {
element.classList.add('HL-planToWatch');
}
}
/** Changes colors on myanimelist.net/topanime.php */
colorTopAnime(){
let tr = document.getElementsByClassName('ranking-list');
for (let i = 0; i < tr.length; i++){
let id = tr[i].getElementsByTagName('a')[0].getAttribute('href').split('/');
if (id[3] === this.type) {
this.addAttributes(id[4], tr[i]);
}
}
}
// Changes colors on myanimelist.net/people/*/*
colorPeoplePage(){
let tr = document.getElementsByTagName('tr');
// Count of garbage tr classes at the bottom that are not wanted
// people-comment classes are also added to this if there are any
let bottom = 0;
if (document.getElementsByClassName('people-comment')) {
bottom += document.getElementsByClassName('people-comment').length;
}
for (let i = 0; i < tr.length - bottom; i++) {
let series = tr[i].getElementsByTagName('a')[1];
let url = series.getAttribute('href').split('/');
if (url.length === 6) {
let id = url[4];
if (url[3] === this.type) {
this.addAttributes(id, tr[i]);
}
}
}
}
/** Changes colors on character pages */
colorCharacterPage(){
let leftBox = document.getElementsByClassName("borderClass");
let allShows = leftBox[0].getElementsByTagName("tr");
for (let i = 0; i < allShows.length; i++){
let url = allShows[i].getElementsByTagName("a")[0].getAttribute("href").split("/");
if (url[3] === this.type){
this.addAttributes(url[4], allShows[i]);
}
}
}
/** Changes colors on producer and season page */
colorGenericPage(){
let allShows = document.getElementsByClassName('seasonal-anime');
for (let i = 0; i < allShows.length; i++){
let id = allShows[i].getElementsByClassName('link-title')[0].getAttribute('href').split('/');
if (id[3] === this.type) {
this.addAttributes(id[4], allShows[i]);
}
}
}
/** Changes colors on the main page */
colorMainPage() {
let column = document.getElementsByClassName("right-column")[0];
let widgets = column.getElementsByTagName("article");
// Friend Updates widget has a different format from everything else
let friendUpdates = widgets[3].getElementsByClassName("widget-content")[0];
this.colorFriendWidget(friendUpdates);
for (let i = 5; i < widgets.length; i++) {
let content = widgets[i].getElementsByTagName("ul")[0].getElementsByTagName("li");
for (let j = 0; j < content.length; j++) {
let data = content[j].getElementsByClassName("data")[0];
let url = data.getElementsByTagName("a")[0].getAttribute("href").split("/");
// Some urls have different format from everything else, so we need to parse it.
let id = this.parseIdFromString(url[5])
if (url[4] === this.type) {
this.addAttributes(id, content[j])
}
}
}
}
/** Changes the color on the "Recent Friend Updates" box on the main page */
colorFriendWidget(element) {
let content = element.getElementsByClassName("item");
for (let i = 0; i < content.length; i++) {
let id = content[i].getElementsByTagName("a")[0].getAttribute("href").split("/");
if (id[3] === this.type) {
this.addAttributes(id[4], content[i])
}
}
}
/** Parse the Anime or Manga id from string */
parseIdFromString(string) {
let id = parseInt(string);
if (!isNaN(id)) {
return id;
}
// Parses the id from format "add?selected_series_id=11757&hideLayout=1"
return string.split("=")[1].split("&")[0];
}
/**
* Sorts all statuses from the JSON.
* @param {JSON} data - User data (anime, manga)
*/
getStatusType(data){
this.statusType = {watching: [], completed: [], onHold: [], dropped: [], planToWatch: []};
let id = this.type + '_id';
for (let property in data){
switch (data[property].status) {
case 1:
this.statusType.watching.push(data[property][id]);
break;
case 2:
this.statusType.completed.push(data[property][id]);
break;
case 3:
this.statusType.onHold.push(data[property][id]);
break;
case 4:
this.statusType.dropped.push(data[property][id]);
break;
case 6:
this.statusType.planToWatch.push(data[property][id]);
}
}
}
/**
* Main function of Highlighter.
* Matches pages and applies colors on them.
*/
async main() {
const data = await this.getData();
this.getStatusType(data);
const url = window.location.href;
if (url.match(/^https?:\/\/myanimelist\.net\/top(manga|anime)\.php/)){
this.colorTopAnime();
} else if (url.match(/^https?:\/\/myanimelist\.net\/people\/\d*\/.*/)){
this.colorPeoplePage();
} else if (url.match(/^https?:\/\/myanimelist\.net\/(anime\/(season((\d*\/.*|$)|^\s*$)|producer\/*)|manga\/magazine\/*)/)){
this.colorGenericPage();
} else if (url.match(/^https?:\/\/myanimelist\.net\/character\/\d*\/.*/)){
this.colorCharacterPage();
} else if (url.match(/^https?:\/\/myanimelist\.net\/$/)) {
this.colorMainPage()
}
}
}
/** Class used for handling the timestamp of the previous request on MAL's JSON handler. */
class TimeStamp {
/**
* Saves timestamp (UNIX time in ms) to the browser's local storage as JSON string.
*/
setTimeStamp(){
const timestamp = {
"JSONLoaded": Date.now().toString()
}
localStorage.setItem("timestamp", JSON.stringify(timestamp));
console.log("Timestamp set for MAL's JSON handler call.")
}
/**
* Gets the timestamp from the local storage as integer.
*/
getTimeStamp(){
const timestamp = JSON.parse(localStorage.getItem("timestamp"))
if (timestamp) {
return parseInt(timestamp.JSONLoaded, 10)
} else {
return 0
}
}
}
/** Class used for handling the user settings of the script, such as custom colors. */
class Settings {
/** Default user settings */
constructor(){
this.watching = "#34ce0f";
this.completed = "#ccede4";
this.onHold = "#f1c83e";
this.dropped = "#f76265";
this.planToWatch = "#dcc8aa";
this.animeHL = "true";
this.mangaHL = "true";
this.whenLoadedJSON = "0";
}
/** Loads settings from local storage as JSON and sets them to variables */
loadSettings(){
const settings = JSON.parse(localStorage.getItem("settings"));
if (settings) {
this.watching = settings.watching;
this.completed = settings.completed;
this.onHold = settings.onHold;
this.dropped = settings.dropped;
this.planToWatch = settings.planToWatch;
this.animeHL = settings.animeHL;
this.mangaHL = settings.mangaHL;
}
}
/** Converts settings to JSON */
setSettings(){
const settings = {
"watching": this.watching,
"completed": this.completed,
"onHold": this.onHold,
"dropped": this.dropped,
"planToWatch": this.planToWatch,
"animeHL": this.animeHL,
"mangaHL": this.mangaHL
}
localStorage.setItem("settings", JSON.stringify(settings));
}
/** Saves settings to local storage as JSON */
saveSettings(){
this.watching = document.getElementById("watching").value;
this.completed = document.getElementById("completed").value;
this.onHold = document.getElementById("onHold").value;
this.dropped = document.getElementById("dropped").value;
this.planToWatch = document.getElementById("planToWatch").value;
this.animeHL = document.getElementById("animeHL").checked ? "true" : "false";
this.mangaHL = document.getElementById("mangaHL").checked ? "true" : "false";
this.setSettings();
location.reload();
}
/** Injects custom CSS */
injectCss(){
$('<style type="text/css"/>').html(
`.HL-settingsWindow {
opacity: 1 !important;
width: 450px;
height: 600px;
position: fixed !important;
top: 20% !important;
left: 35% !important;
display: block !important;
background-color: white;
border-style: solid;
border-width: 0 2px 1px;
border-color: #d9d9d9;
font-size: 15px;
}
#HL-colors {
padding: 2px;
text-align: left;
}
#HL-controls {
margin-top: 20px;
text-align: left;
position: absolute;
bottom: 20px;
}
#HL-controls button {
background-color: #2e51a2;
border-radius: 4px;
color: #fff;
font-family: Avenir,lucida grande,tahoma,verdana,arial,sans-serif;
font-size: 14px;
font-weight: 700;
height: 30px;
padding: 0 6px;
text-align: center;
text-decoration: none;
text-shadow: #323232 -1px -1px 0;
transition-duration: .3s;
transition-property: all;
transition-timing-function: ease-in-out;
vertical-align: middle;
width: 85px;
cursor: pointer;
}
#HL-color-pickers {
display: flex;
}
.HL-color-picker {
flex-basis: 20%;
flex-grow: 0;
text-align: center;
}
.HL-color-picker input[type=color] {
width: 90%;
height: 50px;
}
.HL-highlighter {
display: flex;
justify-content: space-between;
}
.HL-switch {
position: relative;
display: inline-block;
width: 45px;
height: 25px;
align-self: flex-end;
}
.HL-switch input {
opacity: 0;
width: 0;
height: 0;
}
.HL-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #aaa;
transition: .1s;
border-radius: 34px;
}
.HL-slider:before {
position: absolute;
content: "";
height: 19px;
width: 19px;
left: 3px;
bottom: 3px;
background-color: white;
transition: .1s;
border-radius: 50%;
}
input:checked + .HL-slider {
background-color: #39C16C;
}
input:focus + .HL-slider {
box-shadow: 0 0 1px #39C16C;
}
input:checked + .HL-slider:before {
transform: translateX(20px);
}
.information, .your-score .text {
color: #323232 !important;}
.top-anime-rank-text.rank1, .top-anime-rank-text.rank2 {
color: #5d5c5c;}
.top-ranking-table tr.ranking-list td {
background-color: transparent !important;}
.HL-watching {
background-color: ${this.watching} !important;}
.HL-completed {
background-color: ${this.completed} !important;}
.HL-onHold {
background-color: ${this.onHold} !important;}
.HL-dropped {
background-color: ${this.dropped} !important;}
.HL-planToWatch {
background-color: ${this.planToWatch} !important;}`
).appendTo('head');
}
/** Custom HTML */
settingsMenu(){
return `
<h2>Settings for MAL Highlighter</h2>
<div class="HL-highlighter h1">
<div>
Anime Highlighter
</div>
<label class="HL-switch">
<input type="checkbox" id="animeHL">
<span class="HL-slider"></span>
</label>
</div>
<div class="HL-highlighter h1">
<div>
Manga Highlighter
</div>
<label class="HL-switch">
<input type="checkbox" id="mangaHL">
<span class="HL-slider"></span>
</label>
</div>
<h2>Highlighter colors</h2>
<div id="HL-colors">
<div id="HL-color-pickers">
<div class="HL-color-picker">
<p">Watching</p>
<input id="watching" type="color" value="${this.watching}">
</div>
<div class="HL-color-picker">
<p">Completed</p>
<input id="completed" type="color" value="${this.completed}">
</div>
<div class="HL-color-picker">
<p">On hold</p>
<input id="onHold" type="color" value="${this.onHold}">
</div>
<div class="HL-color-picker">
<p">Dropped</p>
<input id="dropped" type="color" value="${this.dropped}">
</div>
<div class="HL-color-picker">
<p">Planned</p>
<input id="planToWatch" type="color" value="${this.planToWatch}">
</div>
</div>
</div>
<div id="HL-controls">
<button value="submit" id="HL-saveSettings">Save</button>
<button value="submit" id="HL-resetSettings">Reset</button>
</div>
`;
}
/** Button used to open settings */
button(){
let button = document.createElement("li");
button.classList.add("small2");
let linkButton = document.createElement("a");
let self = this;
linkButton.classList.add("non-link");
linkButton.href = "#";
linkButton.innerHTML = "Settings";
linkButton.style = "color: orange;";
linkButton.addEventListener("click", function(){
self.openSettings();
});
button.append(linkButton);
let position = document.getElementById("nav");
position.appendChild(button);
}
/** Opens settings menu */
openSettings(){
let position = document.getElementsByClassName("page-common");
let settingsBg = document.createElement("div");
let settingsWindow = document.createElement("div");
let self = this;
settingsBg.id = "fancybox-overlay";
settingsBg.style = "background-color: rgb(102, 102, 102); opacity: 0.3; display: block;";
position[0].append(settingsBg);
settingsWindow.id = "fancybox-wrap";
settingsWindow.classList.add("HL-settingsWindow");
settingsWindow.innerHTML = this.settingsMenu();
settingsBg.addEventListener("click", function(){
position[0].removeChild(settingsWindow);
position[0].removeChild(settingsBg);
});
position[0].append(settingsWindow);
document.getElementById("HL-saveSettings").addEventListener("click", function(){
self.saveSettings();
})
document.getElementById("HL-resetSettings").addEventListener("click", function(){
localStorage.clear("settings");
location.reload();
})
document.getElementById("animeHL").checked = this.animeHL === "true";
document.getElementById("mangaHL").checked = this.mangaHL === "true";
}
}
/** Runs the script */
class StartScript {
run(){
const settings = new Settings();
settings.loadSettings();
const profile = document.getElementsByClassName('header-profile-link')[0];
if (profile){
const user = profile.text;
// Because why not, easiest way to convert string to bool
if (JSON.parse(settings.animeHL)) new Highlighter('anime', user).main();
if (JSON.parse(settings.mangaHL)) new Highlighter('manga', user).main();
}
settings.injectCss();
settings.button();
}
}
const script = new StartScript();
script.run();
})();