1 import { literal, Op, OrderItem, Sequelize } from 'sequelize'
2 import validator from 'validator'
3 import { forceNumber } from '@shared/core-utils'
5 type SortType = { sortModel: string, sortValue: string }
7 // Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
8 function getSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
9 const { direction, field } = buildDirectionAndField(value)
11 let finalField: string | ReturnType<typeof Sequelize.col>
13 if (field.toLowerCase() === 'match') { // Search
14 finalField = Sequelize.col('similarity')
19 return [ [ finalField, direction ], lastSort ]
22 function getAdminUsersSort (value: string): OrderItem[] {
23 const { direction, field } = buildDirectionAndField(value)
25 let finalField: string | ReturnType<typeof Sequelize.col>
27 if (field === 'videoQuotaUsed') { // Users list
28 finalField = Sequelize.col('videoQuotaUsed')
33 const nullPolicy = direction === 'ASC'
38 return [ [ finalField as any, direction, nullPolicy ], [ 'id', 'ASC' ] ]
41 function getPlaylistSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
42 const { direction, field } = buildDirectionAndField(value)
44 if (field.toLowerCase() === 'name') {
45 return [ [ 'displayName', direction ], lastSort ]
48 return getSort(value, lastSort)
51 function getCommentSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
52 const { direction, field } = buildDirectionAndField(value)
54 if (field === 'totalReplies') {
56 [ Sequelize.literal('"totalReplies"'), direction ],
61 return getSort(value, lastSort)
64 function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
65 const { direction, field } = buildDirectionAndField(value)
67 if (field.toLowerCase() === 'trending') { // Sort by aggregation
69 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
71 [ Sequelize.col('VideoModel.views'), direction ],
75 } else if (field === 'publishedAt') {
77 [ 'ScheduleVideoUpdate', 'updateAt', direction + ' NULLS LAST' ],
79 [ Sequelize.col('VideoModel.publishedAt'), direction ],
85 let finalField: string | ReturnType<typeof Sequelize.col>
88 if (field.toLowerCase() === 'match') { // Search
89 finalField = Sequelize.col('similarity')
94 const firstSort: OrderItem = typeof finalField === 'string'
95 ? finalField.split('.').concat([ direction ]) as OrderItem
96 : [ finalField, direction ]
98 return [ firstSort, lastSort ]
101 function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
102 const [ firstSort ] = getSort(value)
104 if (model) return [ [ literal(`"${model}.${firstSort[0]}" ${firstSort[1]}`) ], lastSort ] as OrderItem[]
105 return [ firstSort, lastSort ]
108 function getInstanceFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
109 const { direction, field } = buildDirectionAndField(value)
111 if (field === 'redundancyAllowed') {
113 [ 'ActorFollowing.Server.redundancyAllowed', direction ],
118 return getSort(value, lastSort)
121 function getChannelSyncSort (value: string): OrderItem[] {
122 const { direction, field } = buildDirectionAndField(value)
123 if (field.toLowerCase() === 'videochannel') {
125 [ literal('"VideoChannel.name"'), direction ]
128 return [ [ field, direction ] ]
131 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
132 if (!model.createdAt || !model.updatedAt) {
133 throw new Error('Miss createdAt & updatedAt attributes to model')
136 const now = Date.now()
137 const createdAtTime = model.createdAt.getTime()
138 const updatedAtTime = model.updatedAt.getTime()
140 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
143 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
144 if (nullable && (value === null || value === undefined)) return
146 if (validator(value) === false) {
147 throw new Error(`"${value}" is not a valid ${fieldName}.`)
151 function buildTrigramSearchIndex (indexName: string, attribute: string) {
154 // FIXME: gin_trgm_ops is not taken into account in Sequelize 6, so adding it ourselves in the literal function
155 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + ')) gin_trgm_ops') as any ],
157 operator: 'gin_trgm_ops'
161 function createSimilarityAttribute (col: string, value: string) {
165 searchTrigramNormalizeCol(col),
167 searchTrigramNormalizeValue(value)
171 function buildBlockedAccountSQL (blockerIds: number[]) {
172 const blockerIdsString = blockerIds.join(', ')
174 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
176 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
177 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
178 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
181 function buildBlockedAccountSQLOptimized (columnNameJoin: string, blockerIds: number[]) {
182 const blockerIdsString = blockerIds.join(', ')
187 ` SELECT 1 FROM "accountBlocklist" ` +
188 ` WHERE "targetAccountId" = ${columnNameJoin} ` +
189 ` AND "accountId" IN (${blockerIdsString})` +
195 ` SELECT 1 FROM "account" ` +
196 ` INNER JOIN "actor" ON account."actorId" = actor.id ` +
197 ` INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ` +
198 ` WHERE "account"."id" = ${columnNameJoin} ` +
199 ` AND "serverBlocklist"."accountId" IN (${blockerIdsString})` +
205 function buildServerIdsFollowedBy (actorId: any) {
206 const actorIdNumber = forceNumber(actorId)
209 'SELECT "actor"."serverId" FROM "actorFollow" ' +
210 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
211 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
215 function buildWhereIdOrUUID (id: number | string) {
216 return validator.isInt('' + id) ? { id } : { uuid: id }
219 function parseAggregateResult (result: any) {
220 if (!result) return 0
222 const total = forceNumber(result)
223 if (isNaN(total)) return 0
228 function parseRowCountResult (result: any) {
229 if (result.length !== 0) return result[0].total
234 function createSafeIn (sequelize: Sequelize, toEscape: (string | number)[], additionalUnescaped: string[] = []) {
235 return toEscape.map(t => {
238 : sequelize.escape('' + t)
239 }).concat(additionalUnescaped).join(', ')
242 function buildLocalAccountIdsIn () {
244 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
248 function buildLocalActorIdsIn () {
250 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
254 function buildDirectionAndField (value: string) {
256 let direction: 'ASC' | 'DESC'
258 if (value.substring(0, 1) === '-') {
260 field = value.substring(1)
266 return { direction, field }
269 function searchAttribute (sourceField?: string, targetField?: string) {
270 if (!sourceField) return {}
275 [Op.iLike as any]: `%${sourceField}%`
280 // ---------------------------------------------------------------------------
283 buildBlockedAccountSQL,
284 buildBlockedAccountSQLOptimized,
285 buildLocalActorIdsIn,
288 buildLocalAccountIdsIn,
295 createSimilarityAttribute,
297 buildServerIdsFollowedBy,
298 buildTrigramSearchIndex,
301 parseAggregateResult,
302 getInstanceFollowsSort,
303 buildDirectionAndField,
309 // ---------------------------------------------------------------------------
311 function searchTrigramNormalizeValue (value: string) {
312 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
315 function searchTrigramNormalizeCol (col: string) {
316 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))