]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/utils.ts
Fix theater mode
[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'
3caf77d3 4import { OrderItem } from 'sequelize/types'
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
3caf77d3
C
132const createSafeIn = (model: typeof Model, stringArr: string[]) => {
133 return stringArr.map(t => model.sequelize.escape(t))
134 .join(', ')
135}
136
5c39adb7
C
137// ---------------------------------------------------------------------------
138
65fcc311 139export {
7ad9b984 140 buildBlockedAccountSQL,
06215f15 141 SortType,
792dbaf0 142 getSort,
9a629c6e 143 getVideoSort,
3fd3ab2d 144 getSortOnModel,
57c36b27
C
145 createSimilarityAttribute,
146 throwIfNotValid,
418d092a
C
147 buildServerIdsFollowedBy,
148 buildTrigramSearchIndex,
9f79ade6 149 buildWhereIdOrUUID,
3acc5084 150 isOutdated,
3caf77d3
C
151 parseAggregateResult,
152 createSafeIn
57c36b27
C
153}
154
155// ---------------------------------------------------------------------------
156
157function searchTrigramNormalizeValue (value: string) {
2cebd797 158 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
57c36b27
C
159}
160
161function searchTrigramNormalizeCol (col: string) {
162 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
65fcc311 163}
9a629c6e
C
164
165function buildDirectionAndField (value: string) {
1735c825 166 let field: string
9a629c6e
C
167 let direction: 'ASC' | 'DESC'
168
169 if (value.substring(0, 1) === '-') {
170 direction = 'DESC'
171 field = value.substring(1)
172 } else {
173 direction = 'ASC'
174 field = value
175 }
176
177 return { direction, field }
178}