1 import { literal, Op, OrderItem, Sequelize } from 'sequelize'
2 import validator from 'validator'
4 type SortType = { sortModel: string, sortValue: string }
6 // Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
7 function getSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
8 const { direction, field } = buildDirectionAndField(value)
10 let finalField: string | ReturnType<typeof Sequelize.col>
12 if (field.toLowerCase() === 'match') { // Search
13 finalField = Sequelize.col('similarity')
18 return [ [ finalField, direction ], lastSort ]
21 function getAdminUsersSort (value: string): OrderItem[] {
22 const { direction, field } = buildDirectionAndField(value)
24 let finalField: string | ReturnType<typeof Sequelize.col>
26 if (field === 'videoQuotaUsed') { // Users list
27 finalField = Sequelize.col('videoQuotaUsed')
32 const nullPolicy = direction === 'ASC'
37 return [ [ finalField as any, direction, nullPolicy ], [ 'id', 'ASC' ] ]
40 function getPlaylistSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
41 const { direction, field } = buildDirectionAndField(value)
43 if (field.toLowerCase() === 'name') {
44 return [ [ 'displayName', direction ], lastSort ]
47 return getSort(value, lastSort)
50 function getCommentSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
51 const { direction, field } = buildDirectionAndField(value)
53 if (field === 'totalReplies') {
55 [ Sequelize.literal('"totalReplies"'), direction ],
60 return getSort(value, lastSort)
63 function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
64 const { direction, field } = buildDirectionAndField(value)
66 if (field.toLowerCase() === 'trending') { // Sort by aggregation
68 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
70 [ Sequelize.col('VideoModel.views'), direction ],
74 } else if (field === 'publishedAt') {
76 [ 'ScheduleVideoUpdate', 'updateAt', direction + ' NULLS LAST' ],
78 [ Sequelize.col('VideoModel.publishedAt'), direction ],
84 let finalField: string | ReturnType<typeof Sequelize.col>
87 if (field.toLowerCase() === 'match') { // Search
88 finalField = Sequelize.col('similarity')
93 const firstSort: OrderItem = typeof finalField === 'string'
94 ? finalField.split('.').concat([ direction ]) as OrderItem
95 : [ finalField, direction ]
97 return [ firstSort, lastSort ]
100 function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
101 const [ firstSort ] = getSort(value)
103 if (model) return [ [ literal(`"${model}.${firstSort[0]}" ${firstSort[1]}`) ], lastSort ] as OrderItem[]
104 return [ firstSort, lastSort ]
107 function getInstanceFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
108 const { direction, field } = buildDirectionAndField(value)
110 if (field === 'redundancyAllowed') {
112 [ 'ActorFollowing.Server.redundancyAllowed', direction ],
117 return getSort(value, lastSort)
120 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
121 if (!model.createdAt || !model.updatedAt) {
122 throw new Error('Miss createdAt & updatedAt attributes to model')
125 const now = Date.now()
126 const createdAtTime = model.createdAt.getTime()
127 const updatedAtTime = model.updatedAt.getTime()
129 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
132 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
133 if (nullable && (value === null || value === undefined)) return
135 if (validator(value) === false) {
136 throw new Error(`"${value}" is not a valid ${fieldName}.`)
140 function buildTrigramSearchIndex (indexName: string, attribute: string) {
143 // FIXME: gin_trgm_ops is not taken into account in Sequelize 6, so adding it ourselves in the literal function
144 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + ')) gin_trgm_ops') as any ],
146 operator: 'gin_trgm_ops'
150 function createSimilarityAttribute (col: string, value: string) {
154 searchTrigramNormalizeCol(col),
156 searchTrigramNormalizeValue(value)
160 function buildBlockedAccountSQL (blockerIds: number[]) {
161 const blockerIdsString = blockerIds.join(', ')
163 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
165 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
166 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
167 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
170 function buildBlockedAccountSQLOptimized (columnNameJoin: string, blockerIds: number[]) {
171 const blockerIdsString = blockerIds.join(', ')
176 ` SELECT 1 FROM "accountBlocklist" ` +
177 ` WHERE "targetAccountId" = ${columnNameJoin} ` +
178 ` AND "accountId" IN (${blockerIdsString})` +
184 ` SELECT 1 FROM "account" ` +
185 ` INNER JOIN "actor" ON account."actorId" = actor.id ` +
186 ` INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ` +
187 ` WHERE "account"."id" = ${columnNameJoin} ` +
188 ` AND "serverBlocklist"."accountId" IN (${blockerIdsString})` +
194 function buildServerIdsFollowedBy (actorId: any) {
195 const actorIdNumber = parseInt(actorId + '', 10)
198 'SELECT "actor"."serverId" FROM "actorFollow" ' +
199 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
200 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
204 function buildWhereIdOrUUID (id: number | string) {
205 return validator.isInt('' + id) ? { id } : { uuid: id }
208 function parseAggregateResult (result: any) {
209 if (!result) return 0
211 const total = parseInt(result + '', 10)
212 if (isNaN(total)) return 0
217 function parseRowCountResult (result: any) {
218 if (result.length !== 0) return result[0].total
223 function createSafeIn (sequelize: Sequelize, stringArr: (string | number)[]) {
224 return stringArr.map(t => {
227 : sequelize.escape('' + t)
231 function buildLocalAccountIdsIn () {
233 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
237 function buildLocalActorIdsIn () {
239 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
243 function buildDirectionAndField (value: string) {
245 let direction: 'ASC' | 'DESC'
247 if (value.substring(0, 1) === '-') {
249 field = value.substring(1)
255 return { direction, field }
258 function searchAttribute (sourceField?: string, targetField?: string) {
259 if (!sourceField) return {}
264 [Op.iLike as any]: `%${sourceField}%`
269 // ---------------------------------------------------------------------------
272 buildBlockedAccountSQL,
273 buildBlockedAccountSQLOptimized,
274 buildLocalActorIdsIn,
277 buildLocalAccountIdsIn,
283 createSimilarityAttribute,
285 buildServerIdsFollowedBy,
286 buildTrigramSearchIndex,
289 parseAggregateResult,
290 getInstanceFollowsSort,
291 buildDirectionAndField,
297 // ---------------------------------------------------------------------------
299 function searchTrigramNormalizeValue (value: string) {
300 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
303 function searchTrigramNormalizeCol (col: string) {
304 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))