]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/helpers/youtube-dl.ts
Add subscriptions endpoints to REST API
[github/Chocobozzz/PeerTube.git] / server / helpers / youtube-dl.ts
index ff1fbf59fe1eb422f4424699c75df8f9819ef994..0afc54fd24d5e22823c882b51f48a345e12ac09c 100644 (file)
@@ -1,24 +1,24 @@
-import * as youtubeDL from 'youtube-dl'
 import { truncate } from 'lodash'
-import { CONFIG, CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } from '../initializers'
-import { join } from 'path'
-import * as crypto from 'crypto'
+import { CONSTRAINTS_FIELDS, VIDEO_CATEGORIES } from '../initializers'
 import { logger } from './logger'
+import { generateVideoTmpPath } from './utils'
+import { YoutubeDlUpdateScheduler } from '../lib/schedulers/youtube-dl-update-scheduler'
 
 export type YoutubeDLInfo = {
-  name: string
-  description: string
-  category: number
-  licence: number
-  nsfw: boolean
-  tags: string[]
-  thumbnailUrl: string
+  name?: string
+  description?: string
+  category?: number
+  licence?: number
+  nsfw?: boolean
+  tags?: string[]
+  thumbnailUrl?: string
 }
 
 function getYoutubeDLInfo (url: string): Promise<YoutubeDLInfo> {
-  return new Promise<YoutubeDLInfo>((res, rej) => {
+  return new Promise<YoutubeDLInfo>(async (res, rej) => {
     const options = [ '-j', '--flat-playlist' ]
 
+    const youtubeDL = await safeGetYoutubeDL()
     youtubeDL.getInfo(url, options, (err, info) => {
       if (err) return rej(err)
 
@@ -30,14 +30,14 @@ function getYoutubeDLInfo (url: string): Promise<YoutubeDLInfo> {
 }
 
 function downloadYoutubeDLVideo (url: string) {
-  const hash = crypto.createHash('sha256').update(url).digest('hex')
-  const path = join(CONFIG.STORAGE.VIDEOS_DIR, hash + '-import.mp4')
+  const path = generateVideoTmpPath(url)
 
-  logger.info('Importing video %s', url)
+  logger.info('Importing youtubeDL video %s', url)
 
   const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
 
-  return new Promise<string>((res, rej) => {
+  return new Promise<string>(async (res, rej) => {
+    const youtubeDL = await safeGetYoutubeDL()
     youtubeDL.exec(url, options, async (err, output) => {
       if (err) return rej(err)
 
@@ -55,6 +55,20 @@ export {
 
 // ---------------------------------------------------------------------------
 
+async function safeGetYoutubeDL () {
+  let youtubeDL
+
+  try {
+    youtubeDL = require('youtube-dl')
+  } catch (e) {
+    // Download binary
+    await YoutubeDlUpdateScheduler.Instance.execute()
+    youtubeDL = require('youtube-dl')
+  }
+
+  return youtubeDL
+}
+
 function normalizeObject (obj: any) {
   const newObj: any = {}
 
@@ -120,7 +134,7 @@ function getTags (tags: any) {
 function getLicence (licence: string) {
   if (!licence) return undefined
 
-  if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
+  if (licence.indexOf('Creative Commons Attribution') !== -1) return 1
 
   return undefined
 }