1 import { literal, Op, OrderItem, Sequelize } from 'sequelize'
2 import { Col } from 'sequelize/types/lib/utils'
3 import validator from 'validator'
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 | Col
13 if (field.toLowerCase() === 'match') { // Search
14 finalField = Sequelize.col('similarity')
15 } else if (field === 'videoQuotaUsed') { // Users list
16 finalField = Sequelize.col('videoQuotaUsed')
21 return [ [ finalField, direction ], lastSort ]
24 function getPlaylistSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
25 const { direction, field } = buildDirectionAndField(value)
27 if (field.toLowerCase() === 'name') {
28 return [ [ 'displayName', direction ], lastSort ]
31 return getSort(value, lastSort)
34 function getCommentSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
35 const { direction, field } = buildDirectionAndField(value)
37 if (field === 'totalReplies') {
39 [ Sequelize.literal('"totalReplies"'), direction ],
44 return getSort(value, lastSort)
47 function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
48 const { direction, field } = buildDirectionAndField(value)
50 if (field.toLowerCase() === 'trending') { // Sort by aggregation
52 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
54 [ Sequelize.col('VideoModel.views'), direction ],
58 } else if (field === 'publishedAt') {
60 [ 'ScheduleVideoUpdate', 'updateAt', direction + ' NULLS LAST' ],
62 [ Sequelize.col('VideoModel.publishedAt'), direction ],
68 let finalField: string | Col
71 if (field.toLowerCase() === 'match') { // Search
72 finalField = Sequelize.col('similarity')
77 const firstSort = typeof finalField === 'string'
78 ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
79 : [ finalField, direction ]
81 return [ firstSort, lastSort ]
84 function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
85 const [ firstSort ] = getSort(value)
87 if (model) return [ [ literal(`"${model}.${firstSort[0]}" ${firstSort[1]}`) ], lastSort ] as any[] // FIXME: typings
88 return [ firstSort, lastSort ]
91 function getFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
92 const { direction, field } = buildDirectionAndField(value)
94 if (field === 'redundancyAllowed') {
96 [ 'ActorFollowing', 'Server', 'redundancyAllowed', direction ],
101 return getSort(value, lastSort)
104 function 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()
109 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
112 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
113 if (nullable && (value === null || value === undefined)) return
115 if (validator(value) === false) {
116 throw new Error(`"${value}" is not a valid ${fieldName}.`)
120 function buildTrigramSearchIndex (indexName: string, attribute: string) {
123 // FIXME: gin_trgm_ops is not taken into account in Sequelize 6, so adding it ourselves in the literal function
124 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + ')) gin_trgm_ops') as any ],
126 operator: 'gin_trgm_ops'
130 function createSimilarityAttribute (col: string, value: string) {
134 searchTrigramNormalizeCol(col),
136 searchTrigramNormalizeValue(value)
140 function buildBlockedAccountSQL (blockerIds: number[]) {
141 const blockerIdsString = blockerIds.join(', ')
143 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
145 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
146 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
147 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
150 function buildBlockedAccountSQLOptimized (columnNameJoin: string, blockerIds: number[]) {
151 const blockerIdsString = blockerIds.join(', ')
156 ` SELECT 1 FROM "accountBlocklist" ` +
157 ` WHERE "targetAccountId" = ${columnNameJoin} ` +
158 ` AND "accountId" IN (${blockerIdsString})` +
164 ` SELECT 1 FROM "account" ` +
165 ` INNER JOIN "actor" ON account."actorId" = actor.id ` +
166 ` INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ` +
167 ` WHERE "account"."id" = ${columnNameJoin} ` +
168 ` AND "serverBlocklist"."accountId" IN (${blockerIdsString})` +
174 function buildServerIdsFollowedBy (actorId: any) {
175 const actorIdNumber = parseInt(actorId + '', 10)
178 'SELECT "actor"."serverId" FROM "actorFollow" ' +
179 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
180 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
184 function buildWhereIdOrUUID (id: number | string) {
185 return validator.isInt('' + id) ? { id } : { uuid: id }
188 function parseAggregateResult (result: any) {
189 if (!result) return 0
191 const total = parseInt(result + '', 10)
192 if (isNaN(total)) return 0
197 function createSafeIn (sequelize: Sequelize, stringArr: (string | number)[]) {
198 return stringArr.map(t => {
201 : sequelize.escape('' + t)
205 function buildLocalAccountIdsIn () {
207 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
211 function buildLocalActorIdsIn () {
213 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
217 function buildDirectionAndField (value: string) {
219 let direction: 'ASC' | 'DESC'
221 if (value.substring(0, 1) === '-') {
223 field = value.substring(1)
229 return { direction, field }
232 function searchAttribute (sourceField?: string, targetField?: string) {
233 if (!sourceField) return {}
237 [Op.iLike]: `%${sourceField}%`
242 // ---------------------------------------------------------------------------
245 buildBlockedAccountSQL,
246 buildBlockedAccountSQLOptimized,
247 buildLocalActorIdsIn,
250 buildLocalAccountIdsIn,
255 createSimilarityAttribute,
257 buildServerIdsFollowedBy,
258 buildTrigramSearchIndex,
261 parseAggregateResult,
263 buildDirectionAndField,
268 // ---------------------------------------------------------------------------
270 function searchTrigramNormalizeValue (value: string) {
271 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
274 function searchTrigramNormalizeCol (col: string) {
275 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))