Upgrade sequelize
[oweals/peertube.git] / server / models / utils.ts
1 import { Sequelize } from 'sequelize-typescript'
2 import * as validator from 'validator'
3 import { OrderItem } from 'sequelize'
4 import { Col } from 'sequelize/types/lib/utils'
5
6 type SortType = { sortModel: any, sortValue: string }
7
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)
11
12   let finalField: string | Col
13
14   if (field.toLowerCase() === 'match') { // Search
15     finalField = Sequelize.col('similarity')
16   } else {
17     finalField = field
18   }
19
20   return [ [ finalField, direction ], lastSort ]
21 }
22
23 function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
24   const { direction, field } = buildDirectionAndField(value)
25
26   if (field.toLowerCase() === 'trending') { // Sort by aggregation
27     return [
28       [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
29
30       [ Sequelize.col('VideoModel.views'), direction ],
31
32       lastSort
33     ]
34   }
35
36   let finalField: string | Col
37
38   // Alias
39   if (field.toLowerCase() === 'match') { // Search
40     finalField = Sequelize.col('similarity')
41   } else {
42     finalField = field
43   }
44
45   const firstSort = typeof finalField === 'string'
46     ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
47     : [ finalField, direction ]
48
49   return [ firstSort, lastSort ]
50 }
51
52 function getSortOnModel (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
53   const [ firstSort ] = getSort(value)
54
55   if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ]
56   return [ firstSort, lastSort ]
57 }
58
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()
63
64   return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
65 }
66
67 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
68   if (nullable && (value === null || value === undefined)) return
69
70   if (validator(value) === false) {
71     throw new Error(`"${value}" is not a valid ${fieldName}.`)
72   }
73 }
74
75 function buildTrigramSearchIndex (indexName: string, attribute: string) {
76   return {
77     name: indexName,
78     fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
79     using: 'gin',
80     operator: 'gin_trgm_ops'
81   }
82 }
83
84 function createSimilarityAttribute (col: string, value: string) {
85   return Sequelize.fn(
86     'similarity',
87
88     searchTrigramNormalizeCol(col),
89
90     searchTrigramNormalizeValue(value)
91   )
92 }
93
94 function buildBlockedAccountSQL (serverAccountId: number, userAccountId?: number) {
95   const blockerIds = [ serverAccountId ]
96   if (userAccountId) blockerIds.push(userAccountId)
97
98   const blockerIdsString = blockerIds.join(', ')
99
100   return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
101     ' UNION ALL ' +
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 + ')'
105 }
106
107 function buildServerIdsFollowedBy (actorId: any) {
108   const actorIdNumber = parseInt(actorId + '', 10)
109
110   return '(' +
111     'SELECT "actor"."serverId" FROM "actorFollow" ' +
112     'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
113     'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
114   ')'
115 }
116
117 function buildWhereIdOrUUID (id: number | string) {
118   return validator.isInt('' + id) ? { id } : { uuid: id }
119 }
120
121 function parseAggregateResult (result: any) {
122   if (!result) return 0
123
124   const total = parseInt(result + '', 10)
125   if (isNaN(total)) return 0
126
127   return total
128 }
129
130 // ---------------------------------------------------------------------------
131
132 export {
133   buildBlockedAccountSQL,
134   SortType,
135   getSort,
136   getVideoSort,
137   getSortOnModel,
138   createSimilarityAttribute,
139   throwIfNotValid,
140   buildServerIdsFollowedBy,
141   buildTrigramSearchIndex,
142   buildWhereIdOrUUID,
143   isOutdated,
144   parseAggregateResult
145 }
146
147 // ---------------------------------------------------------------------------
148
149 function searchTrigramNormalizeValue (value: string) {
150   return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
151 }
152
153 function searchTrigramNormalizeCol (col: string) {
154   return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
155 }
156
157 function buildDirectionAndField (value: string) {
158   let field: string
159   let direction: 'ASC' | 'DESC'
160
161   if (value.substring(0, 1) === '-') {
162     direction = 'DESC'
163     field = value.substring(1)
164   } else {
165     direction = 'ASC'
166     field = value
167   }
168
169   return { direction, field }
170 }