ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

71 lines
2.0 KiB

  1. import { remove } from 'fs-extra/esm'
  2. import { Instance as ParseTorrent } from 'parse-torrent'
  3. import { join } from 'path'
  4. import { sha256 } from '@peertube/peertube-node-utils'
  5. import { ResultList } from '@peertube/peertube-models'
  6. import { CONFIG } from '../initializers/config.js'
  7. import { randomBytesPromise } from './core-utils.js'
  8. import { logger } from './logger.js'
  9. function deleteFileAndCatch (path: string) {
  10. remove(path)
  11. .catch(err => logger.error('Cannot delete the file %s asynchronously.', path, { err }))
  12. }
  13. async function generateRandomString (size: number) {
  14. const raw = await randomBytesPromise(size)
  15. return raw.toString('hex')
  16. }
  17. interface FormattableToJSON<U, V> {
  18. toFormattedJSON (args?: U): V
  19. }
  20. function getFormattedObjects<U, V, T extends FormattableToJSON<U, V>> (objects: T[], objectsTotal: number, formattedArg?: U) {
  21. const formattedObjects = objects.map(o => o.toFormattedJSON(formattedArg))
  22. return {
  23. total: objectsTotal,
  24. data: formattedObjects
  25. } as ResultList<V>
  26. }
  27. function generateVideoImportTmpPath (target: string | ParseTorrent, extension = '.mp4') {
  28. const id = typeof target === 'string'
  29. ? target
  30. : target.infoHash
  31. const hash = sha256(id)
  32. return join(CONFIG.STORAGE.TMP_DIR, `${hash}-import${extension}`)
  33. }
  34. function getSecureTorrentName (originalName: string) {
  35. return sha256(originalName) + '.torrent'
  36. }
  37. /**
  38. * From a filename like "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3.mp4", returns
  39. * only the "ede4cba5-742b-46fa-a388-9a6eb3a3aeb3" part. If the filename does
  40. * not contain a UUID, returns null.
  41. */
  42. function getUUIDFromFilename (filename: string) {
  43. const regex = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/
  44. const result = filename.match(regex)
  45. if (!result || Array.isArray(result) === false) return null
  46. return result[0]
  47. }
  48. // ---------------------------------------------------------------------------
  49. export {
  50. deleteFileAndCatch,
  51. generateRandomString,
  52. getFormattedObjects,
  53. getSecureTorrentName,
  54. generateVideoImportTmpPath,
  55. getUUIDFromFilename
  56. }