Fix upload from CLI script
[oweals/peertube.git] / server / tools / upload.ts
1 import * as program from 'commander'
2 import { access, constants } from 'fs'
3 import { isAbsolute } from 'path'
4 import { promisify } from 'util'
5 import { getClient, login } from '../tests/utils'
6 import { uploadVideo } from '../tests/utils/index'
7
8 const accessPromise = promisify(access)
9
10 program
11   .option('-u, --url <url>', 'Server url')
12   .option('-U, --username <username>', 'Username')
13   .option('-p, --password <token>', 'Password')
14   .option('-n, --video-name <name>', 'Video name')
15   .option('-N, --nsfw', 'Video is Not Safe For Work')
16   .option('-c, --category <category number>', 'Category number')
17   .option('-m, --comments-enabled', 'Enable comments')
18   .option('-l, --licence <licence number>', 'Licence number')
19   .option('-L, --language <language number>', 'Language number')
20   .option('-d, --video-description <description>', 'Video description')
21   .option('-t, --tags <tags>', 'Video tags', list)
22   .option('-f, --file <file>', 'Video absolute file path')
23   .parse(process.argv)
24
25 if (!program['tags']) program['tags'] = []
26 if (!program['nsfw']) program['nsfw'] = false
27 if (!program['commentsEnabled']) program['commentsEnabled'] = false
28
29 if (
30   !program['url'] ||
31   !program['username'] ||
32   !program['password'] ||
33   !program['videoName'] ||
34   !program['file']
35 ) {
36   console.error('Url, username, password, name and input file are required.')
37   process.exit(-1)
38 }
39
40 if (isAbsolute(program['file']) === false) {
41   console.error('File path should be absolute.')
42   process.exit(-1)
43 }
44
45 run().catch(err => console.error(err))
46
47 async function run () {
48   const res = await getClient(program[ 'url' ])
49   const client = {
50     id: res.body.client_id,
51     secret: res.body.client_secret
52   }
53
54   const user = {
55     username: program[ 'username' ],
56     password: program[ 'password' ]
57   }
58
59   const res2 = await login(program[ 'url' ], client, user)
60   const accessToken = res2.body.access_token
61
62   await accessPromise(program[ 'file' ], constants.F_OK)
63
64   console.log('Uploading %s video...', program[ 'videoName' ])
65
66   const videoAttributes = {
67     name: program['videoName'],
68     category: program['category'],
69     licence: program['licence'],
70     language: program['language'],
71     nsfw: program['nsfw'],
72     description: program['videoDescription'],
73     tags: program['tags'],
74     commentsEnabled: program['commentsEnabled'],
75     fixture: program['file']
76   }
77
78   await uploadVideo(program['url'], accessToken, videoAttributes)
79
80   console.log(`Video ${program['videoName']} uploaded.`)
81   process.exit(0)
82 }
83
84 // ----------------------------------------------------------------------------
85
86 function list (val) {
87   return val.split(',')
88 }