Federated video streaming platform using ActivityPub and P2P in the web browser with Angular. https://joinpeertube.org/
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.
 
 
 
 
 
 

344 lines
9.6 KiB

  1. import { program } from 'commander'
  2. import { accessSync, constants } from 'fs'
  3. import { remove } from 'fs-extra'
  4. import { join } from 'path'
  5. import { YoutubeDLCLI, YoutubeDLInfo, YoutubeDLInfoBuilder } from '@server/helpers/youtube-dl'
  6. import { wait } from '@shared/core-utils'
  7. import { sha256 } from '@shared/extra-utils'
  8. import { doRequestAndSaveToFile } from '../helpers/requests'
  9. import {
  10. assignToken,
  11. buildCommonVideoOptions,
  12. buildServer,
  13. buildVideoAttributesFromCommander,
  14. getLogger,
  15. getServerCredentials
  16. } from './cli'
  17. import prompt = require('prompt')
  18. const processOptions = {
  19. maxBuffer: Infinity
  20. }
  21. let command = program
  22. .name('import-videos')
  23. command = buildCommonVideoOptions(command)
  24. command
  25. .option('-u, --url <url>', 'Server url')
  26. .option('-U, --username <username>', 'Username')
  27. .option('-p, --password <token>', 'Password')
  28. .option('--target-url <targetUrl>', 'Video target URL')
  29. .option('--since <since>', 'Publication date (inclusive) since which the videos can be imported (YYYY-MM-DD)', parseDate)
  30. .option('--until <until>', 'Publication date (inclusive) until which the videos can be imported (YYYY-MM-DD)', parseDate)
  31. .option('--first <first>', 'Process first n elements of returned playlist')
  32. .option('--last <last>', 'Process last n elements of returned playlist')
  33. .option('--wait-interval <waitInterval>', 'Duration between two video imports (in seconds)', convertIntoMs)
  34. .option('-T, --tmpdir <tmpdir>', 'Working directory', __dirname)
  35. .usage("[global options] [ -- youtube-dl options]")
  36. .parse(process.argv)
  37. const options = command.opts()
  38. const log = getLogger(options.verbose)
  39. getServerCredentials(command)
  40. .then(({ url, username, password }) => {
  41. if (!options.targetUrl) {
  42. exitError('--target-url field is required.')
  43. }
  44. try {
  45. accessSync(options.tmpdir, constants.R_OK | constants.W_OK)
  46. } catch (e) {
  47. exitError('--tmpdir %s: directory does not exist or is not accessible', options.tmpdir)
  48. }
  49. url = normalizeTargetUrl(url)
  50. options.targetUrl = normalizeTargetUrl(options.targetUrl)
  51. run(url, username, password)
  52. .catch(err => exitError(err))
  53. })
  54. .catch(err => console.error(err))
  55. async function run (url: string, username: string, password: string) {
  56. if (!password) password = await promptPassword()
  57. const youtubeDLBinary = await YoutubeDLCLI.safeGet()
  58. let info = await getYoutubeDLInfo(youtubeDLBinary, options.targetUrl, command.args)
  59. if (!Array.isArray(info)) info = [ info ]
  60. // Try to fix youtube channels upload
  61. const uploadsObject = info.find(i => !i.ie_key && !i.duration && i.title === 'Uploads')
  62. if (uploadsObject) {
  63. console.log('Fixing URL to %s.', uploadsObject.url)
  64. info = await getYoutubeDLInfo(youtubeDLBinary, uploadsObject.url, command.args)
  65. }
  66. let infoArray: any[]
  67. infoArray = [].concat(info)
  68. if (options.first) {
  69. infoArray = infoArray.slice(0, options.first)
  70. } else if (options.last) {
  71. infoArray = infoArray.slice(-options.last)
  72. }
  73. log.info('Will download and upload %d videos.\n', infoArray.length)
  74. let skipInterval = true
  75. for (const [ index, info ] of infoArray.entries()) {
  76. try {
  77. if (index > 0 && options.waitInterval && !skipInterval) {
  78. log.info("Wait for %d seconds before continuing.", options.waitInterval / 1000)
  79. await wait(options.waitInterval)
  80. }
  81. skipInterval = await processVideo({
  82. cwd: options.tmpdir,
  83. url,
  84. username,
  85. password,
  86. youtubeInfo: info
  87. })
  88. } catch (err) {
  89. console.error('Cannot process video.', { info, url, err })
  90. }
  91. }
  92. log.info('Video/s for user %s imported: %s', username, options.targetUrl)
  93. process.exit(0)
  94. }
  95. async function processVideo (parameters: {
  96. cwd: string
  97. url: string
  98. username: string
  99. password: string
  100. youtubeInfo: any
  101. }) {
  102. const { youtubeInfo, cwd, url, username, password } = parameters
  103. log.debug('Fetching object.', youtubeInfo)
  104. const videoInfo = await fetchObject(youtubeInfo)
  105. log.debug('Fetched object.', videoInfo)
  106. if (options.since && videoInfo.originallyPublishedAt && videoInfo.originallyPublishedAt.getTime() < options.since.getTime()) {
  107. log.info('Video "%s" has been published before "%s", don\'t upload it.\n', videoInfo.name, formatDate(options.since))
  108. return true
  109. }
  110. if (options.until && videoInfo.originallyPublishedAt && videoInfo.originallyPublishedAt.getTime() > options.until.getTime()) {
  111. log.info('Video "%s" has been published after "%s", don\'t upload it.\n', videoInfo.name, formatDate(options.until))
  112. return true
  113. }
  114. const server = buildServer(url)
  115. const { data } = await server.search.advancedVideoSearch({
  116. search: {
  117. search: videoInfo.name,
  118. sort: '-match',
  119. searchTarget: 'local'
  120. }
  121. })
  122. log.info('############################################################\n')
  123. if (data.find(v => v.name === videoInfo.name)) {
  124. log.info('Video "%s" already exists, don\'t reupload it.\n', videoInfo.name)
  125. return true
  126. }
  127. const path = join(cwd, sha256(videoInfo.url) + '.mp4')
  128. log.info('Downloading video "%s"...', videoInfo.name)
  129. try {
  130. const youtubeDLBinary = await YoutubeDLCLI.safeGet()
  131. const output = await youtubeDLBinary.download({
  132. url: videoInfo.url,
  133. format: YoutubeDLCLI.getYoutubeDLVideoFormat([]),
  134. output: path,
  135. additionalYoutubeDLArgs: command.args,
  136. processOptions
  137. })
  138. log.info(output.join('\n'))
  139. await uploadVideoOnPeerTube({
  140. cwd,
  141. url,
  142. username,
  143. password,
  144. videoInfo,
  145. videoPath: path
  146. })
  147. } catch (err) {
  148. log.error(err.message)
  149. }
  150. return false
  151. }
  152. async function uploadVideoOnPeerTube (parameters: {
  153. videoInfo: YoutubeDLInfo
  154. videoPath: string
  155. cwd: string
  156. url: string
  157. username: string
  158. password: string
  159. }) {
  160. const { videoInfo, videoPath, cwd, url, username, password } = parameters
  161. const server = buildServer(url)
  162. await assignToken(server, username, password)
  163. let thumbnailfile: string
  164. if (videoInfo.thumbnailUrl) {
  165. thumbnailfile = join(cwd, sha256(videoInfo.thumbnailUrl) + '.jpg')
  166. await doRequestAndSaveToFile(videoInfo.thumbnailUrl, thumbnailfile)
  167. }
  168. const baseAttributes = await buildVideoAttributesFromCommander(server, program, videoInfo)
  169. const attributes = {
  170. ...baseAttributes,
  171. originallyPublishedAt: videoInfo.originallyPublishedAt
  172. ? videoInfo.originallyPublishedAt.toISOString()
  173. : null,
  174. thumbnailfile,
  175. previewfile: thumbnailfile,
  176. fixture: videoPath
  177. }
  178. log.info('\nUploading on PeerTube video "%s".', attributes.name)
  179. try {
  180. await server.videos.upload({ attributes })
  181. } catch (err) {
  182. if (err.message.indexOf('401') !== -1) {
  183. log.info('Got 401 Unauthorized, token may have expired, renewing token and retry.')
  184. server.accessToken = await server.login.getAccessToken(username, password)
  185. await server.videos.upload({ attributes })
  186. } else {
  187. exitError(err.message)
  188. }
  189. }
  190. await remove(videoPath)
  191. if (thumbnailfile) await remove(thumbnailfile)
  192. log.info('Uploaded video "%s"!\n', attributes.name)
  193. }
  194. /* ---------------------------------------------------------- */
  195. async function fetchObject (info: any) {
  196. const url = buildUrl(info)
  197. const youtubeDLCLI = await YoutubeDLCLI.safeGet()
  198. const result = await youtubeDLCLI.getInfo({
  199. url,
  200. format: YoutubeDLCLI.getYoutubeDLVideoFormat([]),
  201. processOptions
  202. })
  203. const builder = new YoutubeDLInfoBuilder(result)
  204. const videoInfo = builder.getInfo()
  205. return { ...videoInfo, url }
  206. }
  207. function buildUrl (info: any) {
  208. const webpageUrl = info.webpage_url as string
  209. if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl
  210. const url = info.url as string
  211. if (url?.match(/^https?:\/\//)) return url
  212. // It seems youtube-dl does not return the video url
  213. return 'https://www.youtube.com/watch?v=' + info.id
  214. }
  215. function normalizeTargetUrl (url: string) {
  216. let normalizedUrl = url.replace(/\/+$/, '')
  217. if (!normalizedUrl.startsWith('http://') && !normalizedUrl.startsWith('https://')) {
  218. normalizedUrl = 'https://' + normalizedUrl
  219. }
  220. return normalizedUrl
  221. }
  222. async function promptPassword () {
  223. return new Promise<string>((res, rej) => {
  224. prompt.start()
  225. const schema = {
  226. properties: {
  227. password: {
  228. hidden: true,
  229. required: true
  230. }
  231. }
  232. }
  233. prompt.get(schema, function (err, result) {
  234. if (err) {
  235. return rej(err)
  236. }
  237. return res(result.password)
  238. })
  239. })
  240. }
  241. function parseDate (dateAsStr: string): Date {
  242. if (!/\d{4}-\d{2}-\d{2}/.test(dateAsStr)) {
  243. exitError(`Invalid date passed: ${dateAsStr}. Expected format: YYYY-MM-DD. See help for usage.`)
  244. }
  245. const date = new Date(dateAsStr)
  246. date.setHours(0, 0, 0)
  247. if (isNaN(date.getTime())) {
  248. exitError(`Invalid date passed: ${dateAsStr}. See help for usage.`)
  249. }
  250. return date
  251. }
  252. function formatDate (date: Date): string {
  253. return date.toISOString().split('T')[0]
  254. }
  255. function convertIntoMs (secondsAsStr: string): number {
  256. const seconds = parseInt(secondsAsStr, 10)
  257. if (seconds <= 0) {
  258. exitError(`Invalid duration passed: ${seconds}. Expected duration to be strictly positive and in seconds`)
  259. }
  260. return Math.round(seconds * 1000)
  261. }
  262. function exitError (message: string, ...meta: any[]) {
  263. // use console.error instead of log.error here
  264. console.error(message, ...meta)
  265. process.exit(-1)
  266. }
  267. function getYoutubeDLInfo (youtubeDLCLI: YoutubeDLCLI, url: string, args: string[]) {
  268. return youtubeDLCLI.getInfo({
  269. url,
  270. format: YoutubeDLCLI.getYoutubeDLVideoFormat([]),
  271. additionalYoutubeDLArgs: [ '-j', '--flat-playlist', '--playlist-reverse', ...args ],
  272. processOptions
  273. })
  274. }