1 import { literal, Op, OrderItem } from 'sequelize'
2 import { Model, Sequelize } from 'sequelize-typescript'
3 import { Col } from 'sequelize/types/lib/utils'
4 import validator from 'validator'
6 type SortType = { sortModel: string, sortValue: string }
8 // Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
9 function getSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
10 const { direction, field } = buildDirectionAndField(value)
12 let finalField: string | Col
14 if (field.toLowerCase() === 'match') { // Search
15 finalField = Sequelize.col('similarity')
16 } else if (field === 'videoQuotaUsed') { // Users list
17 finalField = Sequelize.col('videoQuotaUsed')
22 return [ [ finalField, direction ], lastSort ]
25 function getPlaylistSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
26 const { direction, field } = buildDirectionAndField(value)
28 if (field.toLowerCase() === 'name') {
29 return [ [ 'displayName', direction ], lastSort ]
32 return getSort(value, lastSort)
35 function getCommentSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
36 const { direction, field } = buildDirectionAndField(value)
38 if (field === 'totalReplies') {
40 [ Sequelize.literal('"totalReplies"'), direction ],
45 return getSort(value, lastSort)
48 function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
49 const { direction, field } = buildDirectionAndField(value)
51 if (field.toLowerCase() === 'trending') { // Sort by aggregation
53 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
55 [ Sequelize.col('VideoModel.views'), direction ],
59 } else if (field === 'publishedAt') {
61 [ 'ScheduleVideoUpdate', 'updateAt', direction + ' NULLS LAST' ],
63 [ Sequelize.col('VideoModel.publishedAt'), direction ],
69 let finalField: string | Col
72 if (field.toLowerCase() === 'match') { // Search
73 finalField = Sequelize.col('similarity')
78 const firstSort = typeof finalField === 'string'
79 ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
80 : [ finalField, direction ]
82 return [ firstSort, lastSort ]
85 function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
86 const [ firstSort ] = getSort(value)
88 if (model) return [ [ literal(`"${model}.${firstSort[0]}" ${firstSort[1]}`) ], lastSort ] as any[] // FIXME: typings
89 return [ firstSort, lastSort ]
92 function getFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
93 const { direction, field } = buildDirectionAndField(value)
95 if (field === 'redundancyAllowed') {
97 [ 'ActorFollowing', 'Server', 'redundancyAllowed', direction ],
102 return getSort(value, lastSort)
105 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
106 const now = Date.now()
107 const createdAtTime = model.createdAt.getTime()
108 const updatedAtTime = model.updatedAt.getTime()
110 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
113 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
114 if (nullable && (value === null || value === undefined)) return
116 if (validator(value) === false) {
117 throw new Error(`"${value}" is not a valid ${fieldName}.`)
121 function buildTrigramSearchIndex (indexName: string, attribute: string) {
124 // FIXME: gin_trgm_ops is not taken into account in Sequelize 6, so adding it ourselves in the literal function
125 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + ')) gin_trgm_ops') as any ],
127 operator: 'gin_trgm_ops'
131 function createSimilarityAttribute (col: string, value: string) {
135 searchTrigramNormalizeCol(col),
137 searchTrigramNormalizeValue(value)
141 function buildBlockedAccountSQL (blockerIds: number[]) {
142 const blockerIdsString = blockerIds.join(', ')
144 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
146 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
147 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
148 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
151 function buildBlockedAccountSQLOptimized (columnNameJoin: string, blockerIds: number[]) {
152 const blockerIdsString = blockerIds.join(', ')
157 ` SELECT 1 FROM "accountBlocklist" ` +
158 ` WHERE "targetAccountId" = ${columnNameJoin} ` +
159 ` AND "accountId" IN (${blockerIdsString})` +
165 ` SELECT 1 FROM "account" ` +
166 ` INNER JOIN "actor" ON account."actorId" = actor.id ` +
167 ` INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ` +
168 ` WHERE "account"."id" = ${columnNameJoin} ` +
169 ` AND "serverBlocklist"."accountId" IN (${blockerIdsString})` +
175 function buildServerIdsFollowedBy (actorId: any) {
176 const actorIdNumber = parseInt(actorId + '', 10)
179 'SELECT "actor"."serverId" FROM "actorFollow" ' +
180 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
181 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
185 function buildWhereIdOrUUID (id: number | string) {
186 return validator.isInt('' + id) ? { id } : { uuid: id }
189 function parseAggregateResult (result: any) {
190 if (!result) return 0
192 const total = parseInt(result + '', 10)
193 if (isNaN(total)) return 0
198 const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
199 return stringArr.map(t => {
202 : model.sequelize.escape('' + t)
206 function buildLocalAccountIdsIn () {
208 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
212 function buildLocalActorIdsIn () {
214 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
218 function buildDirectionAndField (value: string) {
220 let direction: 'ASC' | 'DESC'
222 if (value.substring(0, 1) === '-') {
224 field = value.substring(1)
230 return { direction, field }
233 function searchAttribute (sourceField?: string, targetField?: string) {
234 if (!sourceField) return {}
238 [Op.iLike]: `%${sourceField}%`
243 // ---------------------------------------------------------------------------
246 buildBlockedAccountSQL,
247 buildBlockedAccountSQLOptimized,
248 buildLocalActorIdsIn,
251 buildLocalAccountIdsIn,
256 createSimilarityAttribute,
258 buildServerIdsFollowedBy,
259 buildTrigramSearchIndex,
262 parseAggregateResult,
264 buildDirectionAndField,
269 // ---------------------------------------------------------------------------
271 function searchTrigramNormalizeValue (value: string) {
272 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
275 function searchTrigramNormalizeCol (col: string) {
276 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))