2
1

peertube-import-videos.ts 9.2 KB

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