1 import { CacheFileObject } from '../../../shared/index'
2 import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
3 import { Transaction } from 'sequelize'
4 import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type'
5 import { MActorId, MVideoRedundancy, MVideoWithAllFiles } from '@server/types/models'
7 function cacheFileActivityObjectToDBAttributes (cacheFileObject: CacheFileObject, video: MVideoWithAllFiles, byActor: MActorId) {
9 if (cacheFileObject.url.mediaType === 'application/x-mpegURL') {
10 const url = cacheFileObject.url
12 const playlist = video.VideoStreamingPlaylists.find(t => t.type === VideoStreamingPlaylistType.HLS)
13 if (!playlist) throw new Error('Cannot find HLS playlist of video ' + video.url)
16 expiresOn: cacheFileObject.expires ? new Date(cacheFileObject.expires) : null,
17 url: cacheFileObject.id,
20 videoStreamingPlaylistId: playlist.id,
25 const url = cacheFileObject.url
26 const videoFile = video.VideoFiles.find(f => {
27 return f.resolution === url.height && f.fps === url.fps
30 if (!videoFile) throw new Error(`Cannot find video file ${url.height} ${url.fps} of video ${video.url}`)
33 expiresOn: cacheFileObject.expires ? new Date(cacheFileObject.expires) : null,
34 url: cacheFileObject.id,
37 videoFileId: videoFile.id,
42 async function createOrUpdateCacheFile (cacheFileObject: CacheFileObject, video: MVideoWithAllFiles, byActor: MActorId, t: Transaction) {
43 const redundancyModel = await VideoRedundancyModel.loadByUrl(cacheFileObject.id, t)
45 if (!redundancyModel) {
46 await createCacheFile(cacheFileObject, video, byActor, t)
48 await updateCacheFile(cacheFileObject, redundancyModel, video, byActor, t)
52 function createCacheFile (cacheFileObject: CacheFileObject, video: MVideoWithAllFiles, byActor: MActorId, t: Transaction) {
53 const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
55 return VideoRedundancyModel.create(attributes, { transaction: t })
58 function updateCacheFile (
59 cacheFileObject: CacheFileObject,
60 redundancyModel: MVideoRedundancy,
61 video: MVideoWithAllFiles,
65 if (redundancyModel.actorId !== byActor.id) {
66 throw new Error('Cannot update redundancy ' + redundancyModel.url + ' of another actor.')
69 const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
71 redundancyModel.expiresOn = attributes.expiresOn
72 redundancyModel.fileUrl = attributes.fileUrl
74 return redundancyModel.save({ transaction: t })
78 createOrUpdateCacheFile,
81 cacheFileActivityObjectToDBAttributes