-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathNotification.ts
More file actions
194 lines (164 loc) · 5.95 KB
/
Notification.ts
File metadata and controls
194 lines (164 loc) · 5.95 KB
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
// Ideally all the Notification-related types would be in @cap/web-domain
// but @cap/web-api-contract is the closest we have right now
import { notifications, videos, users, comments } from "@cap/database/schema";
import { db } from "@cap/database";
import { and, eq, sql } from "drizzle-orm";
import { nanoId } from "@cap/database/helpers";
import { UserPreferences } from "@/app/(org)/dashboard/dashboard-data";
import { revalidatePath } from "next/cache";
import { Notification, NotificationBase } from "@cap/web-api-contract";
export type NotificationType = Notification["type"];
// Notification daata without id, readTime, etc
type NotificationSpecificData = DistributiveOmit<
Notification,
keyof NotificationBase
>;
// Replaces author object with authorId since we query for that info.
// If we add more notifications this would probably be better done manually
// Type is weird since we need to operate on each member of the NotificationSpecificData union
type CreateNotificationInput<D = NotificationSpecificData> =
D extends NotificationSpecificData
? D["author"] extends never
? D
: Omit<D, "author"> & { authorId: string } & { parentCommentId?: string }
: never;
export async function createNotification(
notification: CreateNotificationInput
) {
try {
// First, get the video and owner data
const [videoResult] = await db()
.select({
videoId: videos.id,
ownerId: users.id,
activeOrganizationId: users.activeOrganizationId,
preferences: users.preferences,
})
.from(videos)
.innerJoin(users, eq(users.id, videos.ownerId))
.where(eq(videos.id, notification.videoId))
.limit(1);
if (!videoResult) {
throw new Error("Video or owner not found");
}
const { type, ...data } = notification;
// Handle replies: notify the parent comment's author
if (type === "reply" && notification.parentCommentId) {
const [parentComment] = await db()
.select({ authorId: comments.authorId })
.from(comments)
.where(eq(comments.id, notification.parentCommentId))
.limit(1);
const recipientId = parentComment?.authorId;
if (!recipientId) return;
if (recipientId === videoResult.ownerId) return;
const [recipientUser] = await db()
.select({
preferences: users.preferences,
activeOrganizationId: users.activeOrganizationId,
})
.from(users)
.where(eq(users.id, recipientId))
.limit(1);
if (!recipientUser) {
console.warn(`Reply recipient user ${recipientId} not found`);
return;
}
const recipientPrefs = recipientUser.preferences as
| UserPreferences
| undefined;
if (recipientPrefs?.notifications?.pauseReplies) return;
const [existingReply] = await db()
.select({ id: notifications.id })
.from(notifications)
.where(
and(
eq(notifications.type, "reply"),
eq(notifications.recipientId, recipientId),
sql`JSON_EXTRACT(${notifications.data}, '$.comment.id') = ${notification.comment.id}`
)
)
.limit(1);
if (existingReply) return;
const notificationId = nanoId();
await db().insert(notifications).values({
id: notificationId,
orgId: recipientUser.activeOrganizationId,
recipientId,
type,
data,
});
revalidatePath("/dashboard");
return { success: true, notificationId };
}
// Skip notification if the video owner is the current user
// (this only applies to non-reply types)
if (videoResult.ownerId === notification.authorId) {
return;
}
// Check user preferences
const preferences = videoResult.preferences as UserPreferences;
if (preferences?.notifications) {
const notificationPrefs = preferences.notifications;
const shouldSkipNotification =
(type === "comment" && notificationPrefs.pauseComments) ||
(type === "view" && notificationPrefs.pauseViews) ||
(type === "reaction" && notificationPrefs.pauseReactions);
if (shouldSkipNotification) {
return;
}
}
// Check for existing notification to prevent duplicates
let hasExistingNotification = false;
if (type === "view") {
const [existingNotification] = await db()
.select({ id: notifications.id })
.from(notifications)
.where(
and(
eq(notifications.type, "view"),
eq(notifications.recipientId, videoResult.ownerId),
sql`JSON_EXTRACT(${notifications.data}, '$.videoId') = ${notification.videoId}`,
sql`JSON_EXTRACT(${notifications.data}, '$.authorId') = ${notification.authorId}`
)
)
.limit(1);
hasExistingNotification = !!existingNotification;
} else if (type === "comment" || type === "reaction") {
const [existingNotification] = await db()
.select({ id: notifications.id })
.from(notifications)
.where(
and(
eq(notifications.type, type),
eq(notifications.recipientId, videoResult.ownerId),
sql`JSON_EXTRACT(${notifications.data}, '$.comment.id') = ${notification.comment.id}`
)
)
.limit(1);
hasExistingNotification = !!existingNotification;
}
if (hasExistingNotification) {
return;
}
const notificationId = nanoId();
if (!videoResult.activeOrganizationId) {
console.warn(
`User ${videoResult.ownerId} has no active organization, skipping notification`
);
return;
}
await db().insert(notifications).values({
id: notificationId,
orgId: videoResult.activeOrganizationId,
recipientId: videoResult.ownerId,
type,
data,
});
revalidatePath("/dashboard");
return { success: true, notificationId };
} catch (error) {
console.error("Error creating notification:", error);
throw error;
}
}