]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/utils.ts
Fix video comments feed SQL query
[github/Chocobozzz/PeerTube.git] / server / models / utils.ts
CommitLineData
3caf77d3 1import { Model, Sequelize } from 'sequelize-typescript'
7cde3b9c 2import validator from 'validator'
1735c825 3import { Col } from 'sequelize/types/lib/utils'
e0a92917 4import { literal, OrderItem, Op } from 'sequelize'
57c36b27 5
8319d6ae
RK
6type Primitive = string | Function | number | boolean | Symbol | undefined | null
7type DeepOmitHelper<T, K extends keyof T> = {
8 [P in K]: // extra level of indirection needed to trigger homomorhic behavior
9 T[P] extends infer TP // distribute over unions
10 ? TP extends Primitive
11 ? TP // leave primitives and functions alone
12 : TP extends any[]
13 ? DeepOmitArray<TP, K> // Array special handling
14 : DeepOmit<TP, K>
15 : never
16}
17type DeepOmit<T, K> = T extends Primitive ? T : DeepOmitHelper<T, Exclude<keyof T, K>>
18
19type DeepOmitArray<T extends any[], K> = {
20 [P in keyof T]: DeepOmit<T[P], K>
21}
22
95153292 23type SortType = { sortModel: string, sortValue: string }
06215f15 24
9a629c6e 25// Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
1735c825
C
26function getSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
27 const { direction, field } = buildDirectionAndField(value)
28
29 let finalField: string | Col
4b54f136
C
30
31 if (field.toLowerCase() === 'match') { // Search
1735c825 32 finalField = Sequelize.col('similarity')
aa3796bd
C
33 } else if (field === 'videoQuotaUsed') { // Users list
34 finalField = Sequelize.col('videoQuotaUsed')
1735c825
C
35 } else {
36 finalField = field
4b54f136 37 }
5c39adb7 38
1735c825 39 return [ [ finalField, direction ], lastSort ]
9a629c6e
C
40}
41
c1125bca
RK
42function getCommentSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
43 const { direction, field } = buildDirectionAndField(value)
44
45 if (field === 'totalReplies') {
46 return [
47 [ Sequelize.literal('"totalReplies"'), direction ],
48 lastSort
49 ]
50 }
51
52 return getSort(value, lastSort)
53}
54
1735c825
C
55function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
56 const { direction, field } = buildDirectionAndField(value)
5c39adb7 57
1735c825 58 if (field.toLowerCase() === 'trending') { // Sort by aggregation
9a629c6e
C
59 return [
60 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
61
62 [ Sequelize.col('VideoModel.views'), direction ],
63
64 lastSort
65 ]
66 }
67
1735c825
C
68 let finalField: string | Col
69
70 // Alias
71 if (field.toLowerCase() === 'match') { // Search
72 finalField = Sequelize.col('similarity')
73 } else {
74 finalField = field
75 }
76
77 const firstSort = typeof finalField === 'string'
78 ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
79 : [ finalField, direction ]
afa4374a
C
80
81 return [ firstSort, lastSort ]
5c39adb7
C
82}
83
95153292 84function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
1735c825 85 const [ firstSort ] = getSort(value)
792dbaf0 86
a1587156 87 if (model) return [ [ literal(`"${model}.${firstSort[0]}" ${firstSort[1]}`) ], lastSort ] as any[] // FIXME: typings
3bb6c526 88 return [ firstSort, lastSort ]
792dbaf0
GS
89}
90
cb5ce4cb
C
91function getFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
92 const { direction, field } = buildDirectionAndField(value)
93
94 if (field === 'redundancyAllowed') {
95 return [
96 [ 'ActorFollowing', 'Server', 'redundancyAllowed', direction ],
97 lastSort
98 ]
99 }
100
101 return getSort(value, lastSort)
102}
103
9f79ade6
C
104function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
105 const now = Date.now()
106 const createdAtTime = model.createdAt.getTime()
107 const updatedAtTime = model.updatedAt.getTime()
108
109 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
110}
111
1735c825
C
112function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
113 if (nullable && (value === null || value === undefined)) return
114
3fd3ab2d
C
115 if (validator(value) === false) {
116 throw new Error(`"${value}" is not a valid ${fieldName}.`)
117 }
118}
119
57c36b27
C
120function buildTrigramSearchIndex (indexName: string, attribute: string) {
121 return {
122 name: indexName,
123 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
124 using: 'gin',
125 operator: 'gin_trgm_ops'
126 }
127}
128
129function createSimilarityAttribute (col: string, value: string) {
130 return Sequelize.fn(
131 'similarity',
132
133 searchTrigramNormalizeCol(col),
134
135 searchTrigramNormalizeValue(value)
136 )
137}
138
696d83fd 139function buildBlockedAccountSQL (blockerIds: number[]) {
7ad9b984
C
140 const blockerIdsString = blockerIds.join(', ')
141
418d092a 142 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
7ad9b984 143 ' UNION ALL ' +
7ad9b984
C
144 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
145 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
146 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
418d092a
C
147}
148
149function buildServerIdsFollowedBy (actorId: any) {
150 const actorIdNumber = parseInt(actorId + '', 10)
151
152 return '(' +
153 'SELECT "actor"."serverId" FROM "actorFollow" ' +
154 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
155 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
a1587156 156 ')'
418d092a 157}
7ad9b984 158
418d092a
C
159function buildWhereIdOrUUID (id: number | string) {
160 return validator.isInt('' + id) ? { id } : { uuid: id }
7ad9b984
C
161}
162
3acc5084
C
163function parseAggregateResult (result: any) {
164 if (!result) return 0
165
166 const total = parseInt(result + '', 10)
167 if (isNaN(total)) return 0
168
169 return total
170}
171
6b9c966f 172const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
5f3e2425
C
173 return stringArr.map(t => {
174 return t === null
175 ? null
176 : model.sequelize.escape('' + t)
177 }).join(', ')
3caf77d3
C
178}
179
6b9c966f
C
180function buildLocalAccountIdsIn () {
181 return literal(
182 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
183 )
184}
185
186function buildLocalActorIdsIn () {
187 return literal(
188 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
189 )
190}
191
5f3e2425
C
192function buildDirectionAndField (value: string) {
193 let field: string
194 let direction: 'ASC' | 'DESC'
195
196 if (value.substring(0, 1) === '-') {
197 direction = 'DESC'
198 field = value.substring(1)
199 } else {
200 direction = 'ASC'
201 field = value
202 }
203
204 return { direction, field }
205}
206
feb34f6b
C
207function searchAttribute (sourceField?: string, targetField?: string) {
208 if (!sourceField) return {}
0d3a2982
RK
209
210 return {
feb34f6b
C
211 [targetField]: {
212 [Op.iLike]: `%${sourceField}%`
213 }
0d3a2982
RK
214 }
215}
216
5c39adb7
C
217// ---------------------------------------------------------------------------
218
65fcc311 219export {
8319d6ae 220 DeepOmit,
7ad9b984 221 buildBlockedAccountSQL,
6b9c966f 222 buildLocalActorIdsIn,
06215f15 223 SortType,
6b9c966f 224 buildLocalAccountIdsIn,
792dbaf0 225 getSort,
c1125bca 226 getCommentSort,
9a629c6e 227 getVideoSort,
95153292 228 getBlacklistSort,
57c36b27
C
229 createSimilarityAttribute,
230 throwIfNotValid,
418d092a
C
231 buildServerIdsFollowedBy,
232 buildTrigramSearchIndex,
9f79ade6 233 buildWhereIdOrUUID,
3acc5084 234 isOutdated,
3caf77d3 235 parseAggregateResult,
cb5ce4cb 236 getFollowsSort,
5f3e2425 237 buildDirectionAndField,
e0a92917 238 createSafeIn,
feb34f6b 239 searchAttribute
57c36b27
C
240}
241
242// ---------------------------------------------------------------------------
243
244function searchTrigramNormalizeValue (value: string) {
2cebd797 245 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
57c36b27
C
246}
247
248function searchTrigramNormalizeCol (col: string) {
249 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
65fcc311 250}