From a15871560f80e07386c1dabb8370cd2664ecfd1f Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 31 Jan 2020 16:56:52 +0100 Subject: Move to eslint --- server/tools/cli.ts | 42 ++++++++--------- server/tools/peertube-auth.ts | 10 ++-- server/tools/peertube-import-videos.ts | 83 +++++++++++++++++----------------- server/tools/peertube-plugins.ts | 11 ++--- server/tools/peertube-redundancy.ts | 19 ++++---- server/tools/peertube-repl.ts | 41 ++++++++++++----- server/tools/peertube-upload.ts | 21 +++++---- server/tools/peertube-watch.ts | 10 +--- server/tools/peertube.ts | 23 +++++----- 9 files changed, 138 insertions(+), 122 deletions(-) (limited to 'server/tools') diff --git a/server/tools/cli.ts b/server/tools/cli.ts index 15ac6c6a8..d1a631b69 100644 --- a/server/tools/cli.ts +++ b/server/tools/cli.ts @@ -31,7 +31,7 @@ async function getAdminTokenOrDie (url: string, username: string, password: stri } interface Settings { - remotes: any[], + remotes: any[] default: number } @@ -90,9 +90,9 @@ function getRemoteObjectOrDie ( if (!program['url'] || !program['username'] || !program['password']) { // No remote and we don't have program parameters: quit if (settings.remotes.length === 0 || Object.keys(netrc.machines).length === 0) { - if (!program[ 'url' ]) console.error('--url field is required.') - if (!program[ 'username' ]) console.error('--username field is required.') - if (!program[ 'password' ]) console.error('--password field is required.') + if (!program['url']) console.error('--url field is required.') + if (!program['username']) console.error('--username field is required.') + if (!program['password']) console.error('--password field is required.') return process.exit(-1) } @@ -112,9 +112,9 @@ function getRemoteObjectOrDie ( } return { - url: program[ 'url' ], - username: program[ 'username' ], - password: program[ 'password' ] + url: program['url'], + username: program['username'], + password: program['password'] } } @@ -150,8 +150,8 @@ async function buildVideoAttributesFromCommander (url: string, command: Command, const booleanAttributes: { [id in keyof typeof defaultBooleanAttributes]: boolean } | {} = {} for (const key of Object.keys(defaultBooleanAttributes)) { - if (command[ key ] !== undefined) { - booleanAttributes[key] = command[ key ] + if (command[key] !== undefined) { + booleanAttributes[key] = command[key] } else if (defaultAttributes[key] !== undefined) { booleanAttributes[key] = defaultAttributes[key] } else { @@ -160,19 +160,19 @@ async function buildVideoAttributesFromCommander (url: string, command: Command, } const videoAttributes = { - name: command[ 'videoName' ] || defaultAttributes.name, - category: command[ 'category' ] || defaultAttributes.category || undefined, - licence: command[ 'licence' ] || defaultAttributes.licence || undefined, - language: command[ 'language' ] || defaultAttributes.language || undefined, - privacy: command[ 'privacy' ] || defaultAttributes.privacy || VideoPrivacy.PUBLIC, - support: command[ 'support' ] || defaultAttributes.support || undefined, - description: command[ 'videoDescription' ] || defaultAttributes.description || undefined, - tags: command[ 'tags' ] || defaultAttributes.tags || undefined + name: command['videoName'] || defaultAttributes.name, + category: command['category'] || defaultAttributes.category || undefined, + licence: command['licence'] || defaultAttributes.licence || undefined, + language: command['language'] || defaultAttributes.language || undefined, + privacy: command['privacy'] || defaultAttributes.privacy || VideoPrivacy.PUBLIC, + support: command['support'] || defaultAttributes.support || undefined, + description: command['videoDescription'] || defaultAttributes.description || undefined, + tags: command['tags'] || defaultAttributes.tags || undefined } Object.assign(videoAttributes, booleanAttributes) - if (command[ 'channelName' ]) { + if (command['channelName']) { const res = await getVideoChannel(url, command['channelName']) const videoChannel: VideoChannel = res.body @@ -188,9 +188,9 @@ async function buildVideoAttributesFromCommander (url: string, command: Command, function getServerCredentials (program: any) { return Promise.all([ getSettings(), getNetrc() ]) - .then(([ settings, netrc ]) => { - return getRemoteObjectOrDie(program, settings, netrc) - }) + .then(([ settings, netrc ]) => { + return getRemoteObjectOrDie(program, settings, netrc) + }) } function getLogger (logLevel = 'info') { diff --git a/server/tools/peertube-auth.ts b/server/tools/peertube-auth.ts index acac75034..6b486e575 100644 --- a/server/tools/peertube-auth.ts +++ b/server/tools/peertube-auth.ts @@ -1,3 +1,5 @@ +// eslint-disable @typescript-eslint/no-unnecessary-type-assertion + import { registerTSPaths } from '../helpers/register-ts-paths' registerTSPaths() @@ -5,7 +7,7 @@ import * as program from 'commander' import * as prompt from 'prompt' import { getNetrc, getSettings, writeSettings } from './cli' import { isUserUsernameValid } from '../helpers/custom-validators/users' -import { getAccessToken, login } from '../../shared/extra-utils' +import { getAccessToken } from '../../shared/extra-utils' import * as CliTable3 from 'cli-table3' async function delInstance (url: string) { @@ -108,9 +110,9 @@ program const [ settings, netrc ] = await Promise.all([ getSettings(), getNetrc() ]) const table = new CliTable3({ - head: ['instance', 'login'], - colWidths: [30, 30] - }) as CliTable3.HorizontalTable + head: [ 'instance', 'login' ], + colWidths: [ 30, 30 ] + }) as any settings.remotes.forEach(element => { if (!netrc.machines[element]) return diff --git a/server/tools/peertube-import-videos.ts b/server/tools/peertube-import-videos.ts index c7e85b570..0efe87810 100644 --- a/server/tools/peertube-import-videos.ts +++ b/server/tools/peertube-import-videos.ts @@ -12,7 +12,7 @@ import { accessSync, constants } from 'fs' import { remove } from 'fs-extra' import { sha256 } from '../helpers/core-utils' import { buildOriginallyPublishedAt, safeGetYoutubeDL } from '../helpers/youtube-dl' -import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getServerCredentials, getLogger } from './cli' +import { buildCommonVideoOptions, buildVideoAttributesFromCommander, getLogger, getServerCredentials } from './cli' type UserInfo = { username: string @@ -40,30 +40,29 @@ command .option('-T, --tmpdir ', 'Working directory', __dirname) .parse(process.argv) -let log = getLogger(program[ 'verbose' ]) +const log = getLogger(program['verbose']) getServerCredentials(command) .then(({ url, username, password }) => { - if (!program[ 'targetUrl' ]) { + if (!program['targetUrl']) { exitError('--target-url field is required.') } try { - accessSync(program[ 'tmpdir' ], constants.R_OK | constants.W_OK) + accessSync(program['tmpdir'], constants.R_OK | constants.W_OK) } catch (e) { - exitError('--tmpdir %s: directory does not exist or is not accessible', program[ 'tmpdir' ]) + exitError('--tmpdir %s: directory does not exist or is not accessible', program['tmpdir']) } url = normalizeTargetUrl(url) - program[ 'targetUrl' ] = normalizeTargetUrl(program[ 'targetUrl' ]) + program['targetUrl'] = normalizeTargetUrl(program['targetUrl']) const user = { username, password } run(url, user) - .catch(err => { - exitError(err) - }) + .catch(err => exitError(err)) }) + .catch(err => console.error(err)) async function run (url: string, user: UserInfo) { if (!user.password) { @@ -73,7 +72,7 @@ async function run (url: string, user: UserInfo) { const youtubeDL = await safeGetYoutubeDL() const options = [ '-j', '--flat-playlist', '--playlist-reverse' ] - youtubeDL.getInfo(program[ 'targetUrl' ], options, processOptions, async (err, info) => { + youtubeDL.getInfo(program['targetUrl'], options, processOptions, async (err, info) => { if (err) { exitError(err.message) } @@ -82,10 +81,10 @@ async function run (url: string, user: UserInfo) { // Normalize utf8 fields infoArray = [].concat(info) - if (program[ 'first' ]) { - infoArray = infoArray.slice(0, program[ 'first' ]) - } else if (program[ 'last' ]) { - infoArray = infoArray.slice(-program[ 'last' ]) + if (program['first']) { + infoArray = infoArray.slice(0, program['first']) + } else if (program['last']) { + infoArray = infoArray.slice(-program['last']) } infoArray = infoArray.map(i => normalizeObject(i)) @@ -93,22 +92,22 @@ async function run (url: string, user: UserInfo) { for (const info of infoArray) { await processVideo({ - cwd: program[ 'tmpdir' ], + cwd: program['tmpdir'], url, user, youtubeInfo: info }) } - log.info('Video/s for user %s imported: %s', user.username, program[ 'targetUrl' ]) + log.info('Video/s for user %s imported: %s', user.username, program['targetUrl']) process.exit(0) }) } function processVideo (parameters: { - cwd: string, - url: string, - user: { username: string, password: string }, + cwd: string + url: string + user: { username: string, password: string } youtubeInfo: any }) { const { youtubeInfo, cwd, url, user } = parameters @@ -119,17 +118,17 @@ function processVideo (parameters: { const videoInfo = await fetchObject(youtubeInfo) log.debug('Fetched object.', videoInfo) - if (program[ 'since' ]) { - if (buildOriginallyPublishedAt(videoInfo).getTime() < program[ 'since' ].getTime()) { + if (program['since']) { + if (buildOriginallyPublishedAt(videoInfo).getTime() < program['since'].getTime()) { log.info('Video "%s" has been published before "%s", don\'t upload it.\n', - videoInfo.title, formatDate(program[ 'since' ])) + videoInfo.title, formatDate(program['since'])) return res() } } - if (program[ 'until' ]) { - if (buildOriginallyPublishedAt(videoInfo).getTime() > program[ 'until' ].getTime()) { + if (program['until']) { + if (buildOriginallyPublishedAt(videoInfo).getTime() > program['until'].getTime()) { log.info('Video "%s" has been published after "%s", don\'t upload it.\n', - videoInfo.title, formatDate(program[ 'until' ])) + videoInfo.title, formatDate(program['until'])) return res() } } @@ -174,11 +173,11 @@ function processVideo (parameters: { } async function uploadVideoOnPeerTube (parameters: { - videoInfo: any, - videoPath: string, - cwd: string, - url: string, - user: { username: string; password: string } + videoInfo: any + videoPath: string + cwd: string + url: string + user: { username: string, password: string } }) { const { videoInfo, videoPath, cwd, url, user } = parameters @@ -206,9 +205,9 @@ async function uploadVideoOnPeerTube (parameters: { const defaultAttributes = { name: truncate(videoInfo.title, { - 'length': CONSTRAINTS_FIELDS.VIDEOS.NAME.max, - 'separator': /,? +/, - 'omission': ' […]' + length: CONSTRAINTS_FIELDS.VIDEOS.NAME.max, + separator: /,? +/, + omission: ' […]' }), category, licence, @@ -255,7 +254,7 @@ async function uploadVideoOnPeerTube (parameters: { async function getCategory (categories: string[], url: string) { if (!categories) return undefined - const categoryString = categories[ 0 ] + const categoryString = categories[0] if (categoryString === 'News & Politics') return 11 @@ -263,7 +262,7 @@ async function getCategory (categories: string[], url: string) { const categoriesServer = res.body for (const key of Object.keys(categoriesServer)) { - const categoryServer = categoriesServer[ key ] + const categoryServer = categoriesServer[key] if (categoryString.toLowerCase() === categoryServer.toLowerCase()) return parseInt(key, 10) } @@ -285,12 +284,12 @@ function normalizeObject (obj: any) { // Deprecated key if (key === 'resolution') continue - const value = obj[ key ] + const value = obj[key] if (typeof value === 'string') { - newObj[ key ] = value.normalize() + newObj[key] = value.normalize() } else { - newObj[ key ] = value + newObj[key] = value } } @@ -302,7 +301,7 @@ function fetchObject (info: any) { return new Promise(async (res, rej) => { const youtubeDL = await safeGetYoutubeDL() - youtubeDL.getInfo(url, undefined, processOptions, async (err, videoInfo) => { + youtubeDL.getInfo(url, undefined, processOptions, (err, videoInfo) => { if (err) return rej(err) const videoInfoWithUrl = Object.assign(videoInfo, { url }) @@ -313,10 +312,10 @@ function fetchObject (info: any) { function buildUrl (info: any) { const webpageUrl = info.webpage_url as string - if (webpageUrl && webpageUrl.match(/^https?:\/\//)) return webpageUrl + if (webpageUrl?.match(/^https?:\/\//)) return webpageUrl const url = info.url as string - if (url && url.match(/^https?:\/\//)) return url + if (url?.match(/^https?:\/\//)) return url // It seems youtube-dl does not return the video url return 'https://www.youtube.com/watch?v=' + info.id @@ -384,7 +383,7 @@ function parseDate (dateAsStr: string): Date { } function formatDate (date: Date): string { - return date.toISOString().split('T')[ 0 ] + return date.toISOString().split('T')[0] } function exitError (message: string, ...meta: any[]) { diff --git a/server/tools/peertube-plugins.ts b/server/tools/peertube-plugins.ts index b341c14c1..05b75fab2 100644 --- a/server/tools/peertube-plugins.ts +++ b/server/tools/peertube-plugins.ts @@ -1,3 +1,5 @@ +// eslint-disable @typescript-eslint/no-unnecessary-type-assertion + import { registerTSPaths } from '../helpers/register-ts-paths' registerTSPaths() @@ -79,9 +81,9 @@ async function pluginsListCLI () { const plugins: PeerTubePlugin[] = res.body.data const table = new CliTable3({ - head: ['name', 'version', 'homepage'], + head: [ 'name', 'version', 'homepage' ], colWidths: [ 50, 10, 50 ] - }) as CliTable3.HorizontalTable + }) as any for (const plugin of plugins) { const npmName = plugin.type === PluginType.PLUGIN @@ -124,7 +126,6 @@ async function installPluginCLI (options: any) { } catch (err) { console.error('Cannot install plugin.', err) process.exit(-1) - return } console.log('Plugin installed.') @@ -156,7 +157,6 @@ async function updatePluginCLI (options: any) { } catch (err) { console.error('Cannot update plugin.', err) process.exit(-1) - return } console.log('Plugin updated.') @@ -177,12 +177,11 @@ async function uninstallPluginCLI (options: any) { await uninstallPlugin({ url, accessToken, - npmName: options[ 'npmName' ] + npmName: options['npmName'] }) } catch (err) { console.error('Cannot uninstall plugin.', err) process.exit(-1) - return } console.log('Plugin uninstalled.') diff --git a/server/tools/peertube-redundancy.ts b/server/tools/peertube-redundancy.ts index a71f48104..1ab58a438 100644 --- a/server/tools/peertube-redundancy.ts +++ b/server/tools/peertube-redundancy.ts @@ -1,3 +1,5 @@ +// eslint-disable @typescript-eslint/no-unnecessary-type-assertion + import { registerTSPaths } from '../helpers/register-ts-paths' registerTSPaths() @@ -6,11 +8,12 @@ import { getAdminTokenOrDie, getServerCredentials } from './cli' import { VideoRedundanciesTarget, VideoRedundancy } from '@shared/models' import { addVideoRedundancy, listVideoRedundancies, removeVideoRedundancy } from '@shared/extra-utils/server/redundancy' import validator from 'validator' -import bytes = require('bytes') import * as CliTable3 from 'cli-table3' -import { parse } from 'url' +import { URL } from 'url' import { uniq } from 'lodash' +import bytes = require('bytes') + program .name('plugins') .usage('[command] [options]') @@ -65,7 +68,7 @@ async function listRedundanciesCLI (target: VideoRedundanciesTarget) { const table = new CliTable3({ head: [ 'video id', 'video name', 'video url', 'files', 'playlists', 'by instances', 'total size' ] - }) as CliTable3.HorizontalTable + }) as any for (const redundancy of redundancies) { const webtorrentFiles = redundancy.redundancies.files @@ -82,7 +85,7 @@ async function listRedundanciesCLI (target: VideoRedundanciesTarget) { const instances = uniq( webtorrentFiles.concat(streamingPlaylists) .map(r => r.fileUrl) - .map(u => parse(u).host) + .map(u => new URL(u).host) ) table.push([ @@ -104,7 +107,7 @@ async function addRedundancyCLI (options: { videoId: number }) { const { url, username, password } = await getServerCredentials(program) const accessToken = await getAdminTokenOrDie(url, username, password) - if (!options[ 'video' ] || validator.isInt('' + options[ 'video' ]) === false) { + if (!options['video'] || validator.isInt('' + options['video']) === false) { console.error('You need to specify the video id to duplicate and it should be a number.\n') program.outputHelp() process.exit(-1) @@ -114,7 +117,7 @@ async function addRedundancyCLI (options: { videoId: number }) { await addVideoRedundancy({ url, accessToken, - videoId: options[ 'video' ] + videoId: options['video'] }) console.log('Video will be duplicated by your instance!') @@ -137,13 +140,13 @@ async function removeRedundancyCLI (options: { videoId: number }) { const { url, username, password } = await getServerCredentials(program) const accessToken = await getAdminTokenOrDie(url, username, password) - if (!options[ 'video' ] || validator.isInt('' + options[ 'video' ]) === false) { + if (!options['video'] || validator.isInt('' + options['video']) === false) { console.error('You need to specify the video id to remove from your redundancies.\n') program.outputHelp() process.exit(-1) } - const videoId = parseInt(options[ 'video' ] + '', 10) + const videoId = parseInt(options['video'] + '', 10) let redundancies = await listVideoRedundanciesData(url, accessToken, 'my-videos') let videoRedundancy = redundancies.find(r => videoId === r.id) diff --git a/server/tools/peertube-repl.ts b/server/tools/peertube-repl.ts index ab6e215d9..7c936ae0d 100644 --- a/server/tools/peertube-repl.ts +++ b/server/tools/peertube-repl.ts @@ -1,6 +1,4 @@ import { registerTSPaths } from '../helpers/register-ts-paths' -registerTSPaths() - import * as repl from 'repl' import * as path from 'path' import * as _ from 'lodash' @@ -23,6 +21,8 @@ import * as signupUtils from '../helpers/signup' import * as utils from '../helpers/utils' import * as YoutubeDLUtils from '../helpers/youtube-dl' +registerTSPaths() + const start = async () => { await initDatabaseModels(true) @@ -31,22 +31,39 @@ const start = async () => { const initContext = (replServer) => { return (context) => { const properties = { - context, repl: replServer, env: process.env, - lodash: _, path, - uuidv1, uuidv3, uuidv4, uuidv5, - cli, logger, constants, - Sequelize, sequelizeTypescript, modelsUtils, - models: sequelizeTypescript.models, transaction: sequelizeTypescript.transaction, - query: sequelizeTypescript.query, queryInterface: sequelizeTypescript.getQueryInterface(), + context, + repl: replServer, + env: process.env, + lodash: _, + path, + uuidv1, + uuidv3, + uuidv4, + uuidv5, + cli, + logger, + constants, + Sequelize, + sequelizeTypescript, + modelsUtils, + models: sequelizeTypescript.models, + transaction: sequelizeTypescript.transaction, + query: sequelizeTypescript.query, + queryInterface: sequelizeTypescript.getQueryInterface(), YoutubeDL, - coreUtils, ffmpegUtils, peertubeCryptoUtils, signupUtils, utils, YoutubeDLUtils + coreUtils, + ffmpegUtils, + peertubeCryptoUtils, + signupUtils, + utils, + YoutubeDLUtils } - for (let prop in properties) { + for (const prop in properties) { Object.defineProperty(context, prop, { configurable: false, enumerable: true, - value: properties[ prop ] + value: properties[prop] }) } } diff --git a/server/tools/peertube-upload.ts b/server/tools/peertube-upload.ts index f604c9bee..8de952e7b 100644 --- a/server/tools/peertube-upload.ts +++ b/server/tools/peertube-upload.ts @@ -24,14 +24,14 @@ command getServerCredentials(command) .then(({ url, username, password }) => { - if (!program[ 'videoName' ] || !program[ 'file' ]) { - if (!program[ 'videoName' ]) console.error('--video-name is required.') - if (!program[ 'file' ]) console.error('--file is required.') + if (!program['videoName'] || !program['file']) { + if (!program['videoName']) console.error('--video-name is required.') + if (!program['file']) console.error('--file is required.') process.exit(-1) } - if (isAbsolute(program[ 'file' ]) === false) { + if (isAbsolute(program['file']) === false) { console.error('File path should be absolute.') process.exit(-1) } @@ -41,25 +41,26 @@ getServerCredentials(command) process.exit(-1) }) }) + .catch(err => console.error(err)) async function run (url: string, username: string, password: string) { const accessToken = await getAccessToken(url, username, password) - await access(program[ 'file' ], constants.F_OK) + await access(program['file'], constants.F_OK) - console.log('Uploading %s video...', program[ 'videoName' ]) + console.log('Uploading %s video...', program['videoName']) const videoAttributes = await buildVideoAttributesFromCommander(url, program) Object.assign(videoAttributes, { - fixture: program[ 'file' ], - thumbnailfile: program[ 'thumbnail' ], - previewfile: program[ 'preview' ] + fixture: program['file'], + thumbnailfile: program['thumbnail'], + previewfile: program['preview'] }) try { await uploadVideo(url, accessToken, videoAttributes) - console.log(`Video ${program[ 'videoName' ]} uploaded.`) + console.log(`Video ${program['videoName']} uploaded.`) process.exit(0) } catch (err) { console.error(require('util').inspect(err)) diff --git a/server/tools/peertube-watch.ts b/server/tools/peertube-watch.ts index 9ac1d05f9..5f7d1bb07 100644 --- a/server/tools/peertube-watch.ts +++ b/server/tools/peertube-watch.ts @@ -29,16 +29,10 @@ program console.log(' $ peertube watch https://peertube.cpy.re/videos/watch/e8a1af4e-414a-4d58-bfe6-2146eed06d10') console.log() }) - .action((url, cmd) => { - run(url, cmd) - .catch(err => { - console.error(err) - process.exit(-1) - }) - }) + .action((url, cmd) => run(url, cmd)) .parse(process.argv) -async function run (url: string, program: any) { +function run (url: string, program: any) { if (!url) { console.error(' positional argument is required.') process.exit(-1) diff --git a/server/tools/peertube.ts b/server/tools/peertube.ts index 9883bbf05..88dd5f7f6 100644 --- a/server/tools/peertube.ts +++ b/server/tools/peertube.ts @@ -1,13 +1,12 @@ #!/usr/bin/env node +/* eslint-disable no-useless-escape */ + import { registerTSPaths } from '../helpers/register-ts-paths' registerTSPaths() import * as program from 'commander' -import { - version, - getSettings -} from './cli' +import { getSettings, version } from './cli' program .version(version, '-v, --version') @@ -26,14 +25,15 @@ program /* Not Yet Implemented */ program - .command('diagnostic [action]', - 'like couple therapy, but for your instance', - { noHelp: true } as program.CommandOptions - ).alias('d') + .command( + 'diagnostic [action]', + 'like couple therapy, but for your instance', + { noHelp: true } as program.CommandOptions + ).alias('d') .command('admin', - 'manage an instance where you have elevated rights', - { noHelp: true } as program.CommandOptions - ).alias('a') + 'manage an instance where you have elevated rights', + { noHelp: true } as program.CommandOptions + ).alias('a') // help on no command if (!process.argv.slice(2).length) { @@ -82,3 +82,4 @@ getSettings() }) .parse(process.argv) }) + .catch(err => console.error(err)) -- cgit v1.2.3