]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/live/live-segment-sha-store.ts
Merge branch 'release/4.3.0' into develop
[github/Chocobozzz/PeerTube.git] / server / lib / live / live-segment-sha-store.ts
1 import { writeJson } from 'fs-extra'
2 import { basename } from 'path'
3 import { mapToJSON } from '@server/helpers/core-utils'
4 import { logger, loggerTagsFactory } from '@server/helpers/logger'
5 import { MStreamingPlaylistVideo } from '@server/types/models'
6 import { buildSha256Segment } from '../hls'
7 import { storeHLSFileFromPath } from '../object-storage'
8
9 const lTags = loggerTagsFactory('live')
10
11 class LiveSegmentShaStore {
12
13 private readonly segmentsSha256 = new Map<string, string>()
14
15 private readonly videoUUID: string
16 private readonly sha256Path: string
17 private readonly streamingPlaylist: MStreamingPlaylistVideo
18 private readonly sendToObjectStorage: boolean
19
20 constructor (options: {
21 videoUUID: string
22 sha256Path: string
23 streamingPlaylist: MStreamingPlaylistVideo
24 sendToObjectStorage: boolean
25 }) {
26 this.videoUUID = options.videoUUID
27 this.sha256Path = options.sha256Path
28 this.streamingPlaylist = options.streamingPlaylist
29 this.sendToObjectStorage = options.sendToObjectStorage
30 }
31
32 async addSegmentSha (segmentPath: string) {
33 logger.debug('Adding live sha segment %s.', segmentPath, lTags(this.videoUUID))
34
35 const shaResult = await buildSha256Segment(segmentPath)
36
37 const segmentName = basename(segmentPath)
38 this.segmentsSha256.set(segmentName, shaResult)
39
40 await this.writeToDisk()
41 }
42
43 async removeSegmentSha (segmentPath: string) {
44 const segmentName = basename(segmentPath)
45
46 logger.debug('Removing live sha segment %s.', segmentPath, lTags(this.videoUUID))
47
48 if (!this.segmentsSha256.has(segmentName)) {
49 logger.warn('Unknown segment in files map for video %s and segment %s.', this.videoUUID, segmentPath, lTags(this.videoUUID))
50 return
51 }
52
53 this.segmentsSha256.delete(segmentName)
54
55 await this.writeToDisk()
56 }
57
58 private async writeToDisk () {
59 await writeJson(this.sha256Path, mapToJSON(this.segmentsSha256))
60
61 if (this.sendToObjectStorage) {
62 const url = await storeHLSFileFromPath(this.streamingPlaylist, this.sha256Path)
63
64 if (this.streamingPlaylist.segmentsSha256Url !== url) {
65 this.streamingPlaylist.segmentsSha256Url = url
66 await this.streamingPlaylist.save()
67 }
68 }
69 }
70
71 }
72
73 export {
74 LiveSegmentShaStore
75 }