Repository navigation
Expand file tree
/
Copy pathcontent.ts
More file actions
1435 lines (1302 loc) · 45 KB
/
Copy pathcontent.ts
File metadata and controls
1435 lines (1302 loc) · 45 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
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
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { createTRPCRouter, publicProcedure, protectedProcedure } from "../trpc";
import {
GetUnifiedFeedSchema,
GetContentBySlugSchema,
CreateContentSchema,
UpdateContentSchema,
DeleteContentSchema,
VoteContentSchema,
BookmarkContentSchema,
TrackClickContentSchema,
GetSavedContentSchema,
EditDraftContentSchema,
PublishContentSchema,
MyDraftsContentSchema,
MyPublishedContentSchema,
MyScheduledContentSchema,
} from "../../../schema/content";
import {
posts,
post_votes,
bookmarks,
post_tags,
feed_sources,
follow,
tag as dbTag,
user,
point_event,
post_metadata,
} from "@/server/db/schema";
import {
and,
or,
eq,
desc,
lt,
lte,
sql,
isNull,
exists,
inArray,
} from "drizzle-orm";
import { increment } from "./utils";
import { rankCandidates, hasProfileSignal } from "@/server/lib/feedRanking";
import {
loadUserProfile,
loadTopicsByPost,
} from "@/server/lib/feedPersonalization";
import { applyGate, notifyAdminOfReview } from "@/server/lib/moderation";
import { runDedupeAndGate } from "@/server/lib/dedupe";
import { enforceRateLimit, clientIpFromHeaders } from "@/server/lib/rateLimit";
import { award } from "@/server/lib/engagement";
import { mintUrlId } from "@/server/lib/url-id";
import { buildSlug, buildContentHref } from "@/server/lib/content-url";
import { submitToIndexNow } from "@/server/lib/indexnow";
import { SITE_ORIGIN } from "@/config/site";
// Absolute canonical URL for a freshly published member post, matching the
// sitemap scheme (shared path rules in buildContentHref). The slug already
// ends with the urlId. Returns null when we can't build a stable public URL
// (no username) so callers skip the IndexNow ping rather than submit a 404.
function memberPostUrl(
dbType: DbPostType,
slug: string,
username: string | null | undefined,
): string | null {
const path = buildContentHref({
type: dbType,
slug,
authorUsername: username,
});
return path ? `${SITE_ORIGIN}${path}` : null;
}
function calculateReadTime(body: string | null | undefined): number {
if (!body) return 1;
const wordsPerMinute = 200;
const words = body.trim().split(/\s+/).length;
return Math.max(1, Math.ceil(words / wordsPerMinute));
}
type DbPostType =
"article" | "discussion" | "link" | "resource" | "til" | "question";
function toDbType(frontendType: string): DbPostType {
const typeMap: Record<string, DbPostType> = {
POST: "article",
ARTICLE: "article",
LINK: "link",
TIL: "til",
QUESTION: "question",
VIDEO: "link",
DISCUSSION: "discussion",
article: "article",
link: "link",
discussion: "discussion",
resource: "resource",
til: "til",
question: "question",
};
return typeMap[frontendType] || "article";
}
function toFrontendType(dbType: string): string {
const typeMap: Record<string, string> = {
article: "POST",
link: "LINK",
discussion: "DISCUSSION",
resource: "LINK",
til: "TIL",
question: "QUESTION",
};
return typeMap[dbType] || dbType.toUpperCase();
}
export const contentRouter = createTRPCRouter({
getFeed: publicProcedure
.input(GetUnifiedFeedSchema)
.query(async ({ ctx, input }) => {
const userId = ctx.session?.user?.id;
const limit = input?.limit ?? 25;
const { cursor, sort, type, kinds, sourceId, category, tag, following } =
input;
const userVotes = userId
? ctx.db
.select({
postId: post_votes.postId,
voteType: post_votes.voteType,
})
.from(post_votes)
.where(eq(post_votes.userId, userId))
.as("userVotes")
: null;
const userBookmarks = userId
? ctx.db
.select({
postId: bookmarks.postId,
})
.from(bookmarks)
.where(eq(bookmarks.userId, userId))
.as("userBookmarks")
: null;
const scoreExpr = sql<number>`(${posts.upvotesCount} - ${posts.downvotesCount})`;
// Published AND past its publish time — scheduled releases carry a
// future publishedAt and must not leak into the feed early. A NULL
// publishedAt (legacy/imported rows) counts as visible, not hidden.
const conditions = [
eq(posts.status, "published"),
or(
lte(posts.publishedAt, new Date().toISOString()),
isNull(posts.publishedAt),
)!,
];
if (type) {
const dbType = toDbType(type);
conditions.push(eq(posts.type, dbType));
}
// Multi-kind filter (e.g. Discussions = discussion + question)
if (kinds && kinds.length > 0) {
const dbKinds = [...new Set(kinds.map(toDbType))];
conditions.push(inArray(posts.type, dbKinds));
}
if (sourceId) {
conditions.push(eq(posts.sourceId, sourceId));
}
if (category) {
conditions.push(eq(feed_sources.category, category));
}
if (tag) {
conditions.push(
exists(
ctx.db
.select({ one: sql`1` })
.from(post_tags)
.innerJoin(dbTag, eq(post_tags.tagId, dbTag.id))
.where(and(eq(post_tags.postId, posts.id), eq(dbTag.slug, tag))),
),
);
}
if (following && userId) {
conditions.push(
exists(
ctx.db
.select({ one: sql`1` })
.from(follow)
.where(
and(
eq(follow.followingId, posts.authorId),
eq(follow.followerId, userId),
),
),
),
);
}
const getOrderAndCursor = () => {
switch (sort) {
case "recent":
return {
orderBy: desc(posts.publishedAt),
cursorCondition: cursor?.publishedAt
? lte(posts.publishedAt, cursor.publishedAt)
: undefined,
};
case "trending":
return {
orderBy: desc(scoreExpr),
cursorCondition:
cursor?.score !== undefined
? lt(scoreExpr, cursor.score)
: undefined,
};
case "popular":
return {
orderBy: desc(posts.upvotesCount),
cursorCondition:
cursor?.score !== undefined
? lt(posts.upvotesCount, cursor.score)
: undefined,
};
default:
return {
orderBy: desc(posts.publishedAt),
cursorCondition: undefined,
};
}
};
const { orderBy, cursorCondition } = getOrderAndCursor();
if (cursorCondition) {
conditions.push(cursorCondition);
}
let query;
if (userVotes && userBookmarks) {
query = ctx.db
.select({
id: posts.id,
type: posts.type,
title: posts.title,
excerpt: posts.excerpt,
externalUrl: posts.externalUrl,
imageUrl: posts.coverImage,
ogImageUrl: posts.coverImage,
slug: posts.slug,
urlId: posts.urlId,
publishedAt: posts.publishedAt,
upvotes: posts.upvotesCount,
downvotes: posts.downvotesCount,
clickCount: posts.viewsCount,
readTimeMins: posts.readingTime,
userId: posts.authorId,
sourceId: posts.sourceId,
sourceAuthor: posts.sourceAuthor,
createdAt: posts.createdAt,
sourceName: feed_sources.name,
sourceSlug: feed_sources.slug,
sourceLogo: feed_sources.logoUrl,
sourceWebsite: feed_sources.websiteUrl,
sourceCategory: feed_sources.category,
authorName: user.name,
authorUsername: user.username,
authorImage: user.image,
userVote: userVotes.voteType,
isBookmarked: sql<boolean>`${userBookmarks.postId} IS NOT NULL`,
})
.from(posts)
.leftJoin(feed_sources, eq(posts.sourceId, feed_sources.id))
.leftJoin(user, eq(posts.authorId, user.id))
.leftJoin(userVotes, eq(posts.id, userVotes.postId))
.leftJoin(userBookmarks, eq(posts.id, userBookmarks.postId))
.where(and(...conditions))
.orderBy(orderBy)
.limit(limit + 1);
} else {
query = ctx.db
.select({
id: posts.id,
type: posts.type,
title: posts.title,
excerpt: posts.excerpt,
externalUrl: posts.externalUrl,
imageUrl: posts.coverImage,
ogImageUrl: posts.coverImage,
slug: posts.slug,
urlId: posts.urlId,
publishedAt: posts.publishedAt,
upvotes: posts.upvotesCount,
downvotes: posts.downvotesCount,
clickCount: posts.viewsCount,
readTimeMins: posts.readingTime,
userId: posts.authorId,
sourceId: posts.sourceId,
sourceAuthor: posts.sourceAuthor,
createdAt: posts.createdAt,
sourceName: feed_sources.name,
sourceSlug: feed_sources.slug,
sourceLogo: feed_sources.logoUrl,
sourceWebsite: feed_sources.websiteUrl,
sourceCategory: feed_sources.category,
authorName: user.name,
authorUsername: user.username,
authorImage: user.image,
userVote: sql<"up" | "down" | null>`NULL`,
isBookmarked: sql<boolean>`FALSE`,
})
.from(posts)
.leftJoin(feed_sources, eq(posts.sourceId, feed_sources.id))
.leftJoin(user, eq(posts.authorId, user.id))
.where(and(...conditions))
.orderBy(orderBy)
.limit(limit + 1);
}
const results = await query;
let nextCursor:
{ id: string; publishedAt?: string; score?: number } | undefined;
if (results.length > limit) {
const lastItem = results.pop()!;
const score = lastItem.upvotes - lastItem.downvotes;
nextCursor = {
id: lastItem.id,
publishedAt: lastItem.publishedAt || undefined,
score,
};
}
const mappedItems = results.map((item) => ({
...item,
type: toFrontendType(item.type),
}));
return {
items: mappedItems,
nextCursor,
};
}),
create: protectedProcedure
.input(CreateContentSchema)
.mutation(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
// Throttle publishing so the quick-compose path can't be scripted to
// flood the feed (drafts are unmetered). 10 published posts / 5 min.
if (input.published) {
await enforceRateLimit({
key: `create:${userId}`,
limit: 10,
windowMs: 5 * 60_000,
message: "You're posting too fast. Take a breather and try again.",
});
}
if (input.type === "POST" && !input.body) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Body is required for posts",
});
}
if (
(input.type === "LINK" || input.type === "VIDEO") &&
!input.externalUrl
) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "External URL is required for links and videos",
});
}
const urlId = mintUrlId();
const slug = buildSlug(input.title, urlId);
const readingTime = calculateReadTime(input.body);
const dbType = toDbType(input.type);
// Going-live gate (dedupe + moderation). Only runs on a direct go-live so
// a client can't self-publish around review; drafts stay drafts. May throw
// CONFLICT for a hard duplicate (propagates to the client). When not going
// live there's no gate result and the row is a plain draft.
const gate = input.published
? await runDedupeAndGate({
type: dbType,
title: input.title,
body: input.body,
externalUrl: input.externalUrl,
})
: null;
const dbStatus = gate ? gate.status : "draft";
// Create writes the gate fields inline (typed insert) rather than via
// applyGate; gate may be null on the draft path, and the `gate?.X ?? null`
// form already keeps all four fields in sync, so there's no drift to fix.
const [newContent] = await ctx.db
.insert(posts)
.values({
type: dbType,
title: input.title,
body: input.body,
excerpt: input.excerpt,
externalUrl: input.externalUrl,
externalUrlNormalized: gate?.externalUrlNormalized ?? null,
coverImage: input.imageUrl || input.coverImage,
canonicalUrl: input.canonicalUrl,
authorId: userId,
slug,
urlId,
readingTime,
status: dbStatus,
moderationNote: gate?.moderationNote ?? null,
// No publishedAt while in review — admin approval sets it.
publishedAt: gate?.publishedAt ?? null,
showComments: input.showComments ?? true,
})
.returning();
// Notify the admin there's something to review (fire-and-forget).
if (newContent && gate?.status === "in_review") {
void notifyAdminOfReview({
postId: newContent.id,
title: input.title,
authorName: ctx.session.user.name,
});
}
if (input.tags && input.tags.length > 0) {
for (const tagName of input.tags) {
const existingTags = await ctx.db
.select({ id: dbTag.id })
.from(dbTag)
.where(eq(dbTag.title, tagName.toLowerCase()))
.limit(1);
let tagId: number;
if (existingTags.length > 0) {
tagId = existingTags[0].id;
} else {
const title = tagName.toLowerCase();
// Always set a slug — null slugs break tag links + React keys.
const tagSlug =
title
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "") || title;
const [newTag] = await ctx.db
.insert(dbTag)
.values({ title, slug: tagSlug })
.returning();
tagId = newTag.id;
}
await ctx.db
.insert(post_tags)
.values({ postId: newContent.id, tagId })
.onConflictDoNothing();
}
}
// Award points when a post goes live directly; skipped when routed to
// review (the admin-approval path awards on publish instead). Never throws.
if (newContent && gate?.status === "published") {
await award({
userId,
action: "post_published",
sourceType: "post",
sourceId: newContent.id,
});
// Ping IndexNow (fire-and-forget, guarded inside the lib). Skip
// cross-posted content — its canonical lives off Codú.
if (!input.canonicalUrl) {
const url = memberPostUrl(dbType, slug, ctx.session.user.username);
if (url) void submitToIndexNow(url);
}
}
return newContent;
}),
update: protectedProcedure
.input(UpdateContentSchema)
.mutation(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
const existing = await ctx.db
.select({
authorId: posts.authorId,
type: posts.type,
title: posts.title,
body: posts.body,
externalUrl: posts.externalUrl,
status: posts.status,
})
.from(posts)
.where(eq(posts.id, input.id))
.limit(1);
if (existing.length === 0) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Content not found",
});
}
if (existing[0].authorId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You can only edit your own content",
});
}
const updateData: Record<string, unknown> = {};
if (input.title !== undefined) updateData.title = input.title;
if (input.body !== undefined) {
updateData.body = input.body;
updateData.readingTime = calculateReadTime(input.body);
}
if (input.excerpt !== undefined) updateData.excerpt = input.excerpt;
if (input.externalUrl !== undefined)
updateData.externalUrl = input.externalUrl;
if (input.imageUrl !== undefined) updateData.coverImage = input.imageUrl;
if (input.coverImage !== undefined)
updateData.coverImage = input.coverImage;
if (input.canonicalUrl !== undefined)
updateData.canonicalUrl = input.canonicalUrl;
if (input.showComments !== undefined)
updateData.showComments = input.showComments;
// Moderation owns these lifecycle states — same guard as the publish
// mutation, else update({published:true}) force-publishes around a
// moderator's schedule or rejection. Pulling back to draft stays allowed.
if (
input.published === true &&
(existing[0].status === "scheduled" ||
existing[0].status === "in_review" ||
existing[0].status === "rejected")
) {
throw new TRPCError({
code: "CONFLICT",
message:
existing[0].status === "scheduled"
? "This post is scheduled and will be published automatically."
: "This post is awaiting moderation review.",
});
}
// Going-live gate (dedupe + moderation): a draft→live transition via
// update must go through review too, else a client self-publishes by
// setting published:true here instead of calling publish. Gate input is
// completed from the existing row (title/body/externalUrl), since update
// input may omit them. May throw CONFLICT for a hard duplicate.
const goingLive =
input.published === true && existing[0].status !== "published";
let gate: Awaited<ReturnType<typeof runDedupeAndGate>> | null = null;
if (input.published !== undefined) {
if (goingLive) {
gate = await runDedupeAndGate({
type: existing[0].type,
title: input.title ?? existing[0].title,
body: input.body ?? existing[0].body,
externalUrl:
input.externalUrl !== undefined
? input.externalUrl
: existing[0].externalUrl,
});
// Writes all four gate fields. publishedAt is the gate's now when
// published, null while in review (admin approval sets it). This
// handler has no publishTime scheduling, so no override is needed.
applyGate(updateData, gate);
} else {
// Not going live (e.g. unpublish, or already published) — preserve the
// previous straightforward status flip with no gating.
updateData.status = input.published ? "published" : "draft";
if (input.published) {
updateData.publishedAt = new Date().toISOString();
}
}
}
const [updated] = await ctx.db
.update(posts)
.set(updateData)
.where(eq(posts.id, input.id))
.returning();
// Notify the admin there's something to review (fire-and-forget).
if (updated && gate?.status === "in_review") {
void notifyAdminOfReview({
postId: input.id,
title: input.title ?? existing[0].title,
authorName: ctx.session.user.name,
});
}
// Ping IndexNow when the update leaves the post live (new go-live or edit to
// published content). Fire-and-forget; skip posts that canonical off Codú.
if (updated?.status === "published" && !updated.canonicalUrl) {
const url = memberPostUrl(
updated.type,
updated.slug,
ctx.session.user.username,
);
if (url) void submitToIndexNow(url);
}
if (input.tags !== undefined) {
await ctx.db.delete(post_tags).where(eq(post_tags.postId, input.id));
for (const tagName of input.tags) {
const existingTags = await ctx.db
.select({ id: dbTag.id })
.from(dbTag)
.where(eq(dbTag.title, tagName.toLowerCase()))
.limit(1);
let tagId: number;
if (existingTags.length > 0) {
tagId = existingTags[0].id;
} else {
const title = tagName.toLowerCase();
// Always set a slug — null slugs break tag links + React keys.
const tagSlug =
title
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "") || title;
const [newTag] = await ctx.db
.insert(dbTag)
.values({ title, slug: tagSlug })
.returning();
tagId = newTag.id;
}
await ctx.db
.insert(post_tags)
.values({ postId: input.id, tagId })
.onConflictDoNothing();
}
}
return updated;
}),
delete: protectedProcedure
.input(DeleteContentSchema)
.mutation(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
const existing = await ctx.db
.select({ authorId: posts.authorId })
.from(posts)
.where(eq(posts.id, input.id))
.limit(1);
if (existing.length === 0) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Content not found",
});
}
if (existing[0].authorId !== userId) {
throw new TRPCError({
code: "FORBIDDEN",
message: "You can only delete your own content",
});
}
await ctx.db.delete(posts).where(eq(posts.id, input.id));
return { success: true };
}),
vote: protectedProcedure
.input(VoteContentSchema)
.mutation(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
const { contentId, voteType } = input;
const contentItem = await ctx.db
.select({
id: posts.id,
authorId: posts.authorId,
upvotes: posts.upvotesCount,
downvotes: posts.downvotesCount,
})
.from(posts)
.where(eq(posts.id, contentId))
.limit(1);
if (contentItem.length === 0) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Content not found",
});
}
const existingVote = await ctx.db
.select({ id: post_votes.id, voteType: post_votes.voteType })
.from(post_votes)
.where(
and(eq(post_votes.postId, contentId), eq(post_votes.userId, userId)),
)
.limit(1);
// Whether this voter previously had an "up" vote that is now going away
// (removed entirely, or switched to "down"). Used to revoke the author's
// upvote_received points so a ring can't upvote→unvote to inflate.
const revokingUpvote =
existingVote.length > 0 &&
existingVote[0].voteType === "up" &&
voteType !== "up";
// Database triggers handle vote count updates automatically (tr_post_vote_counts)
if (voteType === null) {
if (existingVote.length > 0) {
await ctx.db
.delete(post_votes)
.where(eq(post_votes.id, existingVote[0].id));
}
} else if (existingVote.length === 0) {
await ctx.db.insert(post_votes).values({
postId: contentId,
userId,
voteType: voteType as "up" | "down",
});
} else if (existingVote[0].voteType !== voteType) {
await ctx.db
.update(post_votes)
.set({ voteType: voteType as "up" | "down" })
.where(eq(post_votes.id, existingVote[0].id));
}
// Revoke the author's awarded point when an upvote is removed/downgraded,
// matching the exact (action, sourceId, actorId) tuple awarded below.
// Without this an upvote→unvote loop permanently inflates the author.
if (revokingUpvote) {
await ctx.db
.delete(point_event)
.where(
and(
eq(point_event.action, "upvote_received"),
eq(point_event.sourceId, contentId),
eq(point_event.actorId, userId),
),
);
}
// Award the author points for an upvote (idempotent per voter+post via
// the dedupe index; never self-award). Fire-and-forget — never throws.
if (
voteType === "up" &&
contentItem[0].authorId &&
contentItem[0].authorId !== userId
) {
await award({
userId: contentItem[0].authorId,
action: "upvote_received",
sourceType: "post",
sourceId: contentId,
actorId: userId,
});
}
return { success: true };
}),
bookmark: protectedProcedure
.input(BookmarkContentSchema)
.mutation(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
const { contentId, setBookmarked } = input;
const contentItem = await ctx.db
.select({ id: posts.id })
.from(posts)
.where(eq(posts.id, contentId))
.limit(1);
if (contentItem.length === 0) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Content not found",
});
}
if (setBookmarked) {
await ctx.db
.insert(bookmarks)
.values({ postId: contentId, userId })
.onConflictDoNothing();
} else {
await ctx.db
.delete(bookmarks)
.where(
and(eq(bookmarks.postId, contentId), eq(bookmarks.userId, userId)),
);
}
return { success: true };
}),
trackClick: publicProcedure
.input(TrackClickContentSchema)
.mutation(async ({ ctx, input }) => {
// This endpoint is unauthenticated and bumps a counter that feeds
// trending/popular sort, so throttle per client+content to stop a script
// inflating any post's view count, and only count published posts.
const identifier =
ctx.session?.user?.id ?? `ip:${clientIpFromHeaders(ctx.headers)}`;
await enforceRateLimit({
key: `trackClick:${identifier}:${input.contentId}`,
limit: 10,
windowMs: 60_000,
});
await ctx.db
.update(posts)
.set({ viewsCount: increment(posts.viewsCount) })
.where(
and(eq(posts.id, input.contentId), eq(posts.status, "published")),
);
return { success: true };
}),
mySavedContent: protectedProcedure
.input(GetSavedContentSchema)
.query(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
const { limit, cursor } = input;
const conditions = [eq(bookmarks.userId, userId)];
if (cursor?.createdAt) {
conditions.push(lte(bookmarks.createdAt, cursor.createdAt));
}
const results = await ctx.db
.select({
id: posts.id,
type: posts.type,
title: posts.title,
excerpt: posts.excerpt,
externalUrl: posts.externalUrl,
slug: posts.slug,
publishedAt: posts.publishedAt,
upvotes: posts.upvotesCount,
downvotes: posts.downvotesCount,
sourceName: feed_sources.name,
sourceSlug: feed_sources.slug,
authorName: user.name,
authorUsername: user.username,
bookmarkedAt: bookmarks.createdAt,
})
.from(bookmarks)
.innerJoin(posts, eq(bookmarks.postId, posts.id))
.leftJoin(feed_sources, eq(posts.sourceId, feed_sources.id))
.leftJoin(user, eq(posts.authorId, user.id))
.where(and(...conditions))
.orderBy(desc(bookmarks.createdAt))
.limit(limit + 1);
let nextCursor: { id: string; createdAt?: string } | undefined;
if (results.length > limit) {
const lastItem = results.pop()!;
nextCursor = {
id: lastItem.id,
createdAt: lastItem.bookmarkedAt || undefined,
};
}
const mappedItems = results.map((item) => ({
...item,
type: toFrontendType(item.type),
}));
return {
items: mappedItems,
nextCursor,
};
}),
editDraft: protectedProcedure
.input(EditDraftContentSchema)
.query(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
const results = await ctx.db
.select({
id: posts.id,
type: posts.type,
title: posts.title,
body: posts.body,
excerpt: posts.excerpt,
externalUrl: posts.externalUrl,
imageUrl: posts.coverImage,
canonicalUrl: posts.canonicalUrl,
coverImage: posts.coverImage,
slug: posts.slug,
published: sql<boolean>`${posts.status} = 'published'`,
publishedAt: posts.publishedAt,
showComments: posts.showComments,
readTimeMins: posts.readingTime,
createdAt: posts.createdAt,
updatedAt: posts.updatedAt,
})
.from(posts)
.where(and(eq(posts.id, input.id), eq(posts.authorId, userId)))
.limit(1);
if (results.length === 0) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Content not found or you don't have permission to edit it",
});
}
const contentTags = await ctx.db
.select({
tag: {
id: dbTag.id,
title: dbTag.title,
},
})
.from(post_tags)
.innerJoin(dbTag, eq(post_tags.tagId, dbTag.id))
.where(eq(post_tags.postId, input.id));
return {
...results[0],
type: toFrontendType(results[0].type),
tags: contentTags,
};
}),
myDrafts: protectedProcedure
.input(MyDraftsContentSchema)
.query(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
const results = await ctx.db
.select({
id: posts.id,
type: posts.type,
title: posts.title,
excerpt: posts.excerpt,
slug: posts.slug,
status: posts.status,
published: sql<boolean>`${posts.status} = 'published'`,
publishedAt: posts.publishedAt,
createdAt: posts.createdAt,
updatedAt: posts.updatedAt,
})
.from(posts)
.where(
and(
eq(posts.authorId, userId),
eq(posts.type, "article"),
// Drafts plus auto-moderation states the author should still see.
inArray(posts.status, ["draft", "in_review", "rejected"]),
),
)
.orderBy(desc(posts.updatedAt))
.limit(input.limit);
return results.map((item) => ({
...item,
type: toFrontendType(item.type),
}));
}),
myPublished: protectedProcedure
.input(MyPublishedContentSchema)
.query(async ({ ctx, input }) => {
const userId = ctx.session.user.id;
const now = new Date().toISOString();
const results = await ctx.db
.select({
id: posts.id,
type: posts.type,
title: posts.title,
excerpt: posts.excerpt,
slug: posts.slug,
published: sql<boolean>`${posts.status} = 'published'`,
publishedAt: posts.publishedAt,