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 ],
61 let finalField: string | Col
64 if (field.toLowerCase() === 'match') { // Search
65 finalField = Sequelize.col('similarity')
70 const firstSort = typeof finalField === 'string'
71 ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
72 : [ finalField, direction ]
74 return [ firstSort, lastSort ]
77 function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
78 const [ firstSort ] = getSort(value)
80 if (model) return [ [ literal(`"${model}.${firstSort[0]}" ${firstSort[1]}`) ], lastSort ] as any[] // FIXME: typings
81 return [ firstSort, lastSort ]
84 function getFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
85 const { direction, field } = buildDirectionAndField(value)
87 if (field === 'redundancyAllowed') {
89 [ 'ActorFollowing', 'Server', 'redundancyAllowed', direction ],
94 return getSort(value, lastSort)
97 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
98 const now = Date.now()
99 const createdAtTime = model.createdAt.getTime()
100 const updatedAtTime = model.updatedAt.getTime()
102 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
105 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
106 if (nullable && (value === null || value === undefined)) return
108 if (validator(value) === false) {
109 throw new Error(`"${value}" is not a valid ${fieldName}.`)
113 function buildTrigramSearchIndex (indexName: string, attribute: string) {
116 // FIXME: gin_trgm_ops is not taken into account in Sequelize 6, so adding it ourselves in the literal function
117 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + ')) gin_trgm_ops') as any ],
119 operator: 'gin_trgm_ops'
123 function createSimilarityAttribute (col: string, value: string) {
127 searchTrigramNormalizeCol(col),
129 searchTrigramNormalizeValue(value)
133 function buildBlockedAccountSQL (blockerIds: number[]) {
134 const blockerIdsString = blockerIds.join(', ')
136 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
138 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
139 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
140 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
143 function buildBlockedAccountSQLOptimized (columnNameJoin: string, blockerIds: number[]) {
144 const blockerIdsString = blockerIds.join(', ')
149 ` SELECT 1 FROM "accountBlocklist" ` +
150 ` WHERE "targetAccountId" = ${columnNameJoin} ` +
151 ` AND "accountId" IN (${blockerIdsString})` +
157 ` SELECT 1 FROM "account" ` +
158 ` INNER JOIN "actor" ON account."actorId" = actor.id ` +
159 ` INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ` +
160 ` WHERE "account"."id" = ${columnNameJoin} ` +
161 ` AND "serverBlocklist"."accountId" IN (${blockerIdsString})` +
167 function buildServerIdsFollowedBy (actorId: any) {
168 const actorIdNumber = parseInt(actorId + '', 10)
171 'SELECT "actor"."serverId" FROM "actorFollow" ' +
172 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
173 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
177 function buildWhereIdOrUUID (id: number | string) {
178 return validator.isInt('' + id) ? { id } : { uuid: id }
181 function parseAggregateResult (result: any) {
182 if (!result) return 0
184 const total = parseInt(result + '', 10)
185 if (isNaN(total)) return 0
190 const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
191 return stringArr.map(t => {
194 : model.sequelize.escape('' + t)
198 function buildLocalAccountIdsIn () {
200 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
204 function buildLocalActorIdsIn () {
206 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
210 function buildDirectionAndField (value: string) {
212 let direction: 'ASC' | 'DESC'
214 if (value.substring(0, 1) === '-') {
216 field = value.substring(1)
222 return { direction, field }
225 function searchAttribute (sourceField?: string, targetField?: string) {
226 if (!sourceField) return {}
230 [Op.iLike]: `%${sourceField}%`
235 // ---------------------------------------------------------------------------
238 buildBlockedAccountSQL,
239 buildBlockedAccountSQLOptimized,
240 buildLocalActorIdsIn,
243 buildLocalAccountIdsIn,
248 createSimilarityAttribute,
250 buildServerIdsFollowedBy,
251 buildTrigramSearchIndex,
254 parseAggregateResult,
256 buildDirectionAndField,
261 // ---------------------------------------------------------------------------
263 function searchTrigramNormalizeValue (value: string) {
264 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
267 function searchTrigramNormalizeCol (col: string) {
268 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))