]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/utils.ts
Rename signup steps
[github/Chocobozzz/PeerTube.git] / server / models / utils.ts
CommitLineData
3caf77d3 1import { Model, Sequelize } from 'sequelize-typescript'
418d092a 2import * as validator from 'validator'
1735c825 3import { Col } from 'sequelize/types/lib/utils'
6b9c966f 4import { OrderItem, literal } from 'sequelize'
57c36b27 5
06215f15
C
6type SortType = { sortModel: any, sortValue: string }
7
9a629c6e 8// Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
1735c825
C
9function getSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
10 const { direction, field } = buildDirectionAndField(value)
11
12 let finalField: string | Col
4b54f136
C
13
14 if (field.toLowerCase() === 'match') { // Search
1735c825 15 finalField = Sequelize.col('similarity')
aa3796bd
C
16 } else if (field === 'videoQuotaUsed') { // Users list
17 finalField = Sequelize.col('videoQuotaUsed')
1735c825
C
18 } else {
19 finalField = field
4b54f136 20 }
5c39adb7 21
1735c825 22 return [ [ finalField, direction ], lastSort ]
9a629c6e
C
23}
24
1735c825
C
25function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
26 const { direction, field } = buildDirectionAndField(value)
5c39adb7 27
1735c825 28 if (field.toLowerCase() === 'trending') { // Sort by aggregation
9a629c6e
C
29 return [
30 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
31
32 [ Sequelize.col('VideoModel.views'), direction ],
33
34 lastSort
35 ]
36 }
37
1735c825
C
38 let finalField: string | Col
39
40 // Alias
41 if (field.toLowerCase() === 'match') { // Search
42 finalField = Sequelize.col('similarity')
43 } else {
44 finalField = field
45 }
46
47 const firstSort = typeof finalField === 'string'
48 ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
49 : [ finalField, direction ]
afa4374a
C
50
51 return [ firstSort, lastSort ]
5c39adb7
C
52}
53
1735c825
C
54function getSortOnModel (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
55 const [ firstSort ] = getSort(value)
792dbaf0 56
3bb6c526
C
57 if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ]
58 return [ firstSort, lastSort ]
792dbaf0
GS
59}
60
9f79ade6
C
61function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
62 const now = Date.now()
63 const createdAtTime = model.createdAt.getTime()
64 const updatedAtTime = model.updatedAt.getTime()
65
66 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
67}
68
1735c825
C
69function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
70 if (nullable && (value === null || value === undefined)) return
71
3fd3ab2d
C
72 if (validator(value) === false) {
73 throw new Error(`"${value}" is not a valid ${fieldName}.`)
74 }
75}
76
57c36b27
C
77function buildTrigramSearchIndex (indexName: string, attribute: string) {
78 return {
79 name: indexName,
80 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
81 using: 'gin',
82 operator: 'gin_trgm_ops'
83 }
84}
85
86function createSimilarityAttribute (col: string, value: string) {
87 return Sequelize.fn(
88 'similarity',
89
90 searchTrigramNormalizeCol(col),
91
92 searchTrigramNormalizeValue(value)
93 )
94}
95
7ad9b984
C
96function buildBlockedAccountSQL (serverAccountId: number, userAccountId?: number) {
97 const blockerIds = [ serverAccountId ]
98 if (userAccountId) blockerIds.push(userAccountId)
99
100 const blockerIdsString = blockerIds.join(', ')
101
418d092a 102 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
7ad9b984 103 ' UNION ALL ' +
7ad9b984
C
104 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
105 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
106 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
418d092a
C
107}
108
109function buildServerIdsFollowedBy (actorId: any) {
110 const actorIdNumber = parseInt(actorId + '', 10)
111
112 return '(' +
113 'SELECT "actor"."serverId" FROM "actorFollow" ' +
114 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
115 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
116 ')'
117}
7ad9b984 118
418d092a
C
119function buildWhereIdOrUUID (id: number | string) {
120 return validator.isInt('' + id) ? { id } : { uuid: id }
7ad9b984
C
121}
122
3acc5084
C
123function parseAggregateResult (result: any) {
124 if (!result) return 0
125
126 const total = parseInt(result + '', 10)
127 if (isNaN(total)) return 0
128
129 return total
130}
131
6b9c966f
C
132const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
133 return stringArr.map(t => model.sequelize.escape('' + t))
3caf77d3
C
134 .join(', ')
135}
136
6b9c966f
C
137function buildLocalAccountIdsIn () {
138 return literal(
139 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
140 )
141}
142
143function buildLocalActorIdsIn () {
144 return literal(
145 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
146 )
147}
148
5c39adb7
C
149// ---------------------------------------------------------------------------
150
65fcc311 151export {
7ad9b984 152 buildBlockedAccountSQL,
6b9c966f 153 buildLocalActorIdsIn,
06215f15 154 SortType,
6b9c966f 155 buildLocalAccountIdsIn,
792dbaf0 156 getSort,
9a629c6e 157 getVideoSort,
3fd3ab2d 158 getSortOnModel,
57c36b27
C
159 createSimilarityAttribute,
160 throwIfNotValid,
418d092a
C
161 buildServerIdsFollowedBy,
162 buildTrigramSearchIndex,
9f79ade6 163 buildWhereIdOrUUID,
3acc5084 164 isOutdated,
3caf77d3
C
165 parseAggregateResult,
166 createSafeIn
57c36b27
C
167}
168
169// ---------------------------------------------------------------------------
170
171function searchTrigramNormalizeValue (value: string) {
2cebd797 172 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
57c36b27
C
173}
174
175function searchTrigramNormalizeCol (col: string) {
176 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
65fcc311 177}
9a629c6e
C
178
179function buildDirectionAndField (value: string) {
1735c825 180 let field: string
9a629c6e
C
181 let direction: 'ASC' | 'DESC'
182
183 if (value.substring(0, 1) === '-') {
184 direction = 'DESC'
185 field = value.substring(1)
186 } else {
187 direction = 'ASC'
188 field = value
189 }
190
191 return { direction, field }
192}