zeres plugin library //META{"name":"MessageLoggerV2","source":"https://gitlab.com/_Lighty_/bdstuff/blob/master/MessageLoggerV2.plugin.js","website":"https://_lighty_.gitlab.io/bdstuff/?plugin=MessageLoggerV2"}*// /*@cc_on @if (@_jscript) // Offer to self-install for clueless users that try to run this directly. var shell = WScript.CreateObject("WScript.Shell"); var fs = new ActiveXObject("Scripting.FileSystemObject"); var pathPlugins = shell.ExpandEnvironmentStrings("%APPDATA%\\BetterDiscord\\plugins"); var pathSelf = WScript.ScriptFullName; // Put the user at ease by addressing them in the first person shell.Popup("It looks like you mistakenly tried to run me directly. (don't do that!)", 0, "I'm a plugin for BetterDiscord", 0x30); if (fs.GetParentFolderName(pathSelf) === fs.GetAbsolutePathName(pathPlugins)) { zeres plugin library How to dowload it? zeres plugin library shell.Popup("I'm in the correct folder already.\nJust reload Discord with Ctrl+R.", 0, "I'm already installed", 0x40); } else if (!fs.FolderExists(pathPlugins)) { shell.Popup("I can't find the BetterDiscord plugins folder.\nAre you sure it's even installed?", 0, "Can't install myself", 0x10); } else if (shell.Popup("Should I copy myself to BetterDiscord's plugins folder for you?", 0, "Do you need some help?", 0x34) === 6) { fs.CopyFile(pathSelf, fs.BuildPath(pathPlugins, fs.GetFileName(pathSelf)), true); // Show the user where to put plugins in the future shell.Exec("explorer " + pathPlugins); shell.Popup("I'm installed!\nJust reload Discord with Ctrl+R.", 0, "Successfully installed", 0x40); } WScript.Quit(); zeres plugin library How to get it for free? zeres plugin library @else @*/ // extra TODOs: // special edited message https://i.clouds.tf/guli/mric.png // modal for checking which servers/channels/users are blacklisted/whitelisted // option to show all hidden // menu is unusable in light theme class MessageLoggerV2 { getName() { return 'MessageLoggerV2'; } zeres plugin library PasteShr zeres plugin library getVersion() { return '1.6.7'; } getAuthor() { return 'Lighty'; } getDescription() { return "Recode of Metalloriff's MessageLogger plugin. Records all sent messages, message edits and message deletions in the specified servers, all unmuted servers or all servers, and in direct messages."; } load() {} zeres plugin library How to use it? zeres plugin library start() { let onLoaded = () => { try { if (!global.ZeresPluginLibrary || !(this.localUser = ZeresPluginLibrary.DiscordModules.UserStore.getCurrentUser())) setTimeout(() => onLoaded(), 1000); else this.initialize(); } catch (err) { ZeresPluginLibrary.Logger.stacktrace(this.getName(), 'Failed to start!', err); ZeresPluginLibrary.Logger.err(this.getName(), `If you cannot solve this yourself, contact ${this.getAuthor()} and provide the errors shown here.`); this.stop(); this.showToast(`[${this.getName()}] Failed to start! Check console (CTRL + SHIFT + I, click console tab) for more error info.`, { type: 'error', timeout: 10000 }); zeres plugin library How to dowload it? zeres plugin library } }; const getDir = () => { // from Zeres Plugin Library, copied here as ZLib may not be available at this point const process = require('process'); const path = require('path'); if (process.env.injDir) return path.resolve(process.env.injDir, 'plugins/'); switch (process.platform) { case 'win32': return path.resolve(process.env.appdata, 'BetterDiscord/plugins/'); zeres plugin library How to get it? zeres plugin library case 'darwin': return path.resolve(process.env.HOME, 'Library/Preferences/', 'BetterDiscord/plugins/'); default: return path.resolve(process.env.XDG_CONFIG_HOME ? process.env.XDG_CONFIG_HOME : process.env.HOME + '/.config', 'BetterDiscord/plugins/'); } }; this.pluginDir = getDir(); let libraryOutdated = false; // I'm sick and tired of people telling me my plugin doesn't work and it's cause zlib is outdated, ffs if (!global.ZLibrary || !global.ZeresPluginLibrary || (bdplugins.ZeresPluginLibrary && (libraryOutdated = ZeresPluginLibrary.PluginUpdater.defaultComparator(bdplugins.ZeresPluginLibrary.plugin._config.info.version, '1.2.6')))) { zeres plugin library How to get it for free? zeres plugin library const title = libraryOutdated ? 'Library outdated' : 'Library Missing'; const ModalStack = BdApi.findModuleByProps('push', 'update', 'pop', 'popWithKey'); const TextElement = BdApi.findModuleByProps('Sizes', 'Weights'); const ConfirmationModal = BdApi.findModule(m => m.defaultProps && m.key && m.key() == 'confirm-modal'); const confirmedDownload = () => { require('request').get('https://rauenzi.github.io/BDPluginLibrary/release/0PluginLibrary.plugin.js', async (error, response, body) => { if (error) return require('electron').shell.openExternal('https://betterdiscord.net/ghdl?url=https://raw.githubusercontent.com/rauenzi/BDPluginLibrary/master/release/0PluginLibrary.plugin.js'); require('fs').writeFile(require('path').join(this.pluginDir, '0PluginLibrary.plugin.js'), body, () => { setTimeout(() => { if (!global.bdplugins.ZeresPluginLibrary) return BdApi.alert('Notice', `Due to you using EnhancedDiscord instead of BetterDiscord, you'll have to reload your Discord before ${this.getName()} starts working. Just press CTRL + R to reload and ${this.getName()} will begin to work!`); zeres plugin library How to dowload it? zeres plugin library onLoaded(); }, 1000); }); }); }; if (!ModalStack || !ConfirmationModal || !TextElement) { BdApi.alert('Uh oh', `Looks like you${libraryOutdated ? 'r Zeres Plugin Library was outdated!' : ' were missing Zeres Plugin Library!'} Also, failed to show a modal, so it has been ${libraryOutdated ? 'updated' : 'downloaded and loaded'} automatically.`); confirmedDownload(); return; } zeres plugin library How to dowload it? zeres plugin library ModalStack.push(props => { return BdApi.React.createElement( ConfirmationModal, Object.assign( { header: title, children: [TextElement({ color: TextElement.Colors.PRIMARY, children: [`The library plugin needed for ${this.getName()} is ${libraryOutdated ? 'outdated' : 'missing'}. Please click Download Now to ${libraryOutdated ? 'update' : 'install'} it.`] })], red: false, confirmText: 'Download Now', cancelText: 'Cancel', zeres plugin library How to get it for free? zeres plugin library onConfirm: () => confirmedDownload() }, props ) ); }); } else onLoaded(); } stop() { try { zeres plugin library PasteShr zeres plugin library this.shutdown(); } catch (err) { ZeresPluginLibrary.Logger.stacktrace(this.getName(), 'Failed to stop!', err); } } getChanges() { return [ { title: 'added', type: 'added', zeres plugin library How to get it? zeres plugin library items: ['Added data file size and severity to corruption to stats modal.'] }, { title: 'fixes', type: 'fixed', items: ['Fixed light theme not being supported fully.', 'Fixed stats modal not showing sent message count.', 'Fixed saved messages cap description not explaining well what it actually does.'] } /* , { title: 'Improved', type: 'improved', zeres plugin library How to get it? zeres plugin library items: [ 'Links in edited messages are darkened like normal text to differentiate between edit and current message', 'Edited message color is no longer hardcoded, it is now simply normal text color but darkened, to match theme colors.', 'Toasts no longer show for local user in DMs (you did it, why show it?).', 'Ghost ping toast no longer shows if you are in the channel.' ] } */ /* , { title: 'Gimme some time', zeres plugin library How to dowload it? zeres plugin library type: 'progress', items: ['Expand Stats modal to show per server and per channel stats, also show disk space usage.'] } */ ]; } initialize() { let defaultSettings = { obfuscateCSSClasses: false, autoBackup: false, dontSaveData: false, zeres plugin library How to get it for free? zeres plugin library displayUpdateNotes: true, ignoreMutedGuilds: true, ignoreMutedChannels: true, ignoreBots: true, ignoreSelf: false, ignoreBlockedUsers: true, ignoreNSFW: false, ignoreLocalEdits: false, ignoreLocalDeletes: false, alwaysLogGhostPings: false, zeres plugin library How to get it? zeres plugin library showOpenLogsButton: true, messageCacheCap: 1000, savedMessagesCap: 1000, reverseOrder: true, onlyLogWhitelist: false, whitelist: [], blacklist: [], toastToggles: { sent: false, edited: true, zeres plugin library How to use it? zeres plugin library deleted: true, ghostPings: true }, toastTogglesDMs: { sent: false, edited: true, deleted: true, ghostPings: true, disableToastsForLocal: false }, zeres plugin library How to use it? zeres plugin library blockSpamEdit: false, disableKeybind: false, cacheAllImages: true, dontDeleteCachedImages: false, aggresiveMessageCaching: true, openLogKeybind: [ /* 162, 77 */ ], // ctrl + m on windows openLogFilteredKeybind: [ /* 162, 78 */ zeres plugin library How to get it? zeres plugin library ], // ctrl + n on windows renderCap: 50, maxShownEdits: 0, hideNewerEditsFirst: true, displayDates: true, deletedMessageColor: '', editedMessageColor: '', showEditedMessages: true, showDeletedMessages: true, showPurgedMessages: true, zeres plugin library How to get it? zeres plugin library showDeletedCount: true, showEditedCount: true, alwaysLogSelected: true, alwaysLogDM: true, restoreDeletedMessages: true, versionInfo: '' }; this.settings = ZeresPluginLibrary.PluginUtilities.loadSettings(this.getName(), defaultSettings); let settingsChanged = false; zeres plugin library PasteShr zeres plugin library if (!this.settings || !Object.keys(this.settings).length) { this.showToast(`[${this.getName()}] Settings file corrupted! All settings restored to default.`, { type: 'error', timeout: 5000 }); this.settings = defaultSettings; // todo: does defaultSettings get changed? settingsChanged = true; } if (!this.settings.openLogKeybind.length) { this.settings.openLogKeybind = [162, 77]; settingsChanged = true; } zeres plugin library PasteShr zeres plugin library if (!this.settings.openLogFilteredKeybind.length) { this.settings.openLogFilteredKeybind = [162, 78]; settingsChanged = true; } // force update ZeresPluginLibrary.PluginUpdater.checkForUpdate(this.getName(), this.getVersion(), 'https://_lighty_.gitlab.io/bdstuff/plugins/MessageLoggerV2.plugin.js'); if (this.settings.versionInfo !== this.getVersion() && this.settings.displayUpdateNotes) { ZeresPluginLibrary.Modals.showChangelogModal(this.getName() + ' Changelog', this.getVersion(), this.getChanges()); this.settings.versionInfo = this.getVersion(); zeres plugin library How to get it for free? zeres plugin library this.saveSettings(); settingsChanged = false; } if (settingsChanged) this.saveSettings(); this.nodeModules = { electron: require('electron'), request: require('request'), fs: require('fs') zeres plugin library PasteShr zeres plugin library }; let defaultConstruct = () => { return Object.assign( {}, { messageRecord: {}, deletedMessageRecord: {}, editedMessageRecord: {}, purgedMessageRecord: {} zeres plugin library How to get it for free? zeres plugin library } ); }; let data; if (this.settings.dontSaveData) { data = defaultConstruct(); } else { data = this.loadData(this.getName() + 'Data', defaultConstruct()); const isBad = map => !(map && map.messageRecord && map.editedMessageRecord && map.deletedMessageRecord && map.purgedMessageRecord && typeof map.messageRecord == 'object' && typeof map.editedMessageRecord == 'object' && typeof map.deletedMessageRecord == 'object' && typeof map.purgedMessageRecord == 'object'); if (isBad(data)) { zeres plugin library PasteShr zeres plugin library if (this.settings.autoBackup) { this.showToast(`[${this.getName()}] Data was corrupted! Loading backup.`, { type: 'info', timeout: 5000 }); data = this.loadData(this.getName() + 'DataBackup', defaultConstruct()); if (isBad(data)) { this.showToast(`[${this.getName()}] Backup was corrupted! All deleted/edited/purged messages have been erased.`, { type: 'error', timeout: 10000 }); data = defaultConstruct(); } } else { this.showToast(`[${this.getName()}] Data was corrupted! Recommended to turn on auto backup in settings! All deleted/edited/purged messages have been erased.`, { type: 'error', timeout: 10000 }); data = defaultConstruct(); zeres plugin library How to use it? zeres plugin library } } } const dataFileSize = this.nodeModules.fs.statSync(this.pluginDir + '/MessageLoggerV2Data.config.json').size / 1024 / 1024; // SEVERITY // 0 OK < 5MiB // 1 MILD < 10MiB // 2 DANGER < 20MiB // 3 EXTREME > 20MiB zeres plugin library How to dowload it? zeres plugin library this.slowSaveModeStep = dataFileSize > 20 ? 3 : dataFileSize > 10 ? 2 : dataFileSize > 5 ? 1 : 0; ZLibrary.Logger.info(this.getName(), `Data file size is ${dataFileSize.toFixed(2)}MB`); if (this.slowSaveModeStep) ZLibrary.Logger.warn(this.getName(), 'Data file is too large, severity level', this.slowSaveModeStep); if (!this.settings.dontSaveData) { const records = data.messageRecord; // data structure changed a wee bit, compensate instead of deleting user data or worse, erroring out for (let a in records) { const record = records[a]; if (record.deletedata) { zeres plugin library How to dowload it? zeres plugin library if (record.deletedata.deletetime) { record.delete_data = {}; record.delete_data.time = record.deletedata.deletetime; record.delete_data.rel_ids = record.deletedata.relativeids; } delete record.deletedata; } if (record.editHistory) { record.edit_history = []; for (let b in record.editHistory) { zeres plugin library How to dowload it? zeres plugin library record.edit_history.push({ content: record.editHistory[b].content, time: record.editHistory[b].editedAt }); } delete record.editHistory; } this.fixEmbeds(record.message); } } this.cachedMessageRecord = []; this.messageRecord = data.messageRecord; zeres plugin library How to get it? zeres plugin library this.deletedMessageRecord = data.deletedMessageRecord; this.editedMessageRecord = data.editedMessageRecord; this.purgedMessageRecord = data.purgedMessageRecord; this.tempEditedMessageRecord = {}; this.editHistoryAntiSpam = {}; this.localDeletes = []; defaultConstruct = () => { return Object.assign( {}, zeres plugin library How to get it for free? zeres plugin library { imageCacheRecord: {} } ); }; this.imageCacheDir = this.pluginDir + '/MLV2_IMAGE_CACHE'; if (this.settings.cacheAllImages && !this.nodeModules.fs.existsSync(this.imageCacheDir)) this.nodeModules.fs.mkdirSync(this.imageCacheDir); zeres plugin library How to dowload it? zeres plugin library if (this.settings.dontSaveData || !this.settings.cacheAllImages) { data = defaultConstruct(); // unused but just in case my stupidity gets in the way } else { data = this.loadData('MLV2_IMAGE_CACHE/ImageCache', defaultConstruct()); const isBad = map => !(map && map.imageCacheRecord && typeof map.imageCacheRecord == 'object'); if (isBad(data)) { data = defaultConstruct(); } } zeres plugin library PasteShr zeres plugin library this.imageCacheRecord = data.imageCacheRecord; defaultConstruct = undefined; this.tools = { openUserContextMenu: null /* NeatoLib.Modules.get('openUserContextMenu').openUserContextMenu */, // TODO: move here getMessage: ZeresPluginLibrary.DiscordModules.MessageStore.getMessage, fetchMessages: ZeresPluginLibrary.DiscordModules.MessageActions.fetchMessages, transitionTo: null /* NeatoLib.Modules.get('transitionTo').transitionTo */, getChannel: ZeresPluginLibrary.DiscordModules.ChannelStore.getChannel, zeres plugin library PasteShr zeres plugin library copyToClipboard: this.nodeModules.electron.clipboard.writeText, getServer: ZeresPluginLibrary.DiscordModules.GuildStore.getGuild, getUser: ZeresPluginLibrary.DiscordModules.UserStore.getUser, parse: ZeresPluginLibrary.WebpackModules.getByProps('parserFor', 'parse').parse, getUserAsync: ZeresPluginLibrary.WebpackModules.getByProps('getUser', 'acceptAgreements').getUser, isBlocked: ZeresPluginLibrary.WebpackModules.getByProps('isBlocked').isBlocked, createMomentObject: ZeresPluginLibrary.WebpackModules.getByProps('createFromInputFallback'), isMentioned: ZeresPluginLibrary.WebpackModules.getByProps('isMentioned').isMentioned }; zeres plugin library How to get it? zeres plugin library this.createButton.classes = { button: (function() { let buttonData = ZeresPluginLibrary.WebpackModules.getByProps('button', 'colorBrand'); return `${buttonData.button} ${buttonData.lookFilled} ${buttonData.colorBrand} ${buttonData.sizeSmall} ${buttonData.grow}`; })(), buttonContents: ZeresPluginLibrary.WebpackModules.getByProps('button', 'colorBrand').contents }; this.createMessageGroup.classes = { containerBounded: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').containerCozyBounded, zeres plugin library PasteShr zeres plugin library message: `.${ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').containerCozyBounded.split(/ /g)[0]} > div`, header: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').headerCozy, avatar: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').avatar, headerMeta: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').headerCozyMeta, username: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').username, timestamp: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').timestampCozy, timestampSingle: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').timestampCozy.split(/ /g)[0], content: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').contentCozy, avatarSingle: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').avatar.split(/ /g)[0], avatarImg: ZeresPluginLibrary.WebpackModules.getByProps('avatar', 'cursorDefault', 'mask').avatar, zeres plugin library How to get it? zeres plugin library avatarImgSingle: ZeresPluginLibrary.WebpackModules.getByProps('avatar', 'cursorDefault', 'mask').avatar.split(/ /g)[0], botTag: ZeresPluginLibrary.WebpackModules.getByProps('botTagRegular').botTagRegular + ' ' + ZeresPluginLibrary.WebpackModules.getByProps('botTagCozy').botTagCozy, markupSingle: ZeresPluginLibrary.WebpackModules.getByProps('markup').markup.split(/ /g)[0] }; this.multiClasses = { defaultColor: ZeresPluginLibrary.WebpackModules.getByProps('defaultColor').defaultColor, item: ZeresPluginLibrary.WebpackModules.find(m => m.item && m.selected && m.topPill).item, tabBarItem: ZeresPluginLibrary.DiscordClassModules.UserModal.tabBarItem, tabBarContainer: ZeresPluginLibrary.DiscordClassModules.UserModal.tabBarContainer, zeres plugin library How to dowload it? zeres plugin library tabBar: ZeresPluginLibrary.DiscordClassModules.UserModal.tabBar, edited: ZeresPluginLibrary.WebpackModules.getByProps('edited').edited, markup: ZeresPluginLibrary.WebpackModules.getByProps('markup')['markup'], message: { cozy: { containerBounded: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').containerCozyBounded, header: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').headerCozy, avatar: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').avatar, headerMeta: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').headerCozyMeta, username: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').username, zeres plugin library PasteShr zeres plugin library timestamp: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').timestampCozy, content: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').contentCozy } } }; this.classes = { markup: ZeresPluginLibrary.WebpackModules.getByProps('markup')['markup'].split(/ /g)[0], content: ZeresPluginLibrary.WebpackModules.getByProps('contentCozy')['content'].split(/ /g)[0], hidden: ZeresPluginLibrary.WebpackModules.getByProps('spoilerText', 'hidden').hidden.split(/ /g)[0], zeres plugin library How to use it? zeres plugin library chat: ZeresPluginLibrary.WebpackModules.getByProps('chat').chat.split(/ /g)[0], messages: `.${ZLibrary.WebpackModules.getByProps('container', 'containerCompactBounded').container.split(/ /g)[0]} > div:not(.${ZeresPluginLibrary.WebpackModules.getByProps('content', 'marginCompactIndent').content.split(/ /g)[0]})`, tabBar: ZeresPluginLibrary.DiscordClassModules.UserModal.tabBar.split(/ /g)[0], containerBounded: ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').containerCozyBounded, messagesWrapper: ZeresPluginLibrary.WebpackModules.getByProps('messagesWrapper').messagesWrapper.split(/ /g)[0] }; this.muteModule = ZeresPluginLibrary.WebpackModules.find(m => m.isMuted); this.menu = {}; zeres plugin library How to get it? zeres plugin library this.menu.classes = {}; this.menu.filter = ''; this.menu.open = false; this.createTextBox.classes = { inputWrapper: ZeresPluginLibrary.WebpackModules.getByProps('inputWrapper').inputWrapper, inputMultiInput: ZeresPluginLibrary.WebpackModules.getByProps('input').input + ' ' + ZeresPluginLibrary.WebpackModules.getByProps('multiInput').multiInput, multiInputFirst: ZeresPluginLibrary.WebpackModules.getByProps('multiInputFirst').multiInputFirst, inputDefaultMultiInputField: ZeresPluginLibrary.WebpackModules.getByProps('inputDefault').inputDefault + ' ' + ZeresPluginLibrary.WebpackModules.getByProps('multiInputField').multiInputField, questionMark: ZeresPluginLibrary.WebpackModules.getByProps('questionMark').questionMark, zeres plugin library PasteShr zeres plugin library icon: ZeresPluginLibrary.WebpackModules.getByProps('questionMark').icon, focused: ZeresPluginLibrary.WebpackModules.getByProps('focused').focused.split(/ /g), questionMarkSingle: ZeresPluginLibrary.WebpackModules.getByProps('questionMark').questionMark.split(/ /g)[0] }; this.createHeader.classes = { itemTabBarItem: ZeresPluginLibrary.DiscordClassModules.UserModal.tabBarItem + ' ' + ZeresPluginLibrary.WebpackModules.find(m => m.item && m.selected && m.topPill).item, tabBarContainer: ZeresPluginLibrary.DiscordClassModules.UserModal.tabBarContainer, tabBar: ZeresPluginLibrary.DiscordClassModules.UserModal.tabBar, tabBarSingle: ZeresPluginLibrary.DiscordClassModules.UserModal.tabBar.split(/ /g)[0] zeres plugin library How to dowload it? zeres plugin library }; this.createModal.imageModal = ZeresPluginLibrary.WebpackModules.getByDisplayName('ImageModal'); this.createModal.confirmationModal = ZeresPluginLibrary.DiscordModules.ConfirmationModal; this.observer.chatClass = ZeresPluginLibrary.WebpackModules.getByProps('chat').chat.split(/ /g)[0]; this.observer.containerCozyClass = ZeresPluginLibrary.WebpackModules.getByProps('containerCozyBounded').containerCozyBounded.split(/ /g)[0]; this.localUser = ZeresPluginLibrary.DiscordModules.UserStore.getCurrentUser(); zeres plugin library PasteShr zeres plugin library this.deletedChatMessagesCount = {}; this.editedChatMessagesCount = {}; this.channelMessages = ZeresPluginLibrary.WebpackModules.find(m => m._channelMessages)._channelMessages; this.autoBackupSaveInterupts = 0; this.unpatches = []; this.unpatches.push(ZeresPluginLibrary.Patcher.instead(this.getName(), ZeresPluginLibrary.WebpackModules.find(m => m.dispatch), 'dispatch', (_, args, original) => this.onDispatchEvent(args, original))); zeres plugin library How to use it? zeres plugin library this.unpatches.push( ZeresPluginLibrary.Patcher.instead(this.getName(), ZeresPluginLibrary.DiscordModules.MessageActions, 'startEditMessage', (_, args, original) => { const channelId = args[0]; const messageId = args[1]; if (!this.editedMessageRecord[channelId] || this.editedMessageRecord[channelId].findIndex(m => m === messageId) == -1) return original(...args); let record = this.getSavedMessage(messageId); if (!record) return original(...args); args[2] = record.message.content; return original(...args); }) zeres plugin library How to get it for free? zeres plugin library ); // todo: maybe do it in dispatch? or use 'instead' this.unpatches.push( ZeresPluginLibrary.Patcher.after(this.getName(), ZeresPluginLibrary.DiscordModules.MessageActions, 'endEditMessage', (_, args, __) => { if (!args.length) setTimeout(() => this.updateMessages(), 0); // settimeout so it can do it after it was restored }) ); this.style = {}; zeres plugin library How to get it for free? zeres plugin library this.style.deleted = this.obfuscatedClass('ml2-deleted'); this.style.edited = this.obfuscatedClass('ml2-edited'); this.style.markupCompact = this.obfuscatedClass('ml2-markup-compact'); this.style.editedCompact = this.obfuscatedClass('ml2-edited-compact'); this.style.tab = this.obfuscatedClass('ml2-tab'); this.style.tabSelected = this.obfuscatedClass('ml2-tab-selected'); this.style.textIndent = this.obfuscatedClass('ml2-help-text-indent'); this.style.menu = this.obfuscatedClass('ML2-MENU'); this.style.openLogs = this.obfuscatedClass('ML2-OL'); zeres plugin library How to get it for free? zeres plugin library this.style.filter = this.obfuscatedClass('ML2-FILTER'); this.style.menuMessages = this.obfuscatedClass('ML2-MENU-MESSAGES'); this.style.menuTabBar = this.obfuscatedClass('ML2-MENU-TABBAR'); this.invalidateAllChannelCache(); this.selectedChannel = this.getSelectedTextChannel(); if (this.selectedChannel) { this.cacheChannelMessages(this.selectedChannel.id); /* setTimeout(() => */ this.updateMessages(); /* , 20); */ // why is this in a settimeout? TODO find out } zeres plugin library How to dowload it? zeres plugin library // todo: custom deleted message text color ZeresPluginLibrary.PluginUtilities.addStyle( (this.style.css = !this.settings.obfuscateCSSClasses ? 'ML2-CSS' : this.randomString()), ` html > head + body #app-mount * .bda-links [href*="MessageLogger"]:after{ display: none !important; } .da-container .da-markup, .da-container .${this.classes.markup} { /* transition: color 0.3s; */ zeres plugin library PasteShr zeres plugin library } .${this.style.deleted} .${this.classes.markup}, .${this.style.deleted} .${this.classes.markup} .hljs{ color: #f04747 !important; } .theme-dark .${this.classes.markup}.${this.style.edited} .${this.style.edited} { filter: brightness(70%); } .theme-light .${this.classes.markup}.${this.style.edited} .${this.style.edited} { opacity: 0.5; } zeres plugin library PasteShr zeres plugin library div > .${ZLibrary.WebpackModules.getByProps('buttonContainer', 'asianCompactTimeStamp') .buttonContainer.split(' ') .join('.')} { z-index: 9999999; } .${this.style.markupCompact} { display: grid; } .${this.style.editedCompact} { zeres plugin library How to use it? zeres plugin library grid-column: 1; grid-row: 1; } .theme-dark .${this.style.deleted}:not(:hover) .${this.classes.content} img, .${this.style.deleted}:not(:hover) .mention, .${this.style.deleted}:not(:hover) .reactions, .${this.style.deleted}:not(:hover) .${this.classes.content} a { filter: grayscale(100%) !important; } .${this.style.deleted} .${this.classes.content} img, .${this.style.deleted} .mention, .${this.style.deleted} .reactions, .${this.style.deleted} .${this.classes.content} a { transition: filter 0.3s !important; zeres plugin library PasteShr zeres plugin library } .theme-dark .${this.style.tab} { border-color: transparent; color: rgba(255, 255, 255, 0.4); } .theme-light .${this.style.tab} { border-color: transparent; color: rgba(0, 0, 0, 0.4); } zeres plugin library How to get it for free? zeres plugin library .theme-dark .${this.style.tabSelected} { border-color: rgb(255, 255, 255); color: rgb(255, 255, 255); } .theme-light .${this.style.tabSelected} { border-color: rgb(0, 0, 0); color: rgb(0, 0, 0); } zeres plugin library PasteShr zeres plugin library .${this.style.textIndent} { margin-left: 40px; } ` ); this.patchModal(); const createKeybindListener = () => { this.keybindListener = new (ZeresPluginLibrary.WebpackModules.getModule(m => typeof m === 'function' && m.toString().includes('.default.setOnInputEventCallback')))(); this.keybindListener.on('change', e => { zeres plugin library How to get it? zeres plugin library if (this.settings.disableKeybind) return; // todo: destroy if disableKeybind is set to true and don't make one if it was true from the start // this is the hackiest thing ever but it works xdd if (!ZeresPluginLibrary.WebpackModules.getByProps('isFocused').isFocused() || document.getElementsByClassName('bda-slist').length) return; const isKeyBind = keybind => { if (e.combo.length != keybind.length) return false; // console.log(e.combo); for (let i = 0; i < e.combo.length; i++) { if (e.combo[i][1] != keybind[i]) { return false; } zeres plugin library How to get it for free? zeres plugin library } return true; }; const close = () => { this.menu.filter = ''; this.menu.open = false; ZeresPluginLibrary.DiscordModules.ModalStack.popWithKey(this.style.menu); }; if (isKeyBind(this.settings.openLogKeybind)) { if (this.menu.open) return close(); zeres plugin library How to get it? zeres plugin library return this.openWindow(); } if (isKeyBind(this.settings.openLogFilteredKeybind)) { if (this.menu.open) return close(); if (!this.selectedChannel) { this.showToast('No channel selected', { type: 'error' }); return this.openWindow(); } this.menu.filter = `channel:${this.selectedChannel.id}`; this.openWindow(); zeres plugin library How to dowload it? zeres plugin library } }); }; this.powerMonitor = ZeresPluginLibrary.WebpackModules.getByProps('remotePowerMonitor').remotePowerMonitor; const refreshKeykindListener = () => { this.keybindListener.destroy(); createKeybindListener(); }; zeres plugin library How to use it? zeres plugin library this.keybindListenerInterval = setInterval(() => refreshKeykindListener(), 30 * 1000 * 60); // 10 minutes createKeybindListener(); this.powerMonitor.on( 'resume', (this.powerMonitorResumeListener = () => { setTimeout(() => refreshKeykindListener(), 1000); }) zeres plugin library PasteShr zeres plugin library ); this.unpatches.push( ZeresPluginLibrary.Patcher.instead(this.getName(), ZeresPluginLibrary.WebpackModules.getByDisplayName('TextAreaAutosize').prototype, 'focus', (thisObj, args, original) => { if (this.menu.open) return; return original(...args); }) ); this.unpatches.push( zeres plugin library How to dowload it? zeres plugin library ZeresPluginLibrary.Patcher.instead(this.getName(), ZeresPluginLibrary.WebpackModules.getByDisplayName('LazyImage').prototype, 'getSrc', (thisObj, args, original) => { let indx; if (((indx = thisObj.props.src.indexOf('?ML2=true')), indx !== -1)) return thisObj.props.src.substr(0, indx); return original(...args); }) ); this.dataManagerInterval = setInterval(() => { this.handleMessagesCap(); }, 60 * 1000 * 5); // every 5 minutes, no need to spam it, could be intensive zeres plugin library PasteShr zeres plugin library const ChannelContextMenu = ZeresPluginLibrary.WebpackModules.getByDisplayName('ChannelContextMenu'); const GuildContextMenu = ZeresPluginLibrary.WebpackModules.getByDisplayName('GuildContextMenu'); const MessageContextMenu = ZeresPluginLibrary.WebpackModules.getByDisplayName('MessageContextMenu'); const NativeLinkGroup = ZeresPluginLibrary.WebpackModules.getByDisplayName('NativeLinkGroup'); const UserContextMenu = ZeresPluginLibrary.WebpackModules.getByDisplayName('UserContextMenu'); this.ContextMenuItem = ZeresPluginLibrary.DiscordModules.ContextMenuItem; this.ContextMenuActions = ZeresPluginLibrary.DiscordModules.ContextMenuActions; this.ContextMenuGroup = ZeresPluginLibrary.DiscordModules.ContextMenuItemsGroup; zeres plugin library How to use it? zeres plugin library this.SubMenuItem = ZeresPluginLibrary.WebpackModules.find(m => m.default && m.default.displayName && m.default.displayName.includes('SubMenuItem')).default; const patchContexts = menu => { this.unpatches.push(ZeresPluginLibrary.Patcher.after(this.getName(), menu.prototype, 'render', (thisObj, args, returnValue) => this.handleContextMenu(thisObj, args, returnValue))); }; for (let menu of [ChannelContextMenu, GuildContextMenu, MessageContextMenu, NativeLinkGroup, UserContextMenu]) patchContexts(menu); this.menu.randomValidChannel = (() => { const channels = ZeresPluginLibrary.DiscordModules.ChannelStore.getChannels(); zeres plugin library How to use it? zeres plugin library var keys = Object.keys(channels); return channels[keys[(keys.length * Math.random()) << 0]]; })(); this.menu.userRequestQueue = []; this.menu.deleteKeyDown = false; document.addEventListener( 'keydown', (this.keydownListener = e => { zeres plugin library How to use it? zeres plugin library if (e.repeat) return; if (e.keyCode === 46) this.menu.deleteKeyDown = true; }) ); document.addEventListener( 'keyup', (this.keyupListener = e => { if (e.repeat) return; if (e.keyCode === 46) this.menu.deleteKeyDown = false; }) zeres plugin library How to use it? zeres plugin library ); this.menu.shownMessages = -1; const iconShit = ZeresPluginLibrary.WebpackModules.getByProps('container', 'children', 'toolbar', 'iconWrapper'); // Icon by font awesome // https://fontawesome.com/license this.channelLogButton = this.parseHTML(`
zeres plugin library How to get it for free? zeres plugin library
`); this.channelLogButton.addEventListener('click', () => { this.openWindow(); }); this.channelLogButton.addEventListener('contextmenu', () => { if (!this.selectedChannel) return; this.menu.filter = `channel:${this.selectedChannel.id}`; this.openWindow(); }); new ZeresPluginLibrary.EmulatedTooltip(this.channelLogButton, 'Open Logs', { side: 'bottom' }); zeres plugin library How to get it? zeres plugin library if (this.settings.showOpenLogsButton) this.addOpenLogsButton(); this.unpatches.push( ZeresPluginLibrary.Patcher.instead(this.getName(), ZeresPluginLibrary.DiscordModules.MessageActions, 'deleteMessage', (thisObj, args, original) => { this.localDeletes.push(args[1]); if (this.localDeletes.length > 10) this.localDeletes.shift(); return original(...args); }) ); zeres plugin library How to use it? zeres plugin library this.selfTestInterval = setInterval(() => { this.selfTestTimeout = setTimeout(() => { if (this.selfTestFailures > 4) { clearInterval(this.selfTestInterval); this.selfTestInterval = 0; return BdApi.alert(`${this.getName()}: internal error.`, `Self test failure: Failed to hook dispatch. Recommended to reload your discord (CTRL + R) as the plugin may be in a broken state! If you still see this error, open up the devtools console (CTRL + SHIFT + I, click console tab) and report the errors to ${this.getAuthor()} for further assistance.`); } ZeresPluginLibrary.Logger.warn(this.getName(), 'Dispatch is not hooked, all our hooks may be invalid, attempting to reload self'); this.selfTestFailures++; zeres plugin library How to use it? zeres plugin library this.stop(); this.start(); }, 3000); ZeresPluginLibrary.WebpackModules.find(m => m.dispatch).dispatch({ type: 'MESSAGE_LOGGER_V2_SELF_TEST' }); }, 10000); if (this.selfTestInited) return; this.selfTestFailures = 0; zeres plugin library How to get it? zeres plugin library this.selfTestInited = true; } shutdown() { const tryUnpatch = fn => { try { // things can bug out, best to reload tbh, should maybe warn the user? fn(); } catch (e) { ZeresPluginLibrary.Logger.stacktrace(this.getName(), 'Error unpatching', e); } zeres plugin library How to get it for free? zeres plugin library }; for (let unpatch of this.unpatches) tryUnpatch(unpatch); if (this.MessageContextMenuPatch) tryUnpatch(this.MessageContextMenuPatch); if (this.ChannelContextMenuPatch) tryUnpatch(this.ChannelContextMenuPatch); if (this.GuildContextMenuPatch) tryUnpatch(this.GuildContextMenuPatch); if (this.keybindListener) this.keybindListener.destroy(); if (this.style && this.style.css) ZeresPluginLibrary.PluginUtilities.removeStyle(this.style.css); if (this.dataManagerInterval) clearInterval(this.dataManagerInterval); if (this.keybindListenerInterval) clearInterval(this.keybindListenerInterval); if (this.selfTestInterval) clearInterval(this.selfTestInterval); zeres plugin library How to dowload it? zeres plugin library if (this.selfTestTimeout) clearTimeout(this.selfTestTimeout); if (this.keydownListener) document.removeEventListener('keydown', this.keydownListener); if (this.keyupListener) document.removeEventListener('keyup', this.keyupListener); if (this.powerMonitor) this.powerMonitor.removeListener('resume', this.powerMonitorResumeListener); if (this.channelLogButton) this.channelLogButton.remove(); // console.log('invalidating cache'); this.invalidateAllChannelCache(); // if (this.selectedChannel) this.cacheChannelMessages(this.selectedChannel.id); // bad idea? } observer({ addedNodes }) { zeres plugin library PasteShr zeres plugin library // from NoDeleteMessages by Mega_Mewthree (original), ShiiroSan (edit logging) let isChat = false; for (const change of addedNodes) { if ((isChat = typeof change.className === 'string' && change.className.indexOf(this.observer.chatClass) != -1) || (change.style && change.style.cssText === 'border-radius: 2px; background-color: rgba(114, 137, 218, 0);') || (typeof change.className === 'string' && change.className.indexOf(this.observer.containerCozyClass) !== -1)) { try { if (isChat) this.selectedChannel = this.getSelectedTextChannel(); if (!this.selectedChannel) return ZeresPluginLibrary.Logger.warn(this.getName(), 'Chat was loaded but no text channel is selected'); if (isChat && this.settings.showOpenLogsButton) { const srch = change.querySelector('div[class*="search-"]'); srch.parentElement.insertBefore(this.channelLogButton, srch); zeres plugin library How to use it? zeres plugin library } this.updateMessages(); const showStuff = (map, name) => { if (map[this.selectedChannel.id] && map[this.selectedChannel.id]) { this.showToast(`There are ${map[this.selectedChannel.id]} new ${name} messages in ${this.selectedChannel.name ? '#' + this.selectedChannel.name : 'DM'}`, { type: 'info', onClick: () => this.openWindow(name), timeout: 3000 }); map[this.selectedChannel.id] = 0; zeres plugin library How to dowload it? zeres plugin library } }; if (this.settings.showDeletedCount) showStuff(this.deletedChatMessagesCount, 'deleted'); if (this.settings.showEditedCount) showStuff(this.editedChatMessagesCount, 'edited'); } catch (e) { ZeresPluginLibrary.Logger.stacktrace(this.getName(), 'Error in observer', e); } break; } } zeres plugin library How to use it? zeres plugin library } buildSetting(data) { // compied from ZLib actually const { name, note, type, value, onChange, id } = data; let setting = null; if (type == 'color') { setting = new ZeresPluginLibrary.Settings.ColorPicker(name, note, value, onChange, { disabled: data.disabled }); // DOESN'T WORK, REEEEEEEEEE } else if (type == 'dropdown') { setting = new ZeresPluginLibrary.Settings.Dropdown(name, note, value, data.options, onChange); } else if (type == 'file') { zeres plugin library PasteShr zeres plugin library setting = new ZeresPluginLibrary.Settings.FilePicker(name, note, onChange); } else if (type == 'keybind') { setting = new ZeresPluginLibrary.Settings.Keybind(name, note, value, onChange); } else if (type == 'radio') { setting = new ZeresPluginLibrary.Settings.RadioGroup(name, note, value, data.options, onChange, { disabled: data.disabled }); } else if (type == 'slider') { const options = {}; if (typeof data.markers != 'undefined') options.markers = data.markers; if (typeof data.stickToMarkers != 'undefined') options.stickToMarkers = data.stickToMarkers; setting = new ZeresPluginLibrary.Settings.Slider(name, note, data.min, data.max, value, onChange, options); zeres plugin library How to get it? zeres plugin library } else if (type == 'switch') { setting = new ZeresPluginLibrary.Settings.Switch(name, note, value, onChange, { disabled: data.disabled }); } else if (type == 'textbox') { setting = new ZeresPluginLibrary.Settings.Textbox(name, note, value, onChange, { placeholder: data.placeholder || '' }); } if (id) setting.getElement().id = this.obfuscatedClass(id); return setting; } createSetting(data) { const current = Object.assign({}, data); zeres plugin library PasteShr zeres plugin library if (!current.onChange) { current.onChange = value => { this.settings[current.id] = value; if (current.callback) current.callback(value); }; } if (typeof current.value === 'undefined') current.value = this.settings[current.id]; return this.buildSetting(current); } createGroup(group) { zeres plugin library PasteShr zeres plugin library const { name, id, collapsible, shown, settings } = group; const list = []; for (let s = 0; s < settings.length; s++) list.push(this.createSetting(settings[s])); const settingGroup = new ZeresPluginLibrary.Settings.SettingGroup(name, { shown, collapsible }).append(...list); settingGroup.group.id = id; // should generate the id in here instead? return settingGroup; } getSettingsPanel() { zeres plugin library How to get it? zeres plugin library // todo, sort out the menu const list = []; list.push( this.createGroup({ name: 'Keybinds', id: this.obfuscatedClass('ml2-settings-keybinds'), collapsible: true, shown: false, settings: [ { zeres plugin library How to dowload it? zeres plugin library name: 'Open menu keybind', id: 'openLogKeybind', type: 'keybind' }, { name: 'Open log filtered by selected channel', id: 'openLogFilteredKeybind', type: 'keybind' }, { zeres plugin library How to dowload it? zeres plugin library name: 'Disable keybinds', id: 'disableKeybind', type: 'switch' } ] }) ); list.push( this.createGroup({ name: 'Ignores and overrides', zeres plugin library How to get it? zeres plugin library id: this.obfuscatedClass('ml2-settings-ignores-overrides'), collapsible: true, shown: false, settings: [ { name: 'Ignore muted servers', id: 'ignoreMutedGuilds', type: 'switch' }, { zeres plugin library How to use it? zeres plugin library name: 'Ignore muted channels', id: 'ignoreMutedChannels', type: 'switch' }, { name: 'Ignore bots', id: 'ignoreBots', type: 'switch' }, { zeres plugin library How to use it? zeres plugin library name: 'Ignore messages posted by you', id: 'ignoreSelf', type: 'switch' }, { name: 'Ignore message edits from you', id: 'ignoreLocalEdits', type: 'switch' }, { zeres plugin library How to use it? zeres plugin library name: 'Ignore message deletes from you', note: 'Only ignores if you delete your own message.', id: 'ignoreLocalDeletes', type: 'switch' }, { name: 'Ignore blocked users', id: 'ignoreBlockedUsers', type: 'switch' }, zeres plugin library How to dowload it? zeres plugin library { name: 'Ignore NSFW channels', id: 'ignoreNSFW', type: 'switch' }, { name: 'Only log whitelist', id: 'onlyLogWhitelist', type: 'switch' }, zeres plugin library How to get it for free? zeres plugin library { name: 'Always log selected channel, regardless of whitelist/blacklist', id: 'alwaysLogSelected', type: 'switch' }, { name: 'Always log DMs, regardless of whitelist/blacklist', id: 'alwaysLogDM', type: 'switch' }, zeres plugin library How to get it for free? zeres plugin library { name: 'Always log ghost pings, regardless of whitelist/blacklist', note: 'Messages sent in ignored/muted/blacklisted servers and channels will be logged and shown in sent, but only gets saved if a ghost ping occurs.', id: 'alwaysLogGhostPings', type: 'switch' } ] }) ); list.push( zeres plugin library How to dowload it? zeres plugin library this.createGroup({ name: 'Display settings', id: this.obfuscatedClass('ml2-settings-display'), collapsible: true, shown: false, settings: [ { name: 'Display dates with timestamps', id: 'displayDates', type: 'switch', zeres plugin library How to dowload it? zeres plugin library callback: () => { if (this.selectedChannel) { // change NOW this.invalidateAllChannelCache(); this.cacheChannelMessages(this.selectedChannel.id); } } }, { name: 'Display deleted messages in chat', zeres plugin library How to get it? zeres plugin library id: 'showDeletedMessages', type: 'switch', callback: () => { this.invalidateAllChannelCache(); if (this.selectedChannel) this.cacheChannelMessages(this.selectedChannel.id); } }, { name: 'Display edited messages in chat', id: 'showEditedMessages', zeres plugin library How to get it for free? zeres plugin library type: 'switch' }, { name: 'Max number of shown edits', id: 'maxShownEdits', type: 'textbox', onChange: val => { if (isNaN(val)) return this.showToast('Value must be a number!', { type: 'error' }); this.settings.maxShownEdits = parseInt(val); } zeres plugin library PasteShr zeres plugin library }, { name: 'Show oldest edit instead of newest if over the shown edits limit', id: 'hideNewerEditsFirst', type: 'switch' }, { name: 'Display purged messages in chat', id: 'showPurgedMessages', type: 'switch', zeres plugin library How to get it? zeres plugin library callback: () => { this.invalidateAllChannelCache(); if (this.selectedChannel) this.cacheChannelMessages(this.selectedChannel.id); } }, { name: 'Restore deleted messages after reload', id: 'restoreDeletedMessages', type: 'switch', callback: val => { zeres plugin library How to dowload it? zeres plugin library if (val) { this.invalidateAllChannelCache(); if (this.selectedChannel) this.cacheChannelMessages(this.selectedChannel.id); } } }, { name: 'Show amount of new deleted messages when entering a channel', id: 'showDeletedCount', type: 'switch' zeres plugin library How to use it? zeres plugin library }, { name: 'Show amount of new edited messages when entering a channel', id: 'showEditedCount', type: 'switch' }, { name: 'Display update notes', id: 'displayUpdateNotes', type: 'switch' zeres plugin library How to get it for free? zeres plugin library }, { name: 'Menu sort direction', id: 'reverseOrder', type: 'radio', options: [ { name: 'New - old', value: false }, zeres plugin library How to dowload it? zeres plugin library { name: 'Old - new', value: true } ] } ] }) ); list.push( zeres plugin library How to use it? zeres plugin library this.createGroup({ name: 'Misc settings', id: this.obfuscatedClass('ml2-settings-misc'), collapsible: true, shown: false, settings: [ { name: 'Disable saving data. Logged messages are erased after reload/restart. Disables auto backup.', id: 'dontSaveData', type: 'switch', zeres plugin library How to use it? zeres plugin library callback: val => { if (!val) this.saveData(); if (!val && this.settings.autoBackup) this.saveBackup(); } }, { name: "Auto backup data (won't fully prevent losing data, just prevent total data loss)", id: 'autoBackup', type: 'switch', callback: val => { zeres plugin library How to use it? zeres plugin library if (val && !this.settings.dontSaveData) this.saveBackup(); } } /* { // no time, TODO! name: 'Deleted messages color', id: 'deletedMessageColor', type: 'color' }, */, { zeres plugin library How to use it? zeres plugin library name: 'Aggresive message caching (makes sure we have the data of any deleted or edited messages)', id: 'aggresiveMessageCaching', type: 'switch' }, { name: 'Cache all images by storing them locally in the MLV2_IMAGE_CACHE folder inside the plugins folder', id: 'cacheAllImages', type: 'switch' }, { zeres plugin library How to get it? zeres plugin library name: "Don't delete cached images", note: "If the message the image is from is erased from data, the cached image will be kept. You'll have to monitor disk usage on your own!", id: 'dontDeleteCachedImages', type: 'switch' }, { name: 'Display open logs button next to the search box top right in channels', id: 'showOpenLogsButton', type: 'switch', callback: val => { zeres plugin library How to use it? zeres plugin library if (val) return this.addOpenLogsButton(); this.removeOpenLogsButton(); } }, { name: 'Block spam edit notifications (if enabled)', id: 'blockSpamEdit', type: 'switch' } ] zeres plugin library How to get it for free? zeres plugin library }) ); list.push( this.createGroup({ name: 'Toast notifications for guilds', id: this.obfuscatedClass('ml2-settings-toast-guilds'), collapsible: true, shown: false, settings: [ { zeres plugin library How to get it for free? zeres plugin library name: 'Message sent', id: 'sent', type: 'switch', value: this.settings.toastToggles.sent, onChange: val => { this.settings.toastToggles.sent = val; } }, { name: 'Message edited', zeres plugin library How to get it? zeres plugin library id: 'edited', type: 'switch', value: this.settings.toastToggles.edited, onChange: val => { this.settings.toastToggles.edited = val; } }, { name: 'Message deleted', id: 'deleted', zeres plugin library How to use it? zeres plugin library type: 'switch', value: this.settings.toastToggles.deleted, onChange: val => { this.settings.toastToggles.deleted = val; } }, { name: 'Ghost pings', id: 'ghostPings', type: 'switch', zeres plugin library How to use it? zeres plugin library value: this.settings.toastToggles.ghostPings, onChange: val => { this.settings.toastToggles.ghostPings = val; } }, { name: 'Disable toasts for local user (yourself)', id: 'disableToastsForLocal', type: 'switch', value: this.settings.toastToggles.disableToastsForLocal, zeres plugin library PasteShr zeres plugin library onChange: val => { this.settings.toastToggles.disableToastsForLocal = val; } } ] }) ); list.push( this.createGroup({ zeres plugin library How to get it for free? zeres plugin library name: 'Toast notifications for DMs', id: this.obfuscatedClass('ml2-settings-toast-dms'), collapsible: true, shown: false, settings: [ { name: 'Message sent', id: 'sent', type: 'switch', value: this.settings.toastTogglesDMs.sent, zeres plugin library How to dowload it? zeres plugin library onChange: val => { this.settings.toastTogglesDMs.sent = val; } }, { name: 'Message edited', id: 'edited', type: 'switch', value: this.settings.toastTogglesDMs.edited, onChange: val => { zeres plugin library How to get it for free? zeres plugin library this.settings.toastTogglesDMs.edited = val; } }, { name: 'Message deleted', id: 'deleted', type: 'switch', value: this.settings.toastTogglesDMs.deleted, onChange: val => { this.settings.toastTogglesDMs.deleted = val; zeres plugin library How to get it for free? zeres plugin library } }, { name: 'Ghost pings', id: 'ghostPings', type: 'switch', value: this.settings.toastTogglesDMs.ghostPings, onChange: val => { this.settings.toastTogglesDMs.ghostPings = val; } zeres plugin library PasteShr zeres plugin library } ] }) ); list.push( this.createGroup({ name: 'Message caps', id: this.obfuscatedClass('ml2-settings-caps'), collapsible: true, zeres plugin library How to get it for free? zeres plugin library shown: false, settings: [ { name: 'Cached messages cap', note: 'Max number of sent messages logger should keep track of', id: 'messageCacheCap', type: 'textbox', onChange: val => { if (isNaN(val)) return this.showToast('Value must be a number!', { type: 'error' }); this.settings.messageCacheCap = parseInt(val); zeres plugin library How to use it? zeres plugin library clearInterval(this.dataManagerInterval); this.dataManagerInterval = setInterval(() => { this.handleMessagesCap(); }, 60 * 1000 * 5); } }, { name: 'Saved messages cap', note: "Max number of messages saved to disk, this limit is for deleted, edited and purged INDIVIDUALLY. So if you have it set to 1000, it'll be 1000 edits, 1000 deletes and 1000 purged messages max", id: 'savedMessagesCap', zeres plugin library How to get it? zeres plugin library type: 'textbox', onChange: val => { if (isNaN(val)) return this.showToast('Value must be a number!', { type: 'error' }); this.settings.savedMessagesCap = parseInt(val); clearInterval(this.dataManagerInterval); this.dataManagerInterval = setInterval(() => { this.handleMessagesCap(); }, 60 * 1000 * 5); } }, zeres plugin library PasteShr zeres plugin library { name: 'Menu message render cap', note: 'How many messages will show before the LOAD MORE button will show', id: 'renderCap', type: 'textbox', onChange: val => { if (isNaN(val)) return this.showToast('Value must be a number!', { type: 'error' }); this.settings.renderCap = parseInt(val); clearInterval(this.dataManagerInterval); } zeres plugin library How to dowload it? zeres plugin library } ] }) ); list.push( this.createGroup({ name: 'Advanced', id: this.obfuscatedClass('ml2-settings-advanced'), collapsible: true, zeres plugin library How to dowload it? zeres plugin library shown: false, settings: [ { name: 'Obfuscate CSS classes', note: 'Enable this if some plugin, library or theme is blocking you from using the plugin', id: 'obfuscateCSSClasses', type: 'switch' } ] }) zeres plugin library How to get it? zeres plugin library ); const div = document.createElement('div'); div.id = this.obfuscatedClass('ml2-settings-buttonbox'); div.style.display = 'inline-flex'; div.appendChild(this.createButton('Changelog', () => ZeresPluginLibrary.Modals.showChangelogModal(this.getName() + ' Changelog', this.getVersion(), this.getChanges()))); div.appendChild(this.createButton('Stats', () => this.showStatsModal())); div.appendChild(this.createButton('Donate', () => this.nodeModules.electron.shell.openExternal('https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=DZUL9UZDDRLB8&source=url'))); div.appendChild(this.createButton('Help', () => this.showLoggerHelpModal())); let button = div.firstElementChild; zeres plugin library How to get it? zeres plugin library while (button) { button.style.marginRight = button.style.marginLeft = `5px`; button = button.nextElementSibling; } list.push(div); return ZeresPluginLibrary.Settings.SettingPanel.build(_ => this.saveSettings(), ...list); } /* ==================================================-|| START HELPERS ||-================================================== */ zeres plugin library PasteShr zeres plugin library saveSettings() { ZeresPluginLibrary.PluginUtilities.saveSettings(this.getName(), this.settings); } loadData(name, construct = {}) { try { return $.extend(true, construct, BdApi.getData(name, 'data')); // zeres library turns all arrays into objects.. for.. some reason? } catch (e) { return {}; // error handling not done here } } zeres plugin library PasteShr zeres plugin library handleDataSaving() { // saveData/setPluginData is synchronous, can get slow with bigger files ZeresPluginLibrary.PluginUtilities.saveData(this.getName() + 'Data', 'data', { messageRecord: this.messageRecord, deletedMessageRecord: this.deletedMessageRecord, editedMessageRecord: this.editedMessageRecord, purgedMessageRecord: this.purgedMessageRecord }); if (this.settings.autoBackup) { if (this.saveBackupTimeout) this.autoBackupSaveInterupts++; zeres plugin library How to use it? zeres plugin library if (this.autoBackupSaveInterupts < 4) { if (this.saveBackupTimeout) clearTimeout(this.saveBackupTimeout); // 10 seconds after, in case shits going down y'know, better not to spam save and corrupt it, don't become the thing you're trying to eliminate this.saveBackupTimeout = setTimeout(() => this.saveBackup(), 10 * 1000); } } this.requestedDataSave = 0; } saveData() { if (!this.settings.dontSaveData && !this.requestedDataSave) this.requestedDataSave = setTimeout(() => this.handleDataSaving(), 1000); // needs to be async zeres plugin library How to dowload it? zeres plugin library this.updateMessages(); } saveBackup() { this.saveBackupTimeout = 0; this.autoBackupSaveInterupts = 0; ZeresPluginLibrary.PluginUtilities.saveData(this.getName() + 'DataBackup', 'data', { messageRecord: this.messageRecord, deletedMessageRecord: this.deletedMessageRecord, editedMessageRecord: this.editedMessageRecord, purgedMessageRecord: this.purgedMessageRecord zeres plugin library How to dowload it? zeres plugin library }); if (!this.loadData(this.getName() + 'DataBackup', 'data').messageRecord) this.saveBackupTimeout = setTimeout(() => this.saveBackup, 300); // don't be taxing } parseHTML(html) { // TODO: drop this func, it's 75% slower than just making the elements manually var template = document.createElement('template'); html = html.trim(); // Never return a text node of whitespace as the result template.innerHTML = html; return template.content.firstChild; } zeres plugin library How to use it? zeres plugin library randomString() { let start = rand(); while (start[0].toUpperCase() == start[0].toLowerCase()) start = rand(); return start + '-' + rand(); function rand() { return Math.random() .toString(36) .substr(2, 7); } } zeres plugin library PasteShr zeres plugin library obfuscatedClass(selector) { if (this.settings.obfuscateCSSClasses) return this.randomString(); return selector; } createTimeStamp(from = undefined, forcedDate = false) { // todo: timestamp for edited tooltip let date; if (from) date = new Date(from); else date = new Date(); return this.settings.displayDates || forcedDate ? `${date.toLocaleTimeString()}, ${date.toLocaleDateString()}` : date.toLocaleTimeString(); zeres plugin library PasteShr zeres plugin library } getCachedMessage(id, channelId = 0) { let cached = this.cachedMessageRecord.find(m => m.id == id); if (cached) return cached; if (channelId) return this.tools.getMessage(channelId, id); // if the message isn't cached, it returns undefined return null; } getEditedMessage(messageId, channelId) { if (this.editedMessageRecord[channelId] && this.editedMessageRecord[channelId].findIndex(m => m === messageId) != -1) { return this.messageRecord[messageId]; zeres plugin library How to get it for free? zeres plugin library } return null; } getSavedMessage(id) { /* DEPRECATED */ return this.messageRecord[id]; } createMiniFormattedData(message) { message = $.extend(true, {}, message); let internalMessage = this.tools.getMessage(message.channel_id, message.id); zeres plugin library How to use it? zeres plugin library let reactions = internalMessage ? internalMessage.reactions : []; let guildId = null; /* let guild = null; */ /* const author = this.tools.getUser(message.author.id); */ const channel = this.tools.getChannel(message.channel_id); if (channel) guildId = channel.guild_id; /* if (guildId) guild = this.tools.getServer(guildId); */ const obj = { message: { author: { zeres plugin library How to dowload it? zeres plugin library discriminator: message.author.discriminator, username: message.author.username, avatar: message.author.avatar, id: message.author.id, bot: internalMessage && internalMessage.author && internalMessage.author.bot // TODO: is bot checking in menu }, /* channel_name: (channel && channel.name) || 'unknown-channel', guild_name: (guild && guild.name) || 'unknown-guild', */ mention_everyone: message.mention_everyone, edited_timestamp: message.edited_timestamp, zeres plugin library How to dowload it? zeres plugin library mention_roles: message.mention_roles, attachments: message.attachments, channel_id: message.channel_id, timestamp: message.timestamp, mentions: message.mentions, content: message.content, pinned: message.pinned, embeds: message.embeds, reactions: reactions, type: message.type, zeres plugin library How to get it for free? zeres plugin library guild_id: guildId, tts: message.tts, id: message.id }, local_mentioned: this.tools.isMentioned(message, this.localUser.id), /* ghost_pinged: false, */ delete_data: null /* { time: integer, rel_ids: [ string, zeres plugin library How to dowload it? zeres plugin library string, string ], hidden: bool } */, edit_history: null /* [ { content: string, timestamp: string } zeres plugin library How to get it for free? zeres plugin library ], edits_hidden: bool */ }; this.fixEmbeds(obj.message); return obj; } getSelectedTextChannel() { return ZeresPluginLibrary.DiscordModules.ChannelStore.getChannel(ZeresPluginLibrary.DiscordModules.SelectedChannelStore.getChannelId()); } invalidateAllChannelCache() { zeres plugin library How to dowload it? zeres plugin library for (let channelId in this.channelMessages) this.invalidateChannelCache(channelId); } invalidateChannelCache(channelId) { if (!this.channelMessages[channelId]) return; this.channelMessages[channelId].ready = false; } cacheChannelMessages(id, relative) { // TODO figure out if I can use this to get messages at a certain point this.tools.fetchMessages(id, null, null, 50, (relative && { messageId: relative, ML2: true }) || undefined); } zeres plugin library PasteShr zeres plugin library /* UNUSED */ cachenChannelMessagesRelative(channelId, messageId) { ZeresPluginLibrary.DiscordModules.APIModule.get({ url: ZeresPluginLibrary.DiscordModules.DiscordConstants.Endpoints.MESSAGES(channelId), query: { before: null, after: null, limit: 50, around: messageId } zeres plugin library How to get it? zeres plugin library }) .then(res => { if (res.status != 200) return; const results = res.body; const final = results.filter(x => this.cachedMessageRecord.findIndex(m => x.id === m.id) == -1); this.cachedMessageRecord.push(...final); }) .catch(err => { ZeresPluginLibrary.Logger.stacktrace(this.getName(), `Error caching messages from ${channelId} around ${messageId}`, err); }); zeres plugin library How to get it for free? zeres plugin library } formatMarkup(content, channelId) { const markup = document.createElement('div'); const parsed = this.tools.parse(content, true, channelId ? { channelId: channelId } : {}); // console.log(parsed); // error, this render doesn't work with tags // TODO: this parser and renderer sucks ZeresPluginLibrary.DiscordModules.ReactDOM.render(ZeresPluginLibrary.DiscordModules.React.createElement('div', { className: '' }, parsed), markup); zeres plugin library How to use it? zeres plugin library const hiddenClass = this.classes.hidden; const hidden = markup.getElementsByClassName(hiddenClass); for (let i = 0; i < hidden.length; i++) { hidden[i].classList.remove(hiddenClass); } return markup; } zeres plugin library PasteShr zeres plugin library ensureContainer() { if (document.querySelector('.toasts')) return; if (!this.ensureContainer.container) this.ensureContainer.container = '.' + ZeresPluginLibrary.WebpackModules.getByProps('content', 'guilds').content.split(/ /g)[0] + ' > div:last-child'; const container = document.querySelector(this.ensureContainer.container); const memberlist = container.querySelector(ZeresPluginLibrary['DiscordSelectors'].MemberList.membersWrap); const form = container ? container.querySelector('form') : null; const left = container ? container.getBoundingClientRect().left : 310; const right = memberlist ? memberlist.getBoundingClientRect().left : 0; const width = right ? right - container.getBoundingClientRect().left : container.offsetWidth; const bottom = form ? form.offsetHeight : 80; zeres plugin library PasteShr zeres plugin library const toastWrapper = document.createElement('div'); toastWrapper.classList.add('toasts'); toastWrapper.style.setProperty('left', left + 'px'); toastWrapper.style.setProperty('width', width + 'px'); toastWrapper.style.setProperty('bottom', bottom + 'px'); document.querySelector('#app-mount').appendChild(toastWrapper); } async showToast(content, options = {}) { // credits to Zere, copied from Zeres Plugin Library const { type = '', icon = '', timeout = 3000, onClick = () => {}, onContext = () => {} } = options; zeres plugin library PasteShr zeres plugin library this.ensureContainer(); const toast = ZeresPluginLibrary['DOMTools'].parseHTML(ZeresPluginLibrary.Toasts.buildToast(content, ZeresPluginLibrary.Toasts.parseType(type), icon)); toast.style.pointerEvents = 'auto'; document.querySelector('.toasts').appendChild(toast); const wait = () => { toast.classList.add('closing'); setTimeout(() => { toast.remove(); if (!document.querySelectorAll('.toasts .toast').length) document.querySelector('.toasts').remove(); }, 300); zeres plugin library How to get it? zeres plugin library }; const sto = setTimeout(wait, timeout); const toastClicked = () => { clearTimeout(sto); wait(); }; toast.addEventListener('auxclick', () => toastClicked()); toast.addEventListener('click', () => { toastClicked(); onClick(); zeres plugin library PasteShr zeres plugin library }); toast.addEventListener('contextmenu', () => { toastClicked(); onContext(); }); } clamp(val, min, max) { // this is so sad, can we hit Metalloriff? // his message logger added the func to Math obj and I didn't realize return Math.max(min, Math.min(val, max)); zeres plugin library How to use it? zeres plugin library } deleteEditedMessageFromRecord(id, editNum) { const record = this.messageRecord[id]; if (!record) return; record.edit_history.splice(editNum, 1); if (!record.edit_history.length) record.edit_history = null; else return this.saveData(); const channelId = record.message.channel_id; zeres plugin library How to get it for free? zeres plugin library const channelMessages = this.editedMessageRecord[channelId]; channelMessages.splice(channelMessages.findIndex(m => m === id), 1); if (this.deletedMessageRecord[channelId] && this.deletedMessageRecord[channelId].findIndex(m => m === id) != -1) return this.saveData(); if (this.purgedMessageRecord[channelId] && this.purgedMessageRecord[channelId].findIndex(m => m === id) != -1) return this.saveData(); delete this.messageRecord[id]; this.saveData(); } jumpToMessage(channelId, messageId, guildId) { if (this.menu.open) ZeresPluginLibrary.DiscordModules.ModalStack.popWithKey(this.style.menu); ZeresPluginLibrary.DiscordModules.NavigationUtils.transitionTo(`/channels/${guildId || '@me'}/${channelId}${messageId ? '/' + messageId : ''}`); zeres plugin library How to get it? zeres plugin library } isImage(url) { return /\.(jpe?g|png|gif|bmp)$/i.test(url); } fixEmbeds(message) { if (!this.fixEmbeds.hex2int) this.fixEmbeds.hex2int = ZeresPluginLibrary.WebpackModules.getByProps('hex2int').hex2int; for (let embed of message.embeds) { if (typeof embed.title !== 'string' || !embed.title.length) embed.rawTitle && embed.rawTitle.length ? (embed.title = embed.rawTitle) : delete embed.title; if (typeof embed.description !== 'string' || !embed.description.length) embed.rawDescription && embed.rawDescription.length ? (embed.description = embed.rawDescription) : delete embed.description; zeres plugin library How to dowload it? zeres plugin library if (typeof embed.color === 'string') embed.color = this.fixEmbeds.hex2int(embed.color); if (typeof embed.footer === 'object') embed.footer = { text: embed.footer.text, icon_url: embed.footer.iconURL, proxy_icon_url: embed.footer.iconProxyURL }; if (typeof embed.author === 'object') embed.author = { name: embed.author.name, zeres plugin library How to get it for free? zeres plugin library url: embed.author.url, icon_url: embed.author.iconURL, proxy_icon_url: embed.author.iconProxyURL }; if (embed.referenceId) embed.reference_id = embed.referenceId; if (embed.fields && embed.fields.length) { for (let field of embed.fields) { for (let b in field) { if (Array.isArray(field[b])) { let result = ''; zeres plugin library PasteShr zeres plugin library for (let c of field[b]) { if (typeof c === 'string') result += c; else if (c.props && c.props.text) result += c.props.text; else if (c.props && c.props.title && c.props.href) result += `[${c.props.title}](${c.props.href})`; } field[b] = result; } } } } zeres plugin library How to get it for free? zeres plugin library } } isCompact() { return ZeresPluginLibrary.DiscordAPI.UserSettings.displayCompact; // can't get a reference } /* ==================================================-|| END HELPERS ||-================================================== */ /* ==================================================-|| START MISC ||-================================================== */ addOpenLogsButton() { if (!this.selectedChannel) return; const parent = document.querySelector('div[class*="chat-"] div[class*="toolbar-"]'); zeres plugin library How to dowload it? zeres plugin library parent.insertBefore(this.channelLogButton, parent.querySelector('div[class*="search-"]')); } removeOpenLogsButton() { const button = document.getElementById(this.style.openLogs); button.remove(); } showLoggerHelpModal() { this.createModal({ confirmText: 'OK', header: 'Logger help', zeres plugin library How to get it? zeres plugin library size: ZeresPluginLibrary.Modals.ModalSizes.LARGE, children: [ ZeresPluginLibrary.ReactTools.createWrappedElement([ this.parseHTML( `
Menu:
DELETE + LEFT-CLICK:
Clicking on a message, deletes the message
zeres plugin library How to get it for free? zeres plugin library Clicking on an edit deletes that specific edit
Clicking on the timestamp deletes all messages in that message group

RIGHT-CLICK:
Right-clicking the timestamp opens up options for the entire message group

Toasts:
zeres plugin library How to use it? zeres plugin library Note: Little "notifications" in discord that tell you if a message was edited, deleted, purged etc are called Toasts!

LEFT-CLICK:
Opens menu with the relevant tab

RIGHT-CLICK:
Jumps to relevant message in the relevant channel

MIDDLE-CLICK/SCROLLWHEEL-CLICK:
zeres plugin library How to dowload it? zeres plugin library
Only dismisses/closes the Toast.

Open Logs button (top right next to search):
LEFT-CLICK:
Opens menu

zeres plugin library How to get it? zeres plugin library RIGHT-CLICK:
Opens filtered menu that only shows messages from selected channel

Whitelist/blacklist, ignores and overrides:
WHITELIST-ONLY:
All servers are ignored unless whitelisted
zeres plugin library PasteShr zeres plugin library Muted channels in whitelisted servers are ignored unless whitelisted or "Ignore muted channels" is disabled
All channels in whitelisted servers are logged unless blacklisted, or muted and "Ignore muted channels" is enabled

DEFAULT:
All servers are logged unless blacklisted or muted and "Ignore muted servers" is enabled
Muted channels are ignored unless whitelisted or "Ignore muted channels" is disabled
Muted servers are ignored unless whitelisted or "Ignore muted servers" is disabled
Whitelisted channels in muted or blacklisted servers are logged

zeres plugin library How to get it? zeres plugin library ALL:
Whitelisted channels in blacklisted servers are logged
Blacklisted channels in whitelisted servers are ignored
"Always log selected channel" overrides blacklist, whitelist-only mode, NSFW channel ignore, mute
"Always log DMs" overrides blacklist as well as whitelist-only mode
Channels marked NSFW and not whitelisted are ignored unless "Ignore NSFW channels" is disabled

Chat:
zeres plugin library How to get it? zeres plugin library
LEFT-CLICK:
Clicking the (Edited) text opens menu of specified message

RIGHT-CLICK:
Right-clicking an edit (darkened text) allows you to delete that edit, or hide edits
Right-clicking on a edited or deleted message gives you the option to hide the deleted message or hide or unhide edits.

zeres plugin library How to use it? zeres plugin library
` ) ]) ], red: false }); } showStatsModal() { const elements = []; zeres plugin library How to dowload it? zeres plugin library let totalMessages = Object.keys(this.messageRecord).length; let messageCounts = []; let spaceUsageMB = 0; let cachedImageCount = 0; let cachedImagesUsageMB = 0; let mostDeletesChannel = { num: 0, id: '' }; let mostEditsChannel = { num: 0, id: '' }; let deleteDataTemp = {}; let editDataTemp = {}; zeres plugin library How to get it for free? zeres plugin library for (const map of [this.deletedMessageRecord, this.editedMessageRecord, this.cachedMessageRecord]) { let messageCount = 0; if (!Array.isArray(map)) { for (const channelId in map) { if (!deleteDataTemp[channelId]) deleteDataTemp[channelId] = []; if (!editDataTemp[channelId]) editDataTemp[channelId] = []; for (const messageId of map[channelId]) { messageCount++; const record = this.messageRecord[messageId]; zeres plugin library How to get it? zeres plugin library if (!record) continue; // wtf? if (record.delete_data && deleteDataTemp[channelId].findIndex(m => m === messageId)) deleteDataTemp[channelId].push(messageId); if (record.edit_history && editDataTemp[channelId].findIndex(m => m === messageId)) editDataTemp[channelId].push(messageId); } } } for (const channelId in deleteDataTemp) if (deleteDataTemp[channelId].length > mostDeletesChannel.num) mostDeletesChannel = { num: deleteDataTemp[channelId].length, id: channelId }; for (const channelId in editDataTemp) if (editDataTemp[channelId].length > mostEditsChannel.num) mostEditsChannel = { num: editDataTemp[channelId].length, id: channelId }; messageCounts.push(messageCount); zeres plugin library PasteShr zeres plugin library } const addLine = (name, value) => { elements.push(this.parseHTML(`
${name}: ${value}

`)); }; addLine('Total messages', totalMessages); addLine('Deleted message count', messageCounts[0]); addLine('Edited message count', messageCounts[1]); addLine('Sent message count', this.cachedMessageRecord.length); let channel = this.tools.getChannel(mostDeletesChannel.id); zeres plugin library How to dowload it? zeres plugin library if (channel) addLine('Most deletes', mostDeletesChannel.num + ' ' + this.getLiteralName(channel.guild_id, channel.id)); if (channel) addLine('Most edits', mostEditsChannel.num + ' ' + this.getLiteralName(channel.guild_id, channel.id)); addLine('Data file size', (this.nodeModules.fs.statSync(this.pluginDir + '/MessageLoggerV2Data.config.json').size / 1024 / 1024).toFixed(2) + 'MB'); addLine('Data file size severity', this.slowSaveModeStep == 0 ? 'OK' : this.slowSaveModeStep == 1 ? 'MILD' : this.slowSaveModeStep == 2 ? 'BAD' : 'EXTREME'); this.createModal({ confirmText: 'OK', header: 'Data stats', size: ZeresPluginLibrary.Modals.ModalSizes.SMALL, children: [ZeresPluginLibrary.ReactTools.createWrappedElement(elements)], zeres plugin library PasteShr zeres plugin library red: false }); } reAddDeletedMessages(messages, id, deletedMessages, purgedMessages) { // hack if (this.antiinfiniteloop.findIndex(m => m === id) != -1) { //this.showToast('Infinite loop detected in data! Faulty ID:' + id, { type: 'error', timeout: 5000 }); //ZeresPluginLibrary.Logger.err(this.getName(), `Infinite loop detected in data! Cancelled restore of ${id}!`); // todo: add code to prevent this bullshit return false; zeres plugin library How to get it? zeres plugin library } const record = this.messageRecord[id]; if (!record || !record.delete_data || record.delete_data.hidden || !record.delete_data.rel_ids) return false; this.antiinfiniteloop.push(record.message.id); for (let prev in record.delete_data.rel_ids) { let relID = record.delete_data.rel_ids[prev]; let mIDX = (messages.length && messages.length - 1) || 0; let addIn = false; zeres plugin library How to get it for free? zeres plugin library if (relID != 'CHANNELEND') { mIDX = messages.findIndex(m => m.id === relID); } if (mIDX !== -1) addIn = true; else { if (deletedMessages && deletedMessages.findIndex(m => m === relID) === -1 && (!this.settings.showPurgedMessages || !purgedMessages || purgedMessages.findIndex(m => m === relID) === -1)) continue; if (this.reAddDeletedMessages(messages, relID)) addIn = true; } if (addIn) { mIDX = messages.findIndex(m => m.id === relID); zeres plugin library PasteShr zeres plugin library //let copy = Object.assign({}, record.message); //for (let attachmentIDX in copy.attachments) { // let attachment = copy.attachments[attachmentIDX]; // console.log(attachment.proxy_url); // attachment.proxy_url = this.imageCacheIdToDataURL(attachment.proxy_url); // console.log(attachment.proxy_url); //} messages.splice(mIDX, 0, record.message); return true; } zeres plugin library How to get it? zeres plugin library } return false; } getLiteralName(guildId, channelId, guildNameBackup = -1, channelNameBackup = -1) { // TODO, custom channel server failure text const guild = this.tools.getServer(guildId); const channel = this.tools.getChannel(channelId); // todo /* if (typeof guildNameBackup !== 'number' && guild && guildNameBackup) */ if (guildId) { const channelName = channel ? channel.name : 'unknown-channel'; const guildName = guild ? guild.name : 'unknown-server'; zeres plugin library How to dowload it? zeres plugin library return `${guildName}, #${channelName}`; } else if (channel && channel.name.length) { return `group ${channel.name}`; } else if (channel && channel.type == 3) { let finalGroupName = ''; for (let i of channel.recipients) { const user = this.tools.getUser(i); if (!user) continue; finalGroupName += ',' + user.username; } zeres plugin library How to get it for free? zeres plugin library if (!finalGroupName.length) { return 'unknown group'; } else { finalGroupName = finalGroupName.substr(1); finalGroupName = finalGroupName.length > 10 ? finalGroupName.substr(0, 10 - 1) + '...' : finalGroupName; return `group ${finalGroupName}`; } } else if (channel && channel.recipients) { const user = this.tools.getUser(channel.recipients[0]); if (!user) return 'DM'; zeres plugin library PasteShr zeres plugin library return `${user.username} DM`; } else { return 'DM'; } } getRelativeMessages(id, channelId) { const messages = this.channelMessages[channelId]; // ready check may be redundant, discord may not save the message if the channel isn't ready if (messages && messages.ready && messages._array.length) { let foundMessage = false; zeres plugin library How to get it? zeres plugin library let relMessages = []; for (let i = messages._array.length - 1; i >= 0; i--) { const message = messages._array[i]; if (!foundMessage && message.id == id) { foundMessage = true; continue; } if (foundMessage) relMessages.push(message.id); if (relMessages.length >= 3) return relMessages; } // todo, better caching if hasMoreBefore = true zeres plugin library How to get it? zeres plugin library if (!messages.hasMoreBefore) { relMessages.push('CHANNELEND'); return relMessages; } } return null; } saveDeletedMessage(message, targetMessageRecord) { let result = this.createMiniFormattedData(message); result.delete_data = {}; zeres plugin library How to get it? zeres plugin library const id = message.id; const channelId = message.channel_id; result.delete_data.time = new Date().getTime(); result.ghost_pinged = result.local_mentioned; // it's simple bruh if (!(result.delete_data.rel_ids = this.getRelativeMessages(id, channelId))) { //console.error(`[${this.getName()}]: saveDeletedMessage -> Failed to get relative IDs!`); //if (this.settings.displayInChat) ZeresPluginLibrary.Toasts.error(`Failed to get relative IDs! Deleted message will not show in chat after reload!`, { timeout: 7500 }); } if (!Array.isArray(targetMessageRecord[channelId])) targetMessageRecord[channelId] = []; if (this.messageRecord[id]) { zeres plugin library How to get it for free? zeres plugin library const record = this.messageRecord[id]; record.delete_data = result.delete_data; record.ghost_pinged = result.ghost_pinged; } else { this.messageRecord[id] = result; } if (this.messageRecord[id].message.attachments) { const attachments = this.messageRecord[id].message.attachments; for (let i = 0; i < attachments.length; i++) { attachments[i].url = attachments[i].proxy_url; // proxy url lasts longer zeres plugin library How to get it? zeres plugin library } } if (this.settings.cacheAllImages) this.cacheMessageImages(this.messageRecord[id].message); targetMessageRecord[channelId].push(id); } createButton(label, callback) { const classes = this.createButton.classes; const ret = this.parseHTML(``); if (callback) ret.addEventListener('click', callback); return ret; zeres plugin library How to get it for free? zeres plugin library } createModal(options, image, name) { const modal = image ? this.createModal.imageModal : this.createModal.confirmationModal; ZeresPluginLibrary.DiscordModules.ModalStack.push( function(props) { return ZeresPluginLibrary.DiscordModules.React.createElement(modal, Object.assign(options, props)); }, undefined, name ); zeres plugin library How to use it? zeres plugin library } getMessageAny(id) { const record = this.messageRecord[id]; if (!record) return this.cachedMessageRecord.find(m => m.id == id); return record.message; } handleImageCacheDataSaving() { this.requestedImageCacheDataSave = 0; // saveData/setPluginData is synchronous, can get slow with bigger files ZeresPluginLibrary.PluginUtilities.saveData('MLV2_IMAGE_CACHE/ImageCache', 'data', { zeres plugin library How to use it? zeres plugin library imageCacheRecord: this.imageCacheRecord }); } saveImageCacheData() { if (!this.settings.dontSaveData && !this.requestedImageCacheDataSave) this.requestedImageCacheDataSave = setTimeout(() => this.handleImageCacheDataSaving(), 5000); // needs to be async } cacheImage(url, attachmentIdx, attachmentId, messageId, channelId, attempts = 0) { this.nodeModules.request({ url: url, encoding: null }, (err, res, buffer) => { if (err || res.statusCode != 200) { if (res.statusCode == 404 || res.statusCode == 403) return; zeres plugin library How to use it? zeres plugin library attempts++; if (attempts > 3) return ZeresPluginLibrary.Logger.warn(this.getName(), `Failed to get image ${attachmentId} for caching, error code ${res.statusCode}`); return setTimeout(() => this.cacheImage(url, attachmentIdx, attachmentId, messageId, channelId, attempts), 1000); } const fileExtension = url.match(/\.[0-9a-z]+$/i)[0]; this.nodeModules.fs.writeFileSync(this.imageCacheDir + `/${attachmentId}${fileExtension}`, buffer, { encoding: null }); let reader = new FileReader(); reader.readAsDataURL(new Blob([buffer], { type: 'image/png' })); reader.onload = () => { const img = new Image(); zeres plugin library PasteShr zeres plugin library const canvas = document.createElement('canvas'); img.src = reader.result; img.onload = () => { const ctx = canvas.getContext('2d'); let width = img.width; let height = img.height; const maxSize = 256; if (width > maxSize || height > maxSize) { if (width > height) { const scale = maxSize / width; zeres plugin library PasteShr zeres plugin library width = maxSize; height *= scale; } else { const scale = maxSize / height; height = maxSize; width *= scale; } } canvas.width = width; canvas.height = height; zeres plugin library How to get it for free? zeres plugin library ctx.drawImage(img, 0, 0, width, height); let outputData = canvas.toDataURL('image/png'); outputData = outputData.substr(0, 14) + `;${channelId};${attachmentId}` + outputData.substr(14); this.imageCacheRecord[attachmentId] = { thumbnail: outputData, attachmentIdx: attachmentIdx, messageId: messageId, extension: fileExtension }; this.saveImageCacheData(); zeres plugin library PasteShr zeres plugin library }; }; }); } cacheMessageImages(message) { // don't block it, ugly but works, might rework later setTimeout(() => { for (let i = 0; i < message.attachments.length; i++) { const attachment = message.attachments[i]; if (!this.isImage(attachment.url)) continue; zeres plugin library How to get it for free? zeres plugin library this.cacheImage(attachment.url, i, attachment.id, message.id, message.channel_id); } }, 0); } /* ==================================================-|| END MISC ||-================================================== */ /* ==================================================-|| START MESSAGE MANAGMENT ||-================================================== */ deleteMessageFromRecords(id) { const record = this.messageRecord[id]; if (!record) { for (let map of [this.deletedMessageRecord, this.editedMessageRecord, this.purgedMessageRecord]) { zeres plugin library PasteShr zeres plugin library for (let channelId in map) { const index = map[channelId].findIndex(m => m === id); if (index == -1) continue; map[channelId].splice(index, 1); if (!map[channelId].length) delete map[channelId]; } } return; } // console.log('Deleting', record); zeres plugin library PasteShr zeres plugin library const channelId = record.message.channel_id; for (let map of [this.deletedMessageRecord, this.editedMessageRecord, this.purgedMessageRecord]) { if (!map[channelId]) continue; const index = map[channelId].findIndex(m => m === id); if (index == -1) continue; map[channelId].splice(index, 1); if (!map[channelId].length) delete map[channelId]; } delete this.messageRecord[id]; } zeres plugin library How to get it? zeres plugin library handleMessagesCap() { try { // TODO: add empty record and infinite loop checking for speed improvements const extractAllMessageIds = map => { let ret = []; for (let channelId in map) { for (let messageId of map[channelId]) { ret.push(messageId); } } zeres plugin library PasteShr zeres plugin library return ret; }; if (this.cachedMessageRecord.length > this.settings.messageCacheCap) this.cachedMessageRecord.splice(0, this.cachedMessageRecord.length - this.settings.messageCacheCap); let changed = false; const deleteMessages = map => { this.sortMessagesByAge(map); const toDelete = map.length - this.settings.savedMessagesCap; for (let i = map.length - 1, deleted = 0; i >= 0 && deleted != toDelete; i--, deleted++) { this.deleteMessageFromRecords(map[i]); } zeres plugin library PasteShr zeres plugin library changed = true; }; const handleInvalidEntries = map => { for (let channelId in map) { for (let messageIdIdx = map[channelId].length - 1; messageIdIdx >= 0; messageIdIdx--) { if (!Array.isArray(map[channelId])) { delete map[channelId]; changed = true; continue; } zeres plugin library How to get it for free? zeres plugin library if (!this.messageRecord[map[channelId][messageIdIdx]]) { map[channelId].splice(messageIdIdx, 1); changed = true; } } if (!map[channelId].length) { delete map[channelId]; changed = true; } } zeres plugin library PasteShr zeres plugin library }; const checkIsInRecords = (channelId, messageId) => { for (let map of [this.deletedMessageRecord, this.editedMessageRecord, this.purgedMessageRecord]) if (map[channelId] && map[channelId].findIndex(m => m === messageId) != -1) return true; return false; }; for (let map of [this.deletedMessageRecord, this.editedMessageRecord, this.purgedMessageRecord]) handleInvalidEntries(map); for (let messageId in this.messageRecord) { if (!checkIsInRecords(this.messageRecord[messageId].message.channel_id, messageId)) delete this.messageRecord[messageId]; } zeres plugin library How to get it for free? zeres plugin library let deletedMessages = extractAllMessageIds(this.deletedMessageRecord); let editedMessages = extractAllMessageIds(this.editedMessageRecord); let purgedMessages = extractAllMessageIds(this.purgedMessageRecord); for (let map of [deletedMessages, editedMessages, purgedMessages]) if (map.length > this.settings.savedMessagesCap) deleteMessages(map); if (changed) this.saveData(); if (!this.settings.cacheAllImages) return; changed = false; for (let attId in this.imageCacheRecord) { const record = this.imageCacheRecord[attId]; const imagePath = `${this.imageCacheDir}/${attId}${record.extension}`; zeres plugin library PasteShr zeres plugin library if (this.messageRecord[record.messageId] && this.nodeModules.fs.existsSync(imagePath)) continue; delete this.imageCacheRecord[attId]; changed = true; } if (changed) this.saveImageCacheData(); if (!this.settings.dontDeleteCachedImages) { const savedImages = this.nodeModules.fs.readdirSync(this.imageCacheDir); for (let img of savedImages) { if (img.indexOf('ImageCache.config.json') != -1) continue; const attId = img.match(/(\d*).[a-z]+/i)[1]; zeres plugin library How to use it? zeres plugin library if (this.imageCacheRecord[attId]) continue; try { this.nodeModules.fs.unlinkSync(`${this.imageCacheDir}/${img}`); } catch (e) { ZeresPluginLibrary.Logger.err(this.getName(), 'Error deleting unreferenced image, what the shit', e); } } } // 10 minutes for (let id in this.editHistoryAntiSpam) if (new Date().getTime() - this.editHistoryAntiSpam[id].times[0] < 10 * 60 * 1000) delete this.editHistoryAntiSpam[id]; zeres plugin library How to get it for free? zeres plugin library } catch (e) { ZeresPluginLibrary.Logger.stacktrace(this.getName(), 'Error clearing out data', e); } } /* ==================================================-|| END MESSAGE MANAGMENT ||-================================================== */ onDispatchEvent(args, callDefault) { const dispatch = args[0]; if (!dispatch) return callDefault(...args); zeres plugin library How to dowload it? zeres plugin library try { if (dispatch.type === 'MESSAGE_LOGGER_V2_SELF_TEST') { clearTimeout(this.selfTestTimeout); //console.log('Self test OK'); this.selfTestFailures = 0; return; } // if (dispatch.type == 'EXPERIMENT_TRIGGER') return callDefault(...args); // console.log('INFO: onDispatchEvent -> dispatch', dispatch); if (dispatch.type === 'CHANNEL_SELECT') { zeres plugin library How to get it? zeres plugin library callDefault(...args); this.selectedChannel = this.getSelectedTextChannel(); return; } if (dispatch.type === 'MODAL_POP') { callDefault(...args); if (!ZeresPluginLibrary.WebpackModules.getByProps('isModalOpenWithKey').isModalOpenWithKey(this.style.menu)) { this.menu.filter = ''; zeres plugin library How to dowload it? zeres plugin library this.menu.open = false; this.menu.shownMessages = -1; if (this.menu.messages) this.menu.messages.length = 0; } return; } if (dispatch.ML2 && dispatch.type === 'MESSAGE_DELETE') { callDefault(...args); setTimeout(() => this.updateMessages(), 0); // because this needs to return for it to continue zeres plugin library How to dowload it? zeres plugin library return; } if (dispatch.type === 'LOAD_MESSAGES_SUCCESS_CACHED') { callDefault(...args); return this.updateMessages(); } if (dispatch.type !== 'MESSAGE_CREATE' && dispatch.type !== 'MESSAGE_DELETE' && dispatch.type !== 'MESSAGE_DELETE_BULK' && dispatch.type !== 'MESSAGE_UPDATE' && dispatch.type !== 'LOAD_MESSAGES_SUCCESS') return callDefault(...args); zeres plugin library How to get it? zeres plugin library // console.log('INFO: onDispatchEvent -> dispatch', dispatch); if (dispatch.message && dispatch.message.type) return callDefault(...args); // anti other shit 1 const channel = this.tools.getChannel(dispatch.message ? dispatch.message.channel_id : dispatch.channelId); if (!channel) return callDefault(...args); const guild = channel.guild_id ? this.tools.getServer(channel.guild_id) : false; let author = dispatch.message && dispatch.message.author ? this.tools.getUser(dispatch.message.author.id) : false; if (!author) author = ((this.channelMessages[channel.id] || { _map: {} })._map[dispatch.message ? dispatch.message.id : dispatch.id] || {}).author; zeres plugin library How to use it? zeres plugin library if (!author) { // last ditch attempt let message = this.getCachedMessage(dispatch.id); if (message) author = this.tools.getUser(message.author.id); } if (!author && !(dispatch.type == 'LOAD_MESSAGES_SUCCESS' || dispatch.type == 'MESSAGE_DELETE_BULK')) return callDefault(...args); const isLocalUser = author && author.id === this.localUser.id; zeres plugin library How to use it? zeres plugin library if (author && author.bot && this.settings.ignoreBots) return callDefault(...args); if (author && isLocalUser && this.settings.ignoreSelf) return callDefault(...args); if (author && this.settings.ignoreBlockedUsers && this.tools.isBlocked(author.id) && !isLocalUser) return callDefault(...args); if (author && author.avatar === 'clyde') return callDefault(...args); if (this.settings.ignoreLocalEdits && dispatch.type === 'MESSAGE_UPDATE' && isLocalUser) return callDefault(...args); if (this.settings.ignoreLocalDeletes && dispatch.type === 'MESSAGE_DELETE' && isLocalUser && this.localDeletes.findIndex(m => m === dispatch.id) !== -1) return callDefault(...args); let guildIsMutedReturn = false; let channelIgnoreReturn = false; zeres plugin library How to dowload it? zeres plugin library const isInWhitelist = id => this.settings.whitelist.findIndex(m => m === id) != -1; const isInBlacklist = id => this.settings.blacklist.findIndex(m => m === id) != -1; const guildWhitelisted = guild && isInWhitelist(guild.id); const channelWhitelisted = isInWhitelist(channel.id); const guildBlacklisted = guild && isInBlacklist(guild.id); const channelBlacklisted = isInBlacklist(channel.id); let doReturn = false; zeres plugin library How to dowload it? zeres plugin library if (guild) { guildIsMutedReturn = this.settings.ignoreMutedGuilds && this.muteModule.isMuted(guild.id); channelIgnoreReturn = (this.settings.ignoreNSFW && channel.nsfw && !channelWhitelisted) || (this.settings.ignoreMutedChannels && (this.muteModule.isChannelMuted(guild.id, channel.id) || (channel.parent_id && this.muteModule.isChannelMuted(channel.parent_id)))); } if (!((this.settings.alwaysLogSelected && this.selectedChannel && this.selectedChannel.id == channel.id) || (this.settings.alwaysLogDM && !guild))) { if (guildBlacklisted) { if (!channelWhitelisted) doReturn = true; // not whitelisted } else if (guildWhitelisted) { zeres plugin library How to get it? zeres plugin library if (channelBlacklisted) doReturn = true; // channel blacklisted if (channelIgnoreReturn && !channelWhitelisted) doReturn = true; } else { if (this.settings.onlyLogWhitelist) { if (!channelWhitelisted) doReturn = true; // guild not in either list, channel not whitelisted } else { if (channelBlacklisted) doReturn = true; // channel blacklisted if (channelIgnoreReturn || guildIsMutedReturn) { if (!channelWhitelisted) doReturn = true; } zeres plugin library How to get it? zeres plugin library } } } if (doReturn && this.settings.alwaysLogGhostPings) { if (dispatch.type === 'MESSAGE_DELETE') { const deleted = this.getCachedMessage(dispatch.id, dispatch.channelId); if (!deleted || deleted.type) return callDefault(...args); // nothing we can do past this point.. if (!this.tools.isMentioned(deleted, this.localUser.id)) return callDefault(...args); const record = this.messageRecord[dispatch.id]; zeres plugin library How to dowload it? zeres plugin library if ((!this.selectedChannel || this.selectedChannel.id != channel.id) && (guild ? this.settings.toastToggles.ghostPings : this.settings.toastTogglesDMs.ghostPings) && (!record || !record.ghost_pinged)) { this.showToast(`You got ghost pinged in ${this.getLiteralName(channel.guild_id, channel.id)}`, { type: 'warning', onClick: () => this.openWindow('ghostpings'), onContext: () => this.jumpToMessage(dispatch.channelId, dispatch.id, guild && guild.id), timeout: 4500 }); } this.saveDeletedMessage(deleted, this.deletedMessageRecord); this.saveData(); zeres plugin library How to dowload it? zeres plugin library } else if (dispatch.type === 'MESSAGE_UPDATE') { if (!dispatch.message.edited_timestamp) { let last = this.getCachedMessage(dispatch.message.id); if (last) last.embeds = dispatch.message.embeds; return callDefault(...args); } let isSaved = this.getEditedMessage(dispatch.message.id, channel.id); const last = this.getCachedMessage(dispatch.message.id, channel.id); const lastEditedSaved = isSaved || this.tempEditedMessageRecord[dispatch.message.id]; zeres plugin library How to get it? zeres plugin library if (isSaved && !lastEditedSaved.local_mentioned) { lastEditedSaved.message.content = dispatch.message.content; // don't save history, just the value so we don't confuse the user return callDefault(...args); } // if we have lastEdited then we can still continue as we have all the data we need to process it. if (!last && !lastEditedSaved) return callDefault(...args); // nothing we can do past this point.. let ghostPinged = false; if (lastEditedSaved) { // last is not needed, we have all the data already saved zeres plugin library How to use it? zeres plugin library if (lastEditedSaved.message.content === dispatch.message.content) return callDefault(...args); // we don't care about that lastEditedSaved.edit_history.push({ content: lastEditedSaved.message.content, time: new Date().getTime() }); lastEditedSaved.message.content = dispatch.message.content; ghostPinged = !lastEditedSaved.ghost_pinged && lastEditedSaved.local_mentioned && !this.tools.isMentioned(dispatch.message, this.localUser.id); } else { if (last.content === dispatch.message.content) return callDefault(...args); // we don't care about that let data = this.createMiniFormattedData(last); zeres plugin library PasteShr zeres plugin library data.edit_history = [ { content: last.content, time: new Date().getTime() } ]; data.message.content = dispatch.message.content; this.tempEditedMessageRecord[data.message.id] = data; ghostPinged = this.tools.isMentioned(last, this.localUser.id) && !this.tools.isMentioned(dispatch.message, this.localUser.id); } zeres plugin library How to get it for free? zeres plugin library if (isSaved) this.saveData(); if (!ghostPinged) return callDefault(...args); if (!isSaved) { const data = this.tempEditedMessageRecord[dispatch.message.id]; data.ghost_pinged = true; this.messageRecord[dispatch.message.id] = data; if (!this.editedMessageRecord[channel.id]) this.editedMessageRecord[channel.id] = []; zeres plugin library How to use it? zeres plugin library this.editedMessageRecord[channel.id].push(dispatch.message.id); this.saveData(); } else { const lastEdited = this.getEditedMessage(dispatch.message.id, channel.id); if (!lastEdited) return callDefault(...args); lastEdited.ghost_pinged = true; this.saveData(); } if ((!this.selectedChannel || this.selectedChannel.id != channel.id) && (guild ? this.settings.toastToggles.ghostPings : this.settings.toastTogglesDMs.ghostPings)) { zeres plugin library How to use it? zeres plugin library this.showToast(`You got ghost pinged in ${this.getLiteralName(channel.guild_id, channel.id)}`, { type: 'warning', onClick: () => this.openWindow('ghostpings'), onContext: () => this.jumpToMessage(dispatch.channelId, dispatch.id, guild && guild.id), timeout: 4500 }); } } else if (dispatch.type == 'MESSAGE_CREATE' && dispatch.message && (dispatch.message.content.length || (dispatch.attachments && dispatch.attachments.length) || (dispatch.embeds && dispatch.embeds.length)) && dispatch.message.state != 'SENDING' && !dispatch.optimistic && !dispatch.message.type) { if (this.cachedMessageRecord.findIndex(m => m.id === dispatch.message.id) != -1) return callDefault(...args); this.cachedMessageRecord.push(dispatch.message); zeres plugin library How to use it? zeres plugin library } } if (doReturn) return callDefault(...args); if (dispatch.type == 'LOAD_MESSAGES_SUCCESS') { if (!this.settings.restoreDeletedMessages) return callDefault(...args); if (dispatch.jump && dispatch.jump.ML2) delete dispatch.jump; const deletedMessages = this.deletedMessageRecord[channel.id]; const purgedMessages = this.purgedMessageRecord[channel.id]; if ((!deletedMessages && !purgedMessages) || (!this.settings.showPurgedMessages && !this.settings.showDeletedMessages)) return callDefault(...args); zeres plugin library How to get it for free? zeres plugin library //console.log('Recursively adding deleted messages'); /* return callDefault(...args); */ if (this.settings.showDeletedMessages && deletedMessages) { for (let messageIDX in deletedMessages) { let recordID = deletedMessages[messageIDX]; if (!this.messageRecord[recordID]) continue; if (this.messageRecord[recordID].delete_data.hidden) { const mIDX = dispatch.messages.findIndex(m => m.id === recordID); if (mIDX != -1) dispatch.messages.splice(mIDX, 1); continue; zeres plugin library How to use it? zeres plugin library } if (this.messageRecord[recordID].message.channel_id != dispatch.channelId || dispatch.messages.findIndex(m => m.id === recordID) != -1) continue; this.antiinfiniteloop = []; this.reAddDeletedMessages(dispatch.messages, recordID, deletedMessages, purgedMessages); } } if (this.settings.showPurgedMessages && purgedMessages) { for (let messageIDX in purgedMessages) { let recordID = purgedMessages[messageIDX]; if (!this.messageRecord[recordID]) continue; zeres plugin library How to use it? zeres plugin library if (this.messageRecord[recordID].delete_data.hidden) { const mIDX = dispatch.messages.findIndex(m => m.id === recordID); if (mIDX != -1) dispatch.messages.splice(mIDX, 1); continue; } if (this.messageRecord[recordID].message.channel_id != dispatch.channelId || dispatch.messages.findIndex(m => m.id == recordID) != -1) continue; this.antiinfiniteloop = []; this.reAddDeletedMessages(dispatch.messages, recordID, deletedMessages, purgedMessages); } } zeres plugin library How to get it for free? zeres plugin library callDefault(...args); this.updateMessages(); return; } if (dispatch.type == 'MESSAGE_DELETE') { const deleted = this.getCachedMessage(dispatch.id, dispatch.channelId); if (this.settings.aggresiveMessageCaching) { const channelMessages = this.channelMessages[channel.id]; zeres plugin library How to get it for free? zeres plugin library if (!channelMessages || !channelMessages.ready) this.cacheChannelMessages(channel.id); } if (!deleted) return callDefault(...args); // nothing we can do past this point.. if (this.deletedMessageRecord[channel.id] && this.deletedMessageRecord[channel.id].findIndex(m => m === deleted.id) != -1) { if (!this.settings.showDeletedMessages) callDefault(...args); return; } zeres plugin library How to get it for free? zeres plugin library if (deleted.type) return callDefault(...args); if (this.settings.showDeletedCount) { if (!this.deletedChatMessagesCount[channel.id]) this.deletedChatMessagesCount[channel.id] = 0; if (!this.selectedChannel || this.selectedChannel.id != channel.id) this.deletedChatMessagesCount[channel.id]++; } if (guild ? this.settings.toastToggles.deleted && ((isLocalUser && !this.settings.toastToggles.disableToastsForLocal) || !isLocalUser) : this.settings.toastTogglesDMs.deleted && !isLocalUser) { this.showToast(`Message deleted from ${this.getLiteralName(channel.guild_id, channel.id)}`, { type: 'error', onClick: () => this.openWindow('deleted'), zeres plugin library PasteShr zeres plugin library onContext: () => this.jumpToMessage(dispatch.channelId, dispatch.id, guild && guild.id), timeout: 4500 }); } const record = this.messageRecord[dispatch.id]; if ((!this.selectedChannel || this.selectedChannel.id != channel.id) && (guild ? this.settings.toastToggles.ghostPings : this.settings.toastTogglesDMs.ghostPings) && record && !record.ghost_pinged && this.tools.isMentioned(deleted, this.localUser.id)) { this.showToast(`You got ghost pinged in ${this.getLiteralName(channel.guild_id, channel.id)}`, { type: 'warning', zeres plugin library How to use it? zeres plugin library onClick: () => this.openWindow('ghostpings'), onContext: () => this.jumpToMessage(dispatch.channelId, dispatch.id, guild && guild.id), timeout: 4500 }); } this.saveDeletedMessage(deleted, this.deletedMessageRecord); // if (this.settings.cacheAllImages) this.cacheImages(deleted); if (!this.settings.showDeletedMessages) callDefault(...args); this.saveData(); zeres plugin library PasteShr zeres plugin library } else if (dispatch.type == 'MESSAGE_DELETE_BULK') { if (this.settings.showDeletedCount) { if (!this.deletedChatMessagesCount[channel.id]) this.deletedChatMessagesCount[channel.id] = 0; if (!this.selectedChannel || this.selectedChannel.id != channel.id) this.deletedChatMessagesCount[channel.id] += dispatch.ids.length; } let failedMessage = false; for (let i = 0; i < dispatch.ids.length; i++) { const purged = this.getCachedMessage(dispatch.ids[i], channel.id); zeres plugin library How to use it? zeres plugin library if (!purged) { failedMessage = true; continue; } this.saveDeletedMessage(purged, this.purgedMessageRecord); } if (failedMessage && this.aggresiveMessageCaching) // forcefully cache the channel in case there are active convos there this.cacheChannelMessages(channel.id); zeres plugin library How to use it? zeres plugin library else if (this.settings.aggresiveMessageCaching) { const channelMessages = this.channelMessages[channel.id]; if (!channelMessages || !channelMessages.ready) this.cacheChannelMessages(channel.id); } if (guild ? this.settings.toastToggles.deleted : this.settings.toastTogglesDMs.deleted) { this.showToast(`${dispatch.ids.length} messages bulk deleted from ${this.getLiteralName(channel.guild_id, channel.id)}`, { type: 'error', onClick: () => this.openWindow('purged'), onContext: () => this.jumpToMessage(channel.id, undefined, guild && guild.id), zeres plugin library How to get it for free? zeres plugin library timeout: 4500 }); } if (!this.settings.showPurgedMessages) callDefault(...args); this.saveData(); } else if (dispatch.type == 'MESSAGE_UPDATE') { if (!dispatch.message.edited_timestamp) { let last = this.getCachedMessage(dispatch.message.id); if (last) last.embeds = dispatch.message.embeds; zeres plugin library How to get it? zeres plugin library return callDefault(...args); } if (this.settings.showEditedCount) { if (!this.editedChatMessagesCount[channel.id]) this.editedChatMessagesCount[channel.id] = 0; if (!this.selectedChannel || this.selectedChannel.id != channel.id) this.editedChatMessagesCount[channel.id]++; } if (this.settings.aggresiveMessageCaching) { const channelMessages = this.channelMessages[channel.id]; zeres plugin library How to use it? zeres plugin library if (!channelMessages || !channelMessages.ready) this.cacheChannelMessages(channel.id); } const last = this.getCachedMessage(dispatch.message.id, channel.id); const lastEditedSaved = this.getEditedMessage(dispatch.message.id, channel.id); // if we have lastEdited then we can still continue as we have all the data we need to process it. if (!last && !lastEditedSaved) return callDefault(...args); // nothing we can do past this point.. let ghostPinged = false; if (lastEditedSaved) { zeres plugin library PasteShr zeres plugin library // last is not needed, we have all the data already saved // console.log(lastEditedSaved.message); // console.log(dispatch.message); if (lastEditedSaved.message.content === dispatch.message.content) { if (!this.settings.showEditedMessages) callDefault(...args); return; // we don't care about that } lastEditedSaved.edit_history.push({ content: lastEditedSaved.message.content, time: new Date().getTime() zeres plugin library How to dowload it? zeres plugin library }); lastEditedSaved.message.content = dispatch.message.content; ghostPinged = !lastEditedSaved.ghost_pinged && lastEditedSaved.local_mentioned && !this.tools.isMentioned(dispatch.message, this.localUser.id); if (ghostPinged) lastEditedSaved.ghost_pinged = true; } else { if (last.content === dispatch.message.content) { if (!this.settings.showEditedMessages) callDefault(...args); return; // we don't care about that } let data = this.createMiniFormattedData(last); zeres plugin library PasteShr zeres plugin library data.edit_history = [ { content: last.content, time: new Date().getTime() } ]; ghostPinged = this.tools.isMentioned(last, this.localUser.id) && !this.tools.isMentioned(dispatch.message, this.localUser.id); data.message.content = dispatch.message.content; if (ghostPinged) data.ghost_pinged = true; this.messageRecord[data.message.id] = data; zeres plugin library How to get it for free? zeres plugin library if (!this.editedMessageRecord[channel.id]) this.editedMessageRecord[channel.id] = []; this.editedMessageRecord[channel.id].push(data.message.id); } if (guild ? this.settings.toastToggles.edited && ((isLocalUser && !this.settings.toastToggles.disableToastsForLocal) || !isLocalUser) : this.settings.toastTogglesDMs.edited && !isLocalUser) { if (!this.settings.blockSpamEdit) { if (!this.editHistoryAntiSpam[author.id]) { this.editHistoryAntiSpam[author.id] = { blocked: false, times: [new Date().getTime()] zeres plugin library How to get it for free? zeres plugin library }; } else { this.editHistoryAntiSpam[author.id].times.push(new Date().getTime()); } if (this.editHistoryAntiSpam[author.id].times.length > 10) this.editHistoryAntiSpam[author.id].times.shift(); if (this.editHistoryAntiSpam[author.id].times.length === 10 && new Date().getTime() - this.editHistoryAntiSpam[author.id].times[0] < 60 * 1000) { if (!this.editHistoryAntiSpam[author.id].blocked) { this.showToast(`Edit notifications from ${author.username} have been temporarily blocked for 1 minute.`, { type: 'warning', timeout: 7500 zeres plugin library How to get it for free? zeres plugin library }); this.editHistoryAntiSpam[author.id].blocked = true; } } else if (this.editHistoryAntiSpam[author.id].blocked) { this.editHistoryAntiSpam[author.id].blocked = false; this.editHistoryAntiSpam[author.id].times = []; } } if (this.settings.blockSpamEdit || !this.editHistoryAntiSpam[author.id].blocked) { this.showToast(`Message edited in ${this.getLiteralName(channel.guild_id, channel.id)}`, { zeres plugin library How to get it? zeres plugin library type: 'info', onClick: () => this.openWindow('edited'), onContext: () => this.jumpToMessage(channel.id, dispatch.message.id, guild && guild.id), timeout: 4500 }); } } if ((!this.selectedChannel || this.selectedChannel.id != channel.id) && (guild ? this.settings.toastToggles.ghostPings : this.settings.toastTogglesDMs.ghostPings) && ghostPinged) { this.showToast(`You got ghost pinged in ${this.getLiteralName(channel.guild_id, channel.id)}`, { zeres plugin library How to use it? zeres plugin library type: 'warning', onClick: () => this.openWindow('ghostpings'), onContext: () => this.jumpToMessage(dispatch.channelId, dispatch.id, guild && guild.id), timeout: 4500 }); } if (!this.settings.showEditedMessages) callDefault(...args); else { const msg = this.cachedMessageRecord.find(m => m.id == dispatch.message.id); zeres plugin library How to get it for free? zeres plugin library if (msg) msg.content = dispatch.message.content; // show new edits afterwards, bruh if (lastEditedSaved && lastEditedSaved.edits_hidden) callDefault(...args); else { const cachedChannel = this.channelMessages[dispatch.message.channel_id]; if (cachedChannel && cachedChannel.ready) { const cachedMessage = cachedChannel._map[dispatch.message.id]; // wtf? if (cachedMessage) { cachedMessage.content = dispatch.message.content; // probably bad idea but it works zeres plugin library How to get it? zeres plugin library cachedMessage.contentParsed = this.tools.parse(dispatch.message.content, true, { channelId: dispatch.message.channel_id }); // omega ghetto cachedMessage.editedTimestamp = this.tools.createMomentObject(dispatch.message.edited_timestamp); // don't ask how I found this } } } } this.saveData(); } else if (dispatch.type == 'MESSAGE_CREATE' && dispatch.message && (dispatch.message.content.length || (dispatch.attachments && dispatch.attachments.length) || (dispatch.embeds && dispatch.embeds.length)) && dispatch.message.state != 'SENDING' && !dispatch.optimistic && !dispatch.message.type) { if (this.cachedMessageRecord.findIndex(m => m.id === dispatch.message.id) != -1) return callDefault(...args); this.cachedMessageRecord.push(dispatch.message); zeres plugin library PasteShr zeres plugin library /* if (this.menu.open && this.menu.selectedTab == 'sent') this.refilterMessages(); */ if (this.settings.aggresiveMessageCaching) { const channelMessages = this.channelMessages[channel.id]; if (!channelMessages || !channelMessages.ready) this.cacheChannelMessages(channel.id); } if ((guild ? this.settings.toastToggles.sent : this.settings.toastTogglesDMs.sent) && (!this.selectedChannel || this.selectedChannel.id != channel.id)) { this.showToast(`Message sent in ${this.getLiteralName(channel.guild_id, channel.id)}`, { type: 'info', onClick: () => this.openWindow('sent'), onContext: () => this.jumpToMessage(channel.id, dispatch.message.id, guild && guild.id), timeout: 4500 }); } zeres plugin library How to get it for free? zeres plugin library callDefault(...args); } else callDefault(...args); } catch (err) { ZeresPluginLibrary.Logger.stacktrace(this.getName(), 'Error in onDispatchEvent', err); } } updateMessages() { if (!this.settings.showEditedMessages && !this.settings.showDeletedMessages && !this.settings.showPurgedMessages) return; if (!this.selectedChannel) return; zeres plugin library How to get it for free? zeres plugin library const chat = document.querySelector('.' + this.classes.chat + ' .' + this.classes.messagesWrapper); if (!chat) return; const messages = chat.querySelectorAll(this.classes.messages); const onClickEditedTag = e => { this.menu.filter = `message:${e.target.messageId}`; this.openWindow('edited'); }; zeres plugin library How to dowload it? zeres plugin library for (let i = 0; i < messages.length; i++) { try { const message = messages[i]; const props = ZeresPluginLibrary.ReactTools.getOwnerInstance(message).props; const msg = props.message || (props.style.borderRadius == 2 && props.children && props.children._owner && props.children._owner.memoizedProps.message); if (!msg) continue; const mid = msg.id; const channID = msg.channel_id; let markup = message.getElementsByClassName(this.classes.markup)[0]; if (!markup) continue; // gay zeres plugin library How to use it? zeres plugin library let record = this.messageRecord[mid]; if (!record) continue; const fuckupdiscord = () => { /* HACK */ if (!markup.fucked) { const original = markup.cloneNode(true); const parent = markup.parentElement; markup.remove(); parent.appendChild(original); markup = original; zeres plugin library How to dowload it? zeres plugin library markup.fucked = true; } /* HACK */ }; let wasDeleted = false; if (message.className.indexOf(this.style.deleted) === -1 && !message.isDeleted && ((this.deletedMessageRecord[channID] && this.deletedMessageRecord[channID].findIndex(m => m === mid) !== -1) || (this.purgedMessageRecord[channID] && this.purgedMessageRecord[channID].findIndex(m => m === mid) != -1))) { if (this.getEditedMessage(mid, channID) && this.settings.showEditedMessages) fuckupdiscord(); const edits = message.getElementsByClassName(this.style.edited); for (let i = 0; i < edits.length; i++) if (edits[i].tooltip) edits[i].tooltip.disabled = true; message.classList.add(this.style.deleted); zeres plugin library How to get it? zeres plugin library new ZeresPluginLibrary.EmulatedTooltip(markup.textContent ? markup : message.getElementsByClassName(this.classes.content)[0].lastChild, 'Deleted at ' + this.createTimeStamp(record.delete_data.time), { side: 'left' }); wasDeleted = true; } if (!this.settings.showEditedMessages) continue; record = this.getEditedMessage(mid, channID); if (record && !record.edits_hidden) { fuckupdiscord(); if (markup.edits === record.edit_history.length) continue; markup.edits = record.edit_history.length; // todo, randomize markup.classList.add(this.style.edited); zeres plugin library How to get it for free? zeres plugin library if (markup.touched) markup.touched = false; const headerWidth = this.isCompact() && markup.firstChild && markup.firstChild.getBoundingClientRect ? markup.firstChild.lastChild.getBoundingClientRect().width : 0; let header; if (this.isCompact()) header = markup.firstChild; while (markup.firstChild) markup.removeChild(markup.firstChild); let e = 0; let max = record.edit_history.length; if (this.settings.maxShownEdits) { if (record.edit_history.length > this.settings.maxShownEdits) { if (this.settings.hideNewerEditsFirst) { zeres plugin library How to dowload it? zeres plugin library max = this.settings.maxShownEdits; } else { e = record.edit_history.length - this.settings.maxShownEdits; } } } for (; e < max; e++) { const editedMarkup = this.formatMarkup(record.edit_history[e].content, record.message.channel_id); const editedTag = document.createElement('time'); editedTag.className = this.multiClasses.edited; zeres plugin library How to get it? zeres plugin library editedTag.innerText = '(edited)'; editedTag.messageId = mid; editedTag.addEventListener('click', onClickEditedTag); editedMarkup.firstChild.appendChild(editedTag); editedMarkup.classList.add(this.style.edited); editedMarkup.firstChild.classList.remove(this.style.edited); editedMarkup.firstChild.editNum = e; const time = record.edit_history[e].time; // compatibility if (!wasDeleted) editedMarkup.tooltip = new ZeresPluginLibrary.EmulatedTooltip(editedMarkup, 'Edited at ' + (typeof time === 'string' ? time : this.createTimeStamp(time)), { side: 'left' }); if (this.isCompact()) { zeres plugin library PasteShr zeres plugin library if (header) { markup.classList.add(this.style.markupCompact); header.classList.add(this.style.editedCompact); editedMarkup.classList.add(this.style.editedCompact); markup.appendChild(header); header = undefined; } editedMarkup.style.textIndent = headerWidth + 'px'; } markup.appendChild(editedMarkup); zeres plugin library How to use it? zeres plugin library } // msg.content is latest, keep it up to date // we may not have the time of edit, but at least we can force it to save the newest if (new Date().getTime() - record.edit_history[record.edit_history.length - 1].time > 60 * 1000) record.message.content = msg.content; const editedMarkup = this.formatMarkup(record.message.content, record.message.channel_id); editedMarkup.firstChild.classList.remove(this.classes.markup); if (this.isCompact()) { editedMarkup.style.textIndent = headerWidth + 'px'; } markup.appendChild(editedMarkup); zeres plugin library How to dowload it? zeres plugin library } else if (record && record.edits_hidden) { if (markup.className.indexOf(this.style.edited) !== -1) { markup.edits = 0; const headerWidth = this.isCompact() && markup.firstChild && markup.firstChild.getBoundingClientRect ? markup.firstChild.lastChild.getBoundingClientRect().width : 0; let header; if (this.isCompact()) header = markup.firstChild; while (markup.firstChild) markup.removeChild(markup.firstChild); const editedMarkup = this.formatMarkup((record.message.content = msg.content), record.message.channel_id); const editedTag = document.createElement('time'); editedTag.className = this.multiClasses.edited; zeres plugin library How to use it? zeres plugin library editedTag.innerText = '(edited)'; editedTag.messageId = mid; editedTag.addEventListener('click', onClickEditedTag); editedMarkup.firstChild.appendChild(editedTag); editedMarkup.firstChild.classList.remove(this.classes.markup); if (this.isCompact()) { markup.classList.add(this.style.markupCompact); header.classList.add(this.style.editedCompact); editedMarkup.classList.add(this.style.editedCompact); markup.appendChild(header); zeres plugin library How to dowload it? zeres plugin library editedMarkup.style.textIndent = headerWidth + 'px'; } markup.appendChild(editedMarkup); } if (markup.touched) continue; const editedText = markup.getElementsByClassName(this.multiClasses.edited.split(/ /g)[0])[0]; if (!editedText) continue; // dunno editedText.messageId = mid; editedText.addEventListener('click', onClickEditedTag); markup.touched = true; zeres plugin library How to use it? zeres plugin library } } catch (e) { ZeresPluginLibrary.Logger.stacktrace(this.getName(), 'Error in updateMessages', e); } } } /* ==================================================-|| START MENU ||-================================================== */ processUserRequestQueue() { if (!this.processUserRequestQueue.queueIntervalTime) this.processUserRequestQueue.queueIntervalTime = 500; if (this.menu.queueInterval) return; zeres plugin library How to use it? zeres plugin library const messageDataManager = () => { if (!this.menu.userRequestQueue.length) { clearInterval(this.menu.queueInterval); this.menu.queueInterval = 0; return; } const data = this.menu.userRequestQueue.shift(); this.tools .getUserAsync(data.id) .then(res => { zeres plugin library How to use it? zeres plugin library for (let ss of data.success) ss(res); }) .catch(reason => { if (reason.status == 429 && typeof reason.body.retry_after === 'number') { clearInterval(this.menu.queueInterval); this.menu.queueInterval = 0; this.processUserRequestQueue.queueIntervalTime += 50; setTimeout(messageDataManager, reason.body.retry_after); ZeresPluginLibrary.Logger.warn(this.getName(), 'Rate limited, retrying in', reason.body.retry_after, 'ms'); this.menu.userRequestQueue.push(data); zeres plugin library How to get it for free? zeres plugin library return; } ZeresPluginLibrary.Logger.warn(this.getName(), `Failed to get info for ${data.username}, reason:`, reason); for (let ff of data.fail) ff(); }); }; this.menu.queueInterval = setInterval(() => messageDataManager(), this.processUserRequestQueue.queueIntervalTime); } patchModal() { // REQUIRED zeres plugin library PasteShr zeres plugin library const onChangeOrder = el => { this.settings.reverseOrder = !this.settings.reverseOrder; el.target.innerText = 'Sort direction: ' + (!this.settings.reverseOrder ? 'new - old' : 'old - new'); // maybe a func? this.saveSettings(); this.refilterMessages(); }; const onClearLog = e => { e.preventDefault(); if (document.getElementById(this.style.filter).parentElement.parentElement.className.indexOf(this.createTextBox.classes.focused[0]) != -1) return; zeres plugin library How to get it for free? zeres plugin library this.scrollPosition = document.getElementById(this.style.menuMessages).parentElement.parentElement.parentElement.scrollTop; let type = this.menu.selectedTab; if (type === 'ghostpings') type = 'ghost pings'; else { type += ' messages'; } ZeresPluginLibrary.Modals.showConfirmationModal('Clear log', `Are you sure you want to delete all ${type}${this.menu.filter.length ? ' that also match filter' : ''}?`, { confirmText: 'Confirm', onConfirm: () => { if (this.menu.selectedTab == 'sent') { zeres plugin library PasteShr zeres plugin library if (!this.menu.filter.length) for (let id of this.menu.messages) this.cachedMessageRecord.splice(this.cachedMessageRecord.findIndex(m => m.id === id), 1); else this.cachedMessageRecord.length = 0; // hack, does it cause a memory leak? } else { for (let id of this.menu.messages) { const record = this.messageRecord[id]; let isSelected = false; if (record) { this.invalidateChannelCache(record.message.channel_id); if (this.selectedChannel) isSelected = record.message.channel_id === this.selectedChannel.id; } zeres plugin library How to dowload it? zeres plugin library this.deleteMessageFromRecords(id); if (this.selectedChannel && isSelected) this.cacheChannelMessages(this.selectedChannel.id); } this.saveData(); } this.menu.refilterOnMount = true; } }); }; zeres plugin library How to get it? zeres plugin library this.unpatches.push( ZeresPluginLibrary.Patcher.instead(this.getName(), ZeresPluginLibrary.DiscordModules.ConfirmationModal.prototype, 'handleClose', (thisObj, args, original) => { if (thisObj.props.ml2Data) onChangeOrder(args[0]); else original(...args); }) ); this.unpatches.push( ZeresPluginLibrary.Patcher.instead(this.getName(), ZeresPluginLibrary.DiscordModules.ConfirmationModal.prototype, 'handleSubmit', (thisObj, args, original) => { if (thisObj.props.ml2Data) onClearLog(args[0]); zeres plugin library How to get it? zeres plugin library else original(...args); }) ); this.unpatches.push( ZeresPluginLibrary.Patcher.instead(this.getName(), ZeresPluginLibrary.DiscordModules.ConfirmationModal.prototype, 'componentDidMount', (thisObj, args, original) => { if (thisObj.props.ml2Data) { if (this.menu.refilterOnMount) { this.refilterMessages(); this.menu.refilterOnMount = false; zeres plugin library PasteShr zeres plugin library } document.getElementById(this.style.menuMessages).parentElement.parentElement.parentElement.scrollTop = this.scrollPosition; } return original(...args); }) ); } // >>-|| POPULATION ||-<< createMessageGroup(message) { let deleted = false; zeres plugin library How to get it? zeres plugin library let edited = false; let details = 'Sent in'; let channel = this.tools.getChannel(message.channel_id); let timestamp = message.timestamp; let author = this.tools.getUser(message.author.id); let noUserInfo = false; let userInfoBeingRequested = true; const isBot = message.author.bot; const record = this.messageRecord[message.id]; if (record) { zeres plugin library How to get it? zeres plugin library deleted = !!record.delete_data; edited = !!record.edit_history; if (deleted && edited) { details = 'Edited and deleted from'; timestamp = record.delete_data.time; } else if (deleted) { details = 'Deleted from'; timestamp = record.delete_data.time; } else if (edited) { zeres plugin library How to use it? zeres plugin library details = 'Last edit in'; // todo: purged? if (typeof record.edit_history[record.edit_history.length - 1].time !== 'string') timestamp = record.edit_history[record.edit_history.length - 1].time; } } details += ` ${this.getLiteralName(message.guild_id || (channel && channel.guild_id), message.channel_id)} `; details += `at ${this.createTimeStamp(timestamp, true)}`; const classes = this.createMessageGroup.classes; zeres plugin library How to get it? zeres plugin library const getAvatarOf = user => { if (!user.avatar) return '/assets/322c936a8c8be1b803cd94861bdfa868.png'; return `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=128`; }; // minify? // what is wrapper-3t9DeA and how do I get it // wtf is avatar-VxgULZ const element = this.parseHTML(`
zeres plugin library How to get it for free? zeres plugin library

${message.author.username} zeres plugin library How to use it? zeres plugin library ${(isBot && ` BOT `) || ''}
${details}
zeres plugin library How to dowload it? zeres plugin library

`); const profImg = element.getElementsByClassName(classes.avatarImgSingle)[0]; profImg.onerror = () => { profImg.src = '/assets/322c936a8c8be1b803cd94861bdfa868.png'; }; zeres plugin library PasteShr zeres plugin library const verifyProfilePicture = () => { if (message.author.avatar != author.avatar && author.avatar) { profImg.src = getAvatarOf(author); if (record) { record.message.author.avatar = author.avatar; } } else { if (record) record.message.author.avatar = null; } }; zeres plugin library How to dowload it? zeres plugin library if (!isBot) { if (!author) { author = message.author; if (this.menu.userRequestQueue.findIndex(m => m.id === author.id) == -1) { this.menu.userRequestQueue.push({ id: author.id, username: author.username, success: [ res => { author = $.extend(true, {}, res); zeres plugin library How to dowload it? zeres plugin library verifyProfilePicture(); userInfoBeingRequested = false; } ], fail: [ () => { noUserInfo = true; userInfoBeingRequested = false; } ] zeres plugin library How to get it? zeres plugin library }); } else { const dt = this.menu.userRequestQueue.find(m => m.id === author.id); dt.success.push(res => { author = $.extend(true, {}, res); verifyProfilePicture(); userInfoBeingRequested = false; }); dt.fail.push(() => { noUserInfo = true; zeres plugin library How to dowload it? zeres plugin library userInfoBeingRequested = false; }); } } else { userInfoBeingRequested = false; verifyProfilePicture(); } } const profIcon = element.getElementsByClassName(classes.avatarSingle)[0]; profIcon.addEventListener('click', () => { zeres plugin library How to use it? zeres plugin library if (isBot) return this.showToast('User is a bot, this action is not possible on a bot.', { type: 'error', timeout: 5000 }); if (userInfoBeingRequested) return this.showToast('Please wait, user profile is being requested', { type: 'info', timeout: 5000 }); if (noUserInfo) return this.showToast('Could not get user info!', { type: 'error' }); this.scrollPosition = document.getElementById(this.style.menuMessages).parentElement.parentElement.parentElement.scrollTop; ZeresPluginLibrary.Popouts.showUserPopout(profIcon, author); }); profIcon.addEventListener('contextmenu', e => { if (isBot) return this.showToast('User is a bot, this action is not possible on a bot.', { type: 'error', timeout: 5000 }); if (userInfoBeingRequested) return this.showToast('Please wait, user profile is being requested', { type: 'info', timeout: 5000 }); if (noUserInfo) return this.showToast('Could not get user info! You can only delete or copy to clipboard!', { timeout: 5000 }); zeres plugin library How to get it? zeres plugin library ZeresPluginLibrary.WebpackModules.getByProps('openUserContextMenu').openUserContextMenu(e, author, channel || this.menu.randomValidChannel); }); const nameLink = element.getElementsByClassName(classes.username.split(/ /g)[0])[0]; nameLink.addEventListener('click', () => { if (isBot) return this.showToast('User is a bot, this action is not possible on a bot.', { type: 'error', timeout: 5000 }); if (userInfoBeingRequested) return this.showToast('Please wait, user profile is being requested', { type: 'info', timeout: 5000 }); if (noUserInfo) return this.showToast('Could not get user info!', { type: 'error' }); this.scrollPosition = document.getElementById(this.style.menuMessages).parentElement.parentElement.parentElement.scrollTop; // todo: turn this into a function ZeresPluginLibrary.Popouts.showUserPopout(nameLink, author); }); zeres plugin library PasteShr zeres plugin library nameLink.addEventListener('contextmenu', e => { if (isBot) return this.showToast('User is a bot, this action is not possible on a bot.', { type: 'error', timeout: 5000 }); if (userInfoBeingRequested) return this.showToast('Please wait, user profile is being requested', { type: 'info', timeout: 5000 }); if (noUserInfo) return this.showToast('Could not get user info! You can only delete or copy to clipboard!', { type: 'error', timeout: 5000 }); ZeresPluginLibrary.WebpackModules.getByProps('openUserContextMenu').openUserContextMenu(e, author, channel || this.menu.randomValidChannel); }); const timestampEl = element.getElementsByClassName(classes.timestampSingle)[0]; timestampEl.addEventListener('contextmenu', e => { const messages = element.querySelectorAll(`div[class] div[class] div .${classes.markupSingle}`); if (!messages.length) return; zeres plugin library How to get it for free? zeres plugin library const messageIds = []; for (let i = 0; i < messages.length; i++) if (messages[i] && messages[i].messageId) messageIds.push(messages[i].messageId); if (!messageIds.length) return; const menu = new ZeresPluginLibrary.ContextMenu.Menu(); const remove = new ZeresPluginLibrary.ContextMenu.TextItem('Remove Group From Log'); const copyMessage = new ZeresPluginLibrary.ContextMenu.TextItem('Copy Formatted Messages'); remove.element.addEventListener('click', () => { menu.removeMenu(); let invalidatedChannelCache = false; for (let msgid of messageIds) { zeres plugin library How to dowload it? zeres plugin library const record = this.messageRecord[msgid]; if (!record) continue; // the hell if ((record.edit_history && !record.edits_hidden) || (record.delete_data && !record.delete_data.hidden)) this.invalidateChannelCache((invalidatedChannelCache = record.message.channel_id)); this.deleteMessageFromRecords(msgid); } if (invalidatedChannelCache) this.cacheChannelMessages(invalidatedChannelCache); this.refilterMessages(); // I don't like calling that, maybe figure out a way to animate it collapsing on itself smoothly this.saveData(); }); copyMessage.element.addEventListener('click', () => { zeres plugin library How to get it? zeres plugin library let result = ''; for (let msgid of messageIds) { const record = this.messageRecord[msgid]; if (!record) continue; if (!result.length) result += `> **${record.message.author.username}** | ${this.createTimeStamp(record.message.timestamp, true)}\n`; result += `> ${record.message.content.replace(/\n/g, '\n> ')}\n`; } this.nodeModules.electron.clipboard.writeText(result); this.showToast('Copied!', { type: 'success' }); menu.removeMenu(); zeres plugin library How to get it for free? zeres plugin library }); menu.addItems(copyMessage, remove); menu.element.style.position = 'absolute'; menu.element.style.zIndex = '99999'; for (let ch of menu.element.children) ch.addClass('clickable-11uBi- da-clickable'); // HACK menu.show(e.clientX, e.clientY); }); timestampEl.addEventListener('click', e => { if (!this.menu.deleteKeyDown) return; const messages = element.querySelectorAll(`div[class] div[class] div .${classes.markupSingle}`); zeres plugin library PasteShr zeres plugin library if (!messages.length) return; const messageIds = []; for (let i = 0; i < messages.length; i++) if (messages[i] && messages[i].messageId) messageIds.push(messages[i].messageId); if (!messageIds.length) return; let invalidatedChannelCache = false; for (let msgid of messageIds) { const record = this.messageRecord[msgid]; if (!record) continue; // the hell if ((record.edit_history && !record.edits_hidden) || (record.delete_data && !record.delete_data.hidden)) this.invalidateChannelCache((invalidatedChannelCache = record.message.channel_id)); this.deleteMessageFromRecords(msgid); zeres plugin library How to get it? zeres plugin library } if (invalidatedChannelCache) this.cacheChannelMessages(invalidatedChannelCache); this.refilterMessages(); // I don't like calling that, maybe figure out a way to animate it collapsing on itself smoothly this.saveData(); }); const messageContext = e => { let target = e.target; if ((!target.classList.contains(this.classes.containerBounded) && !target.classList.contains('mention')) || (target.tagName == 'DIV' && target.classList.contains(ZeresPluginLibrary.WebpackModules.getByProps('imageError').imageError.split(/ /g)[0]))) { let isMarkup = false; let isEdited = false; zeres plugin library How to get it? zeres plugin library let isBadImage = target.tagName == 'DIV' && target.classList == ZeresPluginLibrary.WebpackModules.getByProps('imageError').imageError; if (!isBadImage) { while (!target.classList.contains(this.classes.containerBounded) && !(isMarkup = target.classList.contains(this.classes.markup))) { if (target.classList.contains(this.style.edited)) isEdited = target; target = target.parentElement; } } if (isMarkup || isBadImage) { const messageId = target.messageId; zeres plugin library PasteShr zeres plugin library if (!messageId) return; const record = this.getSavedMessage(messageId); if (!record) return; let editNum = -1; if (isEdited) editNum = isEdited.edit; const menu = new ZeresPluginLibrary.ContextMenu.Menu(); if (channel) { let jump = new ZeresPluginLibrary.ContextMenu.TextItem('Jump to Message'); jump.element.addEventListener('click', () => { this.jumpToMessage(message.channel_id, messageId, message.guild_id); zeres plugin library How to get it for free? zeres plugin library menu.removeMenu(); return; }); menu.addItems(jump); } let remove = new ZeresPluginLibrary.ContextMenu.TextItem('Remove From Log'); let copyId = new ZeresPluginLibrary.ContextMenu.TextItem('Copy Message ID'); remove.element.addEventListener('click', () => { let invalidatedChannelCache = false; if ((record.edit_history && !record.edits_hidden) || (record.delete_data && !record.delete_data.hidden)) this.invalidateChannelCache((invalidatedChannelCache = record.message.channel_id)); zeres plugin library How to dowload it? zeres plugin library this.deleteMessageFromRecords(messageId); this.refilterMessages(); // I don't like calling that, maybe figure out a way to animate it collapsing on itself smoothly menu.removeMenu(); if (invalidatedChannelCache) this.cacheChannelMessages(invalidatedChannelCache); this.saveData(); }); if (!isBadImage || record.message.content.length) { let copyText = new ZeresPluginLibrary.ContextMenu.TextItem('Copy Text'); let copyMessage = new ZeresPluginLibrary.ContextMenu.TextItem('Copy Formatted Message'); copyText.element.addEventListener('click', () => { zeres plugin library How to get it for free? zeres plugin library this.nodeModules.electron.clipboard.writeText(editNum != -1 ? record.edit_history[editNum].content : record.message.content); this.showToast('Copied!', { type: 'success' }); menu.removeMenu(); }); copyMessage.element.addEventListener('click', () => { const content = editNum != -1 ? record.edit_history[editNum].content : record.message.content; const result = `> **${record.message.author.username}** | ${this.createTimeStamp(record.message.timestamp, true)}\n> ${content.replace(/\n/g, '\n> ')}`; this.nodeModules.electron.clipboard.writeText(result); this.showToast('Copied!', { type: 'success' }); menu.removeMenu(); zeres plugin library How to dowload it? zeres plugin library }); menu.addItems(copyText, copyMessage); } copyId.element.addEventListener('click', () => { this.nodeModules.electron.clipboard.writeText(messageId); // todo: store electron or writeText somewhere? this.showToast('Copied!', { type: 'success' }); menu.removeMenu(); }); if (record.delete_data && record.delete_data.hidden) { let unhideDelete = new ZeresPluginLibrary.ContextMenu.TextItem('Unhide Deleted Message'); zeres plugin library PasteShr zeres plugin library unhideDelete.element.addEventListener('click', () => { record.delete_data.hidden = false; this.invalidateChannelCache(record.message.channel_id); // good idea? this.cacheChannelMessages(record.message.channel_id); this.saveData(); this.showToast('Unhidden!', { type: 'success' }); menu.removeMenu(); }); menu.addItems(unhideDelete); } zeres plugin library PasteShr zeres plugin library if (record.edit_history) { if (editNum != -1) { let deleteEdit = new ZeresPluginLibrary.ContextMenu.TextItem('Delete Edit'); deleteEdit.element.addEventListener('click', () => { this.deleteEditedMessageFromRecord(messageId, editNum); this.refilterMessages(); // I don't like calling that, maybe figure out a way to animate it collapsing on itself smoothly this.showToast('Deleted!', { type: 'success' }); menu.removeMenu(); }); menu.addItems(deleteEdit); zeres plugin library PasteShr zeres plugin library } if (record.edits_hidden) { let unhideEdits = new ZeresPluginLibrary.ContextMenu.TextItem('Unhide Edits'); unhideEdits.element.addEventListener('click', () => { record.edits_hidden = false; this.saveData(); this.showToast('Unhidden!', { type: 'success' }); menu.removeMenu(); }); menu.addItems(unhideEdits); zeres plugin library How to dowload it? zeres plugin library } } menu.addItems(remove, copyId); menu.element.style.position = 'absolute'; menu.element.style.zIndex = '99999'; for (let ch of menu.element.children) ch.addClass('clickable-11uBi- da-clickable'); // HACK menu.show(e.clientX, e.clientY); return; } } zeres plugin library How to dowload it? zeres plugin library }; element.querySelector(classes.message).addEventListener('contextmenu', e => messageContext(e)); element.querySelector(classes.message).addEventListener('click', e => { if (!this.menu.deleteKeyDown) return; let target = e.target; if (!target.classList.contains(this.classes.containerBounded)) { let isMarkup = false; let isEdited = false; let isBadImage = target.tagName == 'DIV' && target.classList == ZeresPluginLibrary.WebpackModules.getByProps('imageError').imageError; if (!isBadImage) { zeres plugin library How to get it for free? zeres plugin library while (!target.classList.contains(this.classes.containerBounded) && !(isMarkup = target.classList.contains(this.classes.markup))) { if (target.classList.contains(this.style.edited)) isEdited = target; target = target.parentElement; } } if (!isMarkup && !isBadImage) return; const messageId = target.messageId; if (!messageId) return; const record = this.messageRecord[messageId]; if (!record) return; zeres plugin library PasteShr zeres plugin library this.invalidateChannelCache(record.message.channel_id); // good idea? this.cacheChannelMessages(record.message.channel_id); if (isEdited) { this.deleteEditedMessageFromRecord(messageId, isEdited.edit); } else { this.deleteMessageFromRecords(messageId); } this.refilterMessages(); // I don't like calling that, maybe figure out a way to animate it collapsing on itself smoothly this.saveData(); } zeres plugin library How to get it? zeres plugin library }); return element; } populateParent(parent, messages) { let lastMessage; let lastType; /* unused */ let messageGroup; const registerMentions = markup => { const mentions = markup.getElementsByClassName('mention'); for (let mention of mentions) { zeres plugin library How to use it? zeres plugin library mention.addEventListener('click', () => { this.scrollPosition = document.getElementById(this.style.menuMessages).parentElement.parentElement.parentElement.scrollTop; }); } }; const populate = i => { try { // todo: maybe make the text red if it's deleted? const messageId = messages[i]; const record = this.getSavedMessage(messageId); zeres plugin library How to use it? zeres plugin library const message = record ? record.message : this.getMessageAny(messageId); if (!message) return; // todo: get type and use it if (!messageGroup /* || !lastType */ || !lastMessage || lastMessage.channel_id != message.channel_id || lastMessage.author.id != message.author.id || new Date(message.timestamp).getDate() !== new Date(lastMessage.timestamp).getDate() || (message.attachments.length && message.content.length)) { messageGroup = this.createMessageGroup(message); } lastMessage = message; const messageContent = messageGroup.getElementsByClassName(this.multiClasses.message.cozy.content.split(/ /g)[0])[0]; const div = document.createElement('div'); const divParent = document.createElement('div'); zeres plugin library How to use it? zeres plugin library div.className = this.multiClasses.markup; div.messageId = messageId; if (record && record.edit_history) { div.classList.add(this.style.edited); for (let ii = 0; ii < record.edit_history.length; ii++) { const hist = record.edit_history[ii]; const editedMarkup = this.formatMarkup(hist.content, message.channel_id).firstChild; editedMarkup.insertAdjacentHTML('beforeend', ``); // TODO, change this editedMarkup.tooltip = new ZeresPluginLibrary.EmulatedTooltip(editedMarkup, 'Edited at ' + (typeof hist.time === 'string' ? hist.time : this.createTimeStamp(hist.time)), { side: 'left' }); editedMarkup.classList.add(this.style.edited); zeres plugin library How to get it? zeres plugin library editedMarkup.edit = ii; registerMentions(editedMarkup); div.appendChild(editedMarkup); } } const contentMarkup = this.formatMarkup(message.content, message.channel_id).firstChild; contentMarkup.messageId = message.id; registerMentions(contentMarkup); div.appendChild(contentMarkup); if (!record) { zeres plugin library How to use it? zeres plugin library const channel = this.tools.getChannel(message.channel_id); const guild = this.tools.getServer(channel && channel.guild_id); divParent.addEventListener('click', () => this.jumpToMessage(message.channel_id, message.id, guild && guild.id)); } divParent.appendChild(div); // todo, embeds // how do I do embeds? // why don't attachments show for sent messages? what's up with that? if (message.attachments.length) { zeres plugin library How to dowload it? zeres plugin library // const attachmentsContent = this.parseHTML(`
`); const attemptToUseCachedImage = (attachmentId, attachmentIdx, hidden) => { const cachedImage = this.imageCacheRecord[attachmentId]; if (!cachedImage) return false; const img = document.createElement('img'); img.classList = ZeresPluginLibrary.WebpackModules.getByProps('clickable').clickable; /* img.classList = ZeresPluginLibrary.WebpackModules.getByProps('clickable').clickable; */ img.messageId = messageId; img.idx = attachmentIdx; img.id = attachmentId; // USED FOR FINDING THE IMAGE THRU CONTEXT MENUS zeres plugin library How to use it? zeres plugin library if (hidden) { img.src = `https://i.clouds.tf/q2vy/r8q6.png#${record.message.channel_id},${img.id}`; img.width = 200; } else { img.src = cachedImage.thumbnail; // has channel and attachment id embedded img.width = 256; } img.addEventListener('click', e => { if (!this.menu.deleteKeyDown) return this.nodeModules.electron.shell.openExternal(`file://${this.imageCacheDir}/${attachmentId}${cachedImage.extension}`); this.deleteMessageFromRecords(messageId); zeres plugin library How to get it? zeres plugin library this.refilterMessages(); // I don't like calling that, maybe figure out a way to animate it collapsing on itself smoothly this.saveData(); }); divParent.appendChild(img); return true; }; const handleCreateImage = (attachment, idx) => { if (attachment.url == 'ERROR') { if (attemptToUseCachedImage(attachment.id, idx, attachment.hidden)) return; const imageErrorDiv = document.createElement('div'); zeres plugin library How to get it for free? zeres plugin library imageErrorDiv.classList = ZeresPluginLibrary.WebpackModules.getByProps('imageError').imageError; imageErrorDiv.messageId = messageId; divParent.appendChild(imageErrorDiv); } else { if (!this.isImage(attachment.url)) return; // bruh const img = document.createElement('img'); img.classList = ZeresPluginLibrary.WebpackModules.getByProps('clickable').clickable; img.messageId = messageId; img.id = attachment.id; // USED FOR FINDING THE IMAGE THRU CONTEXT MENUS img.idx = idx; zeres plugin library PasteShr zeres plugin library if (attachment.hidden) { img.src = `https://i.clouds.tf/q2vy/r8q6.png#${record.message.channel_id},${img.id}`; img.width = 200; } else { img.src = attachment.url; img.width = this.clamp(attachment.width, 200, 650); } // img.style.minHeight = '104px'; // bruh? if (record) { img.addEventListener('click', () => { zeres plugin library How to get it? zeres plugin library if (this.menu.deleteKeyDown) { this.deleteMessageFromRecords(messageId); this.refilterMessages(); // I don't like calling that, maybe figure out a way to animate it collapsing on itself smoothly this.saveData(); return; } this.scrollPosition = document.getElementById(this.style.menuMessages).parentElement.parentElement.parentElement.scrollTop; this.createModal( { src: attachment.url + '?ML2=true', // self identify zeres plugin library PasteShr zeres plugin library placeholder: attachment.url, // cute image here original: attachment.url, width: attachment.width, height: attachment.height, onClickUntrusted: e => e.openHref() }, true ); }); } zeres plugin library How to get it? zeres plugin library img.onerror = () => { img.src = '/assets/e0c782560fd96acd7f01fda1f8c6ff24.svg'; img.width = 200; if (record) { this.nodeModules.request.head(attachment.url, (err, res) => { if (err || res.statusCode != 404) return; record.message.attachments[idx].url = 'ERROR'; attemptToUseCachedImage(attachment.id, idx, attachment.hidden); }); } zeres plugin library PasteShr zeres plugin library }; divParent.appendChild(img); } }; for (let ii = 0; ii < message.attachments.length; ii++) handleCreateImage(message.attachments[ii], ii); } if (message.embeds && message.embeds.length) { const ddiv = document.createElement('div'); // TODO: optimize ddiv.className = ZLibrary.WebpackModules.getByProps('containerCozy', 'gifFavoriteButton').containerCozy; zeres plugin library How to get it for free? zeres plugin library for (const embed of message.embeds) { const embedBase = { GIFVComponent: ZLibrary.WebpackModules.getByDisplayName('LazyGIFV'), ImageComponent: ZLibrary.WebpackModules.getByDisplayName('LazyImageZoomable'), LinkComponent: ZLibrary.WebpackModules.getByDisplayName('MaskedLink'), VideoComponent: ZLibrary.WebpackModules.getByDisplayName('LazyVideo'), allowFullScreen: true, autoPlayGif: true, backgroundOpacity: '', className: ZLibrary.WebpackModules.getByProps('embedWrapper', 'gifFavoriteButton').embedWrapper, zeres plugin library PasteShr zeres plugin library embed: ZLibrary.WebpackModules.getByProps('sanitizeEmbed').sanitizeEmbed(message.channel_id, message.id, embed), hideMedia: false, inlineGIFV: true, maxMediaHeight: 300, maxMediaWidth: 400, maxThumbnailHeight: 80, maxThumbnailWidth: 80, suppressEmbed: false }; ZLibrary.DiscordModules.ReactDOM.render(ZLibrary.DiscordModules.React.createElement(ZLibrary.WebpackModules.getByDisplayName('Embed'), embedBase), ddiv); zeres plugin library PasteShr zeres plugin library } divParent.appendChild(ddiv); } if (divParent.childElementCount < 2 && !message.content.length) return; // don't bother messageContent.appendChild(divParent); parent.appendChild(messageGroup); } catch (err) { ZeresPluginLibrary.Logger.stacktrace(this.getName(), 'Error in populateParent', err); } }; zeres plugin library How to dowload it? zeres plugin library let i = 0; const addMore = () => { for (let added = 0; i < messages.length && (added < this.settings.renderCap || (this.menu.shownMessages != -1 && i < this.menu.shownMessages)); i++, added++) populate(i); handleMoreMessages(); this.menu.shownMessages = i; }; const handleMoreMessages = () => { if (i < messages.length) { const div = document.createElement('div'); const moreButton = this.createButton('LOAD MORE', function() { zeres plugin library PasteShr zeres plugin library this.parentElement.remove(); addMore(); }); moreButton.style.width = '100%'; moreButton.style.marginBottom = '20px'; div.appendChild(moreButton); parent.appendChild(div); } }; zeres plugin library PasteShr zeres plugin library if (this.settings.renderCap) addMore(); else for (; i < messages.length; i++) populate(i); this.processUserRequestQueue(); } // >>-|| FILTERING ||-<< sortMessagesByAge(map) { // sort direction: new - old map.sort((a, b) => { const recordA = this.messageRecord[a]; const recordB = this.messageRecord[b]; zeres plugin library How to dowload it? zeres plugin library if (!recordA || !recordB) return 0; let timeA = new Date(recordA.message.timestamp).getTime(); let timeB = new Date(recordB.message.timestamp).getTime(); if (recordA.edit_history && typeof recordA.edit_history[recordA.edit_history.length - 1].time !== 'string') timeA = recordA.edit_history[recordA.edit_history.length - 1].time; if (recordB.edit_history && typeof recordB.edit_history[recordB.edit_history.length - 1].time !== 'string') timeB = recordB.edit_history[recordB.edit_history.length - 1].time; if (recordA.delete_data && recordA.delete_data.time) timeA = recordA.delete_data.time; if (recordB.delete_data && recordB.delete_data.time) timeB = recordB.delete_data.time; return parseInt(timeB) - parseInt(timeA); }); } zeres plugin library How to dowload it? zeres plugin library getFilteredMessages() { let messages = []; const pushIdsIntoMessages = map => { for (let channel in map) { for (let messageIdIDX in map[channel]) { messages.push(map[channel][messageIdIDX]); } } }; zeres plugin library How to get it? zeres plugin library const checkIsMentioned = map => { for (let channel in map) { for (let messageIdIDX in map[channel]) { const messageId = map[channel][messageIdIDX]; const record = this.getSavedMessage(messageId); if (!record) continue; if (record.ghost_pinged) { messages.push(messageId); } } zeres plugin library How to dowload it? zeres plugin library } }; if (this.menu.selectedTab == 'sent') { for (let i of this.cachedMessageRecord) { messages.push(i.id); } } if (this.menu.selectedTab == 'edited') pushIdsIntoMessages(this.editedMessageRecord); if (this.menu.selectedTab == 'deleted') pushIdsIntoMessages(this.deletedMessageRecord); zeres plugin library PasteShr zeres plugin library if (this.menu.selectedTab == 'purged') pushIdsIntoMessages(this.purgedMessageRecord); if (this.menu.selectedTab == 'ghostpings') { checkIsMentioned(this.deletedMessageRecord); checkIsMentioned(this.editedMessageRecord); checkIsMentioned(this.purgedMessageRecord); } const filters = this.menu.filter.split(','); for (let i = 0; i < filters.length; i++) { zeres plugin library How to use it? zeres plugin library const split = filters[i].split(':'); if (split.length < 2) continue; const filterType = split[0].trim().toLowerCase(); const filter = split[1].trim().toLowerCase(); if (filterType == 'server' || filterType == 'guild') messages = messages.filter(x => { const message = this.getMessageAny(x); if (!message) return false; zeres plugin library How to use it? zeres plugin library const channel = this.tools.getChannel(message.channel_id); const guild = this.tools.getServer(message.guild_id || (channel && channel.guild_id)); return (message.guild_id || (channel && channel.guild_id)) == filter || (guild && guild.name.toLowerCase().includes(filter.toLowerCase())); }); if (filterType == 'channel') messages = messages.filter(x => { const message = this.getMessageAny(x); if (!message) return false; const channel = this.tools.getChannel(message.channel_id); zeres plugin library PasteShr zeres plugin library return message.channel_id == filter || (channel && channel.name.toLowerCase().includes(filter.replace('#', '').toLowerCase())); }); if (filterType == 'message' || filterType == 'content') messages = messages.filter(x => { const message = this.getMessageAny(x); return x == filter || (message && message.content.toLowerCase().includes(filter.toLowerCase())); }); if (filterType == 'user') zeres plugin library How to get it for free? zeres plugin library messages = messages.filter(x => { const message = this.getMessageAny(x); if (!message) return false; const channel = this.tools.getChannel(message.channel_id); const member = ZeresPluginLibrary.DiscordModules.GuildMemberStore.getMember(message.guild_id || (channel && channel.guild_id), message.author.id); return message.author.id == filter || message.author.username.toLowerCase().includes(filter.toLowerCase()) || (member && member.nick && member.nick.toLowerCase().includes(filter.toLowerCase())); }); } if (this.menu.selectedTab != 'sent') { zeres plugin library How to use it? zeres plugin library this.sortMessagesByAge(messages); if (this.settings.reverseOrder) messages.reverse(); // this gave me a virtual headache } else if (!this.settings.reverseOrder) messages.reverse(); // this gave me a virtual headache return messages; } // >>-|| REPOPULATE ||-<< refilterMessages() { const messagesDIV = document.getElementById(this.style.menuMessages); const original = messagesDIV.style.display; zeres plugin library How to use it? zeres plugin library messagesDIV.style.display = 'none'; while (messagesDIV.firstChild) messagesDIV.removeChild(messagesDIV.firstChild); this.menu.messages = this.getFilteredMessages(); this.populateParent(messagesDIV, this.menu.messages); messagesDIV.style.display = original; } // >>-|| HEADER ||-<< openTab(tab) { const tabBar = document.getElementById(this.style.menuTabBar); if (!tabBar) return this.showToast(`Error switching to tab ${tab}!`, { type: 'error', timeout: 3000 }); zeres plugin library How to use it? zeres plugin library tabBar.querySelector(`.${this.style.tabSelected}`).classList.remove(this.style.tabSelected); tabBar.querySelector('#' + tab).classList.add(this.style.tabSelected); this.menu.selectedTab = tab; setTimeout(() => this.refilterMessages(), 0); } createHeader() { const classes = this.createHeader.classes; const createTab = (title, id) => { const tab = this.parseHTML(`
${title}
`); tab.addEventListener('mousedown', () => this.openTab(id)); zeres plugin library How to get it for free? zeres plugin library return tab; }; const tabBar = this.parseHTML(`
`); const tabs = tabBar.getElementsByClassName(classes.tabBarSingle)[0]; tabs.appendChild(createTab('Sent', 'sent')); tabs.appendChild(createTab('Deleted', 'deleted')); tabs.appendChild(createTab('Edited', 'edited')); tabs.appendChild(createTab('Purged', 'purged')); tabs.appendChild(createTab('Ghost pings', 'ghostpings')); const measureWidth = el => { zeres plugin library How to use it? zeres plugin library el = el.cloneNode(true); el.style.visibility = 'hidden'; el.style.position = 'absolute'; document.body.appendChild(el); let result = el.getBoundingClientRect().width; el.remove(); return result; }; zeres plugin library How to get it? zeres plugin library const totalWidth = measureWidth(tabs) * 2 - 20; const wantedTabWidth = totalWidth / tabs.childElementCount; const wantedTabMargin = wantedTabWidth / 2; let tab = tabs.firstElementChild; while (tab) { tab.style.marginRight = '0px'; const tabWidth = measureWidth(tab); if (tabWidth > wantedTabWidth) { ZeresPluginLibrary.Logger.err(this.getName(), `What the shit? Tab ${tab} is massive!!`); tab = tab.nextElementSibling; zeres plugin library PasteShr zeres plugin library continue; } tab.style.paddingRight = tab.style.paddingLeft = `${wantedTabMargin - tabWidth / 2}px`; tab = tab.nextElementSibling; } tabBar.style.marginRight = '20px'; return tabBar; } createTextBox() { const classes = this.createTextBox.classes; zeres plugin library How to dowload it? zeres plugin library let textBox = this.parseHTML( `
` ); const inputEl = textBox.getElementsByTagName('input')[0]; inputEl.addEventListener('focusout', e => { DOMTokenList.prototype.remove.apply(e.target.parentElement.parentElement.classList, classes.focused); }); inputEl.addEventListener('focusin', e => { DOMTokenList.prototype.add.apply(e.target.parentElement.parentElement.classList, classes.focused); }); zeres plugin library How to get it? zeres plugin library const onUpdate = e => { if (this.menu.filterSetTimeout) clearTimeout(this.menu.filterSetTimeout); this.menu.filter = inputEl.value; const filters = this.menu.filter.split(','); // console.log(filters); if (!filters[0].length) return this.refilterMessages(); this.menu.filterSetTimeout = setTimeout(() => { if (filters[0].length) { for (let i = 0; i < filters.length; i++) { const split = filters[i].split(':'); zeres plugin library PasteShr zeres plugin library if (split.length < 2) return; } } this.refilterMessages(); }, 200); }; inputEl.addEventListener('keyup', onUpdate); // maybe I can actually use keydown but it didn't work for me inputEl.addEventListener('paste', onUpdate); const helpButton = textBox.getElementsByClassName(classes.questionMarkSingle)[0]; helpButton.addEventListener('click', () => { zeres plugin library How to get it? zeres plugin library this.scrollPosition = document.getElementById(this.style.menuMessages).parentElement.parentElement.parentElement.scrollTop; const extraHelp = this.createButton('Logger help', () => this.showLoggerHelpModal()); this.createModal({ confirmText: 'OK', header: 'Filter help', size: ZeresPluginLibrary.Modals.ModalSizes.LARGE, children: [ ZeresPluginLibrary.ReactTools.createWrappedElement([ this.parseHTML( `
"server: " - Filter results with the specified server name or id. zeres plugin library How to get it? zeres plugin library "channel: " - Filter results with the specified channel name or id. "user: " - Filter results with the specified username, nickname or userid. "message: " or "content: " - Filter results with the specified message content. Separate the search tags with commas. Example: server: tom's bd stuff, message: heck Shortcut help: zeres plugin library How to use it? zeres plugin library "Ctrl + M" (default) - Open message log. "Ctrl + N" (default) - Open message log with selected channel filtered.\n\n
`.replace(/\n/g, '
') ), extraHelp ]) ], red: false }); }); new ZeresPluginLibrary.EmulatedTooltip(helpButton, 'Help!', { side: 'top' }); zeres plugin library How to get it? zeres plugin library return textBox; } // >>-|| MENU MODAL CREATION ||-<< openWindow(type) { if (this.menu.open) { this.menu.scrollPosition = 0; if (type) this.openTab(type); return; } this.menu.open = true; zeres plugin library PasteShr zeres plugin library if (type) this.menu.selectedTab = type; if (!this.menu.selectedTab) this.menu.selectedTab = 'deleted'; const messagesDIV = this.parseHTML(`
`); const viewportHeight = document.getElementById('app-mount').getBoundingClientRect().height; messagesDIV.style.minHeight = viewportHeight * 0.514090909 + 'px'; // hack but ok //messagesDIV.style.display = 'none'; this.createModal( { confirmText: 'Clear log', cancelText: 'Sort direction: ' + (!this.settings.reverseOrder ? 'new - old' : 'old - new'), zeres plugin library How to get it? zeres plugin library header: ZeresPluginLibrary.ReactTools.createWrappedElement([this.createTextBox(), this.createHeader()]), size: ZeresPluginLibrary.Modals.ModalSizes.LARGE, children: [ZeresPluginLibrary.ReactTools.createWrappedElement([messagesDIV])], ml2Data: true }, false, this.style.menu ); let loadAttempts = 0; const loadMessages = () => { zeres plugin library How to get it for free? zeres plugin library loadAttempts++; try { this.refilterMessages(); } catch (e) { if (loadAttempts > 4) { this.showToast(`Couldn't load menu messages! Report this issue to Lighty, error info is in console`, { type: 'error', timeout: 10000 }); ZeresPluginLibrary.Logger.stacktrace(this.getName(), 'Failed loading menu', e); return; } setTimeout(() => loadMessages(), 100); zeres plugin library How to get it for free? zeres plugin library } }; setTimeout(() => loadMessages(), 100); } /* ==================================================-|| END MENU ||-================================================== */ /* ==================================================-|| START CONTEXT MENU ||-================================================== */ handleContextMenu(thisObj, args, returnValue) { if (!returnValue) return returnValue; // console.log(thisObj, args, returnValue); const type = thisObj.props.type; zeres plugin library How to get it? zeres plugin library const newItems = []; const addElement = (label, callback) => { newItems.push( ZeresPluginLibrary.DiscordModules.React.createElement(this.ContextMenuItem, { label: label, action: () => { this.ContextMenuActions.closeContextMenu(); if (callback) callback(); } }) zeres plugin library How to get it for free? zeres plugin library ); }; const handleWhiteBlackList = id => { const whitelistIdx = this.settings.whitelist.findIndex(m => m === id); const blacklistIdx = this.settings.blacklist.findIndex(m => m === id); if (whitelistIdx == -1 && blacklistIdx == -1) { addElement(`Add to Whitelist`, () => { this.settings.whitelist.push(id); this.saveSettings(); zeres plugin library PasteShr zeres plugin library this.showToast('Added!', { type: 'success' }); }); addElement(`Add to Blacklist`, () => { this.settings.blacklist.push(id); this.saveSettings(); this.showToast('Added!', { type: 'success' }); }); } else if (whitelistIdx != -1) { addElement(`Remove From Whitelist`, () => { this.settings.whitelist.splice(whitelistIdx, 1); zeres plugin library How to use it? zeres plugin library this.saveSettings(); this.showToast('Removed!', { type: 'success' }); }); addElement(`Move to Blacklist`, () => { this.settings.whitelist.splice(whitelistIdx, 1); this.settings.blacklist.push(id); this.saveSettings(); this.showToast('Moved!', { type: 'success' }); }); } else { zeres plugin library How to dowload it? zeres plugin library addElement(`Remove From Blacklist`, () => { this.settings.blacklist.splice(blacklistIdx, 1); this.saveSettings(); this.showToast('Removed!', { type: 'success' }); }); addElement(`Move to Whitelist`, () => { this.settings.blacklist.splice(blacklistIdx, 1); this.settings.whitelist.push(id); this.saveSettings(); this.showToast('Moved!', { type: 'success' }); zeres plugin library How to get it? zeres plugin library }); } }; // image has no type property if (!type) { if (!this.menu.open) return; let matched; let isCached = false; if (!thisObj.props.src) return; if (thisObj.props.src.startsWith('data:image/png')) { zeres plugin library How to use it? zeres plugin library const cut = thisObj.props.src.substr(0, 100); matched = cut.match(/;(\d+);(\d+);/); isCached = true; } else { matched = thisObj.props.src.match(/.*ments\/(\d+)\/(\d+)\//); if (!matched) matched = thisObj.props.src.match(/r8q6.png#(\d+),(\d+)/); } if (!matched) return; const channelId = matched[1]; const attachmentId = matched[2]; zeres plugin library How to get it? zeres plugin library const element = document.getElementById(attachmentId); if (!element) return; const attachmentIdx = element.idx; const record = this.getSavedMessage(element.messageId); if (!record) return; const attachmentRecord = this.imageCacheRecord[attachmentId]; addElement('Save to Folder', () => { const { dialog } = this.nodeModules.electron.remote; const dir = dialog.showSaveDialog({ defaultPath: record.message.attachments[attachmentIdx].filename zeres plugin library PasteShr zeres plugin library }); if (!dir) return; const attemptToUseCached = () => { const srcFile = `${this.imageCacheDir}/${attachmentId}${(attachmentRecord && attachmentRecord.extension) || 'fuck'}`; if (!attachmentRecord || !this.nodeModules.fs.existsSync(srcFile)) return this.showToast('Image does not exist locally!', { type: 'error', timeout: 5000 }); this.nodeModules.fs.copyFileSync(srcFile, dir); this.showToast('Saved!', { type: 'success' }); }; if (isCached) { attemptToUseCached(); zeres plugin library PasteShr zeres plugin library } else { const req = this.nodeModules.request(record.message.attachments[attachmentIdx].url); req.on('response', res => { if (res.statusCode == 200) { req .pipe(this.nodeModules.fs.createWriteStream(dir)) .on('finish', () => this.showToast('Saved!', { type: 'success' })) .on('error', () => this.showToast('Failed to save! No permissions.', { type: 'error', timeout: 5000 })); } else if (res.statusCode == 404) { this.showToast('Image does not exist! Attempting to use local image cache.', { type: 'error' }); zeres plugin library PasteShr zeres plugin library attemptToUseCached(); } else { this.showToast('Unknown error, attempting to use local image cache.', { type: 'error' }); attemptToUseCached(); } }); } }); addElement('Copy to Clipboard', () => { const { clipboard, nativeImage } = this.nodeModules.electron; zeres plugin library How to dowload it? zeres plugin library const attemptToUseCached = () => { const srcFile = `${this.imageCacheDir}/${attachmentId}${(attachmentRecord && attachmentRecord.extension) || 'fuck'}`; if (!attachmentRecord || !this.nodeModules.fs.existsSync(srcFile)) return this.showToast('Image does not exist locally!', { type: 'error', timeout: 5000 }); clipboard.write({ image: srcFile }); this.showToast('Copied!', { type: 'success' }); }; if (isCached) { attemptToUseCached(); } else { const path = require('path'); zeres plugin library How to get it? zeres plugin library const process = require('process'); // ImageToClipboard by Zerebos this.nodeModules.request({ url: record.message.attachments[attachmentIdx].url, encoding: null }, (error, response, buffer) => { if (error || response.statusCode != 200) { this.showToast('Failed to copy. Image may not exist. Attempting to use local image cache.', { type: 'error' }); attemptToUseCached(); return; } if (process.platform === 'win32' || process.platform === 'darwin') { clipboard.write({ image: nativeImage.createFromBuffer(buffer) }); zeres plugin library PasteShr zeres plugin library } else { const file = path.join(process.env.HOME, 'ml2temp.png'); this.nodeModules.fs.writeFileSync(file, buffer, { encoding: null }); clipboard.write({ image: file }); this.nodeModules.fs.unlinkSync(file); } this.showToast('Copied!', { type: 'success' }); }); } }); zeres plugin library PasteShr zeres plugin library addElement('Jump to Message', () => { this.jumpToMessage(channelId, element.messageId, record.message.guild_id); }); if (record.delete_data && record.delete_data.hidden) { addElement('Unhide Deleted Message', () => { record.delete_data.hidden = false; this.invalidateChannelCache(record.message.channel_id); // good idea? this.cacheChannelMessages(record.message.channel_id); this.saveData(); this.showToast('Unhidden!', { type: 'success' }); zeres plugin library PasteShr zeres plugin library }); } if (record.edit_history && record.edits_hidden) { addElement('Unhide Deleted Message', () => { record.edits_hidden = false; this.invalidateChannelCache(record.message.channel_id); // good idea? this.cacheChannelMessages(record.message.channel_id); this.saveData(); this.showToast('Unhidden!', { type: 'success' }); }); zeres plugin library How to use it? zeres plugin library } addElement('Remove From Log', () => { let invalidatedChannelCache = false; if ((record.edit_history && !record.edits_hidden) || record.delete_data) this.invalidateChannelCache((invalidatedChannelCache = record.message.channel_id)); this.deleteMessageFromRecords(element.messageId); this.refilterMessages(); // I don't like calling that, maybe figure out a way to animate it collapsing on itself smoothly if (invalidatedChannelCache) this.cacheChannelMessages(invalidatedChannelCache); this.saveData(); }); if (!thisObj.props.src.startsWith('https://i.clouds.tf/q2vy/r8q6.png')) { zeres plugin library PasteShr zeres plugin library addElement('Hide Image From Log', () => { record.message.attachments[attachmentIdx].hidden = true; element.src = `https://i.clouds.tf/q2vy/r8q6.png#${channelId},${attachmentId}`; element.width = 200; }); } else { addElement('Unhide Image From Log', () => { record.message.attachments[attachmentIdx].hidden = false; element.src = isCached ? attachmentRecord && attachmentRecord.thumbnail : record.message.attachments[attachmentIdx].url; element.width = isCached ? 256 : this.clamp(record.message.attachments[attachmentIdx].width, 200, 650); zeres plugin library How to use it? zeres plugin library }); } } else if (type == 'MESSAGE_MAIN') { addElement('Open Logs', () => this.openWindow()); const messageId = thisObj.props.message.id; const channelId = thisObj.props.channel.id; const record = this.messageRecord[messageId]; if (record) { /* addElement('Show in menu', () => { zeres plugin library How to get it? zeres plugin library this.menu.filter = `message:${messageId}`; this.openWindow(); }); */ if (record.delete_data) { const options = returnValue.props.children.find(m => m.props.children && m.props.children.length > 5); options.props.children.splice(0, options.props.children.length); addElement('Hide Deleted Message', () => { ZeresPluginLibrary.WebpackModules.find(m => m.dispatch).dispatch({ type: 'MESSAGE_DELETE', id: messageId, zeres plugin library How to get it? zeres plugin library channelId: channelId, ML2: true // ignore ourselves lol, it's already deleted // on a side note, probably does nothing if we don't ignore }); this.showToast('Hidden!', { type: 'success' }); record.delete_data.hidden = true; this.saveData(); }); let target = thisObj.props.target; if (target) { zeres plugin library PasteShr zeres plugin library while (target && target.className.indexOf(this.style.deleted) === -1) target = target.parentElement; if (target) { addElement('Remove Deleted Tint', () => { target.isDeleted = true; target.classList.remove(this.style.deleted); this.showToast('Removed!', { type: 'success' }); }); } } } zeres plugin library How to get it? zeres plugin library if (record.edit_history) { if (record.edits_hidden) { addElement('Unhide Edits', () => { record.edits_hidden = false; this.saveData(); }); } else { let target = thisObj.props.target; if (!target) return; while (target.className.indexOf(this.style.edited) === -1) { zeres plugin library How to get it for free? zeres plugin library target = target.parentElement; if (!target) return; } const parent = target.parentElement; const editNum = target.firstChild.editNum; if (typeof editNum === 'number') { addElement('Delete Edit', () => { target.remove(); if (parent.childElementCount === 1) { const editedTag = document.createElement('time'); zeres plugin library How to get it? zeres plugin library editedTag.className = this.multiClasses.edited; editedTag.innerText = '(edited)'; parent.firstChild.firstChild.appendChild(editedTag); } this.deleteEditedMessageFromRecord(messageId, editNum); }); } addElement('Hide Edits', () => { record.edits_hidden = true; this.saveData(); zeres plugin library PasteShr zeres plugin library }); } } } } else if (type == 'GUILD_ICON_BAR') { addElement('Open Log For Guild', () => { this.menu.filter = `server:${thisObj.props.guild.id}`; this.openWindow(); }); handleWhiteBlackList(thisObj.props.guild.id); zeres plugin library How to dowload it? zeres plugin library } else if (type == 'CHANNEL_LIST_TEXT') { addElement('Open Log For Channel', () => { this.menu.filter = `channel:${thisObj.props.channel.id}`; this.openWindow(); }); handleWhiteBlackList(thisObj.props.channel.id); } else if (type == 'USER_PRIVATE_CHANNELS_MESSAGE' || type == 'USER_PRIVATE_CHANNELS' || type == 'USER_CHANNEL_MESSAGE') { if (!this.menu.open) { addElement('Open Logs', () => this.openWindow()); addElement('Open Log For User', () => { zeres plugin library How to get it? zeres plugin library this.menu.filter = `user:${thisObj.props.user.id}`; this.openWindow(); }); addElement(`Open Log For ${type == 'USER_CHANNEL_MESSAGE' ? 'Channel' : 'DM'}`, () => { this.menu.filter = `channel:${thisObj.props.channelId}`; this.openWindow(); }); } if (type != 'USER_CHANNEL_MESSAGE') handleWhiteBlackList(thisObj.props.channelId); returnValue.props.children.props.children.props.children.push( zeres plugin library How to dowload it? zeres plugin library ZeresPluginLibrary.DiscordModules.React.createElement(this.ContextMenuGroup, { children: [ZeresPluginLibrary.DiscordModules.React.createElement(this.SubMenuItem, { label: 'Message Logger', render: newItems, invertChildY: true })] }) ); return; } if (!newItems.length) return returnValue; returnValue.props.children.push( ZeresPluginLibrary.DiscordModules.React.createElement(this.ContextMenuGroup, { children: [ZeresPluginLibrary.DiscordModules.React.createElement(this.SubMenuItem, { label: 'Message Logger', render: newItems, invertChildY: true })] zeres plugin library PasteShr zeres plugin library }) ); } /* ==================================================-|| END CONTEXT MENU ||-================================================== */ } /*@end @*/ zeres plugin library