This repository has been archived by the owner on Apr 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
823 lines (693 loc) · 27.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
const { Plugin } = require('powercord/entities');
const {
getModule,
React,
/* contextMenu, */
constants: {
Routes,
Permissions,
APP_URL_PREFIX,
EMOJI_RE,
EMOJI_MAX_LENGTH
}
} = require('powercord/webpack');
/* const { CDN_HOST } = window.GLOBAL_ENV; */
const { ContextMenu } = require('powercord/components');
const { getOwnerInstance, injectContextMenu } = require('powercord/util');
const { inject, uninject } = require('powercord/injector');
const { open: openModal } = require('powercord/modal');
const { writeFile } = require('fs').promises;
const { existsSync } = require('fs');
const { get } = require('powercord/http');
const { extname, resolve } = require('path');
const { parse } = require('url');
const { clipboard } = require('electron');
const Settings = require('./components/Settings.jsx');
const EmojiNameModal = require('./components/EmojiNameModal.jsx');
const colors = {
error: 0xdd2d2d,
success: 0x1bbb1b
};
module.exports = class EmojiUtility extends Plugin {
async import (filter, functionName = filter) {
if (typeof filter === 'string') {
filter = [ filter ];
}
this[functionName] = (await getModule(filter))[functionName];
}
async doImport () {
this.emojiStore = await getModule([ 'getGuildEmoji' ]);
await this.import('getGuild');
await this.import('getGuilds');
await this.import([ 'getFlattenedGuilds', 'getSortedGuilds' ], 'getFlattenedGuilds');
await this.import('uploadEmoji');
await this.import([ 'getChannel', 'getDMFromUserId' ]);
await this.import('getGuildPermissions');
await this.import('transitionTo');
await this.import([ 'getCurrentUser', 'getUser' ], 'getCurrentUser');
await this.import('createBotMessage');
await this.import('receiveMessage');
await this.import([ 'getLastSelectedChannelId' ], 'getChannelId');
await this.import('queryEmojiResults');
}
getEmojiRegex () {
return /^<a?:([a-zA-Z0-9_]+):([0-9]+)>$/;
}
getEmojiUrlRegex () {
return /https:\/\/cdn\.discordapp\.com\/emojis\/(\d+)/;
}
getGuildRoute (guildId) {
const selectedChannelId = this.getChannelId(guildId);
/* eslint-disable new-cap */
return selectedChannelId
? Routes.CHANNEL(guildId, selectedChannelId)
: Routes.GUILD(guildId);
/* eslint-enable new-cap */
}
getGuildUrl (guildId) {
return APP_URL_PREFIX + this.getGuildRoute(guildId);
}
getFullEmoji (emoji) {
return `<${(emoji.animated ? 'a' : '')}:${emoji.name}:${emoji.id}>`;
}
sendBotMessage (content) {
const receivedMessage = this.createBotMessage({
channelId: this.getChannelId(),
content: ''
});
if (typeof content === 'string') {
receivedMessage.content = content;
} else {
receivedMessage.embeds.push(content);
}
return this.receiveMessage(receivedMessage.channel_id, receivedMessage);
}
reply (content, embed) {
this.sendBotMessage(
this.settings.get('useEmbeds')
? Object.assign({
type: 'rich',
description: content
}, embed)
: content
);
}
replySuccess (content, embed) {
this.reply(content, Object.assign({ color: colors.success }, embed));
}
replyError (content, embed) {
this.reply(content, Object.assign({ color: colors.error }, embed));
}
getExtension (url) {
return extname(parse(url).pathname).substring(1);
}
async getImageEncoded (imageUrl) {
imageUrl = imageUrl.replace('.webp', '.png');
const extension = this.getExtension(imageUrl);
const { raw } = await get(imageUrl);
return `data:image/${extension};base64,${raw.toString('base64')}`;
}
getGuildByIdOrName (input) {
let guild = this.getGuild(input);
if (!guild) {
input = input.toLowerCase();
guild = Object.values(this.getGuilds()).find(g => g.name.toLowerCase().includes(input));
}
return guild;
}
findEmojisForCommand (args) {
args = [ ...new Set(args) ];
if (args.length === 0) {
return this.replyError('Please provide an emote');
}
const emojis = Object.values(this.emojiStore.getGuilds()).flatMap(g => g.emojis);
const foundEmojis = [];
const notFoundEmojis = [];
for (const argument of args) {
const matcher = argument.match(this.getEmojiRegex());
if (matcher) {
const emoji = emojis.find(e => e.id === matcher[2]);
if (emoji) {
emoji.guild = this.getGuild(emoji.guildId);
foundEmojis.push(emoji);
continue;
}
if (args.length === 1) {
return this.replyError(`Could not find emote ${argument}`);
}
}
if (args.length === 1) {
return this.replyError(`**${argument}** is not a custom emote`);
}
notFoundEmojis.push(argument);
}
return {
foundEmojis,
notFoundEmojis
};
}
hasPermission (guildId, permission) {
const permissions = this.getGuildPermissions({ id: guildId });
if (typeof permissions === 'object' && 'data' in permissions) {
return permissions.data && (permissions.data & permission.data) !== 0n;
}
return permissions && (permissions & permission) !== 0n;
}
createFakeEmoji (id, name, url) {
return {
id,
name,
url,
animated: this.getExtension(url) === 'gif',
fake: true
};
}
getEmojis (guildId, animated = null) {
return this.emojiStore.getGuilds()[guildId].emojis.filter(e => animated === null || e.animated === animated);
}
getEmojiById (id) {
return Object.values(this.emojiStore.getGuilds()).flatMap(g => g.emojis).find(e => e.id === id);
}
getHiddenGuilds () {
return this.settings.get('hiddenGuilds', []);
}
getMaxEmojiSlots (guildId) {
return this.getGuild(guildId).getMaxEmojiSlots();
}
async startPlugin () {
await this.doImport();
this.loadStylesheet('style.scss');
/* Default settings */
this.settings.set('useEmbeds', this.settings.get('useEmbeds', false));
this.settings.set('displayLink', this.settings.get('displayLink', true));
this.settings.set('includeIdForSavedEmojis', this.settings.get('includeIdForSavedEmojis', true));
this.settings.set('defaultCloneIdUseCurrent', this.settings.get('defaultCloneIdUseCurrent', false));
const getCloneableFeatures = (emoji) => {
const onGuildClick = async (guild) => {
if (!guild) {
if (this.settings.get('defaultCloneIdUseCurrent')) {
guild = this.getGuild(this.getChannel(this.getChannelId()).guild_id);
} else if (this.settings.get('defaultCloneId')) {
guild = this.getGuild(this.settings.get('defaultCloneId'));
if (!guild) {
return this.replyError('You are no longer in your default server, please update your settings');
}
}
if (guild) {
if (!this.hasPermission(guild.id, Permissions.MANAGE_GUILD_EXPRESSIONS)) {
return this.replyError(`Missing permissions to upload emotes in **${guild.name}**`);
}
} else {
return this.replyError('You do not have a default server, please update your settings');
}
}
if (this.getEmojis(guild.id, emoji.animated).length >= this.getMaxEmojiSlots(guild.id)) {
return this.replyError(`**${guild.name}** does not have any more emote slots`);
}
try {
await this.uploadEmoji({
guildId: guild.id,
image: await this.getImageEncoded(emoji.url),
name: emoji.name,
roles: []
});
this.replySuccess(`Cloned emote ${this.getFullEmoji(emoji)} to **${guild.name}**`);
} catch (error) {
console.error(error);
if (error.body && error.body.message) {
this.replyError(error.body.message);
} else {
this.replyError('Failed to clone emote, check the console for more information', {
description: 'Failed to clone emote',
footer: {
text: 'Check the console for more information'
}
});
}
}
};
const getCloneableGuilds = () => {
const items = [];
const clonableGuilds = Object.values(this.getFlattenedGuilds()).filter(guild => this.hasPermission(guild.id, Permissions.MANAGE_GUILD_EXPRESSIONS));
for (const guild of clonableGuilds) {
items.push({
type: 'button',
name: guild.name,
id: `guild___${guild.id}`,
onClick: () => onGuildClick(guild)
});
}
return items;
};
const features = [];
features.push({
type: 'submenu',
name: 'Clone',
hint: 'to',
id: 'emoji-utility-clone',
onClick: () => onGuildClick(null),
getItems: getCloneableGuilds
});
features.push({
type: 'button',
name: 'Save',
id: 'emoji-utility-save',
onClick: async () => {
if (!this.settings.get('filePath')) {
this.replyError('Please set your save directory in the settings');
return;
}
if (!existsSync(this.settings.get('filePath'))) {
this.replyError('The specified save directory does no longer exist, please update it in the settings');
return;
}
try {
const name = this.settings.get('includeIdForSavedEmojis') ? `${emoji.name} (${emoji.id})` : emoji.name;
await writeFile(resolve(this.settings.get('filePath'), name + extname(parse(emoji.url).pathname)), (await get(emoji.url)).raw);
this.replySuccess(`Downloaded ${this.getFullEmoji(emoji)}`);
} catch (error) {
console.error(error);
this.replyError(`Failed to download ${this.getFullEmoji(emoji)}, check the console for more information`, {
description: `Failed to download ${this.getFullEmoji(emoji)}`,
footer: {
text: 'Check the console for more information'
}
});
}
}
});
if (!emoji.fake) {
features.push({
type: 'button',
name: 'Go to server',
id: 'emoji-utility-go-to-server',
onClick: () => {
this.transitionTo(this.getGuildRoute(emoji.guildId));
}
});
}
features.push({
type: 'button',
name: 'Copy Emote ID',
id: 'emoji-utility-copy-id',
onClick: () => clipboard.writeText(emoji.id)
});
return features;
};
const getCreateableFeatures = (target) => {
const url = getOwnerInstance(target)?.props?.href || target.src;
const onGuildClick = (guild) => {
if (!guild) {
if (this.settings.get('defaultCloneIdUseCurrent')) {
guild = this.getGuild(this.getChannel(this.getChannelId()).guild_id);
} else if (this.settings.get('defaultCloneId')) {
guild = this.getGuild(this.settings.get('defaultCloneId'));
if (!guild) {
return this.replyError('You are no longer in your default server, please update your settings');
}
}
if (guild) {
if (!this.hasPermission(guild.id, Permissions.MANAGE_GUILD_EXPRESSIONS)) {
return this.replyError(`Missing permissions to upload emotes in **${guild.name}**`);
}
} else {
return this.replyError('You do not have a default server, please update your settings');
}
}
if (this.getEmojis(guild.id, this.getExtension(url) === 'gif').length >= this.getMaxEmojiSlots(guild.id)) {
return this.replyError(`**${guild.name}** does not have any more emote slots`);
}
openModal(() => React.createElement(EmojiNameModal, {
onConfirm: async (name) => {
name = name.replace(EMOJI_RE, '').substr(0, EMOJI_MAX_LENGTH);
if (name.length < 2) {
this.replyError('Please enter an emote name with 2 or more valid characters, valid characters are **a-z**, **0-9** and **_**');
return;
}
try {
await this.uploadEmoji({
guildId: guild.id,
image: await this.getImageEncoded(url),
name,
roles: []
});
this.replySuccess(`Created emote by the name of **${name}** in **${guild.name}**`);
} catch (error) {
console.error(error);
if (error.body && error.body.image) {
this.replyError(error.body.image[0]);
} else if (error.body && error.body.message) {
this.replyError(error.body.message);
} else {
this.replyError('Failed to create emote, check the console for more information', {
description: 'Failed to create emote',
footer: {
text: 'Check the console for more information'
}
});
}
}
}
}));
};
const getCreateableGuilds = () => {
const items = [];
const createableGuilds = Object.values(this.getFlattenedGuilds()).filter(guild => this.hasPermission(guild.id, Permissions.MANAGE_GUILD_EXPRESSIONS));
for (const guild of createableGuilds) {
items.push({
type: 'button',
name: guild.name,
id: `guild___${guild.id}`,
onClick: () => onGuildClick(guild)
});
}
return items;
};
const features = [];
features.push({
type: 'submenu',
hint: 'in',
name: 'Create',
id: 'emoji-utility-create',
onClick: () => onGuildClick(null),
getItems: getCreateableGuilds
});
return features;
};
this._injectContextMenu(getCloneableFeatures, getCreateableFeatures);
/*
* Discord broke this in a recent update so TODO: Figure out a new way of adding the emote context to reactions
*
* const AnimatedComponent = (await getModule([ 'createAnimatedComponent' ])).div;
* inject('pc-emojiUtility-reactionContext', AnimatedComponent.prototype, 'render', function (args, res) {
* if (this.props.className && this.props.className.includes('pc-reaction')) {
* res.props.onContextMenu = (e) => {
* const { props: propEmoji } = this.props.children.props.children[0];
*
* if (propEmoji.emojiId) {
* let emoji = _this.getEmojiById(propEmoji.emojiId);
* if (emoji) {
* emoji.fake = false;
* } else {
* emoji = _this.createFakeEmoji(propEmoji.emojiId, propEmoji.emojiName, `https://${CDN_HOST}/emojis/${propEmoji.emojiId}.${propEmoji.animated ? 'gif' : 'png'}`);
* }
*
* const { pageX, pageY } = e;
* contextMenu.openContextMenu(e, () =>
* React.createElement(ContextMenu, {
* pageX,
* pageY,
* itemGroups: [ [ {
* type: 'submenu',
* name: 'Emote',
* getItems: () => getCloneableFeatures(emoji)
* } ] ]
* })
* );
* }
* };
* }
*
* return res;
* });
*
* @todo: properly inject like commands does
* injectInFluxContainer('pc-emojiUtility-hideEmojisPickerRm', 'EmojiPicker', 'removeEmotes', function () {
* const hiddenGuilds = _this.settings.get('hiddenGuilds', []);
* const hiddenNames = hiddenGuilds.map(id => _this.getGuild(id).name);
*
* this.setState({
* metaData: this.state.metaData.map(meta => ({
* ...meta,
* items: meta.items.filter(item => !item.emoji.guildId || !hiddenGuilds.includes(item.emoji.guildId))
* })).filter(meta => meta.items.length > 0)
* });
*
* let previousOffset = 0;
* let offsetDiff = 0;
* this.categories = this.categories.map(category => {
* if (category.category.startsWith('custom') && hiddenNames.includes(category.title)) {
* offsetDiff += category.offsetTop - previousOffset;
* previousOffset = category.offsetTop;
* delete this.categoryOffsets[category.category];
* return null;
* }
* category.offsetTop -= offsetDiff;
* this.categoryOffsets[category.category] = category.offsetTop;
* previousOffset = category.offsetTop;
* return category;
* }).filter(category => !!category);
* });
*
* injectInFluxContainer('pc-emojiUtility-hideEmojisPickerMount', 'EmojiPicker', 'componentDidMount', function () {
* this.removeEmotes();
* });
*
* injectInFluxContainer('pc-emojiUtility-hideEmojisPicker', 'EmojiPicker', 'componentDidUpdate', function () {
* if (this.state.searchResults) {
* this.shouldFilter = true;
* } else {
* if (this.shouldFilter) {
* this.shouldFilter = false;
* this.removeEmotes();
* }
* }
* });
*/
const { AUTOCOMPLETE_OPTIONS: AutocompleteTypes } = await getModule([ 'AUTOCOMPLETE_OPTIONS' ]);
inject('pc-emojiUtility-hideEmojisComplete', AutocompleteTypes.EMOJIS_AND_STICKERS, 'queryResults', (args, res) => {
res.results.emojis = res.results.emojis.filter(emoji => !this.getHiddenGuilds().includes(emoji.guildId));
return res;
});
powercord.api.settings.registerSettings('pc-emojiUtility', {
category: this.entityID,
label: 'Emote Utility',
render: Settings
});
powercord.api.commands.registerCommand({
command: 'findemote',
description: 'Find the server an emote is from',
usage: '{c} [emote]',
executor: (args) => {
const object = this.findEmojisForCommand(args);
if (!object) {
return;
}
const { foundEmojis, notFoundEmojis } = object;
if (this.settings.get('useEmbeds')) {
return {
send: false,
result: {
type: 'rich',
description: foundEmojis.map(emoji => `${this.getFullEmoji(emoji)} is from **[${emoji.guild.name}](${this.getGuildUrl(emoji.guildId)})**`).join('\n'),
color: colors.success,
footer: notFoundEmojis.length > 0
? {
text: `${notFoundEmojis.length} of the provided arguments ${notFoundEmojis.length === 1 ? 'is not a custom emote' : 'are not custom emotes'}`
}
: null
}
};
}
let description = foundEmojis.map(emoji => `${this.getFullEmoji(emoji)} is from **${emoji.guild.name}**${this.settings.get('displayLink') ? ` (**${this.getGuildUrl(emoji.guildId)}**)` : ''}`).join('\n');
if (notFoundEmojis.length > 0) {
description += `${description.length > 0 ? '\n\n' : ''}**${notFoundEmojis.length}** of the provided arguments ${notFoundEmojis.length === 1 ? 'is not a custom emote' : 'are not custom emotes'}`;
}
return {
send: false,
result: description
};
}
});
powercord.api.commands.registerCommand({
command: 'massemote',
description: 'Send all emotes containing the specified name',
usage: '{c} [emote name]',
executor: (args) => {
const argument = args.join(' ').toLowerCase();
if (argument.length === 0) {
return this.replyError('Please provide an emote name');
}
const emojis = Object.values(this.emojiStore.getGuilds()).flatMap(g => g.emojis);
const foundEmojis = emojis.filter(emoji => emoji.name.toLowerCase().includes(argument));
if (foundEmojis.length > 0) {
const emojisAsString = foundEmojis.map(emoji => this.getFullEmoji(emoji)).join(' ');
if (emojisAsString.length > 2000) {
return {
send: false,
result: `That is more than 2000 characters, let me send that locally instead!\n${emojisAsString}`
};
}
if (!this.getCurrentUser().premiumType > 0) {
return {
send: false,
result: `Looks like you do not have nitro, let me send that locally instead!\n${emojisAsString}`
};
}
return {
send: true,
result: emojisAsString
};
}
return this.replyError(`Could not find any emotes containing **${argument}**`);
}
});
powercord.api.commands.registerCommand({
command: 'saveemote',
description: 'Save emotes to a specified directory',
usage: '{c} [emote]',
executor: async (args) => {
if (!this.settings.get('filePath')) {
return this.replyError('Please set your save directory in the settings');
}
if (!existsSync(this.settings.get('filePath'))) {
return this.replyError('The specified save directory does no longer exist, please update it in the settings');
}
const object = this.findEmojisForCommand(args);
if (!object) {
return;
}
const { foundEmojis, notFoundEmojis } = object;
if (notFoundEmojis.length > 0) {
return this.replyError(`**${notFoundEmojis.length}** of the provided arguments ${notFoundEmojis.length === 1 ? 'is not a custom emote' : 'are not custom emotes'}`);
}
if (foundEmojis.length < 5) {
for (const emoji of foundEmojis) {
try {
const name = this.settings.get('includeIdForSavedEmojis') ? `${emoji.name} (${emoji.id})` : emoji.name;
await writeFile(resolve(this.settings.get('filePath'), name + extname(parse(emoji.url).pathname)), (await get(emoji.url)).raw);
this.replySuccess(`Downloaded ${this.getFullEmoji(emoji)}`);
} catch (error) {
console.error(error);
this.replyError(`Failed to download ${this.getFullEmoji(emoji)}, check the console for more information`, {
description: `Failed to download ${this.getFullEmoji(emoji)}`,
footer: {
text: 'Check the console for more information'
}
});
}
}
} else {
this.replySuccess(`Downloading **${foundEmojis.length}** emotes, I will report back to you when I am done`);
const failedDownloads = [];
for (const emoji of foundEmojis) {
try {
const name = this.settings.get('includeIdForSavedEmojis') ? `${emoji.name} (${emoji.id})` : emoji.name;
await writeFile(resolve(this.settings.get('filePath'), name + extname(parse(emoji.url).pathname)), (await get(emoji.url)).raw);
} catch (error) {
console.error(error);
failedDownloads.push(emoji);
}
}
this.replySuccess(`Successfully downloaded **${foundEmojis.length - failedDownloads.length}**/**${foundEmojis.length}** emotes`);
}
}
});
powercord.api.commands.registerCommand({
command: 'cloneemote',
description: 'Clone an emote to your own server',
usage: '{c} [emote] [server]',
executor: async (args) => {
if (args.length === 0) {
return this.replyError('Please provide an emote');
}
const emojiRaw = args[0];
const matcher = emojiRaw.match(this.getEmojiRegex());
if (!matcher) {
return this.replyError(`**${emojiRaw}** is not a custom emote`);
}
let guild;
const guildArg = args.slice(1).join(' ');
if (guildArg.length > 0) {
guild = this.getGuildByIdOrName(guildArg);
if (!guild) {
return this.replyError('That is not a valid server');
}
} else {
if (this.settings.get('defaultCloneIdUseCurrent')) {
guild = this.getGuild(this.getChannel(this.getChannelId()).guild_id);
} else if (this.settings.get('defaultCloneId')) {
guild = this.getGuild(this.settings.get('defaultCloneId'));
if (!guild) {
return this.replyError('You are no longer in your default clone server, please update your settings');
}
}
if (!guild) {
return this.replyError('No server argument was provided');
}
}
const emoji = Object.values(this.emojiStore.getGuilds()).flatMap(g => g.emojis).find(e => e.id === matcher[2]);
if (emoji) {
try {
if (!this.hasPermission(guild.id, Permissions.MANAGE_GUILD_EXPRESSIONS)) {
return this.replyError(`Missing permissions to upload emotes in **${guild.name}**`);
}
if (this.getEmojis(guild.id, emoji.animated).length >= this.getMaxEmojiSlots(guild.id)) {
return this.replyError(`**${guild.name}** does not have any more emote slots`);
}
await this.uploadEmoji({
guildId: guild.id,
image: await this.getImageEncoded(emoji.url),
name: emoji.name,
roles: []
});
return this.replySuccess(`Cloned emote ${this.getFullEmoji(emoji)} to **${guild.name}**`);
} catch (error) {
console.error(error);
if (error.body.message) {
return this.replyError(error.body.message);
}
return this.replyError('Failed to clone emote, check the console for more information', {
description: 'Failed to clone emote',
footer: {
text: 'Check the console for more information'
}
});
}
} else {
return this.replyError(`Could not find emote ${emojiRaw}`);
}
}
});
}
pluginWillUnload () {
powercord.api.settings.unregisterSettings('pc-emojiUtility');
powercord.api.commands.unregisterCommand('cloneemote');
powercord.api.commands.unregisterCommand('findemote');
powercord.api.commands.unregisterCommand('massemote');
powercord.api.commands.unregisterCommand('saveemote');
uninject('pc-emojiUtility-emojiContext');
uninject('pc-emojiUtility-reactionContext');
uninject('pc-emojiUtility-hideEmojisPicker');
uninject('pc-emojiUtility-hideEmojisPickerRm');
uninject('pc-emojiUtility-hideEmojisPickerMount');
uninject('pc-emojiUtility-hideEmojisComplete');
}
async _injectContextMenu (cloneSubMenu, createSubMenu) {
const { imageWrapper } = await getModule([ 'imageWrapper' ]);
const { MenuSeparator } = await getModule([ 'MenuGroup' ]);
injectContextMenu('pc-emojiUtility-emojiContext', 'MessageContextMenu', ([ { target } ], res) => {
if (target.classList.contains('emoji')) {
const matcher = target.src.match(this.getEmojiUrlRegex());
if (matcher) {
let emoji = this.getEmojiById(matcher[1]);
if (emoji) {
emoji.fake = false;
} else {
emoji = this.createFakeEmoji(matcher[1], target.alt.substring(1, target.alt.length - 1), target.src);
}
res.props.children.push(
React.createElement(MenuSeparator),
...ContextMenu.renderRawItems(cloneSubMenu(emoji))
);
}
} else if (target.tagName.toLowerCase() === 'img' && target.parentElement.classList.contains(imageWrapper)) {
res.props.children.push(
React.createElement(MenuSeparator),
...ContextMenu.renderRawItems(createSubMenu(target))
);
}
return res;
});
}
};