1 import { Model, Sequelize } from 'sequelize-typescript'
2 import validator from 'validator'
3 import { Col } from 'sequelize/types/lib/utils'
4 import { literal, OrderItem } from 'sequelize'
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 getCommentSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
26 const { direction, field } = buildDirectionAndField(value)
28 if (field === 'totalReplies') {
30 [ Sequelize.literal('"totalReplies"'), direction ],
35 return getSort(value, lastSort)
38 function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
39 const { direction, field } = buildDirectionAndField(value)
41 if (field.toLowerCase() === 'trending') { // Sort by aggregation
43 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
45 [ Sequelize.col('VideoModel.views'), direction ],
51 let finalField: string | Col
54 if (field.toLowerCase() === 'match') { // Search
55 finalField = Sequelize.col('similarity')
60 const firstSort = typeof finalField === 'string'
61 ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
62 : [ finalField, direction ]
64 return [ firstSort, lastSort ]
67 function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
68 const [ firstSort ] = getSort(value)
70 if (model) return [ [ literal(`"${model}.${firstSort[ 0 ]}" ${firstSort[ 1 ]}`) ], lastSort ] as any[] // FIXME: typings
71 return [ firstSort, lastSort ]
74 function getFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
75 const { direction, field } = buildDirectionAndField(value)
77 if (field === 'redundancyAllowed') {
79 [ 'ActorFollowing', 'Server', 'redundancyAllowed', direction ],
84 return getSort(value, lastSort)
87 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
88 const now = Date.now()
89 const createdAtTime = model.createdAt.getTime()
90 const updatedAtTime = model.updatedAt.getTime()
92 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
95 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
96 if (nullable && (value === null || value === undefined)) return
98 if (validator(value) === false) {
99 throw new Error(`"${value}" is not a valid ${fieldName}.`)
103 function buildTrigramSearchIndex (indexName: string, attribute: string) {
106 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
108 operator: 'gin_trgm_ops'
112 function createSimilarityAttribute (col: string, value: string) {
116 searchTrigramNormalizeCol(col),
118 searchTrigramNormalizeValue(value)
122 function buildBlockedAccountSQL (serverAccountId: number, userAccountId?: number) {
123 const blockerIds = [ serverAccountId ]
124 if (userAccountId) blockerIds.push(userAccountId)
126 const blockerIdsString = blockerIds.join(', ')
128 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
130 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
131 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
132 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
135 function buildServerIdsFollowedBy (actorId: any) {
136 const actorIdNumber = parseInt(actorId + '', 10)
139 'SELECT "actor"."serverId" FROM "actorFollow" ' +
140 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
141 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
145 function buildWhereIdOrUUID (id: number | string) {
146 return validator.isInt('' + id) ? { id } : { uuid: id }
149 function parseAggregateResult (result: any) {
150 if (!result) return 0
152 const total = parseInt(result + '', 10)
153 if (isNaN(total)) return 0
158 const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
159 return stringArr.map(t => model.sequelize.escape('' + t))
163 function buildLocalAccountIdsIn () {
165 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
169 function buildLocalActorIdsIn () {
171 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
175 // ---------------------------------------------------------------------------
178 buildBlockedAccountSQL,
179 buildLocalActorIdsIn,
181 buildLocalAccountIdsIn,
186 createSimilarityAttribute,
188 buildServerIdsFollowedBy,
189 buildTrigramSearchIndex,
192 parseAggregateResult,
197 // ---------------------------------------------------------------------------
199 function searchTrigramNormalizeValue (value: string) {
200 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
203 function searchTrigramNormalizeCol (col: string) {
204 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
207 function buildDirectionAndField (value: string) {
209 let direction: 'ASC' | 'DESC'
211 if (value.substring(0, 1) === '-') {
213 field = value.substring(1)
219 return { direction, field }