]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/tools/cli.ts
ca05dab92cd37f92b800e10c2eda51ebcc054e95
[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('-m, --comments-enabled', 'Enable comments')
123 .option('-s, --support <support>', 'Video support text')
124 .option('-w, --wait-transcoding', 'Wait transcoding before publishing the video')
125 .option('-v, --verbose <verbose>', 'Verbosity, from 0/\'error\' to 4/\'debug\'', 'info')
126 }
127
128 async function buildVideoAttributesFromCommander (url: string, command: CommanderStatic, defaultAttributes: any = {}) {
129 const defaultBooleanAttributes = {
130 nsfw: false,
131 commentsEnabled: true,
132 downloadEnabled: true,
133 waitTranscoding: true
134 }
135
136 const booleanAttributes: { [id in keyof typeof defaultBooleanAttributes]: boolean } | {} = {}
137
138 for (const key of Object.keys(defaultBooleanAttributes)) {
139 if (command[key] !== undefined) {
140 booleanAttributes[key] = command[key]
141 } else if (defaultAttributes[key] !== undefined) {
142 booleanAttributes[key] = defaultAttributes[key]
143 } else {
144 booleanAttributes[key] = defaultBooleanAttributes[key]
145 }
146 }
147
148 const videoAttributes = {
149 name: command['videoName'] || defaultAttributes.name,
150 category: command['category'] || defaultAttributes.category || undefined,
151 licence: command['licence'] || defaultAttributes.licence || undefined,
152 language: command['language'] || defaultAttributes.language || undefined,
153 privacy: command['privacy'] || defaultAttributes.privacy || VideoPrivacy.PUBLIC,
154 support: command['support'] || defaultAttributes.support || undefined,
155 description: command['videoDescription'] || defaultAttributes.description || undefined,
156 tags: command['tags'] || defaultAttributes.tags || undefined
157 }
158
159 Object.assign(videoAttributes, booleanAttributes)
160
161 if (command['channelName']) {
162 const res = await getVideoChannel(url, command['channelName'])
163 const videoChannel: VideoChannel = res.body
164
165 Object.assign(videoAttributes, { channelId: videoChannel.id })
166
167 if (!videoAttributes.support && videoChannel.support) {
168 Object.assign(videoAttributes, { support: videoChannel.support })
169 }
170 }
171
172 return videoAttributes
173 }
174
175 function getServerCredentials (program: any) {
176 return Promise.all([ getSettings(), getNetrc() ])
177 .then(([ settings, netrc ]) => {
178 return getRemoteObjectOrDie(program, settings, netrc)
179 })
180 }
181
182 function getLogger (logLevel = 'info') {
183 const logLevels = {
184 0: 0,
185 error: 0,
186 1: 1,
187 warn: 1,
188 2: 2,
189 info: 2,
190 3: 3,
191 verbose: 3,
192 4: 4,
193 debug: 4
194 }
195
196 const logger = createLogger({
197 levels: logLevels,
198 format: format.combine(
199 format.splat(),
200 format.simple()
201 ),
202 transports: [
203 new (transports.Console)({
204 level: logLevel
205 })
206 ]
207 })
208
209 return logger
210 }
211
212 // ---------------------------------------------------------------------------
213
214 export {
215 version,
216 getLogger,
217 getSettings,
218 getNetrc,
219 getRemoteObjectOrDie,
220 writeSettings,
221 deleteSettings,
222
223 getServerCredentials,
224
225 buildCommonVideoOptions,
226 buildVideoAttributesFromCommander,
227
228 getAdminTokenOrDie
229 }