1 import { Model, Sequelize } from 'sequelize-typescript'
2 import * as validator from 'validator'
3 import { Col } from 'sequelize/types/lib/utils'
4 import { OrderItem } from 'sequelize/types'
6 type SortType = { sortModel: any, 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')
20 return [ [ finalField, direction ], lastSort ]
23 function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
24 const { direction, field } = buildDirectionAndField(value)
26 if (field.toLowerCase() === 'trending') { // Sort by aggregation
28 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
30 [ Sequelize.col('VideoModel.views'), direction ],
36 let finalField: string | Col
39 if (field.toLowerCase() === 'match') { // Search
40 finalField = Sequelize.col('similarity')
45 const firstSort = typeof finalField === 'string'
46 ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
47 : [ finalField, direction ]
49 return [ firstSort, lastSort ]
52 function getSortOnModel (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
53 const [ firstSort ] = getSort(value)
55 if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ]
56 return [ firstSort, lastSort ]
59 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
60 const now = Date.now()
61 const createdAtTime = model.createdAt.getTime()
62 const updatedAtTime = model.updatedAt.getTime()
64 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
67 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
68 if (nullable && (value === null || value === undefined)) return
70 if (validator(value) === false) {
71 throw new Error(`"${value}" is not a valid ${fieldName}.`)
75 function buildTrigramSearchIndex (indexName: string, attribute: string) {
78 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
80 operator: 'gin_trgm_ops'
84 function createSimilarityAttribute (col: string, value: string) {
88 searchTrigramNormalizeCol(col),
90 searchTrigramNormalizeValue(value)
94 function buildBlockedAccountSQL (serverAccountId: number, userAccountId?: number) {
95 const blockerIds = [ serverAccountId ]
96 if (userAccountId) blockerIds.push(userAccountId)
98 const blockerIdsString = blockerIds.join(', ')
100 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
102 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
103 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
104 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
107 function buildServerIdsFollowedBy (actorId: any) {
108 const actorIdNumber = parseInt(actorId + '', 10)
111 'SELECT "actor"."serverId" FROM "actorFollow" ' +
112 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
113 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
117 function buildWhereIdOrUUID (id: number | string) {
118 return validator.isInt('' + id) ? { id } : { uuid: id }
121 function parseAggregateResult (result: any) {
122 if (!result) return 0
124 const total = parseInt(result + '', 10)
125 if (isNaN(total)) return 0
130 const createSafeIn = (model: typeof Model, stringArr: string[]) => {
131 return stringArr.map(t => model.sequelize.escape(t))
135 // ---------------------------------------------------------------------------
138 buildBlockedAccountSQL,
143 createSimilarityAttribute,
145 buildServerIdsFollowedBy,
146 buildTrigramSearchIndex,
149 parseAggregateResult,
153 // ---------------------------------------------------------------------------
155 function searchTrigramNormalizeValue (value: string) {
156 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
159 function searchTrigramNormalizeCol (col: string) {
160 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
163 function buildDirectionAndField (value: string) {
165 let direction: 'ASC' | 'DESC'
167 if (value.substring(0, 1) === '-') {
169 field = value.substring(1)
175 return { direction, field }