1 import { Command } from 'commander'
2 import { Netrc } from 'netrc-parser'
3 import { join } from 'path'
4 import { createLogger, format, transports } from 'winston'
5 import { getAppNumber, isTestInstance } from '@server/helpers/core-utils'
6 import { loadLanguages } from '@server/initializers/constants'
7 import { root } from '@shared/core-utils'
8 import { UserRole, VideoPrivacy } from '@shared/models'
9 import { PeerTubeServer } from '@shared/server-commands'
11 let configName = 'PeerTube/CLI'
12 if (isTestInstance()) configName += `-${getAppNumber()}`
14 const config = require('application-config')(configName)
16 const version = require(join(root(), 'package.json')).version
18 async function getAdminTokenOrDie (server: PeerTubeServer, username: string, password: string) {
19 const token = await server.login.getAccessToken(username, password)
20 const me = await server.users.getMyInfo({ token })
22 if (me.role.id !== UserRole.ADMINISTRATOR) {
23 console.error('You must be an administrator.')
35 async function getSettings (): Promise<Settings> {
36 const defaultSettings = {
41 const data = await config.read()
43 return Object.keys(data).length === 0
48 async function getNetrc () {
49 const Netrc = require('netrc-parser').Netrc
51 const netrc = isTestInstance()
52 ? new Netrc(join(root(), 'test' + getAppNumber(), 'netrc'))
60 function writeSettings (settings: Settings) {
61 return config.write(settings)
64 function deleteSettings () {
68 function getRemoteObjectOrDie (
72 ): { url: string, username: string, password: string } {
73 const options = program.opts()
75 function exitIfNoOptions (optionNames: string[], errorPrefix: string = '') {
78 for (const key of optionNames) {
80 if (exit === false && errorPrefix) console.error(errorPrefix)
82 console.error(`--${key} field is required`)
87 if (exit) process.exit(-1)
90 // If username or password are specified, both are mandatory
91 if (options.username || options.password) {
92 exitIfNoOptions([ 'username', 'password' ])
95 // If no available machines, url, username and password args are mandatory
96 if (Object.keys(netrc.machines).length === 0) {
97 exitIfNoOptions([ 'url', 'username', 'password' ], 'No account found in netrc')
100 if (settings.remotes.length === 0 || settings.default === -1) {
101 exitIfNoOptions([ 'url' ], 'No default instance found')
104 let url: string = options.url
105 let username: string = options.username
106 let password: string = options.password
108 if (!url && settings.default !== -1) url = settings.remotes[settings.default]
110 const machine = netrc.machines[url]
111 if ((!username || !password) && !machine) {
112 console.error('Cannot find existing configuration for %s.', url)
116 if (!username && machine) username = machine.login
117 if (!password && machine) password = machine.password
119 return { url, username, password }
122 function buildCommonVideoOptions (command: Command) {
123 function list (val) {
124 return val.split(',')
128 .option('-n, --video-name <name>', 'Video name')
129 .option('-c, --category <category_number>', 'Category number')
130 .option('-l, --licence <licence_number>', 'Licence number')
131 .option('-L, --language <language_code>', 'Language ISO 639 code (fr or en...)')
132 .option('-t, --tags <tags>', 'Video tags', list)
133 .option('-N, --nsfw', 'Video is Not Safe For Work')
134 .option('-d, --video-description <description>', 'Video description')
135 .option('-P, --privacy <privacy_number>', 'Privacy')
136 .option('-C, --channel-name <channel_name>', 'Channel name')
137 .option('--no-comments-enabled', 'Disable video comments')
138 .option('-s, --support <support>', 'Video support text')
139 .option('--no-wait-transcoding', 'Do not wait transcoding before publishing the video')
140 .option('--no-download-enabled', 'Disable video download')
141 .option('-v, --verbose <verbose>', 'Verbosity, from 0/\'error\' to 4/\'debug\'', 'info')
144 async function buildVideoAttributesFromCommander (server: PeerTubeServer, command: Command, defaultAttributes: any = {}) {
145 const options = command.opts()
147 const defaultBooleanAttributes = {
149 commentsEnabled: true,
150 downloadEnabled: true,
151 waitTranscoding: true
154 const booleanAttributes: { [id in keyof typeof defaultBooleanAttributes]: boolean } | {} = {}
156 for (const key of Object.keys(defaultBooleanAttributes)) {
157 if (options[key] !== undefined) {
158 booleanAttributes[key] = options[key]
159 } else if (defaultAttributes[key] !== undefined) {
160 booleanAttributes[key] = defaultAttributes[key]
162 booleanAttributes[key] = defaultBooleanAttributes[key]
166 const videoAttributes = {
167 name: options.videoName || defaultAttributes.name,
168 category: options.category || defaultAttributes.category || undefined,
169 licence: options.licence || defaultAttributes.licence || undefined,
170 language: options.language || defaultAttributes.language || undefined,
171 privacy: options.privacy || defaultAttributes.privacy || VideoPrivacy.PUBLIC,
172 support: options.support || defaultAttributes.support || undefined,
173 description: options.videoDescription || defaultAttributes.description || undefined,
174 tags: options.tags || defaultAttributes.tags || undefined
177 Object.assign(videoAttributes, booleanAttributes)
179 if (options.channelName) {
180 const videoChannel = await server.channels.get({ channelName: options.channelName })
182 Object.assign(videoAttributes, { channelId: videoChannel.id })
184 if (!videoAttributes.support && videoChannel.support) {
185 Object.assign(videoAttributes, { support: videoChannel.support })
189 return videoAttributes
192 function getServerCredentials (program: Command) {
193 return Promise.all([ getSettings(), getNetrc() ])
194 .then(([ settings, netrc ]) => {
195 return getRemoteObjectOrDie(program, settings, netrc)
199 function buildServer (url: string) {
201 return new PeerTubeServer({ url })
204 async function assignToken (server: PeerTubeServer, username: string, password: string) {
205 const bodyClient = await server.login.getClient()
206 const client = { id: bodyClient.client_id, secret: bodyClient.client_secret }
208 const body = await server.login.login({ client, user: { username, password } })
210 server.accessToken = body.access_token
213 function getLogger (logLevel = 'info') {
227 const logger = createLogger({
229 format: format.combine(
234 new (transports.Console)({
243 // ---------------------------------------------------------------------------
250 getRemoteObjectOrDie,
254 getServerCredentials,
256 buildCommonVideoOptions,
257 buildVideoAttributesFromCommander,