1 import { literal, Model, ModelStatic, Op, OrderItem, Sequelize } from 'sequelize'
2 import validator from 'validator'
3 import { forceNumber } from '@shared/core-utils'
4 import { AttributesOnly } from '@shared/typescript-utils'
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 | ReturnType<typeof Sequelize.col>
14 if (field.toLowerCase() === 'match') { // Search
15 finalField = Sequelize.col('similarity')
20 return [ [ finalField, direction ], lastSort ]
23 function getAdminUsersSort (value: string): OrderItem[] {
24 const { direction, field } = buildDirectionAndField(value)
26 let finalField: string | ReturnType<typeof Sequelize.col>
28 if (field === 'videoQuotaUsed') { // Users list
29 finalField = Sequelize.col('videoQuotaUsed')
34 const nullPolicy = direction === 'ASC'
39 return [ [ finalField as any, direction, nullPolicy ], [ 'id', 'ASC' ] ]
42 function getPlaylistSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
43 const { direction, field } = buildDirectionAndField(value)
45 if (field.toLowerCase() === 'name') {
46 return [ [ 'displayName', direction ], lastSort ]
49 return getSort(value, lastSort)
52 function getCommentSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
53 const { direction, field } = buildDirectionAndField(value)
55 if (field === 'totalReplies') {
57 [ Sequelize.literal('"totalReplies"'), direction ],
62 return getSort(value, lastSort)
65 function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
66 const { direction, field } = buildDirectionAndField(value)
68 if (field.toLowerCase() === 'trending') { // Sort by aggregation
70 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
72 [ Sequelize.col('VideoModel.views'), direction ],
76 } else if (field === 'publishedAt') {
78 [ 'ScheduleVideoUpdate', 'updateAt', direction + ' NULLS LAST' ],
80 [ Sequelize.col('VideoModel.publishedAt'), direction ],
86 let finalField: string | ReturnType<typeof Sequelize.col>
89 if (field.toLowerCase() === 'match') { // Search
90 finalField = Sequelize.col('similarity')
95 const firstSort: OrderItem = typeof finalField === 'string'
96 ? finalField.split('.').concat([ direction ]) as OrderItem
97 : [ finalField, direction ]
99 return [ firstSort, lastSort ]
102 function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
103 const [ firstSort ] = getSort(value)
105 if (model) return [ [ literal(`"${model}.${firstSort[0]}" ${firstSort[1]}`) ], lastSort ] as OrderItem[]
106 return [ firstSort, lastSort ]
109 function getInstanceFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
110 const { direction, field } = buildDirectionAndField(value)
112 if (field === 'redundancyAllowed') {
114 [ 'ActorFollowing.Server.redundancyAllowed', direction ],
119 return getSort(value, lastSort)
122 function getChannelSyncSort (value: string): OrderItem[] {
123 const { direction, field } = buildDirectionAndField(value)
124 if (field.toLowerCase() === 'videochannel') {
126 [ literal('"VideoChannel.name"'), direction ]
129 return [ [ field, direction ] ]
132 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
133 if (!model.createdAt || !model.updatedAt) {
134 throw new Error('Miss createdAt & updatedAt attributes to model')
137 const now = Date.now()
138 const createdAtTime = model.createdAt.getTime()
139 const updatedAtTime = model.updatedAt.getTime()
141 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
144 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
145 if (nullable && (value === null || value === undefined)) return
147 if (validator(value) === false) {
148 throw new Error(`"${value}" is not a valid ${fieldName}.`)
152 function buildTrigramSearchIndex (indexName: string, attribute: string) {
155 // FIXME: gin_trgm_ops is not taken into account in Sequelize 6, so adding it ourselves in the literal function
156 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + ')) gin_trgm_ops') as any ],
158 operator: 'gin_trgm_ops'
162 function createSimilarityAttribute (col: string, value: string) {
166 searchTrigramNormalizeCol(col),
168 searchTrigramNormalizeValue(value)
172 function buildBlockedAccountSQL (blockerIds: number[]) {
173 const blockerIdsString = blockerIds.join(', ')
175 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
177 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
178 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
179 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
182 function buildServerIdsFollowedBy (actorId: any) {
183 const actorIdNumber = forceNumber(actorId)
186 'SELECT "actor"."serverId" FROM "actorFollow" ' +
187 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
188 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
192 function buildWhereIdOrUUID (id: number | string) {
193 return validator.isInt('' + id) ? { id } : { uuid: id }
196 function parseAggregateResult (result: any) {
197 if (!result) return 0
199 const total = forceNumber(result)
200 if (isNaN(total)) return 0
205 function parseRowCountResult (result: any) {
206 if (result.length !== 0) return result[0].total
211 function createSafeIn (sequelize: Sequelize, toEscape: (string | number)[], additionalUnescaped: string[] = []) {
212 return toEscape.map(t => {
215 : sequelize.escape('' + t)
216 }).concat(additionalUnescaped).join(', ')
219 function buildLocalAccountIdsIn () {
221 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
225 function buildLocalActorIdsIn () {
227 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
231 function buildDirectionAndField (value: string) {
233 let direction: 'ASC' | 'DESC'
235 if (value.substring(0, 1) === '-') {
237 field = value.substring(1)
243 return { direction, field }
246 function searchAttribute (sourceField?: string, targetField?: string) {
247 if (!sourceField) return {}
252 [Op.iLike as any]: `%${sourceField}%`
257 function buildSQLAttributes <M extends Model> (options: {
258 model: ModelStatic<M>
261 excludeAttributes?: Exclude<keyof AttributesOnly<M>, symbol>[]
264 const { model, tableName, aliasPrefix, excludeAttributes } = options
266 const attributes = Object.keys(model.getAttributes()) as Exclude<keyof AttributesOnly<M>, symbol>[]
270 if (!excludeAttributes) return true
271 if (excludeAttributes.includes(a)) return false
276 return `"${tableName}"."${a}" AS "${aliasPrefix || ''}${a}"`
280 // ---------------------------------------------------------------------------
284 buildBlockedAccountSQL,
285 buildLocalActorIdsIn,
288 buildLocalAccountIdsIn,
295 createSimilarityAttribute,
297 buildServerIdsFollowedBy,
298 buildTrigramSearchIndex,
301 parseAggregateResult,
302 getInstanceFollowsSort,
303 buildDirectionAndField,
309 // ---------------------------------------------------------------------------
311 function searchTrigramNormalizeValue (value: string) {
312 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
315 function searchTrigramNormalizeCol (col: string) {
316 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))