Undiscord

Undiscord 5.2.3, but with some fixes.

当前为 2025-01-12 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Undiscord
  3. // @description Undiscord 5.2.3, but with some fixes.
  4. // @version 5.2.3.with.fixes.b
  5. // @author victornpb
  6. // @homepageURL https://github.com/victornpb/undiscord
  7. // @supportURL https://github.com/victornpb/undiscord/discussions
  8. // @match https://*.discord.com/app
  9. // @match https://*.discord.com/channels/*
  10. // @match https://*.discord.com/login
  11. // @license MIT
  12. // @namespace https://github.com/victornpb/deleteDiscordMessages
  13. // @icon https://victornpb.github.io/undiscord/images/icon128.png
  14. // @contributionURL https://www.buymeacoffee.com/vitim
  15. // @grant none
  16. // ==/UserScript==
  17. (function () {
  18. 'use strict';
  19.  
  20. /* rollup-plugin-baked-env */
  21. const VERSION = "5.2.3.with.fixes";
  22.  
  23. var themeCss = (`
  24. /* undiscord window */
  25. #undiscord.browser { box-shadow: var(--elevation-stroke), var(--elevation-high); overflow: hidden; }
  26. #undiscord.container,
  27. #undiscord .container { background-color: var(--background-secondary); border-radius: 8px; box-sizing: border-box; cursor: default; flex-direction: column; }
  28. #undiscord .header { background-color: var(--background-tertiary); height: 48px; align-items: center; min-height: 48px; padding: 0 16px; display: flex; color: var(--header-secondary); cursor: grab; }
  29. #undiscord .header .icon { color: var(--interactive-normal); margin-right: 8px; flex-shrink: 0; width: 24; height: 24; }
  30. #undiscord .header .icon:hover { color: var(--interactive-hover); }
  31. #undiscord .header h3 { font-size: 16px; line-height: 20px; font-weight: 500; font-family: var(--font-display); color: var(--header-primary); flex-shrink: 0; margin-right: 16px; }
  32. #undiscord .spacer { flex-grow: 1; }
  33. #undiscord .header .vert-divider { width: 1px; height: 24px; background-color: var(--background-modifier-accent); margin-right: 16px; flex-shrink: 0; }
  34. #undiscord legend,
  35. #undiscord label { color: var(--header-secondary); font-size: 12px; line-height: 16px; font-weight: 500; text-transform: uppercase; cursor: default; font-family: var(--font-display); margin-bottom: 8px; }
  36. #undiscord .multiInput { display: flex; align-items: center; font-size: 16px; box-sizing: border-box; width: 100%; border-radius: 3px; color: var(--text-normal); background-color: var(--input-background); border: none; transition: border-color 0.2s ease-in-out 0s; }
  37. #undiscord .multiInput :first-child { flex-grow: 1; }
  38. #undiscord .multiInput button:last-child { margin-right: 4px; }
  39. #undiscord .input { font-size: 16px; box-sizing: border-box; width: 100%; border-radius: 3px; color: var(--text-normal); background-color: var(--input-background); border: none; transition: border-color 0.2s ease-in-out 0s; padding: 10px; height: 40px; }
  40. #undiscord fieldset { margin-top: 16px; }
  41. #undiscord .input-wrapper { display: flex; align-items: center; font-size: 16px; box-sizing: border-box; width: 100%; border-radius: 3px; color: var(--text-normal); background-color: var(--input-background); border: none; transition: border-color 0.2s ease-in-out 0s; }
  42. #undiscord input[type="search"],
  43. #undiscord input[type="text"],
  44. #undiscord input[type="datetime-local"],
  45. #undiscord input[type="number"],
  46. #undiscord input[type="range"] { font-size: 16px; box-sizing: border-box; width: 100%; border-radius: 3px; color: var(--text-normal); background-color: var(--input-background); border: none; transition: border-color 0.2s ease-in-out 0s; padding: 10px; height: 40px; }
  47. #undiscord .divider,
  48. #undiscord hr { border: none; margin-bottom: 24px; padding-bottom: 4px; border-bottom: 1px solid var(--background-modifier-accent); }
  49. #undiscord .sectionDescription { margin-bottom: 16px; color: var(--header-secondary); font-size: 14px; line-height: 20px; font-weight: 400; }
  50. #undiscord a { color: var(--text-link); text-decoration: none; }
  51. #undiscord .btn,
  52. #undiscord button { position: relative; display: flex; -webkit-box-pack: center; justify-content: center; -webkit-box-align: center; align-items: center; box-sizing: border-box; background: none; border: none; border-radius: 3px; font-size: 14px; font-weight: 500; line-height: 16px; padding: 2px 16px; user-select: none; /* sizeSmall */ width: 60px; height: 32px; min-width: 60px; min-height: 32px; /* lookFilled colorPrimary */ color: rgb(255, 255, 255); background-color: var(--button-secondary-background); }
  53. #undiscord .sizeMedium { width: 96px; height: 38px; min-width: 96px; min-height: 38px; }
  54. #undiscord .sizeMedium.icon { width: 38px; min-width: 38px; }
  55. #undiscord sup { vertical-align: top; }
  56. /* lookFilled colorPrimary */
  57. #undiscord .accent { background-color: var(--brand-experiment); }
  58. #undiscord .danger { background-color: var(--button-danger-background); }
  59. #undiscord .positive { background-color: var(--button-positive-background); }
  60. #undiscord .info { font-size: 12px; line-height: 16px; padding: 8px 10px; color: var(--text-muted); }
  61. /* Scrollbar */
  62. #undiscord .scroll::-webkit-scrollbar { width: 8px; height: 8px; }
  63. #undiscord .scroll::-webkit-scrollbar-corner { background-color: transparent; }
  64. #undiscord .scroll::-webkit-scrollbar-thumb { background-clip: padding-box; border: 2px solid transparent; border-radius: 4px; background-color: var(--scrollbar-thin-thumb); min-height: 40px; }
  65. #undiscord .scroll::-webkit-scrollbar-track { border-color: var(--scrollbar-thin-track); background-color: var(--scrollbar-thin-track); border: 2px solid var(--scrollbar-thin-track); }
  66. /* fade scrollbar */
  67. #undiscord .scroll::-webkit-scrollbar-thumb,
  68. #undiscord .scroll::-webkit-scrollbar-track { visibility: hidden; }
  69. #undiscord .scroll:hover::-webkit-scrollbar-thumb,
  70. #undiscord .scroll:hover::-webkit-scrollbar-track { visibility: visible; }
  71. /**** functional classes ****/
  72. #undiscord.redact .priv { display: none !important; }
  73. #undiscord.redact x:not(:active) { color: transparent !important; background-color: var(--primary-700) !important; cursor: default; user-select: none; }
  74. #undiscord.redact x:hover { position: relative; }
  75. #undiscord.redact x:hover::after { content: "Redacted information (Streamer mode: ON)"; position: absolute; display: inline-block; top: -32px; left: -20px; padding: 4px; width: 150px; font-size: 8pt; text-align: center; white-space: pre-wrap; background-color: var(--background-floating); -webkit-box-shadow: var(--elevation-high); box-shadow: var(--elevation-high); color: var(--text-normal); border-radius: 5px; pointer-events: none; }
  76. #undiscord.redact [priv] { -webkit-text-security: disc !important; }
  77. #undiscord :disabled { display: none; }
  78. /**** layout and utility classes ****/
  79. #undiscord,
  80. #undiscord * { box-sizing: border-box; }
  81. #undiscord .col { display: flex; flex-direction: column; }
  82. #undiscord .row { display: flex; flex-direction: row; align-items: center; }
  83. #undiscord .mb1 { margin-bottom: 8px; }
  84. #undiscord .log { margin-bottom: 0.25em; }
  85. #undiscord .log-debug { color: inherit; }
  86. #undiscord .log-info { color: #00b0f4; }
  87. #undiscord .log-verb { color: #72767d; }
  88. #undiscord .log-warn { color: #faa61a; }
  89. #undiscord .log-error { color: #f04747; }
  90. #undiscord .log-success { color: #43b581; }
  91. `);
  92.  
  93. var mainCss = (`
  94. /**** Undiscord Button ****/
  95. #undicord-btn { position: relative; width: auto; height: 24px; margin: 0 8px; cursor: pointer; color: var(--interactive-normal); flex: 0 0 auto; }
  96. #undicord-btn progress { position: absolute; top: 23px; left: -4px; width: 32px; height: 12px; display: none; }
  97. #undicord-btn.running { color: var(--button-danger-background) !important; }
  98. #undicord-btn.running progress { display: block; }
  99. /**** Undiscord Interface ****/
  100. #undiscord { position: right; z-index: 100; top: 58px; right: 44px; display: flex; flex-direction: column; width: 800px; height: 80vh; min-width: 610px; max-width: 100vw; min-height: 448px; max-height: 100vh; color: var(--text-normal); border-radius: 4px; background-color: var(--background-secondary); box-shadow: var(--elevation-stroke), var(--elevation-high); will-change: top, left, width, height; }
  101. #undiscord .header .icon { cursor: pointer; }
  102. #undiscord .window-body { height: calc(100% - 48px); }
  103. #undiscord .sidebar { overflow: hidden scroll; overflow-y: auto; width: 270px; min-width: 250px; height: 100%; max-height: 100%; padding: 8px; background: var(--background-secondary); }
  104. #undiscord .sidebar legend,
  105. #undiscord .sidebar label { display: block; width: 100%; }
  106. #undiscord .main { display: flex; max-width: calc(100% - 250px); background-color: var(--background-primary); flex-grow: 1; }
  107. #undiscord.hide-sidebar .sidebar { display: none; }
  108. #undiscord.hide-sidebar .main { max-width: 100%; }
  109. #undiscord #logArea { font-family: Consolas, Liberation Mono, Menlo, Courier, monospace; font-size: 0.75rem; overflow: auto; padding: 10px; user-select: text; flex-grow: 1; flex-grow: 1; cursor: auto; }
  110. #undiscord .tbar { padding: 8px; background-color: var(--background-secondary-alt); }
  111. #undiscord .tbar button { margin-right: 4px; margin-bottom: 4px; }
  112. #undiscord .footer { cursor: se-resize; padding-right: 30px; }
  113. #undiscord .footer #progressPercent { padding: 0 1em; font-size: small; color: var(--interactive-muted); flex-grow: 1; }
  114. .resize-handle { position: absolute; bottom: -15px; right: -15px; width: 30px; height: 30px; transform: rotate(-45deg); background: repeating-linear-gradient(0, var(--background-modifier-accent), var(--background-modifier-accent) 1px, transparent 2px, transparent 4px); cursor: nwse-resize; }
  115. /**** Elements ****/
  116. #undiscord summary { font-size: 16px; font-weight: 500; line-height: 20px; position: relative; overflow: hidden; margin-bottom: 2px; padding: 6px 10px; cursor: pointer; white-space: nowrap; text-overflow: ellipsis; color: var(--interactive-normal); border-radius: 4px; flex-shrink: 0; }
  117. #undiscord fieldset { padding-left: 8px; }
  118. #undiscord legend a { float: right; text-transform: initial; }
  119. #undiscord progress { height: 8px; margin-top: 4px; flex-grow: 1; }
  120. #undiscord .importJson { display: flex; flex-direction: row; }
  121. #undiscord .importJson button { margin-left: 5px; width: fit-content; }
  122. `);
  123.  
  124. var dragCss = (`
  125. [name^="grab-"] { position: absolute; --size: 6px; --corner-size: 16px; --offset: -1px; z-index: 9; }
  126. [name^="grab-"]:hover{ background: rgba(128,128,128,0.1); }
  127. [name="grab-t"] { top: 0px; left: var(--corner-size); right: var(--corner-size); height: var(--size); margin-top: var(--offset); cursor: ns-resize; }
  128. [name="grab-r"] { top: var(--corner-size); bottom: var(--corner-size); right: 0px; width: var(--size); margin-right: var(--offset);
  129. cursor: ew-resize; }
  130. [name="grab-b"] { bottom: 0px; left: var(--corner-size); right: var(--corner-size); height: var(--size); margin-bottom: var(--offset); cursor: ns-resize; }
  131. [name="grab-l"] { top: var(--corner-size); bottom: var(--corner-size); left: 0px; width: var(--size); margin-left: var(--offset); cursor: ew-resize; }
  132. [name="grab-tl"] { top: 0px; left: 0px; width: var(--corner-size); height: var(--corner-size); margin-top: var(--offset); margin-left: var(--offset); cursor: nwse-resize; }
  133. [name="grab-tr"] { top: 0px; right: 0px; width: var(--corner-size); height: var(--corner-size); margin-top: var(--offset); margin-right: var(--offset); cursor: nesw-resize; }
  134. [name="grab-br"] { bottom: 0px; right: 0px; width: var(--corner-size); height: var(--corner-size); margin-bottom: var(--offset); margin-right: var(--offset); cursor: nwse-resize; }
  135. [name="grab-bl"] { bottom: 0px; left: 0px; width: var(--corner-size); height: var(--corner-size); margin-bottom: var(--offset); margin-left: var(--offset); cursor: nesw-resize; }
  136. `);
  137.  
  138. var buttonHtml = (`
  139. <div id="undicord-btn" tabindex="0" role="button" aria-label="Delete Messages" title="Delete Messages with Undiscord">
  140. <svg aria-hidden="false" width="24" height="24" viewBox="0 0 24 24">
  141. <path fill="currentColor" d="M15 3.999V2H9V3.999H3V5.999H21V3.999H15Z"></path>
  142. <path fill="currentColor" d="M5 6.99902V18.999C5 20.101 5.897 20.999 7 20.999H17C18.103 20.999 19 20.101 19 18.999V6.99902H5ZM11 17H9V11H11V17ZM15 17H13V11H15V17Z"></path>
  143. </svg>
  144. <progress></progress>
  145. </div>
  146. `);
  147.  
  148. var undiscordTemplate = (`
  149. <div id="undiscord" class="browser container redact" style="display:none;">
  150. <div class="header">
  151. <svg class="icon" aria-hidden="false" width="24" height="24" viewBox="0 0 24 24">
  152. <path fill="currentColor" d="M15 3.999V2H9V3.999H3V5.999H21V3.999H15Z"></path>
  153. <path fill="currentColor"
  154. d="M5 6.99902V18.999C5 20.101 5.897 20.999 7 20.999H17C18.103 20.999 19 20.101 19 18.999V6.99902H5ZM11 17H9V11H11V17ZM15 17H13V11H15V17Z">
  155. </path>
  156. </svg>
  157. <h3>Undiscord</h3>
  158. <div class="vert-divider"></div>
  159. <span> Bulk delete messages</span>
  160. <div class="spacer"></div>
  161. <div id="hide" class="icon" aria-label="Close" role="button" tabindex="0">
  162. <svg aria-hidden="false" width="24" height="24" viewBox="0 0 24 24">
  163. <path fill="currentColor"
  164. d="M18.4 4L12 10.4L5.6 4L4 5.6L10.4 12L4 18.4L5.6 20L12 13.6L18.4 20L20 18.4L13.6 12L20 5.6L18.4 4Z">
  165. </path>
  166. </svg>
  167. </div>
  168. </div>
  169. <div class="window-body" style="display: flex; flex-direction: row;">
  170. <div class="sidebar scroll">
  171. <details open>
  172. <summary>General</summary>
  173. <fieldset>
  174. <legend>
  175. Author ID
  176. <a href="{{WIKI}}/authorId" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  177. </legend>
  178. <div class="multiInput">
  179. <div class="input-wrapper">
  180. <input class="input" id="authorId" type="text" priv>
  181. </div>
  182. <button id="getAuthor">me</button>
  183. </div>
  184. </fieldset>
  185. <hr>
  186. <fieldset>
  187. <legend>
  188. Server ID
  189. <a href="{{WIKI}}/guildId" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  190. </legend>
  191. <div class="multiInput">
  192. <div class="input-wrapper">
  193. <input class="input" id="guildId" type="text" priv>
  194. </div>
  195. <button id="getGuild">current</button>
  196. </div>
  197. </fieldset>
  198. <fieldset>
  199. <legend>
  200. Channel ID
  201. <a href="{{WIKI}}/channelId" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  202. </legend>
  203. <div class="multiInput mb1">
  204. <div class="input-wrapper">
  205. <input class="input" id="channelId" type="text" priv>
  206. </div>
  207. <button id="getChannel">current</button>
  208. </div>
  209. <div class="sectionDescription">
  210. <label class="row"><input id="includeNsfw" type="checkbox">This is a NSFW channel</label>
  211. </div>
  212. </fieldset>
  213. </details>
  214. <details>
  215. <summary>Wipe Archive</summary>
  216. <fieldset>
  217. <legend>
  218. Import index.json
  219. <a href="{{WIKI}}/importJson" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  220. </legend>
  221. <div class="input-wrapper">
  222. <input type="file" id="importJsonInput" accept="application/json,.json" style="width:100%";>
  223. </div>
  224. <div class="sectionDescription">
  225. <br>
  226. After requesting your data from discord, you can import it here.<br>
  227. Select the "messages/index.json" file from the discord archive.
  228. </div>
  229. </fieldset>
  230. </details>
  231. <hr>
  232. <details>
  233. <summary>Filter</summary>
  234. <fieldset>
  235. <legend>
  236. Search
  237. <a href="{{WIKI}}/filters" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  238. </legend>
  239. <div class="input-wrapper">
  240. <input id="search" type="text" placeholder="Containing text" priv>
  241. </div>
  242. <div class="sectionDescription">
  243. Only delete messages that contain the text
  244. </div>
  245. <div class="sectionDescription">
  246. <label><input id="hasLink" type="checkbox">has: link</label>
  247. </div>
  248. <div class="sectionDescription">
  249. <label><input id="hasFile" type="checkbox">has: file</label>
  250. </div>
  251. <div class="sectionDescription">
  252. <label><input id="includePinned" type="checkbox">Include pinned</label>
  253. </div>
  254. </fieldset>
  255. <hr>
  256. <fieldset>
  257. <legend>
  258. Pattern
  259. <a href="{{WIKI}}/pattern" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  260. </legend>
  261. <div class="sectionDescription">
  262. Delete messages that match the regular expression
  263. </div>
  264. <div class="input-wrapper">
  265. <span class="info">/</span>
  266. <input id="pattern" type="text" placeholder="regular expression" priv>
  267. <span class="info">/</span>
  268. </div>
  269. </fieldset>
  270. </details>
  271. <details>
  272. <summary>Messages interval</summary>
  273. <fieldset>
  274. <legend>
  275. Interval of messages
  276. <a href="{{WIKI}}/messageId" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  277. </legend>
  278. <div class="multiInput mb1">
  279. <div class="input-wrapper">
  280. <input id="minId" type="text" placeholder="After a message" priv>
  281. </div>
  282. <button id="pickMessageAfter">Pick</button>
  283. </div>
  284. <div class="multiInput">
  285. <div class="input-wrapper">
  286. <input id="maxId" type="text" placeholder="Before a message" priv>
  287. </div>
  288. <button id="pickMessageBefore">Pick</button>
  289. </div>
  290. <div class="sectionDescription">
  291. Specify an interval to delete messages.
  292. </div>
  293. </fieldset>
  294. </details>
  295. <details>
  296. <summary>Date interval</summary>
  297. <fieldset>
  298. <legend>
  299. After date
  300. <a href="{{WIKI}}/dateRange" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  301. </legend>
  302. <div class="input-wrapper mb1">
  303. <input id="minDate" type="datetime-local" title="Messages posted AFTER this date">
  304. </div>
  305. <legend>
  306. Before date
  307. <a href="{{WIKI}}/dateRange" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  308. </legend>
  309. <div class="input-wrapper">
  310. <input id="maxDate" type="datetime-local" title="Messages posted BEFORE this date">
  311. </div>
  312. <div class="sectionDescription">
  313. Delete messages that were posted between the two dates.
  314. </div>
  315. <div class="sectionDescription">
  316. * Filtering by date doesn't work if you use the "Messages interval".
  317. </div>
  318. </fieldset>
  319. </details>
  320. <hr>
  321. <details>
  322. <summary>Advanced settings</summary>
  323. <fieldset>
  324. <legend>
  325. Search delay
  326. <a href="{{WIKI}}/delay" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  327. </legend>
  328. <div class="input-wrapper">
  329. <input id="searchDelay" type="range" value="30000" step="100" min="100" max="60000">
  330. <div id="searchDelayValue"></div>
  331. </div>
  332. </fieldset>
  333. <fieldset>
  334. <legend>
  335. Delete delay
  336. <a href="{{WIKI}}/delay" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  337. </legend>
  338. <div class="input-wrapper">
  339. <input id="deleteDelay" type="range" value="1000" step="50" min="50" max="10000">
  340. <div id="deleteDelayValue"></div>
  341. </div>
  342. <br>
  343. <div class="sectionDescription">
  344. This will affect the speed in which the messages are deleted.
  345. Use the help link for more information.
  346. </div>
  347. </fieldset>
  348. <hr>
  349. <fieldset>
  350. <legend>
  351. Authorization Token
  352. <a href="{{WIKI}}/authToken" title="Help" target="_blank" rel="noopener noreferrer">help</a>
  353. </legend>
  354. <div class="multiInput">
  355. <div class="input-wrapper">
  356. <input class="input" id="token" type="text" priv>
  357. </div>
  358. <button id="getToken">fill</button>
  359. </div>
  360. </fieldset>
  361. </details>
  362. <hr>
  363. <div></div>
  364. <div class="info">
  365. Undiscord {{VERSION}}
  366. <br> victornpb
  367. </div>
  368. </div>
  369. <div class="main col">
  370. <div class="tbar col">
  371. <div class="row">
  372. <button id="toggleSidebar" class="sizeMedium icon">☰</button>
  373. <button id="start" class="sizeMedium danger" style="width: 150px;" title="Start the deletion process">▶︎ Delete</button>
  374. <button id="stop" class="sizeMedium" title="Stop the deletion process" disabled>🛑 Stop</button>
  375. <button id="clear" class="sizeMedium">Clear log</button>
  376. <label class="row" title="Hide sensitive information on your screen for taking screenshots">
  377. <input id="redact" type="checkbox" checked> Streamer mode
  378. </label>
  379. </div>
  380. <div class="row">
  381. <progress id="progressBar" style="display:none;"></progress>
  382. </div>
  383. </div>
  384. <pre id="logArea" class="logarea scroll">
  385. <div class="" style="background: var(--background-mentioned); padding: .5em;">Notice: Undiscord may be working slower than usual and<wbr>require multiple attempts due to a recent Discord update.<br>We're working on a fix, and we thank you for your patience.</div>
  386. <center>
  387. <div>Star <a href="{{HOME}}" target="_blank" rel="noopener noreferrer">this project</a> on GitHub!</div>
  388. <div><a href="{{HOME}}/discussions" target="_blank" rel="noopener noreferrer">Issues or help</a></div>
  389. </center>
  390. </pre>
  391. <div class="tbar footer row">
  392. <div id="progressPercent"></div>
  393. <span class="spacer"></span>
  394. <label>
  395. <input id="autoScroll" type="checkbox" checked> Auto scroll
  396. </label>
  397. <div class="resize-handle"></div>
  398. </div>
  399. </div>
  400. </div>
  401. </div>
  402.  
  403. `);
  404.  
  405. const log = {
  406. debug() { return logFn ? logFn('debug', arguments) : console.debug.apply(console, arguments); },
  407. info() { return logFn ? logFn('info', arguments) : console.info.apply(console, arguments); },
  408. verb() { return logFn ? logFn('verb', arguments) : console.log.apply(console, arguments); },
  409. warn() { return logFn ? logFn('warn', arguments) : console.warn.apply(console, arguments); },
  410. error() { return logFn ? logFn('error', arguments) : console.error.apply(console, arguments); },
  411. success() { return logFn ? logFn('success', arguments) : console.info.apply(console, arguments); },
  412. };
  413.  
  414. var logFn; // custom console.log function
  415. const setLogFn = (fn) => logFn = fn;
  416.  
  417. // Helpers
  418. const wait = async ms => new Promise(done => setTimeout(done, ms));
  419. const msToHMS = s => `${s / 3.6e6 | 0}h ${(s % 3.6e6) / 6e4 | 0}m ${(s % 6e4) / 1000 | 0}s`;
  420. const escapeHTML = html => String(html).replace(/[&<"']/g, m => ({ '&': '&amp;', '<': '&lt;', '"': '&quot;', '\'': '&#039;' })[m]);
  421. const redact = str => `<x>${escapeHTML(str)}</x>`;
  422. const queryString = params => params.filter(p => p[1] !== undefined).map(p => p[0] + '=' + encodeURIComponent(p[1])).join('&');
  423. const ask = async msg => new Promise(resolve => setTimeout(() => resolve(window.confirm(msg)), 10));
  424. const toSnowflake = (date) => /:/.test(date) ? ((new Date(date).getTime() - 1420070400000) * Math.pow(2, 22)) : date;
  425. const replaceInterpolations = (str, obj, removeMissing = false) => str.replace(/\{\{([\w_]+)\}\}/g, (m, key) => obj[key] || (removeMissing ? '' : m));
  426.  
  427. const PREFIX$1 = '[UNDISCORD]';
  428.  
  429. /**
  430. * Delete all messages in a Discord channel or DM
  431. * @author Victornpb <https://www.github.com/victornpb>
  432. * @see https://github.com/victornpb/undiscord
  433. */
  434. class UndiscordCore {
  435.  
  436. options = {
  437. authToken: null, // Your authorization token
  438. authorId: null, // Author of the messages you want to delete
  439. guildId: null, // Server were the messages are located
  440. channelId: null, // Channel were the messages are located
  441. minId: null, // Only delete messages after this, leave blank do delete all
  442. maxId: null, // Only delete messages before this, leave blank do delete all
  443. content: null, // Filter messages that contains this text content
  444. hasLink: null, // Filter messages that contains link
  445. hasFile: null, // Filter messages that contains file
  446. includeNsfw: null, // Search in NSFW channels
  447. includePinned: null, // Delete messages that are pinned
  448. pattern: null, // Only delete messages that match the regex (insensitive)
  449. searchDelay: null, // Delay each time we fetch for more messages
  450. deleteDelay: null, // Delay between each delete operation
  451. maxAttempt: 2, // Attempts to delete a single message if it fails
  452. askForConfirmation: true,
  453. };
  454.  
  455. state = {
  456. running: false,
  457. delCount: 0,
  458. failCount: 0,
  459. grandTotal: 0,
  460. offset: 0,
  461. iterations: 0,
  462.  
  463. _seachResponse: null,
  464. _messagesToDelete: [],
  465. _skippedMessages: [],
  466. };
  467.  
  468. stats = {
  469. startTime: new Date(), // start time
  470. throttledCount: 0, // how many times you have been throttled
  471. throttledTotalTime: 0, // the total amount of time you spent being throttled
  472. lastPing: null, // the most recent ping
  473. avgPing: null, // average ping used to calculate the estimated remaining time
  474. etr: 0,
  475. };
  476.  
  477. // events
  478. onStart = undefined;
  479. onProgress = undefined;
  480. onStop = undefined;
  481.  
  482. resetState() {
  483. this.state = {
  484. running: false,
  485. delCount: 0,
  486. failCount: 0,
  487. grandTotal: 0,
  488. offset: 0,
  489. iterations: 0,
  490.  
  491. _seachResponse: null,
  492. _messagesToDelete: [],
  493. _skippedMessages: [],
  494. };
  495.  
  496. this.options.askForConfirmation = true;
  497. }
  498.  
  499. /** Automate the deletion process of multiple channels */
  500. async runBatch(queue) {
  501. if (this.state.running) return log.error('Already running!');
  502.  
  503. log.info(`Runnning batch with queue of ${queue.length} jobs`);
  504. for (let i = 0; i < queue.length; i++) {
  505. const job = queue[i];
  506. log.info('Starting job...', `(${i + 1}/${queue.length})`);
  507.  
  508. // set options
  509. this.options = {
  510. ...this.options, // keep current options
  511. ...job, // override with options for that job
  512. };
  513.  
  514. await this.run(true);
  515. if (!this.state.running) break;
  516.  
  517. log.info('Job ended.', `(${i + 1}/${queue.length})`);
  518. this.resetState();
  519. this.options.askForConfirmation = false;
  520. this.state.running = true; // continue running
  521. }
  522.  
  523. log.info('Batch finished.');
  524. this.state.running = false;
  525. }
  526.  
  527. /** Start the deletion process */
  528. async run(isJob = false) {
  529. if (this.state.running && !isJob) return log.error('Already running!');
  530.  
  531. this.state.running = true;
  532. this.stats.startTime = new Date();
  533.  
  534. log.success(`\nStarted at ${this.stats.startTime.toLocaleString()}`);
  535. log.debug(
  536. `authorId = "${redact(this.options.authorId)}"`,
  537. `guildId = "${redact(this.options.guildId)}"`,
  538. `channelId = "${redact(this.options.channelId)}"`,
  539. `minId = "${redact(this.options.minId)}"`,
  540. `maxId = "${redact(this.options.maxId)}"`,
  541. `hasLink = ${!!this.options.hasLink}`,
  542. `hasFile = ${!!this.options.hasFile}`,
  543. );
  544.  
  545. if (this.onStart) this.onStart(this.state, this.stats);
  546.  
  547. do {
  548. this.state.iterations++;
  549.  
  550. log.verb('Fetching messages...');
  551. // Search messages
  552. await this.search();
  553.  
  554. // Process results and find which messages should be deleted
  555. await this.filterResponse();
  556.  
  557. log.verb(
  558. `Grand total: ${this.state.grandTotal}`,
  559. `(Messages in current page: ${this.state._seachResponse.messages.length}`,
  560. `To be deleted: ${this.state._messagesToDelete.length}`,
  561. `Skipped: ${this.state._skippedMessages.length})`,
  562. `offset: ${this.state.offset}`
  563. );
  564. this.printStats();
  565.  
  566. // Calculate estimated time
  567. this.calcEtr();
  568. log.verb(`Estimated time remaining: ${msToHMS(this.stats.etr)}`);
  569.  
  570. const messagesRemaining = this.state.grandTotal - this.state.offset;
  571.  
  572. // if there are messages to delete, delete them
  573. if (this.state._messagesToDelete.length > 0) {
  574.  
  575. if (await this.confirm() === false) {
  576. this.state.running = false; // break out of a job
  577. break; // immmediately stop this iteration
  578. }
  579.  
  580. await this.deleteMessagesFromList();
  581. }
  582. else if (this.state._skippedMessages.length > 0) {
  583. // There are stuff, but nothing to delete (example a page full of system messages)
  584. // check next page until we see a page with nothing in it (end of results).
  585. const oldOffset = this.state.offset;
  586. this.state.offset += this.state._skippedMessages.length;
  587. log.verb('There\'s nothing we can delete on this page, checking next page...');
  588. log.verb(`Skipped ${this.state._skippedMessages.length} out of ${this.state._seachResponse.messages.length} in this page.`, `(Offset was ${oldOffset}, ajusted to ${this.state.offset})`);
  589. }
  590.  
  591. else if (this.state.delCount < messagesRemaining) {
  592. log.verb('There\'s messages remaining, checking next page...');
  593. }
  594.  
  595. else {
  596. log.verb('Ended because API returned an empty page.');
  597. log.verb('[End state]', this.state);
  598. if (isJob) break; // break without stopping if this is part of a job
  599. this.state.running = false;
  600. }
  601.  
  602. // wait before next page (fix search page not updating fast enough)
  603. log.verb(`Waiting ${(this.options.searchDelay / 1000).toFixed(2)}s before next page...`);
  604. await wait(this.options.searchDelay);
  605.  
  606. } while (this.state.running);
  607.  
  608. this.stats.endTime = new Date();
  609. log.success(`Ended at ${this.stats.endTime.toLocaleString()}! Total time: ${msToHMS(this.stats.endTime.getTime() - this.stats.startTime.getTime())}`);
  610. this.printStats();
  611. log.debug(`Deleted ${this.state.delCount} messages, ${this.state.failCount} failed.\n`);
  612.  
  613. if (this.onStop) this.onStop(this.state, this.stats);
  614. }
  615.  
  616. stop() {
  617. this.state.running = false;
  618. if (this.onStop) this.onStop(this.state, this.stats);
  619. }
  620.  
  621. /** Calculate the estimated time remaining based on the current stats */
  622. calcEtr() {
  623. this.stats.etr = (this.options.searchDelay * Math.round(this.state.grandTotal / 25)) + ((this.options.deleteDelay + this.stats.avgPing) * this.state.grandTotal);
  624. }
  625.  
  626. /** As for confirmation in the beggining process */
  627. async confirm() {
  628. if (!this.options.askForConfirmation) return true;
  629.  
  630. log.verb('Waiting for your confirmation...');
  631. const preview = this.state._messagesToDelete.map(m => `${m.author.username}#${m.author.discriminator}: ${m.attachments.length ? '[ATTACHMENTS]' : m.content}`).join('\n');
  632.  
  633. const answer = await ask(
  634. `Do you want to delete ~${this.state.grandTotal} messages? (Estimated time: ${msToHMS(this.stats.etr)})` +
  635. '(The actual number of messages may be less, depending if you\'re using filters to skip some messages)' +
  636. '\n\n---- Preview ----\n' +
  637. preview
  638. );
  639.  
  640. if (!answer) {
  641. log.error('Aborted by you!');
  642. return false;
  643. }
  644. else {
  645. log.verb('OK');
  646. this.options.askForConfirmation = false; // do not ask for confirmation again on the next request
  647. return true;
  648. }
  649. }
  650.  
  651. async search() {
  652. let API_SEARCH_URL;
  653. if (this.options.guildId === '@me') API_SEARCH_URL = `https://discord.com/api/v9/channels/${this.options.channelId}/messages/`; // DMs
  654. else API_SEARCH_URL = `https://discord.com/api/v9/guilds/${this.options.guildId}/messages/`; // Server
  655.  
  656. let resp;
  657. try {
  658. this.beforeRequest();
  659. resp = await fetch(API_SEARCH_URL + 'search?' + queryString([
  660. ['author_id', this.options.authorId || undefined],
  661. ['channel_id', (this.options.guildId !== '@me' ? this.options.channelId : undefined) || undefined],
  662. ['min_id', this.options.minId ? toSnowflake(this.options.minId) : undefined],
  663. ['max_id', this.options.maxId ? toSnowflake(this.options.maxId) : undefined],
  664. ['sort_by', 'timestamp'],
  665. ['sort_order', 'desc'],
  666. ['offset', this.state.offset],
  667. ['has', this.options.hasLink ? 'link' : undefined],
  668. ['has', this.options.hasFile ? 'file' : undefined],
  669. ['content', this.options.content || undefined],
  670. ['include_nsfw', this.options.includeNsfw ? true : undefined],
  671. ]), {
  672. headers: {
  673. 'Authorization': this.options.authToken,
  674. }
  675. });
  676. this.afterRequest();
  677. } catch (err) {
  678. this.state.running = false;
  679. log.error('Search request threw an error:', err);
  680. throw err;
  681. }
  682.  
  683. // not indexed yet
  684. if (resp.status === 202) {
  685. let w = (await resp.json()).retry_after * 1000;
  686. w = w || this.stats.searchDelay; // Fix retry_after 0
  687. this.stats.throttledCount++;
  688. this.stats.throttledTotalTime += w;
  689. log.warn(`This channel isn't indexed yet. Waiting ${w}ms for discord to index it...`);
  690. await wait(w);
  691. return await this.search();
  692. }
  693.  
  694. if (!resp.ok) {
  695. // searching messages too fast
  696. if (resp.status === 429) {
  697. let w = (await resp.json()).retry_after * 1000;
  698. w = w || this.stats.searchDelay; // Fix retry_after 0
  699.  
  700. this.stats.throttledCount++;
  701. this.stats.throttledTotalTime += w;
  702. this.stats.searchDelay += w; // increase delay
  703. w = this.stats.searchDelay;
  704. log.warn(`Being rate limited by the API for ${w}ms! Increasing search delay...`);
  705. this.printStats();
  706. log.verb(`Cooling down for ${w * 2}ms before retrying...`);
  707.  
  708. await wait(w * 2);
  709. return await this.search();
  710. }
  711. else {
  712. this.state.running = false;
  713. log.error(`Error searching messages, API responded with status ${resp.status}!\n`, await resp.json());
  714. throw resp;
  715. }
  716. }
  717. const data = await resp.json();
  718. this.state._seachResponse = data;
  719. console.log(PREFIX$1, 'search', data);
  720. return data;
  721. }
  722.  
  723. async filterResponse() {
  724. const data = this.state._seachResponse;
  725.  
  726. // the search total will decrease as we delete stuff
  727. const total = data.total_results;
  728. if (total > this.state.grandTotal) this.state.grandTotal = total;
  729.  
  730. // search returns messages near the the actual message, only get the messages we searched for.
  731. const discoveredMessages = data.messages.map(convo => convo.find(message => message.hit === true));
  732.  
  733. // we can only delete some types of messages, system messages are not deletable.
  734. let messagesToDelete = discoveredMessages;
  735. messagesToDelete = messagesToDelete.filter(msg => msg.type === 0 || (msg.type >= 6 && msg.type <= 21));
  736. messagesToDelete = messagesToDelete.filter(msg => msg.pinned ? this.options.includePinned : true);
  737.  
  738. // custom filter of messages
  739. try {
  740. const regex = new RegExp(this.options.pattern, 'i');
  741. messagesToDelete = messagesToDelete.filter(msg => regex.test(msg.content));
  742. } catch (e) {
  743. log.warn('Ignoring RegExp because pattern is malformed!', e);
  744. }
  745.  
  746. // create an array containing everything we skipped. (used to calculate offset for next searches)
  747. const skippedMessages = discoveredMessages.filter(msg => !messagesToDelete.find(m => m.id === msg.id));
  748.  
  749. this.state._messagesToDelete = messagesToDelete;
  750. this.state._skippedMessages = skippedMessages;
  751.  
  752. console.log(PREFIX$1, 'filterResponse', this.state);
  753. }
  754.  
  755. async deleteMessagesFromList() {
  756. for (let i = 0; i < this.state._messagesToDelete.length; i++) {
  757. const message = this.state._messagesToDelete[i];
  758. if (!this.state.running) return log.error('Stopped by you!');
  759.  
  760. log.debug(
  761. // `${((this.state.delCount + 1) / this.state.grandTotal * 100).toFixed(2)}%`,
  762. `[${this.state.delCount + 1}/${this.state.grandTotal}] ` +
  763. `<sup>${new Date(message.timestamp).toLocaleString()}</sup> ` +
  764. `<b>${redact(message.author.username + '#' + message.author.discriminator)}</b>` +
  765. `: <i>${redact(message.content).replace(/\n/g, '↵')}</i>` +
  766. (message.attachments.length ? redact(JSON.stringify(message.attachments)) : ''),
  767. `<sup>{ID:${redact(message.id)}}</sup>`
  768. );
  769.  
  770. // Delete a single message (with retry)
  771. let attempt = 0;
  772. while (attempt < this.options.maxAttempt) {
  773. const result = await this.deleteMessage(message);
  774.  
  775. if (result === 'RETRY') {
  776. attempt++;
  777. log.verb(`Retrying in ${this.options.deleteDelay}ms... (${attempt}/${this.options.maxAttempt})`);
  778. await wait(this.options.deleteDelay);
  779. }
  780. else break;
  781. }
  782.  
  783. this.calcEtr();
  784. if (this.onProgress) this.onProgress(this.state, this.stats);
  785.  
  786. await wait(this.options.deleteDelay);
  787. }
  788. }
  789.  
  790. async deleteMessage(message) {
  791. const API_DELETE_URL = `https://discord.com/api/v9/channels/${message.channel_id}/messages/${message.id}`;
  792. let resp;
  793. try {
  794. this.beforeRequest();
  795. resp = await fetch(API_DELETE_URL, {
  796. method: 'DELETE',
  797. headers: {
  798. 'Authorization': this.options.authToken,
  799. },
  800. });
  801. this.afterRequest();
  802. } catch (err) {
  803. // no response error (e.g. network error)
  804. log.error('Delete request throwed an error:', err);
  805. log.verb('Related object:', redact(JSON.stringify(message)));
  806. this.state.failCount++;
  807. return 'FAILED';
  808. }
  809.  
  810. if (!resp.ok) {
  811. if (resp.status === 429) {
  812. // deleting messages too fast
  813. const w = (await resp.json()).retry_after * 1000;
  814. this.stats.throttledCount++;
  815. this.stats.throttledTotalTime += w;
  816. this.options.deleteDelay = w; // increase delay
  817. log.warn(`Being rate limited by the API for ${w}ms! Adjusted delete delay to ${this.options.deleteDelay}ms.`);
  818. this.printStats();
  819. log.verb(`Cooling down for ${w * 2}ms before retrying...`);
  820. await wait(w * 2);
  821. return 'RETRY';
  822. } else {
  823. const body = await resp.text();
  824.  
  825. try {
  826. const r = JSON.parse(body);
  827.  
  828. if (resp.status === 400 && r.code === 50083) {
  829. // 400 can happen if the thread is archived (code=50083)
  830. // in this case we need to "skip" this message from the next search
  831. // otherwise it will come up again in the next page (and fail to delete again)
  832. log.warn('Error deleting message (Thread is archived). Will increment offset so we don\'t search this in the next page...');
  833. this.state.offset++;
  834. this.state.failCount++;
  835. return 'FAIL_SKIP'; // Failed but we will skip it next time
  836. }
  837.  
  838. log.error(`Error deleting message, API responded with status ${resp.status}!`, r);
  839. log.verb('Related object:', redact(JSON.stringify(message)));
  840. this.state.failCount++;
  841. return 'FAILED';
  842. } catch (e) {
  843. log.error(`Fail to parse JSON. API responded with status ${resp.status}!`, body);
  844. }
  845. }
  846. }
  847.  
  848. this.state.delCount++;
  849. return 'OK';
  850. }
  851.  
  852. #beforeTs = 0; // used to calculate latency
  853. beforeRequest() {
  854. this.#beforeTs = Date.now();
  855. }
  856. afterRequest() {
  857. this.stats.lastPing = (Date.now() - this.#beforeTs);
  858. this.stats.avgPing = this.stats.avgPing > 0 ? (this.stats.avgPing * 0.9) + (this.stats.lastPing * 0.1) : this.stats.lastPing;
  859. }
  860.  
  861. printStats() {
  862. log.verb(
  863. `Delete delay: ${this.options.deleteDelay}ms, Search delay: ${this.options.searchDelay}ms`,
  864. `Last Ping: ${this.stats.lastPing}ms, Average Ping: ${this.stats.avgPing | 0}ms`,
  865. );
  866. log.verb(
  867. `Rate Limited: ${this.stats.throttledCount} times.`,
  868. `Total time throttled: ${msToHMS(this.stats.throttledTotalTime)}.`
  869. );
  870. }
  871. }
  872.  
  873. const MOVE = 0;
  874. const RESIZE_T = 1;
  875. const RESIZE_B = 2;
  876. const RESIZE_L = 4;
  877. const RESIZE_R = 8;
  878. const RESIZE_TL = RESIZE_T + RESIZE_L;
  879. const RESIZE_TR = RESIZE_T + RESIZE_R;
  880. const RESIZE_BL = RESIZE_B + RESIZE_L;
  881. const RESIZE_BR = RESIZE_B + RESIZE_R;
  882.  
  883. /**
  884. * Make an element draggable/resizable
  885. * @author Victor N. wwww.vitim.us
  886. */
  887. class DragResize {
  888. constructor({ elm, moveHandle, options }) {
  889. this.options = defaultArgs({
  890. enabledDrag: true,
  891. enabledResize: true,
  892. minWidth: 200,
  893. maxWidth: Infinity,
  894. minHeight: 100,
  895. maxHeight: Infinity,
  896. dragAllowX: true,
  897. dragAllowY: true,
  898. resizeAllowX: true,
  899. resizeAllowY: true,
  900. draggingClass: 'drag',
  901. useMouseEvents: true,
  902. useTouchEvents: true,
  903. createHandlers: true,
  904. }, options);
  905. Object.assign(this, options);
  906. options = undefined;
  907.  
  908. elm.style.position = 'fixed';
  909.  
  910. this.drag_m = new Draggable(elm, moveHandle, MOVE, this.options);
  911.  
  912. if (this.options.createHandlers) {
  913. this.el_t = createElement('div', { name: 'grab-t' }, elm);
  914. this.drag_t = new Draggable(elm, this.el_t, RESIZE_T, this.options);
  915. this.el_r = createElement('div', { name: 'grab-r' }, elm);
  916. this.drag_r = new Draggable(elm, this.el_r, RESIZE_R, this.options);
  917. this.el_b = createElement('div', { name: 'grab-b' }, elm);
  918. this.drag_b = new Draggable(elm, this.el_b, RESIZE_B, this.options);
  919. this.el_l = createElement('div', { name: 'grab-l' }, elm);
  920. this.drag_l = new Draggable(elm, this.el_l, RESIZE_L, this.options);
  921. this.el_tl = createElement('div', { name: 'grab-tl' }, elm);
  922. this.drag_tl = new Draggable(elm, this.el_tl, RESIZE_TL, this.options);
  923. this.el_tr = createElement('div', { name: 'grab-tr' }, elm);
  924. this.drag_tr = new Draggable(elm, this.el_tr, RESIZE_TR, this.options);
  925. this.el_br = createElement('div', { name: 'grab-br' }, elm);
  926. this.drag_br = new Draggable(elm, this.el_br, RESIZE_BR, this.options);
  927. this.el_bl = createElement('div', { name: 'grab-bl' }, elm);
  928. this.drag_bl = new Draggable(elm, this.el_bl, RESIZE_BL, this.options);
  929. }
  930. }
  931. }
  932.  
  933. class Draggable {
  934. constructor(targetElm, handleElm, op, options) {
  935. Object.assign(this, options);
  936. options = undefined;
  937.  
  938. this._targetElm = targetElm;
  939. this._handleElm = handleElm;
  940.  
  941. let vw = window.innerWidth;
  942. let vh = window.innerHeight;
  943. let initialX, initialY, initialT, initialL, initialW, initialH;
  944.  
  945. const clamp = (value, min, max) => value < min ? min : value > max ? max : value;
  946.  
  947. const moveOp = (x, y) => {
  948. const deltaX = (x - initialX);
  949. const deltaY = (y - initialY);
  950. const t = clamp(initialT + deltaY, 0, vh - initialH);
  951. const l = clamp(initialL + deltaX, 0, vw - initialW);
  952. this._targetElm.style.top = t + 'px';
  953. this._targetElm.style.left = l + 'px';
  954. };
  955.  
  956. const resizeOp = (x, y) => {
  957. x = clamp(x, 0, vw);
  958. y = clamp(y, 0, vh);
  959. const deltaX = (x - initialX);
  960. const deltaY = (y - initialY);
  961. const resizeDirX = (op & RESIZE_L) ? -1 : 1;
  962. const resizeDirY = (op & RESIZE_T) ? -1 : 1;
  963. const deltaXMax = (this.maxWidth - initialW);
  964. const deltaXMin = (this.minWidth - initialW);
  965. const deltaYMax = (this.maxHeight - initialH);
  966. const deltaYMin = (this.minHeight - initialH);
  967. const t = initialT + clamp(deltaY * resizeDirY, deltaYMin, deltaYMax) * resizeDirY;
  968. const l = initialL + clamp(deltaX * resizeDirX, deltaXMin, deltaXMax) * resizeDirX;
  969. const w = initialW + clamp(deltaX * resizeDirX, deltaXMin, deltaXMax);
  970. const h = initialH + clamp(deltaY * resizeDirY, deltaYMin, deltaYMax);
  971. if (op & RESIZE_T) { // resize ↑
  972. this._targetElm.style.top = t + 'px';
  973. this._targetElm.style.height = h + 'px';
  974. }
  975. if (op & RESIZE_B) { // resize ↓
  976. this._targetElm.style.height = h + 'px';
  977. }
  978. if (op & RESIZE_L) { // resize ←
  979. this._targetElm.style.left = l + 'px';
  980. this._targetElm.style.width = w + 'px';
  981. }
  982. if (op & RESIZE_R) { // resize →
  983. this._targetElm.style.width = w + 'px';
  984. }
  985. };
  986.  
  987. let operation = op === MOVE ? moveOp : resizeOp;
  988.  
  989. function dragStartHandler(e) {
  990. const touch = e.type === 'touchstart';
  991. if ((e.buttons === 1 || e.which === 1) || touch) {
  992. e.preventDefault();
  993. const x = touch ? e.touches[0].clientX : e.clientX;
  994. const y = touch ? e.touches[0].clientY : e.clientY;
  995. initialX = x;
  996. initialY = y;
  997. vw = window.innerWidth;
  998. vh = window.innerHeight;
  999. initialT = this._targetElm.offsetTop;
  1000. initialL = this._targetElm.offsetLeft;
  1001. initialW = this._targetElm.clientWidth;
  1002. initialH = this._targetElm.clientHeight;
  1003. if (this.useMouseEvents) {
  1004. document.addEventListener('mousemove', this._dragMoveHandler);
  1005. document.addEventListener('mouseup', this._dragEndHandler);
  1006. }
  1007. if (this.useTouchEvents) {
  1008. document.addEventListener('touchmove', this._dragMoveHandler, { passive: false });
  1009. document.addEventListener('touchend', this._dragEndHandler);
  1010. }
  1011. this._targetElm.classList.add(this.draggingClass);
  1012. }
  1013. }
  1014.  
  1015. function dragMoveHandler(e) {
  1016. e.preventDefault();
  1017. let x, y;
  1018. const touch = e.type === 'touchmove';
  1019. if (touch) {
  1020. const t = e.touches[0];
  1021. x = t.clientX;
  1022. y = t.clientY;
  1023. } else { //mouse
  1024. // If the button is not down, dispatch a "fake" mouse up event, to stop listening to mousemove
  1025. // This happens when the mouseup is not captured (outside the browser)
  1026. if ((e.buttons || e.which) !== 1) {
  1027. this._dragEndHandler();
  1028. return;
  1029. }
  1030. x = e.clientX;
  1031. y = e.clientY;
  1032. }
  1033. // perform drag / resize operation
  1034. operation(x, y);
  1035. }
  1036.  
  1037. function dragEndHandler(e) {
  1038. if (this.useMouseEvents) {
  1039. document.removeEventListener('mousemove', this._dragMoveHandler);
  1040. document.removeEventListener('mouseup', this._dragEndHandler);
  1041. }
  1042. if (this.useTouchEvents) {
  1043. document.removeEventListener('touchmove', this._dragMoveHandler);
  1044. document.removeEventListener('touchend', this._dragEndHandler);
  1045. }
  1046. this._targetElm.classList.remove(this.draggingClass);
  1047. }
  1048.  
  1049. // We need to bind the handlers to this instance
  1050. this._dragStartHandler = dragStartHandler.bind(this);
  1051. this._dragMoveHandler = dragMoveHandler.bind(this);
  1052. this._dragEndHandler = dragEndHandler.bind(this);
  1053.  
  1054. this.enable();
  1055. }
  1056.  
  1057. /** Turn on the drag and drop of the instance */
  1058. enable() {
  1059. this.destroy(); // prevent events from getting binded twice
  1060. if (this.useMouseEvents) this._handleElm.addEventListener('mousedown', this._dragStartHandler);
  1061. if (this.useTouchEvents) this._handleElm.addEventListener('touchstart', this._dragStartHandler, { passive: false });
  1062. }
  1063.  
  1064. /** Teardown all events bound to the document and elements. You can resurrect this instance by calling enable() */
  1065. destroy() {
  1066. this._targetElm.classList.remove(this.draggingClass);
  1067. if (this.useMouseEvents) {
  1068. this._handleElm.removeEventListener('mousedown', this._dragStartHandler);
  1069. document.removeEventListener('mousemove', this._dragMoveHandler);
  1070. document.removeEventListener('mouseup', this._dragEndHandler);
  1071. }
  1072. if (this.useTouchEvents) {
  1073. this._handleElm.removeEventListener('touchstart', this._dragStartHandler);
  1074. document.removeEventListener('touchmove', this._dragMoveHandler);
  1075. document.removeEventListener('touchend', this._dragEndHandler);
  1076. }
  1077. }
  1078. }
  1079.  
  1080. function createElement(tag='div', attrs, parent) {
  1081. const elm = document.createElement(tag);
  1082. if (attrs) Object.entries(attrs).forEach(([k, v]) => elm.setAttribute(k, v));
  1083. if (parent) parent.appendChild(elm);
  1084. return elm;
  1085. }
  1086.  
  1087. function defaultArgs(defaults, options) {
  1088. function isObj(x) { return x !== null && typeof x === 'object'; }
  1089. function hasOwn(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
  1090. if (isObj(options)) for (let prop in defaults) {
  1091. if (hasOwn(defaults, prop) && hasOwn(options, prop) && options[prop] !== undefined) {
  1092. if (isObj(defaults[prop])) defaultArgs(defaults[prop], options[prop]);
  1093. else defaults[prop] = options[prop];
  1094. }
  1095. }
  1096. return defaults;
  1097. }
  1098.  
  1099. function createElm(html) {
  1100. const temp = document.createElement('div');
  1101. temp.innerHTML = html;
  1102. return temp.removeChild(temp.firstElementChild);
  1103. }
  1104.  
  1105. function insertCss(css) {
  1106. const style = document.createElement('style');
  1107. style.appendChild(document.createTextNode(css));
  1108. document.head.appendChild(style);
  1109. return style;
  1110. }
  1111.  
  1112. const messagePickerCss = `
  1113. body.undiscord-pick-message [data-list-id="chat-messages"] {
  1114. background-color: var(--background-secondary-alt);
  1115. box-shadow: inset 0 0 0px 2px var(--button-outline-brand-border);
  1116. }
  1117.  
  1118. body.undiscord-pick-message [id^="message-content-"]:hover {
  1119. cursor: pointer;
  1120. cursor: cell;
  1121. background: var(--background-message-automod-hover);
  1122. }
  1123. body.undiscord-pick-message [id^="message-content-"]:hover::after {
  1124. position: absolute;
  1125. top: calc(50% - 11px);
  1126. left: 4px;
  1127. z-index: 1;
  1128. width: 65px;
  1129. height: 22px;
  1130. line-height: 22px;
  1131. font-family: var(--font-display);
  1132. background-color: var(--button-secondary-background);
  1133. color: var(--header-secondary);
  1134. font-size: 12px;
  1135. font-weight: 500;
  1136. text-transform: uppercase;
  1137. text-align: center;
  1138. border-radius: 3px;
  1139. content: 'This 👉';
  1140. }
  1141. body.undiscord-pick-message.before [id^="message-content-"]:hover::after {
  1142. content: 'Before 👆';
  1143. }
  1144. body.undiscord-pick-message.after [id^="message-content-"]:hover::after {
  1145. content: 'After 👇';
  1146. }
  1147. `;
  1148.  
  1149. const messagePicker = {
  1150. init() {
  1151. insertCss(messagePickerCss);
  1152. },
  1153. grab(auxiliary) {
  1154. return new Promise((resolve, reject) => {
  1155. document.body.classList.add('undiscord-pick-message');
  1156. if (auxiliary) document.body.classList.add(auxiliary);
  1157. function clickHandler(e) {
  1158. const message = e.target.closest('[id^="message-content-"]');
  1159. if (message) {
  1160. e.preventDefault();
  1161. e.stopPropagation();
  1162. e.stopImmediatePropagation();
  1163. if (auxiliary) document.body.classList.remove(auxiliary);
  1164. document.body.classList.remove('undiscord-pick-message');
  1165. document.removeEventListener('click', clickHandler);
  1166. try {
  1167. resolve(message.id.match(/message-content-(\d+)/)[1]);
  1168. } catch (e) {
  1169. resolve(null);
  1170. }
  1171. }
  1172. }
  1173. document.addEventListener('click', clickHandler);
  1174. });
  1175. }
  1176. };
  1177. window.messagePicker = messagePicker;
  1178.  
  1179. function getToken() {
  1180. window.dispatchEvent(new Event('beforeunload'));
  1181. const LS = document.body.appendChild(document.createElement('iframe')).contentWindow.localStorage;
  1182. try {
  1183. return JSON.parse(LS.token);
  1184. } catch {
  1185. log.info('Could not automatically detect Authorization Token in local storage!');
  1186. log.info('Attempting to grab token using webpack');
  1187. return (window.webpackChunkdiscord_app.push([[''], {}, e => { window.m = []; for (let c in e.c) window.m.push(e.c[c]); }]), window.m).find(m => m?.exports?.default?.getToken !== void 0).exports.default.getToken();
  1188. }
  1189. }
  1190.  
  1191. function getAuthorId() {
  1192. const LS = document.body.appendChild(document.createElement('iframe')).contentWindow.localStorage;
  1193. return JSON.parse(LS.user_id_cache);
  1194. }
  1195.  
  1196. function getGuildId() {
  1197. const m = location.href.match(/channels\/([\w@]+)\/(\d+)/);
  1198. if (m) return m[1];
  1199. else alert('Could not find the Guild ID!\nPlease make sure you are on a Server or DM.');
  1200. }
  1201.  
  1202. function getChannelId() {
  1203. const m = location.href.match(/channels\/([\w@]+)\/(\d+)/);
  1204. if (m) return m[2];
  1205. else alert('Could not find the Channel ID!\nPlease make sure you are on a Channel or DM.');
  1206. }
  1207.  
  1208. function fillToken() {
  1209. try {
  1210. return getToken();
  1211. } catch (err) {
  1212. log.verb(err);
  1213. log.error('Could not automatically detect Authorization Token!');
  1214. log.info('Please make sure Undiscord is up to date');
  1215. log.debug('Alternatively, you can try entering a Token manually in the "Advanced Settings" section.');
  1216. }
  1217. return '';
  1218. }
  1219.  
  1220. const PREFIX = '[UNDISCORD]';
  1221.  
  1222. // -------------------------- User interface ------------------------------- //
  1223.  
  1224. // links
  1225. const HOME = 'https://github.com/victornpb/undiscord';
  1226. const WIKI = 'https://github.com/victornpb/undiscord/wiki';
  1227.  
  1228. const undiscordCore = new UndiscordCore();
  1229. messagePicker.init();
  1230.  
  1231. const ui = {
  1232. undiscordWindow: null,
  1233. undiscordBtn: null,
  1234. logArea: null,
  1235. autoScroll: null,
  1236.  
  1237. // progress handler
  1238. progressMain: null,
  1239. progressIcon: null,
  1240. percent: null,
  1241. };
  1242. const $ = s => ui.undiscordWindow.querySelector(s);
  1243.  
  1244. function initUI() {
  1245.  
  1246. insertCss(themeCss);
  1247. insertCss(mainCss);
  1248. insertCss(dragCss);
  1249.  
  1250. // create undiscord window
  1251. const undiscordUI = replaceInterpolations(undiscordTemplate, {
  1252. VERSION,
  1253. HOME,
  1254. WIKI,
  1255. });
  1256. ui.undiscordWindow = createElm(undiscordUI);
  1257. document.body.appendChild(ui.undiscordWindow);
  1258.  
  1259. // enable drag and resize on undiscord window
  1260. new DragResize({ elm: ui.undiscordWindow, moveHandle: $('.header') });
  1261.  
  1262. // create undiscord Trash icon
  1263. ui.undiscordBtn = createElm(buttonHtml);
  1264. ui.undiscordBtn.onclick = toggleWindow;
  1265. function mountBtn() {
  1266. const toolbar = document.querySelector('#app-mount [class^=toolbar]');
  1267. if (toolbar) toolbar.appendChild(ui.undiscordBtn);
  1268. }
  1269. mountBtn();
  1270. // watch for changes and re-mount button if necessary
  1271. const discordElm = document.querySelector('#app-mount');
  1272. let observerThrottle = null;
  1273. const observer = new MutationObserver((_mutationsList, _observer) => {
  1274. if (observerThrottle) return;
  1275. observerThrottle = setTimeout(() => {
  1276. observerThrottle = null;
  1277. if (!discordElm.contains(ui.undiscordBtn)) mountBtn(); // re-mount the button to the toolbar
  1278. }, 3000);
  1279. });
  1280. observer.observe(discordElm, { attributes: false, childList: true, subtree: true });
  1281.  
  1282. function toggleWindow() {
  1283. if (ui.undiscordWindow.style.display !== 'none') {
  1284. ui.undiscordWindow.style.display = 'none';
  1285. ui.undiscordBtn.style.color = 'var(--interactive-normal)';
  1286. }
  1287. else {
  1288. ui.undiscordWindow.style.display = '';
  1289. ui.undiscordBtn.style.color = 'var(--interactive-active)';
  1290. }
  1291. }
  1292.  
  1293. // cached elements
  1294. ui.logArea = $('#logArea');
  1295. ui.autoScroll = $('#autoScroll');
  1296. ui.progressMain = $('#progressBar');
  1297. ui.progressIcon = ui.undiscordBtn.querySelector('progress');
  1298. ui.percent = $('#progressPercent');
  1299.  
  1300. // register event listeners
  1301. $('#hide').onclick = toggleWindow;
  1302. $('#toggleSidebar').onclick = ()=> ui.undiscordWindow.classList.toggle('hide-sidebar');
  1303. $('button#start').onclick = startAction;
  1304. $('button#stop').onclick = stopAction;
  1305. $('button#clear').onclick = () => ui.logArea.innerHTML = '';
  1306. $('button#getAuthor').onclick = () => $('input#authorId').value = getAuthorId();
  1307. $('button#getGuild').onclick = () => {
  1308. const guildId = $('input#guildId').value = getGuildId();
  1309. if (guildId === '@me') $('input#channelId').value = getChannelId();
  1310. };
  1311. $('button#getChannel').onclick = () => {
  1312. $('input#channelId').value = getChannelId();
  1313. $('input#guildId').value = getGuildId();
  1314. };
  1315. $('#redact').onchange = () => {
  1316. const b = ui.undiscordWindow.classList.toggle('redact');
  1317. if (b) alert('This mode will attempt to hide personal information, so you can screen share / take screenshots.\nAlways double check you are not sharing sensitive information!');
  1318. };
  1319. $('#pickMessageAfter').onclick = async () => {
  1320. alert('Select a message on the chat.\nThe message below it will be deleted.');
  1321. toggleWindow();
  1322. const id = await messagePicker.grab('after');
  1323. if (id) $('input#minId').value = id;
  1324. toggleWindow();
  1325. };
  1326. $('#pickMessageBefore').onclick = async () => {
  1327. alert('Select a message on the chat.\nThe message above it will be deleted.');
  1328. toggleWindow();
  1329. const id = await messagePicker.grab('before');
  1330. if (id) $('input#maxId').value = id;
  1331. toggleWindow();
  1332. };
  1333. $('button#getToken').onclick = () => $('input#token').value = fillToken();
  1334.  
  1335. // sync delays
  1336. $('input#searchDelay').onchange = (e) => {
  1337. const v = parseInt(e.target.value);
  1338. if (v) undiscordCore.options.searchDelay = v;
  1339. };
  1340. $('input#deleteDelay').onchange = (e) => {
  1341. const v = parseInt(e.target.value);
  1342. if (v) undiscordCore.options.deleteDelay = v;
  1343. };
  1344.  
  1345. $('input#searchDelay').addEventListener('input', (event) => {
  1346. $('div#searchDelayValue').textContent = event.target.value + 'ms';
  1347. });
  1348. $('input#deleteDelay').addEventListener('input', (event) => {
  1349. $('div#deleteDelayValue').textContent = event.target.value + 'ms';
  1350. });
  1351.  
  1352. // import json
  1353. const fileSelection = $('input#importJsonInput');
  1354. fileSelection.onchange = async () => {
  1355. const files = fileSelection.files;
  1356.  
  1357. // No files added
  1358. if (files.length === 0) return log.warn('No file selected.');
  1359.  
  1360. // Get channel id field to set it later
  1361. const channelIdField = $('input#channelId');
  1362.  
  1363. // Force the guild id to be ourself (@me)
  1364. const guildIdField = $('input#guildId');
  1365. guildIdField.value = '@me';
  1366.  
  1367. // Set author id in case its not set already
  1368. $('input#authorId').value = getAuthorId();
  1369. try {
  1370. const file = files[0];
  1371. const text = await file.text();
  1372. const json = JSON.parse(text);
  1373. const channelIds = Object.keys(json);
  1374. channelIdField.value = channelIds.join(',');
  1375. log.info(`Loaded ${channelIds.length} channels.`);
  1376. } catch(err) {
  1377. log.error('Error parsing file!', err);
  1378. }
  1379. };
  1380.  
  1381. // redirect console logs to inside the window after setting up the UI
  1382. setLogFn(printLog);
  1383.  
  1384. setupUndiscordCore();
  1385. }
  1386.  
  1387. function printLog(type = '', args) {
  1388. ui.logArea.insertAdjacentHTML('beforeend', `<div class="log log-${type}">${Array.from(args).map(o => typeof o === 'object' ? JSON.stringify(o, o instanceof Error && Object.getOwnPropertyNames(o)) : o).join('\t')}</div>`);
  1389. if (ui.autoScroll.checked) ui.logArea.querySelector('div:last-child').scrollIntoView(false);
  1390. if (type==='error') console.error(PREFIX, ...Array.from(args));
  1391. }
  1392.  
  1393. function setupUndiscordCore() {
  1394.  
  1395. undiscordCore.onStart = (state, stats) => {
  1396. console.log(PREFIX, 'onStart', state, stats);
  1397. $('#start').disabled = true;
  1398. $('#stop').disabled = false;
  1399.  
  1400. ui.undiscordBtn.classList.add('running');
  1401. ui.progressMain.style.display = 'block';
  1402. ui.percent.style.display = 'block';
  1403. };
  1404.  
  1405. undiscordCore.onProgress = (state, stats) => {
  1406. // console.log(PREFIX, 'onProgress', state, stats);
  1407. let max = state.grandTotal;
  1408. const value = state.delCount + state.failCount;
  1409. max = Math.max(max, value, 0); // clamp max
  1410.  
  1411. // status bar
  1412. const percent = value >= 0 && max ? Math.round(value / max * 100) + '%' : '';
  1413. const elapsed = msToHMS(Date.now() - stats.startTime.getTime());
  1414. const remaining = msToHMS(stats.etr);
  1415. ui.percent.innerHTML = `${percent} (${value}/${max}) Elapsed: ${elapsed} Remaining: ${remaining}`;
  1416.  
  1417. ui.progressIcon.value = value;
  1418. ui.progressMain.value = value;
  1419.  
  1420. // indeterminate progress bar
  1421. if (max) {
  1422. ui.progressIcon.setAttribute('max', max);
  1423. ui.progressMain.setAttribute('max', max);
  1424. } else {
  1425. ui.progressIcon.removeAttribute('value');
  1426. ui.progressMain.removeAttribute('value');
  1427. ui.percent.innerHTML = '...';
  1428. }
  1429.  
  1430. // update delays
  1431. const searchDelayInput = $('input#searchDelay');
  1432. searchDelayInput.value = undiscordCore.options.searchDelay;
  1433. $('div#searchDelayValue').textContent = undiscordCore.options.searchDelay+'ms';
  1434.  
  1435. const deleteDelayInput = $('input#deleteDelay');
  1436. deleteDelayInput.value = undiscordCore.options.deleteDelay;
  1437. $('div#deleteDelayValue').textContent = undiscordCore.options.deleteDelay+'ms';
  1438. };
  1439.  
  1440. undiscordCore.onStop = (state, stats) => {
  1441. console.log(PREFIX, 'onStop', state, stats);
  1442. $('#start').disabled = false;
  1443. $('#stop').disabled = true;
  1444. ui.undiscordBtn.classList.remove('running');
  1445. ui.progressMain.style.display = 'none';
  1446. ui.percent.style.display = 'none';
  1447. };
  1448. }
  1449.  
  1450. async function startAction() {
  1451. console.log(PREFIX, 'startAction');
  1452. // general
  1453. const authorId = $('input#authorId').value.trim();
  1454. const guildId = $('input#guildId').value.trim();
  1455. const channelIds = $('input#channelId').value.trim().split(/\s*,\s*/);
  1456. const includeNsfw = $('input#includeNsfw').checked;
  1457. // filter
  1458. const content = $('input#search').value.trim();
  1459. const hasLink = $('input#hasLink').checked;
  1460. const hasFile = $('input#hasFile').checked;
  1461. const includePinned = $('input#includePinned').checked;
  1462. const pattern = $('input#pattern').value;
  1463. // message interval
  1464. const minId = $('input#minId').value.trim();
  1465. const maxId = $('input#maxId').value.trim();
  1466. // date range
  1467. const minDate = $('input#minDate').value.trim();
  1468. const maxDate = $('input#maxDate').value.trim();
  1469. //advanced
  1470. const searchDelay = parseInt($('input#searchDelay').value.trim());
  1471. const deleteDelay = parseInt($('input#deleteDelay').value.trim());
  1472.  
  1473. // token
  1474. const authToken = $('input#token').value.trim() || fillToken();
  1475. if (!authToken) return; // get token already logs an error.
  1476.  
  1477. // validate input
  1478. if (!guildId) return log.error('You must fill the "Server ID" field!');
  1479.  
  1480. // clear logArea
  1481. ui.logArea.innerHTML = '';
  1482.  
  1483. undiscordCore.resetState();
  1484. undiscordCore.options = {
  1485. ...undiscordCore.options,
  1486. authToken,
  1487. authorId,
  1488. guildId,
  1489. channelId: channelIds.length === 1 ? channelIds[0] : undefined, // single or multiple channel
  1490. minId: minId || minDate,
  1491. maxId: maxId || maxDate,
  1492. content,
  1493. hasLink,
  1494. hasFile,
  1495. includeNsfw,
  1496. includePinned,
  1497. pattern,
  1498. searchDelay,
  1499. deleteDelay,
  1500. // maxAttempt: 2,
  1501. };
  1502. if (channelIds.length > 1) {
  1503. const jobs = channelIds.map(ch => ({
  1504. guildId: guildId,
  1505. channelId: ch,
  1506. }));
  1507.  
  1508. try {
  1509. await undiscordCore.runBatch(jobs);
  1510. } catch (err) {
  1511. log.error('CoreException', err);
  1512. }
  1513. }
  1514. // single channel
  1515. else {
  1516. try {
  1517. await undiscordCore.run();
  1518. } catch (err) {
  1519. log.error('CoreException', err);
  1520. undiscordCore.stop();
  1521. }
  1522. }
  1523. }
  1524.  
  1525. function stopAction() {
  1526. console.log(PREFIX, 'stopAction');
  1527. undiscordCore.stop();
  1528. }
  1529.  
  1530. // ---- END Undiscord ----
  1531.  
  1532. initUI();
  1533.  
  1534. })();