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')
14 } else if (field === 'videoQuotaUsed') { // Users list
15 finalField = Sequelize.col('videoQuotaUsed')
20 return [ [ finalField, direction ], lastSort ]
23 function getPlaylistSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
24 const { direction, field } = buildDirectionAndField(value)
26 if (field.toLowerCase() === 'name') {
27 return [ [ 'displayName', direction ], lastSort ]
30 return getSort(value, lastSort)
33 function getCommentSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
34 const { direction, field } = buildDirectionAndField(value)
36 if (field === 'totalReplies') {
38 [ Sequelize.literal('"totalReplies"'), direction ],
43 return getSort(value, lastSort)
46 function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
47 const { direction, field } = buildDirectionAndField(value)
49 if (field.toLowerCase() === 'trending') { // Sort by aggregation
51 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
53 [ Sequelize.col('VideoModel.views'), direction ],
57 } else if (field === 'publishedAt') {
59 [ 'ScheduleVideoUpdate', 'updateAt', direction + ' NULLS LAST' ],
61 [ Sequelize.col('VideoModel.publishedAt'), direction ],
67 let finalField: string | ReturnType<typeof Sequelize.col>
70 if (field.toLowerCase() === 'match') { // Search
71 finalField = Sequelize.col('similarity')
76 const firstSort: OrderItem = typeof finalField === 'string'
77 ? finalField.split('.').concat([ direction ]) as OrderItem
78 : [ finalField, direction ]
80 return [ firstSort, lastSort ]
83 function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
84 const [ firstSort ] = getSort(value)
86 if (model) return [ [ literal(`"${model}.${firstSort[0]}" ${firstSort[1]}`) ], lastSort ] as OrderItem[]
87 return [ firstSort, lastSort ]
90 function getFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
91 const { direction, field } = buildDirectionAndField(value)
93 if (field === 'redundancyAllowed') {
95 [ 'ActorFollowing', 'Server', 'redundancyAllowed', direction ],
100 return getSort(value, lastSort)
103 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
104 if (!model.createdAt || !model.updatedAt) {
105 throw new Error('Miss createdAt & updatedAt attribuets to model')
108 const now = Date.now()
109 const createdAtTime = model.createdAt.getTime()
110 const updatedAtTime = model.updatedAt.getTime()
112 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
115 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
116 if (nullable && (value === null || value === undefined)) return
118 if (validator(value) === false) {
119 throw new Error(`"${value}" is not a valid ${fieldName}.`)
123 function buildTrigramSearchIndex (indexName: string, attribute: string) {
126 // FIXME: gin_trgm_ops is not taken into account in Sequelize 6, so adding it ourselves in the literal function
127 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + ')) gin_trgm_ops') as any ],
129 operator: 'gin_trgm_ops'
133 function createSimilarityAttribute (col: string, value: string) {
137 searchTrigramNormalizeCol(col),
139 searchTrigramNormalizeValue(value)
143 function buildBlockedAccountSQL (blockerIds: number[]) {
144 const blockerIdsString = blockerIds.join(', ')
146 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
148 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
149 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
150 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
153 function buildBlockedAccountSQLOptimized (columnNameJoin: string, blockerIds: number[]) {
154 const blockerIdsString = blockerIds.join(', ')
159 ` SELECT 1 FROM "accountBlocklist" ` +
160 ` WHERE "targetAccountId" = ${columnNameJoin} ` +
161 ` AND "accountId" IN (${blockerIdsString})` +
167 ` SELECT 1 FROM "account" ` +
168 ` INNER JOIN "actor" ON account."actorId" = actor.id ` +
169 ` INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ` +
170 ` WHERE "account"."id" = ${columnNameJoin} ` +
171 ` AND "serverBlocklist"."accountId" IN (${blockerIdsString})` +
177 function buildServerIdsFollowedBy (actorId: any) {
178 const actorIdNumber = parseInt(actorId + '', 10)
181 'SELECT "actor"."serverId" FROM "actorFollow" ' +
182 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
183 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
187 function buildWhereIdOrUUID (id: number | string) {
188 return validator.isInt('' + id) ? { id } : { uuid: id }
191 function parseAggregateResult (result: any) {
192 if (!result) return 0
194 const total = parseInt(result + '', 10)
195 if (isNaN(total)) return 0
200 function createSafeIn (sequelize: Sequelize, stringArr: (string | number)[]) {
201 return stringArr.map(t => {
204 : sequelize.escape('' + t)
208 function buildLocalAccountIdsIn () {
210 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
214 function buildLocalActorIdsIn () {
216 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
220 function buildDirectionAndField (value: string) {
222 let direction: 'ASC' | 'DESC'
224 if (value.substring(0, 1) === '-') {
226 field = value.substring(1)
232 return { direction, field }
235 function searchAttribute (sourceField?: string, targetField?: string) {
236 if (!sourceField) return {}
241 [Op.iLike as any]: `%${sourceField}%`
246 // ---------------------------------------------------------------------------
249 buildBlockedAccountSQL,
250 buildBlockedAccountSQLOptimized,
251 buildLocalActorIdsIn,
254 buildLocalAccountIdsIn,
259 createSimilarityAttribute,
261 buildServerIdsFollowedBy,
262 buildTrigramSearchIndex,
265 parseAggregateResult,
267 buildDirectionAndField,
272 // ---------------------------------------------------------------------------
274 function searchTrigramNormalizeValue (value: string) {
275 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
278 function searchTrigramNormalizeCol (col: string) {
279 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))