summaryrefslogtreecommitdiff
path: root/static/client.js
blob: 2e691f8de1a22b939e7d6ff372c763779ca7d6f2 (plain)
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

/*
	Global functions
*/
function htmlspecialchars(str){

	var map = {
		'&': '&',
		'<': '&lt;',
		'>': '&gt;',
		'"': '&quot;',
		"'": '&#039;'
	}

	return str.replace(/[&<>"']/g, function(m){return map[m];});
}

function htmlspecialchars_decode(str){
	
	var map = {
		'&amp;': '&',
		'&lt;': '<',
		'&gt;': '>',
		'&quot;': '"',
		'&#039;': "'"
	}
	
	return str.replace(/&amp;|&lt;|&gt;|&quot;|&#039;/g, function(m){return map[m];});
}

function is_click_within(elem, classname, is_id = false){
	
	while(true){
		
		if(elem === null){
			
			return false;
		}
		
		if(
			(
				is_id === false &&
				elem.className == classname
			) ||
			(
				is_id === true &&
				elem.id == classname
			)
		){
			
			return elem;
		}
		
		elem = elem.parentElement;
	}
}



/*
	Prevent GET parameter pollution
*/
var form = document.getElementsByTagName("form");

if(
	form.length !== 0 &&
	window.location.pathname != "/" &&
	window.location.pathname != "/settings.php" &&
	window.location.pathname != "/settings"
){
	form = form[0];
	
	var scraper_dropdown = document.getElementsByName("scraper")[0];
	
	scraper_dropdown.addEventListener("change", function(choice){
		
		submit(form);
	});
	
	form.addEventListener("submit", function(e){
		
		e.preventDefault();
		submit(e.srcElement);
	});
}

function submit(e){
	
	var GET = "";
	var first = true;
	
	if((s = document.getElementsByName("s")).length !== 0){
		
		GET += "?s=" + encodeURIComponent(s[0].value).replaceAll("%20", "+");
		first = false;
	}
	
	Array.from(
		e.getElementsByTagName("select")
	).concat(
		Array.from(
			e.getElementsByTagName("input")
		)
	).forEach(function(el){
		
		var firstelem = el.getElementsByTagName("option");
		
		if(
			(
				(
					firstelem.length === 0 ||
					firstelem[0].value != el.value
				) &&
				el.name != "" &&
				el.value != "" &&
				el.name != "s"
			) ||
			el.name == "scraper" ||
			el.name == "nsfw"
		){
			
			if(first){
				
				GET += "?";
				first = false;
			}else{
				
				GET += "&";
			}
			
			GET += encodeURIComponent(el.name).replaceAll("%20", "+") + "=" + encodeURIComponent(el.value).replaceAll("%20", "+");
		}
	});
	
	window.location.href = GET;
}



/*
	Hide show more button when it's not needed on answers
*/
var answer_div = document.getElementsByClassName("answer");

if(answer_div.length !== 0){
	answer_div = Array.from(answer_div);
	var spoiler_button_div = Array.from(document.getElementsByClassName("spoiler-button"));

	// execute on pageload
	hide_show_more();

	window.addEventListener("resize", hide_show_more);

	function hide_show_more(){
		
		var height = window.innerWidth >= 1000 ? 600 : 200;
		
		for(i=0; i<answer_div.length; i++){
			
			if(answer_div[i].scrollHeight < height){
				
				spoiler_button_div[i].style.display = "none";
				
				document.getElementById(spoiler_button_div[i].htmlFor).checked = true;
			}else{
				
				spoiler_button_div[i].style.display = "block";
			}
		}
	}
}

switch(document.location.pathname){
	
	case "/web":
	case "/web.php":
		var image_class = "image";
		break;
	
	case "/images":
	case "/images.php":
		var image_class = "thumb";
		break;
	
	default:
		var image_class = null;
}

if(image_class !== null){
	
	/*
		Add popup to document
	*/
	var popup_bg = document.createElement("div");
	popup_bg.id = "popup-bg";
	document.body.appendChild(popup_bg);
	
	// enable/disable pointer events
	if(!document.cookie.includes("bg_noclick=yes")){
		
		popup_bg.style.pointerEvents = "none";
	}
	
	var popup_status = document.createElement("div");
	popup_status.id = "popup-status";
	document.body.appendChild(popup_status);
	
	var popup_body = document.createElement("div");
	popup_body.id = "popup";
	document.body.appendChild(popup_body);
	
	// import popup
	var popup_body = document.getElementById("popup");
	var popup_status = document.getElementById("popup-status");
	var popup_image = null; // is set later on popup click
	
	// image metadata
	var collection = []; // will contain width, height, image URL
	var collection_index = 0;
	
	// event handling helper variables
	var is_popup_shown = false;
	var mouse_down = false;
	var mouse_move = false;
	var move_x = 0;
	var move_y = 0;
	var target_is_popup = false;
	var mirror_x = false;
	var mirror_y = false;
	var rotation = 0;
	
	/*
		Image dragging (mousedown)
	*/
	document.addEventListener("mousedown", function(div){
		
		if(div.buttons !== 1){
			
			return;
		}
		
		mouse_down = true;
		mouse_move = false;
		
		if(is_click_within(div.target, "popup", true) === false){
			
			target_is_popup = false;
		}else{

			target_is_popup = true;
			
			var pos = popup_body.getBoundingClientRect();
			move_x = div.x - pos.x;
			move_y = div.y - pos.y;
		}
	});
	
	/*
		Image dragging (mousemove)
	*/
	document.addEventListener("mousemove", function(pos){
		
		if(
			target_is_popup &&
			mouse_down
		){
			
			mouse_move = true;
			movepopup(popup_body, pos.clientX - move_x, pos.clientY - move_y);
		}
	});
	
	/*
		Image dragging (mouseup)
	*/
	document.addEventListener("mouseup", function(){
		
		mouse_down = false;
	});
	
	/*
		Image popup open
	*/
	document.addEventListener("click", function(click){
		
		// should our click trigger image open?
		if(
			elem = is_click_within(click.target, image_class) ||
			click.target.classList.contains("openimg")
		){
			
			event.preventDefault();
			is_popup_shown = true;
			
			// reset position params
			mirror_x = false;
			mirror_y = false;
			rotation = 0;
			scale = 60;
			collection_index = 0;
			
			// get popup data
			if(elem === true){
				// we clicked a simple image preview
				elem = click.target;
				var image_url = elem.getAttribute("src");
				
				if(image_url.startsWith("/proxy")){
					
					var match = image_url.match(/i=([^&]+)/);
					
					if(match !== null){
						
						image_url = decodeURIComponent(match[1]);
					}
				}else{
					
					image_url = htmlspecialchars_decode(image_url);
				}
				
				collection = [
					{
						"url": image_url,
						"width": Math.round(click.target.naturalWidth),
						"height": Math.round(click.target.naturalHeight)
					}
				];
				
				var title = "No description provided";
				
				if(click.target.title != ""){
					
					title = click.target.title;
				}else{
					
					if(click.target.alt != ""){
						
						title = click.target.alt;
					}
				}
			}else{
				
				if(image_class == "thumb"){
					// we're inside image.php
					
					elem =
						elem
						.parentElement
						.parentElement;
					
					var image_url = elem.getElementsByTagName("a")[1].href;
				}else{
					
					// we're inside web.php
					var image_url = elem.href;
				}
				
				collection =
					JSON.parse(
						elem.getAttribute("data-json")
					);
				
				var imagesize = elem.getElementsByTagName("img")[0];
				
				if(imagesize.complete){
					
					var imagesize_w = imagesize.naturalWidth;
					var imagesize_h = imagesize.naturalHeight;
				}
				
				for(var i=0; i<collection.length; i++){
					
					if(collection[i].width === null){
						
						collection[i].width = imagesize_w;
						collection[i].height = imagesize_h;
					}
				}
				
				var title = elem.title;
			}
			
			// prepare HTML
			var html =
				'<div id="popup-num">(' + collection.length + ')</div>' + 
				'<div id="popup-dropdown">' +
					'<select name="viewer-res" onchange="changeimage(event)">';
			
			for(i=0; i<collection.length; i++){
				
				if(collection[i].url.startsWith("data:")){
					
					var domain = "&lt;Base64 Data&gt;";
				}else{
					
					var domain = new URL(collection[i].url).hostname;
				}
				
				html += '<option value="' + i + '">' + '(' + collection[i].width + 'x' + collection[i].height + ') ' + domain + '</option>';
			}
			
			popup_status.innerHTML =
				html + '</select></div>' +
				'<a href="' + htmlspecialchars(image_url) + '" rel="noreferrer nofollow "id="popup-title">' + htmlspecialchars(title) + '</a>';
			
			popup_body.innerHTML =
				'<img src="' + getproxylink(collection[0].url) + '" draggable="false" id="popup-image">';
			
			// make changes to DOM
			popup_body.style.display = "block";
			popup_bg.style.display = "block";
			popup_status.style.display = "table";
			
			// store for rotation functions & changeimage()
			popup_image = document.getElementById("popup-image");
			
			scalepopup(collection[collection_index], scale);
			centerpopup();
		}else{
			
			// click inside the image viewer
			// resize image
			if(is_click_within(click.target, "popup", true)){
				
				if(mouse_move === false){
					scale = 80;
					scalepopup(collection[collection_index], scale);
					centerpopup();
				}
			}else{
				
				if(is_click_within(click.target, "popup-status", true) === false){
					
					// click outside the popup while its open
					// close it
					if(is_popup_shown){
						
						hidepopup();
					}
				}
			}
		}
	});
	
	/*
		Scale image viewer
	*/
	popup_body.addEventListener("wheel", function(scroll){
		
		event.preventDefault();
		
		if(
			scroll.altKey ||
			scroll.ctrlKey ||
			scroll.shiftKey
		){
			
			var increment = 7;
		}else{
			
			var increment = 14;
		}
		
		if(scroll.wheelDelta > 0){
			
			// scrolling up
			scale = scale + increment;
		}else{
			
			// scrolling down
			if(scale - increment > 7){
				scale = scale - increment;
			}
		}
		
		// calculate relative size before scroll
		var pos = popup_body.getBoundingClientRect();
		var x = (scroll.x - pos.x) / pos.width;
		var y = (scroll.y - pos.y) / pos.height;
		
		scalepopup(collection[collection_index], scale);
		
		// move popup to % we found
		pos = popup_body.getBoundingClientRect();
		
		movepopup(
			popup_body,
			scroll.clientX - (x * pos.width),
			scroll.clientY - (y * pos.height)
		);
	});
	
	/*
		Keyboard controls
	*/
	
	document.addEventListener("keydown", function(key){
		
		// close popup
		if(
			is_popup_shown &&
			key.keyCode === 27
		){
			
			hidepopup();
			return;
		}
		
		if(is_popup_shown === false){
			
			return;
		}
		
		if(
			key.altKey ||
			key.ctrlKey ||
			key.shiftKey
		){
			
			// mirror image
			switch(key.keyCode){
				
				case 37:
					// left
					key.preventDefault();
					mirror_x = true;
					break;
				
				case 38:
					// up
					key.preventDefault();
					mirror_y = false;
					break;
				
				case 39:
					// right
					key.preventDefault();
					mirror_x = false;
					break;
				
				case 40:
					// down
					key.preventDefault();
					mirror_y = true;
					break;
			}
		}else{
			
			// rotate image
			switch(key.keyCode){
				
				case 37:
					// left
					key.preventDefault();
					rotation = -90;
					break;
				
				case 38:
					// up
					key.preventDefault();
					rotation = 0;
					break;
				
				case 39:
					// right
					key.preventDefault();
					rotation = 90;
					break;
				
				case 40:
					// down
					key.preventDefault();
					rotation = -180;
					break;
			}
		}
		
		popup_image.style.transform =
			"scale(" +
				(mirror_x ? "-1" : "1") +
				", " +
				(mirror_y ? "-1" : "1") +
			") " +
			"rotate(" +
				rotation + "deg" +
			")";
	});
}

function getproxylink(url){
	
	if(url.startsWith("data:")){
		
		return htmlspecialchars(url);
	}else{
		
		return '/proxy?i=' + encodeURIComponent(url);
	}
}

function hidepopup(){
	
	is_popup_shown = false;
	popup_status.style.display = "none";
	popup_body.style.display = "none";
	popup_bg.style.display = "none";
}

function scalepopup(size, scale){
	
	var ratio =
		Math.min(
			(window.innerWidth * (scale / 100)) / collection[collection_index].width, (window.innerHeight * (scale / 100)) / collection[collection_index].height
		);
	
	popup_body.style.width = size.width * ratio + "px";
	popup_body.style.height = size.height * ratio + "px";
}

function centerpopup(){
	
	var size = popup_body.getBoundingClientRect();
	var size = {
		"width": parseInt(size.width),
		"height": parseInt(size.height)
	};
	
	movepopup(
		popup_body,
		(window.innerWidth / 2) - (size.width / 2),
		(window.innerHeight / 2) - (size.height / 2)
	);
}

function movepopup(popup_body, x, y){
	
	popup_body.style.left = x + "px";
	popup_body.style.top = y + "px";
}

function changeimage(event){
	
	// reset rotation params
	mirror_x = false;
	mirror_y = false;
	rotation = 0;
	
	scale = 60;
	
	collection_index = parseInt(event.target.value);
	
	// we set innerHTML otherwise old image lingers a little
	popup_body.innerHTML =
		'<img src="' + getproxylink(collection[collection_index].url) + '" draggable="false" id="popup-image">';
	
	// store for rotation functions & changeimage()
	popup_image = document.getElementById("popup-image");
	
	scalepopup(collection[collection_index], scale);
	centerpopup();
}

var searchbox_wrapper = document.getElementsByClassName("searchbox");

if(searchbox_wrapper.length !== 0){
		
	searchbox_wrapper = searchbox_wrapper[0];
	var searchbox = searchbox_wrapper.getElementsByTagName("input")[1];
	
	/*
		Textarea shortcuts
	*/
	document.addEventListener("keydown", function(key){
		
		switch(key.keyCode){
			
			case 191:
				// 191 = /
				if(document.activeElement.tagName == "INPUT"){
					
					// already focused, ignore
					break;
				}
				
				if(
					typeof is_popup_shown != "undefined" &&
					is_popup_shown
				){
					
					hidepopup();
				}
				
				window.scrollTo(0, 0);
				searchbox.focus();
				key.preventDefault();
				break;
		}
	});
	
	/*
		Autocompleter
	*/
	if( // make sure the user wants it
		document.cookie.includes("scraper_ac=") &&
		document.cookie.includes("scraper_ac=disabled") === false
	){
		
		var autocomplete_cache = [];
		var focuspos = -1;
		var list = [];
		var autocomplete_div = document.getElementsByClassName("autocomplete")[0];
		
		if(
			document.cookie.includes("scraper_ac=auto") &&
			typeof scraper_dropdown != "undefined"
		){
			
			var ac_req_appendix = "&scraper=" + scraper_dropdown.value;
		}else{
			
			var ac_req_appendix = "";
		}
		
		function getsearchboxtext(){
			
			var value =
				searchbox.value
				.trim()
				.replace(
					/ +/g,
					" "
				)
				.toLowerCase();
			
			return value;
		}
		
		searchbox.addEventListener("input", async function(){
			
			// ratelimit on input only
			// dont ratelimit if we already have res
			if(typeof autocomplete_cache[getsearchboxtext()] != "undefined"){
				
				await getac();
			}else{
				
				await getac_ratelimit();
			}
		});
		
		async function getac(){
			
			var curvalue = getsearchboxtext();
			
			if(curvalue == ""){
				
				// hide autocompleter
				autocomplete_div.style.display = "none";
				return;
			}
			
			if(typeof autocomplete_cache[curvalue] == "undefined"){
				
				/*
					Fetch autocomplete
				*/
				// make sure we dont fetch same thing twice
				autocomplete_cache[curvalue] = [];
				
				var res = await fetch("/api/v1/ac?s=" + (encodeURIComponent(curvalue).replaceAll("%20", "+")) + ac_req_appendix);
				if(!res.ok){
					
					return;
				}
				
				var json = await res.json();
				
				autocomplete_cache[curvalue] = json[1];
				
				if(curvalue == getsearchboxtext()){
					
					render_ac(curvalue, autocomplete_cache[curvalue]);
				}
				return;
			}
			
			render_ac(curvalue, autocomplete_cache[curvalue]);	
		}
		
		var ac_func = null;
		function getac_ratelimit(){
			
			return new Promise(async function(resolve, reject){
				
				if(ac_func !== null){
					
					clearTimeout(ac_func);
				}//else{
					
					// no ratelimits
					//getac();
				//}
				
				ac_func =
					setTimeout(function(){
						
						ac_func = null;
						getac(); // get results after 100ms of no keystroke
						resolve();
					}, 200);
			});
		}
		
		function render_ac(query, list){
			
			if(list.length === 0){
				
				autocomplete_div.style.display = "none";
				return;
			}
			
			html = "";
			
			// prepare regex
			var highlight = query.split(" ");
			var regex = [];
			
			for(var k=0; k<highlight.length; k++){
				
				// espace regex
				regex.push(
					highlight[k].replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
				);
			}
			
			regex = new RegExp(highlight.join("|"), "gi");
			
			for(var i=0; i<list.length; i++){
				
				html +=
					'<div tabindex="0" class="entry" onclick="handle_entry_click(this);">' +
						htmlspecialchars(
							list[i]
						).replace(
							regex,
							'<u>$&</u>'
						) +
					'</div>';
			}
			
			autocomplete_div.innerHTML = html;
			autocomplete_div.style.display = "block";
		}
		
		var should_focus = false;
		document.addEventListener("keydown", function(event){
			
			if(event.key == "Escape"){
				
				document.activeElement.blur();
				focuspos = -1;
				autocomplete_div.style.display = "none";
				return;
			}
			
			if(
				is_click_within(event.target, "searchbox") === false ||
				typeof autocomplete_cache[getsearchboxtext()] == "undefined"
			){
				
				return;
			}
			
			switch(event.key){
				
				case "ArrowUp":
					event.preventDefault();
					focuspos--;
					if(focuspos === -2){
						
						focuspos = autocomplete_cache[getsearchboxtext()].length - 1;
					}
					break;
				
				case "ArrowDown":
				case "Tab":
					event.preventDefault();
					
					focuspos++;
					if(focuspos >= autocomplete_cache[getsearchboxtext()].length){
						
						focuspos = -1;
					}
					break;
				
				case "Enter":
					should_focus = true;
					
					if(focuspos !== -1){
						
						// replace input content
						event.preventDefault();
						searchbox.value =
							autocomplete_div.getElementsByClassName("entry")[focuspos].innerText;
						break;
					}
					break;
				
				default:
					focuspos = -1;
					break;
			}
			
			if(focuspos === -1){
				
				searchbox.focus();
				return;
			}
			
			autocomplete_div.getElementsByClassName("entry")[focuspos].focus();
		});
		
		window.addEventListener("blur", function(){
			
			autocomplete_div.style.display = "none";
		});
		
		document.addEventListener("keyup", function(event){
			
			// handle ENTER key on entry
			if(should_focus){
				
				should_focus = false;
				searchbox.focus();
			}
		});
		
		document.addEventListener("mousedown", function(event){
			
			// hide input if click is outside
			if(is_click_within(event.target, "searchbox") === false){
				
				autocomplete_div.style.display = "none";
				return;
			}
		});
		
		function handle_entry_click(event){
			
			searchbox.value = event.innerText;
			focuspos = -1;
			searchbox.focus();
		}
		
		searchbox.addEventListener("focus", function(){
			
			focuspos = -1;
			getac();
		});
	}
}