]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/utils.ts
Fix notification tests
[github/Chocobozzz/PeerTube.git] / server / models / utils.ts
1 import { Sequelize } from 'sequelize-typescript'
2 import * as validator from 'validator'
3 import { ACTIVITY_PUB } from '../initializers'
4
5 type SortType = { sortModel: any, sortValue: string }
6
7 // Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
8 function getSort (value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
9 let { direction, field } = buildDirectionAndField(value)
10
11 if (field.toLowerCase() === 'match') { // Search
12 field = Sequelize.col('similarity')
13 }
14
15 return [ [ field, direction ], lastSort ]
16 }
17
18 function getVideoSort (value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
19 let { direction, field } = buildDirectionAndField(value)
20
21 // Alias
22 if (field.toLowerCase() === 'match') { // Search
23 field = Sequelize.col('similarity')
24 } else if (field.toLowerCase() === 'trending') { // Sort by aggregation
25 return [
26 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
27
28 [ Sequelize.col('VideoModel.views'), direction ],
29
30 lastSort
31 ]
32 }
33
34 const firstSort = typeof field === 'string' ?
35 field.split('.').concat([ direction ]) :
36 [ field, direction ]
37
38 return [ firstSort, lastSort ]
39 }
40
41 function getSortOnModel (model: any, value: string, lastSort: string[] = [ 'id', 'ASC' ]) {
42 let [ firstSort ] = getSort(value)
43
44 if (model) return [ [ model, firstSort[0], firstSort[1] ], lastSort ]
45 return [ firstSort, lastSort ]
46 }
47
48 function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
49 const now = Date.now()
50 const createdAtTime = model.createdAt.getTime()
51 const updatedAtTime = model.updatedAt.getTime()
52
53 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
54 }
55
56 function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value') {
57 if (validator(value) === false) {
58 throw new Error(`"${value}" is not a valid ${fieldName}.`)
59 }
60 }
61
62 function buildTrigramSearchIndex (indexName: string, attribute: string) {
63 return {
64 name: indexName,
65 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
66 using: 'gin',
67 operator: 'gin_trgm_ops'
68 }
69 }
70
71 function createSimilarityAttribute (col: string, value: string) {
72 return Sequelize.fn(
73 'similarity',
74
75 searchTrigramNormalizeCol(col),
76
77 searchTrigramNormalizeValue(value)
78 )
79 }
80
81 function buildBlockedAccountSQL (serverAccountId: number, userAccountId?: number) {
82 const blockerIds = [ serverAccountId ]
83 if (userAccountId) blockerIds.push(userAccountId)
84
85 const blockerIdsString = blockerIds.join(', ')
86
87 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
88 ' UNION ALL ' +
89 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
90 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
91 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
92 }
93
94 function buildServerIdsFollowedBy (actorId: any) {
95 const actorIdNumber = parseInt(actorId + '', 10)
96
97 return '(' +
98 'SELECT "actor"."serverId" FROM "actorFollow" ' +
99 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
100 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
101 ')'
102 }
103
104 function buildWhereIdOrUUID (id: number | string) {
105 return validator.isInt('' + id) ? { id } : { uuid: id }
106 }
107
108 // ---------------------------------------------------------------------------
109
110 export {
111 buildBlockedAccountSQL,
112 SortType,
113 getSort,
114 getVideoSort,
115 getSortOnModel,
116 createSimilarityAttribute,
117 throwIfNotValid,
118 buildServerIdsFollowedBy,
119 buildTrigramSearchIndex,
120 buildWhereIdOrUUID,
121 isOutdated
122 }
123
124 // ---------------------------------------------------------------------------
125
126 function searchTrigramNormalizeValue (value: string) {
127 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
128 }
129
130 function searchTrigramNormalizeCol (col: string) {
131 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
132 }
133
134 function buildDirectionAndField (value: string) {
135 let field: any
136 let direction: 'ASC' | 'DESC'
137
138 if (value.substring(0, 1) === '-') {
139 direction = 'DESC'
140 field = value.substring(1)
141 } else {
142 direction = 'ASC'
143 field = value
144 }
145
146 return { direction, field }
147 }