1Lighty-BetterDiscordPlugins/Plugins/SaveToRedux/SaveToRedux.plugin.js

1195 lines
54 KiB
JavaScript
Raw Normal View History

2019-12-21 20:35:10 +01:00
//META{"name":"SaveToRedux","source":"https://github.com/1Lighty/BetterDiscordPlugins/blob/master/Plugins/SaveToRedux/SaveToRedux.plugin.js","website":"https://1lighty.github.io/BetterDiscordStuff/?plugin=SaveToRedux"}*//
/*@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\'ve mistakenly tried to run me directly. \n(Don\'t do that!)', 0, 'I\'m a plugin for BetterDiscord', 0x30);
if (fs.GetParentFolderName(pathSelf) === fs.GetAbsolutePathName(pathPlugins)) {
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();
@else@*/
/*
2020-01-09 20:16:01 +01:00
* Copyright © 2019-2020, _Lighty_
2019-12-21 20:35:10 +01:00
* All rights reserved.
* Code may not be redistributed, modified or otherwise taken without explicit permission.
*/
var SaveToRedux = (() => {
/* Setup */
const config = {
main: 'index.js',
info: {
name: 'SaveToRedux',
authors: [
{
name: 'Lighty',
discord_id: '239513071272329217',
github_username: 'LightyPon',
twitter_username: ''
}
],
2020-02-27 21:04:39 +01:00
version: '2.0.10',
2019-12-21 20:35:10 +01:00
description: 'Allows you to save images, videos, profile icons, server icons, reactions, emotes and custom status emotes to any folder quickly.',
github: 'https://github.com/1Lighty',
github_raw: 'https://raw.githubusercontent.com/1Lighty/BetterDiscordPlugins/master/Plugins/SaveToRedux/SaveToRedux.plugin.js'
},
changelog: [
{
2020-02-27 21:04:39 +01:00
title: 'heck',
type: 'added',
items: ['Fixed the append random option when a file conflicted not working properly.', "Most of the changes are under the hood and functionally don't make too much of a difference.", 'Saving with Save As... or browsing for a folder no longer freezes Discord.', 'In the event the plugin cannot start, it will warn you that it failed to start.']
2019-12-21 20:35:10 +01:00
}
],
defaultConfig: [
{
type: 'category',
id: 'saveOptions',
name: 'File save settings',
collapsible: true,
shown: false,
settings: [
{
name: 'Filename preview',
type: 'preview'
},
{
name: 'File name save',
id: 'fileNameType',
type: 'dropdown',
value: 0,
options: [
{ label: 'Original', value: 0 },
{ label: 'Date', value: 1 },
{ label: 'Random', value: 2 },
{ label: 'Original + random', value: 3 },
{ label: 'Custom', value: 4 }
]
},
2020-01-16 17:03:23 +01:00
{ name: 'Custom file name save', note: 'Available options: file rand date time day month year hours minutes seconds name. options must be wrapped in ${<OPTION>}!', id: 'customFileName', type: 'textbox', value: '${file}_${date}_${time}' },
2019-12-21 20:35:10 +01:00
{ name: 'Random string length', id: 'randLength', type: 'textbox', value: 7 },
{
name: 'Conflicting filename mode',
id: 'conflictingFilesHandle',
type: 'radio',
value: 0,
options: [
{ name: 'Warn', value: 0 },
{ name: 'Overwrite', value: 1 },
{ name: 'Append number: (1)', value: 2 },
2020-02-24 21:58:30 +01:00
{ name: 'Append random', value: 3 },
{ name: 'Save as...', value: 4 }
2019-12-21 20:35:10 +01:00
]
2020-01-09 20:16:01 +01:00
},
2020-01-16 17:03:23 +01:00
{ name: 'User and Server icons get saved by the users or servers name, instead of randomized', id: 'saveByName', type: 'switch', value: true },
{ name: 'Append server name or DM name to image/file name', id: 'appendCurrentName', type: 'switch', value: false }
2019-12-21 20:35:10 +01:00
]
},
{ type: 'category', id: 'misc', name: 'Misc', collapsible: true, shown: false, settings: [{ name: 'Context menu option at the bottom instead of top', id: 'contextMenuOnBottom', type: 'switch', value: true }] }
]
};
/* Build */
const buildPlugin = ([Plugin, Api]) => {
2020-02-27 21:04:39 +01:00
const { Settings, Modals, Utilities, WebpackModules, DiscordModules, DiscordClasses, ReactComponents, DiscordAPI, Logger, Patcher, PluginUpdater, PluginUtilities } = Api;
const { React, ContextMenuActions, ReactDOM, GuildStore, DiscordConstants, Dispatcher, SwitchRow, EmojiUtils, RadioGroup } = DiscordModules;
const TextComponent = Utilities.getNestedProp(DiscordModules, 'TextElement.default');
const getEmojiURL = Utilities.getNestedProp(WebpackModules.getByProps('getEmojiURL'), 'getEmojiURL');
const showAlertModal = Utilities.getNestedProp(
WebpackModules.find(m => m.show && m.show.toString().search(/\w\.minorText,\w=\w\.onConfirmSecondary/)),
'show'
);
2019-12-21 20:35:10 +01:00
2020-02-27 21:04:39 +01:00
const dialog = Utilities.getNestedProp(require('electron'), 'remote.dialog');
const openItem = Utilities.getNestedProp(require('electron'), 'shell.openItem');
const DelayedCall = Utilities.getNestedProp(WebpackModules.getByProps('DelayedCall'), 'DelayedCall');
2019-12-21 20:35:10 +01:00
const FsModule = require('fs');
const RequestModule = require('request');
const PathModule = require('path');
2020-01-07 13:08:29 +01:00
const MimeTypesModule = require('mime-types');
2019-12-21 20:35:10 +01:00
const FormItem = WebpackModules.getByDisplayName('FormItem');
2020-02-27 21:04:39 +01:00
const Messages = Utilities.getNestedProp(WebpackModules.getByProps('Messages'), 'Messages');
2019-12-21 20:35:10 +01:00
const TextInput = WebpackModules.getByDisplayName('TextInput');
2020-01-09 20:16:01 +01:00
const AvatarModule = WebpackModules.getByProps('getChannelIconURL');
2020-01-07 13:08:29 +01:00
const MessageShit = WebpackModules.find(m => m.default && m.getMessage);
const TrustStore = WebpackModules.getByProps('isTrustedDomain');
const isTrustedDomain = url => {
for (const domain of isTrustedDomain.domains) if (url.search(domain) !== -1) return true;
return TrustStore.isTrustedDomain(url);
};
isTrustedDomain.domains = [/\/\/steamuserimages-\w\.akamaihd\.net\//, /\/\/steamcdn-\w\.akamaihd\.net\//, /\/\/steamcommunity-\w\.akamaihd\.net\//, '//cdn.discordapp.com/', '//media.discordapp.net/', /\/\/images-ext-\d\.discordapp\.net\//, '//i.ytimg.com/', /\/\/static\d\.e621\.net\//, '//pbs.twimg.com/', '//preview.redd.it/', '//cdn.shopify.com/', '//discordapp.com/', '//i.imgur.com/', '//i.clouds.tf/', '//image.prntscr.com/', '//i.giphy.com/', '//media.tenor.co/'];
const MessageStrings = {
2020-02-27 21:04:39 +01:00
UNTRUSTED_LINK: (() => {
try {
return MessageShit.getMessage("If you see this, SaveToRedux has failed to get a safe proxied version of the image URL **!!{url}!!**. If you do not recognize the domain, it's best you don't download from it as it could potentially be an IP logger.\n\nAre you sure you want to download an image from this domain?", 'en-US');
} catch (e) {
Logger.stacktrace('Failed to create message', e);
return null;
}
})()
2020-01-07 13:08:29 +01:00
};
2019-12-21 20:35:10 +01:00
class FolderEditor extends React.Component {
constructor(props) {
super(props);
this.state = {
name: props.name,
path: props.path
};
XenoLib.DiscordUtils.bindAll(this, ['handleNameChange', 'handlePathChange']);
}
handleNameChange(name) {
this.setState({ name });
this.props.onNameChange(name);
}
handlePathChange(path) {
this.setState({ path });
this.props.onPathChange(path);
}
render() {
return [
React.createElement(
FormItem,
{
className: DiscordClasses.Margins.marginBottom20.value,
title: Messages.GUILD_FOLDER_NAME
},
React.createElement(TextInput, {
maxLength: DiscordConstants.MAX_GUILD_FOLDER_NAME_LENGTH * 4,
value: this.state.name,
onChange: this.handleNameChange,
placeholder: Messages.SERVER_FOLDER_PLACEHOLDER,
autoFocus: true
})
),
React.createElement(
FormItem,
{
className: DiscordClasses.Margins.marginBottom20,
title: 'Folder path'
},
React.createElement(XenoLib.ReactComponents.FilePicker, {
path: this.state.path,
placeholder: 'Path to folder',
onChange: this.handlePathChange,
properties: ['openDirectory', 'createDirectory'],
nullOnInvalid: true
})
)
];
}
}
class Preview extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
rand: props.rand
};
this.handleSettingsUpdate = this.handleSettingsUpdate.bind(this);
}
componentDidMount() {
Dispatcher.subscribe('ST_SETTINGS_UPDATE', this.handleSettingsUpdate);
}
componentWillUnmount() {
Dispatcher.unsubscribe('ST_SETTINGS_UPDATE', this.handleSettingsUpdate);
}
handleSettingsUpdate(e) {
if (typeof e.rand !== 'undefined') this.setState({ rand: e.rand });
else this.forceUpdate();
}
render() {
return React.createElement(TextComponent, { color: TextComponent.Colors.PRIMARY }, this.props.formatFilename('unknown', this.state.date, this.state.rand), '.png');
}
}
class PreviewField extends Settings.SettingField {
constructor(name, note, data, onChange) {
super(name, note, onChange, Preview, data);
}
}
2020-02-24 21:58:30 +01:00
/*
* I DO NOT OWN THESE TWO
*/
function sanitizeFileName(r, e) {
// https://github.com/parshap/node-sanitize-filename
function n(r, n) {
function o(r, e, n) {
// https://github.com/parshap/truncate-utf8-bytes
function t(r) {
return r >= 55296 && 56319 >= r;
}
function u(r) {
return r >= 56320 && 57343 >= r;
}
if ('string' != typeof e) throw new Error('Input must be string');
for (var i, f, c = e.length, o = 0, l = 0; c > l; l += 1) {
if (((i = e.charCodeAt(l)), (f = e[l]), t(i) && u(e.charCodeAt(l + 1)) && ((l += 1), (f += e[l])), (o += r(f)), o === n)) return e.slice(0, l + 1);
if (o > n) return e.slice(0, l - f.length + 1);
}
return e;
}
if ('string' != typeof r) throw new Error('Input must be string');
var l = Buffer.byteLength.bind(Buffer),
a = o.bind(null, l),
p = r
.replace(t, n)
.replace(u, n)
.replace(i, n)
.replace(f, n)
.replace(c, n);
return a(p, e.extLength);
}
var t = /[\/\?<>\\:\*\|"]/g,
u = /[\x00-\x1f\x80-\x9f]/g,
i = /^\.+$/,
f = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,
c = /[\. ]+$/,
o = (e && e.replacement) || '',
l = n(r, o);
return '' === o ? l : n(l, '');
}
2020-02-27 21:04:39 +01:00
const faultyVars = [];
{
const vars = { TextComponent, getEmojiURL, openItem, DelayedCall, FormItem, Messages, TextInput, AvatarModule, TrustStore };
for (const varName in vars) {
if (!vars[varName]) faultyVars.push(varName);
}
}
2019-12-21 20:35:10 +01:00
return class SaveToRedux extends Plugin {
constructor() {
super();
this.promises = {
state: { cancelled: false },
cancel() {
this.state.cancelled = true;
},
restore() {
this.state.cancelled = false;
}
};
XenoLib.DiscordUtils.bindAll(this, ['handleContextMenu', 'formatFilename']);
XenoLib.changeName(__filename, 'SaveToRedux');
2020-02-27 21:04:39 +01:00
const oOnStart = this.onStart.bind(this);
this.onStart = () => {
try {
oOnStart();
} catch (e) {
Logger.stacktrace('Failed to start!', e);
PluginUpdater.checkForUpdate(this.name, this.version, this._config.info.github_raw);
XenoLib.Notifications.error(`[**${this.name}**] Failed to start! Please update it, press CTRL + R, or ${GuildStore.getGuild(XenoLib.supportServerId) ? 'go to <#639665366380838924>' : '[join my support server](https://discord.gg/NYvWdN5)'} for further assistance.`, { timeout: 0 });
try {
this.onStop();
} catch (e) {}
}
};
2019-12-21 20:35:10 +01:00
}
onStart() {
2020-02-27 21:04:39 +01:00
this.promises = { state: { cancelled: false } };
if (faultyVars.length) {
Logger.error(`Following vars are invalid: ${faultyVars.map(e => '\n' + e).reduce((e, b) => e + b, '')}`);
PluginUpdater.checkForUpdate(this.name, this.version, this._config.info.github_raw);
return XenoLib.Notifications.error(`[**${this.name}**] Plugin is in a broken state. Please update it, press CTRL + R or ${GuildStore.getGuild(XenoLib.supportServerId) ? 'go to <#639665366380838924>' : '[join my support server](https://discord.gg/NYvWdN5)'} for further assistance.`, { timeout: 0 });
}
2019-12-21 20:35:10 +01:00
/* trigger settings migration */
if (typeof this.settings.folders !== 'undefined') {
const settings = Utilities.deepclone(this.defaultSettings);
const folders = [];
settings.saveOptions.fileNameType = this.settings.fileNameType;
settings.saveOptions.customFileName = this.settings.customFileName;
settings.saveOptions.randLength = this.settings.randLength;
settings.saveOptions.conflictingFilesHandle = this.settings.conflictingFilesHandle;
settings.misc.contextMenuOnBottom = this.settings.contextMenuOnBottom;
Object.values(this.settings.folders).forEach(folder => folders.push({ name: folder.name, path: folder.path }));
this.settings = settings;
this.folders = folders;
this.saveSettings();
this.saveFolders();
}
this.folders = XenoLib.loadData(this.name, 'folders', {
data: []
}).data;
this.channelMessages = WebpackModules.find(m => m._channelMessages)._channelMessages;
this.patchAll();
PluginUtilities.addStyle(
this.short + '-CSS',
`
.ST-modal {
min-height: 320px;
}
2020-02-24 21:58:30 +01:00
.ST-randomize {
justify-content: unset;
}
.ST-randomize > .${XenoLib.getSingleClass('lookBlank contents')} {
margin: 0;
}
2019-12-21 20:35:10 +01:00
`
);
this.lastUsedFolder = -1;
}
onStop() {
this.promises.state.cancelled = true;
Patcher.unpatchAll();
XenoLib.unpatchContext(this.handleContextMenu);
PluginUtilities.removeStyle(this.short + '-CSS');
}
/* zlib uses reference to defaultSettings instead of a cloned object, which sets settings as default settings, messing everything up */
loadSettings(defaultSettings) {
return PluginUtilities.loadSettings(this.name, Utilities.deepclone(this.defaultSettings ? this.defaultSettings : defaultSettings));
}
buildSetting(data) {
if (data.type === 'preview') {
return new PreviewField(data.name, data.note, {
rand: this.rand(),
formatFilename: this.formatFilename
});
}
return super.buildSetting(data);
}
saveSettings(_, setting, value) {
super.saveSettings(_, setting, value);
Dispatcher.dispatch({ type: 'ST_SETTINGS_UPDATE', rand: setting === 'randLength' ? this.rand() : undefined });
}
saveFolders() {
PluginUtilities.saveData(this.name, 'folders', { data: this.folders });
}
/* PATCHES */
patchAll() {
XenoLib.patchContext(this.handleContextMenu);
Utilities.suppressErrors(this.patchReactions.bind(this), 'Reaction patch')(this.promises.state);
}
async patchReactions(promiseState) {
const Reaction = await ReactComponents.getComponentByName('Reaction', `.${XenoLib.getSingleClass('reactionMe reactions')} > div:not(.${XenoLib.getSingleClass('reactionMe reactionBtn')})`);
if (promiseState.cancelled) return;
2020-02-24 21:58:30 +01:00
const unpatch = Patcher.after(Reaction.component.prototype, 'render', (_this, _, ret) => {
2019-12-21 20:35:10 +01:00
const oChildren = ret.props.children;
ret.props.children = e => {
2020-02-24 21:58:30 +01:00
try {
const oChRet = oChildren(e);
const url = _this.props.emoji.id ? getEmojiURL({ id: _this.props.emoji.id, animated: _this.props.emoji.animated }) : WebpackModules.getByProps('getURL').getURL(_this.props.emoji.name);
XenoLib.createSharedContext(
() => {
const submenu = this.constructMenu(url.split('?')[0], 'Reaction', _this.props.emoji.name);
return XenoLib.createContextMenuGroup([submenu]);
},
oChRet.props,
'MESSAGE_REACTIONS'
);
return oChRet;
} catch (e) {
Logger.stacktrace('Error in Reaction patch', e);
unpatch(); // for the better..
return null;
}
2019-12-21 20:35:10 +01:00
};
});
Reaction.forceUpdateAll();
}
/* PATCHES */
rand() {
let result = '';
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const charactersLength = characters.length;
for (var i = 0; i < this.settings.saveOptions.randLength; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
2020-01-16 17:03:23 +01:00
getLocationName() {
if (DiscordAPI.currentGuild) return DiscordAPI.currentGuild.name;
if (!DiscordAPI.currentChannel) return '';
if (DiscordAPI.currentChannel.recipient) return DiscordAPI.currentChannel.recipient.username;
if (DiscordAPI.currentChannel.name) return DiscordAPI.currentChannel.name;
return DiscordAPI.currentChannel.members.reduce((p, c) => (p ? `${p}, ${c.username}` : c.username), '');
}
2020-02-24 21:58:30 +01:00
formatFilename(name, previewDate, previewRand, extension, throwFail) {
2019-12-21 20:35:10 +01:00
const date = previewDate || new Date();
const rand = previewRand || this.rand();
2020-01-16 17:03:23 +01:00
let ret = 'INTERNAL_ERROR';
2019-12-21 20:35:10 +01:00
switch (this.settings.saveOptions.fileNameType) {
case 0: // original
2020-01-16 17:03:23 +01:00
ret = name;
break;
2019-12-21 20:35:10 +01:00
case 1: // date
2020-01-16 17:03:23 +01:00
ret = `${date
2019-12-21 20:35:10 +01:00
.toLocaleDateString()
.split('/')
.join('-')} ${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}`;
2020-01-16 17:03:23 +01:00
break;
2019-12-21 20:35:10 +01:00
case 2: // random
2020-01-16 17:03:23 +01:00
ret = rand;
break;
2019-12-21 20:35:10 +01:00
case 3: // original + random
2020-01-16 17:03:23 +01:00
ret = `${name}-${rand}`;
break;
2019-12-21 20:35:10 +01:00
case 4: // custom
2020-01-16 17:03:23 +01:00
// options file rand date time day month year hours minutes seconds name
2020-02-24 21:58:30 +01:00
ret = Utilities.formatTString(this.settings.saveOptions.customFileName, {
2019-12-21 20:35:10 +01:00
rand,
file: name,
date: date
.toLocaleDateString()
.split('/')
.join('-'),
time: `${date.getMinutes()}-${date.getSeconds()}-${date.getMilliseconds()}`,
2020-02-24 21:58:30 +01:00
day: date.getDate(), // note to self: getDate gives you the day of month
month: date.getMonth() + 1, // getMonth gives 0-11
2019-12-21 20:35:10 +01:00
year: date.getFullYear(),
hours: date.getHours(),
minutes: date.getMinutes(),
2020-01-16 17:03:23 +01:00
seconds: date.getSeconds(),
name: this.getLocationName()
2019-12-21 20:35:10 +01:00
});
}
2020-02-24 21:58:30 +01:00
if (this.settings.saveOptions.fileNameType !== 4) {
if (this.settings.saveOptions.appendCurrentName && (DiscordAPI.currentGuild || DiscordAPI.currentChannel)) {
const name = this.getLocationName();
if (name) ret += `-${name}`;
}
2020-01-16 17:03:23 +01:00
}
2020-02-24 21:58:30 +01:00
ret = sanitizeFileName(ret, { extLength: extension ? 255 - (extension.length + 1) : 255 });
if (!ret.length && throwFail) throw 'CUST_ERROR_1';
2020-01-16 17:03:23 +01:00
return ret;
2019-12-21 20:35:10 +01:00
}
2020-01-07 13:08:29 +01:00
formatURL(url, requiresSize, customName, fallbackExtension, proxiedUrl) {
// url = url.replace(/\/$/, '');
2019-12-21 20:35:10 +01:00
if (requiresSize) url += '?size=2048';
2020-01-07 13:08:29 +01:00
const match = url.match(/(?:\/)([^\/]+?)(?:(?:\.)([^.\/?:]+)){0,1}(?:[^\w\/\.]+\w+){0,1}(?:(?:\?[^\/]+){0,1}|(?:\/){0,1})$/);
2019-12-21 20:35:10 +01:00
let name = customName || match[1];
2020-01-07 13:08:29 +01:00
let extension = match[2] || fallbackExtension;
2019-12-21 20:35:10 +01:00
if (url.indexOf('//media.tenor.co') !== -1) {
extension = name;
name = url.match(/\/\/media.tenor.co\/[^\/]+\/([^\/]+)\//)[1];
} else if (url.indexOf('//i.giphy.com/media/') !== -1) name = url.match(/\/\/i\.giphy\.com\/media\/([^\/]+)\//)[1];
2020-02-24 21:58:30 +01:00
let forceSaveAs = false;
try {
name = this.formatFilename(name, undefined, undefined, extension, true);
} catch (e) {
if (e !== 'CUST_ERROR_1') throw e;
forceSaveAs = true;
}
2020-01-07 13:08:29 +01:00
const isTrusted = isTrustedDomain(url);
2020-02-24 21:58:30 +01:00
const ret = { fileName: (extension && `${name}.${extension}`) || name, url: isTrusted ? url : proxiedUrl || url, name, extension, untrusted: !isTrusted && !proxiedUrl, forceSaveAs };
2020-01-03 17:18:26 +01:00
// Logger.info(`[formatURL] url \`${url}\` requiresSize \`${requiresSize}\` customName \`${customName}\`, ret ${JSON.stringify(ret, '', 1)}`);
return ret;
2019-12-21 20:35:10 +01:00
}
2020-01-07 13:08:29 +01:00
constructMenu(url, type, customName, onNoExtension = () => {}, fallbackExtension, proxiedUrl) {
2019-12-21 20:35:10 +01:00
const createSubMenu = (name, items, callback) =>
XenoLib.createContextMenuSubMenu(name, items, {
action: () => {
if (!callback) return;
ContextMenuActions.closeContextMenu();
callback();
}
});
const subItems = [];
const folderSubMenus = [];
2020-01-07 13:08:29 +01:00
const formattedurl = this.formatURL(url, type === 'Icon' || type === 'Avatar', customName, fallbackExtension, proxiedUrl);
if (!formattedurl.extension) onNoExtension(formattedurl.url);
const downloadEx = (path, openOnSave) => {
2019-12-21 20:35:10 +01:00
const req = RequestModule(formattedurl.url);
req.on('response', res => {
if (res.statusCode == 200) {
req
.pipe(FsModule.createWriteStream(path))
.on('finish', () => {
if (openOnSave) openItem(path);
BdApi.showToast(`Saved to '${path}'`, { type: 'success' });
2019-12-21 20:35:10 +01:00
})
.on('error', e => BdApi.showToast(`Failed to save! ${e}`, { type: 'error', timeout: 10000 }));
} else if (res.statusCode == 404) BdApi.showToast('Image does not exist!', { type: 'error' });
else BdApi.showToast(`Unknown error. ${res.statusCode}`, { type: 'error' });
});
};
2020-01-07 13:08:29 +01:00
const download = (path, openOnSave) => {
const onOk = () => downloadEx(path, openOnSave);
if (formattedurl.untrusted) {
showAlertModal({
title: Messages.HOLD_UP,
body: MessageStrings.UNTRUSTED_LINK.format({ url: formattedurl.url }),
cancelText: Messages.MASKED_LINK_CANCEL,
confirmText: Messages.MASKED_LINK_CONFIRM,
minorText: Messages.MASKED_LINK_TRUST_THIS_DOMAIN,
onConfirm: onOk,
onConfirmSecondary: function() {
WebpackModules.getByProps('trustDomain').trustDomain(formattedurl.url);
onOk();
}
});
} else {
onOk();
}
};
2020-02-24 21:58:30 +01:00
const saveAs = (folder, onOk) => {
let val = formattedurl.name;
let inputRef = null;
let delayedCall = new DelayedCall(350, () => {
inputRef.props.value = val = sanitizeFileName(val, 255 - (formattedurl.extension ? formattedurl.extension.length + 1 : 0));
inputRef.forceUpdate();
});
Modals.showModal(
'Save as...',
React.createElement(
FormItem,
{
title: 'Name your file'
},
React.createElement(TextInput, {
maxLength: 255 - (formattedurl.extension ? formattedurl.extension.length + 1 : 0),
ref: e => (inputRef = e),
value: val,
onChange: e => {
val = e;
inputRef.props.value = val;
if (val.trim() !== sanitizeFileName(val.trim(), 255 - (formattedurl.extension ? formattedurl.extension.length + 1 : 0))) inputRef.props.error = 'Invalid characters in name';
else inputRef.props.error = undefined;
inputRef.forceUpdate();
},
placeholder: formattedurl.name,
autoFocus: true,
error: !folder ? 'Invalid filename, please set a name' : folder === -1 ? 'File already exists, try another name' : undefined
}),
React.createElement(XenoLib.ReactComponents.Button, {
children: 'Randomize',
className: XenoLib.joinClassNames(DiscordClasses.Margins.marginBottom20.value, XenoLib.getClass('input reset'), 'ST-randomize'),
color: XenoLib.ReactComponents.Button.Colors.PRIMARY,
look: XenoLib.ReactComponents.ButtonOptions.ButtonLooks.LINK,
onClick: () => {
val = this.rand();
inputRef.props.value = val;
inputRef.forceUpdate();
}
})
),
{
confirmText: 'Save',
onConfirm: () => {
const onDoShitOrWhateverFuckThisShitMan = val => {
if (!folder || folder === -1) return onOk(val);
this.lastUsedFolder = this.folders.findIndex(m => m === folder);
if (!val.length) val = formattedurl.name;
else formattedurl.name = val;
saveFile(folder.path + `/${val}${formattedurl.extension ? '.' + formattedurl.extension : ''}`, folder.path, false, false);
};
const sanitized = sanitizeFileName(val, 255 - (formattedurl.extension ? formattedurl.extension.length + 1 : 0));
if (val !== sanitized) {
if (!sanitized.length) return saveAs(undefined, onOk);
return Modals.showConfirmationModal('Invalid characters', `There are invalid characters in the filename. Do you want to strip them? Resulting filename will be ${sanitized}`, {
onConfirm: () => {
onOk(sanitized);
onDoShitOrWhateverFuckThisShitMan(sanitized);
}
});
}
onDoShitOrWhateverFuckThisShitMan(val);
}
}
);
};
const saveFile = (path, basePath, openOnSave, dontWarn, resolved) => {
2019-12-21 20:35:10 +01:00
try {
FsModule.accessSync(PathModule.dirname(path), FsModule.constants.W_OK);
} catch (err) {
2020-02-24 21:58:30 +01:00
Logger.stacktrace('Failed to save to folder', err);
2019-12-21 20:35:10 +01:00
return BdApi.showToast(`Error saving to folder: ${err.message.match(/.*: (.*), access '/)[1]}`, { type: 'error' });
}
2020-02-24 21:58:30 +01:00
const handleSaveAs = invFilename => saveAs(invFilename ? -1 : undefined, fileName => ((formattedurl.forceSaveAs = false), saveFile(`${basePath}/${fileName}${formattedurl.extension ? '.' + formattedurl.extension : ''}`, basePath, openOnSave, dontWarn, true)));
if (formattedurl.forceSaveAs && !resolved) return handleSaveAs();
2019-12-21 20:35:10 +01:00
if (!dontWarn && FsModule.existsSync(path)) {
const handleConflict = mode => {
switch (mode) {
case 2: {
let num = 1;
try {
while (FsModule.existsSync(path)) {
path = `${basePath}/${formattedurl.name}(${num})${formattedurl.extension ? '.' + formattedurl.extension : ''}`;
num++;
if (num > 99) return Logger.err('Save attempt passed num 99!');
}
} catch (e) {
return Logger.stacktrace('Error finding good number', e);
}
break;
}
case 3: {
path = `${basePath}/${formattedurl.name}-${this.rand()}${formattedurl.extension ? '.' + formattedurl.extension : ''}`;
2020-02-27 21:04:39 +01:00
break;
2019-12-21 20:35:10 +01:00
}
2020-02-24 21:58:30 +01:00
case 4:
return handleSaveAs(true);
2019-12-21 20:35:10 +01:00
}
download(path, openOnSave);
};
2020-02-24 21:58:30 +01:00
if (this.settings.saveOptions.conflictingFilesHandle && !formattedurl.forceSaveAs) {
2019-12-21 20:35:10 +01:00
handleConflict(this.settings.saveOptions.conflictingFilesHandle);
} else {
let ref1, ref2;
Modals.showModal(
'File conflict',
[
React.createElement(
WebpackModules.getByDisplayName('Text'),
{
className: WebpackModules.getByProps('defaultColor').defaultColor + ' ' + WebpackModules.getByProps('marginBottom20').marginBottom20
},
'A file with the existing name already exists! What do you want to do?'
),
React.createElement(RadioGroup, {
className: WebpackModules.getByProps('marginBottom20').marginBottom20,
clearable: false,
searchable: false,
options: [
{
name: 'Overwrite',
value: 1
},
{
name: 'Append number: (1)',
value: 2
},
{
name: 'Append random',
value: 3
2020-02-24 21:58:30 +01:00
},
{
name: 'Save as...',
value: 4
2019-12-21 20:35:10 +01:00
}
],
value: 1,
ref: e => (ref1 = e),
onChange: e => {
ref1.props.value = e.value;
ref1.forceUpdate();
}
}),
React.createElement(SwitchRow, {
children: 'Disable this warning and save this option',
note: 'This can be changed in settings',
value: 0,
ref: e => (ref2 = e),
onChange: e => {
const checked = e.currentTarget.checked;
ref2.props.value = checked;
ref2.forceUpdate();
}
})
],
{
confirmText: 'Ok',
cancelText: 'Cancel',
size: Modals.ModalSizes.SMALL,
red: false,
onConfirm: () => {
2020-01-16 17:03:23 +01:00
if (ref2.props.value) {
this.settings.saveOptions.conflictingFilesHandle = ref1.props.value;
this.saveSettings();
}
2019-12-21 20:35:10 +01:00
handleConflict(ref1.props.value);
}
}
);
}
} else {
download(path, openOnSave);
}
};
const folderSubMenu = folder => {
return createSubMenu(
folder.name,
[
XenoLib.createContextMenuItem('Remove Folder', () => {
const index = this.folders.findIndex(m => m === folder);
if (index === -1) return BdApi.showToast("Fatal error! Attempted to remove a folder that doesn't exist!", { type: 'error', timeout: 5000 });
this.folders.splice(index, 1);
this.saveFolders();
BdApi.showToast('Removed!', { type: 'success' });
}),
XenoLib.createContextMenuItem('Open Folder', () => {
openItem(folder.path);
}),
XenoLib.createContextMenuItem('Save', () => {
this.lastUsedFolder = this.folders.findIndex(m => m === folder);
const path = folder.path + `/${formattedurl.fileName}`;
saveFile(path, folder.path);
}),
2020-02-24 21:58:30 +01:00
XenoLib.createContextMenuItem('Save As...', () => saveAs(folder)),
2019-12-21 20:35:10 +01:00
XenoLib.createContextMenuItem('Save And Open', () => {
this.lastUsedFolder = this.folders.findIndex(m => m === folder);
const path = folder.path + `/${formattedurl.fileName}`;
saveFile(path, folder.path, true);
}),
XenoLib.createContextMenuItem('Edit', () => {
let __name = folder.name.slice(0);
let __path = folder.path.slice(0);
const saveFolder = () => {
if (!__path || !__path.length) return BdApi.showToast('Invalid path', { type: 'error' });
folder.name = __name;
folder.path = __path;
this.saveFolders();
};
Modals.showModal(
'Edit folder',
React.createElement(FolderEditor, {
name: __name,
path: __path,
onNameChange: e => (__name = e),
onPathChange: e => (__path = e)
}),
{
confirmText: 'Create',
onConfirm: saveFolder,
size: XenoLib.joinClassNames(Modals.ModalSizes.MEDIUM, 'ST-modal')
}
);
})
],
() => {
this.lastUsedFolder = this.folders.findIndex(m => m === folder);
const path = folder.path + `/${formattedurl.fileName}`;
saveFile(path, folder.path);
}
);
};
for (const folder of this.folders) folderSubMenus.push(folderSubMenu(folder));
subItems.push(
...folderSubMenus,
XenoLib.createContextMenuItem('Add Folder', () => {
2020-02-27 21:04:39 +01:00
dialog
.showOpenDialog({
title: 'Add folder',
properties: ['openDirectory', 'createDirectory']
})
.then(({ filePaths: [path] }) => {
if (!path) return BdApi.showToast('Maybe next time.');
let idx;
if ((idx = this.folders.findIndex(m => m.path === path)) !== -1) return BdApi.showToast(`Folder already exists as ${this.folders[idx].name}!`, { type: 'error', timeout: 5000 });
const folderName = PathModule.basename(path);
let __name = folderName;
let __path = path.slice(0);
const saveFolder = () => {
if (!__path || !__path.length) return BdApi.showToast('Invalid path', { type: 'error' });
this.folders.push({
path: __path,
name: __name || 'Unnamed'
});
this.saveFolders();
BdApi.showToast('Added!', { type: 'success' });
};
Modals.showModal(
'Create New Folder',
React.createElement(FolderEditor, {
name: folderName,
path: path,
onNameChange: e => (__name = e),
onPathChange: e => (__path = e)
}),
{
confirmText: 'Create',
onConfirm: saveFolder,
size: XenoLib.joinClassNames(Modals.ModalSizes.MEDIUM, 'ST-modal')
}
);
2019-12-21 20:35:10 +01:00
});
}),
XenoLib.createContextMenuItem('Save As...', () => {
2020-02-27 21:04:39 +01:00
dialog
.showSaveDialog({
defaultPath: formattedurl.fileName,
filters: formattedurl.extension
? [
{
name: /\.{0,1}(png|jpe?g|webp|gif|svg)$/i.test(formattedurl.extension) ? 'Images' : /\.{0,1}(mp4|webm|mov)$/i.test(formattedurl.extension) ? 'Videos' : /\.{0,1}(mp3|ogg|wav|flac)$/i.test(formattedurl.extension) ? 'Audio' : 'Files',
extensions: [formattedurl.extension]
},
{
name: 'All Files',
extensions: ['*']
}
]
: undefined
})
.then(({ filePath: path }) => {
if (!path) return BdApi.showToast('Maybe next time.');
saveFile(path, undefined, false, true);
});
2019-12-21 20:35:10 +01:00
})
);
return createSubMenu(`Save ${type} To`, subItems, () => {
if (this.lastUsedFolder === -1) return BdApi.showToast('No folder has been used yet', { type: 'error' });
const folder = this.folders[this.lastUsedFolder];
if (!folder) return BdApi.showToast('Folder no longer exists', { type: 'error' });
const path = folder.path + `/${formattedurl.fileName}`;
saveFile(path, folder.path);
});
}
handleContextMenu(_this, ret) {
if (!ret) return ret;
2020-01-09 20:16:01 +01:00
// Logger.info(_this, ret);
2019-12-21 20:35:10 +01:00
const type = _this.props.type;
let saveType = 'File';
let url = '';
2020-01-07 13:08:29 +01:00
let proxiedUrl = '';
2019-12-21 20:35:10 +01:00
let customName = '';
2020-01-09 20:16:01 +01:00
const isImage = e => /\.{0,1}(png|jpe?g|webp|gif|svg)$/i.test(e);
const isVideo = e => /\.{0,1}(mp4|webm|mov)$/i.test(e);
const isAudio = e => /\.{0,1}(mp3|ogg|wav|flac)$/i.test(e);
2020-02-24 21:58:30 +01:00
const useCorrectShit = () => {
if (url.indexOf('/a_') !== -1) url = url.replace('.webp', '.gif').replace('.png', '.gif');
else url = url.replace('.webp', '.png');
};
2019-12-21 20:35:10 +01:00
if (type === 'NATIVE_IMAGE' || type === 'MESSAGE_MAIN') {
2020-01-07 13:08:29 +01:00
let src;
if (type === 'NATIVE_IMAGE') {
2020-01-09 20:16:01 +01:00
src = Utilities.getNestedProp(ret, 'props.children.props.href') || Utilities.getNestedProp(_this, 'props.href');
proxiedUrl = Utilities.getNestedProp(ret, 'props.children.props.src') || Utilities.getNestedProp(_this, 'props.src');
2020-01-07 13:08:29 +01:00
if (typeof proxiedUrl === 'string') proxiedUrl = proxiedUrl.split('?')[0];
2020-01-09 20:16:01 +01:00
/* if src does not have an extension but the proxied URL does, use the proxied URL instead */
if (typeof src !== 'string' || src.indexOf('discordapp.com/channels') !== -1 || (!(isImage(src) || isVideo(src) || isAudio(src)) && (isImage(proxiedUrl) || isVideo(proxiedUrl) || isAudio(proxiedUrl)))) {
2020-01-07 13:08:29 +01:00
src = proxiedUrl;
proxiedUrl = '';
}
}
2020-01-09 20:16:01 +01:00
// Logger.info('src', src, 'proxiedUrl', proxiedUrl, _this, ret);
2020-01-07 13:08:29 +01:00
if (!src) src = Utilities.getNestedProp(_this, 'props.attachment.href') || Utilities.getNestedProp(_this, 'props.attachment.url');
2019-12-21 20:35:10 +01:00
/* is that enough specific cases? */
if (typeof src === 'string') {
src = src.split('?')[0];
if (src.indexOf('//giphy.com/gifs/') !== -1) src = `https://i.giphy.com/media/${src.match(/-([^-]+)$/)[1]}/giphy.gif`;
else if (src.indexOf('//tenor.com/view/') !== -1) {
src = _this.props.src;
saveType = 'Video';
} else if (src.indexOf('//preview.redd.it/') !== -1) {
src = src.replace('preview', 'i');
} else if (src.indexOf('twimg.com/') !== -1) saveType = 'Image';
}
if (!src) {
let C = _this.props.target;
2020-01-07 13:08:29 +01:00
let proxiedsauce;
let sauce;
2019-12-21 20:35:10 +01:00
while (null != C) {
2020-01-07 13:08:29 +01:00
if (C instanceof HTMLImageElement && null != C.src) proxiedsauce = C.src;
if (C instanceof HTMLAnchorElement && null != C.href) sauce = C.href;
C = C.parentNode;
}
if (!proxiedsauce && !sauce) return;
if (proxiedsauce) proxiedsauce = proxiedsauce.split('?')[0];
if (sauce) sauce = sauce.split('?')[0];
2020-01-09 20:16:01 +01:00
// Logger.info('sauce', sauce, 'proxiedsauce', proxiedsauce);
2020-01-08 01:14:10 +01:00
/* do not check if proxiedsauce is an image video or audio, it will always be video or image!
an anchor element however is just a link which could be anything! so best we check it
*/
if (!proxiedsauce && !(isImage(sauce) || isVideo(sauce) || isAudio(sauce))) return;
2020-01-07 13:08:29 +01:00
src = sauce;
proxiedUrl = proxiedsauce;
2020-01-09 20:16:01 +01:00
/* if src does not have an extension but the proxied URL does, use the proxied URL instead */
if (!src || (!(isImage(sauce) || isVideo(sauce) || isAudio(sauce)) && (isImage(proxiedsauce) || isVideo(proxiedsauce) || isAudio(proxiedsauce)))) {
2020-01-07 13:08:29 +01:00
src = proxiedsauce;
proxiedUrl = '';
2019-12-21 20:35:10 +01:00
}
if (!src) return;
}
url = src;
if (!url) return;
2020-01-07 13:08:29 +01:00
if (isImage(url) || url.indexOf('//steamuserimages') !== -1) saveType = 'Image';
else if (isVideo(url)) saveType = 'Video';
else if (isAudio(url)) saveType = 'Audio';
2020-01-09 20:16:01 +01:00
if (url.indexOf('app.com/emojis/') !== -1) {
2019-12-21 20:35:10 +01:00
saveType = 'Emoji';
const emojiId = url.split('emojis/')[1].split('.')[0];
const emoji = EmojiUtils.getDisambiguatedEmojiContext().getById(emojiId);
if (!emoji) {
if (!DiscordAPI.currentChannel || !this.channelMessages[DiscordAPI.currentChannel.id]) return;
const message = this.channelMessages[DiscordAPI.currentChannel.id]._array.find(m => m.content.indexOf(emojiId) !== -1);
if (message && message.content) {
const group = message.content.match(new RegExp(`<a?:([^:>]*):${emojiId}>`));
if (group && group[1]) customName = group[1];
}
if (!customName) {
const alt = _this.props.target.alt;
if (alt) customName = alt.split(':')[1] || alt;
}
} else customName = emoji.name;
2020-01-07 13:08:29 +01:00
} else if (_this.state.__STR_extension) {
if (isImage(_this.state.__STR_extension)) saveType = 'Image';
else if (isVideo(_this.state.__STR_extension)) saveType = 'Video';
else if (isAudio(_this.state.__STR_extension)) saveType = 'Audio';
2020-01-09 20:16:01 +01:00
} else if (url.indexOf('//discordapp.com/assets/') !== -1 && _this.props.target && _this.props.target.className.indexOf('emoji') !== -1) {
const alt = _this.props.target.alt;
if (alt) customName = alt.split(':')[1] || alt;
2019-12-21 20:35:10 +01:00
}
if (!Array.isArray(ret.props.children)) ret.props.children = [ret.props.children];
} else if (type === 'GUILD_ICON_BAR') {
saveType = 'Icon';
url = _this.props.guild.getIconURL();
if (!url) return;
2020-01-09 20:16:01 +01:00
if (this.settings.saveOptions.saveByName) customName = _this.props.guild.name;
2020-02-24 21:58:30 +01:00
useCorrectShit();
2019-12-21 20:35:10 +01:00
} else {
2020-01-09 20:16:01 +01:00
if (_this.props.user && _this.props.user.getAvatarURL) {
saveType = 'Avatar';
url = _this.props.user.getAvatarURL();
if (this.settings.saveOptions.saveByName) customName = _this.props.user.username;
} else if (_this.props.channel && _this.props.channel.type === 3 /* group DM */) {
url = AvatarModule.getChannelIconURL(_this.props.channel);
saveType = 'Icon';
} else return /* hurr durr? */;
2020-02-24 21:58:30 +01:00
useCorrectShit();
2019-12-21 20:35:10 +01:00
if (url.startsWith('/assets/')) url = 'https://discordapp.com' + url;
}
try {
2020-01-07 13:08:29 +01:00
const submenu = this.constructMenu(
url.split('?')[0],
saveType,
customName,
targetUrl => {
if (_this.state.__STR_requesting || _this.state.__STR_requested) return;
if (!isTrustedDomain(targetUrl)) return;
_this.state.__STR_requesting = true;
RequestModule.head(targetUrl, (err, res) => {
if (err) return _this.setState({ __STR_requesting: false, __STR_requested: true });
const extension = MimeTypesModule.extension(res.headers['content-type']);
_this.setState({
__STR_requesting: false,
__STR_requested: true,
__STR_extension: extension
});
});
targetUrl;
},
_this.state.__STR_extension,
proxiedUrl
);
2019-12-21 20:35:10 +01:00
const group = XenoLib.createContextMenuGroup([submenu]);
const targetGroup = ret.props.children;
if (this.settings.misc.contextMenuOnBottom) targetGroup.push(group);
else targetGroup.unshift(group);
} catch (e) {
Logger.warn('Failed to parse URL...', url, e);
}
}
getSettingsPanel() {
return this.buildSettingsPanel().getElement();
}
get [Symbol.toStringTag]() {
return 'Plugin';
}
get name() {
return config.info.name;
}
get short() {
let string = '';
for (let i = 0, len = config.info.name.length; i < len; i++) {
const char = config.info.name[i];
if (char === char.toUpperCase()) string += char;
}
return string;
}
get author() {
return config.info.authors.map(author => author.name).join(', ');
}
get version() {
return config.info.version;
}
get description() {
return config.info.description;
}
};
};
/* Finalize */
2020-02-27 21:04:39 +01:00
/* this new lib loader is lit */
let ZeresPluginLibraryOutdated = false;
let XenoLibOutdated = false;
try {
if (global.BdApi && 'function' == typeof BdApi.getPlugin) {
const i = (i, n) => ((i = i.split('.').map(i => parseInt(i))), (n = n.split('.').map(i => parseInt(i))), !!(n[0] > i[0]) || !!(n[0] == i[0] && n[1] > i[1]) || !!(n[0] == i[0] && n[1] == i[1] && n[2] > i[2])),
n = (n, e) => n && n._config && n._config.info && n._config.info.version && i(n._config.info.version, e),
e = BdApi.getPlugin('ZeresPluginLibrary'),
o = BdApi.getPlugin('XenoLib');
n(e, '1.2.10') && (ZeresPluginLibraryOutdated = !0), n(o, '1.3.10') && (XenoLibOutdated = !0);
}
} catch (i) {
console.error('Error checking if libraries are out of date', i);
}
return !global.ZeresPluginLibrary || !global.XenoLib || ZeresPluginLibraryOutdated || XenoLibOutdated
2019-12-21 20:35:10 +01:00
? class {
2020-01-03 17:18:26 +01:00
getName() {
return this.name.replace(/\s+/g, '');
}
getAuthor() {
return this.author;
}
getVersion() {
return this.version;
}
getDescription() {
return this.description;
}
stop() {}
load() {
2020-02-27 21:04:39 +01:00
const a = !global.XenoLib,
b = !global.ZeresPluginLibrary,
c = (a && b) || ((a || b) && (XenoLibOutdated || ZeresPluginLibraryOutdated)) || XenoLibOutdated || ZeresPluginLibraryOutdated,
d = (() => {
let d = '';
return a || b ? (d += `Missing${XenoLibOutdated || ZeresPluginLibraryOutdated ? ' and outdated' : ''} `) : (XenoLibOutdated || ZeresPluginLibraryOutdated) && (d += `Outdated `), (d += `${c ? 'Libraries' : 'Library'} `), d;
})(),
e = (() => {
let d = `The ${c ? 'libraries' : 'library'} `;
return a || XenoLibOutdated ? ((d += 'XenoLib '), (b || ZeresPluginLibraryOutdated) && (d += 'and ZeresPluginLibrary ')) : (b || ZeresPluginLibraryOutdated) && (d += 'ZeresPluginLibrary '), (d += `required for ${this.name} ${c ? 'are' : 'is'} ${a || b ? 'missing' : ''}${XenoLibOutdated || ZeresPluginLibraryOutdated ? (a || b ? ' and/or outdated' : 'outdated') : ''}.`), d;
})(),
f = BdApi.findModuleByProps('push', 'update', 'pop', 'popWithKey'),
g = BdApi.findModuleByProps('Sizes', 'Weights'),
h = BdApi.findModule(a => a.defaultProps && a.key && 'confirm-modal' === a.key()),
i = () => BdApi.getCore().alert(d, `${e}<br/>Due to a slight mishap however, you'll have to download the libraries yourself. After opening the links, do CTRL + S to download the library.<br/>${b || ZeresPluginLibraryOutdated ? '<br/><a href="http://betterdiscord.net/ghdl/?url=https://github.com/rauenzi/BDPluginLibrary/blob/master/release/0PluginLibrary.plugin.js"target="_blank">Click here to download ZeresPluginLibrary</a>' : ''}${a || XenoLibOutdated ? '<br/><a href="http://betterdiscord.net/ghdl/?url=https://github.com/1Lighty/BetterDiscordPlugins/blob/master/Plugins/1XenoLib.plugin.js"target="_blank">Click here to download XenoLib</a>' : ''}`);
if (!f || !h || !g) return i();
let j;
const k = (() => {
if (!global.pluginModule || !global.BDEvents) return;
if (a || XenoLibOutdated) {
const a = () => {
BDEvents.off('xenolib-loaded', a), f.popWithKey(j), pluginModule.reloadPlugin(this.name);
};
return BDEvents.on('xenolib-loaded', a), () => BDEvents.off('xenolib-loaded', a);
}
const b = a => {
'ZeresPluginLibrary' !== a || (BDEvents.off('plugin-loaded', b), BDEvents.off('plugin-reloaded', b), f.popWithKey(j), pluginModule.reloadPlugin(this.name));
};
return BDEvents.on('plugin-loaded', b), BDEvents.on('plugin-reloaded', b), () => (BDEvents.off('plugin-loaded', b), BDEvents.off('plugin-reloaded', b));
})();
class l extends BdApi.React.PureComponent {
constructor(a) {
super(a), (this.state = { hasError: !1 });
}
componentDidCatch(a, b) {
console.error(`Error in ${this.props.label}, screenshot or copy paste the error above to Lighty for help.`), this.setState({ hasError: !0 }), 'function' == typeof this.props.onError && this.props.onError(a);
}
render() {
return this.state.hasError ? null : this.props.children;
}
}
j = f.push(a =>
BdApi.React.createElement(
l,
{
label: 'missing dependency modal',
onError: () => {
f.popWithKey(j), i();
}
},
BdApi.React.createElement(
h,
Object.assign(
{
header: d,
children: [BdApi.React.createElement(g, { color: g.Colors.PRIMARY, children: [`${e} Please click Download Now to download ${c ? 'them' : 'it'}.`] })],
red: !1,
confirmText: 'Download Now',
cancelText: 'Cancel',
onConfirm: () => {
k();
const a = require('request'),
b = require('fs'),
c = require('path'),
d = a => {
if (!global.BDEvents) return a();
const b = c => {
'ZeresPluginLibrary' !== c || (BDEvents.off('plugin-loaded', b), BDEvents.off('plugin-reloaded', b), a());
};
BDEvents.on('plugin-loaded', b), BDEvents.on('plugin-reloaded', b);
},
e = () => {
if (!global.pluginModule || (!global.BDEvents && !global.XenoLib)) return;
if ((global.XenoLib && !XenoLibOutdated) || !global.BDEvents) return pluginModule.reloadPlugin(this.name);
const a = () => {
BDEvents.off('xenolib-loaded', a), pluginModule.reloadPlugin(this.name);
};
BDEvents.on('xenolib-loaded', a);
},
f = () => (global.XenoLib && !XenoLibOutdated ? e() : void a('https://raw.githubusercontent.com/1Lighty/BetterDiscordPlugins/master/Plugins/1XenoLib.plugin.js', (a, d, f) => (a ? i() : void (e(), b.writeFile(c.join(window.ContentManager.pluginsFolder, '1XenoLib.plugin.js'), f, () => {})))));
!global.ZeresPluginLibrary || ZeresPluginLibraryOutdated ? a('https://rauenzi.github.io/BDPluginLibrary/release/0PluginLibrary.plugin.js', (a, e, g) => (a ? i() : void (d(f), b.writeFile(c.join(window.ContentManager.pluginsFolder, '0PluginLibrary.plugin.js'), g, () => {})))) : f();
}
},
a
)
2020-01-03 17:18:26 +01:00
)
2020-02-27 21:04:39 +01:00
)
);
2020-01-03 17:18:26 +01:00
}
2019-12-21 20:35:10 +01:00
2020-01-03 17:18:26 +01:00
start() {}
get [Symbol.toStringTag]() {
return 'Plugin';
}
get name() {
return config.info.name;
}
get short() {
let string = '';
for (let i = 0, len = config.info.name.length; i < len; i++) {
const char = config.info.name[i];
if (char === char.toUpperCase()) string += char;
}
return string;
}
get author() {
return config.info.authors.map(author => author.name).join(', ');
}
get version() {
return config.info.version;
}
get description() {
return config.info.description;
2019-12-21 20:35:10 +01:00
}
}
: buildPlugin(global.ZeresPluginLibrary.buildPlugin(config));
})();
/*@end@*/