1 import { pathExists, readdir, remove } from 'fs-extra'
2 import { basename, join } from 'path'
3 import { logger } from '@server/helpers/logger'
4 import { MStreamingPlaylist, MStreamingPlaylistVideo, MVideo } from '@server/types/models'
5 import { VideoStorage } from '@shared/models'
6 import { listHLSFileKeysOf, removeHLSFileObjectStorage, removeHLSObjectStorage } from '../object-storage'
7 import { getLiveDirectory } from '../paths'
9 function buildConcatenatedName (segmentOrPlaylistPath: string) {
10 const num = basename(segmentOrPlaylistPath).match(/^(\d+)(-|\.)/)
12 return 'concat-' + num[1] + '.ts'
15 async function cleanupAndDestroyPermanentLive (video: MVideo, streamingPlaylist: MStreamingPlaylist) {
16 await cleanupTMPLiveFiles(video, streamingPlaylist)
18 await streamingPlaylist.destroy()
21 async function cleanupUnsavedNormalLive (video: MVideo, streamingPlaylist: MStreamingPlaylist) {
22 const hlsDirectory = getLiveDirectory(video)
24 // We uploaded files to object storage too, remove them
25 if (streamingPlaylist.storage === VideoStorage.OBJECT_STORAGE) {
26 await removeHLSObjectStorage(streamingPlaylist.withVideo(video))
29 await remove(hlsDirectory)
31 await streamingPlaylist.destroy()
34 async function cleanupTMPLiveFiles (video: MVideo, streamingPlaylist: MStreamingPlaylist) {
35 await cleanupTMPLiveFilesFromObjectStorage(streamingPlaylist.withVideo(video))
37 await cleanupTMPLiveFilesFromFilesystem(video)
41 cleanupAndDestroyPermanentLive,
42 cleanupUnsavedNormalLive,
47 // ---------------------------------------------------------------------------
49 function isTMPLiveFile (name: string) {
50 return name.endsWith('.ts') ||
51 name.endsWith('.m3u8') ||
52 name.endsWith('.json') ||
53 name.endsWith('.mpd') ||
54 name.endsWith('.m4s') ||
58 async function cleanupTMPLiveFilesFromFilesystem (video: MVideo) {
59 const hlsDirectory = getLiveDirectory(video)
61 if (!await pathExists(hlsDirectory)) return
63 logger.info('Cleanup TMP live files from filesystem of %s.', hlsDirectory)
65 const files = await readdir(hlsDirectory)
67 for (const filename of files) {
68 if (isTMPLiveFile(filename)) {
69 const p = join(hlsDirectory, filename)
72 .catch(err => logger.error('Cannot remove %s.', p, { err }))
77 async function cleanupTMPLiveFilesFromObjectStorage (streamingPlaylist: MStreamingPlaylistVideo) {
78 if (streamingPlaylist.storage !== VideoStorage.OBJECT_STORAGE) return
80 const keys = await listHLSFileKeysOf(streamingPlaylist)
82 for (const key of keys) {
83 if (isTMPLiveFile(key)) {
84 await removeHLSFileObjectStorage(streamingPlaylist, key)