1 import * as program from 'commander'
2 import * as prompt from 'prompt'
3 import { getSettings, writeSettings, getNetrc } from './cli'
4 import { isHostValid } from '../helpers/custom-validators/servers'
5 import { isUserUsernameValid } from '../helpers/custom-validators/users'
7 const Table = require('cli-table')
9 async function delInstance (url: string) {
10 const [ settings, netrc ] = await Promise.all([ getSettings(), getNetrc() ])
12 settings.remotes.splice(settings.remotes.indexOf(url))
13 await writeSettings(settings)
15 delete netrc.machines[url]
20 async function setInstance (url: string, username: string, password: string) {
21 const [ settings, netrc ] = await Promise.all([ getSettings(), getNetrc() ])
23 if (settings.remotes.indexOf(url) === -1) {
24 settings.remotes.push(url)
26 await writeSettings(settings)
28 netrc.machines[url] = { login: username, password }
32 function isURLaPeerTubeInstance (url: string) {
33 return isHostValid(url) || (url.includes('localhost'))
38 .usage('[command] [options]')
42 .description('remember your accounts on remote instances for easier use')
43 .option('-u, --url <url>', 'Server url')
44 .option('-U, --username <username>', 'Username')
45 .option('-p, --password <token>', 'Password')
46 .option('--default', 'add the entry as the new default')
48 prompt.override = options
53 description: 'instance url',
54 conform: (value) => isURLaPeerTubeInstance(value),
58 conform: (value) => isUserUsernameValid(value),
59 message: 'Name must be only letters, spaces, or dashes',
68 }, async (_, result) => {
69 await setInstance(result.url, result.username, result.password)
77 .description('unregisters a remote instance')
78 .action(async url => {
79 await delInstance(url)
86 .description('lists registered remote instances')
88 const [ settings, netrc ] = await Promise.all([ getSettings(), getNetrc() ])
90 const table = new Table({
91 head: ['instance', 'login'],
95 settings.remotes.forEach(element => {
96 if (!netrc.machines[element]) return
100 netrc.machines[element].login
104 console.log(table.toString())
110 .command('set-default <url>')
111 .description('set an existing entry as default')
112 .action(async url => {
113 const settings = await getSettings()
114 const instanceExists = settings.remotes.indexOf(url) !== -1
116 if (instanceExists) {
117 settings.default = settings.remotes.indexOf(url)
118 await writeSettings(settings)
122 console.log('<url> is not a registered instance.')
127 program.on('--help', function () {
128 console.log(' Examples:')
130 console.log(' $ peertube add -u peertube.cpy.re -U "PEERTUBE_USER" --password "PEERTUBE_PASSWORD"')
131 console.log(' $ peertube add -u peertube.cpy.re -U root')
132 console.log(' $ peertube list')
133 console.log(' $ peertube del peertube.cpy.re')
137 if (!process.argv.slice(2).length) {
141 program.parse(process.argv)