Fix redundancy totalVideos stats
[oweals/peertube.git] / server / lib / activitypub / cache-file.ts
1 import { CacheFileObject } from '../../../shared/index'
2 import { VideoModel } from '../../models/video/video'
3 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
4 import { Transaction } from 'sequelize'
5
6 function cacheFileActivityObjectToDBAttributes (cacheFileObject: CacheFileObject, video: VideoModel, byActor: { id?: number }) {
7   const url = cacheFileObject.url
8
9   const videoFile = video.VideoFiles.find(f => {
10     return f.resolution === url.height && f.fps === url.fps
11   })
12
13   if (!videoFile) throw new Error(`Cannot find video file ${url.height} ${url.fps} of video ${video.url}`)
14
15   return {
16     expiresOn: new Date(cacheFileObject.expires),
17     url: cacheFileObject.id,
18     fileUrl: cacheFileObject.url.href,
19     strategy: null,
20     videoFileId: videoFile.id,
21     actorId: byActor.id
22   }
23 }
24
25 function createCacheFile (cacheFileObject: CacheFileObject, video: VideoModel, byActor: { id?: number }, t: Transaction) {
26   const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
27
28   return VideoRedundancyModel.create(attributes, { transaction: t })
29 }
30
31 function updateCacheFile (
32   cacheFileObject: CacheFileObject,
33   redundancyModel: VideoRedundancyModel,
34   video: VideoModel,
35   byActor: { id?: number },
36   t: Transaction
37 ) {
38   if (redundancyModel.actorId !== byActor.id) {
39     throw new Error('Cannot update redundancy ' + redundancyModel.url + ' of another actor.')
40   }
41
42   const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
43
44   redundancyModel.set('expires', attributes.expiresOn)
45   redundancyModel.set('fileUrl', attributes.fileUrl)
46
47   return redundancyModel.save({ transaction: t })
48 }
49
50 export {
51   createCacheFile,
52   updateCacheFile,
53   cacheFileActivityObjectToDBAttributes
54 }