]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/redundancy/video-redundancy.ts
Increase timeout on upload endpoint
[github/Chocobozzz/PeerTube.git] / server / models / redundancy / video-redundancy.ts
CommitLineData
c48e82b5
C
1import {
2 AfterDestroy,
3 AllowNull,
4 BelongsTo,
5 Column,
6 CreatedAt,
7 DataType,
8 ForeignKey,
9 Is,
10 Model,
11 Scopes,
c48e82b5
C
12 Table,
13 UpdatedAt
14} from 'sequelize-typescript'
15import { ActorModel } from '../activitypub/actor'
b36f41ca 16import { getVideoSort, throwIfNotValid } from '../utils'
c48e82b5 17import { isActivityPubUrlValid, isUrlValid } from '../../helpers/custom-validators/activitypub/misc'
b36f41ca 18import { CONFIG, CONSTRAINTS_FIELDS, VIDEO_EXT_MIMETYPE } from '../../initializers'
c48e82b5 19import { VideoFileModel } from '../video/video-file'
c48e82b5
C
20import { getServerActor } from '../../helpers/utils'
21import { VideoModel } from '../video/video'
22import { VideoRedundancyStrategy } from '../../../shared/models/redundancy'
23import { logger } from '../../helpers/logger'
4a08f669 24import { CacheFileObject, VideoPrivacy } from '../../../shared'
c48e82b5
C
25import { VideoChannelModel } from '../video/video-channel'
26import { ServerModel } from '../server/server'
27import { sample } from 'lodash'
28import { isTestInstance } from '../../helpers/core-utils'
3f6b6a56 29import * as Bluebird from 'bluebird'
e5565833 30import * as Sequelize from 'sequelize'
c48e82b5
C
31
32export enum ScopeNames {
33 WITH_VIDEO = 'WITH_VIDEO'
34}
35
36@Scopes({
37 [ ScopeNames.WITH_VIDEO ]: {
38 include: [
39 {
40 model: () => VideoFileModel,
41 required: true,
42 include: [
43 {
44 model: () => VideoModel,
45 required: true
46 }
47 ]
48 }
49 ]
50 }
51})
52
53@Table({
54 tableName: 'videoRedundancy',
55 indexes: [
56 {
57 fields: [ 'videoFileId' ]
58 },
59 {
60 fields: [ 'actorId' ]
61 },
62 {
63 fields: [ 'url' ],
64 unique: true
65 }
66 ]
67})
68export class VideoRedundancyModel extends Model<VideoRedundancyModel> {
69
70 @CreatedAt
71 createdAt: Date
72
73 @UpdatedAt
74 updatedAt: Date
75
76 @AllowNull(false)
77 @Column
78 expiresOn: Date
79
80 @AllowNull(false)
81 @Is('VideoRedundancyFileUrl', value => throwIfNotValid(value, isUrlValid, 'fileUrl'))
82 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
83 fileUrl: string
84
85 @AllowNull(false)
86 @Is('VideoRedundancyUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
87 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS_REDUNDANCY.URL.max))
88 url: string
89
90 @AllowNull(true)
91 @Column
92 strategy: string // Only used by us
93
94 @ForeignKey(() => VideoFileModel)
95 @Column
96 videoFileId: number
97
98 @BelongsTo(() => VideoFileModel, {
99 foreignKey: {
100 allowNull: false
101 },
102 onDelete: 'cascade'
103 })
104 VideoFile: VideoFileModel
105
106 @ForeignKey(() => ActorModel)
107 @Column
108 actorId: number
109
110 @BelongsTo(() => ActorModel, {
111 foreignKey: {
112 allowNull: false
113 },
114 onDelete: 'cascade'
115 })
116 Actor: ActorModel
117
118 @AfterDestroy
e5565833 119 static removeFile (instance: VideoRedundancyModel) {
c48e82b5
C
120 // Not us
121 if (!instance.strategy) return
122
e5565833 123 logger.info('Removing duplicated video file %s-%s.', instance.VideoFile.Video.uuid, instance.VideoFile.resolution)
c48e82b5
C
124
125 return instance.VideoFile.Video.removeFile(instance.VideoFile)
126 }
127
128 static loadByFileId (videoFileId: number) {
129 const query = {
130 where: {
131 videoFileId
132 }
133 }
134
135 return VideoRedundancyModel.scope(ScopeNames.WITH_VIDEO).findOne(query)
136 }
137
e5565833 138 static loadByUrl (url: string, transaction?: Sequelize.Transaction) {
c48e82b5
C
139 const query = {
140 where: {
141 url
e5565833
C
142 },
143 transaction
c48e82b5
C
144 }
145
146 return VideoRedundancyModel.findOne(query)
147 }
148
5ce1208a
C
149 static async isLocalByVideoUUIDExists (uuid: string) {
150 const actor = await getServerActor()
151
152 const query = {
153 raw: true,
154 attributes: [ 'id' ],
155 where: {
156 actorId: actor.id
157 },
158 include: [
159 {
160 attributes: [ ],
161 model: VideoFileModel,
162 required: true,
163 include: [
164 {
165 attributes: [ ],
166 model: VideoModel,
167 required: true,
168 where: {
169 uuid
170 }
171 }
172 ]
173 }
174 ]
175 }
176
177 return VideoRedundancyModel.findOne(query)
178 .then(r => !!r)
179 }
180
3f6b6a56
C
181 static async getVideoSample (p: Bluebird<VideoModel[]>) {
182 const rows = await p
b36f41ca
C
183 const ids = rows.map(r => r.id)
184 const id = sample(ids)
185
186 return VideoModel.loadWithFile(id, undefined, !isTestInstance())
187 }
188
c48e82b5
C
189 static async findMostViewToDuplicate (randomizedFactor: number) {
190 // On VideoModel!
191 const query = {
b36f41ca 192 attributes: [ 'id', 'views' ],
c48e82b5 193 limit: randomizedFactor,
b36f41ca 194 order: getVideoSort('-views'),
4a08f669
C
195 where: {
196 privacy: VideoPrivacy.PUBLIC
197 },
c48e82b5 198 include: [
b36f41ca
C
199 await VideoRedundancyModel.buildVideoFileForDuplication(),
200 VideoRedundancyModel.buildServerRedundancyInclude()
201 ]
202 }
203
3f6b6a56 204 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
b36f41ca
C
205 }
206
207 static async findTrendingToDuplicate (randomizedFactor: number) {
208 // On VideoModel!
209 const query = {
210 attributes: [ 'id', 'views' ],
211 subQuery: false,
b36f41ca
C
212 group: 'VideoModel.id',
213 limit: randomizedFactor,
214 order: getVideoSort('-trending'),
4a08f669
C
215 where: {
216 privacy: VideoPrivacy.PUBLIC
217 },
b36f41ca
C
218 include: [
219 await VideoRedundancyModel.buildVideoFileForDuplication(),
220 VideoRedundancyModel.buildServerRedundancyInclude(),
221
222 VideoModel.buildTrendingQuery(CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS)
c48e82b5
C
223 ]
224 }
225
3f6b6a56
C
226 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
227 }
228
229 static async findRecentlyAddedToDuplicate (randomizedFactor: number, minViews: number) {
230 // On VideoModel!
231 const query = {
232 attributes: [ 'id', 'publishedAt' ],
3f6b6a56
C
233 limit: randomizedFactor,
234 order: getVideoSort('-publishedAt'),
235 where: {
4a08f669 236 privacy: VideoPrivacy.PUBLIC,
3f6b6a56
C
237 views: {
238 [ Sequelize.Op.gte ]: minViews
239 }
240 },
241 include: [
242 await VideoRedundancyModel.buildVideoFileForDuplication(),
243 VideoRedundancyModel.buildServerRedundancyInclude()
244 ]
245 }
c48e82b5 246
3f6b6a56 247 return VideoRedundancyModel.getVideoSample(VideoModel.unscoped().findAll(query))
c48e82b5
C
248 }
249
e5565833
C
250 static async loadOldestLocalThatAlreadyExpired (strategy: VideoRedundancyStrategy, expiresAfterMs: number) {
251 const expiredDate = new Date()
252 expiredDate.setMilliseconds(expiredDate.getMilliseconds() - expiresAfterMs)
253
254 const actor = await getServerActor()
255
256 const query = {
257 where: {
258 actorId: actor.id,
259 strategy,
260 createdAt: {
261 [ Sequelize.Op.lt ]: expiredDate
262 }
263 }
264 }
265
266 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findOne(query)
267 }
268
3f6b6a56 269 static async getTotalDuplicated (strategy: VideoRedundancyStrategy) {
c48e82b5
C
270 const actor = await getServerActor()
271
3f6b6a56 272 const options = {
3f6b6a56
C
273 include: [
274 {
275 attributes: [],
276 model: VideoRedundancyModel,
277 required: true,
278 where: {
279 actorId: actor.id,
280 strategy
281 }
282 }
283 ]
c48e82b5
C
284 }
285
e5565833 286 return VideoFileModel.sum('size', options as any) // FIXME: typings
c48e82b5
C
287 }
288
e5565833
C
289 static async listLocalExpired () {
290 const actor = await getServerActor()
291
292 const query = {
293 where: {
294 actorId: actor.id,
295 expiresOn: {
296 [ Sequelize.Op.lt ]: new Date()
297 }
298 }
299 }
300
301 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
302 }
303
304 static async listRemoteExpired () {
305 const actor = await getServerActor()
306
c48e82b5 307 const query = {
c48e82b5 308 where: {
e5565833
C
309 actorId: {
310 [Sequelize.Op.ne]: actor.id
311 },
c48e82b5 312 expiresOn: {
b36f41ca 313 [ Sequelize.Op.lt ]: new Date()
c48e82b5
C
314 }
315 }
316 }
317
e5565833 318 return VideoRedundancyModel.scope([ ScopeNames.WITH_VIDEO ]).findAll(query)
c48e82b5
C
319 }
320
161b061d
C
321 static async listLocalOfServer (serverId: number) {
322 const actor = await getServerActor()
323
324 const query = {
325 where: {
326 actorId: actor.id
327 },
328 include: [
329 {
330 model: VideoFileModel,
331 required: true,
332 include: [
333 {
334 model: VideoModel,
335 required: true,
336 include: [
337 {
338 attributes: [],
339 model: VideoChannelModel.unscoped(),
340 required: true,
341 include: [
342 {
343 attributes: [],
344 model: ActorModel.unscoped(),
345 required: true,
346 where: {
347 serverId
348 }
349 }
350 ]
351 }
352 ]
353 }
354 ]
355 }
356 ]
357 }
358
359 return VideoRedundancyModel.findAll(query)
360 }
361
4b5384f6
C
362 static async getStats (strategy: VideoRedundancyStrategy) {
363 const actor = await getServerActor()
364
365 const query = {
366 raw: true,
367 attributes: [
368 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoFile.size')), '0'), 'totalUsed' ],
ebdb6124
C
369 [ Sequelize.fn('COUNT', Sequelize.fn('DISTINCT', Sequelize.col('videoId'))), 'totalVideos' ],
370 [ Sequelize.fn('COUNT', Sequelize.col('videoFileId')), 'totalVideoFiles' ]
4b5384f6
C
371 ],
372 where: {
373 strategy,
374 actorId: actor.id
375 },
376 include: [
377 {
378 attributes: [],
379 model: VideoFileModel,
380 required: true
381 }
382 ]
383 }
384
385 return VideoRedundancyModel.find(query as any) // FIXME: typings
386 .then((r: any) => ({
387 totalUsed: parseInt(r.totalUsed.toString(), 10),
388 totalVideos: r.totalVideos,
389 totalVideoFiles: r.totalVideoFiles
390 }))
391 }
392
c48e82b5
C
393 toActivityPubObject (): CacheFileObject {
394 return {
395 id: this.url,
396 type: 'CacheFile' as 'CacheFile',
397 object: this.VideoFile.Video.url,
398 expires: this.expiresOn.toISOString(),
399 url: {
400 type: 'Link',
401 mimeType: VIDEO_EXT_MIMETYPE[ this.VideoFile.extname ] as any,
402 href: this.fileUrl,
403 height: this.VideoFile.resolution,
404 size: this.VideoFile.size,
405 fps: this.VideoFile.fps
406 }
407 }
408 }
409
b36f41ca
C
410 // Don't include video files we already duplicated
411 private static async buildVideoFileForDuplication () {
c48e82b5
C
412 const actor = await getServerActor()
413
b36f41ca 414 const notIn = Sequelize.literal(
c48e82b5 415 '(' +
e5565833 416 `SELECT "videoFileId" FROM "videoRedundancy" WHERE "actorId" = ${actor.id}` +
c48e82b5
C
417 ')'
418 )
b36f41ca
C
419
420 return {
421 attributes: [],
422 model: VideoFileModel.unscoped(),
423 required: true,
424 where: {
425 id: {
426 [ Sequelize.Op.notIn ]: notIn
427 }
428 }
429 }
430 }
431
432 private static buildServerRedundancyInclude () {
433 return {
434 attributes: [],
435 model: VideoChannelModel.unscoped(),
436 required: true,
437 include: [
438 {
439 attributes: [],
440 model: ActorModel.unscoped(),
441 required: true,
442 include: [
443 {
444 attributes: [],
445 model: ServerModel.unscoped(),
446 required: true,
447 where: {
448 redundancyAllowed: true
449 }
450 }
451 ]
452 }
453 ]
454 }
c48e82b5
C
455 }
456}