1 import { Model, Sequelize } from 'sequelize-typescript'
2 import * as 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 getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
26 const { direction, field } = buildDirectionAndField(value)
28 if (field.toLowerCase() === 'trending') { // Sort by aggregation
30 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
32 [ Sequelize.col('VideoModel.views'), direction ],
38 let finalField: string | Col
41 if (field.toLowerCase() === 'match') { // Search
42 finalField = Sequelize.col('similarity')
47 const firstSort = typeof finalField === 'string'
48 ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
49 : [ finalField, direction ]
51 return [ firstSort, lastSort ]
54 function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
55 const [ firstSort ] = getSort(value)
57 if (model) return [ [ literal(`"${model}.${firstSort[ 0 ]}" ${firstSort[ 1 ]}`) ], lastSort ] as any[] // FIXME: typings
58 return [ firstSort, lastSort ]
61 function getFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
62 const { direction, field } = buildDirectionAndField(value)
64 if (field === 'redundancyAllowed') {
66 [ 'ActorFollowing', 'Server', 'redundancyAllowed', direction ],
71 return getSort(value, lastSort)
74 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
75 const now = Date.now()
76 const createdAtTime = model.createdAt.getTime()
77 const updatedAtTime = model.updatedAt.getTime()
79 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
82 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
83 if (nullable && (value === null || value === undefined)) return
85 if (validator(value) === false) {
86 throw new Error(`"${value}" is not a valid ${fieldName}.`)
90 function buildTrigramSearchIndex (indexName: string, attribute: string) {
93 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
95 operator: 'gin_trgm_ops'
99 function createSimilarityAttribute (col: string, value: string) {
103 searchTrigramNormalizeCol(col),
105 searchTrigramNormalizeValue(value)
109 function buildBlockedAccountSQL (serverAccountId: number, userAccountId?: number) {
110 const blockerIds = [ serverAccountId ]
111 if (userAccountId) blockerIds.push(userAccountId)
113 const blockerIdsString = blockerIds.join(', ')
115 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
117 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
118 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
119 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
122 function buildServerIdsFollowedBy (actorId: any) {
123 const actorIdNumber = parseInt(actorId + '', 10)
126 'SELECT "actor"."serverId" FROM "actorFollow" ' +
127 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
128 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
132 function buildWhereIdOrUUID (id: number | string) {
133 return validator.isInt('' + id) ? { id } : { uuid: id }
136 function parseAggregateResult (result: any) {
137 if (!result) return 0
139 const total = parseInt(result + '', 10)
140 if (isNaN(total)) return 0
145 const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
146 return stringArr.map(t => model.sequelize.escape('' + t))
150 function buildLocalAccountIdsIn () {
152 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
156 function buildLocalActorIdsIn () {
158 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
162 // ---------------------------------------------------------------------------
165 buildBlockedAccountSQL,
166 buildLocalActorIdsIn,
168 buildLocalAccountIdsIn,
172 createSimilarityAttribute,
174 buildServerIdsFollowedBy,
175 buildTrigramSearchIndex,
178 parseAggregateResult,
183 // ---------------------------------------------------------------------------
185 function searchTrigramNormalizeValue (value: string) {
186 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
189 function searchTrigramNormalizeCol (col: string) {
190 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
193 function buildDirectionAndField (value: string) {
195 let direction: 'ASC' | 'DESC'
197 if (value.substring(0, 1) === '-') {
199 field = value.substring(1)
205 return { direction, field }