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'
6 function cacheFileActivityObjectToDBAttributes (cacheFileObject: CacheFileObject, video: VideoModel, byActor: { id?: number }) {
7 const url = cacheFileObject.url
9 const videoFile = video.VideoFiles.find(f => {
10 return f.resolution === url.height && f.fps === url.fps
13 if (!videoFile) throw new Error(`Cannot find video file ${url.height} ${url.fps} of video ${video.url}`)
16 expiresOn: new Date(cacheFileObject.expires),
17 url: cacheFileObject.id,
18 fileUrl: cacheFileObject.url.href,
20 videoFileId: videoFile.id,
25 async function createOrUpdateCacheFile (cacheFileObject: CacheFileObject, video: VideoModel, byActor: { id?: number }, t: Transaction) {
26 const redundancyModel = await VideoRedundancyModel.loadByUrl(cacheFileObject.id, t)
28 if (!redundancyModel) {
29 await createCacheFile(cacheFileObject, video, byActor, t)
31 await updateCacheFile(cacheFileObject, redundancyModel, video, byActor, t)
35 function createCacheFile (cacheFileObject: CacheFileObject, video: VideoModel, byActor: { id?: number }, t: Transaction) {
36 const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
38 return VideoRedundancyModel.create(attributes, { transaction: t })
41 function updateCacheFile (
42 cacheFileObject: CacheFileObject,
43 redundancyModel: VideoRedundancyModel,
45 byActor: { id?: number },
48 if (redundancyModel.actorId !== byActor.id) {
49 throw new Error('Cannot update redundancy ' + redundancyModel.url + ' of another actor.')
52 const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
54 redundancyModel.set('expires', attributes.expiresOn)
55 redundancyModel.set('fileUrl', attributes.fileUrl)
57 return redundancyModel.save({ transaction: t })
61 createOrUpdateCacheFile,
64 cacheFileActivityObjectToDBAttributes