aboutsummaryrefslogtreecommitdiff
path: root/static/js/weabot.js
blob: c379ffcb4d5f0e9250efd9afc89b1f4359617e80 (plain) (blame)
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
var style_cookie = 'weabot_style_ib';

function set_stylesheet(styletitle) {
  var css=document.getElementById("css");
  if(css) {
    css.href="/static/css/" + styletitle.toLowerCase()+".css";
    localStorage.setItem(style_cookie, styletitle);
  }
}

if(style_cookie && localStorage.hasOwnProperty(style_cookie)) {
  set_stylesheet(localStorage.getItem(style_cookie));
}

var hiddenthreads = Array();
/* IE/Opera fix, because they need to go learn a book on how to use indexOf with arrays */
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(elt /*, from*/) {
	var len = this.length;
	var from = Number(arguments[1]) || 0;
	from = (from < 0) ? Math.ceil(from) : Math.floor(from);
	if (from < 0) from += len;
	for (; from < len; from++) {
    if (from in this && this[from] === elt) return from;
	}
	return -1;
  };
}

function postClick(num) {
  var sel = window.getSelection().toString();
  if (sel) sel = sel.replace(/^/gm, ">") + "\n";
  insert(">>"+num+"\n"+sel);
}

function insert(text) {
	var textarea=document.forms.postform.message;
	if(textarea) {
		if(textarea.createTextRange && textarea.caretPos) { // IE 
			var caretPos=textarea.caretPos;
			caretPos.text=caretPos.text.charAt(caretPos.text.length-1)==" "?text+" ":text;
		} else if(textarea.setSelectionRange) { // Firefox 
			var start=textarea.selectionStart;
			var end=textarea.selectionEnd;
			textarea.value=textarea.value.substr(0,start)+text+textarea.value.substr(end);
			textarea.setSelectionRange(start+text.length,start+text.length);
		} else { textarea.value+=text+" "; }
		textarea.focus();
	}
  return false;
}

function quote(b, a) { 
	var v = eval("document." + a + ".message");
	v.value += ">>" + b + "a\ndfs";
	v.focus();
}

function checkhighlight() {
	var match;
	if(match=/#i([0-9]+)/.exec(document.location.toString()))
	if(!document.forms.postform.message.value)
	insert(">>"+match[1]+"\r\n");
	if(match=/#([0-9]+)/.exec(document.location.toString()))
	highlight(match[1]);
}

function highlight(post) {
	var cells = document.getElementsByClassName("reply");
	for(var i=0;i<cells.length;i++) if(cells[i].className == "reply highlight") cells[i].className = "reply";
	var reply = document.getElementById("reply" + post);
	if(reply) {
		reply.className = "reply highlight";
		var match = /^([^#]*)/.exec(document.location.toString());
		document.location = match[1] + "#" + post;
	}
}

function expandimg(e) {
  var post_id = e.dataset.id;
  var img_url = e.href;
  var thumb_url = e.dataset.thumb;
  var img_w = parseInt(e.dataset.w);
  var img_h = parseInt(e.dataset.h);
  var thumb_w = parseInt(e.dataset.tw);
  var thumb_h = parseInt(e.dataset.th);
  var format = img_url.substring(img_url.lastIndexOf(".")+1, img_url.length);
  var exp_vid = 0;

  if(window.innerWidth > 900) var ratio = Math.min((window.innerWidth-130) / img_w, 1);
  else var ratio = Math.min((window.innerWidth-40) / img_w, 1);

  if(thumb_w < 1) return true;
  
  var img_cont = document.getElementById("thumb" + post_id);
  var post_block = img_cont.parentElement.parentElement.getElementsByTagName("blockquote")[0];
  var img;
  
  for(var i = 0; i < img_cont.childNodes.length; i++)
    if(img_cont.childNodes[i].nodeName.toLowerCase() == "img") {
      img = img_cont.childNodes[i];
    } else if(img_cont.childNodes[i].nodeName.toLowerCase() == "video") {
      img = img_cont.childNodes[i];
      exp_vid = 1;
    }
  
  if(img) {
    if( (format == "webm") && (exp_vid == 0) ) var new_img = document.createElement("video");
    else var new_img = document.createElement("img");
    new_img.setAttribute("class", "thumb");
    new_img.setAttribute("alt", "" + post_id);
    
    if( (img.getAttribute("width") == ("" + thumb_w)) && (img.getAttribute("height") == ("" + thumb_h)) ) {
      // thumbnail -> fullsize
      if(format == "webm") {
        new_img.setAttribute("controls", "");
        new_img.setAttribute("loop", "");
        new_img.setAttribute("autoplay", "");
      }
      new_img.setAttribute("src", "" + img_url);
      new_img.setAttribute("width", img_w);
      new_img.setAttribute("height", img_h);
      new_img.setAttribute("style", "max-width:"+Math.floor((img_w*ratio))+"px;max-height:"+Math.floor((img_h*ratio))+"px;");
      post_block.setAttribute("style", "");
      img_cont.style.display = 'table';
    } else {
      // fullsize -> thumbnail
      if(format == "webm") {
        new_img.removeAttribute("controls");
        new_img.removeAttribute("loop");
        new_img.removeAttribute("autoplay");
      }
      new_img.setAttribute("src", "" + thumb_url);
      new_img.setAttribute("width", thumb_w);
      new_img.setAttribute("height", thumb_h);
      post_block.setAttribute("style", "margin-left:"+(parseInt(thumb_w)+40)+"px;max-width:"+(1000-parseInt(thumb_w))+"px");
      img_cont.removeAttribute("style");
    }

    while(img_cont.lastChild) img_cont.removeChild(img_cont.lastChild);
    
    img_cont.appendChild(new_img);
  }
}

function filePreview(e) {
  var file = postform.file.files[0];
  var inpt = document.getElementById("file");
  var prev = document.getElementById("filepreview");
  var noimg = document.getElementById("noimage");
  if (noimg) noimg = document.getElementById("noimage").parentNode;
  if (file.size > (maxsize*1024)) { inpt.value = ""; return alert("El archivo es muy grande. El tamaño máximo es " + maxsize + " KB."); }
  if (!types.includes(inpt.value.slice(inpt.value.lastIndexOf(".")+1).toUpperCase())) { inpt.value = ""; return alert("Tipo de archivo no soportado."); }
  var read = new FileReader();
  read.readAsDataURL(file);
  read.onload = function(){
    inpt.style.display = "none";
    if (noimg) noimg.style.display = "none";
    prev.removeAttribute("style");
    var fname = (file.name.length < 20) ? file.name : file.name.substr(0, 19) + "…";
    if (file.type.startsWith("image")) prev.insertAdjacentHTML('beforeend', '<img class="thumbpreview" src="' + read.result + '" /> ' + fname);
    else prev.insertAdjacentHTML('beforeend', fname);
    prev.appendChild(document.createTextNode(" ["));
    var btn = document.createElement("a");
    btn.href = "#";
    btn.innerText = "Quitar"
    btn.addEventListener("click", function(e) {
      e.preventDefault();
      prev.innerHTML = "";
      prev.style.display = "none";
      inpt.removeAttribute("style");
      if (noimg) noimg.removeAttribute("style");
      inpt.value = "";
    });
    prev.appendChild(btn);
    prev.appendChild(document.createTextNode("] "));
  };
}

function togglethread(e) {
  if(e.parentElement.id.startsWith("unhide")) {
    var threadid = e.parentElement.id.substr(6);
  } else if(e.parentElement.parentElement.id.startsWith("thread")) {
    var threadid = e.parentElement.parentElement.id.substr(6);
  } else { return; }
  if (hiddenthreads.toString().indexOf(threadid) !== -1) {
    document.getElementById("unhide" + threadid).style.display = "none";
    document.getElementById("thread" + threadid).removeAttribute("style");
    hiddenthreads.splice(hiddenthreads.indexOf(threadid), 1);
  } else {
    document.getElementById("unhide" + threadid).removeAttribute("style");
    document.getElementById("thread" + threadid).style.display = "none";
    hiddenthreads.push(threadid);
  }
  if (hiddenthreads == "") localStorage.removeItem("hiddenthreads");
  else localStorage.setItem("hiddenthreads", hiddenthreads.join("!"));
}

function saveInputs(e) {
  var e = e || window.event;
  var form = e.target || e.srcElement;
  if(typeof(form.fielda) !== "undefined") weabot.name = form.fielda.value;
  if(typeof(form.fielda) !== "undefined") weabot.email = form.fieldb.value;
  localStorage.setItem("weabot", JSON.stringify(weabot));
}

function setInputs(id) {
  if (document.getElementById(id)) {
    with(document.getElementById(id)) {
    if(typeof(fielda) !== 'undefined' && !fielda.value && weabot.name) fielda.value = weabot.name;
    if(typeof(fielda) !== 'undefined' && !fieldb.value && weabot.email) fieldb.value = weabot.email;
    if(!password.value) password.value = getPassword();
    addEventListener("submit", saveInputs);
    }
  }
}

function getPassword() {
  if (weabot.password) return weabot.password;
  var pass="";
  var char="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789?!-_.";
  while (pass.length<10) {
    pass += char[Math.floor(Math.random()*char.length)];
  }
  weabot.password = pass;
  localStorage.setItem("weabot", JSON.stringify(weabot));
  return(pass);
}

function catSort(type) {
  for(var i=0;i<srt.length;i++) srt[i].innerHTML=srt[i].innerText;
  srt[type].innerHTML = "<b>"+srt[type].innerText+"</b>";
  var cont = document.getElementById("catalog");
  var elem = document.getElementsByClassName("thread");
  var arr = Array.prototype.slice.call(elem);
  if (type==0) arr.sort(function (a,b) { return (a.dataset.num-b.dataset.num) });
  else if (type==1) arr.sort(function (a,b) { return (b.dataset.id-a.dataset.id) });
  else if (type==2) arr.sort(function (a,b) { return (a.dataset.id-b.dataset.id) });
  else if (type==3) arr.sort(function (a,b) { return (b.dataset.res-a.dataset.res) });
  else if (type==4) arr.sort(function (a,b) { return (a.dataset.res-b.dataset.res) });
  for (var j=0;j<arr.length;j++) cont.appendChild(arr[j]);
  localStorage.setItem("catalog", JSON.stringify(opcs));
}

function catSearch() {
  var filter = document.getElementById("cat_search").value.toLowerCase();
  var nodes = document.getElementsByTagName("p");
  for (i = 0; i < nodes.length; i++) {
    if (nodes[i].innerText.toLowerCase().includes(filter))
      nodes[i].parentNode.removeAttribute("style");
    else nodes[i].parentNode.style.display = "none";
  }
}

function catThumbs(big) {
  var btn = document.getElementById("cat_size");
  var cat = document.getElementById("catalog");
  var threads = document.getElementsByClassName("thread");
  if (opcs.big) {
    cat.className = "enlarged";
    for (j = 0; j < threads.length; j++) {
      img = threads[j].getElementsByTagName("a")[0];
      img.innerHTML = img.innerHTML.replace("/cat/", "/thumb/");
    }
    btn.innerText = "Grande";
  } else {
    cat.removeAttribute("class");
    for (j = 0; j < threads.length; j++) {
      img = threads[j].getElementsByTagName("a")[0];
      img.innerHTML = img.innerHTML.replace("/thumb/", "/cat/");
    }
    btn.innerText = "Pequeño";
  }
  localStorage.setItem("catalog", JSON.stringify(opcs));
}

function catTeasers(teaser) {
  var btn = document.getElementById("cat_hide");
  if (!teaser) {
    var style = document.createElement("style");
    style.id = "teaser_style";
    style.type = "text/css";
    style.innerText = '#catalog p{display:none}';
    document.head.appendChild(style);
    btn.innerText = "Mostrar";
  } else {
    var style = document.getElementById("teaser_style");
    if (style) style.parentNode.removeChild(style);
    btn.innerText = "Ocultar";
  }
  localStorage.setItem("catalog", JSON.stringify(opcs));
}

function catMenu(e) {
  var brd = document.getElementsByName("board")[0].value;
  var id = this.dataset.id;
  this.insertAdjacentHTML('afterbegin', '<div id="thread_ctrl" style="margin-bottom:3px;">[<a href="/cgi/report/' + brd + '/' + id + '">Denunciar</a>] [<a href="#" class="hh">Ocultar</a>]');
  this.getElementsByClassName("hh")[0].addEventListener("click", function(e) {
    document.getElementById("cat" + id + brd).style.display = "none";
    hiddenthreads.push(id + brd);
    localStorage.setItem("hiddenthreads", hiddenthreads.join("!"))
    if (document.getElementById("hidden_label")) { hidden_num++; document.getElementById("hidden_num").innerText = hidden_num; }
    else { hidden_num = 1; catHidden(); }
  });
}

function catMenuClose(e) { document.getElementById("thread_ctrl").remove(); }

function catHidden() {
  var menu = document.getElementById("ctrl");
  menu.insertAdjacentHTML('beforeend', ' <span id="hidden_label">[Hilos ocultos: <span id="hidden_num">' + hidden_num + '</span> - ');
  var lbl = document.getElementById("hidden_label");
  var shw = document.createElement("a");
  shw.href = "#"; shw.innerText = "Deshacer";
  shw.addEventListener("click", function(e) {
    e.preventDefault();
    for(var i=0;i<hiddenthreads.length;i++){
      try {document.getElementById("cat" + hiddenthreads[i]).removeAttribute("style");}
      catch(err) { continue; } }
    lbl.parentElement.removeChild(lbl); hidden_num = 0;
    var aux = hiddenthreads.join("!");
    var exp = new RegExp("\\b[0-9]+" + document.getElementsByName("board")[0].value + "\\b", "g");
    aux = aux.replace(exp, "!"); aux = aux.replace(/!+/g, "!"); aux = aux.replace(/(^!|!$)/g, "");
    if (aux == "") { localStorage.removeItem("hiddenthreads"); hiddenthreads = []; }
    else { localStorage.setItem("hiddenthreads", aux); hiddenthreads = aux.split("!"); }
  });
  lbl.appendChild(shw); lbl.appendChild(document.createTextNode("]"));
}

function applyTheme() {
  var newTheme = document.getElementById("styles").value;
  set_stylesheet(newTheme);
}

function readableSize(B) {
  var thresh = 1024;
  if(Math.abs(B) < thresh) return B + " B";
  var units = ["KB","MB","GB"];
  var u = -1;
  do {
    B /= thresh;
    ++u;
  } while(Math.abs(B) >= thresh && u < units.length - 1);
  return B.toFixed(1)+" "+units[u];
}

function fixFileSize(){
  var obj = document.getElementsByClassName("fs");
  for (var i=0; i<obj.length; i++){
    var parts = obj[i].childNodes[2].textContent.split(" B, ");
    var filesize = parts[0].substring(2);
    obj[i].childNodes[2].textContent = "-(" + readableSize(filesize) + ", " + parts[1];
  }
}

document.addEventListener("DOMContentLoaded", function(e) {
  checkhighlight();
  if (localStorage.hasOwnProperty("weabot")) weabot = JSON.parse(localStorage.getItem("weabot"));
  else weabot = {"name":null,"email":null,"password":null};
  
  board = document.body.dataset.brd;
  var a = document.getElementById("main_nav").getElementsByTagName("a");
  for(var i=0; i<a.length; i++) {
    if (a[i].getAttribute("href") == "/"+board+"/") {a[i].className = "cur_brd"; break;}
  }

  if (screen.width<720) {
    var head=document.getElementById("main_nav");
    var b=head.getElementsByTagName("a");
    var s=document.createElement("select");
    for(var i=1;i<b.length;i++) {
      var o = document.createElement("option");
      o.value = b[i].href;
      o.textContent = b[i].textContent;
      if(b[i].className=="cur_brd") o.defaultSelected = true;
      s.appendChild(o);
    }
    s.addEventListener("change", function(e){ window.location.href=this.value; });
    head.removeChild(head.childNodes[0]);
    head.className = "mob fix";
    head.insertBefore(s, head.childNodes[0]);
  }

  if(localStorage.hasOwnProperty("hiddenthreads")) {
    hiddenthreads = localStorage.getItem("hiddenthreads").split("!");
    if (document.getElementById("catalog")) {
      hidden_num = 0;
      for(var i=0;i<hiddenthreads.length;i++){
        try {
          document.getElementById("cat" + hiddenthreads[i]).style.display = "none";
          hidden_num++;
        } catch(err) { continue; }
      }
      if (hidden_num) { catHidden(); }
    } else {
      for(var i=0;i<hiddenthreads.length;i++){
        try {
          document.getElementById("unhide" + hiddenthreads[i]).removeAttribute("style");
          document.getElementById("thread" + hiddenthreads[i]).style.display = "none";
        } catch(err) { continue; }
      }
    }
  }

  var styleSelect = document.getElementById("styles");
  if (styleSelect) {
    styleSelect.addEventListener("change", applyTheme, false);
    styleSelect.value = localStorage.getItem(style_cookie);
  }

  if (document.getElementById("postform")) {
    setInputs("postform");
    maxsize = document.getElementById("maxsize").innerText;
    types = document.getElementById("filetypes").innerText.split(", ");
    if (types.includes("JPG")) types.push("JPEG");
    postform.file.addEventListener("change", filePreview);
    fixFileSize();
  }
  
  var del = document.getElementById("delform");
  if (del) del.password.value = weabot.password;

  window.addEventListener("hashchange", checkhighlight);

  if (document.getElementById("catalog")) {
    srt = document.getElementsByClassName("cat_sort");
    for(var i=0;i<srt.length;i++) { srt[i].innerHTML=srt[i].innerText; srt[i].addEventListener("click", function(e) { e.preventDefault(); opcs.sort=this.dataset.sort; catSort(opcs.sort); }); }
    document.getElementById("cat_size").addEventListener("click", function(e) { e.preventDefault(); opcs.big=!opcs.big; catThumbs(opcs.big); });
    document.getElementById("cat_hide").addEventListener("click", function(e) { e.preventDefault(); opcs.teaser=!opcs.teaser; catTeasers(opcs.teaser); });
    document.getElementById("cat_search").addEventListener("keyup", catSearch);
    if (localStorage.hasOwnProperty("catalog")) {
      opcs = JSON.parse(localStorage.getItem("catalog"));
      if(match=/\?sort=([0-9])/.exec(document.location.toString())) opcs.sort=match[1];
      catSort(opcs.sort); catThumbs(opcs.big); catTeasers(opcs.teaser);
    } else {
      opcs = {"sort":1,"big":false,"teaser":true}; localStorage.setItem("catalog", JSON.stringify(opcs));
    }
    var thr = document.getElementsByClassName("thread");
    for(var i=0;i<thr.length;i++) { thr[i].addEventListener("mouseenter", catMenu); thr[i].addEventListener("mouseleave", catMenuClose); }
  }
});
document.addEventListener("click", function(e) {
  var cn = e.target.className;
	if (cn == "num") {
    e.preventDefault();
		postClick(e.target.textContent);
    return;
	}
	if (cn == "tt") {
    e.preventDefault();
		togglethread(e.target);
    return;
	}
	if (cn == "expimg") {
    e.preventDefault();
		expandimg(e.target);
    return;
	}
},false);