]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/activitypub/cache-file.ts
Upsert cache file on create activity
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / cache-file.ts
CommitLineData
c48e82b5
C
1import { CacheFileObject } from '../../../shared/index'
2import { VideoModel } from '../../models/video/video'
c48e82b5 3import { VideoRedundancyModel } from '../../models/redundancy/video-redundancy'
e5565833 4import { Transaction } from 'sequelize'
c48e82b5 5
e587e0ec 6function cacheFileActivityObjectToDBAttributes (cacheFileObject: CacheFileObject, video: VideoModel, byActor: { id?: number }) {
c48e82b5
C
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
b88a4596
C
25async function createOrUpdateCacheFile (cacheFileObject: CacheFileObject, video: VideoModel, byActor: { id?: number }, t: Transaction) {
26 const redundancyModel = await VideoRedundancyModel.loadByUrl(cacheFileObject.id, t)
27
28 if (!redundancyModel) {
29 await createCacheFile(cacheFileObject, video, byActor, t)
30 } else {
31 await updateCacheFile(cacheFileObject, redundancyModel, video, byActor, t)
32 }
33}
34
e5565833
C
35function createCacheFile (cacheFileObject: CacheFileObject, video: VideoModel, byActor: { id?: number }, t: Transaction) {
36 const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
c48e82b5 37
e5565833 38 return VideoRedundancyModel.create(attributes, { transaction: t })
c48e82b5
C
39}
40
e5565833
C
41function updateCacheFile (
42 cacheFileObject: CacheFileObject,
43 redundancyModel: VideoRedundancyModel,
44 video: VideoModel,
45 byActor: { id?: number },
46 t: Transaction
47) {
12ba460e
C
48 if (redundancyModel.actorId !== byActor.id) {
49 throw new Error('Cannot update redundancy ' + redundancyModel.url + ' of another actor.')
50 }
51
e5565833 52 const attributes = cacheFileActivityObjectToDBAttributes(cacheFileObject, video, byActor)
c48e82b5
C
53
54 redundancyModel.set('expires', attributes.expiresOn)
55 redundancyModel.set('fileUrl', attributes.fileUrl)
56
e5565833 57 return redundancyModel.save({ transaction: t })
c48e82b5
C
58}
59
60export {
b88a4596 61 createOrUpdateCacheFile,
c48e82b5
C
62 createCacheFile,
63 updateCacheFile,
64 cacheFileActivityObjectToDBAttributes
65}