-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathsub.js
356 lines (320 loc) · 10.8 KB
/
sub.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
import { whenRange } from '@/lib/time'
import { validateSchema, territorySchema } from '@/lib/validate'
import { decodeCursor, LIMIT, nextCursorEncoded } from '@/lib/cursor'
import { viewGroup } from './growth'
import { notifyTerritoryTransfer } from '@/lib/webPush'
import performPaidAction from '../paidAction'
import { GqlAuthenticationError, GqlInputError } from '@/lib/error'
export async function getSub (parent, { name }, { models, me }) {
if (!name) return null
return await models.sub.findUnique({
where: {
name
},
...(me
? {
include: {
MuteSub: {
where: {
userId: Number(me?.id)
}
},
SubSubscription: {
where: {
userId: Number(me?.id)
}
}
}
}
: {})
})
}
export default {
Query: {
sub: getSub,
subs: async (parent, args, { models, me }) => {
if (me) {
const currentUser = await models.user.findUnique({ where: { id: me.id } })
const showNsfw = currentUser ? currentUser.nsfwMode : false
return await models.$queryRawUnsafe(`
SELECT "Sub".*, "Sub".created_at as "createdAt", COALESCE(json_agg("MuteSub".*) FILTER (WHERE "MuteSub"."userId" IS NOT NULL), '[]') AS "MuteSub"
FROM "Sub"
LEFT JOIN "MuteSub" ON "Sub".name = "MuteSub"."subName" AND "MuteSub"."userId" = ${me.id}::INTEGER
WHERE status <> 'STOPPED' ${showNsfw ? '' : 'AND "Sub"."nsfw" = FALSE'}
GROUP BY "Sub".name, "MuteSub"."userId"
ORDER BY "Sub".name ASC
`)
}
return await models.sub.findMany({
where: {
status: {
not: 'STOPPED'
},
nsfw: false
},
orderBy: {
name: 'asc'
}
})
},
subLatestPost: async (parent, { name }, { models, me }) => {
const latest = await models.item.findFirst({
where: {
subName: name
},
orderBy: {
createdAt: 'desc'
}
})
return latest?.createdAt
},
topSubs: async (parent, { cursor, when, by, from, to, limit = LIMIT }, { models, me }) => {
const decodedCursor = decodeCursor(cursor)
const range = whenRange(when, from, to || decodeCursor.time)
let column
switch (by) {
case 'revenue': column = 'revenue'; break
case 'spent': column = 'spent'; break
case 'posts': column = 'nposts'; break
case 'comments': column = 'ncomments'; break
default: column = 'stacked'; break
}
const subs = await models.$queryRawUnsafe(`
SELECT "Sub".*,
COALESCE(floor(sum(msats_revenue)/1000), 0) as revenue,
COALESCE(floor(sum(msats_stacked)/1000), 0) as stacked,
COALESCE(floor(sum(msats_spent)/1000), 0) as spent,
COALESCE(sum(posts), 0) as nposts,
COALESCE(sum(comments), 0) as ncomments
FROM ${viewGroup(range, 'sub_stats')}
JOIN "Sub" on "Sub".name = u.sub_name
GROUP BY "Sub".name
ORDER BY ${column} DESC NULLS LAST, "Sub".created_at ASC
OFFSET $3
LIMIT $4`, ...range, decodedCursor.offset, limit)
return {
cursor: subs.length === limit ? nextCursorEncoded(decodedCursor, limit) : null,
subs
}
},
userSubs: async (_parent, { name, cursor, when, by, from, to, limit = LIMIT }, { models }) => {
if (!name) {
throw new GqlInputError('must supply user name')
}
const user = await models.user.findUnique({ where: { name } })
if (!user) {
throw new GqlInputError('no user has that name')
}
const decodedCursor = decodeCursor(cursor)
const range = whenRange(when, from, to || decodeCursor.time)
let column
switch (by) {
case 'revenue': column = 'revenue'; break
case 'spent': column = 'spent'; break
case 'posts': column = 'nposts'; break
case 'comments': column = 'ncomments'; break
default: column = 'stacked'; break
}
const subs = await models.$queryRawUnsafe(`
SELECT "Sub".*,
"Sub".created_at as "createdAt",
COALESCE(floor(sum(msats_revenue)/1000), 0) as revenue,
COALESCE(floor(sum(msats_stacked)/1000), 0) as stacked,
COALESCE(floor(sum(msats_spent)/1000), 0) as spent,
COALESCE(sum(posts), 0) as nposts,
COALESCE(sum(comments), 0) as ncomments
FROM ${viewGroup(range, 'sub_stats')}
JOIN "Sub" on "Sub".name = u.sub_name
WHERE "Sub"."userId" = $3
AND "Sub".status = 'ACTIVE'
GROUP BY "Sub".name
ORDER BY ${column} DESC NULLS LAST, "Sub".created_at ASC
OFFSET $4
LIMIT $5`, ...range, user.id, decodedCursor.offset, limit)
return {
cursor: subs.length === limit ? nextCursorEncoded(decodedCursor, limit) : null,
subs
}
}
},
Mutation: {
upsertSub: async (parent, { ...data }, { me, models, lnd }) => {
if (!me) {
throw new GqlAuthenticationError()
}
await validateSchema(territorySchema, data, { models, me, sub: { name: data.oldName } })
if (data.oldName) {
return await updateSub(parent, data, { me, models, lnd })
} else {
return await createSub(parent, data, { me, models, lnd })
}
},
paySub: async (parent, { name }, { me, models, lnd }) => {
// check that they own the sub
const sub = await models.sub.findUnique({
where: {
name
}
})
if (!sub) {
throw new GqlInputError('sub not found')
}
if (sub.userId !== me.id) {
throw new GqlInputError('you do not own this sub')
}
if (sub.status === 'ACTIVE') {
return sub
}
return await performPaidAction('TERRITORY_BILLING', { name }, { me, models, lnd })
},
toggleMuteSub: async (parent, { name }, { me, models }) => {
if (!me) {
throw new GqlAuthenticationError()
}
const lookupData = { userId: Number(me.id), subName: name }
const where = { userId_subName: lookupData }
const existing = await models.muteSub.findUnique({ where })
if (existing) {
await models.muteSub.delete({ where })
return false
} else {
await models.muteSub.create({ data: { ...lookupData } })
return true
}
},
toggleSubSubscription: async (sub, { name }, { me, models }) => {
if (!me) {
throw new GqlAuthenticationError()
}
const lookupData = { userId: me.id, subName: name }
const where = { userId_subName: lookupData }
const existing = await models.subSubscription.findUnique({ where })
if (existing) {
await models.subSubscription.delete({ where })
return false
} else {
await models.subSubscription.create({ data: lookupData })
return true
}
},
transferTerritory: async (parent, { subName, userName }, { me, models }) => {
if (!me) {
throw new GqlAuthenticationError()
}
const sub = await models.sub.findUnique({
where: {
name: subName
}
})
if (!sub) {
throw new GqlInputError('sub not found')
}
if (sub.userId !== me.id) {
throw new GqlInputError('you do not own this sub')
}
const user = await models.user.findFirst({ where: { name: userName } })
if (!user) {
throw new GqlInputError('user not found')
}
if (user.id === me.id) {
throw new GqlInputError('cannot transfer territory to yourself')
}
const [, updatedSub] = await models.$transaction([
models.territoryTransfer.create({ data: { subName, oldUserId: me.id, newUserId: user.id } }),
models.sub.update({ where: { name: subName }, data: { userId: user.id, billingAutoRenew: false } })
])
notifyTerritoryTransfer({ models, sub, to: user })
return updatedSub
},
unarchiveTerritory: async (parent, { ...data }, { me, models, lnd }) => {
if (!me) {
throw new GqlAuthenticationError()
}
const { name } = data
await validateSchema(territorySchema, data, { models, me })
const oldSub = await models.sub.findUnique({ where: { name } })
if (!oldSub) {
throw new GqlInputError('sub not found')
}
if (oldSub.status !== 'STOPPED') {
throw new GqlInputError('sub is not archived')
}
if (oldSub.billingType === 'ONCE') {
// sanity check. this should never happen but leaving this comment here
// to stop error propagation just in case and document that this should never happen.
// #defensivecode
throw new GqlInputError('sub should not be archived')
}
return await performPaidAction('TERRITORY_UNARCHIVE', data, { me, models, lnd })
}
},
Sub: {
optional: sub => sub,
user: async (sub, args, { models }) => {
if (sub.user) {
return sub.user
}
return await models.user.findUnique({ where: { id: sub.userId } })
},
meMuteSub: async (sub, args, { models }) => {
if (sub.meMuteSub !== undefined) {
return sub.meMuteSub
}
return sub.MuteSub?.length > 0
},
nposts: async (sub, { when, from, to }, { models }) => {
if (typeof sub.nposts !== 'undefined') {
return sub.nposts
}
},
ncomments: async (sub, { when, from, to }, { models }) => {
if (typeof sub.ncomments !== 'undefined') {
return sub.ncomments
}
},
meSubscription: async (sub, args, { me, models }) => {
if (sub.meSubscription !== undefined) {
return sub.meSubscription
}
return sub.SubSubscription?.length > 0
},
customDomain: async (sub, args, { models }) => {
return models.customDomain.findUnique({ where: { subName: sub.name } })
},
createdAt: sub => sub.createdAt || sub.created_at
}
}
async function createSub (parent, data, { me, models, lnd }) {
try {
return await performPaidAction('TERRITORY_CREATE', data, { me, models, lnd })
} catch (error) {
if (error.code === 'P2002') {
throw new GqlInputError('name taken')
}
throw error
}
}
async function updateSub (parent, { oldName, ...data }, { me, models, lnd }) {
const oldSub = await models.sub.findUnique({
where: {
name: oldName,
userId: me.id,
// this function's logic is only valid if the sub is not stopped
// so prevent updates to stopped subs
status: {
not: 'STOPPED'
}
}
})
if (!oldSub) {
throw new GqlInputError('sub not found')
}
try {
return await performPaidAction('TERRITORY_UPDATE', { oldName, ...data }, { me, models, lnd })
} catch (error) {
if (error.code === 'P2002') {
throw new GqlInputError('name taken')
}
throw error
}
}