aboutsummaryrefslogtreecommitdiff
path: root/static/js/shobon.js
blob: c9bce9596869d053e05a8782ebfb06b8e978c00d (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
var are_filters = false;
var hide_word = new Set()
var hide_name = new Set();
var hide_id = new Set();

var shobon_ver = "v0.4+";
function shobon() {
  console.log("Running shobon " + shobon_ver);

  boardName = document.getElementsByName("board")[0].value;
  var inThread = document.getElementsByTagName("body")[0].className == "threadpage";
  var newRepliesCounter = 0;

  if(!inThread) {
    /* Create settings link */
    var box = document.getElementsByClassName("links")[0];
    box.appendChild(document.createTextNode(" | "));
    var slnk = document.createElement("a");
    slnk.href = "#";
    slnk.innerHTML = "<b>Configuración</b>";
    slnk.addEventListener("click", shobonSettings);
    box.appendChild(slnk);
  }

  if(localStorage.getItem("shobon_on") == "false") {
    console.log("Shutting down Shobon");
    return;
  }

  if (localStorage.getItem("shobon_usefilters") != "false") {
    loadFilters();
  }

  var threadList = document.getElementsByClassName("thread");
  for (var i = 0; i < threadList.length; i++) {
    var threadId;
    var thread = threadList[i];
    var replyList = thread.getElementsByClassName("reply");
    if (inThread) {
      threadId = document.getElementsByName("parent")[0].value;
    } else {
      threadId = thread.getElementsByTagName("input").parent.value;
    }

    var lastReplyN = replyList[replyList.length - 1].attributes["data-n"].value;
    if(localStorage.getItem("shobon_newposts") == "true" && localStorage.getItem(boardName + "_" + threadId) == null) {
      localStorage.setItem(boardName + "_" + threadId, lastReplyN);
    }
    var lastSeen = localStorage.getItem(boardName + "_" + threadId);
    var newRepliesInThread = 0;

    for (var e = 0; e < replyList.length; e++) {
      var reply = replyList[e];
      var message = reply.getElementsByClassName("msg")[0];

      if(localStorage.getItem("shobon_newposts") == "true") {
        var replyId = reply.attributes["data-n"].value;
        var isNewReply = parseInt(lastSeen) < parseInt(replyId);

        if (isNewReply) {
          newRepliesCounter++;
          newRepliesInThread++;
          reply.children[0].innerHTML += " <span class='shobonNew' style='color: #CC6666; font-weight: bold;'>NUEVO!</span>";
        }
      }

      // ocultar mensajes que tienen palabras en la blacklist
      if(are_filters) {
        checkBlackList(reply);
      }

      // reemplaza los codigos iso de los paises por el nombre completo
      if (localStorage.getItem("shobon_country") == "true" && boardName == "world") {
        replaceCountryName(reply)
      }
      // colorea los id's
      if(localStorage.getItem("shobon_ids") == "true") {
        paintIds(reply);
      }
      // deja la barra superior fija
      if(localStorage.getItem("shobon_navbar") == "true") {
        fixedNav();
      }
      // incluye imagenes
      if(localStorage.getItem("shobon_embedimg") == "true") {
        embedImg(reply);
      }
 
    }
    if (newRepliesInThread > 0 && !inThread) {
      thread.getElementsByClassName("threadlinks")[0].innerHTML += "<span onClick='localStorage.setItem(\"" + boardName + "_" + threadId + "\" , " + lastReplyN + "); this.hidden = true;' style='font-weight: bold; background: #81a2be; padding: 5px; border-radius: 5px; float: right; margin-bottom: 10px;'>Marcar como leido</span>";
    }

  }
  if (newRepliesCounter > 0 && !inThread) {
    var banner = document.createElement("span");
    banner.onclick = function() { this.hidden = true; };
    banner.setAttribute("style", "font-weight: bold; background: #8c9440; padding: 8px; border-radius: 30px; float: right; position: fixed; bottom: 10px; right: 10px");
    banner.textContent = "Nuevas respuestas: " + newRepliesCounter;
    document.body.appendChild(banner);
  }

  if(localStorage.getItem("shobon_newposts") == "true" && inThread) {
    localStorage.setItem(boardName + "_" + threadId, lastReplyN);
  }
}

function on_checked(e) {
  localStorage.setItem(e.target.id, e.target.checked);
}
function createCheckbox(name, label, def) {
  var lbl = document.createElement("label");
  var chk = document.createElement("input");
  chk.type = "checkbox";
  chk.id = name;
  chk.onchange = on_checked;
  lbl.appendChild(chk);
  lbl.insertAdjacentHTML("beforeend", " "+label+" ");

  var checked = localStorage.getItem(name);
  if(checked !== null) {
    chk.checked = (checked == "true");
  } else {
    chk.checked = def;
  }

  return lbl;
}
function createOption(name, label) {
  var opt = document.createElement("option");
  opt.value = name;
  opt.text = label;
  return opt;
}
function createButton(label, func) {
  var btn = document.createElement("button");
  btn.type = "button";
  btn.textContent = label;
  btn.onclick = func;
  return btn;
}
function createTh(label, w) {
  var th = document.createElement("th");
  th.textContent = label;
  th.width = w;
  return th;
}
function loadFilters() {
  var filters = JSON.parse(localStorage.getItem("shobon_filters"));

  if(filters) {
    are_filters = true;
    hide_word = new Set(filters.word);
    hide_name = new Set(filters.name);
    hide_id = new Set(filters.id);
  }
}
function saveFilters() {
  var filters = {
    "word": Array.from(hide_word),
    "name": Array.from(hide_name),
    "id": Array.from(hide_id)
  };
  localStorage.setItem("shobon_filters", JSON.stringify(filters));
}
function deleteFilter(e) {
  var tr = this.parentElement.parentElement;
  var name = tr.dataset.name;
  var type = tr.dataset.type;
  switch(type) {
    case "word":
      hide_word.delete(name);
      break;
    case "name":
      hide_name.delete(name);
      break;
    case "id":
      hide_id.delete(name);
      break;
  }
  saveFilters();
  tr.remove();
}
function addFilter(e) {
  var name = document.getElementById("txt_filter").value;
  var type = document.getElementById("lst_type").value;
  if(!name) {
    return;
  }

  switch(type) {
    case "word":
      hide_word.add(name);
      break;
    case "name":
      hide_name.add(name);
      break;
    case "id":
      hide_id.add(name);
      break;
  }
  addToFilterTable(name, type);
  saveFilters();
  document.getElementById("txt_filter").value = "";
}

function addToFilterTable(name, type) {
  var dict = {"word": "Palabra", "name": "Nombre/Tripcode", "id": "ID"};
  var table = document.getElementById("tbl_filters");

  var td_type = document.createElement("td");
  td_type.textContent = dict[type];
  var td_name = document.createElement("td");
  td_name.textContent = name;
  var td_btn = document.createElement("td");
  td_btn.appendChild(createButton("X", deleteFilter));

  var tr = document.createElement("tr");
  tr.dataset.type = type;
  tr.dataset.name = name;
  tr.appendChild(td_type);
  tr.appendChild(td_name);
  tr.appendChild(td_btn);

  table.appendChild(tr);
}
function shobonSettings(e) {
  e.preventDefault();

  var titlebox = document.getElementById("titlebox");
  
  var box = document.getElementById("settings");
  if(box) {
   box.hidden = !box.hidden;
  } else {
   box = document.createElement("div");
   box.id = "settings";
   box.className = "innerbox";
   box.style.textAlign = "center";

   var p = document.createElement("div");
   p.appendChild(createCheckbox("shobon_on", "<b>Activar extensión</b>", true));
   p.appendChild(createCheckbox("shobon_navbar", "Fijar barra superior", false));
   p.appendChild(createCheckbox("shobon_ids", "Colorear IDs", false));
   p.appendChild(createCheckbox("shobon_embedimg", "Incluir imágenes miniatura", false));
   p.appendChild(createCheckbox("shobon_newposts", "Destacar mensajes nuevos", false));
   p.appendChild(createCheckbox("shobon_country", "Reemplazar códigos de país por nombres", false));
   p.appendChild(createCheckbox("shobon_time", "Convertir fechas a hora local", true));
   p.appendChild(createCheckbox("shobon_backlink", "Mostrar quién ha citado un post", true));
   p.appendChild(createCheckbox("shobon_preview", "Previsualizar citas", true));
   p.appendChild(createCheckbox("shobon_usefilters", "Activar filtros", false));
   /*var a = document.createElement("a");
   a.href = "#";
   a.innerText = "[Editar filtros]";
   a.addEventListener("click", function() {
    var x = document.getElementById("filters");
    x.hidden = !x.hidden;
   });
   p.appendChild(a);*/
   box.appendChild(p);

   var title2 = document.createElement("h6");
   title2.textContent = "Filtros";
   title2.style.fontSize = "18px";
   title2.style.margin = "0.5em 0";
   box.appendChild(title2);

   box.appendChild(document.createTextNode("Filtrar mensajes por: "));

   var lst_type = document.createElement("select");
   lst_type.id = "lst_type";
   lst_type.appendChild(createOption("word", "Palabra"));
   lst_type.appendChild(createOption("name", "Nombre/Tripcode"));
   lst_type.appendChild(createOption("id", "ID"));
   box.appendChild(lst_type);

   var txt_filter = document.createElement("input");
   txt_filter.id = "txt_filter";
   txt_filter.type = "text";
   box.appendChild(txt_filter);

   box.appendChild(createButton("Agregar", addFilter));

   var tbl_filters = document.createElement("table");
   tbl_filters.id = "tbl_filters";
   tbl_filters.border = "1";
   tbl_filters.style.margin = "0 auto";
   var row = document.createElement("tr");
   row.appendChild(createTh("Tipo", 150));
   row.appendChild(createTh("Filtro", 300));
   row.appendChild(createTh("", 75));
   tbl_filters.appendChild(row);
   box.appendChild(tbl_filters);
   
   var msg = document.createElement("a");
   msg.style.display = "block";
   msg.href = "#";
   msg.textContent = "Actualizar página para ver cambios";
   msg.style.marginTop = "1em";
   msg.addEventListener("click", function() { location.reload(); });
   box.appendChild(msg);

   titlebox.appendChild(box);

   var i;
   hide_word.forEach(v => {
     addToFilterTable(v, "word")
   });
   hide_name.forEach(v => {
     addToFilterTable(v, "name")
   });
   hide_id.forEach(v => {
     addToFilterTable(v, "id")
   });
  }
}

function replaceCountryName(reply) {
  var country = JSON.parse('{"AF":"Afghanistan","AX":"A£land Islands","AL":"Albania","DZ":"Algeria","AS":"American Samoa","AD":"Andorra","AO":"Angola","AI":"Anguilla","AQ":"Antarctica","AG":"Antigua and Barbuda","AR":"Argentina","AM":"Armenia","AW":"Aruba","AU":"Australia","AT":"Austria","AZ":"Azerbaijan","BS":"Bahamas","BH":"Bahrain","BD":"Bangladesh","BB":"Barbados","BY":"Belarus","BE":"Belgium","BZ":"Belize","BJ":"Benin","BM":"Bermuda","BT":"Bhutan","BO":"Bolivia (Plurinational State of)","BQ":"Bonaire, Sint Eustatius and Saba","BA":"Bosnia and Herzegovina","BW":"Botswana","BV":"Bouvet Island","BR":"Brazil","IO":"British Indian Ocean Territory","BN":"Brunei Darussalam","BG":"Bulgaria","BF":"Burkina Faso","BI":"Burundi","KH":"Cambodia","CM":"Cameroon","CA":"Canada","CV":"Cabo Verde","KY":"Cayman Islands","CF":"Central African Republic","TD":"Chad","CL":"Chile","CN":"China","CX":"Christmas Island","CC":"Cocos (Keeling) Islands","CO":"Colombia","KM":"Comoros","CG":"Congo","CD":"Congo (Democratic Republic of the)","CK":"Cook Islands","CR":"Costa Rica","CI":"CAŒte d\'Ivoire","HR":"Croatia","CU":"Cuba","CW":"CuraAXao","CY":"Cyprus","CZ":"Czech Republic","DK":"Denmark","DJ":"Djibouti","DM":"Dominica","DO":"Dominican Republic","EC":"Ecuador","EG":"Egypt","SV":"El Salvador","GQ":"Equatorial Guinea","ER":"Eritrea","EE":"Estonia","ET":"Ethiopia","FK":"Falkland Islands (Malvinas)","FO":"Faroe Islands","FJ":"Fiji","FI":"Finland","FR":"France","GF":"French Guiana","PF":"French Polynesia","TF":"French Southern Territories","GA":"Gabon","GM":"Gambia","GE":"Georgia","DE":"Germany","GH":"Ghana","GI":"Gibraltar","GR":"Greece","GL":"Greenland","GD":"Grenada","GP":"Guadeloupe","GU":"Guam","GT":"Guatemala","GG":"Guernsey","GN":"Guinea","GW":"Guinea-Bissau","GY":"Guyana","HT":"Haiti","HM":"Heard Island and McDonald Islands","VA":"Holy See","HN":"Honduras","HK":"Hong Kong","HU":"Hungary","IS":"Iceland","IN":"India","ID":"Indonesia","IR":"Iran (Islamic Republic of)","IQ":"Iraq","IE":"Ireland","IM":"Isle of Man","IL":"Israel","IT":"Italy","JM":"Jamaica","JP":"Japan","JE":"Jersey","JO":"Jordan","KZ":"Kazakhstan","KE":"Kenya","KI":"Kiribati","KP":"Korea (Democratic People\'s Republic of)","KR":"Korea (Republic of)","KW":"Kuwait","KG":"Kyrgyzstan","LA":"Lao People\'s Democratic Republic","LV":"Latvia","LB":"Lebanon","LS":"Lesotho","LR":"Liberia","LY":"Libya","LI":"Liechtenstein","LT":"Lithuania","LU":"Luxembourg","MO":"Macao","MK":"Macedonia (the former Yugoslav Republic of)","MG":"Madagascar","MW":"Malawi","MY":"Malaysia","MV":"Maldives","ML":"Mali","MT":"Malta","MH":"Marshall Islands","MQ":"Martinique","MR":"Mauritania","MU":"Mauritius","YT":"Mayotte","MX":"Mexico","FM":"Micronesia (Federated States of)","MD":"Moldova (Republic of)","MC":"Monaco","MN":"Mongolia","ME":"Montenegro","MS":"Montserrat","MA":"Morocco","MZ":"Mozambique","MM":"Myanmar","NA":"Namibia","NR":"Nauru","NP":"Nepal","NL":"Netherlands","NC":"New Caledonia","NZ":"New Zealand","NI":"Nicaragua","NE":"Niger","NG":"Nigeria","NU":"Niue","NF":"Norfolk Island","MP":"Northern Mariana Islands","NO":"Norway","OM":"Oman","PK":"Pakistan","PW":"Palau","PS":"Palestine, State of","PA":"Panama","PG":"Papua New Guinea","PY":"Paraguay","PE":"Peru","PH":"Philippines","PN":"Pitcairn","PL":"Poland","PT":"Portugal","PR":"Puerto Rico","QA":"Qatar","RE":"RAcunion","RO":"Romania","RU":"Russian Federation","RW":"Rwanda","BL":"Saint BarthAclemy","SH":"Saint Helena, Ascension and Tristan da Cunha","KN":"Saint Kitts and Nevis","LC":"Saint Lucia","MF":"Saint Martin (French part)","PM":"Saint Pierre and Miquelon","VC":"Saint Vincent and the Grenadines","WS":"Samoa","SM":"San Marino","ST":"Sao Tome and Principe","SA":"Saudi Arabia","SN":"Senegal","RS":"Serbia","SC":"Seychelles","SL":"Sierra Leone","SG":"Singapore","SX":"Sint Maarten (Dutch part)","SK":"Slovakia","SI":"Slovenia","SB":"Solomon Islands","SO":"Somalia","ZA":"South Africa","GS":"South Georgia and the South Sandwich Islands","SS":"South Sudan","ES":"Spain","LK":"Sri Lanka","SD":"Sudan","SR":"Suriname","SJ":"Svalbard and Jan Mayen","SZ":"Swaziland","SE":"Sweden","CH":"Switzerland","SY":"Syrian Arab Republic","TW":"Taiwan, Province of China","TJ":"Tajikistan","TZ":"Tanzania, United Republic of","TH":"Thailand","TL":"Timor-Leste","TG":"Togo","TK":"Tokelau","TO":"Tonga","TT":"Trinidad and Tobago","TN":"Tunisia","TR":"Turkey","TM":"Turkmenistan","TC":"Turks and Caicos Islands","TV":"Tuvalu","UG":"Uganda","UA":"Ukraine","AE":"United Arab Emirates","GB":"United Kingdom of Great Britain and Northern Ireland","US":"United States of America","UM":"United States Minor Outlying Islands","UY":"Uruguay","UZ":"Uzbekistan","VU":"Vanuatu","VE":"Venezuela (Bolivarian Republic of)","VN":"Viet Nam","VG":"Virgin Islands (British)","VI":"Virgin Islands (U.S.)","WF":"Wallis and Futuna","EH":"Western Sahara","YE":"Yemen","ZM":"Zambia","ZW":"Zimbabwe"}');
  var countryEM = reply.getElementsByTagName("em")[0];
  var newCountryStr = country[countryEM.innerText.substr(1, 2)];
  countryEM.innerText = "(" + newCountryStr + ")";
}

function checkBlackList(reply) {
  var i;

  // Check words
  var low = reply.children[1].innerText.toLowerCase();
  hide_word.forEach(v => {
    console.log(v);
    if (low.includes(v.toLowerCase())) {
      hidepost(reply);
    }
  });

  // Check name/trip
  var msg_name = reply.firstElementChild.getElementsByClassName("name")[0].textContent.toLowerCase();
  hide_name.forEach(v => {
    if (msg_name.includes(hide_name[i])) {
      hidepost(reply);
    }
  });

  // Check ID
  var date_div = reply.firstElementChild.getElementsByClassName("date")[0].textContent;
  var id_index = date_div.indexOf("ID:");
  if(id_index != -1) {
    var id = date_div.substr(id_index+3);

    hide_id.forEach(v => {
      if(id.includes(v)) {
        hidepost(reply);
      }
    });
  }
}

function paintIds(reply) {
  var dateId = reply.getElementsByClassName("date")[0];
  if (dateId.innerText.includes("ID:")) {
    var postDate = dateId.innerText.split("ID:")[0];
    var userId = dateId.innerText.split("ID:")[1];
    var idColor = toHex(userId).substring(0, 6);
    var reverseColor = invertColor(idColor);
    var lastChar = userId.substring(userId.length-1, userId.length);
    dateId.innerHTML = postDate + "<span style='background-color:#" + idColor + "; color:#" + reverseColor + "; padding:0 3px; border-radius:5px; font-size:0.9em; vertical-align:top;'>ID:" + userId + "</span>";
  }
}

function embedImg(reply) {
  var links = reply.getElementsByTagName("a");
  for(i=0;i<links.length&&i<5;i++) {
    var url = links[i].href;
    if(url.startsWith("https://i.imgur.com")) {
      var ext = url.lastIndexOf('.');
      var thumburl = url.slice(0, ext) + 's' + url.slice(ext);
    } else if(links[i].href.startsWith("https://pbs.twimg.com")) {
      var thumburl = links[i].href + ":thumb";
    } else continue;
    var thumb = document.createElement("img");
    thumb.src = thumburl;
    links[i].appendChild(document.createElement("br"));
    links[i].appendChild(thumb); 
  }
}

function toHex(str) {
  var hex = '';
  for (var i = 0; i < str.length; i++) {
    hex += '' + (str.charCodeAt(i) + 125).toString(16);
  }
  return hex;
}

function invertColor(hex) {
  if (hex.indexOf('#') === 0) {
    hex = hex.slice(1);
  }
  // convert 3-digit hex to 6-digits.
  if (hex.length === 3) {
    hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  }
  if (hex.length !== 6) {
    throw new Error('Invalid HEX color.');
  }
  // invert color components
  var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16),
    g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16),
    b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16);
  // pad each with zeros and return
  return padZero(r) + padZero(g) + padZero(b);
}

function padZero(str, len) {
  len = len || 2;
  var zeros = new Array(len).join('0');
  return (zeros + str).slice(-len);
}

function fixedNav() {
  if (document.body.className === "mainpage" || document.body.className === "threads") {
    document.getElementById("main_nav").style.position = "fixed";
    document.getElementById("main_nav").style.top = "0";
     document.body.style.marginTop = "2em";
  }
}

document.addEventListener('DOMContentLoaded', shobon, false);