1 import { Transaction } from 'sequelize'
2 import { MActorId, MVideoRedundancy, MVideoWithAllFiles } from '@server/types/models'
3 import { CacheFileObject, VideoStreamingPlaylistType } from '@shared/models'
4 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
6 async function createOrUpdateCacheFile (cacheFileObject: CacheFileObject, video: MVideoWithAllFiles, byActor: MActorId, t: Transaction) {
7 const redundancyModel = await VideoRedundancyModel.loadByUrl(cacheFileObject.id, t)
10 return updateCacheFile(cacheFileObject, redundancyModel, video, byActor, t)
13 return createCacheFile(cacheFileObject, video, byActor, t)
16 // ---------------------------------------------------------------------------
19 createOrUpdateCacheFile
22 // ---------------------------------------------------------------------------
24 function createCacheFile (cacheFileObject: CacheFileObject, video: MVideoWithAllFiles, byActor: MActorId, t: Transaction) {
25 const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
27 return VideoRedundancyModel.create(attributes, { transaction: t })
30 function updateCacheFile (
31 cacheFileObject: CacheFileObject,
32 redundancyModel: MVideoRedundancy,
33 video: MVideoWithAllFiles,
37 if (redundancyModel.actorId !== byActor.id) {
38 throw new Error('Cannot update redundancy ' + redundancyModel.url + ' of another actor.')
41 const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
43 redundancyModel.expiresOn = attributes.expiresOn
44 redundancyModel.fileUrl = attributes.fileUrl
46 return redundancyModel.save({ transaction: t })
49 function cacheFileActivityObjectToDBAttributes (cacheFileObject: CacheFileObject, video: MVideoWithAllFiles, byActor: MActorId) {
51 if (cacheFileObject.url.mediaType === 'application/x-mpegURL') {
52 const url = cacheFileObject.url
54 const playlist = video.VideoStreamingPlaylists.find(t => t.type === VideoStreamingPlaylistType.HLS)
55 if (!playlist) throw new Error('Cannot find HLS playlist of video ' + video.url)
58 expiresOn: cacheFileObject.expires ? new Date(cacheFileObject.expires) : null,
59 url: cacheFileObject.id,
62 videoStreamingPlaylistId: playlist.id,
67 const url = cacheFileObject.url
68 const videoFile = video.VideoFiles.find(f => {
69 return f.resolution === url.height && f.fps === url.fps
72 if (!videoFile) throw new Error(`Cannot find video file ${url.height} ${url.fps} of video ${video.url}`)
75 expiresOn: cacheFileObject.expires ? new Date(cacheFileObject.expires) : null,
76 url: cacheFileObject.id,
79 videoFileId: videoFile.id,