4569cbb85b31dd89802d1d36304bb29403f521a8
[oweals/peertube.git] / server / tools / peertube-upload.ts
1 import * as program from 'commander'
2 import { access, constants } from 'fs-extra'
3 import { isAbsolute } from 'path'
4 import { getAccessToken } from '../../shared/extra-utils'
5 import { uploadVideo } from '../../shared/extra-utils/'
6 import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getServerCredentials } from './cli'
7
8 let command = program
9   .name('upload')
10
11 command = buildCommonVideoOptions(command)
12
13 command
14   .option('-u, --url <url>', 'Server url')
15   .option('-U, --username <username>', 'Username')
16   .option('-p, --password <token>', 'Password')
17   .option('-b, --thumbnail <thumbnailPath>', 'Thumbnail path')
18   .option('-v, --preview <previewPath>', 'Preview path')
19   .option('-f, --file <file>', 'Video absolute file path')
20   .parse(process.argv)
21
22 getServerCredentials(command)
23   .then(({ url, username, password }) => {
24     if (!program[ 'videoName' ] || !program[ 'file' ]) {
25       if (!program[ 'videoName' ]) console.error('--video-name is required.')
26       if (!program[ 'file' ]) console.error('--file is required.')
27
28       process.exit(-1)
29     }
30
31     if (isAbsolute(program[ 'file' ]) === false) {
32       console.error('File path should be absolute.')
33       process.exit(-1)
34     }
35
36     run(url, username, password).catch(err => {
37       console.error(err)
38       process.exit(-1)
39     })
40   })
41
42 async function run (url: string, username: string, password: string) {
43   const accessToken = await getAccessToken(url, username, password)
44
45   await access(program[ 'file' ], constants.F_OK)
46
47   console.log('Uploading %s video...', program[ 'videoName' ])
48
49   const videoAttributes = await buildVideoAttributesFromCommander(url, program)
50
51   Object.assign(videoAttributes, {
52     fixture: program[ 'file' ],
53     thumbnailfile: program[ 'thumbnail' ],
54     previewfile: program[ 'preview' ]
55   })
56
57   try {
58     await uploadVideo(url, accessToken, videoAttributes)
59     console.log(`Video ${program[ 'videoName' ]} uploaded.`)
60     process.exit(0)
61   } catch (err) {
62     console.error(require('util').inspect(err))
63     process.exit(-1)
64   }
65 }
66
67 // ----------------------------------------------------------------------------