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 Primitive = string | Function | number | boolean | Symbol | undefined | null
7 type DeepOmitHelper<T, K extends keyof T> = {
8 [P in K]: // extra level of indirection needed to trigger homomorhic behavior
9 T[P] extends infer TP // distribute over unions
10 ? TP extends Primitive
11 ? TP // leave primitives and functions alone
13 ? DeepOmitArray<TP, K> // Array special handling
17 type DeepOmit<T, K> = T extends Primitive ? T : DeepOmitHelper<T, Exclude<keyof T, K>>
19 type DeepOmitArray<T extends any[], K> = {
20 [P in keyof T]: DeepOmit<T[P], K>
23 type SortType = { sortModel: string, sortValue: string }
25 // Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
26 function getSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
27 const { direction, field } = buildDirectionAndField(value)
29 let finalField: string | Col
31 if (field.toLowerCase() === 'match') { // Search
32 finalField = Sequelize.col('similarity')
33 } else if (field === 'videoQuotaUsed') { // Users list
34 finalField = Sequelize.col('videoQuotaUsed')
39 return [ [ finalField, direction ], lastSort ]
42 function getCommentSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
43 const { direction, field } = buildDirectionAndField(value)
45 if (field === 'totalReplies') {
47 [ Sequelize.literal('"totalReplies"'), direction ],
52 return getSort(value, lastSort)
55 function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
56 const { direction, field } = buildDirectionAndField(value)
58 if (field.toLowerCase() === 'trending') { // Sort by aggregation
60 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
62 [ Sequelize.col('VideoModel.views'), direction ],
68 let finalField: string | Col
71 if (field.toLowerCase() === 'match') { // Search
72 finalField = Sequelize.col('similarity')
77 const firstSort = typeof finalField === 'string'
78 ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
79 : [ finalField, direction ]
81 return [ firstSort, lastSort ]
84 function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
85 const [ firstSort ] = getSort(value)
87 if (model) return [ [ literal(`"${model}.${firstSort[0]}" ${firstSort[1]}`) ], lastSort ] as any[] // FIXME: typings
88 return [ firstSort, lastSort ]
91 function getFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
92 const { direction, field } = buildDirectionAndField(value)
94 if (field === 'redundancyAllowed') {
96 [ 'ActorFollowing', 'Server', 'redundancyAllowed', direction ],
101 return getSort(value, lastSort)
104 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
105 const now = Date.now()
106 const createdAtTime = model.createdAt.getTime()
107 const updatedAtTime = model.updatedAt.getTime()
109 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
112 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
113 if (nullable && (value === null || value === undefined)) return
115 if (validator(value) === false) {
116 throw new Error(`"${value}" is not a valid ${fieldName}.`)
120 function buildTrigramSearchIndex (indexName: string, attribute: string) {
123 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
125 operator: 'gin_trgm_ops'
129 function createSimilarityAttribute (col: string, value: string) {
133 searchTrigramNormalizeCol(col),
135 searchTrigramNormalizeValue(value)
139 function buildBlockedAccountSQL (serverAccountId: number, userAccountId?: number) {
140 const blockerIds = [ serverAccountId ]
141 if (userAccountId) blockerIds.push(userAccountId)
143 const blockerIdsString = blockerIds.join(', ')
145 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
147 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
148 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
149 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
152 function buildServerIdsFollowedBy (actorId: any) {
153 const actorIdNumber = parseInt(actorId + '', 10)
156 'SELECT "actor"."serverId" FROM "actorFollow" ' +
157 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
158 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
162 function buildWhereIdOrUUID (id: number | string) {
163 return validator.isInt('' + id) ? { id } : { uuid: id }
166 function parseAggregateResult (result: any) {
167 if (!result) return 0
169 const total = parseInt(result + '', 10)
170 if (isNaN(total)) return 0
175 const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
176 return stringArr.map(t => {
179 : model.sequelize.escape('' + t)
183 function buildLocalAccountIdsIn () {
185 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
189 function buildLocalActorIdsIn () {
191 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
195 function buildDirectionAndField (value: string) {
197 let direction: 'ASC' | 'DESC'
199 if (value.substring(0, 1) === '-') {
201 field = value.substring(1)
207 return { direction, field }
210 // ---------------------------------------------------------------------------
214 buildBlockedAccountSQL,
215 buildLocalActorIdsIn,
217 buildLocalAccountIdsIn,
222 createSimilarityAttribute,
224 buildServerIdsFollowedBy,
225 buildTrigramSearchIndex,
228 parseAggregateResult,
230 buildDirectionAndField,
234 // ---------------------------------------------------------------------------
236 function searchTrigramNormalizeValue (value: string) {
237 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
240 function searchTrigramNormalizeCol (col: string) {
241 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))