-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodules_nukecomments.js.html
394 lines (337 loc) · 24.1 KB
/
modules_nukecomments.js.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>modules/nukecomments.js - Documentation</title>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
<script src="scripts/nav.js" defer></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav >
<input type="text" id="nav-search" placeholder="Search" />
<h2><a href="index.html">Home</a></h2><h2><a href="https://github.com/toolbox-team/reddit-moderator-toolbox" target="_blank" class="menu-item" >Github</a></h2><h2><a href="https://www.reddit.com/r/toolbox" target="_blank" class="menu-item" >Subreddit</a></h2><h3>Classes</h3><ul><li><a href="Module.html">Module</a><ul class='methods'><li data-type='method'><a href="Module.html#get">get</a></li><li data-type='method'><a href="Module.html#getEnabled">getEnabled</a></li><li data-type='method'><a href="Module.html#init">init</a></li><li data-type='method'><a href="Module.html#set">set</a></li><li data-type='method'><a href="Module.html#setEnabled">setEnabled</a></li></ul></li><li><a href="TBListener.html">TBListener</a><ul class='methods'><li data-type='method'><a href="TBListener.html#clear">clear</a></li><li data-type='method'><a href="TBListener.html#on">on</a></li><li data-type='method'><a href="TBListener.html#start">start</a></li><li data-type='method'><a href="TBListener.html#stop">stop</a></li></ul></li></ul><h3>Global</h3><ul><li><a href="global.html#DISPLAY_BOTTOM">DISPLAY_BOTTOM</a></li><li><a href="global.html#DISPLAY_CENTER">DISPLAY_CENTER</a></li><li><a href="global.html#FEEDBACK_NEGATIVE">FEEDBACK_NEGATIVE</a></li><li><a href="global.html#FEEDBACK_NEUTRAL">FEEDBACK_NEUTRAL</a></li><li><a href="global.html#FEEDBACK_POSITIVE">FEEDBACK_POSITIVE</a></li><li><a href="global.html#ModNotesBadge">ModNotesBadge</a></li><li><a href="global.html#ModNotesPager">ModNotesPager</a></li><li><a href="global.html#ModNotesPopup">ModNotesPopup</a></li><li><a href="global.html#NoteTableRow">NoteTableRow</a></li><li><a href="global.html#RandomFeedback">RandomFeedback</a></li><li><a href="global.html#RandomQuote">RandomQuote</a></li><li><a href="global.html#TBsettingsObject">TBsettingsObject</a></li><li><a href="global.html#actionButton">actionButton</a></li><li><a href="global.html#addModSubsToSidebar">addModSubsToSidebar</a></li><li><a href="global.html#addToSiteTable">addToSiteTable</a></li><li><a href="global.html#addTrophiesToSidebar">addTrophiesToSidebar</a></li><li><a href="global.html#alert">alert</a></li><li><a href="global.html#baseDomain">baseDomain</a></li><li><a href="global.html#browserName">browserName</a></li><li><a href="global.html#buildSha">buildSha</a></li><li><a href="global.html#buildType">buildType</a></li><li><a href="global.html#button">button</a></li><li><a href="global.html#checkForActions">checkForActions</a></li><li><a href="global.html#cleanSubredditName">cleanSubredditName</a></li><li><a href="global.html#clearCache">clearCache</a></li><li><a href="global.html#colorNameToHex">colorNameToHex</a></li><li><a href="global.html#contextTrigger">contextTrigger</a></li><li><a href="global.html#createDeferredProcessQueue">createDeferredProcessQueue</a></li><li><a href="global.html#daysToMilliseconds">daysToMilliseconds</a></li><li><a href="global.html#debounce">debounce</a></li><li><a href="global.html#debugInformation">debugInformation</a></li><li><a href="global.html#defaultNoteLabelValueToLabelType">defaultNoteLabelValueToLabelType</a></li><li><a href="global.html#delay">delay</a></li><li><a href="global.html#displayNotes">displayNotes</a></li><li><a href="global.html#domain">domain</a></li><li><a href="global.html#escapeHTML">escapeHTML</a></li><li><a href="global.html#fetchModSubs">fetchModSubs</a></li><li><a href="global.html#fetchNewsNotes">fetchNewsNotes</a></li><li><a href="global.html#figureOutMulti">figureOutMulti</a></li><li><a href="global.html#filterModdable">filterModdable</a></li><li><a href="global.html#getActions">getActions</a></li><li><a href="global.html#getAllModNotes">getAllModNotes</a></li><li><a href="global.html#getAnonymizedSettings">getAnonymizedSettings</a></li><li><a href="global.html#getCache">getCache</a></li><li><a href="global.html#getContextURL">getContextURL</a></li><li><a href="global.html#getLastVersion">getLastVersion</a></li><li><a href="global.html#getLatestModNote">getLatestModNote</a></li><li><a href="global.html#getModSubs">getModSubs</a></li><li><a href="global.html#getModlog">getModlog</a></li><li><a href="global.html#getRandomNumber">getRandomNumber</a></li><li><a href="global.html#getSetting">getSetting</a></li><li><a href="global.html#getSettingAsync">getSettingAsync</a></li><li><a href="global.html#getSettings">getSettings</a></li><li><a href="global.html#getSubmissionFullname">getSubmissionFullname</a></li><li><a href="global.html#getSubredditColors">getSubredditColors</a></li><li><a href="global.html#getTime">getTime</a></li><li><a href="global.html#getToolboxDevs">getToolboxDevs</a></li><li><a href="global.html#handleMessage">handleMessage</a></li><li><a href="global.html#handleTBThings">handleTBThings</a></li><li><a href="global.html#handleThing">handleThing</a></li><li><a href="global.html#hideModActionsThings">hideModActionsThings</a></li><li><a href="global.html#htmlDecode">htmlDecode</a></li><li><a href="global.html#htmlEncode">htmlEncode</a></li><li><a href="global.html#humaniseDays">humaniseDays</a></li><li><a href="global.html#init">init</a></li><li><a href="global.html#initialLoadPromise">initialLoadPromise</a></li><li><a href="global.html#isConfigValidVersion">isConfigValidVersion</a></li><li><a href="global.html#isEquivalent">isEquivalent</a></li><li><a href="global.html#isModSub">isModSub</a></li><li><a href="global.html#isNewModmail">isNewModmail</a></li><li><a href="global.html#isOldReddit">isOldReddit</a></li><li><a href="global.html#labelColors">labelColors</a></li><li><a href="global.html#labelNames">labelNames</a></li><li><a href="global.html#link">link</a></li><li><a href="global.html#listenerAliases">listenerAliases</a></li><li><a href="global.html#literalRegExp">literalRegExp</a></li><li><a href="global.html#makeCommentThread">makeCommentThread</a></li><li><a href="global.html#makeQueueOverlay">makeQueueOverlay</a></li><li><a href="global.html#makeSingleComment">makeSingleComment</a></li><li><a href="global.html#makeSubmissionEntry">makeSubmissionEntry</a></li><li><a href="global.html#makeUserSidebar">makeUserSidebar</a></li><li><a href="global.html#messageHandlers">messageHandlers</a></li><li><a href="global.html#millisecondsToDays">millisecondsToDays</a></li><li><a href="global.html#minutesToMilliseconds">minutesToMilliseconds</a></li><li><a href="global.html#modbarExists">modbarExists</a></li><li><a href="global.html#moveArrayItem">moveArrayItem</a></li><li><a href="global.html#newModmailSidebar">newModmailSidebar</a></li><li><a href="global.html#niceDateDiff">niceDateDiff</a></li><li><a href="global.html#notification">notification</a></li><li><a href="global.html#overlay">overlay</a></li><li><a href="global.html#pager">pager</a></li><li><a href="global.html#pagerForItems">pagerForItems</a></li><li><a href="global.html#parseComments">parseComments</a></li><li><a href="global.html#parser">parser</a></li><li><a href="global.html#popup">popup</a></li><li><a href="global.html#progressivePager">progressivePager</a></li><li><a href="global.html#purify">purify</a></li><li><a href="global.html#purifyObject">purifyObject</a></li><li><a href="global.html#regExpEscape">regExpEscape</a></li><li><a href="global.html#relativeTime">relativeTime</a></li><li><a href="global.html#reloadIframe">reloadIframe</a></li><li><a href="global.html#reloadToolbox">reloadToolbox</a></li><li><a href="global.html#remove">remove</a></li><li><a href="global.html#removeLastDirectoryPartOf">removeLastDirectoryPartOf</a></li><li><a href="global.html#removeQuotes">removeQuotes</a></li><li><a href="global.html#replaceAll">replaceAll</a></li><li><a href="global.html#replaceTokens">replaceTokens</a></li><li><a href="global.html#saneSort">saneSort</a></li><li><a href="global.html#saneSortAs">saneSortAs</a></li><li><a href="global.html#saveSettingsToBrowser">saveSettingsToBrowser</a></li><li><a href="global.html#searchProfile">searchProfile</a></li><li><a href="global.html#setCache">setCache</a></li><li><a href="global.html#setSetting">setSetting</a></li><li><a href="global.html#setSettingAsync">setSettingAsync</a></li><li><a href="global.html#settings">settings</a></li><li><a href="global.html#settingsToObject">settingsToObject</a></li><li><a href="global.html#shortVersion">shortVersion</a></li><li><a href="global.html#showNote">showNote</a></li><li><a href="global.html#sortBy">sortBy</a></li><li><a href="global.html#standardColors">standardColors</a></li><li><a href="global.html#stringToColor">stringToColor</a></li><li><a href="global.html#submissionFullnamesCache">submissionFullnamesCache</a></li><li><a href="global.html#tbRedditEvent">tbRedditEvent</a></li><li><a href="global.html#textFeedback">textFeedback</a></li><li><a href="global.html#timeConverterRead">timeConverterRead</a></li><li><a href="global.html#title_to_url">title_to_url</a></li><li><a href="global.html#toolboxVersion">toolboxVersion</a></li><li><a href="global.html#toolboxVersionName">toolboxVersionName</a></li><li><a href="global.html#typeNames">typeNames</a></li><li><a href="global.html#unescapeHTML">unescapeHTML</a></li><li><a href="global.html#unescapeJSON">unescapeJSON</a></li><li><a href="global.html#verifiedSettingsSave">verifiedSettingsSave</a></li><li><a href="global.html#watchForURLChanges">watchForURLChanges</a></li><li><a href="global.html#wrapWithLastValue">wrapWithLastValue</a></li><li><a href="global.html#zlibDeflate">zlibDeflate</a></li><li><a href="global.html#zlibInflate">zlibInflate</a></li></ul>
</nav>
<div id="main">
<h1 class="page-title">modules/nukecomments.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import $ from 'jquery';
import * as TBApi from '../tbapi.ts';
import * as TBCore from '../tbcore.js';
import * as TBHelpers from '../tbhelpers.js';
import TBListener from '../tblistener.js';
import {Module} from '../tbmodule.jsx';
import * as TBStorage from '../tbstorage.js';
import * as TBui from '../tbui.js';
export default new Module({
name: 'Comment Nuke',
id: 'CommentNuke',
enabledByDefault: false,
settings: [
{
id: 'ignoreDistinguished',
description: 'Ignore distinguished comments from mods and admins when nuking a chain.',
type: 'boolean',
default: true,
},
{
id: 'executionType',
description: 'Default nuke type selected when nuking',
type: 'selector',
values: ['remove', 'lock'],
default: 'remove',
advanced: true,
},
// Settings for old reddit only
{
id: 'showNextToUser',
description: 'Show nuke button next to the username instead of under the comment.',
oldReddit: true,
type: 'boolean',
default: true,
advanced: true,
},
],
}, function init ({ignoreDistinguished, showNextToUser, executionType}) {
// This will contain a flat listing of all comments to be removed.
let removalChain = [];
// Distinguished chain
let distinguishedComments = [];
// If we do get api errors we put the comment id in here so we can retry removing them.
let missedComments = [];
let retryExecutionType = '';
let removalRunning = false;
let nukeOpen = false;
const $body = $('body');
const self = this;
// Nuke button clicked
$body.on('click', '.tb-nuke-button', function (event) {
self.log('nuke button clicked.');
if (nukeOpen) {
TBui.textFeedback('Nuke popup is already open.', TBui.FEEDBACK_NEGATIVE);
return;
}
TBui.longLoadSpinner(true);
nukeOpen = true;
removalChain = [];
missedComments = [];
retryExecutionType = '';
distinguishedComments = [];
const $this = $(this);
const commentID = $this.attr('data-comment-id');
const postID = $this.attr('data-post-id');
const subreddit = $this.attr('data-subreddit');
const positions = TBui.drawPosition(event);
const fetchURL = `/r/${subreddit}/comments/${postID}/slug/${commentID}.json?limit=1500`;
const $popupContents = $(`<div class="tb-nuke-popup-content">
<div class="tb-nuke-feedback">Fetching all comments belonging to chain.</div>
<div class="tb-nuke-details"></div>
</div>`);
// Pop-up
const $popup = TBui.popup({
title: 'Nuke comment chain',
tabs: [
{
title: 'Nuke tab',
tooltip: '',
content: $popupContents,
footer: `
${TBui.actionButton('Execute', 'tb-execute-nuke')}
${TBui.actionButton('Retry', 'tb-retry-nuke')}
`,
},
],
cssClass: 'nuke-button-popup',
draggable: true,
// We don't let the user close this popup while items are being processed, so we use a custom handler
closable: false,
}).appendTo($body)
.css({
left: positions.leftPosition,
top: positions.topPosition,
display: 'block',
});
TBApi.getJSON(fetchURL, {raw_json: 1}).then(data => {
TBStorage.purifyObject(data);
parseComments(data[1].data.children[0], postID, subreddit).then(() => {
TBui.longLoadSpinner(false);
$popup.find('.tb-nuke-feedback').text('Finished analyzing comments.');
const removalChainLength = removalChain.length;
// Distinguished chain
const distinguishedCommentsLength = distinguishedComments.length;
$popup.find('.tb-nuke-details').html(TBStorage.purify(`
<p>${
removalChainLength + distinguishedCommentsLength
} comments found (Already removed comments not included).</p>
<p>${distinguishedCommentsLength} distinguished comments found.</p>
<p><label><input type="checkbox" class="tb-ignore-distinguished-checkbox" ${
ignoreDistinguished ? ' checked="checked"' : ''
}>Ignore distinguished comments from mods and admins</label></p>
<p>
<label><input type="radio" value="remove" name="tb-execution-type-radio" class="tb-execution-type-radio" ${
executionType === 'remove' ? ' checked="checked"' : ''
}>Remove comments</label>
<label><input type="radio" value="lock" name="tb-execution-type-radio" class="tb-execution-type-radio" ${
executionType === 'lock' ? ' checked="checked"' : ''
}>Lock comments</label>
</p>
`));
$popup.find('.tb-execute-nuke').show();
});
});
$popup.on('click', '.tb-execute-nuke, .tb-retry-nuke', function () {
removalRunning = true;
TBui.longLoadSpinner(true);
const $this = $(this);
$this.hide();
let commentArray;
const $nukeFeedback = $popup.find('.tb-nuke-feedback');
const $nukeDetails = $popup.find('.tb-nuke-details');
const temptIgnoreDistinguished = $popup.find('.tb-ignore-distinguished-checkbox').prop('checked');
let executionType = '';
if ($this.hasClass('tb-retry-nuke')) {
executionType = retryExecutionType;
commentArray = missedComments;
missedComments = [];
} else {
executionType = $popup.find('.tb-execution-type-radio:checked').val();
if (temptIgnoreDistinguished) {
commentArray = removalChain;
} else {
commentArray = removalChain.concat(distinguishedComments);
}
}
$nukeFeedback.text(`${executionType === 'remove' ? 'Removing' : 'Locking'} comments.`);
$nukeDetails.html('');
// Oldest comments first.
commentArray = TBHelpers.saneSort(commentArray);
const removalArrayLength = commentArray.length;
let removalCount = 0;
Promise.all(commentArray.map(async comment => {
removalCount++;
TBui.textFeedback(
`${
executionType === 'remove'
? 'Removing'
: 'Locking'
} comment ${removalCount}/${removalArrayLength}`,
TBui.FEEDBACK_NEUTRAL,
);
if (executionType === 'remove') {
await TBApi.removeThing(`t1_${comment}`, false, false).catch(() => {
missedComments.push(comment);
});
} else {
await TBApi.lock(`t1_${comment}`, false).catch(() => {
missedComments.push(comment);
});
}
})).then(() => {
removalRunning = false;
TBui.longLoadSpinner(false);
$nukeFeedback.text(`Done ${executionType === 'remove' ? 'removing' : 'locking'} comments.`);
const missedLength = missedComments.length;
if (missedLength) {
retryExecutionType = executionType;
$nukeDetails.text(
`${missedLength}: not ${
executionType === 'remove' ? 'removed' : 'locked'
} because of API errors. Hit retry to attempt removing them again.`,
);
$popup.find('.tb-retry-nuke').show();
} else {
setTimeout(() => {
$popup.find('.close').click();
}, 1500);
}
});
});
// Handle popup close button, with custom logic to prevent the close if currently running
$popup.on('click', '.close', event => {
event.stopPropagation();
if (removalRunning) {
TBui.textFeedback('Comment chain nuke in progress, cannot close popup.', TBui.FEEDBACK_NEGATIVE);
} else {
$popup.remove();
nukeOpen = false;
}
});
});
/**
* Will given a reddit API comment object go through the chain and put all comments
* @function parseComments
* @param {object} object Comment chain object
* @param {string} postID Post id the comments belong to
* @param {string} subreddit Subreddit the comment chain belongs to.
* @returns {Promise}
*/
async function parseComments (object, postID, subreddit) {
switch (object.kind) {
case 'Listing': {
for (let i = 0; i < object.data.children.length; i++) {
await parseComments(object.data.children[i], postID, subreddit);
}
break;
}
case 't1': {
const distinguishedType = object.data.distinguished;
if (
(distinguishedType === 'admin' || distinguishedType === 'moderator')
&& !distinguishedComments.includes(object.data.id)
) {
distinguishedComments.push(object.data.id);
// Ignore already removed stuff to lower the amount of calls we need to make.
} else if (!removalChain.includes(object.data.id) && !object.data.removed && !object.data.spam) {
removalChain.push(object.data.id);
}
if (
Object.prototype.hasOwnProperty.call(object.data, 'replies') && object.data.replies
&& typeof object.data.replies === 'object'
) {
await parseComments(object.data.replies, postID, subreddit); // we need to go deeper.
}
break;
}
case 'more':
{
self.log('"load more" encountered, going even deeper');
let commentIDs = object.data.children;
if (!commentIDs.length) {
// "continue this thread" links generated when a thread gets
// too deep return empty `children` lists, thanks Reddit
commentIDs = [object.data.parent_id.substring(3)];
}
for (const id of commentIDs) {
const fetchUrl = `/r/${subreddit}/comments/${postID}/slug/${id}.json?limit=1500`;
// Lets get the comments.
const data = await TBApi.getJSON(fetchUrl, {raw_json: 1});
TBStorage.purifyObject(data);
await parseComments(data[1].data.children[0], postID, subreddit);
}
}
break;
default: {
self.log('default, this should not happen...');
// This shouldn't actually happen...
}
}
}
// Add nuke buttons where needed
TBListener.on('comment', async e => {
const pageType = TBCore.pageDetails.pageType;
const $target = $(e.target);
const subreddit = e.detail.data.subreddit.name;
const commentID = e.detail.data.id.substring(3);
const postID = e.detail.data.post.id.substring(3);
const isMod = await TBCore.isModSub(subreddit);
// We have to mod the subreddit to show the button
if (!isMod) {
return;
}
// We also have to be on a comments page or looking at a context popup
if (
pageType !== 'subredditCommentsPage' && pageType !== 'subredditCommentPermalink'
&& !$target.closest('.context-button-popup').length
) {
return;
}
const NukeButtonHTML =
`<span class="tb-nuke-button tb-bracket-button" data-comment-id="${commentID}" data-post-id="${postID}" data-subreddit="${subreddit}" title="Remove comment chain starting with this comment">${
e.detail.type === 'TBcommentOldReddit' && !showNextToUser ? 'Nuke' : 'R'
}</span>`;
if (showNextToUser && TBCore.isOldReddit) {
const $userContainter = $target.closest('.entry, .tb-comment-entry').find(
'.tb-jsapi-author-container .tb-frontend-container',
);
$userContainter.append(NukeButtonHTML);
} else {
$target.append(NukeButtonHTML);
}
});
});
</code></pre>
</article>
</section>
</div>
<br class="clear">
<footer>
Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 4.0.2</a> on Thu Jan 23 2025 14:58:03 GMT+0000 (Coordinated Universal Time) using the <a href="https://github.com/clenemt/docdash">docdash</a> theme.
</footer>
<script>prettyPrint();</script>
<script src="scripts/polyfill.js"></script>
<script src="scripts/linenumber.js"></script>
<script src="scripts/search.js" defer></script>
</body>
</html>