aboutsummaryrefslogtreecommitdiff
path: root/static/js/mobile.js
blob: b4dd8cf41fb7cc19a05aac4f1f75d55bfa585716 (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
function sendPost(e) {
  e.preventDefault();
  var button = document.getElementById("post");
  button.disabled = true;
  var sendpost = new XMLHttpRequest();
  var postform = document.getElementById("postform");
  sendpost.open("POST", "/cgi/api/post", true);
  sendpost.send(new FormData(postform));
  sendpost.onreadystatechange = function() {
    if (sendpost.readyState == 4) {
      button.disabled = false;
      var response = JSON.parse(sendpost.responseText);
      if (response.state == "success") { postform.message.value = ""; checkNew(e); }
      else alert(response.message);
    }
  }
}

function postClick(e) {
  e.preventDefault();
  var sel = window.getSelection().toString();
  if (sel) { sel=sel.replace(/^/gm, ">")+"\n"; sel="\n"+sel; }
  insert(">>" + parseInt(this.innerHTML, 10) + 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 getPassword() {
  if (weabot.password) return weabot.password;
	var char="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	var pass="";
	for (var i=0;i<8;i++) {
		var rnd = Math.floor(Math.random()*char.length);
		pass += char.substring(rnd, rnd+1);
	}
  console.log(weabot.password);
	weabot.password = pass;
  localStorage.setItem("weabot", JSON.stringify(weabot));
	return(pass);
}

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() {
  with(document.getElementById("postform")) {
    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 showMenu(e) {
  e.preventDefault();
  if (document.getElementById("mnu-opened")) closeMenu(e);
  this.id = "mnu-opened";
  var brd = postform.board.value;
  var post = this.parentNode.parentNode;
  if (document.body.className === "txt") {
    var id = post.id.substr(1);
    var num = parseInt(post.getElementsByClassName("num")[0].innerText, 10);
  } else {
    var id = post.getElementsByClassName("num")[0].innerText;
    var num = ((post.className === "first") ? 1 : 0);
  }
  var menu = document.createElement("div");
  menu.id = "mnu-list";
  menu.style.top = (e.pageY + 5) + "px";
  menu.style.left = (e.pageX + 5) + "px";
  document.body.appendChild(menu);
  menu = document.getElementById("mnu-list");
  var rep = document.createElement("a");
  rep.href = "#";
  rep.innerText = "Denunciar post";
  rep.addEventListener("click", function(e) {
    var reason = prompt("Razón de denuncia:");
    if (reason === "") while(reason === "") reason = prompt("Error: Ingresa una razón.");
    if (reason) {
      var rep_req = new XMLHttpRequest();
      var report = "/cgi/report/" + brd + "/" + id + ((num) ? "/" + num : "") + "?reason=" + reason;
      rep_req.open("GET", report, true);
      rep_req.send();
      rep_req.onreadystatechange = function() {
        if (rep_req.readyState == 4 && rep_req.status == 200) alert("Denuncia enviada.");
      }
    }
  });
  menu.appendChild(rep);
  var del = document.createElement("a");
  del.href = "#";
  del.innerText = "Eliminar post";
  del.addEventListener("click", function(e) {
    if(confirm("¿Seguro que deseas borrar el mensaje "+((num) ? num : id)+"?")) {
      var del_req = new XMLHttpRequest();
      var del_form = "/cgi/api/delete?dir=" + brd + "&id=" + id + "&password=" + postform.password.value;
      del_req.open("GET", del_form, true);
      del_req.send();
      del_req.onreadystatechange = function() {
        if (del_req.readyState == 4) {
          var response = JSON.parse(del_req.responseText);
          if (response.state == "success") {
            if (num == 1) {
              alert("Hilo eliminado.");
              document.location = "/cgi/mobile/" + brd;
            } else {
              alert("Mensaje eliminado.");
              location.reload();
            }
          } else if (response.state == "failed") alert(response.message);
        }
      }
    }
  });
  menu.appendChild(del);
  var file = post.getElementsByClassName("thm")[0];
  if (file) {
    var dfile = document.createElement("a");
    dfile.href = "#";
    dfile.innerText = "Eliminar archivo";
    dfile.addEventListener("click", function(e) {
      if(confirm("¿Seguro que deseas borrar el archivo del mensaje "+((num) ? num : id)+"?")) {
        var fdel_req = new XMLHttpRequest();
        var fdel_form = "/cgi/api/delete?dir=" + brd + "&id=" + id + "&password=" + postform.password.value + "&imageonly=true";
        fdel_req.open("GET", fdel_form, true);
        fdel_req.send();
        fdel_req.onreadystatechange = function() {
          if (fdel_req.readyState == 4) {
            var response = JSON.parse(fdel_req.responseText);
            if (response.state == "success") {
              alert("Archivo eliminado.");
              post.removeChild(file);
            } else if (response.state == "failed") alert(response.message);
          }
        }
      }
    });
    menu.appendChild(dfile);
  }
  e.stopPropagation();
  this.removeEventListener("click", showMenu);
  document.addEventListener("click", closeMenu);
}

function closeMenu(e) {
  var menu = document.getElementById("mnu-list");
  menu.parentElement.removeChild(menu);
  document.removeEventListener("click", closeMenu);
  var btn = document.getElementById("mnu-opened");
  btn.addEventListener("click", showMenu);
  btn.removeAttribute("id");
  e.preventDefault();
}

function searchSubjects() {
  var filter = document.getElementById("search").value.toLowerCase();
  var nodes = document.getElementsByClassName("list")[0].getElementsByTagName("a");
  for (i = 0; i < nodes.length; i++) {
    if (nodes[i].innerHTML.toLowerCase().split(/<\/?br[^>]*>\s*/im)[0].includes(filter))
      nodes[i].removeAttribute("style");
    else nodes[i].style.display = "none";
  }
}

function searchCatalog() {
  var filter = document.getElementById("catsearch").value.toLowerCase();
  var nodes = document.getElementsByClassName("cat");
  for (i = 0; i < nodes.length; i++) {
    if (nodes[i].innerText.toLowerCase().substring(nodes[i].innerText.indexOf("R)")+2).includes(filter))
      nodes[i].removeAttribute("style");
    else nodes[i].style.display = "none";
  }
}

var lastTime = 0;
var refreshInterval;
var refreshMaxTime = 30;
var refreshTime;
var manual = 0;
var serviceType = 0;
var thread_length = 0;
var thread_lastreply = 0;
var thread_title = "";
var thread_first_length = 0;
var http_request = new XMLHttpRequest();

function checkNew(e) {
  e.preventDefault();
  manual = 1;
  loadJSON();
  if (chk.checked) refreshMaxTime = 25;
}

function loadJSON() {
  if (chk.checked) stopCounter("...");
  if (manual) {
    document.getElementById("n").style.color = "gray";
    document.getElementById("n").innerText = "Revisando...";
  }
  var data_file;
  if (serviceType)
    data_file = "/cgi/api/thread?dir=" + postform.board.value + "&id=" + postform.parent.value + "&offset=" + thread_length + "&time=" + lastTime;
  else return false;
  http_request.open("GET", data_file, true);
  http_request.send();
}

function updateThread(posts, total_replies, serverTime) {
  thread_div = document.getElementById("thread");
  last_elem = document.getElementById("n");

  for (var i = 0; i < posts.length; i++) {
    post = posts[i];
    brd = postform.board.value;
    var div = document.createElement('div');
    div.className = "pst";
    div.id = "p" + post.id;
    if (post.IS_DELETED == 0) {
      s_name = post.name;
      if (post.tripcode) s_name += ' ' + post.tripcode;
      s_time = post.timestamp_formatted.replace(/\(.{1,3}\)/g, " ");
      if (post.file)
        s_img = '<a href="/' + brd + '/src/' + post.file + '" target="_blank" class="thm"><img src="/' + brd + '/mobile/' + post.thumb + '" /><br />' + Math.round(post.file_size/1024) + 'KB ' + post.file.substring(post.file.lastIndexOf(".")+1, post.file.length).toUpperCase() + '</a>';
      else s_img = '';
    }
    if (serviceType == 1) {
      var pad = "0000" + (thread_length + i + 1);
      pad = pad.substr(pad.length-4);
      if (post.IS_DELETED == 0)
        div.innerHTML = '<h3><a href="#" class="num">' + pad + '</a> ' + s_name + '</h3>' + s_img + '<div class="msg">' + post.message + '</div><h4>' + s_time + '<a href="#" class="mnu">|||</a></h4>';
      else if (post.IS_DELETED == 1)
        div.innerHTML = '<h3 class="del"><a href="#" class="num">' + pad + '</a> : Eliminado por el usuario.</h3>';
      else
        div.innerHTML = '<h3 class="del"><a href="#" class="num">' + pad + '</a> : Eliminado por miembro del staff.</h3>';
    } else {
      if (post.IS_DELETED == 0) {
        div.innerHTML = '<h3>' + s_name + ' ' + s_time + ' <a href="#" class="num" name="' + post.id + '">' + post.id + '</a><a href="#" class="mnu">|||</a></h3>' + s_img + '<div class="msg">' + post.message + '</div>';
      } else if (post.IS_DELETED == 1) { div.innerHTML = '<h3 class="del"><a name="' + post.id + '"></a>No.' + post.id + ' eliminado por el usuario.</h3>'; }
      else { div.innerHTML = '<h3 class="del"><a name="' + post.id + '"></a>No.' + post.id + ' eliminado por miembro del staff.</h3>'; }
    }

    div.getElementsByClassName("mnu")[0].addEventListener("click", showMenu);
    div.getElementsByClassName("num")[0].addEventListener("click", postClick);
    thread_div.insertBefore(div, last_elem);
    document.getElementsByTagName("h1")[0].getElementsByTagName("span")[0].innerText = "(" + (thread_length + i + 1) + ")"
  }

  if (posts.length > 0) {
    if (!manual) refreshMaxTime = 10;
    if (!document.hasFocus())
      if (posts.length > 1) notif(thread_title, posts.length + ' nuevos mensajes');
      else notif(thread_title, 'Un nuevo mensaje');
  } else { if (refreshMaxTime <= 60) refreshMaxTime += 5; }

  thread_length = parseInt(total_replies) + 1;
  new_unread = thread_length - thread_first_length;

  if (new_unread) document.title = '(' + new_unread + ') ' + thread_title;
  else document.title = thread_title;
}

function notif(title, msg) {
  var n = new Notification(title, { body: msg });
  setTimeout(n.close.bind(n), 10000);
}

function counter() {
  if (refreshTime < 1) loadJSON();
  else {
    refreshTime--;
    document.getElementById("counter").innerHTML = (refreshTime + 1);
  }
}

function detectService() {
  if (document.getElementById("thread")) {
    thread_title = document.getElementsByTagName("h1")[0].innerHTML.split(" \<span\>")[0] + " - " + document.title;
    thread_length = parseInt(document.getElementsByTagName("h1")[0].getElementsByTagName("span")[0].innerText.slice(1, -1), 10);
    thread_first_length = thread_length;
    if (document.body.className === "txt") {
      serviceType = 1;
      replylist = document.getElementsByClassName("pst");
      thread_lastreply = parseInt(replylist[replylist.length - 1].getElementsByClassName("num")[0].innerText);
      if (thread_length == thread_lastreply) {
        serviceType = 1;
        document.getElementById("n2").setAttribute("style", "border-top:1px solid #c6c7c8;border-left:1px solid #c6c7c8;display:inline-block;text-align:center;width:50%;");
        return true;
      } else return false;
    } else if (document.body.className === "img") {
      serviceType = 2;
      document.getElementById("n").innerText = "Ver nuevos posts";
      document.getElementById("n2").setAttribute("style", "border-top:1px solid #333;border-left:1px solid #333;display:inline-block;text-align:center;width:50%;");
      replylist = document.getElementsByClassName("first");
      replylist += document.getElementsByClassName("pst");
      return true;
    }
  } else return false;
}

function startCounter() {
  refreshTime = refreshMaxTime;
  counter();
  refreshInterval = setInterval(counter, 1000);
}

function stopCounter(str) {
  clearInterval(refreshInterval);
  document.getElementById("counter").innerHTML = str;
}

function autoRefresh(e) {
  chk_snd = document.getElementById("autosound");
  if (document.getElementById("autorefresh").checked) {
    if (chk_snd) chk_snd.disabled = false;
    Notification.requestPermission();
    lastTime = Math.floor(Date.now() / 1000);
    refreshTime = refreshMaxTime;
    startCounter();
  } else {
    if (chk_snd) document.getElementById("autosound").disabled = true;
    stopCounter("OFF");
  }
}

http_request.onreadystatechange = function() {
  if (http_request.readyState == 4) {
    var jsonObj = JSON.parse(http_request.responseText);
    if (jsonObj.state == "success") {
      updateThread(jsonObj.posts, jsonObj.total_replies, jsonObj.time);
      lastTime = jsonObj.time;
      if (chk.checked) startCounter();
    }
    if (manual) {
      document.getElementById("n").style.color = "inherit";
      document.getElementById("n").innerText = "Ver nuevos posts";
    }
    manual = 0;
  }
}

function sortList(type) {
  for(var i=0;i<srts.length;i++) srts[i].removeAttribute("class");
  srts[type].className = "sel";
  var cont = document.getElementById("to_sort");
  var elem = cont.getElementsByTagName("a");
  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]);
}

document.addEventListener("DOMContentLoaded", function(e) {
  if (localStorage.hasOwnProperty("weabot")) weabot = JSON.parse(localStorage.getItem("weabot"));
  else weabot = {"name":null,"email":null,"password":null};

  var ids = document.getElementsByClassName("num");
  for(var i=0;i<ids.length;i++) ids[i].addEventListener("click", postClick);
  
  var form = document.getElementById("postform");
  if (form) {
    setInputs();
    if (document.getElementById("post").value == "Responder")
      form.addEventListener("submit", sendPost);
  }
  
  if (document.getElementById("search")) document.getElementById("search").addEventListener("keyup", searchSubjects);
  if (document.getElementById("catsearch")) document.getElementById("catsearch").addEventListener("keyup", searchCatalog);
  if (document.getElementById("to_sort")) {
    srts = document.getElementsByClassName("ord")[0].getElementsByTagName("a");
    for(var i=0;i<srts.length;i++) srts[i].addEventListener("click", function(e) { e.preventDefault(); sortList(this.dataset.sort); });
  }

  if (document.getElementById("thread")) {
    var mnu = document.createElement('a');
    mnu.href = "#";
    mnu.className = "mnu";
    mnu.innerHTML = "|||";
    if (document.body.className === "txt") var ft = document.getElementsByTagName("h4");
    else if (document.body.className === "img") var ft = document.getElementsByTagName("h3");
    for(var i=0;i<ft.length;i++) {
      if (!ft[i].classList.contains("del")) {
        var cln = mnu.cloneNode(true);
        cln.addEventListener("click", showMenu);
        ft[i].appendChild(cln);
      }
    }
  }

  if (!detectService()) return;
  document.title = thread_title;
  document.getElementById("n").style.display = "inline-block";
  document.getElementById("n").style.width = "50%";
  document.getElementById("n").addEventListener("click", checkNew);
  var lbl = document.createElement("label");
  lbl.id = "auto";
  lbl.style.display = "block";
  lbl.style.padding = "6px 0";
  var btn = document.createElement("input");
  btn.id = "autorefresh";
  btn.setAttribute("type", "checkbox");
  btn.addEventListener("click", autoRefresh);
  var cnt = document.createElement("span");
  cnt.id = "counter";
  cnt.textContent = "OFF";
  document.getElementById("n2").appendChild(lbl);
  document.getElementById("auto").appendChild(btn);
  document.getElementById("auto").appendChild(document.createTextNode(" Auto "));
  document.getElementById("auto").appendChild(cnt);
  
  chk = document.getElementById("autorefresh");
  if (localStorage.getItem("autorefreshmobile")) {
    chk.checked = true;
    autoRefresh();
  }
});

window.addEventListener("unload", function() {  
  chk = document.getElementById("autorefresh");
  if (!serviceType) return;
  if (chk.checked) localStorage.setItem("autorefreshmobile", true);
  else localStorage.removeItem("autorefreshmobile");
});