Fix changelog syntax related to AP url warning
[oweals/peertube.git] / server / tools / import-videos.ts
1 // FIXME: https://github.com/nodejs/node/pull/16853
2 require('tls').DEFAULT_ECDH_CURVE = 'auto'
3
4 import * as program from 'commander'
5 import { join } from 'path'
6 import * as youtubeDL from 'youtube-dl'
7 import { VideoPrivacy } from '../../shared/models/videos'
8 import { unlinkPromise } from '../helpers/core-utils'
9 import { doRequestAndSaveToFile } from '../helpers/requests'
10 import { CONSTRAINTS_FIELDS } from '../initializers'
11 import { getClient, getVideoCategories, login, searchVideo, uploadVideo } from '../tests/utils'
12 import { truncate } from 'lodash'
13 import * as prompt from 'prompt'
14
15 program
16   .option('-u, --url <url>', 'Server url')
17   .option('-U, --username <username>', 'Username')
18   .option('-p, --password <token>', 'Password')
19   .option('-t, --target-url <targetUrl>', 'Video target URL')
20   .option('-l, --language <languageCode>', 'Language ISO 639 code (fr or en...)')
21   .option('-v, --verbose', 'Verbose mode')
22   .parse(process.argv)
23
24 if (
25   !program['url'] ||
26   !program['username'] ||
27   !program['targetUrl']
28 ) {
29   console.error('All arguments are required.')
30   process.exit(-1)
31 }
32
33 const user = {
34   username: program['username'],
35   password: program['password']
36 }
37
38 run().catch(err => console.error(err))
39
40 let accessToken: string
41 let client: { id: string, secret: string }
42
43 const processOptions = {
44   cwd: __dirname,
45   maxBuffer: Infinity
46 }
47
48 async function promptPassword () {
49   return new Promise((res, rej) => {
50     prompt.start()
51     const schema = {
52       properties: {
53         password: {
54           hidden: true,
55           required: true
56         }
57       }
58     }
59     prompt.get(schema, function (err, result) {
60       if (err) {
61         return rej(err)
62       }
63       return res(result.password)
64     })
65   })
66 }
67
68 async function run () {
69   if (!user.password) {
70     user.password = await promptPassword()
71   }
72
73   const res = await getClient(program['url'])
74   client = {
75     id: res.body.client_id,
76     secret: res.body.client_secret
77   }
78
79   const res2 = await login(program['url'], client, user)
80   accessToken = res2.body.access_token
81
82   const options = [ '-j', '--flat-playlist', '--playlist-reverse' ]
83   youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => {
84     if (err) {
85       console.log(err.message)
86       process.exit(1)
87     }
88
89     let infoArray: any[]
90
91     // Normalize utf8 fields
92     if (Array.isArray(info) === true) {
93       infoArray = info.map(i => normalizeObject(i))
94     } else {
95       infoArray = [ normalizeObject(info) ]
96     }
97     console.log('Will download and upload %d videos.\n', infoArray.length)
98
99     for (const info of infoArray) {
100       await processVideo(info, program['language'])
101     }
102
103     // https://www.youtube.com/watch?v=2Upx39TBc1s
104     console.log('I\'m finished!')
105     process.exit(0)
106   })
107 }
108
109 function processVideo (info: any, languageCode: string) {
110   return new Promise(async res => {
111     if (program['verbose']) console.log('Fetching object.', info)
112
113     const videoInfo = await fetchObject(info)
114     if (program['verbose']) console.log('Fetched object.', videoInfo)
115
116     const result = await searchVideo(program['url'], videoInfo.title)
117
118     console.log('############################################################\n')
119
120     if (result.body.data.find(v => v.name === videoInfo.title)) {
121       console.log('Video "%s" already exists, don\'t reupload it.\n', videoInfo.title)
122       return res()
123     }
124
125     const path = join(__dirname, new Date().getTime() + '.mp4')
126
127     console.log('Downloading video "%s"...', videoInfo.title)
128
129     const options = [ '-f', 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best', '-o', path ]
130     try {
131       youtubeDL.exec(videoInfo.url, options, processOptions, async (err, output) => {
132         if (err) {
133           console.error(err)
134           return res()
135         }
136
137         console.log(output.join('\n'))
138         await uploadVideoOnPeerTube(normalizeObject(videoInfo), path, languageCode)
139         return res()
140       })
141     } catch (err) {
142       console.log(err.message)
143       return res()
144     }
145   })
146 }
147
148 async function uploadVideoOnPeerTube (videoInfo: any, videoPath: string, language?: string) {
149   const category = await getCategory(videoInfo.categories)
150   const licence = getLicence(videoInfo.license)
151   let tags = []
152   if (Array.isArray(videoInfo.tags)) {
153     tags = videoInfo.tags
154       .filter(t => t.length < CONSTRAINTS_FIELDS.VIDEOS.TAG.max && t.length > CONSTRAINTS_FIELDS.VIDEOS.TAG.min)
155       .map(t => t.normalize())
156       .slice(0, 5)
157   }
158
159   let thumbnailfile
160   if (videoInfo.thumbnail) {
161     thumbnailfile = join(__dirname, 'thumbnail.jpg')
162
163     await doRequestAndSaveToFile({
164       method: 'GET',
165       uri: videoInfo.thumbnail
166     }, thumbnailfile)
167   }
168
169   const videoAttributes = {
170     name: truncate(videoInfo.title, {
171       'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max,
172       'separator': /,? +/,
173       'omission': ' […]'
174     }),
175     category,
176     licence,
177     language,
178     nsfw: isNSFW(videoInfo),
179     waitTranscoding: true,
180     commentsEnabled: true,
181     description: videoInfo.description || undefined,
182     support: undefined,
183     tags,
184     privacy: VideoPrivacy.PUBLIC,
185     fixture: videoPath,
186     thumbnailfile,
187     previewfile: thumbnailfile
188   }
189
190   console.log('\nUploading on PeerTube video "%s".', videoAttributes.name)
191   try {
192     await uploadVideo(program['url'], accessToken, videoAttributes)
193   } catch (err) {
194     if (err.message.indexOf('401') !== -1) {
195       console.log('Got 401 Unauthorized, token may have expired, renewing token and retry.')
196
197       const res = await login(program['url'], client, user)
198       accessToken = res.body.access_token
199
200       await uploadVideo(program['url'], accessToken, videoAttributes)
201     } else {
202       console.log(err.message)
203       process.exit(1)
204     }
205   }
206
207   await unlinkPromise(videoPath)
208   if (thumbnailfile) {
209     await unlinkPromise(thumbnailfile)
210   }
211
212   console.log('Uploaded video "%s"!\n', videoAttributes.name)
213 }
214
215 async function getCategory (categories: string[]) {
216   if (!categories) return undefined
217
218   const categoryString = categories[0]
219
220   if (categoryString === 'News & Politics') return 11
221
222   const res = await getVideoCategories(program['url'])
223   const categoriesServer = res.body
224
225   for (const key of Object.keys(categoriesServer)) {
226     const categoryServer = categoriesServer[key]
227     if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10)
228   }
229
230   return undefined
231 }
232
233 function getLicence (licence: string) {
234   if (!licence) return undefined
235
236   if (licence.indexOf('Creative Commons Attribution licence') !== -1) return 1
237
238   return undefined
239 }
240
241 function normalizeObject (obj: any) {
242   const newObj: any = {}
243
244   for (const key of Object.keys(obj)) {
245     // Deprecated key
246     if (key === 'resolution') continue
247
248     const value = obj[key]
249
250     if (typeof value === 'string') {
251       newObj[key] = value.normalize()
252     } else {
253       newObj[key] = value
254     }
255   }
256
257   return newObj
258 }
259
260 function fetchObject (info: any) {
261   const url = buildUrl(info)
262
263   return new Promise<any>(async (res, rej) => {
264     youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => {
265       if (err) return rej(err)
266
267       const videoInfoWithUrl = Object.assign(videoInfo, { url })
268       return res(normalizeObject(videoInfoWithUrl))
269     })
270   })
271 }
272
273 function buildUrl (info: any) {
274   const webpageUrl = info.webpage_url as string
275   if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl
276
277   const url = info.url as string
278   if (url && url.match(/^https?:\/\//)) return url
279
280   // It seems youtube-dl does not return the video url
281   return 'https://www.youtube.com/watch?v=' + info.id
282 }
283
284 function isNSFW (info: any) {
285   if (info.age_limit && info.age_limit >= 16) return true
286
287   return false
288 }