aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/helpers/custom-validators/video-captions.ts
blob: d5b09ea03628a998a921958bb72fec5c20c572b4 (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
import { UploadFilesForCheck } from 'express'
import { readFile } from 'fs-extra'
import { getFileSize } from '@shared/extra-utils'
import { CONSTRAINTS_FIELDS, MIMETYPES, VIDEO_LANGUAGES } from '../../initializers/constants'
import { exists, isFileValid } from './misc'

function isVideoCaptionLanguageValid (value: any) {
  return exists(value) && VIDEO_LANGUAGES[value] !== undefined
}

// MacOS sends application/octet-stream
const videoCaptionTypesRegex = [ ...Object.keys(MIMETYPES.VIDEO_CAPTIONS.MIMETYPE_EXT), 'application/octet-stream' ]
  .map(m => `(${m})`)
  .join('|')

function isVideoCaptionFile (files: UploadFilesForCheck, field: string) {
  return isFileValid({
    files,
    mimeTypeRegex: videoCaptionTypesRegex,
    field,
    maxSize: CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.FILE_SIZE.max
  })
}

async function isVTTFileValid (filePath: string) {
  const size = await getFileSize(filePath)

  if (size > CONSTRAINTS_FIELDS.VIDEO_CAPTIONS.CAPTION_FILE.FILE_SIZE.max) return false

  const content = await readFile(filePath, 'utf8')

  return content?.startsWith('WEBVTT\n')
}

// ---------------------------------------------------------------------------

export {
  isVideoCaptionFile,
  isVTTFileValid,
  isVideoCaptionLanguageValid
}