-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.tsx
621 lines (535 loc) · 23.1 KB
/
index.tsx
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
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2023 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { definePluginSettings } from "@api/Settings";
import { makeRange } from "@components/PluginSettings/components";
import { Devs } from "@utils/constants";
import definePlugin, { OptionType } from "@utils/types";
import { findByPropsLazy } from "@webpack";
import { Button, ChannelStore, GuildStore, NavigationRouter, RelationshipStore, SelectedChannelStore, UserStore } from "@webpack/common";
import { Channel, Message, MessageAttachment, User } from "discord-types/general";
import { ReactNode } from "react";
import { Webpack } from "Vencord";
import { NotificationData, showNotification } from "./components/Notifications";
import { MessageTypes } from "./types";
import { RelationshipType } from "plugins/relationshipNotifier/types";
let ignoredUsers: string[] = [];
let notifyFor: string[] = [];
// Functional variables.
const MuteStore = Webpack.findByPropsLazy("isSuppressEveryoneEnabled");
const SelectedChannelActionCreators = findByPropsLazy("selectPrivateChannel");
const UserUtils = findByPropsLazy("getGlobalName");
// Adjustable variables.
const USER_MENTION_REGEX = /<@!?(\d{17,20})>|<#(\d{17,20})>|<@&(\d{17,20})>/g; // This regex captures user, channel, and role mentions.
enum StreamingTreatment {
NORMAL = 0,
NO_CONTENT = 1,
IGNORE = 2
}
export const settings = definePluginSettings({
position: {
type: OptionType.SELECT,
description: "The position of the toast notification",
options: [
{
label: "Bottom Left",
value: "bottom-left",
default: true
},
{
label: "Top Left",
value: "top-left"
},
{
label: "Top Right",
value: "top-right"
},
{
label: "Bottom Right",
value: "bottom-right"
},
]
},
timeout: {
type: OptionType.SLIDER,
description: "Time in seconds notifications will be shown for",
default: 5,
markers: makeRange(1, 15, 1)
},
opacity: {
type: OptionType.SLIDER,
description: "Opacity of the notification",
default: 100,
markers: makeRange(10, 100, 10)
},
maxNotifications: {
type: OptionType.SLIDER,
description: "Maximum number of notifications displayed at once",
default: 3,
markers: makeRange(1, 5, 1)
},
determineServerNotifications: {
type: OptionType.BOOLEAN,
description: "Automatically determine what server notifications to show based on your channel/guild settings",
default: true
},
disableInStreamerMode: {
type: OptionType.BOOLEAN,
description: "Disable notifications while in streamer mode",
default: true
},
renderImages: {
type: OptionType.BOOLEAN,
description: "Render images in notifications",
default: true
},
directMessages: {
type: OptionType.BOOLEAN,
description: "Show notifications for direct messages",
default: true
},
groupMessages: {
type: OptionType.BOOLEAN,
description: "Show notifications for group messages",
default: true
},
friendServerNotifications: {
type: OptionType.BOOLEAN,
description: "Show notifications when friends send messages in servers they share with you",
default: true
},
friendActivity: {
type: OptionType.BOOLEAN,
description: "Show notifications for friend activity",
default: true
},
streamingTreatment: {
type: OptionType.SELECT,
description: "How to treat notifications while sharing your screen",
options: [
{
label: "Normal - Show the notification as normal",
value: StreamingTreatment.NORMAL,
default: true
},
{
label: "No Content - Hide the notification body",
value: StreamingTreatment.NO_CONTENT
},
{
label: "Ignore - Don't show the notification at all",
value: StreamingTreatment.IGNORE
}
]
},
notifyFor: {
type: OptionType.STRING,
description: "Create a list of channel ids to receive notifications from (separate with commas)",
onChange: () => { notifyFor = stringToList(settings.store.notifyFor); },
default: ""
},
ignoreUsers: {
type: OptionType.STRING,
description: "Create a list of user ids to ignore all their notifications from (separate with commas)",
onChange: () => { ignoredUsers = stringToList(settings.store.ignoreUsers); },
default: ""
},
exampleButton: {
type: OptionType.COMPONENT,
description: "Show an example toast notification.",
component: () =>
<Button onClick={showExampleNotification}>
Show Example Notification
</Button>
}
});
function stringToList(str: string): string[] {
if (str !== "") {
const array: string[] = [];
const string = str.replace(/\s/g, '');
const splitArray = string.split(",");
splitArray.forEach((id) => {
array.push(id);
});
return array;
}
return [];
}
function limitMessageLength(body: string, hasAttachments: boolean): string {
if (hasAttachments) {
if (body?.length > 30) {
return body.substring(0, 27) + "...";
}
}
if (body?.length > 165) {
return body.substring(0, 162) + "...";
}
return body;
}
/**
* getName()
* Helper function to get a user's nickname if they have one, otherwise their username.
*
* @param {User} user The user to get the name of.
* @returns {String} The name of the user.
*/
function getName(user: User): string {
return RelationshipStore.getNickname(user.id) ?? UserUtils.getName(user);
}
/**
* addMention()
* Helper function to add a mention to a notification.
*
* @param {string} id The id of the user, channel or role.
* @param {string} type The type of mention.
* @param {string} guildId The id of the guild.
* @returns {ReactNode} The mention as a ReactNode.
*/
const addMention = (id: string, type: string, guildId?: string): ReactNode => {
let name;
if (type === "user")
name = `@${UserStore.getUser(id)?.username || "unknown-user"}`;
else if (type === "channel")
name = `#${ChannelStore.getChannel(id)?.name || "unknown-channel"}`;
else if (type === "role" && guildId)
name = `@${GuildStore.getGuild(guildId).getRole(id)?.name || "unknown-role"}`;
// Return the mention as a styled span.
return (
<span key={`${type}-${id}`} className={"toastnotifications-mention-class"}>
{name}
</span>
);
};
export default definePlugin({
name: "ToastNotifications",
description: "Show a toast notification whenever you receive a direct message.",
authors: [
{
name: "Skully",
id: 150298098516754432n
},
{
name: "Ethan",
id: 721717126523781240n
},
{
name: "Buzzy",
id: 1273353654644117585n
}
],
settings,
flux: {
async MESSAGE_CREATE({ message }: { message: Message; }) {
const channel: Channel = ChannelStore.getChannel(message.channel_id);
const currentUser = UserStore.getCurrentUser();
const isStreaming = Vencord.Webpack.findStore('ApplicationStreamingStore').getState().activeStreams?.length >= 1;
const streamerMode = settings.store.disableInStreamerMode;
const currentUserStreamerMode = Vencord.Webpack.findStore("StreamerModeStore").enabled;
if (streamerMode && currentUserStreamerMode) return;
if (isStreaming && settings.store.streamingTreatment === StreamingTreatment.IGNORE) return;
if (
(
(message.author.id === currentUser.id) // If message is from the user.
|| (channel.id === SelectedChannelStore.getChannelId()) // If the user is currently in the channel.
|| (ignoredUsers.includes(message.author.id)) // If the user is ignored.
)
) return;
if (channel.guild_id) { // If this is a guild message and not a private message.
handleGuildMessage(message);
return;
}
if (!settings.store.directMessages && channel.isDM() || !settings.store.groupMessages && channel.isGroupDM() || MuteStore.isChannelMuted(null, channel.id)) return;
// Prepare the notification.
const Notification: NotificationData = {
title: getName(message.author),
icon: `https://cdn.discordapp.com/avatars/${message.author.id}/${message.author.avatar}.png?size=128`,
body: message.content,
attachments: message.attachments?.length,
richBody: null,
permanent: false,
onClick() { SelectedChannelActionCreators.selectPrivateChannel(message.channel_id); }
};
const notificationText = message.content?.length > 0 ? message.content : false;
const richBodyElements: React.ReactNode[] = [];
// If this channel is a group DM, include the channel name.
if (channel.isGroupDM()) {
let channelName = channel.name?.trim() ?? false;
if (!channelName) { // If the channel doesn't have a set name, use the first 3 recipients.
channelName = channel.rawRecipients.slice(0, 3).map(e => e.username).join(", ");
}
// Finally, truncate the channel name if it's too long.
const truncatedChannelName = channelName?.length > 20 ? channelName.substring(0, 20) + "..." : channelName;
Notification.title = `${message.author.username} (${truncatedChannelName})`;
}
else if (channel.guild_id) // If this is a guild message and not a private message.
{
Notification.title = `${getName(message.author)} (#${channel.name})`;
}
// Handle specific message types.
switch (message.type) {
case MessageTypes.CALL: {
Notification.body = "Started a call with you!";
break;
}
case MessageTypes.CHANNEL_RECIPIENT_ADD: {
const actor = UserStore.getUser(message.author.id);
const targetUser = UserStore.getUser(message.mentions[0]?.id);
Notification.body = `${getName(targetUser)} was added to the group by ${getName(actor)}.`;
break;
}
case MessageTypes.CHANNEL_RECIPIENT_REMOVE: {
const actor = UserStore.getUser(message.author.id);
const targetUser = UserStore.getUser(message.mentions[0]?.id);
if (actor.id !== targetUser.id) {
Notification.body = `${getName(targetUser)} was removed from the group by ${getName(actor)}.`;
} else {
Notification.body = "Left the group.";
}
break;
}
case MessageTypes.CHANNEL_NAME_CHANGE: {
Notification.body = `Changed the channel name to '${message.content}'.`;
break;
}
case MessageTypes.CHANNEL_ICON_CHANGE: {
Notification.body = "Changed the channel icon.";
break;
}
case MessageTypes.CHANNEL_PINNED_MESSAGE: {
Notification.body = "Pinned a message.";
break;
}
}
// Message contains an embed.
if (message.embeds?.length !== 0) {
Notification.body = notificationText || "Sent an embed.";
}
// Message contains a sticker.
if (message?.stickerItems) {
Notification.body = notificationText || "Sent a sticker.";
}
// Message contains an attachment.
if (message.attachments?.length !== 0) {
const images = message.attachments.filter(e => typeof e?.content_type === "string" && e?.content_type.startsWith("image"));
// Label the notification with the attachment type.
if (images?.length !== 0) {
Notification.body = notificationText || ""; // Dont show any body
Notification.image = images[0].url;
} else {
Notification.body += ` [Attachment: ${message.attachments[0].filename}]`;
}
}
// TODO: Format emotes properly.
const matches = Notification.body.match(new RegExp("(<a?:\\w+:\\d+>)", "g"));
if (matches) {
for (const match of matches) {
Notification.body = Notification.body.replace(new RegExp(`${match}`, "g"), `:${match.split(":")[1]}:`);
}
}
// Replace any mention of users, roles and channels.
if (message.mentions?.length !== 0 || message.mentionRoles?.length > 0) {
let lastIndex = 0;
Notification.body.replace(USER_MENTION_REGEX, (match, userId, channelId, roleId, offset) => {
richBodyElements.push(Notification.body.slice(lastIndex, offset));
// Add the mention itself as a styled span.
if (userId) {
richBodyElements.push(addMention(userId, "user"));
} else if (channelId) {
richBodyElements.push(addMention(channelId, "channel"));
} else if (roleId) {
richBodyElements.push(addMention(roleId, "role", channel.guild_id));
}
lastIndex = offset + match?.length;
return match; // This value is not used but is necessary for the replace function
});
}
if (richBodyElements?.length > 0) {
const MyRichBodyComponent = () => <>{richBodyElements}</>;
Notification.richBody = <MyRichBodyComponent />;
}
Notification.body = limitMessageLength(Notification.body, Notification.attachments > 0);
if (isStreaming && settings.store.streamingTreatment === StreamingTreatment.NO_CONTENT) {
Notification.body = "Message content has been redacted.";
};
showNotification(Notification);
},
async RELATIONSHIP_ADD({ relationship }) {
if (ignoredUsers.includes(relationship.user.id)) return;
relationshipAdd(relationship.user, relationship.type);
}
},
start() {
ignoredUsers = stringToList(settings.store.ignoreUsers);
notifyFor = stringToList(settings.store.notifyFor);
}
});
function switchChannels(guildId: string | null, channelId: string) {
if (!ChannelStore.hasChannel(channelId)) return;
NavigationRouter.transitionTo(`/channels/${guildId ?? "@me"}/${channelId}/`);
}
enum NotificationLevel {
ALL_MESSAGES = 0,
ONLY_MENTIONS = 1,
NO_MESSAGES = 2
}
function findNotificationLevel(channel: Channel): NotificationLevel {
const store = Vencord.Webpack.findStore("UserGuildSettingsStore");
const userGuildSettings = store.getAllSettings().userGuildSettings[channel.guild_id];
if (!settings.store.determineServerNotifications || MuteStore.isGuildOrCategoryOrChannelMuted(channel.guild_id, channel.id)) {
return NotificationLevel.NO_MESSAGES;
}
if (userGuildSettings) {
const channelOverrides = userGuildSettings.channel_overrides?.[channel.id];
const guildDefault = userGuildSettings.message_notifications;
// Check if channel overrides exist and are in the expected format
if (channelOverrides && typeof channelOverrides === 'object' && 'message_notifications' in channelOverrides) {
return channelOverrides.message_notifications;
}
// Check if guild default is in the expected format
if (typeof guildDefault === 'number') {
return guildDefault;
}
}
// Return a default value if no valid overrides or guild default is found
return NotificationLevel.NO_MESSAGES;
}
async function handleGuildMessage(message: Message) {
const c = ChannelStore.getChannel(message.channel_id);
const notificationLevel: number = findNotificationLevel(c);
let t = false;
/*
0: All messages
1: Only mentions
2: No messages
*/
// console.log("[NOTIFICATION LEVEL] " + notificationLevel); // Avoid nuking the whole console
// !! IF ITS ONLY MENTIONS REPLYS ARE GOING THROUGH
// todo: check if the user who sent it is a friend
const all = notifyFor.includes(message.channel_id);
const friend = settings.store.friendServerNotifications && RelationshipStore.isFriend(message.author.id);
if (!all || !friend) {
t = true;
const isMention: boolean = message.content.includes(`<@${UserStore.getCurrentUser().id}>`);
const meetsMentionCriteria = notificationLevel !== NotificationLevel.ALL_MESSAGES && !isMention;
if (notificationLevel === NotificationLevel.NO_MESSAGES || meetsMentionCriteria) return;
}
const channel: Channel = ChannelStore.getChannel(message.channel_id);
const notificationText = message.content.length > 0 ? message.content : false;
const richBodyElements: React.ReactNode[] = [];
const g = GuildStore.getGuild(c.guild_id);
// console.log("[DEBUG] [CHANNEL] " + JSON.stringify(c));
// console.log("[DEBUG] [GUILD] " + JSON.stringify(g));
// Prepare the notification.
const Notification: NotificationData = {
title: `${getName(message.author)} (#${channel.name})`,
icon: `https://cdn.discordapp.com/avatars/${message.author.id}/${message.author.avatar}.png?size=128`,
body: message.content,
attachments: message.attachments?.length,
richBody: null,
permanent: false,
onClick() { switchChannels(channel.guild_id, channel.id); }
};
if (message.embeds?.length !== 0) {
Notification.body = notificationText || "Sent an embed.";
}
// Message contains a sticker.
if (message?.stickerItems) {
Notification.body = notificationText || "Sent a sticker.";
}
// Message contains an attachment.
if (message.attachments?.length !== 0) {
const images = message.attachments.filter(e => typeof e?.content_type === "string" && e?.content_type.startsWith("image"));
// Label the notification with the attachment type.
if (images?.length !== 0) {
Notification.body = notificationText || ""; // Dont show any body
Notification.image = images[0].url;
} else {
Notification.body += ` [Attachment: ${message.attachments[0].filename}]`;
}
}
// TODO: Format emotes properly.
const matches = Notification.body.match(new RegExp("(<a?:\\w+:\\d+>)", "g"));
if (matches) {
for (const match of matches) {
Notification.body = Notification.body.replace(new RegExp(`${match}`, "g"), `:${match.split(":")[1]}:`);
}
}
// Replace any mention of users, roles and channels.
if (message.mentions?.length !== 0 || message.mentionRoles?.length > 0) {
let lastIndex = 0;
Notification.body.replace(USER_MENTION_REGEX, (match, userId, channelId, roleId, offset) => {
richBodyElements.push(Notification.body.slice(lastIndex, offset));
// Add the mention itself as a styled span.
if (userId) {
richBodyElements.push(addMention(userId, "user"));
} else if (channelId) {
richBodyElements.push(addMention(channelId, "channel"));
} else if (roleId) {
richBodyElements.push(addMention(roleId, "role", channel.guild_id));
}
lastIndex = offset + match?.length;
return match; // This value is not used but is necessary for the replace function
});
}
if (richBodyElements?.length > 0) {
const MyRichBodyComponent = () => <>{richBodyElements}</>;
Notification.richBody = <MyRichBodyComponent />;
}
Notification.body = limitMessageLength(Notification.body, Notification.attachments > 0);
const isStreaming = Vencord.Webpack.findStore('ApplicationStreamingStore').getState().activeStreams?.length >= 1;
if (isStreaming && settings.store.streamingTreatment === StreamingTreatment.NO_CONTENT) {
Notification.body = "Message content has been redacted.";
};
console.log("noti that went through: " + t);
await showNotification(Notification);
}
async function relationshipAdd(user: User, type: Number) {
user = UserStore.getUser(user.id);
if (!settings.store.friendActivity) return;
let notification: NotificationData = {
title: "",
icon: user.getAvatarURL(),
body: "",
attachments: 0,
};
if (type === RelationshipType.FRIEND) {
notification.title = `${user.username} is now your friend`;
notification.body = "You can now message them directly.";
notification.onClick = () => switchChannels(null, user.id);
await showNotification(notification);
} else if (type === RelationshipType.INCOMING_REQUEST) {
notification.title = `${user.username} sent you a friend request`;
notification.body = "You can accept or decline it in the Friends tab.";
notification.onClick = () => switchChannels(null, "");
await showNotification(notification);
}
}
/**
* showExampleNotification()
* Helper function to show an example notification.
*
* @returns {Promise<void>} A promise that resolves when the notification is shown.
*/
function showExampleNotification(): Promise<void> {
return showNotification({
title: "Example Notification",
icon: `https://cdn.discordapp.com/avatars/${UserStore.getCurrentUser().id}/${UserStore.getCurrentUser().avatar}.png?size=128`,
body: "This is an example toast notification!",
attachments: 0,
permanent: false
});
}