Skip to content

Commit

Permalink
Internal: Changed app interface. Improved errors handling. App linked…
Browse files Browse the repository at this point in the history
…. Updated README.MD
  • Loading branch information
SlawekGreczyn committed Jun 19, 2018
1 parent 00a3307 commit 1aa4399
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 47 deletions.
23 changes: 12 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,21 @@
- npm@v4

### Installation
npm install
npm install easy-image-cli

### Usage
node index.js upload -p /User/Admin/images/ -u http://example.com/upload/ -t http://example.com/token/ --output images.json
easy-image-cli upload /User/Admin/images/ http://example.com/upload/ -t http://example.com/token/ --output images.json

### Options
-p, --path <filePath> Path to file or directory
-e, --environment <environment> Environment id
-k, --key <key> Access key
-u, --uploadUrl <url> Upload URL
-t, --tokenUrl <url> Token URL
-o, --output <path> Path to the file where result should be saved
-h, --help output usage information
easy-image-cli upload <filePath> <uploadUrl> [options]

Options:

-e, --environment <environment> Environment id
-k, --key <key> Access key
-t, --tokenUrl <url> Token URL
-o, --output <path> Path to the file where result should be saved
-h, --help output usage information

Warning: tokenUrl or environment id with key must be passed.
62 changes: 38 additions & 24 deletions commands/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

'use strict';

const CliProgress = require( 'cli-progress' );
const { Bar: ProgressBar, Presets: CliProgressPresets } = require( 'cli-progress' );

const fs = require( 'fs' );
const Path = require( 'path' );
Expand All @@ -13,22 +13,23 @@ const AuthHelpers = require( './../helpers/authhelpers' );
const RequestHelpers = require( './../helpers/requesthelpers' );

const ALLOWED_IMAGES_FORMATS = [ 'png', 'jpeg', 'jpg', 'bmp', 'tiff', 'webp', 'gif' ];
const MAX_IMAGE_SIZE = 100000000;

/**
* CLI method which allows to upload images to easy-image
*/
class UploadCommand {
/**
* @param {Object} cmd
* @param {String} cmd.path
* @param {String} cmd.environment
* @param {String} cmd.key
* @param {String} cmd.uploadUrl
* @param {String} cmd.tokenUrl
* @param {String} cmd.output
* @param {String} path
* @param {String} uploadUrl
* @param {Object} args
* @param {String} args.environment
* @param {String} args.key
* @param {String} args.tokenUrl
* @param {String} args.output
*/
constructor( cmd ) {
const { path, environment, key, uploadUrl, tokenUrl, output } = cmd;
constructor( path, uploadUrl, args ) {
const { environment, key, tokenUrl, output } = args;

/**
* @type {String}
Expand Down Expand Up @@ -66,19 +67,15 @@ class UploadCommand {
*/
this._output = output;

if ( !fs.existsSync( this._path ) ) {
throw new Error( 'Path doesn\'t exist.' );
}

if ( !this._uploadUrl ) {
throw new Error( 'Upload url must be provided.' );
if ( !!this._path && !fs.existsSync( this._path ) ) {
throw new Error( `Path doesn\'t exist: ${ this._path }` );
}

if ( !this._tokenUrl && !this._accessKey ) {
throw new Error( 'Token or accessKey must be provided.' );
}

if ( !this._tokenUrl && key && !this._environment ) {
if ( !this._tokenUrl && this._accessKey && !this._environment ) {
throw new Error( 'Environment must be provided.' );
}
}
Expand All @@ -91,6 +88,7 @@ class UploadCommand {
async execute() {
const token = await AuthHelpers.createToken( this._environment, this._accessKey, this._tokenUrl );

const errors = [];
let files = [];

if ( fs.lstatSync( this._path ).isFile() ) {
Expand All @@ -102,18 +100,28 @@ class UploadCommand {
}

files = files.filter( file => {
return _validateImageFormat( file );
if ( _validateImage( file ) ) {
return true;
} else {
errors.push( new Error( `"Not allowed file format or the file is too big." for file "${ file }"` ) );

return false;
}
} );

const result = {};

const progress = new CliProgress.Bar( {}, CliProgress.Presets.shades_classic );
const progress = new ProgressBar( {}, CliProgressPresets.shades_classic );

progress.start( files.length, 0 );

for ( let [ index, filePath ] of files.entries() ) {
result[ filePath ] = await this._upload( filePath, token, this._uploadUrl );
progress.update( index + 1 );
try {
result[ filePath ] = await this._upload( filePath, token, this._uploadUrl );
progress.update( index + 1 );
} catch ( error ) {
errors.push( new Error( `"${ error.message}" for file "${ filePath}"` ) )
}
}

progress.stop();
Expand All @@ -122,7 +130,7 @@ class UploadCommand {
_saveToJSONFile( result, this._output );
}

return result;
return { result, errors };
}

/**
Expand Down Expand Up @@ -177,15 +185,21 @@ function _scanDirectorySync( path, fileList = [] ) {
}

/**
* Returns true if extension of file is supported by easy image and false if not.
* Returns true if extension of file is supported by easy image and size of the file is less or equal than limit and false if not.
*
* @param {String} imagePath
* @return {Boolean}
* @private
*/
function _validateImageFormat( imagePath ) {
function _validateImage( imagePath ) {
const file = Path.parse( imagePath );

const { size: fileSize } = fs.statSync( imagePath );

if ( fileSize > MAX_IMAGE_SIZE ) {
return false;
}

return ALLOWED_IMAGES_FORMATS.includes( file.ext.toLowerCase().replace( '.', '' ) );
}

Expand Down
9 changes: 7 additions & 2 deletions helpers/authhelpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,14 @@ class AuthHelpers {
static async _getTokenFromTokenUrl( tokenUrl ) {
let { data, statusCode } = await RequestHelpers.get( tokenUrl, {} );

if ( statusCode >= 400 ) {
if ( statusCode >= 400 && statusCode < 500 ) {
const response = JSON.parse( data );
throw new Error( response );

throw new Error( `Fetching token from url error: "${response.message}"` );
}

if ( statusCode >= 500 ) {
throw new Error( 'Token URL is invalid.' );
}

return data.toString();
Expand Down
27 changes: 17 additions & 10 deletions index.js
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#!/usr/bin/env node

/*
Copyright (c) 2016-2018, CKSource - Frederico Knabben. All rights reserved.
*/
Expand All @@ -10,31 +12,35 @@ const app = require( 'commander' );

const UploadCommand = require( './commands/upload' );

app.command( 'upload' )
app.command( 'upload <filePath> <uploadUrl>' )
.description( 'Uploads files to system' )
.option( '-p, --path <filePath>', 'Path to file or directory' )
.option( '-e, --environment <environment>', 'Environment id' )
.option( '-k, --key <key>', 'Access key' )
.option( '-u, --uploadUrl <url>', 'Upload URL' )
.option( '-t, --tokenUrl <url>', 'Token URL' )
.option( '-o, --output <path>', 'Path to the file where result should be saved' )
.action( async cmd => {
.action( async ( filePath, uploadUrl, cmd ) => {
try {
const upload = new UploadCommand( cmd );
const upload = new UploadCommand( filePath, uploadUrl, cmd );

const result = await upload.execute();
const { result, errors } = await upload.execute();
_printDataToStdOut( result, '========= Addresses ========= \n' );

for ( const error of errors ) {
_printError( error.message );
}
} catch ( error ) {
_printError( error.message );
}
} );

app.action( () => console.error(
colors.red( '----------\nEasyImage CLI\n----------\nCommand doesn\'t exist. \nCheck --help for list of commands.\n' )
) );
app.action( () => app.commands[ 0 ].help() );

app.parse( process.argv );

if ( !app.args.length ) {
app.commands[ 0 ].help();
}

/**
* Prints error in console.
*
Expand All @@ -53,5 +59,6 @@ function _printError( message ) {
* @private
*/
function _printDataToStdOut( data, description = '' ) {
process.stdout.write( `${colors.green( description )}${JSON.stringify( data, null, '\t' )}${'\n'}` );
process.stderr.write( colors.green( description ) );
process.stdout.write( `${ JSON.stringify( data, null, '\t' ) }${'\n'}` );
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
"license": "ISC",
"author": "CKSource",
"scripts": {},
"preferGlobal": true,
"bin": "./index.js",
"dependencies": {
"cli-progress": "^2.0.0",
"colors": "^1.3.0",
Expand Down

0 comments on commit 1aa4399

Please sign in to comment.