Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extensions! #146

Open
wants to merge 4 commits into
base: v3.0.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 55 additions & 5 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,22 @@
* @property {string} mime - MIME type of this file
*/

const {UnifileError} = require('./error.js');
/**
* Signature of a plugin function
* @typedef {function} PluginAction
* @param {string|Buffer} input - Data entering the plugin, either from the client or the service
* @return {string|Buffer} the transformed input data
*/

/**
* Representation of a plugin
* @typedef {Object} plugin
* @property {PluginAction} [onWrite] - Action when the client writes in the service
* @property {PluginAction} [onRead] - Action when the client reads from the service
*/

const {UnifileError} = require('./error.js');
const {Transform} = require('stream');
/**
* Tells if a method needs authentification
* @param {string} methodName - Name of the method to test
Expand All @@ -88,6 +102,17 @@ function isAuthentifiedFunction(methodName) {
'stat', 'batch'].includes(methodName);
}

const HOOKS = {
ON_READ: 'onRead',
ON_READSTREAM: 'onReadStream',
ON_WRITE: 'onWrite',
ON_WRITESTREAM: 'onWriteStream'
};

const applyPlugin = (plugin, content) => {
return plugin ? plugin(content) : content;
};

const connectors = Symbol('connectors');

/**
Expand All @@ -105,6 +130,7 @@ class Unifile {
*/
constructor() {
this[connectors] = new Map();
this.plugins = {};
}

/**
Expand All @@ -118,6 +144,17 @@ class Unifile {
this[connectors].set(connector.name.toLowerCase(), connector);
}

/**
* Adds an extension into Unifile.
* The plugin actions will be applied for all the connectors.
* @param {Plugin} plugin - A plugin with at least one hook implemented
*/
ext(plugin) {
Object.values(HOOKS).forEach((hook) => {
if(plugin.hasOwnProperty(hook)) this.plugins[hook] = plugin[hook];
});
}

// Infos commands

/**
Expand Down Expand Up @@ -236,7 +273,8 @@ class Unifile {
* @return {external:Promise<null>} an empty promise.
*/
writeFile(session, connectorName, path, content) {
return this.callMethod(connectorName, session, 'writeFile', path, content);
const input = applyPlugin(this.plugins[HOOKS.ON_WRITE], content);
return this.callMethod(connectorName, session, 'writeFile', path, input);
}

/**
Expand All @@ -247,7 +285,13 @@ class Unifile {
* @return {external:WritableStream} a writable stream into the file
*/
createWriteStream(session, connectorName, path) {
return this.callMethod(connectorName, session, 'createWriteStream', path);
const content = this.callMethod(connectorName, session, 'createWriteStream', path);
const plugin = this.plugins[HOOKS.ON_WRITESTREAM];
if(plugin instanceof Transform) {
plugin.pipe(content);
return plugin;
}
return content;
}

/**
Expand All @@ -258,7 +302,8 @@ class Unifile {
* @return {external:Promise<string>} a promise of the content of the file
*/
readFile(session, connectorName, path) {
return this.callMethod(connectorName, session, 'readFile', path);
return this.callMethod(connectorName, session, 'readFile', path)
.then((content) => applyPlugin(this.plugins[HOOKS.ON_READ], content));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

here maybe the plugins should have a ON_BEFORE_READ in order to change the paths and possibly the session and connectorName

}

/**
Expand All @@ -269,7 +314,12 @@ class Unifile {
* @return {external:ReadableStream} a readable stream from the file
*/
createReadStream(session, connectorName, path) {
return this.callMethod(connectorName, session, 'createReadStream', path);
const content = this.callMethod(connectorName, session, 'createReadStream', path);
const plugin = this.plugins[HOOKS.ON_READSTREAM];
if(plugin instanceof Transform) {
return content.pipe(plugin);
}
return content;
}

/**
Expand Down
56 changes: 56 additions & 0 deletions samples/extensions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
'use strict';

const fs = require('fs');
const crypto = require('crypto');

const Unifile = require('../lib/');
const unifile = new Unifile();

const PWD = 'a password';

const cipher = crypto.createCipher('aes192', PWD);
const decipher = crypto.createDecipher('aes192', PWD);

// Configure connectors
const dbxconnector = new Unifile.DropboxConnector({
clientId: '37mo489tld3rdi2',
clientSecret: 'kqfzd11vamre6xr',
redirectUri: 'http://localhost:6805/dropbox/oauth-callback'
});

// Register connectors
unifile.use(dbxconnector);

const session = {};

// Register extensions
unifile.ext({
onRead: (input) => {
console.log(input.toString('utf8'));
let decrypted = decipher.update(input.toString('utf8'), 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
},
onWrite: (input) => {
let encrypted = cipher.update(input, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
});

if(process.argv.length <= 2) {
console.log('Usage: ' + __filename + ' FILE_PATH');
process.exit(-1);
}

const param = process.argv[2];
const input = fs.readFileSync(param);

unifile.setAccessToken(session, 'dropbox', process.env.DROPBOX_TOKEN);

unifile.writeFile(session, 'dropbox', '/encrypted.txt', input)
.then(() => {
return unifile.readFile(session, 'dropbox', '/encrypted.txt');
})
.then((content) => console.log(`Content is ${content}`));

99 changes: 98 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

const PassThrough = require('stream').PassThrough;
const {Readable, Writable, Transform, PassThrough} = require('stream');
const chai = require('chai');
chai.use(require('chai-as-promised'));
const Promise = require('bluebird');
Expand Down Expand Up @@ -82,6 +82,103 @@ describe('Unifile class', function() {
});
});

describe('ext()', function() {
let unifile;
let inMemoryFile = '';
beforeEach('Instanciation', function() {
inMemoryFile = '';
unifile = new Unifile();
unifile.use({
name: 'memory',
getInfos: () => {return {isLoggedIn: true};},
readFile: (session, path) => Promise.resolve(inMemoryFile),
writeFile: (session, path, content) => {
inMemoryFile = content;
return Promise.resolve();
},
createReadStream: (session, path) => {
return new Readable({
read(size) {
this.push('hello');
this.push(null);
}
});
},
createWriteStream: (session, path) => {
//return require('fs').createWriteStream('./test.log');
return new Writable({
write(chunk, encoding, callback) {
inMemoryFile += chunk.toString();
callback(null);
}
});
}
});
});

it('registers an extension', function() {
unifile.ext({
onWrite: console.log,
onRead: console.log
});
expect(unifile.plugins.onRead).to.equal(console.log);
expect(unifile.plugins.onWrite).to.equal(console.log);
});

it('can modify the input on write action', function() {
unifile.ext({
onWrite: (input) => input.replace('a', 'b')
});
return unifile.writeFile({}, 'memory', '', 'ab')
.then(() => expect(inMemoryFile).to.equal('bb'));
});

it('can modify the input on read action', function() {
inMemoryFile = 'ab';
unifile.ext({
onRead: (input) => input.replace('b', 'a')
});
return unifile.readFile({}, 'memory', '')
.should.eventually.equal('aa');
});

it('can modify the input on write stream', function(done) {
unifile.ext({
onWriteStream: new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().toUpperCase());
}
})
});
const stream = unifile.createWriteStream({}, 'memory', '');
stream.on('end', () => {
expect(inMemoryFile).to.equal('HELLO');
done();
});
stream.end('hello');
});

it('can modify the input on read stream', function(done) {
inMemoryFile = 'hello';
unifile.ext({
onReadStream: new Transform({
transform(chunk, encoding, callback) {
callback(null, chunk.toString().toUpperCase());
}
})
});
const stream = unifile.createReadStream({}, 'memory', '');
const chunks = [];
stream.on('data', (chunk) => {
chunks.push(chunk);
});
stream.on('end', () => {
expect(Buffer.concat(chunks).toString()).to.equal('HELLO');
done();
});
});
});

describe('getInfos()', function() {
let unifile;
beforeEach('Instanciation', function() {
Expand Down