]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/helpers/utils.ts
Add torrent tests
[github/Chocobozzz/PeerTube.git] / server / helpers / utils.ts
index cfb4275703280bd87e8a968b19b7f49a4ca46b46..eaad555553527b98549e69580203f0357063b0ee 100644 (file)
@@ -6,11 +6,37 @@ import { CONFIG } from '../initializers'
 import { UserModel } from '../models/account/user'
 import { ActorModel } from '../models/activitypub/actor'
 import { ApplicationModel } from '../models/application/application'
-import { pseudoRandomBytesPromise } from './core-utils'
+import { pseudoRandomBytesPromise, sha256, unlinkPromise } from './core-utils'
 import { logger } from './logger'
+import { isArray } from './custom-validators/misc'
+import { join } from 'path'
+import { Instance as ParseTorrent } from 'parse-torrent'
 
 const isCidr = require('is-cidr')
 
+function cleanUpReqFiles (req: { files: { [ fieldname: string ]: Express.Multer.File[] } | Express.Multer.File[] }) {
+  const files = req.files
+
+  if (!files) return
+
+  if (isArray(files)) {
+    (files as Express.Multer.File[]).forEach(f => deleteFileAsync(f.path))
+    return
+  }
+
+  for (const key of Object.keys(files)) {
+    const file = files[key]
+
+    if (isArray(file)) file.forEach(f => deleteFileAsync(f.path))
+    else deleteFileAsync(file.path)
+  }
+}
+
+function deleteFileAsync (path: string) {
+  unlinkPromise(path)
+    .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
+}
+
 async function generateRandomString (size: number) {
   const raw = await pseudoRandomBytesPromise(size)
 
@@ -157,17 +183,32 @@ async function getServerActor () {
   return Promise.resolve(serverActor)
 }
 
+function generateVideoTmpPath (target: string | ParseTorrent) {
+  const id = typeof target === 'string' ? target : target.infoHash
+
+  const hash = sha256(id)
+  return join(CONFIG.STORAGE.VIDEOS_DIR, hash + '-import.mp4')
+}
+
+function getSecureTorrentName (originalName: string) {
+  return sha256(originalName) + '.torrent'
+}
+
 type SortType = { sortModel: any, sortValue: string }
 
 // ---------------------------------------------------------------------------
 
 export {
+  cleanUpReqFiles,
+  deleteFileAsync,
   generateRandomString,
   getFormattedObjects,
   isSignupAllowed,
+  getSecureTorrentName,
   isSignupAllowedForCurrentIP,
   computeResolutionsToTranscode,
   resetSequelizeInstance,
   getServerActor,
-  SortType
+  SortType,
+  generateVideoTmpPath
 }