RedditRestore

Restores edits and deletes on Reddit

  1. // ==UserScript==
  2. // @name RedditRestore
  3. // @namespace https://www.reddit.dynu.net
  4. // @version 0.8
  5. // @description Restores edits and deletes on Reddit
  6. // @author /u/PortugalCache
  7. // @match https://www.reddit.com/r/*/comments/*/*/
  8. // @exclude https://www.reddit.com/r/*/comments/*/*/*/
  9. // @grant none
  10. // @require https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js
  11. // ==/UserScript==
  12.  
  13.  
  14. (function() {
  15. 'use strict';
  16.  
  17. var postId = location.pathname.match(/comments\/(.+?)\//i)[1];
  18. var postCacheUrl = 'https://www.reddit.dynu.net'+location.pathname;
  19.  
  20. // time ago
  21. var timeSince = function(date) {
  22. var format = function (intervalType) { return interval + ' ' + intervalType + (interval > 1 || interval === 0 ? 's' : '') + ' ago'; };
  23. var seconds = Math.floor((new Date() - date) / 1000);
  24. var interval = Math.floor(seconds / 31536000);
  25. if (interval >= 1) return format('year');
  26. if ((interval = Math.floor(seconds / 2592000)) >= 1) return format('month');
  27. if ((interval = Math.floor(seconds / 86400)) >= 1) return format('day');
  28. if ((interval = Math.floor(seconds / 3600)) >= 1) return format('hour');
  29. if ((interval = Math.floor(seconds / 60)) >= 1) return format('minute');
  30. interval = seconds;
  31. return format('second');
  32. };
  33.  
  34. // time html
  35. var timeHtml = function (timestamp) {
  36. var date = new Date(timestamp*1000);
  37. return `<time title="${date.toString()}" datetime="${date.toISOString()}" class="">${timeSince(date)}</time>`;
  38. };
  39.  
  40. // compare html strings
  41. var compareHtml = function(html1, html2) {
  42. var el1 = document.createElement('span'); el1.innerHTML = html1;
  43. var el2 = document.createElement('span'); el2.innerHTML = html2;
  44. return el1.innerHTML == el2.innerHTML;
  45. };
  46.  
  47. // comment text html
  48. var editsHtml = function (plainTexts, original) {
  49. var html = '', text = '', lastHtml, edits = Object.keys(plainTexts), onlyIns = true, onlyDel = true, texts = {};
  50. for (var i in plainTexts) texts[i] = marked(plainTexts[i]);
  51.  
  52. if (original && !compareHtml(original.replace(/\n/g, ''), texts[edits[edits.length-1]].replace(/\n/g, ''))) {
  53. var i = Math.floor(Date.now()/1000);
  54. texts[i] = original;
  55. edits.push(i);
  56. }
  57. //if (edits.length == 1) return texts[edits[0]];
  58. for (var i in texts) {
  59. if (edits.length != 1) html += '<p class="tagline" style="font-size: 11px; font-weight: bold;">'+(Number(i) ? 'Edited ' + timeHtml(i) : 'Original')+':</p>';
  60. html += lastHtml = text ? htmlDiff(text, text = texts[i]) : text = texts[i];
  61. if (/<span class="del">/.test(lastHtml)) onlyIns = false;
  62. if (/<span class="ins">/.test(lastHtml)) onlyDel = false;
  63. }
  64. if (onlyIns || onlyDel) return htmlDiff(texts[edits[0]], text);
  65. return text + `<div><a href="javascript:" onclick="this.parentNode.childNodes[1].style.display = (this.parentNode.childNodes[1].style.display ? '' : 'none');">Show ${edits.length-1} edits</a><div style="display: none;">${html}</div></div>`;
  66. };
  67.  
  68. // comment html
  69. var commentHtml = function (id, comment, childInnerHTML) {
  70. return `
  71. <div class="midcol unvoted">
  72. <div class="arrow up login-required access-required" data-event-action="upvote" role="button" aria-label="upvote" tabindex="0"></div>
  73. <div class="arrow down login-required access-required" data-event-action="downvote" role="button" aria-label="downvote" tabindex="0"></div>
  74. </div>
  75. <div class="entry unvoted">
  76. <p class="tagline">
  77. <a href="javascript:void(0)" class="expand" onclick="return togglecomment(this)">[–]</a>
  78. <a href="https://www.reddit.com/user/${comment.author}" class="author may-blank id-t2_ydhqk">${comment.author}</a>
  79. <span class="userattrs"></span>
  80. <span class="score dislikes"></span>
  81. <span class="score unvoted"></span>
  82. <span class="score likes"></span>
  83. ${timeHtml(comment.created)}
  84. <span class="del">DELETED</span>
  85. &nbsp;
  86. <a href="javascript:void(0)" class="numchildren" onclick="return togglecomment(this)">(- childs)</a>
  87. </p>
  88. <form action="#" class="usertext warn-on-unload" onsubmit="return post_form(this, 'editusertext')" id="form-t1_${id}6t3"><input type="hidden" name="thing_id" value="t1_${id}">
  89. <div class="usertext-body may-blank-within md-container ">
  90. <div class="md">${editsHtml(comment.text)}</div>
  91. </div>
  92. </form>
  93. <ul class="flat-list buttons">
  94. <li class="first"><a href="${postCacheUrl+id}/" target="_blank" data-event-action="permalink" class="bylink" rel="nofollow">cachelink</a></li>
  95. <li class="reply-button"><a class="access-required" href="javascript:void(0)">reply</a></li>
  96. </ul>
  97. <div class="reportform report-t1_${id}"></div>
  98. </div>
  99. <div class="child">${childInnerHTML ? childInnerHTML : ''}</div>
  100. <div class="clearleft"></div>`;
  101. };
  102.  
  103. // add cachelink button
  104. var addCacheLinkButton = function (id) {
  105. var buttons = document.querySelector('#thing_'+id+' .buttons');
  106. if (buttons) {
  107. var button = document.createElement('li');
  108. button.innerHTML = '<a href="'+postCacheUrl+(/^t1_/.test(id) ? id.replace(/^t1_/, '') + '/' : '')+'" target="_blank">cachelink</a>';
  109. buttons.insertBefore(button, buttons.childNodes[1]);
  110. }
  111. else console.log('Could not add cachelink button to ' + id);
  112. };
  113.  
  114. // add cachelink button to post
  115. addCacheLinkButton('t3_'+postId);
  116.  
  117. // add styles for the green and red background
  118. var style = document.createElement('style');
  119. style.textContent = ".ins, .ins * { background-color: #dfffd1!important; }\n.del, .del * { background-color: #faa!important; }";
  120. document.head.appendChild(style);
  121.  
  122. // retrieve ids of visible comments
  123. var visibleComments = [];
  124. var editedComments = [];
  125. var els = document.getElementsByClassName('parent'); //this way it doesn't match 'morechildren' comments
  126. for (var i = 0; i < els.length; i++) {
  127. var el = els[i].firstChild;
  128. if (el) {
  129. var name = el.getAttribute('name');
  130. if (document.querySelector('#thing_t1_'+name+' > div > p > .edited-timestamp')) {
  131. editedComments.push(name);
  132. }
  133. else visibleComments.push(name);
  134. }
  135. }
  136.  
  137. var moreCommentsLoadedTimer = {};
  138. var observer = new MutationObserver(function(mutations) {
  139. mutations.forEach(function(mutation) {
  140. if (!mutation.target.querySelector(':scope > .morechildren')) {
  141. var id = mutation.target.parentNode.parentNode.id;
  142. if (moreCommentsLoadedTimer[id]) clearTimeout(moreCommentsLoadedTimer[id]);
  143. moreCommentsLoadedTimer[id] = setTimeout(function () {
  144. console.log("more comments for:", id);
  145. }, 100);
  146. }
  147. });
  148. });
  149. // configuration of the observer:
  150. var config = {attributes: true, childList: true, characterData: true, attributeOldValue: true};
  151.  
  152. // retrieve ids of morechildren comments
  153. var hiddenComments = [];
  154. var els = document.querySelectorAll('.morechildren, .morerecursion');
  155. for (var i = 0; i < els.length; i++) {
  156. observer.observe(els[i].parentNode, config);
  157. var id = els[i].parentNode.parentNode.parentNode.id;
  158. if (id) hiddenComments.push(id.replace(/^thing_t1_/, ''));
  159. }
  160.  
  161. // fixme: will repeat ids already in visible comments
  162. // retrieve ids of orphan comments
  163. var orphanComments = [];
  164. var deletedComments = document.getElementsByClassName('deleted');
  165. var getFirstOrphanComment = function (deletedComment) {
  166. return deletedComment.querySelector('.child > div > .comment:not(.deleted)');
  167. };
  168. for (var i = 0; i < deletedComments.length; i++) {
  169. var child = getFirstOrphanComment(deletedComments[i]);
  170. if (child) orphanComments.push(child.id.replace(/^thing_t1_/, ''));
  171. }
  172.  
  173. // retrieve ids of comments from deleted users
  174. //var it = function (xpath) { var r = [], n = null; while (n = xpath.iterateNext()) r.push(n); return r; };
  175. var deletedUsersComments = [], deletedUserPost = false;
  176. var els = document.evaluate('//span[@class="author" and text()="[deleted]"]/../../..', document, null, XPathResult.ANY_TYPE, null), el;
  177. while ((el = els.iterateNext())) {
  178. if (/^thing_t3_/.test(el.id)) deletedUserPost = true;
  179. else deletedUsersComments.push(el.id.replace(/^thing_t1_/, ''));
  180. }
  181.  
  182. // is removed post
  183. var deletedPost = document.evaluate('//em[text()="[removed]"]/..', document, null, XPathResult.ANY_TYPE, null).iterateNext();
  184. if (deletedPost) deletedPost.innerHTML = `<div class="md"><p></p></div>`;
  185.  
  186. // handle response
  187. var responseHandler = function (responseText) {
  188. var result = JSON.parse(responseText);
  189. console.log(result);
  190.  
  191. var addReplyButton = function (el, comment) {
  192. el.querySelector('.reply-button').addEventListener('click', function (e) {
  193. var parent = e.target.parentNode.parentNode.parentNode.parentNode, replyButton;
  194. do {
  195. parent = parent.parentNode;
  196. replyButton = parent.querySelector(':scope > .entry > .buttons .reply-button');
  197. console.log(parent, replyButton);
  198. } while (parent.className != 'commentarea' && !replyButton);
  199. if (replyButton) replyButton.firstChild.click();
  200.  
  201. var text; for (var i in comment.text) text = comment.text[i];
  202. text = text.split("\n");
  203. for (var i = 0; i < text.length; i++) if (text[i]) text[i] = ' > /u/' + comment.author + ': ' + text[i];
  204. text = text.join("\n");
  205.  
  206. var textarea = parent.querySelector('textarea');
  207. textarea.value = text + "\n\n";
  208. textarea.focus();
  209. });
  210. };
  211.  
  212. for (var id in result.edits) {
  213. // add edits
  214. var md = document.querySelector('#thing_'+id+' .md');
  215. if (md) {
  216. md.innerHTML = editsHtml(result.edits[id], md.innerHTML);
  217. addCacheLinkButton(id);
  218. }
  219. else console.log('could not add edits to ' + id);
  220. }
  221.  
  222. // restore deleted authors
  223. if (result.authors) {
  224. for (var id in result.authors) {
  225. var span = document.querySelector('#thing_'+(/^t3_/.test(id) ? '' : 't1_')+id+' .author');
  226. var author = result.authors[id];
  227. span.innerHTML = `<a href="https://www.reddit.dynu.net/user/${author}" class="author del" target="_blank">${author}</a>`;
  228. }
  229. }
  230.  
  231. // restore parent of orphan comments
  232. var deletedComments = document.getElementsByClassName('deleted');
  233. for (var i = 0; i < deletedComments.length; i++) {
  234. var firstOrphan = getFirstOrphanComment(deletedComments[i]);
  235. if (firstOrphan) {
  236. var orphanName = firstOrphan.id.replace(/^thing_t1_/, '');
  237. var parent = result.parents && result.parents[orphanName];
  238. if (parent) {
  239. deletedComments[i].innerHTML = commentHtml(parent.id, parent, deletedComments[i].querySelector('.child').innerHTML);
  240. addReplyButton(deletedComments[i], parent);
  241. deletedComments[i].className = deletedComments[i].className.replace(/deleted/i,''); // becomes null after this
  242. }
  243. else console.log('parent not received for ' + orphanName);
  244. }
  245. }
  246.  
  247. // restore remaining deleted comments
  248. if (result.dels) {
  249. var siteTable = document.getElementById('siteTable_t3_'+postId, true);
  250. var keys = Object.keys(result.dels).sort(function(a,b) { return a > b ? 1 : -1;}); // we want to add comments by chronological order
  251. for (var i = 0; i < keys.length; i++) {
  252. var name = keys[i];
  253. var comment = result.dels[name];
  254. var parentEl = comment.parent_id ? document.querySelector('#thing_t1_'+comment.parent_id+' .child') : siteTable;
  255. if (parentEl) {
  256. var div = document.createElement('div');
  257. div.className = 'thing comment noncollapsed';
  258. div.id = 'thing_t1_' + name;
  259. div.innerHTML = commentHtml(name, comment);
  260. addReplyButton(div, comment);
  261. parentEl.appendChild(div);
  262. }
  263. else console.log('add comment ' + name + ' to ' + comment.parent_id + ': ERROR');
  264. }
  265. }
  266.  
  267. };
  268.  
  269. // the request to the cache site
  270. var xhttp = new XMLHttpRequest();
  271. xhttp.onreadystatechange = function() {
  272. if (this.readyState == 4 && this.status == 200 && this.responseText) {
  273. responseHandler(this.responseText);
  274. }
  275. };
  276. xhttp.open("POST", "https://www.reddit.dynu.net/?gm=0.8&p="+postId, true);
  277. xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  278. xhttp.send(
  279. function (post) {
  280. var r = [];
  281. for (var i in post.arrays) if (post.arrays[i].length) r.push(i + '=' + post.arrays[i].join(','));
  282. for (var i in post.booleans) if (post.booleans[i]) r.push(i + '=');
  283. return r.join('&');
  284. }({
  285. arrays: {c: visibleComments, o: orphanComments, uc: deletedUsersComments, e: editedComments, h: hiddenComments},
  286. booleans: {up: deletedUserPost, dp: deletedPost}
  287. })
  288. );
  289. })();
  290.  
  291. // compute diff between two strings
  292. this.diff = function(oldStr, newStr) {
  293. var array_keys = function (a, s) {
  294. var r = [];
  295. if (!a) return r;
  296. for (var i = 0; i < a.length; i++) {
  297. if (a[i] == s) r.push(i);
  298. }
  299. return r;
  300. };
  301. var maxlen = 0, omax = 0, nmax = 0, matrix = [];
  302. for (var oindex = 0; oindex < oldStr.length; oindex++) {
  303. var ovalue = oldStr[oindex];
  304. var nkeys = array_keys(newStr, ovalue);
  305. for (var i = 0; i < nkeys.length; i++) {
  306. var nindex = nkeys[i];
  307. if (!matrix[oindex]) matrix[oindex] = [];
  308. matrix[oindex][nindex] = (matrix[oindex - 1] && matrix[oindex - 1][nindex - 1]) ?
  309. matrix[oindex - 1][nindex - 1] + 1 : 1;
  310. if (matrix[oindex][nindex] > maxlen) {
  311. maxlen = matrix[oindex][nindex];
  312. omax = oindex + 1 - maxlen;
  313. nmax = nindex + 1 - maxlen;
  314. }
  315. }
  316. }
  317. if (maxlen === 0) return [{d: oldStr, i: newStr}];
  318. return diff(oldStr.slice(0, omax), newStr.slice(0, nmax)).concat(
  319. newStr.slice(nmax, nmax + maxlen)).concat(
  320. diff(oldStr.slice(omax + maxlen), newStr.slice(nmax + maxlen)));
  321. };
  322.  
  323. // pretty print the diff
  324. this.htmlDiff = function(oldStr, newStr) {
  325. var explode = function (str) { return str.trim().match(/<.+?>|[a-záéíóúâêîôûãõç0-9]+[ \n]*|[^a-záéíóúâêîôûãõç0-9]/ig); };
  326. var diffResult = diff(explode(oldStr), explode(newStr));
  327. var ret = '';
  328. for (var i = 0; i < diffResult.length; i++) {
  329. var k = diffResult[i];
  330. if (k instanceof Object) {
  331. ret += (k.d.length ? '<span class="del">'+k.d.join('')+"</span>" : '') +
  332. (k.i.length ? '<span class="ins">'+k.i.join('')+"</span>" : '');
  333. }
  334. else ret += k;
  335. }
  336. return ret;
  337. };