]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tools/cli.ts
Merge branch 'release/2.1.0' into develop
[github/Chocobozzz/PeerTube.git] / server / tools / cli.ts
1 import { Netrc } from 'netrc-parser'
2 import { getAppNumber, isTestInstance } from '../helpers/core-utils'
3 import { join } from 'path'
4 import { root } from '../../shared/extra-utils/miscs/miscs'
5 import { getVideoChannel } from '../../shared/extra-utils/videos/video-channels'
6 import { Command } from 'commander'
7 import { VideoChannel, VideoPrivacy } from '../../shared/models/videos'
8 import { createLogger, format, transports } from 'winston'
9 import { getMyUserInformation } from '@shared/extra-utils/users/users'
10 import { User, UserRole } from '@shared/models'
11 import { getAccessToken } from '@shared/extra-utils/users/login'
12
13 let configName = 'PeerTube/CLI'
14 if (isTestInstance()) configName += `-${getAppNumber()}`
15
16 const config = require('application-config')(configName)
17
18 const version = require('../../../package.json').version
19
20 async function getAdminTokenOrDie (url: string, username: string, password: string) {
21 const accessToken = await getAccessToken(url, username, password)
22 const resMe = await getMyUserInformation(url, accessToken)
23 const me: User = resMe.body
24
25 if (me.role !== UserRole.ADMINISTRATOR) {
26 console.error('You must be an administrator.')
27 process.exit(-1)
28 }
29
30 return accessToken
31 }
32
33 interface Settings {
34 remotes: any[]
35 default: number
36 }
37
38 function getSettings () {
39 return new Promise<Settings>((res, rej) => {
40 const defaultSettings = {
41 remotes: [],
42 default: -1
43 }
44
45 config.read((err, data) => {
46 if (err) return rej(err)
47
48 return res(Object.keys(data).length === 0 ? defaultSettings : data)
49 })
50 })
51 }
52
53 async function getNetrc () {
54 const Netrc = require('netrc-parser').Netrc
55
56 const netrc = isTestInstance()
57 ? new Netrc(join(root(), 'test' + getAppNumber(), 'netrc'))
58 : new Netrc()
59
60 await netrc.load()
61
62 return netrc
63 }
64
65 function writeSettings (settings) {
66 return new Promise((res, rej) => {
67 config.write(settings, err => {
68 if (err) return rej(err)
69
70 return res()
71 })
72 })
73 }
74
75 function deleteSettings () {
76 return new Promise((res, rej) => {
77 config.trash((err) => {
78 if (err) return rej(err)
79
80 return res()
81 })
82 })
83 }
84
85 function getRemoteObjectOrDie (
86 program: any,
87 settings: Settings,
88 netrc: Netrc
89 ): { url: string, username: string, password: string } {
90 if (!program['url'] || !program['username'] || !program['password']) {
91 // No remote and we don't have program parameters: quit
92 if (settings.remotes.length === 0 || Object.keys(netrc.machines).length === 0) {
93 if (!program['url']) console.error('--url field is required.')
94 if (!program['username']) console.error('--username field is required.')
95 if (!program['password']) console.error('--password field is required.')
96
97 return process.exit(-1)
98 }
99
100 let url: string = program['url']
101 let username: string = program['username']
102 let password: string = program['password']
103
104 if (!url && settings.default !== -1) url = settings.remotes[settings.default]
105
106 const machine = netrc.machines[url]
107
108 if (!username && machine) username = machine.login
109 if (!password && machine) password = machine.password
110
111 return { url, username, password }
112 }
113
114 return {
115 url: program['url'],
116 username: program['username'],
117 password: program['password']
118 }
119 }
120
121 function buildCommonVideoOptions (command: Command) {
122 function list (val) {
123 return val.split(',')
124 }
125
126 return command
127 .option('-n, --video-name <name>', 'Video name')
128 .option('-c, --category <category_number>', 'Category number')
129 .option('-l, --licence <licence_number>', 'Licence number')
130 .option('-L, --language <language_code>', 'Language ISO 639 code (fr or en...)')
131 .option('-t, --tags <tags>', 'Video tags', list)
132 .option('-N, --nsfw', 'Video is Not Safe For Work')
133 .option('-d, --video-description <description>', 'Video description')
134 .option('-P, --privacy <privacy_number>', 'Privacy')
135 .option('-C, --channel-name <channel_name>', 'Channel name')
136 .option('-m, --comments-enabled', 'Enable comments')
137 .option('-s, --support <support>', 'Video support text')
138 .option('-w, --wait-transcoding', 'Wait transcoding before publishing the video')
139 .option('-v, --verbose <verbose>', 'Verbosity, from 0/\'error\' to 4/\'debug\'', 'info')
140 }
141
142 async function buildVideoAttributesFromCommander (url: string, command: Command, defaultAttributes: any = {}) {
143 const defaultBooleanAttributes = {
144 nsfw: false,
145 commentsEnabled: true,
146 downloadEnabled: true,
147 waitTranscoding: true
148 }
149
150 const booleanAttributes: { [id in keyof typeof defaultBooleanAttributes]: boolean } | {} = {}
151
152 for (const key of Object.keys(defaultBooleanAttributes)) {
153 if (command[key] !== undefined) {
154 booleanAttributes[key] = command[key]
155 } else if (defaultAttributes[key] !== undefined) {
156 booleanAttributes[key] = defaultAttributes[key]
157 } else {
158 booleanAttributes[key] = defaultBooleanAttributes[key]
159 }
160 }
161
162 const videoAttributes = {
163 name: command['videoName'] || defaultAttributes.name,
164 category: command['category'] || defaultAttributes.category || undefined,
165 licence: command['licence'] || defaultAttributes.licence || undefined,
166 language: command['language'] || defaultAttributes.language || undefined,
167 privacy: command['privacy'] || defaultAttributes.privacy || VideoPrivacy.PUBLIC,
168 support: command['support'] || defaultAttributes.support || undefined,
169 description: command['videoDescription'] || defaultAttributes.description || undefined,
170 tags: command['tags'] || defaultAttributes.tags || undefined
171 }
172
173 Object.assign(videoAttributes, booleanAttributes)
174
175 if (command['channelName']) {
176 const res = await getVideoChannel(url, command['channelName'])
177 const videoChannel: VideoChannel = res.body
178
179 Object.assign(videoAttributes, { channelId: videoChannel.id })
180
181 if (!videoAttributes.support && videoChannel.support) {
182 Object.assign(videoAttributes, { support: videoChannel.support })
183 }
184 }
185
186 return videoAttributes
187 }
188
189 function getServerCredentials (program: any) {
190 return Promise.all([ getSettings(), getNetrc() ])
191 .then(([ settings, netrc ]) => {
192 return getRemoteObjectOrDie(program, settings, netrc)
193 })
194 }
195
196 function getLogger (logLevel = 'info') {
197 const logLevels = {
198 0: 0,
199 error: 0,
200 1: 1,
201 warn: 1,
202 2: 2,
203 info: 2,
204 3: 3,
205 verbose: 3,
206 4: 4,
207 debug: 4
208 }
209
210 const logger = createLogger({
211 levels: logLevels,
212 format: format.combine(
213 format.splat(),
214 format.simple()
215 ),
216 transports: [
217 new (transports.Console)({
218 level: logLevel
219 })
220 ]
221 })
222
223 return logger
224 }
225
226 // ---------------------------------------------------------------------------
227
228 export {
229 version,
230 config,
231 getLogger,
232 getSettings,
233 getNetrc,
234 getRemoteObjectOrDie,
235 writeSettings,
236 deleteSettings,
237
238 getServerCredentials,
239
240 buildCommonVideoOptions,
241 buildVideoAttributesFromCommander,
242
243 getAdminTokenOrDie
244 }