]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tools/cli.ts
d5416fc3870a8e24291881f1c8090a411deb10da
[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 { CommanderStatic } 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 async function getSettings (): Promise<Settings> {
39 const defaultSettings = {
40 remotes: [],
41 default: -1
42 }
43
44 const data = await config.read()
45
46 return Object.keys(data).length === 0
47 ? defaultSettings
48 : data
49 }
50
51 async function getNetrc () {
52 const Netrc = require('netrc-parser').Netrc
53
54 const netrc = isTestInstance()
55 ? new Netrc(join(root(), 'test' + getAppNumber(), 'netrc'))
56 : new Netrc()
57
58 await netrc.load()
59
60 return netrc
61 }
62
63 function writeSettings (settings: Settings) {
64 return config.write(settings)
65 }
66
67 function deleteSettings () {
68 return config.trash()
69 }
70
71 function getRemoteObjectOrDie (
72 program: any,
73 settings: Settings,
74 netrc: Netrc
75 ): { url: string, username: string, password: string } {
76 if (!program['url'] || !program['username'] || !program['password']) {
77 // No remote and we don't have program parameters: quit
78 if (settings.remotes.length === 0 || Object.keys(netrc.machines).length === 0) {
79 if (!program['url']) console.error('--url field is required.')
80 if (!program['username']) console.error('--username field is required.')
81 if (!program['password']) console.error('--password field is required.')
82
83 return process.exit(-1)
84 }
85
86 let url: string = program['url']
87 let username: string = program['username']
88 let password: string = program['password']
89
90 if (!url && settings.default !== -1) url = settings.remotes[settings.default]
91
92 const machine = netrc.machines[url]
93
94 if (!username && machine) username = machine.login
95 if (!password && machine) password = machine.password
96
97 return { url, username, password }
98 }
99
100 return {
101 url: program['url'],
102 username: program['username'],
103 password: program['password']
104 }
105 }
106
107 function buildCommonVideoOptions (command: CommanderStatic) {
108 function list (val) {
109 return val.split(',')
110 }
111
112 return command
113 .option('-n, --video-name <name>', 'Video name')
114 .option('-c, --category <category_number>', 'Category number')
115 .option('-l, --licence <licence_number>', 'Licence number')
116 .option('-L, --language <language_code>', 'Language ISO 639 code (fr or en...)')
117 .option('-t, --tags <tags>', 'Video tags', list)
118 .option('-N, --nsfw', 'Video is Not Safe For Work')
119 .option('-d, --video-description <description>', 'Video description')
120 .option('-P, --privacy <privacy_number>', 'Privacy')
121 .option('-C, --channel-name <channel_name>', 'Channel name')
122 .option('--no-comments-enabled', 'Disable video comments')
123 .option('-s, --support <support>', 'Video support text')
124 .option('--no-wait-transcoding', 'Do not wait transcoding before publishing the video')
125 .option('--no-download-enabled', 'Disable video download')
126 .option('-v, --verbose <verbose>', 'Verbosity, from 0/\'error\' to 4/\'debug\'', 'info')
127 }
128
129 async function buildVideoAttributesFromCommander (url: string, command: CommanderStatic, defaultAttributes: any = {}) {
130 const defaultBooleanAttributes = {
131 nsfw: false,
132 commentsEnabled: true,
133 downloadEnabled: true,
134 waitTranscoding: true
135 }
136
137 const booleanAttributes: { [id in keyof typeof defaultBooleanAttributes]: boolean } | {} = {}
138
139 for (const key of Object.keys(defaultBooleanAttributes)) {
140 if (command[key] !== undefined) {
141 booleanAttributes[key] = command[key]
142 } else if (defaultAttributes[key] !== undefined) {
143 booleanAttributes[key] = defaultAttributes[key]
144 } else {
145 booleanAttributes[key] = defaultBooleanAttributes[key]
146 }
147 }
148
149 const videoAttributes = {
150 name: command['videoName'] || defaultAttributes.name,
151 category: command['category'] || defaultAttributes.category || undefined,
152 licence: command['licence'] || defaultAttributes.licence || undefined,
153 language: command['language'] || defaultAttributes.language || undefined,
154 privacy: command['privacy'] || defaultAttributes.privacy || VideoPrivacy.PUBLIC,
155 support: command['support'] || defaultAttributes.support || undefined,
156 description: command['videoDescription'] || defaultAttributes.description || undefined,
157 tags: command['tags'] || defaultAttributes.tags || undefined
158 }
159
160 Object.assign(videoAttributes, booleanAttributes)
161
162 if (command['channelName']) {
163 const res = await getVideoChannel(url, command['channelName'])
164 const videoChannel: VideoChannel = res.body
165
166 Object.assign(videoAttributes, { channelId: videoChannel.id })
167
168 if (!videoAttributes.support && videoChannel.support) {
169 Object.assign(videoAttributes, { support: videoChannel.support })
170 }
171 }
172
173 return videoAttributes
174 }
175
176 function getServerCredentials (program: any) {
177 return Promise.all([ getSettings(), getNetrc() ])
178 .then(([ settings, netrc ]) => {
179 return getRemoteObjectOrDie(program, settings, netrc)
180 })
181 }
182
183 function getLogger (logLevel = 'info') {
184 const logLevels = {
185 0: 0,
186 error: 0,
187 1: 1,
188 warn: 1,
189 2: 2,
190 info: 2,
191 3: 3,
192 verbose: 3,
193 4: 4,
194 debug: 4
195 }
196
197 const logger = createLogger({
198 levels: logLevels,
199 format: format.combine(
200 format.splat(),
201 format.simple()
202 ),
203 transports: [
204 new (transports.Console)({
205 level: logLevel
206 })
207 ]
208 })
209
210 return logger
211 }
212
213 // ---------------------------------------------------------------------------
214
215 export {
216 version,
217 getLogger,
218 getSettings,
219 getNetrc,
220 getRemoteObjectOrDie,
221 writeSettings,
222 deleteSettings,
223
224 getServerCredentials,
225
226 buildCommonVideoOptions,
227 buildVideoAttributesFromCommander,
228
229 getAdminTokenOrDie
230 }