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