Skip to content

Commit

Permalink
Splitting controllers & updating config
Browse files Browse the repository at this point in the history
  • Loading branch information
MKHenson committed Mar 13, 2017
1 parent e9a59f7 commit e54d2fc
Show file tree
Hide file tree
Showing 4 changed files with 420 additions and 315 deletions.
301 changes: 3 additions & 298 deletions src/controllers/bucket-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { Controller } from './controller'
import { BucketManager } from '../bucket-manager';
import * as multiparty from 'multiparty';
import * as compression from 'compression';
import * as winston from 'winston';
import { CommsController } from '../socket-api/comms-controller';
import { ClientInstruction } from '../socket-api/client-instruction';
import { ClientInstructionType } from '../socket-api/socket-event-types';
Expand All @@ -23,16 +22,16 @@ import { BucketModel } from '../models/bucket-model';
* Main class to use for managing users
*/
export class BucketController extends Controller {
private _config: users.IConfig;
private _config: Modepress.IConfig;
private _allowedFileTypes: Array<string>;

/**
* Creates an instance of the user manager
* @param e The express app
* @param The config options of this manager
*/
constructor( e: express.Express, config: users.IConfig ) {
super( [ Model.registerModel( BucketModel ) ]);
constructor( e: express.Express, config: Modepress.IConfig ) {
super( [ Model.registerModel( BucketModel ) ] );

this._config = config;

Expand All @@ -45,167 +44,15 @@ export class BucketController extends Controller {
router.use( bodyParser.json() );
router.use( bodyParser.json( { type: 'application/vnd.api+json' } ) );

router.get( '/files/:id/download', <any>[ this.getFile.bind( this ) ] );
router.get( '/users/:user/buckets/:bucket/files', <any>[ ownerRights, this.getFiles.bind( this ) ] );
router.get( '/users/:user/get-stats', <any>[ ownerRights, this.getStats.bind( this ) ] );
router.get( '/users/:user/buckets', <any>[ ownerRights, this.getBuckets.bind( this ) ] );
router.delete( '/buckets/:buckets', <any>[ requireUser, this.removeBuckets.bind( this ) ] );
router.delete( '/files/:files', <any>[ requireUser, this.removeFiles.bind( this ) ] );
router.post( '/buckets/:bucket/upload/:parentFile?', <any>[ requireUser, this.uploadUserFiles.bind( this ) ] );
router.post( '/users/:user/buckets/:name', <any>[ ownerRights, this.createBucket.bind( this ) ] );
router.post( '/create-stats/:target', <any>[ ownerRights, this.createStats.bind( this ) ] );
router.put( '/stats/storage-calls/:target/:value', <any>[ ownerRights, this.verifyTargetValue, this.updateCalls.bind( this ) ] );
router.put( '/stats/storage-memory/:target/:value', <any>[ ownerRights, this.verifyTargetValue, this.updateMemory.bind( this ) ] );
router.put( '/stats/storage-allocated-calls/:target/:value', <any>[ ownerRights, this.verifyTargetValue, this.updateAllocatedCalls.bind( this ) ] );
router.put( '/stats/storage-allocated-memory/:target/:value', <any>[ ownerRights, this.verifyTargetValue, this.updateAllocatedMemory.bind( this ) ] );
router.put( '/files/:file/rename-file', <any>[ requireUser, this.renameFile.bind( this ) ] );
router.put( '/files/:id/make-public', <any>[ requireUser, this.makePublic.bind( this ) ] );
router.put( '/files/:id/make-private', <any>[ requireUser, this.makePrivate.bind( this ) ] );

// Register the path
e.use( `${config.apiPrefix}`, router );
}

/**
* Makes sure the target user exists and the numeric value specified is valid
*/
private async verifyTargetValue( req: users.AuthRequest, res: express.Response, next: Function ) {
try {
// Set the content type
const value = parseInt( req.params.value );

if ( !req.params.target || req.params.target.trim() === '' )
throw new Error( 'Please specify a valid user to target' );

if ( !req.params.value || req.params.value.trim() === '' || isNaN( value ) )
throw new Error( 'Please specify a valid value' );

// Make sure the user exists
const user = await UserManager.get.getUser( req.params.target );

if ( !user )
throw new Error( `Could not find the user '${req.params.target}'` );

req._target = user;
next();

} catch ( err ) {
return errJson( err, res );
};
}

/**
* Updates the target user's api calls
*/
private async updateCalls( req: users.AuthRequest, res: express.Response ) {
try {
const value = parseInt( req.params.value );
const manager = BucketManager.get;
await manager.updateStorage( req._target.dbEntry.username!, <users.IStorageStats>{ apiCallsUsed: value } );
okJson<def.IResponse>( { message: `Updated the user API calls to [${value}]`, error: false }, res );

} catch ( err ) {
return errJson( err, res );
};
}

/**
* Updates the target user's memory usage
*/
private async updateMemory( req: users.AuthRequest, res: express.Response ) {
try {
const value = parseInt( req.params.value );
const manager = BucketManager.get;
await manager.updateStorage( req._target.dbEntry.username!, <users.IStorageStats>{ memoryUsed: value } );

okJson<def.IResponse>( { message: `Updated the user memory to [${value}] bytes`, error: false }, res );

} catch ( err ) {
return errJson( err, res );
};
}

/**
* Updates the target user's allocated api calls
*/
private async updateAllocatedCalls( req: users.AuthRequest, res: express.Response ) {
try {
const value = parseInt( req.params.value );
const manager = BucketManager.get;
await manager.updateStorage( req._target.dbEntry.username!, <users.IStorageStats>{ apiCallsAllocated: value } );
okJson<def.IResponse>( { message: `Updated the user API calls to [${value}]`, error: false }, res );

} catch ( err ) {
return errJson( err, res );
};
}

/**
* Updates the target user's allocated memory
*/
private async updateAllocatedMemory( req: users.AuthRequest, res: express.Response ) {
try {
const value = parseInt( req.params.value );
const manager = BucketManager.get;
await manager.updateStorage( req._target.dbEntry.username!, <users.IStorageStats>{ memoryAllocated: value } );
okJson<def.IResponse>( { message: `Updated the user memory to [${value}] bytes`, error: false }, res );

} catch ( err ) {
return errJson( err, res );
};
}

/**
* Removes files specified in the URL
*/
private async removeFiles( req: users.AuthRequest, res: express.Response ) {
try {
const manager = BucketManager.get;
let files: Array<string>;

if ( !req.params.files || req.params.files.trim() === '' )
throw new Error( 'Please specify the files to remove' );

files = req.params.files.split( ',' );
const filesRemoved = await manager.removeFilesByIdentifiers( files, req._user!.dbEntry.username );

okJson<users.IRemoveFiles>( {
message: `Removed [${filesRemoved.length}] files`,
error: false,
data: filesRemoved,
count: filesRemoved.length
}, res );

} catch ( err ) {
return errJson( err, res );
};
}

/**
* Renames a file
*/
private async renameFile( req: users.AuthRequest, res: express.Response ) {
try {
const manager = BucketManager.get;

if ( !req.params.file || req.params.file.trim() === '' )
throw new Error( 'Please specify the file to rename' );
if ( !req.body || !req.body.name || req.body.name.trim() === '' )
throw new Error( 'Please specify the new name of the file' );

const fileEntry = await manager.getFile( req.params.file, req._user!.dbEntry.username );

if ( !fileEntry )
throw new Error( `Could not find the file '${req.params.file}'` );

await manager.renameFile( fileEntry, req.body.name );
okJson<def.IResponse>( { message: `Renamed file to '${req.body.name}'`, error: false }, res );

} catch ( err ) {
return errJson( err, res );
};
}

/**
* Removes buckets specified in the URL
*/
Expand Down Expand Up @@ -233,134 +80,6 @@ export class BucketController extends Controller {
};
}

/**
* Fetches the statistic information for the specified user
*/
private async getStats( req: users.AuthRequest, res: express.Response ) {
try {
const manager = BucketManager.get;
const stats = await manager.getUserStats( req._user!.dbEntry.username );

return okJson<users.IGetUserStorageData>( {
message: `Successfully retrieved ${req._user!.dbEntry.username}'s stats`,
error: false,
data: stats
}, res );

} catch ( err ) {
return errJson( err, res );
};
}

/**
* Attempts to download a file from the server
*/
private async getFile( req: users.AuthRequest, res: express.Response ) {
try {
const manager = BucketManager.get;
const fileID = req.params.id;
let file: users.IFileEntry;
const cache = this._config.google.bucket.cacheLifetime;

if ( !fileID || fileID.trim() === '' )
throw new Error( `Please specify a file ID` );

file = await manager.getFile( fileID );
res.setHeader( 'Content-Type', file.mimeType! );
res.setHeader( 'Content-Length', file.size!.toString() );
if ( cache )
res.setHeader( 'Cache-Control', 'public, max-age=' + cache );

manager.downloadFile( <express.Request><Express.Request>req, res, file );
manager.incrementAPI( file.user! );

} catch ( err ) {
winston.error( err.toString(), { process: process.pid } );
return res.status( 404 ).send( 'File not found' );
}
}

/**
* Attempts to make a file public
*/
private async makePublic( req: users.AuthRequest, res: express.Response ) {
try {
const manager = BucketManager.get;
const fileID = req.params.id;

if ( !fileID || fileID.trim() === '' )
throw new Error( `Please specify a file ID` );

let fileEntry = await manager.getFile( fileID, req._user!.dbEntry.username );
fileEntry = await manager.makeFilePublic( fileEntry );

okJson<users.IGetFile>( { message: `File is now public`, error: false, data: fileEntry }, res );

} catch ( err ) {
return errJson( err, res );
}
}

/**
* Attempts to make a file private
*/
private async makePrivate( req: users.AuthRequest, res: express.Response ) {
try {
const manager = BucketManager.get;
const fileID = req.params.id;
let fileEntry: users.IFileEntry;

if ( !fileID || fileID.trim() === '' )
throw new Error( `Please specify a file ID` );

fileEntry = await manager.getFile( fileID, req._user!.dbEntry.username );
fileEntry = await manager.makeFilePrivate( fileEntry )

okJson<users.IGetFile>( { message: `File is now private`, error: false, data: fileEntry }, res );

} catch ( err ) {
return errJson( err, res );
}
}

/**
* Fetches all file entries from the database. Optionally specifying the bucket to fetch from.
*/
private async getFiles( req: users.AuthRequest, res: express.Response ) {
const manager = BucketManager.get;
const index = parseInt( req.query.index );
const limit = parseInt( req.query.limit );
let bucketEntry: users.IBucketEntry | null;
let searchTerm: RegExp | undefined;

try {
if ( !req.params.bucket || req.params.bucket.trim() === '' )
throw new Error( 'Please specify a valid bucket name' );

// Check for keywords
if ( req.query.search )
searchTerm = new RegExp( req.query.search, 'i' );

bucketEntry = await manager.getIBucket( req.params.bucket, req._user!.dbEntry.username );

if ( !bucketEntry )
throw new Error( `Could not find the bucket '${req.params.bucket}'` );

const count = await manager.numFiles( { bucketId: bucketEntry.identifier } );
const files = await manager.getFilesByBucket( bucketEntry, index, limit, searchTerm );

return okJson<users.IGetFiles>( {
message: `Found [${count}] files`,
error: false,
data: files,
count: count
}, res );

} catch ( err ) {
return errJson( err, res );
};
}

/**
* Fetches all bucket entries from the database
*/
Expand Down Expand Up @@ -388,20 +107,6 @@ export class BucketController extends Controller {
};
}

/**
* Creates a new user stat entry. This is usually done for you when creating a new user
*/
private async createStats( req: users.AuthRequest, res: express.Response ) {
try {
const manager = BucketManager.get;
await manager.createUserStats( req.params.target );
okJson<users.IResponse>( { message: `Stats for the user '${req.params.target}' have been created`, error: false }, res );

} catch ( err ) {
return errJson( err, res );
};
}

private alphaNumericDashSpace( str: string ): boolean {
if ( !str.match( /^[0-9A-Z _\-]+$/i ) )
return false;
Expand Down
Loading

0 comments on commit e54d2fc

Please sign in to comment.