1 import { Transaction } from 'sequelize'
2 import { MActorId, MVideoRedundancy, MVideoWithAllFiles } from '@server/types/models'
3 import { CacheFileObject } from '../../../shared/index'
4 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
5 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
7 async function createOrUpdateCacheFile (cacheFileObject: CacheFileObject, video: MVideoWithAllFiles, byActor: MActorId, t: Transaction) {
8 const redundancyModel = await VideoRedundancyModel.loadByUrl(cacheFileObject.id, t)
10 if (redundancyModel) {
11 return updateCacheFile(cacheFileObject, redundancyModel, video, byActor, t)
14 return createCacheFile(cacheFileObject, video, byActor, t)
17 // ---------------------------------------------------------------------------
20 createOrUpdateCacheFile
23 // ---------------------------------------------------------------------------
25 function createCacheFile (cacheFileObject: CacheFileObject, video: MVideoWithAllFiles, byActor: MActorId, t: Transaction) {
26 const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
28 return VideoRedundancyModel.create(attributes, { transaction: t })
31 function updateCacheFile (
32 cacheFileObject: CacheFileObject,
33 redundancyModel: MVideoRedundancy,
34 video: MVideoWithAllFiles,
38 if (redundancyModel.actorId !== byActor.id) {
39 throw new Error('Cannot update redundancy ' + redundancyModel.url + ' of another actor.')
42 const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
44 redundancyModel.expiresOn = attributes.expiresOn
45 redundancyModel.fileUrl = attributes.fileUrl
47 return redundancyModel.save({ transaction: t })
50 function cacheFileActivityObjectToDBAttributes (cacheFileObject: CacheFileObject, video: MVideoWithAllFiles, byActor: MActorId) {
52 if (cacheFileObject.url.mediaType === 'application/x-mpegURL') {
53 const url = cacheFileObject.url
55 const playlist = video.VideoStreamingPlaylists.find(t => t.type === VideoStreamingPlaylistType.HLS)
56 if (!playlist) throw new Error('Cannot find HLS playlist of video ' + video.url)
59 expiresOn: cacheFileObject.expires ? new Date(cacheFileObject.expires) : null,
60 url: cacheFileObject.id,
63 videoStreamingPlaylistId: playlist.id,
68 const url = cacheFileObject.url
69 const videoFile = video.VideoFiles.find(f => {
70 return f.resolution === url.height && f.fps === url.fps
73 if (!videoFile) throw new Error(`Cannot find video file ${url.height} ${url.fps} of video ${video.url}`)
76 expiresOn: cacheFileObject.expires ? new Date(cacheFileObject.expires) : null,
77 url: cacheFileObject.id,
80 videoFileId: videoFile.id,