|
| 1 | +import { log } from '../utils/log.js'; |
| 2 | +import { wait } from '../utils/time.js'; |
| 3 | +import { redact } from '../utils/html.js'; |
| 4 | +import { DELETE_RESULT } from '../utils/constants.js'; |
| 5 | +import { deleteMessage as apiDelete } from '../api/discord-api.js'; |
| 6 | +import { MAX_DELETE_DELAY_MS } from '../utils/constants.js'; |
| 7 | +import { tryUnarchiveThread } from './unarchive.js'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Delete a single message via the Discord API with error handling. |
| 11 | + * @param {Object} message - Discord message object |
| 12 | + * @param {Object} options - Core options (authToken, deleteDelay) |
| 13 | + * @param {Object} stats - Core stats (throttledCount, throttledTotalTime) |
| 14 | + * @param {Function} beforeRequest - Ping tracking |
| 15 | + * @param {Function} afterRequest - Ping tracking |
| 16 | + * @param {Function} printStats - Logs current stats |
| 17 | + * @returns {Promise<string>} DELETE_RESULT value |
| 18 | + */ |
| 19 | +export async function deleteSingleMessage(message, options, stats, beforeRequest, afterRequest, printStats) { |
| 20 | + let resp; |
| 21 | + try { |
| 22 | + beforeRequest(); |
| 23 | + resp = await apiDelete(options.authToken, message.channel_id, message.id); |
| 24 | + afterRequest(); |
| 25 | + } catch (err) { |
| 26 | + log.error('Delete request throwed an error:', err); |
| 27 | + log.verb('Related object:', redact(JSON.stringify(message))); |
| 28 | + return DELETE_RESULT.FAILED; |
| 29 | + } |
| 30 | + |
| 31 | + if (!resp.ok) { |
| 32 | + if (resp.status === 429) { |
| 33 | + const w = Math.max((await resp.json()).retry_after * 1000, 0) || options.deleteDelay; |
| 34 | + stats.throttledCount++; |
| 35 | + stats.throttledTotalTime += w; |
| 36 | + if (w > options.deleteDelay) { |
| 37 | + options.deleteDelay = Math.min(options.deleteDelay + w, MAX_DELETE_DELAY_MS); |
| 38 | + log.warn(`Being rate limited by the API for ${w}ms! Adjusted delete delay to ${options.deleteDelay}ms.`); |
| 39 | + } else { |
| 40 | + log.warn(`Being rate limited by the API for ${w}ms!`); |
| 41 | + } |
| 42 | + printStats(); |
| 43 | + log.verb(`Cooling down for ${w * 2}ms before retrying...`); |
| 44 | + await wait(w * 2); |
| 45 | + return DELETE_RESULT.RETRY; |
| 46 | + } else if (resp.status === 403) { |
| 47 | + log.warn('Insufficient permissions to delete message. Skipping...'); |
| 48 | + return DELETE_RESULT.FAIL_SKIP; |
| 49 | + } else { |
| 50 | + const body = await resp.text(); |
| 51 | + try { |
| 52 | + const r = JSON.parse(body); |
| 53 | + if (resp.status === 400 && r.code === 50083) { |
| 54 | + log.warn('Thread is archived. Attempting to unarchive...'); |
| 55 | + return tryUnarchiveThread(options.authToken, message.channel_id, beforeRequest, afterRequest); |
| 56 | + } |
| 57 | + log.error(`Error deleting message, API responded with status ${resp.status}!`, r); |
| 58 | + log.verb('Related object:', redact(JSON.stringify(message))); |
| 59 | + return DELETE_RESULT.FAILED; |
| 60 | + } catch (e) { |
| 61 | + log.error(`Fail to parse JSON. API responded with status ${resp.status}!`, body); |
| 62 | + return DELETE_RESULT.FAILED; |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return DELETE_RESULT.OK; |
| 68 | +} |
| 69 | + |
| 70 | +/** |
| 71 | + * Delete all messages in the current batch with retry logic. |
| 72 | + * @param {Object} state - Core state (running, delCount, failCount, offset, grandTotal, _messagesToDelete) |
| 73 | + * @param {Object} options - Core options (maxAttempt, deleteDelay, authToken) |
| 74 | + * @param {Object} stats - Core stats |
| 75 | + * @param {Function} beforeRequest - Ping tracking |
| 76 | + * @param {Function} afterRequest - Ping tracking |
| 77 | + * @param {Function} printStats - Logs current stats |
| 78 | + * @param {Function} calcEtr - Recalculate estimated time remaining |
| 79 | + * @param {Function} [onProgress] - Progress callback |
| 80 | + */ |
| 81 | +export async function deleteMessagesFromList(state, options, stats, beforeRequest, afterRequest, printStats, calcEtr, onProgress) { |
| 82 | + for (let i = 0; i < state._messagesToDelete.length; i++) { |
| 83 | + const message = state._messagesToDelete[i]; |
| 84 | + if (!state.running) return log.error('Stopped by you!'); |
| 85 | + |
| 86 | + log.debug( |
| 87 | + `[${state.delCount + 1}/${state.grandTotal}] ` + |
| 88 | + `${new Date(message.timestamp).toLocaleString()} ` + |
| 89 | + `${redact((message.author?.username || 'Unknown') + '#' + (message.author?.discriminator || '0000'))}` + |
| 90 | + `: ${redact((message.content || '').replace(/\n/g, '↵'))}` + |
| 91 | + (message.attachments?.length ? ` [${message.attachments.length} attachment(s)]` : ''), |
| 92 | + `{ID:${redact(message.id)}}` |
| 93 | + ); |
| 94 | + |
| 95 | + // retry loop |
| 96 | + let attempt = 0; |
| 97 | + while (attempt < options.maxAttempt) { |
| 98 | + const result = await deleteSingleMessage(message, options, stats, beforeRequest, afterRequest, printStats); |
| 99 | + attempt++; |
| 100 | + |
| 101 | + if (result === DELETE_RESULT.RETRY || result === DELETE_RESULT.FAILED) { |
| 102 | + if (attempt >= options.maxAttempt) { |
| 103 | + state.offset++; |
| 104 | + state.failCount++; |
| 105 | + break; |
| 106 | + } |
| 107 | + log.verb(`Retrying in ${options.deleteDelay}ms... (${attempt}/${options.maxAttempt})`); |
| 108 | + await wait(options.deleteDelay); |
| 109 | + continue; |
| 110 | + } else if (result === DELETE_RESULT.FAIL_SKIP) { |
| 111 | + state.offset++; |
| 112 | + state.failCount++; |
| 113 | + } else { |
| 114 | + state.delCount++; |
| 115 | + } |
| 116 | + break; |
| 117 | + } |
| 118 | + |
| 119 | + calcEtr(); |
| 120 | + if (onProgress) onProgress(state, stats); |
| 121 | + |
| 122 | + await wait(options.deleteDelay); |
| 123 | + } |
| 124 | +} |
0 commit comments