aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/live/live-utils.ts
blob: 6365e23db371892b4b14601606587bdefe534eb6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { pathExists, readdir, remove } from 'fs-extra'
import { basename, join } from 'path'
import { logger } from '@server/helpers/logger'
import { MStreamingPlaylist, MVideo } from '@server/types/models'
import { getLiveDirectory } from '../paths'

function buildConcatenatedName (segmentOrPlaylistPath: string) {
  const num = basename(segmentOrPlaylistPath).match(/^(\d+)(-|\.)/)

  return 'concat-' + num[1] + '.ts'
}

async function cleanupPermanentLive (video: MVideo, streamingPlaylist?: MStreamingPlaylist) {
  const hlsDirectory = getLiveDirectory(video)

  await cleanupTMPLiveFiles(hlsDirectory)

  if (streamingPlaylist) await streamingPlaylist.destroy()
}

async function cleanupNormalLive (video: MVideo, streamingPlaylist?: MStreamingPlaylist) {
  const hlsDirectory = getLiveDirectory(video)

  await remove(hlsDirectory)

  if (streamingPlaylist) await streamingPlaylist.destroy()
}

async function cleanupTMPLiveFiles (hlsDirectory: string) {
  if (!await pathExists(hlsDirectory)) return

  const files = await readdir(hlsDirectory)

  for (const filename of files) {
    if (
      filename.endsWith('.ts') ||
      filename.endsWith('.m3u8') ||
      filename.endsWith('.mpd') ||
      filename.endsWith('.m4s') ||
      filename.endsWith('.tmp')
    ) {
      const p = join(hlsDirectory, filename)

      remove(p)
        .catch(err => logger.error('Cannot remove %s.', p, { err }))
    }
  }
}

export {
  cleanupPermanentLive,
  cleanupNormalLive,
  cleanupTMPLiveFiles,
  buildConcatenatedName
}