-
-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathitem.js
1576 lines (1426 loc) · 55.7 KB
/
item.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
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 { ensureProtocol, removeTracking, stripTrailingSlash } from '@/lib/url'
import { decodeCursor, LIMIT, nextCursorEncoded } from '@/lib/cursor'
import { getMetadata, metadataRuleSets } from 'page-metadata-parser'
import { ruleSet as publicationDateRuleSet } from '@/lib/timedate-scraper'
import domino from 'domino'
import {
ITEM_SPAM_INTERVAL, ITEM_FILTER_THRESHOLD,
COMMENT_DEPTH_LIMIT, COMMENT_TYPE_QUERY,
USER_ID, POLL_COST, ADMIN_ITEMS, GLOBAL_SEED,
NOFOLLOW_LIMIT, UNKNOWN_LINK_REL, SN_ADMIN_IDS,
BOOST_MULT,
ITEM_EDIT_SECONDS,
COMMENTS_LIMIT,
COMMENTS_OF_COMMENT_LIMIT,
FULL_COMMENTS_THRESHOLD
} from '@/lib/constants'
import { msatsToSats } from '@/lib/format'
import { parse } from 'tldts'
import uu from 'url-unshort'
import { actSchema, advSchema, bountySchema, commentSchema, discussionSchema, jobSchema, linkSchema, pollSchema, validateSchema } from '@/lib/validate'
import { defaultCommentSort, isJob, deleteItemByAuthor } from '@/lib/item'
import { datePivot, whenRange } from '@/lib/time'
import { uploadIdsFromText } from './upload'
import assertGofacYourself from './ofac'
import assertApiKeyNotPermitted from './apiKey'
import performPaidAction from '../paidAction'
import { GqlAuthenticationError, GqlInputError } from '@/lib/error'
import { verifyHmac } from './wallet'
function commentsOrderByClause (me, models, sort) {
const sharedSortsArray = []
sharedSortsArray.push('("Item"."pinId" IS NOT NULL) DESC')
sharedSortsArray.push('("Item"."deletedAt" IS NULL) DESC')
const sharedSorts = sharedSortsArray.join(', ')
if (sort === 'recent') {
return `ORDER BY ${sharedSorts},
("Item".cost > 0 OR "Item"."weightedVotes" - "Item"."weightedDownVotes" > 0) DESC,
COALESCE("Item"."invoicePaidAt", "Item".created_at) DESC, "Item".id DESC`
}
if (me && sort === 'hot') {
return `ORDER BY ${sharedSorts},
"personal_hot_score" DESC NULLS LAST,
"Item".msats DESC, ("Item".cost > 0) DESC, "Item".id DESC`
} else {
if (sort === 'top') {
return `ORDER BY ${sharedSorts}, ${orderByNumerator({ models, commentScaler: 0 })} DESC NULLS LAST, "Item".msats DESC, ("Item".cost > 0) DESC, "Item".id DESC`
} else {
return `ORDER BY ${sharedSorts}, ${orderByNumerator({ models, commentScaler: 0, considerBoost: true })}/POWER(GREATEST(3, EXTRACT(EPOCH FROM (now_utc() - "Item".created_at))/3600), 1.3) DESC NULLS LAST, "Item".msats DESC, ("Item".cost > 0) DESC, "Item".id DESC`
}
}
}
async function comments (me, models, item, sort, cursor) {
const orderBy = commentsOrderByClause(me, models, sort)
if (item.nDirectComments === 0) {
return {
comments: [],
cursor: null
}
}
const decodedCursor = decodeCursor(cursor)
const offset = decodedCursor.offset
// XXX what a mess
let comments
if (me) {
const filter = ` AND ("Item"."invoiceActionState" IS NULL OR "Item"."invoiceActionState" = 'PAID' OR "Item"."userId" = ${me.id}) AND "Item".created_at <= '${decodedCursor.time.toISOString()}'::TIMESTAMP(3) `
if (item.ncomments > FULL_COMMENTS_THRESHOLD) {
const [{ item_comments_zaprank_with_me_limited: limitedComments }] = await models.$queryRawUnsafe(
'SELECT item_comments_zaprank_with_me_limited($1::INTEGER, $2::INTEGER, $3::INTEGER, $4::INTEGER, $5::INTEGER, $6::INTEGER, $7::INTEGER, $8, $9)',
Number(item.id), GLOBAL_SEED, Number(me.id), COMMENTS_LIMIT, offset, COMMENTS_OF_COMMENT_LIMIT, COMMENT_DEPTH_LIMIT, filter, orderBy)
comments = limitedComments
} else {
const [{ item_comments_zaprank_with_me: fullComments }] = await models.$queryRawUnsafe(
'SELECT item_comments_zaprank_with_me($1::INTEGER, $2::INTEGER, $3::INTEGER, $4::INTEGER, $5, $6)',
Number(item.id), GLOBAL_SEED, Number(me.id), COMMENT_DEPTH_LIMIT, filter, orderBy)
comments = fullComments
}
} else {
const filter = ` AND ("Item"."invoiceActionState" IS NULL OR "Item"."invoiceActionState" = 'PAID') AND "Item".created_at <= '${decodedCursor.time.toISOString()}'::TIMESTAMP(3) `
if (item.ncomments > FULL_COMMENTS_THRESHOLD) {
const [{ item_comments_limited: limitedComments }] = await models.$queryRawUnsafe(
'SELECT item_comments_limited($1::INTEGER, $2::INTEGER, $3::INTEGER, $4::INTEGER, $5::INTEGER, $6, $7)',
Number(item.id), COMMENTS_LIMIT, offset, COMMENTS_OF_COMMENT_LIMIT, COMMENT_DEPTH_LIMIT, filter, orderBy)
comments = limitedComments
} else {
const [{ item_comments: fullComments }] = await models.$queryRawUnsafe(
'SELECT item_comments($1::INTEGER, $2::INTEGER, $3, $4)', Number(item.id), COMMENT_DEPTH_LIMIT, filter, orderBy)
comments = fullComments
}
}
return {
comments,
cursor: comments.length + offset < item.nDirectComments ? nextCursorEncoded(decodedCursor, COMMENTS_LIMIT) : null
}
}
export async function getItem (parent, { id }, { me, models }) {
const [item] = await itemQueryWithMeta({
me,
models,
query: `
${SELECT}
FROM "Item"
${whereClause(
'"Item".id = $1',
activeOrMine(me)
)}`
}, Number(id))
return item
}
export async function getAd (parent, { sub, subArr = [], showNsfw = false }, { me, models }) {
return (await itemQueryWithMeta({
me,
models,
query: `
${SELECT}
FROM "Item"
LEFT JOIN "Sub" ON "Sub"."name" = "Item"."subName"
${whereClause(
'"parentId" IS NULL',
'"Item"."pinId" IS NULL',
'"Item"."deletedAt" IS NULL',
'"Item"."parentId" IS NULL',
'"Item".bio = false',
'"Item".boost > 0',
activeOrMine(),
subClause(sub, 1, 'Item', me, showNsfw),
muteClause(me))}
ORDER BY boost desc, "Item".created_at ASC
LIMIT 1`
}, ...subArr))?.[0] || null
}
const orderByClause = (by, me, models, type) => {
switch (by) {
case 'comments':
return 'ORDER BY "Item".ncomments DESC'
case 'sats':
return 'ORDER BY "Item".msats DESC'
case 'zaprank':
return topOrderByWeightedSats(me, models)
case 'boost':
return 'ORDER BY "Item".boost DESC'
case 'random':
return 'ORDER BY RANDOM()'
default:
return `ORDER BY ${type === 'bookmarks' ? '"bookmarkCreatedAt"' : '"Item".created_at'} DESC`
}
}
export function orderByNumerator ({ models, commentScaler = 0.5, considerBoost = false }) {
return `((CASE WHEN "Item"."weightedVotes" - "Item"."weightedDownVotes" > 0 THEN
GREATEST("Item"."weightedVotes" - "Item"."weightedDownVotes", POWER("Item"."weightedVotes" - "Item"."weightedDownVotes", 1.2))
ELSE
"Item"."weightedVotes" - "Item"."weightedDownVotes"
END + "Item"."weightedComments"*${commentScaler}) + ${considerBoost ? `("Item".boost / ${BOOST_MULT})` : 0})`
}
export function joinZapRankPersonalView (me, models) {
let join = ` JOIN zap_rank_personal_view g ON g.id = "Item".id AND g."viewerId" = ${GLOBAL_SEED} `
if (me) {
join += ` LEFT JOIN zap_rank_personal_view l ON l.id = g.id AND l."viewerId" = ${me.id} `
}
return join
}
// this grabs all the stuff we need to display the item list and only
// hits the db once ... orderBy needs to be duplicated on the outer query because
// joining does not preserve the order of the inner query
export async function itemQueryWithMeta ({ me, models, query, orderBy = '' }, ...args) {
if (!me) {
return await models.$queryRawUnsafe(`
SELECT "Item".*, to_json(users.*) as user, to_jsonb("Sub".*) as sub
FROM (
${query}
) "Item"
JOIN users ON "Item"."userId" = users.id
LEFT JOIN "Sub" ON "Sub"."name" = "Item"."subName"
${orderBy}`, ...args)
} else {
return await models.$queryRawUnsafe(`
SELECT "Item".*, to_jsonb(users.*) || jsonb_build_object('meMute', "Mute"."mutedId" IS NOT NULL) as user,
COALESCE("ItemAct"."meMsats", 0) as "meMsats", COALESCE("ItemAct"."mePendingMsats", 0) as "mePendingMsats",
COALESCE("ItemAct"."meMcredits", 0) as "meMcredits", COALESCE("ItemAct"."mePendingMcredits", 0) as "mePendingMcredits",
COALESCE("ItemAct"."meDontLikeMsats", 0) as "meDontLikeMsats", b."itemId" IS NOT NULL AS "meBookmark",
"ThreadSubscription"."itemId" IS NOT NULL AS "meSubscription", "ItemForward"."itemId" IS NOT NULL AS "meForward",
to_jsonb("Sub".*) || jsonb_build_object('meMuteSub', "MuteSub"."userId" IS NOT NULL)
|| jsonb_build_object('meSubscription', "SubSubscription"."userId" IS NOT NULL) as sub
FROM (
${query}
) "Item"
JOIN users ON "Item"."userId" = users.id
LEFT JOIN "Mute" ON "Mute"."muterId" = ${me.id} AND "Mute"."mutedId" = "Item"."userId"
LEFT JOIN "Bookmark" b ON b."itemId" = "Item".id AND b."userId" = ${me.id}
LEFT JOIN "ThreadSubscription" ON "ThreadSubscription"."itemId" = "Item".id AND "ThreadSubscription"."userId" = ${me.id}
LEFT JOIN "ItemForward" ON "ItemForward"."itemId" = "Item".id AND "ItemForward"."userId" = ${me.id}
LEFT JOIN "Sub" ON "Sub"."name" = "Item"."subName"
LEFT JOIN "MuteSub" ON "Sub"."name" = "MuteSub"."subName" AND "MuteSub"."userId" = ${me.id}
LEFT JOIN "SubSubscription" ON "Sub"."name" = "SubSubscription"."subName" AND "SubSubscription"."userId" = ${me.id}
LEFT JOIN LATERAL (
SELECT "itemId",
sum("ItemAct".msats) FILTER (WHERE "invoiceActionState" IS DISTINCT FROM 'FAILED' AND "InvoiceForward".id IS NOT NULL AND (act = 'FEE' OR act = 'TIP')) AS "meMsats",
sum("ItemAct".msats) FILTER (WHERE "invoiceActionState" IS DISTINCT FROM 'FAILED' AND "InvoiceForward".id IS NULL AND (act = 'FEE' OR act = 'TIP')) AS "meMcredits",
sum("ItemAct".msats) FILTER (WHERE "invoiceActionState" IS NOT DISTINCT FROM 'PENDING' AND "InvoiceForward".id IS NOT NULL AND (act = 'FEE' OR act = 'TIP')) AS "mePendingMsats",
sum("ItemAct".msats) FILTER (WHERE "invoiceActionState" IS NOT DISTINCT FROM 'PENDING' AND "InvoiceForward".id IS NULL AND (act = 'FEE' OR act = 'TIP')) AS "mePendingMcredits",
sum("ItemAct".msats) FILTER (WHERE "invoiceActionState" IS DISTINCT FROM 'FAILED' AND act = 'DONT_LIKE_THIS') AS "meDontLikeMsats"
FROM "ItemAct"
LEFT JOIN "Invoice" ON "Invoice".id = "ItemAct"."invoiceId"
LEFT JOIN "InvoiceForward" ON "InvoiceForward"."invoiceId" = "Invoice"."id"
WHERE "ItemAct"."userId" = ${me.id}
AND "ItemAct"."itemId" = "Item".id
GROUP BY "ItemAct"."itemId"
) "ItemAct" ON true
${orderBy}`, ...args)
}
}
const relationClause = (type) => {
let clause = ''
switch (type) {
case 'comments':
clause += ' FROM "Item" JOIN "Item" root ON "Item"."rootId" = root.id LEFT JOIN "Sub" ON "Sub"."name" = root."subName" '
break
case 'bookmarks':
clause += ' FROM "Item" JOIN "Bookmark" ON "Bookmark"."itemId" = "Item"."id" LEFT JOIN "Item" root ON "Item"."rootId" = root.id LEFT JOIN "Sub" ON "Sub"."name" = COALESCE(root."subName", "Item"."subName") '
break
case 'outlawed':
case 'borderland':
case 'freebies':
case 'all':
clause += ' FROM "Item" LEFT JOIN "Item" root ON "Item"."rootId" = root.id LEFT JOIN "Sub" ON "Sub"."name" = COALESCE(root."subName", "Item"."subName") '
break
default:
clause += ' FROM "Item" LEFT JOIN "Sub" ON "Sub"."name" = "Item"."subName" '
}
return clause
}
const selectClause = (type) => type === 'bookmarks'
? `${SELECT}, "Bookmark"."created_at" as "bookmarkCreatedAt"`
: SELECT
const subClauseTable = (type) => COMMENT_TYPE_QUERY.includes(type) ? 'root' : 'Item'
export const whereClause = (...clauses) => {
const clause = clauses.flat(Infinity).filter(c => c).join(' AND ')
return clause ? ` WHERE ${clause} ` : ''
}
function whenClause (when, table) {
return `"${table}".created_at <= $2 and "${table}".created_at >= $1`
}
export const activeOrMine = (me) => {
return me
? [`("Item"."invoiceActionState" IS NULL OR "Item"."invoiceActionState" = 'PAID' OR "Item"."userId" = ${me.id})`,
`("Item".status <> 'STOPPED' OR "Item"."userId" = ${me.id})`]
: ['("Item"."invoiceActionState" IS NULL OR "Item"."invoiceActionState" = \'PAID\')', '"Item".status <> \'STOPPED\'']
}
export const muteClause = me =>
me ? `NOT EXISTS (SELECT 1 FROM "Mute" WHERE "Mute"."muterId" = ${me.id} AND "Mute"."mutedId" = "Item"."userId")` : ''
const HIDE_NSFW_CLAUSE = '("Sub"."nsfw" = FALSE OR "Sub"."nsfw" IS NULL)'
export const nsfwClause = showNsfw => showNsfw ? '' : HIDE_NSFW_CLAUSE
const subClause = (sub, num, table = 'Item', me, showNsfw) => {
// Intentionally show nsfw posts (i.e. no nsfw clause) when viewing a specific nsfw sub
if (sub) {
const tables = [...new Set(['Item', table])].map(t => `"${t}".`)
return `(${tables.map(t => `${t}"subName" = $${num}::CITEXT`).join(' OR ')})`
}
if (!me) { return HIDE_NSFW_CLAUSE }
const excludeMuted = `NOT EXISTS (SELECT 1 FROM "MuteSub" WHERE "MuteSub"."userId" = ${me.id} AND "MuteSub"."subName" = ${table ? `"${table}".` : ''}"subName")`
if (showNsfw) return excludeMuted
return excludeMuted + ' AND ' + HIDE_NSFW_CLAUSE
}
function investmentClause (sats) {
return `(
CASE WHEN "Item"."parentId" IS NULL
THEN ("Item".cost + "Item".boost + ("Item".msats / 1000)) >= ${sats}
ELSE ("Item".cost + "Item".boost + ("Item".msats / 1000)) >= ${Math.min(sats, 1)}
END
)`
}
export async function filterClause (me, models, type) {
// if you are explicitly asking for marginal content, don't filter them
if (['outlawed', 'borderland', 'freebies'].includes(type)) {
if (me && ['outlawed', 'borderland'].includes(type)) {
// unless the item is mine
return `"Item"."userId" <> ${me.id}`
}
return ''
}
// handle freebies
// by default don't include freebies unless they have upvotes
let satsFilter = investmentClause(10)
if (me) {
const user = await models.user.findUnique({ where: { id: me.id } })
satsFilter = `(${investmentClause(user.satsFilter)} OR "Item"."userId" = ${me.id})`
if (user.wildWestMode) {
return satsFilter
}
}
// handle outlawed
// if the item is above the threshold or is mine
const outlawClauses = [`"Item"."weightedVotes" - "Item"."weightedDownVotes" > -${ITEM_FILTER_THRESHOLD} AND NOT "Item".outlawed`]
if (me) {
outlawClauses.push(`"Item"."userId" = ${me.id}`)
}
const outlawClause = '(' + outlawClauses.join(' OR ') + ')'
return [satsFilter, outlawClause]
}
function typeClause (type) {
switch (type) {
case 'links':
return ['"Item".url IS NOT NULL', '"Item"."parentId" IS NULL']
case 'discussions':
return ['"Item".url IS NULL', '"Item".bio = false', '"Item"."pollCost" IS NULL', '"Item"."parentId" IS NULL']
case 'polls':
return ['"Item"."pollCost" IS NOT NULL', '"Item"."parentId" IS NULL']
case 'bios':
return ['"Item".bio = true', '"Item"."parentId" IS NULL']
case 'bounties':
return ['"Item".bounty IS NOT NULL', '"Item"."parentId" IS NULL']
case 'bounties_active':
return ['"Item".bounty IS NOT NULL', '"Item"."parentId" IS NULL', '"Item"."bountyPaidTo" IS NULL']
case 'comments':
return '"Item"."parentId" IS NOT NULL'
case 'freebies':
return '"Item".cost = 0'
case 'outlawed':
return `"Item"."weightedVotes" - "Item"."weightedDownVotes" <= -${ITEM_FILTER_THRESHOLD} OR "Item".outlawed`
case 'borderland':
return '"Item"."weightedVotes" - "Item"."weightedDownVotes" < 0'
case 'all':
case 'bookmarks':
return ''
case 'jobs':
return '"Item"."subName" = \'jobs\''
default:
return '"Item"."parentId" IS NULL'
}
}
export default {
Query: {
itemRepetition: async (parent, { parentId }, { me, models }) => {
if (!me) return 0
// how many of the parents starting at parentId belong to me
const [{ item_spam: count }] = await models.$queryRawUnsafe(`SELECT item_spam($1::INTEGER, $2::INTEGER, '${ITEM_SPAM_INTERVAL}')`,
Number(parentId), Number(me.id))
return count
},
items: async (parent, { sub, sort, type, cursor, name, when, from, to, by, limit = LIMIT }, { me, models }) => {
const decodedCursor = decodeCursor(cursor)
let items, user, pins, subFull, table, ad
// special authorization for bookmarks depending on owning users' privacy settings
if (type === 'bookmarks' && name && me?.name !== name) {
// the calling user is either not logged in, or not the user upon which the query is made,
// so we need to check authz
user = await models.user.findUnique({ where: { name } })
// additionally check if the user ids are not the same since if the nym changed
// since the last session update we would hide bookmarks from their owners
// see https://github.com/stackernews/stacker.news/issues/586
if (user?.hideBookmarks && user.id !== me.id) {
// early return with no results if bookmarks are hidden
return {
cursor: null,
items: [],
pins: []
}
}
}
// HACK we want to optionally include the subName in the query
// but the query planner doesn't like unused parameters
const subArr = sub ? [sub] : []
const currentUser = me ? await models.user.findUnique({ where: { id: me.id } }) : null
const showNsfw = currentUser ? currentUser.nsfwMode : false
switch (sort) {
case 'user':
if (!name) {
throw new GqlInputError('must supply name')
}
user ??= await models.user.findUnique({ where: { name } })
if (!user) {
throw new GqlInputError('no user has that name')
}
table = type === 'bookmarks' ? 'Bookmark' : 'Item'
items = await itemQueryWithMeta({
me,
models,
query: `
${selectClause(type)}
${relationClause(type)}
${whereClause(
`"${table}"."userId" = $3`,
activeOrMine(me),
nsfwClause(showNsfw),
typeClause(type),
by === 'boost' && '"Item".boost > 0',
whenClause(when || 'forever', table))}
${orderByClause(by, me, models, type)}
OFFSET $4
LIMIT $5`,
orderBy: orderByClause(by, me, models, type)
}, ...whenRange(when, from, to || decodedCursor.time), user.id, decodedCursor.offset, limit)
break
case 'recent':
items = await itemQueryWithMeta({
me,
models,
query: `
${SELECT}
${relationClause(type)}
${whereClause(
'"Item".created_at <= $1',
'"Item"."deletedAt" IS NULL',
subClause(sub, 4, subClauseTable(type), me, showNsfw),
activeOrMine(me),
await filterClause(me, models, type),
typeClause(type),
muteClause(me)
)}
ORDER BY COALESCE("Item"."invoicePaidAt", "Item".created_at) DESC
OFFSET $2
LIMIT $3`,
orderBy: 'ORDER BY COALESCE("Item"."invoicePaidAt", "Item".created_at) DESC'
}, decodedCursor.time, decodedCursor.offset, limit, ...subArr)
break
case 'top':
items = await itemQueryWithMeta({
me,
models,
query: `
${selectClause(type)}
${relationClause(type)}
${whereClause(
'"Item"."deletedAt" IS NULL',
type === 'posts' && '"Item"."subName" IS NOT NULL',
subClause(sub, 5, subClauseTable(type), me, showNsfw),
typeClause(type),
whenClause(when, 'Item'),
activeOrMine(me),
await filterClause(me, models, type),
by === 'boost' && '"Item".boost > 0',
muteClause(me))}
${orderByClause(by || 'zaprank', me, models, type)}
OFFSET $3
LIMIT $4`,
orderBy: orderByClause(by || 'zaprank', me, models, type)
}, ...whenRange(when, from, to || decodedCursor.time), decodedCursor.offset, limit, ...subArr)
break
case 'random':
items = await itemQueryWithMeta({
me,
models,
query: `
${selectClause(type)}
${relationClause(type)}
${whereClause(
'"Item"."deletedAt" IS NULL',
'"Item"."weightedVotes" - "Item"."weightedDownVotes" > 2',
'"Item"."ncomments" > 0',
'"Item"."parentId" IS NULL',
'"Item".bio = false',
type === 'posts' && '"Item"."subName" IS NOT NULL',
subClause(sub, 3, subClauseTable(type), me, showNsfw),
typeClause(type),
await filterClause(me, models, type),
activeOrMine(me),
muteClause(me))}
${orderByClause('random', me, models, type)}
OFFSET $1
LIMIT $2`,
orderBy: orderByClause('random', me, models, type)
}, decodedCursor.offset, limit, ...subArr)
break
default:
// sub so we know the default ranking
if (sub) {
subFull = await models.sub.findUnique({ where: { name: sub } })
}
switch (subFull?.rankingType) {
case 'AUCTION':
items = await itemQueryWithMeta({
me,
models,
query: `
${SELECT},
(boost IS NOT NULL AND boost > 0)::INT AS group_rank,
CASE WHEN boost IS NOT NULL AND boost > 0
THEN rank() OVER (ORDER BY boost DESC, created_at ASC)
ELSE rank() OVER (ORDER BY created_at DESC) END AS rank
FROM "Item"
${whereClause(
'"parentId" IS NULL',
'"Item"."deletedAt" IS NULL',
'"Item"."status" = \'ACTIVE\'',
'created_at <= $1',
'"pinId" IS NULL',
subClause(sub, 4)
)}
ORDER BY group_rank DESC, rank
OFFSET $2
LIMIT $3`,
orderBy: 'ORDER BY group_rank DESC, rank'
}, decodedCursor.time, decodedCursor.offset, limit, ...subArr)
break
default:
if (decodedCursor.offset === 0) {
// get pins for the page and return those separately
pins = await itemQueryWithMeta({
me,
models,
query: `
SELECT rank_filter.*
FROM (
${SELECT}, position,
rank() OVER (
PARTITION BY "pinId"
ORDER BY "Item".created_at DESC
)
FROM "Item"
JOIN "Pin" ON "Item"."pinId" = "Pin".id
${whereClause(
'"pinId" IS NOT NULL',
'"parentId" IS NULL',
sub ? '"subName" = $1' : '"subName" IS NULL',
muteClause(me))}
) rank_filter WHERE RANK = 1
ORDER BY position ASC`,
orderBy: 'ORDER BY position ASC'
}, ...subArr)
ad = await getAd(parent, { sub, subArr, showNsfw }, { me, models })
}
items = await itemQueryWithMeta({
me,
models,
query: `
${SELECT}, ${me ? 'GREATEST(g.tf_hot_score, l.tf_hot_score)' : 'g.tf_hot_score'} AS rank
FROM "Item"
LEFT JOIN "Sub" ON "Sub"."name" = "Item"."subName"
${joinZapRankPersonalView(me, models)}
${whereClause(
// in home (sub undefined), filter out global pinned items since we inject them later
sub ? '"Item"."pinId" IS NULL' : 'NOT ("Item"."pinId" IS NOT NULL AND "Item"."subName" IS NULL)',
'"Item"."deletedAt" IS NULL',
'"Item"."parentId" IS NULL',
'"Item".outlawed = false',
'"Item".bio = false',
ad ? `"Item".id <> ${ad.id}` : '',
activeOrMine(me),
await filterClause(me, models, type),
subClause(sub, 3, 'Item', me, showNsfw),
muteClause(me))}
ORDER BY rank DESC
OFFSET $1
LIMIT $2`,
orderBy: 'ORDER BY rank DESC'
}, decodedCursor.offset, limit, ...subArr)
// XXX this is mostly for subs that are really empty
if (items.length < limit) {
items = await itemQueryWithMeta({
me,
models,
query: `
${SELECT}
FROM "Item"
LEFT JOIN "Sub" ON "Sub"."name" = "Item"."subName"
${whereClause(
subClause(sub, 3, 'Item', me, showNsfw),
muteClause(me),
// in home (sub undefined), filter out global pinned items since we inject them later
sub ? '"Item"."pinId" IS NULL' : 'NOT ("Item"."pinId" IS NOT NULL AND "Item"."subName" IS NULL)',
'"Item"."deletedAt" IS NULL',
'"Item"."parentId" IS NULL',
'"Item".bio = false',
ad ? `"Item".id <> ${ad.id}` : '',
activeOrMine(me),
await filterClause(me, models, type))}
ORDER BY ${orderByNumerator({ models, considerBoost: true })}/POWER(GREATEST(3, EXTRACT(EPOCH FROM (now_utc() - "Item".created_at))/3600), 1.3) DESC NULLS LAST,
"Item".msats DESC, ("Item".cost > 0) DESC, "Item".id DESC
OFFSET $1
LIMIT $2`,
orderBy: `ORDER BY ${orderByNumerator({ models, considerBoost: true })}/POWER(GREATEST(3, EXTRACT(EPOCH FROM (now_utc() - "Item".created_at))/3600), 1.3) DESC NULLS LAST,
"Item".msats DESC, ("Item".cost > 0) DESC, "Item".id DESC`
}, decodedCursor.offset, limit, ...subArr)
}
break
}
break
}
return {
cursor: items.length === limit ? nextCursorEncoded(decodedCursor) : null,
items,
pins,
ad
}
},
item: getItem,
pageTitleAndUnshorted: async (parent, { url }, { models }) => {
const res = {}
try {
const response = await fetch(ensureProtocol(url), { redirect: 'follow' })
const html = await response.text()
const doc = domino.createWindow(html).document
const metadata = getMetadata(doc, url, { title: metadataRuleSets.title, publicationDate: publicationDateRuleSet })
const dateHint = ` (${metadata.publicationDate?.getFullYear()})`
const moreThanOneYearAgo = metadata.publicationDate && metadata.publicationDate < datePivot(new Date(), { years: -1 })
res.title = metadata?.title
if (moreThanOneYearAgo) res.title += dateHint
} catch { }
try {
const unshorted = await uu().expand(url)
if (unshorted) {
res.unshorted = unshorted
}
} catch { }
return res
},
dupes: async (parent, { url }, { me, models }) => {
const urlObj = new URL(ensureProtocol(url))
let { hostname, pathname } = urlObj
// remove subdomain from hostname
const parseResult = parse(urlObj.hostname)
if (parseResult?.subdomain?.length > 0) {
hostname = hostname.replace(`${parseResult.subdomain}.`, '')
}
// hostname with optional protocol, subdomain, and port
const hostnameRegex = `^(http(s)?:\\/\\/)?(\\w+\\.)?${(hostname + '(:[0-9]+)?').replace(/\./g, '\\.')}`
// pathname with trailing slash and escaped special characters
const pathnameRegex = stripTrailingSlash(pathname).replace(/(\+|\.|\/)/g, '\\$1') + '\\/?'
// url with optional trailing slash
let similar = hostnameRegex + pathnameRegex
const whitelist = ['news.ycombinator.com/item', 'bitcointalk.org/index.php']
const youtube = ['www.youtube.com', 'youtube.com', 'm.youtube.com', 'youtu.be']
const hostAndPath = stripTrailingSlash(urlObj.hostname + urlObj.pathname)
if (whitelist.includes(hostAndPath)) {
// make query string match for whitelist domains
similar += `\\${urlObj.search}`
} else if (youtube.includes(urlObj.hostname)) {
// extract id and create both links
const matches = url.match(/(https?:\/\/)?((www\.)?(youtube(-nocookie)?|youtube.googleapis)\.com.*(v\/|v=|vi=|vi\/|e\/|embed\/|user\/.*\/u\/\d+\/)|youtu\.be\/)(?<id>[_0-9a-z-]+)/i)
similar = `^(http(s)?:\\/\\/)?((www\\.|m\\.)?youtube.com\\/(watch\\?v\\=|v\\/|live\\/)${matches?.groups?.id}|youtu\\.be\\/${matches?.groups?.id})&?`
} else if (urlObj.hostname === 'yewtu.be') {
const matches = url.match(/(https?:\/\/)?yewtu\.be.*(v=|embed\/)(?<id>[_0-9a-z-]+)/i)
similar = `^(http(s)?:\\/\\/)?yewtu\\.be\\/(watch\\?v\\=|embed\\/)${matches?.groups?.id}&?`
}
return await itemQueryWithMeta({
me,
models,
query: `
${SELECT}
FROM "Item"
WHERE url ~* $1
ORDER BY created_at DESC
LIMIT 3`
}, similar)
},
auctionPosition: async (parent, { id, sub, boost }, { models, me }) => {
const createdAt = id ? (await getItem(parent, { id }, { models, me })).createdAt : new Date()
let where
if (boost > 0) {
// if there's boost
// has a larger boost than ours, or has an equal boost and is older
// count items: (boost > ours.boost OR (boost = ours.boost AND create_at < ours.created_at))
where = {
OR: [
{ boost: { gt: boost } },
{ boost, createdAt: { lt: createdAt } }
]
}
} else {
// else
// it's an active with a bid gt ours, or its newer than ours and not STOPPED
// count items: ((bid > ours.bid AND status = 'ACTIVE') OR (created_at > ours.created_at AND status <> 'STOPPED'))
where = {
OR: [
{ boost: { gt: 0 } },
{ createdAt: { gt: createdAt } }
]
}
}
where.AND = {
subName: sub,
status: 'ACTIVE',
deletedAt: null
}
if (id) {
where.AND.id = { not: Number(id) }
}
return await models.item.count({ where }) + 1
},
boostPosition: async (parent, { id, sub, boost = 0 }, { models, me }) => {
const where = {
boost: { gte: boost },
status: 'ACTIVE',
deletedAt: null,
outlawed: false,
parentId: null
}
if (id) {
where.id = { not: Number(id) }
}
const homeAgg = await models.item.aggregate({
_count: { id: true },
_max: { boost: true },
where
})
let subAgg
if (sub) {
subAgg = await models.item.aggregate({
_count: { id: true },
_max: { boost: true },
where: {
...where,
subName: sub
}
})
}
return {
home: homeAgg._count.id === 0 && boost >= BOOST_MULT,
sub: subAgg?._count.id === 0 && boost >= BOOST_MULT,
homeMaxBoost: homeAgg._max.boost || 0,
subMaxBoost: subAgg?._max.boost || 0
}
}
},
Mutation: {
bookmarkItem: async (parent, { id }, { me, models }) => {
const data = { itemId: Number(id), userId: me.id }
const old = await models.bookmark.findUnique({ where: { userId_itemId: data } })
if (old) {
await models.bookmark.delete({ where: { userId_itemId: data } })
} else await models.bookmark.create({ data })
return { id }
},
pinItem: async (parent, { id }, { me, models }) => {
if (!me) {
throw new GqlAuthenticationError()
}
const [item] = await models.$queryRawUnsafe(
`${SELECT}, p.position
FROM "Item" LEFT JOIN "Pin" p ON p.id = "Item"."pinId"
WHERE "Item".id = $1`, Number(id))
const args = []
if (item.parentId) {
args.push(item.parentId)
// OPs can only pin top level replies
if (item.path.split('.').length > 2) {
throw new GqlInputError('can only pin root replies')
}
const root = await models.item.findUnique({
where: {
id: Number(item.parentId)
},
include: { pin: true }
})
if (root.userId !== Number(me.id)) {
throw new GqlInputError('not your post')
}
} else if (item.subName) {
args.push(item.subName)
// only territory founder can pin posts
const sub = await models.sub.findUnique({ where: { name: item.subName } })
if (Number(me.id) !== sub.userId) {
throw new GqlInputError('not your sub')
}
} else {
throw new GqlInputError('item must have subName or parentId')
}
let pinId
if (item.pinId) {
// item is already pinned. remove pin
await models.$transaction([
models.item.update({ where: { id: item.id }, data: { pinId: null } }),
models.pin.delete({ where: { id: item.pinId } }),
// make sure that pins have no gaps
models.$queryRawUnsafe(`
UPDATE "Pin"
SET position = position - 1
WHERE position > $2 AND id IN (
SELECT "pinId" FROM "Item" i
${whereClause('"pinId" IS NOT NULL', item.subName ? 'i."subName" = $1' : 'i."parentId" = $1')}
)`, ...args, item.position)
])
pinId = null
} else {
// only max 3 pins allowed per territory and post
const [{ count: npins }] = await models.$queryRawUnsafe(`
SELECT COUNT(p.id) FROM "Pin" p
JOIN "Item" i ON i."pinId" = p.id
${
whereClause(item.subName ? 'i."subName" = $1' : 'i."parentId" = $1')
}`, ...args)
if (npins >= 3) {
throw new GqlInputError('max 3 pins allowed')
}
const [{ pinId: newPinId }] = await models.$queryRawUnsafe(`
WITH pin AS (
INSERT INTO "Pin" (position)
SELECT COALESCE(MAX(p.position), 0) + 1 AS position
FROM "Pin" p
JOIN "Item" i ON i."pinId" = p.id
${whereClause(item.subName ? 'i."subName" = $1' : 'i."parentId" = $1')}
RETURNING id
)
UPDATE "Item"
SET "pinId" = pin.id
FROM pin
WHERE "Item".id = $2
RETURNING "pinId"`, ...args, item.id)
pinId = newPinId
}
return { id, pinId }
},
subscribeItem: async (parent, { id }, { me, models }) => {
const data = { itemId: Number(id), userId: me.id }
const old = await models.threadSubscription.findUnique({ where: { userId_itemId: data } })
if (old) {
await models.threadSubscription.delete({ where: { userId_itemId: data } })
} else await models.threadSubscription.create({ data })
return { id }
},
deleteItem: async (parent, { id }, { me, models }) => {
const old = await models.item.findUnique({ where: { id: Number(id) } })
if (Number(old.userId) !== Number(me?.id)) {
throw new GqlInputError('item does not belong to you')
}
if (old.bio) {
throw new GqlInputError('cannot delete bio')
}
return await deleteItemByAuthor({ models, id, item: old })
},
upsertLink: async (parent, { id, ...item }, { me, models, lnd }) => {
await validateSchema(linkSchema, item, { models, me })
if (id) {
return await updateItem(parent, { id, ...item }, { me, models, lnd })
} else {
return await createItem(parent, item, { me, models, lnd })
}
},
upsertDiscussion: async (parent, { id, ...item }, { me, models, lnd }) => {
await validateSchema(discussionSchema, item, { models, me })
if (id) {
return await updateItem(parent, { id, ...item }, { me, models, lnd })
} else {
return await createItem(parent, item, { me, models, lnd })
}
},
upsertBounty: async (parent, { id, ...item }, { me, models, lnd }) => {
await validateSchema(bountySchema, item, { models, me })
if (id) {
return await updateItem(parent, { id, ...item }, { me, models, lnd })
} else {
return await createItem(parent, item, { me, models, lnd })
}
},
upsertPoll: async (parent, { id, ...item }, { me, models, lnd }) => {
const numExistingChoices = id
? await models.pollOption.count({
where: {
itemId: Number(id)
}
})
: 0
await validateSchema(pollSchema, item, { models, me, numExistingChoices })
if (id) {
return await updateItem(parent, { id, ...item }, { me, models, lnd })
} else {
item.pollCost = item.pollCost || POLL_COST
return await createItem(parent, item, { me, models, lnd })
}
},
upsertJob: async (parent, { id, ...item }, { me, models, lnd }) => {
if (!me) {
throw new GqlAuthenticationError()
}
item.location = item.location?.toLowerCase() === 'remote' ? undefined : item.location
await validateSchema(jobSchema, item, { models })
if (item.logo !== undefined) {
item.uploadId = item.logo
delete item.logo
}
if (id) {
return await updateItem(parent, { id, ...item }, { me, models, lnd })
} else {
return await createItem(parent, item, { me, models, lnd })
}
},
upsertComment: async (parent, { id, ...item }, { me, models, lnd }) => {
await validateSchema(commentSchema, item)
if (id) {
return await updateItem(parent, { id, ...item }, { me, models, lnd })
} else {
item = await createItem(parent, item, { me, models, lnd })
return item
}
},
updateNoteId: async (parent, { id, noteId }, { me, models }) => {
if (!id) {
throw new GqlInputError('id required')
}
await models.item.update({
where: { id: Number(id), userId: Number(me.id) },
data: { noteId }
})
return { id, noteId }
},
pollVote: async (parent, { id }, { me, models, lnd }) => {
if (!me) {
throw new GqlAuthenticationError()
}
return await performPaidAction('POLL_VOTE', { id }, { me, models, lnd })
},
act: async (parent, { id, sats, act = 'TIP', hasSendWallet }, { me, models, lnd, headers }) => {
assertApiKeyNotPermitted({ me })
await validateSchema(actSchema, { sats, act })
await assertGofacYourself({ models, headers })
const [item] = await models.$queryRawUnsafe(`
${SELECT}
FROM "Item"
WHERE id = $1`, Number(id))
if (item.deletedAt) {
throw new GqlInputError('item is deleted')
}