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'
9 const lTags = loggerTagsFactory('live')
11 class LiveSegmentShaStore {
13 private readonly segmentsSha256 = new Map<string, string>()
15 private readonly videoUUID: string
16 private readonly sha256Path: string
17 private readonly streamingPlaylist: MStreamingPlaylistVideo
18 private readonly sendToObjectStorage: boolean
20 constructor (options: {
23 streamingPlaylist: MStreamingPlaylistVideo
24 sendToObjectStorage: boolean
26 this.videoUUID = options.videoUUID
27 this.sha256Path = options.sha256Path
28 this.streamingPlaylist = options.streamingPlaylist
29 this.sendToObjectStorage = options.sendToObjectStorage
32 async addSegmentSha (segmentPath: string) {
33 logger.debug('Adding live sha segment %s.', segmentPath, lTags(this.videoUUID))
35 const shaResult = await buildSha256Segment(segmentPath)
37 const segmentName = basename(segmentPath)
38 this.segmentsSha256.set(segmentName, shaResult)
40 await this.writeToDisk()
43 async removeSegmentSha (segmentPath: string) {
44 const segmentName = basename(segmentPath)
46 logger.debug('Removing live sha segment %s.', segmentPath, lTags(this.videoUUID))
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))
53 this.segmentsSha256.delete(segmentName)
55 await this.writeToDisk()
58 private async writeToDisk () {
59 await writeJson(this.sha256Path, mapToJSON(this.segmentsSha256))
61 if (this.sendToObjectStorage) {
62 const url = await storeHLSFileFromPath(this.streamingPlaylist, this.sha256Path)
64 if (this.streamingPlaylist.segmentsSha256Url !== url) {
65 this.streamingPlaylist.segmentsSha256Url = url
66 await this.streamingPlaylist.save()