]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/helpers/custom-validators/misc.ts
Resumable video uploads (#3933)
[github/Chocobozzz/PeerTube.git] / server / helpers / custom-validators / misc.ts
index 89149b3e0a0cf91af9d589e0350aec2ddd7436d3..fd3b45804245d955ef8265f24b2985225d5e82d7 100644 (file)
@@ -1,6 +1,7 @@
 import 'multer'
-import validator from 'validator'
+import { UploadFilesForCheck } from 'express'
 import { sep } from 'path'
+import validator from 'validator'
 
 function exists (value: any) {
   return value !== undefined && value !== null
@@ -45,6 +46,10 @@ function isBooleanValid (value: any) {
   return typeof value === 'boolean' || (typeof value === 'string' && validator.isBoolean(value))
 }
 
+function isIntOrNull (value: any) {
+  return value === null || validator.isInt('' + value)
+}
+
 function toIntOrNull (value: string) {
   const v = toValueOrNull(value)
 
@@ -82,6 +87,50 @@ function toIntArray (value: any) {
   return value.map(v => validator.toInt(v))
 }
 
+function isFileFieldValid (
+  files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[],
+  field: string,
+  optional = false
+) {
+  // Should have files
+  if (!files) return optional
+  if (isArray(files)) return optional
+
+  // Should have a file
+  const fileArray = files[field]
+  if (!fileArray || fileArray.length === 0) {
+    return optional
+  }
+
+  // The file should exist
+  const file = fileArray[0]
+  if (!file || !file.originalname) return false
+  return file
+}
+
+function isFileMimeTypeValid (
+  files: UploadFilesForCheck,
+  mimeTypeRegex: string,
+  field: string,
+  optional = false
+) {
+  // Should have files
+  if (!files) return optional
+  if (isArray(files)) return optional
+
+  // Should have a file
+  const fileArray = files[field]
+  if (!fileArray || fileArray.length === 0) {
+    return optional
+  }
+
+  // The file should exist
+  const file = fileArray[0]
+  if (!file || !file.originalname) return false
+
+  return new RegExp(`^${mimeTypeRegex}$`, 'i').test(file.mimetype)
+}
+
 function isFileValid (
   files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[],
   mimeTypeRegex: string,
@@ -94,13 +143,13 @@ function isFileValid (
   if (isArray(files)) return optional
 
   // Should have a file
-  const fileArray = files[ field ]
+  const fileArray = files[field]
   if (!fileArray || fileArray.length === 0) {
     return optional
   }
 
   // The file should exist
-  const file = fileArray[ 0 ]
+  const file = fileArray[0]
   if (!file || !file.originalname) return false
 
   // Check size
@@ -116,6 +165,7 @@ export {
   isArrayOf,
   isNotEmptyIntArray,
   isArray,
+  isIntOrNull,
   isIdValid,
   isSafePath,
   isUUIDValid,
@@ -127,5 +177,7 @@ export {
   toIntOrNull,
   toArray,
   toIntArray,
+  isFileFieldValid,
+  isFileMimeTypeValid,
   isFileValid
 }