<commit_before>'use strict';

var fs = require('fs');
var async = require('async');
var ics = require('ics-parser');
var Anyfetch = require('anyfetch');

function generateIdentifier(baseIdentifier, event) {
  var identifier = event.type;

  if(event.uid) {
    identifier = event.uid;
  }
  else {
    if(event.summary) {
      identifier += "-" + event.summary;
    }
    if(event.start) {
      identifier += "-" + event.start;
    }
    if(event.end) {
      identifier += "-" + event.end;
    }
  }

  return baseIdentifier + " - " + (new Buffer(identifier).toString('base64'));
}

module.exports = function(path, document, changes, finalCb) {
  fs.readFile(path, function(err, data) {
    if(err) {
      finalCb(err);
    }
    var events = ics(data.toString());

    var anyfetch = new Anyfetch(document.access_token);
    anyfetch.setApiUrl(finalCb.apiUrl);

    async.each(events, function(event, cb) {
      if(event.type === "VEVENT") {
        var eventDocument = {
          document_type: "event",
          creation_date: document.creation_date,
          identifier: generateIdentifier(document.identifier, event),
          metadata: {}
        };

        if(event.geo) {
          event.geolocation = event.geo.latitude + ";" + event.geo.longitude;
        }

        ['startDate', 'endDate', 'name', 'description', 'attendee', 'location', 'geolocation'].forEach(function(param) {
          if(event[param]) {
            eventDocument.metadata[param] = event[param];
          }
        });

        anyfetch.postDocument(eventDocument, cb);
      }
      else {
        cb();
      }
    },
    function(err) {
      if(err) {
        return finalCb(err);
      }
      anyfetch.deleteDocumentByIdentifier(document.identifier, function(err) {
        finalCb(err, null);
      });
    });
  });
};
<commit_msg>Copying preivous document actions onto document<commit_after>'use strict';

var fs = require('fs');
var async = require('async');
var ics = require('ics-parser');
var Anyfetch = require('anyfetch');

function generateIdentifier(baseIdentifier, event) {
  var identifier = event.type;

  if(event.uid) {
    identifier = event.uid;
  }
  else {
    if(event.summary) {
      identifier += "-" + event.summary;
    }
    if(event.start) {
      identifier += "-" + event.start;
    }
    if(event.end) {
      identifier += "-" + event.end;
    }
  }

  return baseIdentifier + " - " + (new Buffer(identifier).toString('base64'));
}

module.exports = function(path, document, changes, finalCb) {
  fs.readFile(path, function(err, data) {
    if(err) {
      finalCb(err);
    }
    var events = ics(data.toString());

    var anyfetch = new Anyfetch(document.access_token);
    anyfetch.setApiUrl(finalCb.apiUrl);

    async.each(events, function(event, cb) {
      if(event.type === "VEVENT") {
        var eventDocument = {
          document_type: "event",
          actions: document.actions,
          creation_date: document.creation_date,
          identifier: generateIdentifier(document.identifier, event),
          metadata: {}
        };

        if(event.geo) {
          event.geolocation = event.geo.latitude + ";" + event.geo.longitude;
        }

        ['startDate', 'endDate', 'name', 'description', 'attendee', 'location', 'geolocation'].forEach(function(param) {
          if(event[param]) {
            eventDocument.metadata[param] = event[param];
          }
        });

        anyfetch.postDocument(eventDocument, cb);
      }
      else {
        cb();
      }
    },
    function(err) {
      if(err) {
        return finalCb(err);
      }
      anyfetch.deleteDocumentByIdentifier(document.identifier, function(err) {
        finalCb(err, null);
      });
    });
  });
};
<|endoftext|>


<commit_before>// Load modules

var Os = require('os');
var Path = require('path');
var Handlebars = require('handlebars');
var Hapi = require('hapi');
var Hoek = require('hoek');
var Url = require('url');
var Ws = require('ws');

// Declare internals

var internals = {};

internals.defaults = {
    endpoint: '/debug/console',
    queryKey: 'debug',
    template: 'index',
    host: undefined,
    port: 0
};

exports.register = function (server, options, next) {

    var settings = Hoek.applyToDefaults(internals.defaults, options);

    server.views({
        engines: { html: { module: Handlebars } },
        path: Path.join(__dirname, '../templates')
    });

    server.route({
        method: 'GET',
        path: settings.endpoint + '/{file*2}',
        config: {
            handler: {
                directory: {
                    path: Path.join(__dirname, '../public'),
                    listing: false,
                    index: false
                }
            },
            plugins: {
                lout: false
            }
        }
    });

    var subscribers = {};                                                   // Map: debug session -> [ subscriber ]
    var tv = new Hapi.Server();
    tv.connection({ host: settings.host, port: settings.port});

    tv.start(function () {

        var ws = new Ws.Server({ server: tv.listener });
        ws.on('connection', function (socket) {

            var subscriptions = {};

            socket.on('message', function (rawMessage) {
                var message = rawMessage.split(':');
                var action = message[0];
                var channel = message[1];

                if (action === 'subscribe') {
                    // only add socket to subscribers if no existing subscription found for socket
                    if (subscriptions[channel] === undefined) {
                        subscribers[channel] = subscribers[channel] || [];
                        subscribers[channel].push(socket);

                        subscriptions[channel] = subscribers[channel].length - 1;   // index of socket in subscribers array
                    }
                }

                if (action === 'unsubscribe') {
                    subscribers[channel].splice(subscriptions[channel], 1);
                    delete subscriptions[channel];
                }
            });
        });

        var host = settings.publicHost || settings.host || tv.info.host;
        if (host === '0.0.0.0') {
            host = Os.hostname();
        }

        server.route({
            method: 'GET',
            path: settings.endpoint,
            config: {
                auth: false,                        // In case defaults are set otherwise
                handler: function (request, reply) {

                    var context = {
                        endpoint: settings.endpoint,
                        host: host,
                        port: tv.info.port
                    };

                    return reply.view(settings.template, context);
                },
                plugins: {
                    lout: false
                }
            }
        });

        server.ext('onRequest', function (request, reply) {

            if (request.plugins.tv && request.plugins.tv.debugId) {

                var key = settings.queryKey;

                delete request.query[key];
                delete request.url.search;
                delete request.url.query[key];

                request.setUrl(Url.format(request.url));
            }

            return reply.continue();
        });

        var onLog = function (request, event, tags) {

            var transmit = function (key) {

                var subs = subscribers[key];
                if (!subs) {
                    return;
                }

                var valid = [];
                for (var i = 0, il = subs.length; i < il; ++i) {
                    try {
                        if (subs[i].readyState === Ws.OPEN) {
                            subs[i].send(JSON.stringify(event, null, 4));
                            valid.push(subs[i]);
                        }
                    }
                    catch (err) { }
                }

                subscribers[key] = valid;                         // Removes subscriber on any send error
            };

            var session = request.plugins.tv && request.plugins.tv.debugId;
            if (session) {
                transmit(session);
            }

            transmit('*');
        };

        server.on('request', onLog);
        server.on('request-internal', function(request, event, tags) {

            var key = settings.queryKey;
            if (tags.received && request.query[key] && !request.plugins.tv) {            // first internal event has tag received: true
                request.plugins.tv = { debugId: request.query[key] };
            }

            onLog(request, event, tags);
        });
        server.on('response', function (request) {

            var event = {
                timestamp: Date.now(),
                request: request.id,
                server: request.connection.info.uri,
                response: true,
                data: {
                    statusCode: request.response.statusCode,
                    payload: request.response.variety === 'plain' ? request.response.source : null
                }
            };

            onLog(request, event);
        });

        return next();
    });
};

exports.register.attributes = {
    pkg: require('../package.json')
};
<commit_msg>Remove extra whitespace<commit_after>// Load modules

var Os = require('os');
var Path = require('path');
var Handlebars = require('handlebars');
var Hapi = require('hapi');
var Hoek = require('hoek');
var Url = require('url');
var Ws = require('ws');

// Declare internals

var internals = {};

internals.defaults = {
    endpoint: '/debug/console',
    queryKey: 'debug',
    template: 'index',
    host: undefined,
    port: 0
};

exports.register = function (server, options, next) {

    var settings = Hoek.applyToDefaults(internals.defaults, options);

    server.views({
        engines: { html: { module: Handlebars } },
        path: Path.join(__dirname, '../templates')
    });

    server.route({
        method: 'GET',
        path: settings.endpoint + '/{file*2}',
        config: {
            handler: {
                directory: {
                    path: Path.join(__dirname, '../public'),
                    listing: false,
                    index: false
                }
            },
            plugins: {
                lout: false
            }
        }
    });

    var subscribers = {};                                                   // Map: debug session -> [ subscriber ]
    var tv = new Hapi.Server();
    tv.connection({ host: settings.host, port: settings.port});

    tv.start(function () {

        var ws = new Ws.Server({ server: tv.listener });
        ws.on('connection', function (socket) {

            var subscriptions = {};

            socket.on('message', function (rawMessage) {
                var message = rawMessage.split(':');
                var action = message[0];
                var channel = message[1];

                if (action === 'subscribe') {
                    // only add socket to subscribers if no existing subscription found for socket
                    if (subscriptions[channel] === undefined) {
                        subscribers[channel] = subscribers[channel] || [];
                        subscribers[channel].push(socket);

                        subscriptions[channel] = subscribers[channel].length - 1;   // index of socket in subscribers array
                    }
                }

                if (action === 'unsubscribe') {
                    subscribers[channel].splice(subscriptions[channel], 1);
                    delete subscriptions[channel];
                }
            });
        });

        var host = settings.publicHost || settings.host || tv.info.host;
        if (host === '0.0.0.0') {
            host = Os.hostname();
        }

        server.route({
            method: 'GET',
            path: settings.endpoint,
            config: {
                auth: false,                        // In case defaults are set otherwise
                handler: function (request, reply) {

                    var context = {
                        endpoint: settings.endpoint,
                        host: host,
                        port: tv.info.port
                    };

                    return reply.view(settings.template, context);
                },
                plugins: {
                    lout: false
                }
            }
        });

        server.ext('onRequest', function (request, reply) {

            if (request.plugins.tv && request.plugins.tv.debugId) {

                var key = settings.queryKey;

                delete request.query[key];
                delete request.url.search;
                delete request.url.query[key];

                request.setUrl(Url.format(request.url));
            }

            return reply.continue();
        });

        var onLog = function (request, event, tags) {

            var transmit = function (key) {

                var subs = subscribers[key];
                if (!subs) {
                    return;
                }

                var valid = [];
                for (var i = 0, il = subs.length; i < il; ++i) {
                    try {
                        if (subs[i].readyState === Ws.OPEN) {
                            subs[i].send(JSON.stringify(event, null, 4));
                            valid.push(subs[i]);
                        }
                    }
                    catch (err) { }
                }

                subscribers[key] = valid;                         // Removes subscriber on any send error
            };

            var session = request.plugins.tv && request.plugins.tv.debugId;
            if (session) {
                transmit(session);
            }

            transmit('*');
        };

        server.on('request', onLog);
        server.on('request-internal', function(request, event, tags) {

            var key = settings.queryKey;
            if (tags.received && request.query[key] && !request.plugins.tv) {            // first internal event has tag received: true
                request.plugins.tv = { debugId: request.query[key] };
            }

            onLog(request, event, tags);
        });
        server.on('response', function (request) {

            var event = {
                timestamp: Date.now(),
                request: request.id,
                server: request.connection.info.uri,
                response: true,
                data: {
                    statusCode: request.response.statusCode,
                    payload: request.response.variety === 'plain' ? request.response.source : null
                }
            };

            onLog(request, event);
        });

        return next();
    });
};

exports.register.attributes = {
    pkg: require('../package.json')
};
<|endoftext|>


<commit_before>'use strict';

var cbox = global.$cbox;

// Strategies
var FacebookStrategy = require('passport-facebook').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

// Models
var ObjectID = require('mongodb').ObjectID;
// var User = require('../../models/user');

var credentials = require('./credentials');

module.exports = function() {
    var passport = cbox.passport;

    // serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user._id);
    });

    // deserialize the user
    passport.deserializeUser(function(id, done) {
        var users = cbox.db.collection('users');
        users.findOne({'_id': ObjectID.createFromHexString(id)}, function(err, user) {
            done(err, user);
        });
    });

    // Google
    passport.use(new GoogleStrategy({

        clientID: credentials.google.clientID,
        callbackURL: credentials.google.callbackURL,
        clientSecret: credentials.google.clientSecret

    }, function(accessToken, refreshToken, profile, done) {

        // asynchronous
        process.nextTick(function() {
            var users = cbox.db.collection('users');
            users.findOne({'google.id': profile.id}, function(err, user) {
                if (err) { return done(err); }

                if (user) {
                    return done(null, user);
                } else {
                    var google = profile._json;
                    google.token = accessToken;

                    users.insert({ google: google }, {w:1}, function(err, result) {
                        if (err) { throw err; }
                        return done(null, result[0]);
                    });
                }
            });
        });

    }));

    // Facebook
    passport.use(new FacebookStrategy({

        clientID: credentials.facebook.clientID,
        callbackURL: credentials.facebook.callbackURL,
        clientSecret: credentials.facebook.clientSecret,
        profileFields: ['displayName', 'photos', 'name', 'email']

    }, function(accessToken, refreshToken, profile, done) {

        // asynchronous
        process.nextTick(function() {
            var users = cbox.db.collection('users');
            users.findOne({'facebook.id': profile.id}, function(err, user) {
                if (err) {
                    return done(err);
                }

                if (user) {
                    return done(null, user);
                } else {
                    var facebook = profile._json;
                    facebook.token = accessToken;

                    users.insert({ facebook: facebook }, {w:1}, function(err, result) {
                        if (err) { throw err; }
                        return done(null, result[0]);
                    });
                }
            });
        });
    }));
};
<commit_msg>add friends scope to facebook request<commit_after>'use strict';

var cbox = global.$cbox;

// Strategies
var FacebookStrategy = require('passport-facebook').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

// Models
var ObjectID = require('mongodb').ObjectID;
// var User = require('../../models/user');

var credentials = require('./credentials');

module.exports = function() {
    var passport = cbox.passport;

    // serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user._id);
    });

    // deserialize the user
    passport.deserializeUser(function(id, done) {
        var users = cbox.db.collection('users');
        users.findOne({'_id': ObjectID.createFromHexString(id)}, function(err, user) {
            done(err, user);
        });
    });

    // Google
    passport.use(new GoogleStrategy({

        clientID: credentials.google.clientID,
        callbackURL: credentials.google.callbackURL,
        clientSecret: credentials.google.clientSecret

    }, function(accessToken, refreshToken, profile, done) {

        // asynchronous
        process.nextTick(function() {
            var users = cbox.db.collection('users');
            users.findOne({'google.id': profile.id}, function(err, user) {
                if (err) { return done(err); }

                if (user) {
                    return done(null, user);
                } else {
                    var google = profile._json;
                    google.token = accessToken;

                    users.insert({ google: google }, {w:1}, function(err, result) {
                        if (err) { throw err; }
                        return done(null, result[0]);
                    });
                }
            });
        });

    }));

    // Facebook
    passport.use(new FacebookStrategy({

        clientID: credentials.facebook.clientID,
        callbackURL: credentials.facebook.callbackURL,
        clientSecret: credentials.facebook.clientSecret,
        profileFields: ['displayName', 'photos', 'name', 'email', 'friends']

    }, function(accessToken, refreshToken, profile, done) {

        // asynchronous
        process.nextTick(function() {
            var users = cbox.db.collection('users');
            users.findOne({'facebook.id': profile.id}, function(err, user) {
                if (err) {
                    return done(err);
                }

                if (user) {
                    return done(null, user);
                } else {
                    var facebook = profile._json;
                    facebook.token = accessToken;

                    users.insert({ facebook: facebook }, {w:1}, function(err, result) {
                        if (err) { throw err; }
                        return done(null, result[0]);
                    });
                }
            });
        });
    }));
};
<|endoftext|>


<commit_before>var fs = require("fs"),
	path = require("path");

function createWebViewer(app){
	app.all("*", function(req, res, next){
		if (!req.query.path) {
			res.sendStatus(404);
			return;
		}
		req.query.path = path.normalize(req.query.path);
		next();
	});

	app.get("/view", function(req, res, next){
		// basic information
		res.locals.path = req.query.path;
		res.locals.dirname = path.dirname(req.query.path),
		res.locals.basename = path.basename(req.query.path);

		// read parent dir, get prev, next
		if (res.locals.dirname == req.query.path) {
			next();
			return;
		}
		fs.readdir(res.locals.dirname, function(err, files){
			if (err) {
				next();
				return;
			}
			var i = files.indexOf(res.locals.basename);

			res.locals.prev = files[i - 1];
			res.locals.next = files[i + 1];

			next();
		});
	}, function(req, res, next) {
		// get stats
		fs.stat(req.query.path, function(err, stat){
			if (err) {
				res.sendStatus(404);
				return;
			}
			res.locals.isFile = stat.isFile();
			next();
		});
	}, function(req, res, next) {
		// get dir info
		if (res.locals.isFile) {
			res.locals.files = [res.locals.basename];
			next();
			return;
		}
		fs.readdir(req.query.path, function(err, files) {
			if (err) {
				res.sendStatus(500);
				return;
			}
			var i, promises = [];
			for (i = 0; i < files.length; i++) {
				promises.push(getStats(path.join(res.locals.path, files[i]), {
					name: files[i],
					isFile: null
				}));
			}
			Promise.all(promises).then(function(values){
				var files = [], dirs = [], i;
				for (i = 0; i < values.length; i++) {
					if (values[i].isFile) {
						files.push(values[i].name);
					} else {
						dirs.push(values[i].name);
					}
				}
				res.locals.files = files;
				res.locals.dirs = dirs;
				next();
			});
		});
	});

	app.get("/src", function(req, res) {
		fs.stat(req.query.path, function(err, stat){
			if (err || !stat.isFile()) {
				res.sendStatus(404);
			} else {
				res.sendFile(req.query.path);
			}
		});
	});

	function getStats(fn, file) {
		return new Promise(function(resolve, reject){
			fs.stat(fn, function(err, stat){
				if (err) {
					file.isFile = stat.isFile()
				}
				resolve(file);
			});
		});
	}

	return app;
}

module.export = createWebViewer;
<commit_msg>Sort array with fnCmp<commit_after>var fs = require("fs"),
	path = require("path");

function strCmp(a, b) {
	return a < b ? -1 : a > b;
}

function fnCmp(a, b) {
	var ma = a.match(/\d+|\D+/g),
		mb = b.match(/\d+|\D+/g);

	var i, nanA = Number.isNaN(+ma[0][0]), nanB = Number.isNaN(+mb[0][0]), diff, q;
	if (nanA ^ nanB) {
		return strCmp(a, b);
	}
	if (diff = ma.length - mb.length) {
		return diff;
	}
	if (nanA) {
		q = 1;
	} else {
		q = 0;
	}
	for (i = 0; i < ma.length; i++) {
		if (i % 2 == q) {
			if (diff = ma[i] - mb[i]) {
				return diff;
			}
		} else {
			if (diff = strCmp(ma[i], mb[i])) {
				return diff;
			}
		}
	}
}

function createWebViewer(app){
	app.all("*", function(req, res, next){
		if (!req.query.path) {
			res.sendStatus(404);
			return;
		}
		req.query.path = path.normalize(req.query.path);
		next();
	});

	app.get("/view", function(req, res, next){
		// basic information
		var curr = res.locals.curr = {
			dir: path.dirname(req.query.path),
			full: req.query.path,
			name: path.basename(req.query.path)
		};

		// read parent dir, get prev, next
		if (curr.dir == curr.full) {
			// under drive
			next();
			return;
		}
		fs.readdir(curr.dir, function(err, files){
			if (err) {
				next();
				return;
			}

			files.sort(fnCmp);

			var i = files.indexOf(curr.name),
				p = files[i - 1],
				n = files[i + 1];

			res.locals.prev = p && {
				full: path.join(curr.dir, p),
				name: p
			};

			res.locals.next = n && {
				full: path.join(curr.dir, n),
				name: n
			};

			next();
		});
	}, function(req, res, next) {
		// get stats
		fs.stat(res.locals.curr.full, function(err, stat){
			if (err) {
				res.sendStatus(404);
				return;
			}
			res.locals.isFile = stat.isFile();
			next();
		});
	}, function(req, res, next) {
		// get dir info
		if (res.locals.isFile) {
			res.locals.files = [res.locals.curr];
			res.locals.dirs = [];
			next();
			return;
		}
		fs.readdir(res.locals.curr.full, function(err, files) {
			if (err) {
				res.sendStatus(500);
				return;
			}

			files.sort(fnCmp);

			var i, promises = [];
			for (i = 0; i < files.length; i++) {
				promises.push(getStats({
					name: files[i],
					full: path.join(res.locals.curr.full, files[i]),
					isFile: null
				}));
			}
			Promise.all(promises).then(function(values){
				var files = [], dirs = [], i;
				for (i = 0; i < values.length; i++) {
					if (values[i].isFile) {
						files.push(values[i]);
					} else {
						dirs.push(values[i]);
					}
				}
				res.locals.files = files;
				res.locals.dirs = dirs;
				next();
			});
		});
	});

	app.get("/src", function(req, res) {
		fs.stat(req.query.path, function(err, stat){
			if (err || !stat.isFile()) {
				res.sendStatus(404);
			} else {
				res.sendFile(req.query.path);
			}
		});
	});

	function getStats(file) {
		return new Promise(function(resolve, reject){
			fs.stat(file.full, function(err, stat){
				if (!err) {
					file.isFile = stat.isFile();
				}
				resolve(file);
			});
		});
	}

	return app;
}

module.exports = createWebViewer;
<|endoftext|>


<commit_before>var express     = require('express')
  , Promise     = require('bluebird')
  , bodyParser  = require('body-parser')
  , config      = require('config')
  , _           = require('underscore')
  , Repository  = require('./git/repository')
  ;

var app = express();

app.use(bodyParser.json());

app.post('/blob', function(req, res, next){
  var remote          = req.body.remote   //|| 'https://github.com/a7medkamel/taskmill-core-agent.git'
    , branch          = req.body.branch   || 'master' // todo [akamel] not used
    , filename        = req.body.filename //|| 'lib/core/worker.js'
    , token           = req.body.token
    ;

  var repo = Repository.get(remote);

  repo
    .updatedAt()
    .then((at) => {
      console.log('blob', 'at', repo.id, at);
      if (!at || Date.now - at > config.get('ttl')) {
        return repo.pull({ token : token }).then(() => Date.now);
      }

      return at;
    })
    .then((at) => {
      return [ at, repo.acl({ token : token }) ];
    })
    .spread((at, repository) => {
      // todo [akamel] this can leak repo existance, mask with 'file not found'
      return repo
              .stat(filename)
              .then((stat) => {
                if (stat.rawsize > 1024 /* 1kb */ * 10) {
                  throw new Error('file is larger than 10kb limit');
                }

                if (stat.isBinary) {
                  throw new Error('file is binary');
                }
                return [ at, stat, repository ];
              });
    })
    .spread((at, stat, repository) => {
      return repo
              .cat(filename)
              .then((data) => {
                res.send({
                    stat        : stat
                  , repository  : _.omit(repository, '_id', 'token')
                  , updatedAt   : at
                  , content     : data
                });
              });
    })
    .catch(function(err){
      console.error(err);
      res.status(400).send({ message : err.message });
    });
});

app.post('/pull', function(req, res, next){
  var remote          = req.body.remote
    , token           = req.body.token
    ;

  var repo = Repository.get(remote);

  repo
    .updatedAt()
    .then((at) => {
      console.log('pull', 'at', repo.id, at);
      if (at) {
        return repo.pull({ token : token });
      }
    })
    .then(() => {
      res.send({ message : 'OK' });
    })
    .catch(function(err){
      console.error(err);
      res.status(400).send({ message : err.message });
    });
});

app.post('/ls', function(req, res, next){
  var remote          = req.body.remote
    , token           = req.body.token
    ;

  var repo = Repository.get(remote);

  repo
    .updatedAt()
    .then((at) => {
      console.log('ls', 'at', repo.id, at);
      if (!at) {
        return repo.pull({ token : token }).then(() => at);
      }

      return at;
    })
    .tap(() => {
      return repo.acl({ token : token });
    })
    .then((at) => {
      return repo
              .ls()
              .then((result) => {
                return {
                    updatedAt : at
                  , data      : result.data
                }
              });
    })
    .then((result) => {
      res.send(result);
    })
    .catch(function(err){
      console.error(err);
      res.status(400).send({ message : err.message });
    });
});

function listen(options, cb) {
    Promise
      .promisify(app.listen, { context : app})(options.port)
      .tap(function(){
      console.log('codedb started and listeing to:', options.port);
    })
    .nodeify(cb);
}

module.exports = {
    listen : listen
};<commit_msg>return more info in blob<commit_after>var express     = require('express')
  , Promise     = require('bluebird')
  , bodyParser  = require('body-parser')
  , config      = require('config')
  , _           = require('underscore')
  , Repository  = require('./git/repository')
  ;

var app = express();

app.use(bodyParser.json());

app.post('/blob', function(req, res, next){
  var remote          = req.body.remote   //|| 'https://github.com/a7medkamel/taskmill-core-agent.git'
    , branch          = req.body.branch   || 'master' // todo [akamel] not used
    , filename        = req.body.filename //|| 'lib/core/worker.js'
    , token           = req.body.token
    ;

  var repo = Repository.get(remote);

  repo
    .updatedAt()
    .then((at) => {
      console.log('blob', 'at', repo.id, at);
      if (!at || Date.now - at > config.get('ttl')) {
        return repo.pull({ token : token }).then(() => Date.now);
      }

      return at;
    })
    .then((at) => {
      return [ at, repo.acl({ token : token }) ];
    })
    .spread((at, repository) => {
      // todo [akamel] this can leak repo existance, mask with 'file not found'
      return repo
              .stat(filename)
              .then((stat) => {
                if (stat.rawsize > 1024 /* 1kb */ * 10) {
                  throw new Error('file is larger than 10kb limit');
                }

                if (stat.isBinary) {
                  throw new Error('file is binary');
                }
                return [ at, stat, repository ];
              });
    })
    .spread((at, stat, repository) => {
      return repo
              .cat(filename)
              .then((data) => {
                res.send({
                    stat        : stat
                  , repository  : _.omit(repository, '_id', 'token')
                  // todo [akamel] add branch and path to ls as well...
                  , branch      : branch
                  , path        : filename[0] === '/'? filename : '/' + filename
                  , updatedAt   : at
                  , content     : data
                });
              });
    })
    .catch(function(err){
      console.error(err);
      res.status(400).send({ message : err.message });
    });
});

app.post('/pull', function(req, res, next){
  var remote          = req.body.remote
    , token           = req.body.token
    ;

  var repo = Repository.get(remote);

  repo
    .updatedAt()
    .then((at) => {
      console.log('pull', 'at', repo.id, at);
      if (at) {
        return repo.pull({ token : token });
      }
    })
    .then(() => {
      res.send({ message : 'OK' });
    })
    .catch(function(err){
      console.error(err);
      res.status(400).send({ message : err.message });
    });
});

app.post('/ls', function(req, res, next){
  var remote          = req.body.remote
    , token           = req.body.token
    ;

  var repo = Repository.get(remote);

  repo
    .updatedAt()
    .then((at) => {
      console.log('ls', 'at', repo.id, at);
      if (!at) {
        return repo.pull({ token : token }).then(() => at);
      }

      return at;
    })
    .tap(() => {
      return repo.acl({ token : token });
    })
    .then((at) => {
      return repo
              .ls()
              .then((result) => {
                return {
                    updatedAt : at
                  , data      : result.data
                }
              });
    })
    .then((result) => {
      res.send(result);
    })
    .catch(function(err){
      console.error(err);
      res.status(400).send({ message : err.message });
    });
});

function listen(options, cb) {
    Promise
      .promisify(app.listen, { context : app})(options.port)
      .tap(function(){
      console.log('codedb started and listeing to:', options.port);
    })
    .nodeify(cb);
}

module.exports = {
    listen : listen
};<|endoftext|>


<commit_before>/*jshint esversion: 6 */
var async = require('async');
var Web3 = require('web3');
var fs = require('fs');
var grunt = require('grunt');
var mkdirp = require('mkdirp');
var colors = require('colors');
var chokidar = require('chokidar');

var Cmd = require('./cmd.js');
var Deploy = require('./deploy.js');
var ContractsManager = require('./contracts.js');
var ABIGenerator = require('./abi.js');
var TemplateGenerator = require('./template_generator.js');
var Blockchain = require('./blockchain.js');
var Server = require('./server.js');
var Watch = require('./watch.js');
var Pipeline = require('./pipeline.js');
var Test = require('./test.js');
var Logger = require('./logger.js');
var Config = require('./config.js');
var Monitor = require('./monitor.js');
var ServicesMonitor = require('./services.js');
var Console = require('./console.js');
var IPFS = require('./ipfs.js');

var Embark = {

  process: function(args) {
    var cmd = new Cmd(Embark);
    cmd.process(args);
  },

  generateTemplate: function(templateName, destinationFolder, name) {
    var templateGenerator = new TemplateGenerator(templateName);
    templateGenerator.generate(destinationFolder, name);
  },

  initConfig: function(env, options) {
    this.config = new Config({env: env});
    this.config.loadConfigFiles(options);
    this.logger = new Logger({logLevel: 'debug'});

    //this.contractsManager = new ContractsManager(configDir, files, env);
    //this.contractsManager.init();
    //return this.contractsManager;
  },

  redeploy: function(env) {
    var self = this;
    async.waterfall([
      function reloadFiles(callback) {
        self.config.reloadConfig();
        callback();
      },
      self.buildDeployGenerate.bind(self)
    ], function(err, result) {
      self.logger.trace("finished".underline);
    });
  },

  run: function(options) {
    var self = this;
    var env = options.env;
    async.waterfall([
      function welcome(callback) {
        if (!options.useDashboard) {
          console.log('========================'.bold.green);
          console.log('Welcome to Embark 2.1.3'.yellow.bold);
          console.log('========================'.bold.green);
        }
        callback();
      },
      function startConsole(callback) {
        Embark.console = new Console();
        callback();
      },
      function startMonitor(callback) {
        if (!options.useDashboard) {
          return callback();
        }
        Embark.monitor = new Monitor({env: env, console: Embark.console});
        self.logger.logFunction = Embark.monitor.logEntry;
        self.logger.contractsState = Embark.monitor.setContracts;
        self.logger.availableServices = Embark.monitor.availableServices;
        self.logger.setStatus = Embark.monitor.setStatus.bind(Embark.monitor);
        // TODO: do this after monitor is rendered
        callback();
      },
      function monitorServices(callback) {
        if (!options.useDashboard) {
          return callback();
        }
        Embark.servicesMonitor = new ServicesMonitor({
          logger: Embark.logger,
          config: Embark.config,
          serverHost: options.serverHost,
          serverPort: options.serverPort,
          runWebserver: options.runWebserver
        });
        Embark.servicesMonitor.startMonitor();
        callback();
      },
      self.buildDeployGenerate.bind(self),
      function startAssetServer(callback) {
        if (!options.runWebserver) {
          return callback();
        }
        self.logger.setStatus("Starting Server");
        var server = new Server({
          logger: self.logger,
          host: options.serverHost,
          port: options.serverPort
        });
        server.start(callback);
      },
      function watchFilesForChanges(callback) {
        self.logger.setStatus("Watching for changes");
        var watch = new Watch({logger: self.logger});
        watch.start();
        watch.on('redeploy', function() {
          self.logger.info("received redeploy event");
          Embark.redeploy();
        });
        watch.on('rebuildAssets', function() {
          self.logger.info("received rebuildAssets event");
          // TODO: make this more efficient
          Embark.redeploy();
        });
        callback();
      }
    ], function(err, result) {
      self.logger.setStatus("Ready".green);
      self.logger.trace("finished".underline);
    });
  },

  build: function(env) {
    async.waterfall([
      function deployAndGenerateABI(callback) {
        Embark.deploy(function(abi) {
          callback(null, abi);
        });
      },
      function buildPipeline(abi, callback) {
        var pipeline = new Pipeline({});
        pipeline.build(abi);
        callback();
      }
    ], function(err, result) {
      self.logger.trace("finished".underline);
    });
  },

  blockchain: function(env, client) {
    var blockchain = Blockchain(this.config.blockchainConfig, client);
    blockchain.run({env: env});
  },

  buildAndDeploy: function(done) {
    var self = this;
    async.waterfall([
      function buildContracts(callback) {
        var contractsManager = new ContractsManager({
          contractFiles:  self.config.contractsFiles,
          contractsConfig: self.config.contractsConfig,
          logger: Embark.logger
        });
        contractsManager.build(callback);
      },
      function deployContracts(contractsManager, callback) {

        //TODO: figure out where to put this since the web3 can be passed along if needed
        // perhaps it should go into the deploy object itself
        // TODO: should come from the config object
        var web3 = new Web3();
        var web3Endpoint = 'http://' + self.config.blockchainConfig.rpcHost + ':' + self.config.blockchainConfig.rpcPort;
        web3.setProvider(new web3.providers.HttpProvider(web3Endpoint));

        if (!web3.isConnected()) {
          console.log(("Couldn't connect to " + web3Endpoint.underline + " are you sure it's on?").red);
          console.log("make sure you have an ethereum node or simulator running. e.g 'embark blockchain'".magenta);
          exit();
        }

        web3.eth.getAccounts(function(err, accounts) {
          web3.eth.defaultAccount = accounts[0];

          var deploy = new Deploy({
            web3: web3,
            contractsManager: contractsManager,
            logger: Embark.logger,
            chainConfig: self.config.chainTracker,
            env: self.config.env
          });
          deploy.deployAll(function() {
            callback(null, contractsManager);
          });
        });

      }
    ], function(err, result) {
      if (err) {
        done(err, null);
      } else {
        done(null, result);
      }
    });
  },

  deploy: function(done) {
    var self = this;
    async.waterfall([
      function buildAndDeploy(callback) {
        Embark.buildAndDeploy(function(contractsManager) {
          callback(null, contractsManager);
        });
      },
      function generateABI(contractsManager, callback) {
        var abiGenerator = new ABIGenerator(self.config.blockchainConfig, contractsManager);
        callback(null, abiGenerator.generateABI({useEmbarkJS: true}));
      }
    ], function(err, result) {
      done(result);
    });
  },

  buildDeployGenerate: function(done) {
    var self = this;

    self.logger.setStatus("Deploying...".magenta.underline);
    async.waterfall([
      function deployAndBuildContractsManager(callback) {
        Embark.buildAndDeploy(function(err, contractsManager) {
          if (err) {
            callback(err);
          } else {
            callback(null, contractsManager);
          }
        });
      },
      function generateConsoleABI(contractsManager, callback) {
        var abiGenerator = new ABIGenerator(self.config.blockchainConfig, contractsManager);
        var consoleABI = abiGenerator.generateABI({useEmbarkJS: false});
        Embark.console.runCode(consoleABI);
        callback(null, contractsManager);
      },
      function generateABI(contractsManager, callback) {
        var abiGenerator = new ABIGenerator(self.config.blockchainConfig, contractsManager);
        callback(null, abiGenerator.generateABI({useEmbarkJS: true}));
      },
      function buildPipeline(abi, callback) {
        self.logger.setStatus("Building Assets");
        var pipeline = new Pipeline({
          buildDir: self.config.buildDir,
          contractsFiles: self.config.contractsFiles,
          assetFiles: self.config.assetFiles,
          logger: self.logger
        });
        pipeline.build(abi);
        callback();
      }
    ], function(err, result) {
      if (err) {
        self.logger.error("error deploying");
        self.logger.error(err.message);
        self.logger.setStatus("Deployment Error".red);
      } else {
        self.logger.setStatus("Ready".green);
      }
      done(result);
    });
  },

  initTests: function(options) {
    return new Test(options);
  },

  // TODO: should deploy if it hasn't already
  ipfs: function() {
    var ipfs = new IPFS({buildDir: 'dist/'});
    ipfs.deploy();
  }

};

module.exports = Embark;

<commit_msg>return callback<commit_after>/*jshint esversion: 6 */
var async = require('async');
var Web3 = require('web3');
var fs = require('fs');
var grunt = require('grunt');
var mkdirp = require('mkdirp');
var colors = require('colors');
var chokidar = require('chokidar');

var Cmd = require('./cmd.js');
var Deploy = require('./deploy.js');
var ContractsManager = require('./contracts.js');
var ABIGenerator = require('./abi.js');
var TemplateGenerator = require('./template_generator.js');
var Blockchain = require('./blockchain.js');
var Server = require('./server.js');
var Watch = require('./watch.js');
var Pipeline = require('./pipeline.js');
var Test = require('./test.js');
var Logger = require('./logger.js');
var Config = require('./config.js');
var Monitor = require('./monitor.js');
var ServicesMonitor = require('./services.js');
var Console = require('./console.js');
var IPFS = require('./ipfs.js');

var Embark = {

  process: function(args) {
    var cmd = new Cmd(Embark);
    cmd.process(args);
  },

  generateTemplate: function(templateName, destinationFolder, name) {
    var templateGenerator = new TemplateGenerator(templateName);
    templateGenerator.generate(destinationFolder, name);
  },

  initConfig: function(env, options) {
    this.config = new Config({env: env});
    this.config.loadConfigFiles(options);
    this.logger = new Logger({logLevel: 'debug'});

    //this.contractsManager = new ContractsManager(configDir, files, env);
    //this.contractsManager.init();
    //return this.contractsManager;
  },

  redeploy: function(env) {
    var self = this;
    async.waterfall([
      function reloadFiles(callback) {
        self.config.reloadConfig();
        callback();
      },
      self.buildDeployGenerate.bind(self)
    ], function(err, result) {
      self.logger.trace("finished".underline);
    });
  },

  run: function(options) {
    var self = this;
    var env = options.env;
    async.waterfall([
      function welcome(callback) {
        if (!options.useDashboard) {
          console.log('========================'.bold.green);
          console.log('Welcome to Embark 2.1.3'.yellow.bold);
          console.log('========================'.bold.green);
        }
        callback();
      },
      function startConsole(callback) {
        Embark.console = new Console();
        callback();
      },
      function startMonitor(callback) {
        if (!options.useDashboard) {
          return callback();
        }
        Embark.monitor = new Monitor({env: env, console: Embark.console});
        self.logger.logFunction = Embark.monitor.logEntry;
        self.logger.contractsState = Embark.monitor.setContracts;
        self.logger.availableServices = Embark.monitor.availableServices;
        self.logger.setStatus = Embark.monitor.setStatus.bind(Embark.monitor);
        // TODO: do this after monitor is rendered
        callback();
      },
      function monitorServices(callback) {
        if (!options.useDashboard) {
          return callback();
        }
        Embark.servicesMonitor = new ServicesMonitor({
          logger: Embark.logger,
          config: Embark.config,
          serverHost: options.serverHost,
          serverPort: options.serverPort,
          runWebserver: options.runWebserver
        });
        Embark.servicesMonitor.startMonitor();
        callback();
      },
      self.buildDeployGenerate.bind(self),
      function startAssetServer(callback) {
        if (!options.runWebserver) {
          return callback();
        }
        self.logger.setStatus("Starting Server");
        var server = new Server({
          logger: self.logger,
          host: options.serverHost,
          port: options.serverPort
        });
        server.start(callback);
      },
      function watchFilesForChanges(callback) {
        self.logger.setStatus("Watching for changes");
        var watch = new Watch({logger: self.logger});
        watch.start();
        watch.on('redeploy', function() {
          self.logger.info("received redeploy event");
          Embark.redeploy();
        });
        watch.on('rebuildAssets', function() {
          self.logger.info("received rebuildAssets event");
          // TODO: make this more efficient
          Embark.redeploy();
        });
        callback();
      }
    ], function(err, result) {
      self.logger.setStatus("Ready".green);
      self.logger.trace("finished".underline);
    });
  },

  build: function(env) {
    async.waterfall([
      function deployAndGenerateABI(callback) {
        Embark.deploy(function(abi) {
          callback(null, abi);
        });
      },
      function buildPipeline(abi, callback) {
        var pipeline = new Pipeline({});
        pipeline.build(abi);
        callback();
      }
    ], function(err, result) {
      self.logger.trace("finished".underline);
    });
  },

  blockchain: function(env, client) {
    var blockchain = Blockchain(this.config.blockchainConfig, client);
    blockchain.run({env: env});
  },

  buildAndDeploy: function(done) {
    var self = this;
    async.waterfall([
      function buildContracts(callback) {
        var contractsManager = new ContractsManager({
          contractFiles:  self.config.contractsFiles,
          contractsConfig: self.config.contractsConfig,
          logger: Embark.logger
        });
        contractsManager.build(callback);
      },
      function deployContracts(contractsManager, callback) {

        //TODO: figure out where to put this since the web3 can be passed along if needed
        // perhaps it should go into the deploy object itself
        // TODO: should come from the config object
        var web3 = new Web3();
        var web3Endpoint = 'http://' + self.config.blockchainConfig.rpcHost + ':' + self.config.blockchainConfig.rpcPort;
        web3.setProvider(new web3.providers.HttpProvider(web3Endpoint));

        if (!web3.isConnected()) {
          console.log(("Couldn't connect to " + web3Endpoint.underline + " are you sure it's on?").red);
          console.log("make sure you have an ethereum node or simulator running. e.g 'embark blockchain'".magenta);
          exit();
        }

        web3.eth.getAccounts(function(err, accounts) {
          web3.eth.defaultAccount = accounts[0];

          var deploy = new Deploy({
            web3: web3,
            contractsManager: contractsManager,
            logger: Embark.logger,
            chainConfig: self.config.chainTracker,
            env: self.config.env
          });
          deploy.deployAll(function() {
            callback(null, contractsManager);
          });
        });

      }
    ], function(err, result) {
      if (err) {
        done(err, null);
      } else {
        done(null, result);
      }
    });
  },

  deploy: function(done) {
    var self = this;
    async.waterfall([
      function buildAndDeploy(callback) {
        Embark.buildAndDeploy(function(contractsManager) {
          callback(null, contractsManager);
        });
      },
      function generateABI(contractsManager, callback) {
        var abiGenerator = new ABIGenerator(self.config.blockchainConfig, contractsManager);
        callback(null, abiGenerator.generateABI({useEmbarkJS: true}));
      }
    ], function(err, result) {
      done(result);
    });
  },

  buildDeployGenerate: function(done) {
    var self = this;

    self.logger.setStatus("Deploying...".magenta.underline);
    async.waterfall([
      function deployAndBuildContractsManager(callback) {
        Embark.buildAndDeploy(function(err, contractsManager) {
          if (err) {
            return callback(err);
          }
          return callback(null, contractsManager);
        });
      },
      function generateConsoleABI(contractsManager, callback) {
        var abiGenerator = new ABIGenerator(self.config.blockchainConfig, contractsManager);
        var consoleABI = abiGenerator.generateABI({useEmbarkJS: false});
        Embark.console.runCode(consoleABI);
        callback(null, contractsManager);
      },
      function generateABI(contractsManager, callback) {
        var abiGenerator = new ABIGenerator(self.config.blockchainConfig, contractsManager);
        callback(null, abiGenerator.generateABI({useEmbarkJS: true}));
      },
      function buildPipeline(abi, callback) {
        self.logger.setStatus("Building Assets");
        var pipeline = new Pipeline({
          buildDir: self.config.buildDir,
          contractsFiles: self.config.contractsFiles,
          assetFiles: self.config.assetFiles,
          logger: self.logger
        });
        pipeline.build(abi);
        callback();
      }
    ], function(err, result) {
      if (err) {
        self.logger.error("error deploying");
        self.logger.error(err.message);
        self.logger.setStatus("Deployment Error".red);
      } else {
        self.logger.setStatus("Ready".green);
      }
      done(result);
    });
  },

  initTests: function(options) {
    return new Test(options);
  },

  // TODO: should deploy if it hasn't already
  ipfs: function() {
    var ipfs = new IPFS({buildDir: 'dist/'});
    ipfs.deploy();
  }

};

module.exports = Embark;

<|endoftext|>


<commit_before>exports = module.exports = function express(id) {
  var map = {
    'service': './service',
    'authenticator': './authenticator',
    //'authorizer': './authorizer',
    //'middleware/authenticate': './middleware/authenticate',
    //'middleware/authorize': './middleware/authorize'
  };

  var mid = map[id];
  if (mid) {
    return require(mid);
  }
};

exports.used = function(container) {
  // Register specs so objects can be auto-wired by interface.
  container.add('authenticator');
  //container.register('authorizer');
  //container.register('middleware/authenticate');
  //container.register('middleware/authorize');
}

exports.main = function(pre) {
  function _pre(IoC) {
    IoC.use('http', require('bixby-http'));
    IoC.use('http', exports);
    pre && pre(IoC);
  }

  function _post(IoC) {
    var service = IoC.create('http/service');
    var server = IoC.create('http/server');
    var logger = IoC.create('logger');
    var settings = IoC.create('settings');

    // Dispatch requests to the handler, which in this case is an Express app.
    server.on('request', service);

    var init = IoC.create('initializer');
    init.phase(require('./phases/listen')(service, server, logger, settings.get('http/server')));

    try {
      // If service discovery is available, add a phase to announce the
      // service(s) provided by the application.
      var registry = IoC.create('sd/registry');
      init.phase(require('./phases/announce')(registry, server, logger, settings.get('http/service')));
    } catch (_) {}
  }

  require('bixby').main(_pre, _post);
}
<commit_msg>Simplify spec manifest.<commit_after>exports = module.exports = {
  'authenticator': require('./authenticator')
};

exports.load = function(id) {
  try {
    return require('./' + id);
  } catch (ex) {
    if (ex.code == 'MODULE_NOT_FOUND') { return; }
    throw ex;
  }
};

exports.main = function(pre) {
  function _pre(IoC) {
    IoC.use('http', require('bixby-http'));
    IoC.use('http', exports);
    pre && pre(IoC);
  }

  function _post(IoC) {
    var service = IoC.create('http/service');
    var server = IoC.create('http/server');
    var logger = IoC.create('logger');
    var settings = IoC.create('settings');

    // Dispatch requests to the handler, which in this case is an Express app.
    server.on('request', service);

    var init = IoC.create('initializer');
    init.phase(require('./phases/listen')(service, server, logger, settings.get('http/server')));

    try {
      // If service discovery is available, add a phase to announce the
      // service(s) provided by the application.
      var registry = IoC.create('sd/registry');
      init.phase(require('./phases/announce')(registry, server, logger, settings.get('http/service')));
    } catch (_) {}
  }

  require('bixby').main(_pre, _post);
}
<|endoftext|>


<commit_before>import React from "react";
import {isDataURL} from "./utils";

class Cropper extends React.Component {

  constructor () {
    super();

    // getInitialState
    this.state = {
      dragging: false,
      image: {},
      mouse: {
        x: null,
        y: null
      },
      preview: null
    };

    // getDefaultProps
    this.defaultProps = {
      zoom: 1
    }
  }

  fitImageToCanvas (width, height) {
    var scaledHeight, scaledWidth;

    var canvasAspectRatio = this.props.height / this.props.width;
    var imageAspectRatio = height / width;

    if (canvasAspectRatio > imageAspectRatio) {
      scaledHeight = this.props.height;
      var scaleRatio = scaledHeight / height;
      scaledWidth = width * scaleRatio;
    } else {
      scaledWidth = this.props.width;
      var scaleRatio = scaledWidth / width;
      scaledHeight = height * scaleRatio;
    }

    return { width: scaledWidth, height: scaledHeight };
  }

  prepareImage (imageUri) {
    var img = new Image();
    if (!isDataURL(imageUri)) img.crossOrigin = 'anonymous';
    img.onload = () => {
      var scaledImage = this.fitImageToCanvas(img.width, img.height);
      scaledImage.resource = img;
      scaledImage.x = 0;
      scaledImage.y = 0;
      this.setState({dragging: false, image: scaledImage});
    }
    img.src = imageUri;
  }

  mouseDownListener (e) {
    this.setState({
      image: this.state.image,
      dragging: true,
      mouse: {
        x: null,
        y: null
      }
    });
  }

  preventSelection (e) {
    if (this.state.dragging) {
      e.preventDefault();
      return false;
    }
  }

  mouseUpListener (e) {
    this.setState({ dragging: false, preview: this.toDataURL() });
  }

  mouseMoveListener (e) {
    if (!this.state.dragging) return;

    var mouseX = e.clientX;
    var mouseY = e.clientY;
    var imageX = this.state.image.x;
    var imageY = this.state.image.y;

    var newImage = this.state.image;

    if (this.state.mouse.x && this.state.mouse.y) {
      var dx = this.state.mouse.x - mouseX;
      var dy = this.state.mouse.y - mouseY;

      var bounded = this.boundedCoords(imageX, imageY, dx, dy);

      newImage.x = bounded.x;
      newImage.y = bounded.y;
    }

    this.setState({
      image: this.state.image,
      mouse: {
        x: mouseX,
        y: mouseY
      }
    });
  }

  boundedCoords (x, y, dx, dy) {
    var newX = x - dx;
    var newY = y - dy;

    var scaledWidth = this.state.image.width * this.props.zoom;
    var dw = (scaledWidth - this.state.image.width) / 2;
    var imageLeftEdge = this.state.image.x - dw;
    var imageRightEdge = (imageLeftEdge + scaledWidth);

    var rightEdge = this.props.width;
    var leftEdge = 0;

    if (newX - dw > 0) { x = dw; }
    else if (newX < (-scaledWidth + rightEdge)) { x = rightEdge - scaledWidth; }
    else {
      x = newX;
    }

    var scaledHeight = this.state.image.height * this.props.zoom;
    var dh = (scaledHeight - this.state.image.height) / 2;
    var imageTopEdge = this.state.image.y - dh;
    var imageBottomEdge = imageTopEdge + scaledHeight;

    var bottomEdge = this.props.height
    var topEdge = 0;
    if (newY - dw > 0) { y = dh; }
    else if (newY < (-scaledHeight + bottomEdge)) { y = bottomEdge - scaledHeight; }
    else {
      y = newY;
    }

    return { x: x, y: y };
  }

  componentDidMount () {
    var canvas = React.findDOMNode(this.refs.canvas);
    var context = canvas.getContext("2d");
    this.prepareImage(this.props.image);
    window.addEventListener("mousemove", e => this.mouseMoveListener(e), false);
    window.addEventListener("mouseup", e => this.mouseUpListener(e), false);
    canvas.addEventListener("mousedown", e => this.mouseDownListener(e), false);
    document.onselectstart = e => this.preventSelection(e);
  }

  componentWillUnmount () {
    var canvas = React.findDOMNode(this.refs.canvas);
    window.removeEventListener("mousemove", this.mouseMoveListener);
    window.removeEventListener("mouseup", this.mouseMoveListener);
    canvas.removeEventListener("mousedown", this.mouseDownListener);
  }

  componentDidUpdate () {
    var context = React.findDOMNode(this.refs.canvas).getContext("2d");
    context.clearRect(0, 0, this.props.width, this.props.height);
    this.addImageToCanvas(context, this.state.image);
  }

  addImageToCanvas (context, image) {
    if (!image.resource) return;
    context.save();
    context.globalCompositeOperation = "destination-over";
    var scaledWidth = this.state.image.width * this.props.zoom;
    var scaledHeight = this.state.image.height * this.props.zoom;

    var x = image.x - (scaledWidth - this.state.image.width) / 2;
    var y = image.y - (scaledHeight - this.state.image.height) / 2;

    // need to make sure we aren't going out of bounds here...
    x = Math.min(x, 0);
    y = Math.min(y, 0);
    y = scaledHeight + y >= this.props.height ? y : (y + (this.props.height - (scaledHeight + y)));
    x = scaledWidth + x >= this.props.width ? x : (x + (this.props.width - (scaledWidth + x)));

    context.drawImage( image.resource, x, y, image.width * this.props.zoom, image.height * this.props.zoom);
    context.restore();
  }

  toDataURL () {
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");

    canvas.width = this.props.width;
    canvas.height = this.props.height;

    this.addImageToCanvas(context, {
      resource: this.state.image.resource,
      x: this.state.image.x,
      y: this.state.image.y,
      height: this.state.image.height,
      width: this.state.image.width
    });

    return canvas.toDataURL();
  }

  render () {
    return (

        <canvas
          ref="canvas"
          width={this.props.width}
          height={this.props.height}
        ></canvas>

        {this.state.preview &&

        }

    );
  }
};

class AvatarCropper extends React.Component {
  constructor () {
    super();
    this.state = {
      zoom: 1
    };
  }

  handleZoomUpdate () {
    var zoom = React.findDOMNode(this.refs.zoom).value;
    this.setState({ zoom: zoom });
  }

  render () {
    return (

        <Cropper
          image={this.props.image}
          width={this.props.width}
          height={this.props.height}
          zoom={this.state.zoom}
        />

        <input
          type="range"
          name="zoom"
          ref="zoom"
          onChange={this.handleZoomUpdate.bind(this)}
          min="1"
          max="3"
          step="0.01"
          defaultValue="1"
        />

    );
  }
}

export default AvatarCropper;
<commit_msg>dded proptypes validation to both components.<commit_after>import React from "react";
import {isDataURL} from "./utils";
import warning from "react/lib/warning";

var numberableType = (props, propName, componentName) => {
  warning(
    !isNaN(parseInt(props[propName])),
    `Invalid ${propName} '${props.size}' sent to '${componentName}'. Requires an
    int or string capable of conversion to an int. Check the render method of

    == '${componentName}'. ==

    `
  );
};

class Cropper extends React.Component {

  constructor () {
    super();

    // getInitialState
    this.state = {
      dragging: false,
      image: {},
      mouse: {
        x: null,
        y: null
      },
      preview: null
    };

  }

  fitImageToCanvas (width, height) {
    var scaledHeight, scaledWidth;

    var canvasAspectRatio = this.props.height / this.props.width;
    var imageAspectRatio = height / width;

    if (canvasAspectRatio > imageAspectRatio) {
      scaledHeight = this.props.height;
      var scaleRatio = scaledHeight / height;
      scaledWidth = width * scaleRatio;
    } else {
      scaledWidth = this.props.width;
      var scaleRatio = scaledWidth / width;
      scaledHeight = height * scaleRatio;
    }

    return { width: scaledWidth, height: scaledHeight };
  }

  prepareImage (imageUri) {
    var img = new Image();
    if (!isDataURL(imageUri)) img.crossOrigin = 'anonymous';
    img.onload = () => {
      var scaledImage = this.fitImageToCanvas(img.width, img.height);
      scaledImage.resource = img;
      scaledImage.x = 0;
      scaledImage.y = 0;
      this.setState({dragging: false, image: scaledImage});
    }
    img.src = imageUri;
  }

  mouseDownListener (e) {
    this.setState({
      image: this.state.image,
      dragging: true,
      mouse: {
        x: null,
        y: null
      }
    });
  }

  preventSelection (e) {
    if (this.state.dragging) {
      e.preventDefault();
      return false;
    }
  }

  mouseUpListener (e) {
    this.setState({ dragging: false, preview: this.toDataURL() });
  }

  mouseMoveListener (e) {
    if (!this.state.dragging) return;

    var mouseX = e.clientX;
    var mouseY = e.clientY;
    var imageX = this.state.image.x;
    var imageY = this.state.image.y;

    var newImage = this.state.image;

    if (this.state.mouse.x && this.state.mouse.y) {
      var dx = this.state.mouse.x - mouseX;
      var dy = this.state.mouse.y - mouseY;

      var bounded = this.boundedCoords(imageX, imageY, dx, dy);

      newImage.x = bounded.x;
      newImage.y = bounded.y;
    }

    this.setState({
      image: this.state.image,
      mouse: {
        x: mouseX,
        y: mouseY
      }
    });
  }

  boundedCoords (x, y, dx, dy) {
    var newX = x - dx;
    var newY = y - dy;

    var scaledWidth = this.state.image.width * this.props.zoom;
    var dw = (scaledWidth - this.state.image.width) / 2;
    var imageLeftEdge = this.state.image.x - dw;
    var imageRightEdge = (imageLeftEdge + scaledWidth);

    var rightEdge = this.props.width;
    var leftEdge = 0;

    if (newX - dw > 0) { x = dw; }
    else if (newX < (-scaledWidth + rightEdge)) { x = rightEdge - scaledWidth; }
    else {
      x = newX;
    }

    var scaledHeight = this.state.image.height * this.props.zoom;
    var dh = (scaledHeight - this.state.image.height) / 2;
    var imageTopEdge = this.state.image.y - dh;
    var imageBottomEdge = imageTopEdge + scaledHeight;

    var bottomEdge = this.props.height
    var topEdge = 0;
    if (newY - dw > 0) { y = dh; }
    else if (newY < (-scaledHeight + bottomEdge)) { y = bottomEdge - scaledHeight; }
    else {
      y = newY;
    }

    return { x: x, y: y };
  }

  componentDidMount () {
    var canvas = React.findDOMNode(this.refs.canvas);
    var context = canvas.getContext("2d");
    this.prepareImage(this.props.image);
    window.addEventListener("mousemove", e => this.mouseMoveListener(e), false);
    window.addEventListener("mouseup", e => this.mouseUpListener(e), false);
    canvas.addEventListener("mousedown", e => this.mouseDownListener(e), false);
    document.onselectstart = e => this.preventSelection(e);
  }

  componentWillUnmount () {
    var canvas = React.findDOMNode(this.refs.canvas);
    window.removeEventListener("mousemove", this.mouseMoveListener);
    window.removeEventListener("mouseup", this.mouseMoveListener);
    canvas.removeEventListener("mousedown", this.mouseDownListener);
  }

  componentDidUpdate () {
    var context = React.findDOMNode(this.refs.canvas).getContext("2d");
    context.clearRect(0, 0, this.props.width, this.props.height);
    this.addImageToCanvas(context, this.state.image);
  }

  addImageToCanvas (context, image) {
    if (!image.resource) return;
    context.save();
    context.globalCompositeOperation = "destination-over";
    var scaledWidth = this.state.image.width * this.props.zoom;
    var scaledHeight = this.state.image.height * this.props.zoom;

    var x = image.x - (scaledWidth - this.state.image.width) / 2;
    var y = image.y - (scaledHeight - this.state.image.height) / 2;

    // need to make sure we aren't going out of bounds here...
    x = Math.min(x, 0);
    y = Math.min(y, 0);
    y = scaledHeight + y >= this.props.height ? y : (y + (this.props.height - (scaledHeight + y)));
    x = scaledWidth + x >= this.props.width ? x : (x + (this.props.width - (scaledWidth + x)));

    context.drawImage( image.resource, x, y, image.width * this.props.zoom, image.height * this.props.zoom);
    context.restore();
  }

  toDataURL () {
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");

    canvas.width = this.props.width;
    canvas.height = this.props.height;

    this.addImageToCanvas(context, {
      resource: this.state.image.resource,
      x: this.state.image.x,
      y: this.state.image.y,
      height: this.state.image.height,
      width: this.state.image.width
    });

    return canvas.toDataURL();
  }

  render () {
    return (

        <canvas
          ref="canvas"
          width={this.props.width}
          height={this.props.height}
        ></canvas>

        {this.state.preview &&

        }

    );
  }
};
Cropper.propTypes = {
    image: React.PropTypes.string.isRequired,
    width: numberableType,
    height: numberableType,
    zoom: numberableType
};
Cropper.defaultProps = { width: 400, height: 400, zoom: 1 };

class AvatarCropper extends React.Component {
  constructor () {
    super();
    this.state = {
      zoom: 1
    };
  }

  handleZoomUpdate () {
    var zoom = React.findDOMNode(this.refs.zoom).value;
    this.setState({ zoom: zoom });
  }

  render () {
    return (

        <Cropper
          image={this.props.image}
          width={this.props.width}
          height={this.props.height}
          zoom={this.state.zoom}
        />

        <input
          type="range"
          name="zoom"
          ref="zoom"
          onChange={this.handleZoomUpdate.bind(this)}
          min="1"
          max="3"
          step="0.01"
          defaultValue="1"
        />

    );
  }
}

// The AvatarCropper Prop API
AvatarCropper.propTypes = {
  image: React.PropTypes.string.isRequired,
  width: numberableType,
  height: numberableType
};
AvatarCropper.defaultProps = { width: 400, height: 400 };

export default AvatarCropper;
<|endoftext|>


<commit_before>'use strict';

const env = process.env.NODE_ENV || 'development';
const config = require('./config.json')[env];

const defaults = {
    session: {
        secret: "i'm a teapot",
        proxy: true,
        secureCookie: true
    }
}

let sessionConfig = () => {
    let sessionOverrides = {};

    if (config.session) {
        sessionOverrides = config.session;
    }

    if (config.session_secret_env_variable) {
        sessionOverrides.secret = process.env[config.session_secret_env_variable];
    }

    return Object.assign(defaults.session, sessionOverrides);
}

let logFormat = () => {
    if (['development', 'test'].indexOf(env) > -1) {
        return 'dev';
    }
    else {
        return '[:date[iso]] :remote-addr - :remote-user ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"';
    }
};

module.exports = {
    session: sessionConfig(),
    logFormat: logFormat()
}
<commit_msg>Lets see if this fixes it on heroku?<commit_after>'use strict';

const env = process.env.NODE_ENV || 'development';
const config = require('./config.json')[env];

const defaults = {
    session: {
        secret: "i'm a teapot",
        proxy: false,
        secureCookie: true
    }
};

let sessionConfig = () => {
    let sessionOverrides = {};

    if (config.session) {
        sessionOverrides = config.session;
    }

    if (config.session_secret_env_variable) {
        sessionOverrides.secret = process.env[config.session_secret_env_variable];
    }

    return Object.assign(defaults.session, sessionOverrides);
};

let logFormat = () => {
    if (['development', 'test'].indexOf(env) > -1) {
        return 'dev';
    }
    else {
        return '[:date[iso]] :remote-addr - :remote-user ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"';
    }
};

module.exports = {
    session: sessionConfig(),
    logFormat: logFormat()
};
<|endoftext|>


<commit_before>var path = require('path');
var child = require('child_process');
var which = require('which');
var util = require('util');

var debug = util.debuglog('browser_process');

var browsers = {
  chrome: {
    type: 'chrome',
    paths: {
      darwin: [
        '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome',
      ],
      linux: [
        'google-chrome'
      ],
      win32: [
        process.env['LOCALAPPDATA'] + '\\Google\\Chrome\\Application\\chrome.exe',
        process.env['PROGRAMFILES'] + '\\Google\\Chrome\\Application\\chrome.exe',
        process.env['PROGRAMFILES(X86)'] + '\\Google\\Chrome\\Application\\chrome.exe',
      ],
    }[process.platform],
  },

  chromium: {
    type: 'chrome',
    paths: {
      darwin: [
        '/Applications/Chromium.app/Contents/MacOS/Chromium',
      ],
      linux: [
        'chromium-browser',
      ],
      win32: [
        process.env['LOCALAPPDATA'] + '\\Chromium\\Application\\chrome.exe',
        process.env['PROGRAMFILES'] + '\\Chromium\\Application\\chrome.exe',
        process.env['PROGRAMFILES(X86)'] + '\\Chromium\\Application\\chrome.exe',
      ]
    }[process.platform],
  },

  electron: {
    type: 'chrome',
    paths: {
      darwin: [
        'electron',
      ],
      linux: [
        'electron',
      ],
      win32: [
        'electron',
        'electron.cmd',
      ]
    }[process.platform],
  },
  firefox: {
    type: 'firefox',
    paths: {
      darwin: [
        '/Applications/Firefox.app/Contents/MacOS/Firefox',
      ],
      linux: [
        'firefox',
      ],
      win32: [
        process.env['LOCALAPPDATA'] + '\\Mozilla\ Firefox\\firefox.exe',
        process.env['PROGRAMFILES'] + '\\Mozilla\ Firefox\\firefox.exe',
        process.env['PROGRAMFILES(X86)'] + '\\Mozilla\ Firefox\\firefox.exe',
      ],
    }[process.platform],
  },
};

var browserOptions = {
  chrome: {
    debug: '--remote-debugging-port=',
    profile: '--user-data-dir=',
    window: '--new-window',
    private: '--incognito',
  },

  firefox: {
    debug: '--start-debugging-server',
    profile: '--profile',
    window: '--new-window',
    private: '--private',
  }
};

function type(command) {
  var basename = path.basename(command);

  var key = Object.keys(browsers).filter(function (key) {
    return browsers[key].paths.some(function (exename) {
      return basename === path.basename(exename);
    });
  })[0];

  if (key) {
    return browsers[key].type;
  }

  throw Error('Bad browser command ' + command);
}

module.exports.type = type;

function find(command, callback) {
  if (path.isAbsolute(command)) {
    return callback(null, command);
  }

  var browser = browsers[command];
  if (browser === undefined) {
    var error = new Error('Invalid browser command');
    return callback(error);
  }

  var done = false;
  browser.paths.forEach(function (exename) {
    which(exename, function (error, command) {
      if (error || done) {
        return;
      }

      done = true;
      callback(null, command);
    });
  });
}

module.exports.find = find;

function options(command, options) {
  var browserType = type(command);
  var args = [];

  var keys = Object.keys(options);
  keys.forEach(function (key) {
    var value = options[key];

    if (value !== undefined) {
      var option = browserOptions[browserType][key];

      if (key === 'url') {
        args.push(value);
      } else if (option.match(/\S=$/)) {
        args.push(option + value);
      } else if (value === true) {
        args.push(option);
      } else {
        args.push(option, value.toString());
      }
    }
  });

  return args;
}

module.exports.options = options;

function spawn(command, args, options, callback) {
  if (typeof args === 'function') {
    callback = args;
    args = undefined;
  } else if (typeof options === 'function') {
    callback = options;
    options = undefined;
  }

  find(command, function (error, command) {
    debug('spawn %s %s', command, util.inspect(args));

    if (error) {
      return callback(error);
    }

    var exe = child.spawn(command, args, options);
    exe.once('error', function (error) {
      callback(error);
    });

    process.nextTick(function () {
      callback(null, exe);
    });
  });
}

module.exports.spawn = spawn;
<commit_msg>Remove browser type lookup in options<commit_after>var path = require('path');
var child = require('child_process');
var which = require('which');
var util = require('util');

var debug = util.debuglog('browser_process');

var browsers = {
  chrome: {
    type: 'chrome',
    paths: {
      darwin: [
        '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome',
      ],
      linux: [
        'google-chrome'
      ],
      win32: [
        process.env['LOCALAPPDATA'] + '\\Google\\Chrome\\Application\\chrome.exe',
        process.env['PROGRAMFILES'] + '\\Google\\Chrome\\Application\\chrome.exe',
        process.env['PROGRAMFILES(X86)'] + '\\Google\\Chrome\\Application\\chrome.exe',
      ],
    }[process.platform],
  },

  chromium: {
    type: 'chrome',
    paths: {
      darwin: [
        '/Applications/Chromium.app/Contents/MacOS/Chromium',
      ],
      linux: [
        'chromium-browser',
      ],
      win32: [
        process.env['LOCALAPPDATA'] + '\\Chromium\\Application\\chrome.exe',
        process.env['PROGRAMFILES'] + '\\Chromium\\Application\\chrome.exe',
        process.env['PROGRAMFILES(X86)'] + '\\Chromium\\Application\\chrome.exe',
      ]
    }[process.platform],
  },

  electron: {
    type: 'chrome',
    paths: {
      darwin: [
        'electron',
      ],
      linux: [
        'electron',
      ],
      win32: [
        'electron',
        'electron.cmd',
      ]
    }[process.platform],
  },
  firefox: {
    type: 'firefox',
    paths: {
      darwin: [
        '/Applications/Firefox.app/Contents/MacOS/Firefox',
      ],
      linux: [
        'firefox',
      ],
      win32: [
        process.env['LOCALAPPDATA'] + '\\Mozilla\ Firefox\\firefox.exe',
        process.env['PROGRAMFILES'] + '\\Mozilla\ Firefox\\firefox.exe',
        process.env['PROGRAMFILES(X86)'] + '\\Mozilla\ Firefox\\firefox.exe',
      ],
    }[process.platform],
  },
};

var browserOptions = {
  chrome: {
    debug: '--remote-debugging-port=',
    profile: '--user-data-dir=',
    window: '--new-window',
    private: '--incognito',
  },

  firefox: {
    debug: '--start-debugging-server',
    profile: '--profile',
    window: '--new-window',
    private: '--private',
  }
};

function type(command) {
  var basename = path.basename(command);

  var key = Object.keys(browsers).filter(function (key) {
    return browsers[key].paths.some(function (exename) {
      return basename === path.basename(exename);
    });
  })[0];

  if (key) {
    return browsers[key].type;
  }

  throw Error('Bad browser command ' + command);
}

module.exports.type = type;

function find(command, callback) {
  if (path.isAbsolute(command)) {
    return callback(null, command);
  }

  var browser = browsers[command];
  if (browser === undefined) {
    var error = new Error('Invalid browser command');
    return callback(error);
  }

  var done = false;
  browser.paths.forEach(function (exename) {
    which(exename, function (error, command) {
      if (error || done) {
        return;
      }

      done = true;
      callback(null, command);
    });
  });
}

module.exports.find = find;

function options(type, options) {
  var args = [];
  var keys = Object.keys(options);
  keys.forEach(function (key) {
    var value = options[key];

    if (value !== undefined) {
      var option = browserOptions[type][key];

      if (key === 'url') {
        args.push(value);
      } else if (option.match(/\S=$/)) {
        args.push(option + value);
      } else if (value === true) {
        args.push(option);
      } else {
        args.push(option, value.toString());
      }
    }
  });

  return args;
}

module.exports.options = options;

function spawn(command, args, options, callback) {
  if (typeof args === 'function') {
    callback = args;
    args = undefined;
  } else if (typeof options === 'function') {
    callback = options;
    options = undefined;
  }

  find(command, function (error, command) {
    debug('spawn %s %s', command, util.inspect(args));

    if (error) {
      return callback(error);
    }

    var exe = child.spawn(command, args, options);
    exe.once('error', function (error) {
      callback(error);
    });

    process.nextTick(function () {
      callback(null, exe);
    });
  });
}

module.exports.spawn = spawn;
<|endoftext|>


<commit_before>/**
 * @file Defines the hydrater settings.
 */

// nodeEnv can either be "development" or "production"
var nodeEnv = process.env.nodeEnv || "development";
var defaultPort = 8000;

// Number of instance to run simultaneously per cluster
var defaultConcurrency = 1;

if(nodeEnv === "production") {
  defaultPort = 80;
}

// Exports configuration
module.exports = {
  env: nodeEnv,
  port: process.env.PORT || defaultPort,

  thumb_size: "350x250",
  display_size: "750x750",
  redisUrl: process.env.REDIS_URL,
  concurrency: process.env.IMAGE_CONCURRENCY || defaultConcurrency,
  appName: process.env.APP_NAME || "imahe-hydrater"
};
<commit_msg>Add opbeat config<commit_after>/**
 * @file Defines the hydrater settings.
 */

// nodeEnv can either be "development" or "production"
var nodeEnv = process.env.nodeEnv || "development";
var defaultPort = 8000;

// Number of instance to run simultaneously per cluster
var defaultConcurrency = 1;

if(nodeEnv === "production") {
  defaultPort = 80;
}

// Exports configuration
module.exports = {
  env: nodeEnv,
  port: process.env.PORT || defaultPort,

  thumb_size: "350x250",
  display_size: "750x750",
  redisUrl: process.env.REDIS_URL,
  concurrency: process.env.IMAGE_CONCURRENCY || defaultConcurrency,
  appName: process.env.APP_NAME || "imahe-hydrater",

  opbeat: {
    organizationId: process.env.OPBEAT_ORGANIZATION_ID,
    appId: process.env.OPBEAT_APP_ID,
    secretToken: process.env.OPBEAT_SECRET_TOKEN
  }
};
<|endoftext|>


<commit_before>/**
 * Assemble
 *
 * Assemble <http://assemble.io>
 * Created and maintained by Jon Schlinkert and Brian Woodward
 *
 * Copyright (c) 2014 Upstage.
 * Licensed under the MIT License (MIT).
 */

var path = require('path');

var resolve = require('resolve-dep');
var glob = require('globule');
var ewait = require('ewait');
var async = require('async');
var _ = require('lodash');

var plugins = require('./plugins');
var Plugin = require('./plugin');

var isEventMatch = function (a, b) {
  return (a === b) || a === '*';
};

var Dovetail = module.exports = function (app, logger) {
  this.eventCache = {};
  this.cache = {};

  this.app = app;
  this.logger = logger;
};

Dovetail.plugins = plugins;

Dovetail.prototype.setEventCache = function (event, plugin) {
  (this.eventCache[event] = this.eventCache[event] || []).push(plugin);
};

Dovetail.prototype.getEventCache = function (event) {
  return (this.eventCache[event] || []);
};

Dovetail.prototype.setCache = function (name, plugin) {
  this.cache[name] = plugin;
};

Dovetail.prototype.getCache = function (name) {
  return this.cache[name];
};

Dovetail.prototype.expandEvents = function (pluginEvents) {
  if (!_.isArray(pluginEvents)) {
    pluginEvents = [pluginEvents];
  }

  return _.filter(plugins.events, function (event) {
    var eventParts = event.split(':');
    var isMatch = false;
    _.map(pluginEvents, function (pluginEvent) {
      var pluginParts = pluginEvent.split(':');
      isMatch = isMatch || (isEventMatch(pluginParts[0], eventParts[0]) &&
        isEventMatch(pluginParts[1], eventParts[1]) &&
        isEventMatch(pluginParts[2], eventParts[2]));
    });
    return isMatch;
  });
};

Dovetail.prototype.addListeners = function (events, plugin) {
  var self = this;
  // setup a listener for each event this plugin registered
  events = self.expandEvents(events);
  events.forEach(function (event) {
    self.setEventCache(event, plugin);
    plugin.listen(event);
  });
};

Dovetail.prototype.createPlugin = function (name, description, options, fn) {

  // name must be provided
  if (!name || !_.isString(name)) {
    throw new Error('Must supply the name parameter.');
  }

  // name must be unique
  if (this.getCache(name)) {
    throw new Error('A plugin with the name (' + name + ') already exists.');
  }

  // if description is an object, then it's the options
  if (description && _.isObject(description)) {
    fn = options;
    options = description;
    description = '';
  }

  // if options is a function, then it's the callback
  if (options && _.isFunction(options)) {
    fn = options;
    options = {};
  }

  // function must be provided
  if (!fn) {
    throw new Error('[Error loading plugin (' + name + ')] Must supply a function parameter.');
  }

  var plugin = new Plugin(name, description, options, fn, this.app, this.logger);

  var events = (fn.options && (fn.options.event || fn.options.events)) || options.event || options.events || [];
  this.addListeners(events, plugin);
  this.setCache(name, plugin);
  return plugin;
};

/**
 * Find plugins and load them based on the list of plugins
 * @param  {[type]} app     [description]
 * @param  {[type]} _plugins [description]
 * @param  {[type]} options  [description]
 * @return {[type]}          [description]
 */
Dovetail.prototype.resolve = function (_plugins, options) {
  var self = this;
  options = options || {};
  _plugins = _plugins || [];
  if (!_.isArray(_plugins)) {
    _plugins = [_plugins];
  }
  var actualPlugins = [];

  _plugins.forEach(function (plugin) {
    // if plugin is a string, attempt to resolve to module
    if (_.isString(plugin)) {
      var resolved = resolve.all(plugin);
      // if resolved to an npm module then use it, otherwise assume local file/pattern so expand
      var relPaths = resolve.length ? resolved : glob.find(plugin);
      var resolvedPlugins = relPaths.map(function (relPath) {
        // normalize the relative path given current working directory
        var fullPath = path.normalize(path.join(options.cwd || process.cwd() || '', relPath));
        try {
          var required = require(fullPath);
          return required;
        } catch (ex) {
          self.logger.error('Error requiring plugin "' + plugin + '"');
          self.logger.error(ex);
        }
      });
      actualPlugins = actualPlugins.concat(resolvedPlugins || []);
    }
    // otherwise, assume plugin is already a function
    else {
      actualPlugins.push(plugin);
    }
  });

  // set plugin options
  _.map(actualPlugins, function (plugin) {
    plugin.options = plugin.options || {};
    plugin.options.event = plugin.options.event || (plugin.options.event = plugin.options.events || plugins.events.renderPrePage);
    plugin(self.app);
  });
};

Dovetail.prototype.run = function (params, done) {
  var self = this;
  async.forEachSeries(_.keys(plugins.events), function (key, next) {
      var event = plugins.events[key];
      self.runevent(event, params, next);
    },
    function (err) {
      if (err) {
        self.logger.error(err);
        done();
      } else {
        done();
      }
    });
};

Dovetail.prototype.runEvent = function (event, params, done) {
  var self = this;
  var eventCache = self.getEventCache(event);
  if (eventCache && eventCache.length) {

    ewait.waitForAll(eventCache, function (err) {
      if (err) {
        self.logger.error(err);
      }
      done();
    });

    params = _.extend({event: event}, params);
    self.app.emit(event, params);
  } else {

    done();
  }
};<commit_msg>removing options.cwd<commit_after>/**
 * Assemble
 *
 * Assemble <http://assemble.io>
 * Created and maintained by Jon Schlinkert and Brian Woodward
 *
 * Copyright (c) 2014 Upstage.
 * Licensed under the MIT License (MIT).
 */

var path = require('path');

var resolve = require('resolve-dep');
var glob = require('globule');
var ewait = require('ewait');
var async = require('async');
var _ = require('lodash');

var plugins = require('./plugins');
var Plugin = require('./plugin');

var isEventMatch = function (a, b) {
  return (a === b) || a === '*';
};

var Dovetail = module.exports = function (app, logger) {
  this.eventCache = {};
  this.cache = {};

  this.app = app;
  this.logger = logger;
};

Dovetail.plugins = plugins;

Dovetail.prototype.setEventCache = function (event, plugin) {
  (this.eventCache[event] = this.eventCache[event] || []).push(plugin);
};

Dovetail.prototype.getEventCache = function (event) {
  return (this.eventCache[event] || []);
};

Dovetail.prototype.setCache = function (name, plugin) {
  this.cache[name] = plugin;
};

Dovetail.prototype.getCache = function (name) {
  return this.cache[name];
};

Dovetail.prototype.expandEvents = function (pluginEvents) {
  if (!_.isArray(pluginEvents)) {
    pluginEvents = [pluginEvents];
  }

  return _.filter(plugins.events, function (event) {
    var eventParts = event.split(':');
    var isMatch = false;
    _.map(pluginEvents, function (pluginEvent) {
      var pluginParts = pluginEvent.split(':');
      isMatch = isMatch || (isEventMatch(pluginParts[0], eventParts[0]) &&
        isEventMatch(pluginParts[1], eventParts[1]) &&
        isEventMatch(pluginParts[2], eventParts[2]));
    });
    return isMatch;
  });
};

Dovetail.prototype.addListeners = function (events, plugin) {
  var self = this;
  // setup a listener for each event this plugin registered
  events = self.expandEvents(events);
  events.forEach(function (event) {
    self.setEventCache(event, plugin);
    plugin.listen(event);
  });
};

Dovetail.prototype.createPlugin = function (name, description, options, fn) {

  // name must be provided
  if (!name || !_.isString(name)) {
    throw new Error('Must supply the name parameter.');
  }

  // name must be unique
  if (this.getCache(name)) {
    throw new Error('A plugin with the name (' + name + ') already exists.');
  }

  // if description is an object, then it's the options
  if (description && _.isObject(description)) {
    fn = options;
    options = description;
    description = '';
  }

  // if options is a function, then it's the callback
  if (options && _.isFunction(options)) {
    fn = options;
    options = {};
  }

  // function must be provided
  if (!fn) {
    throw new Error('[Error loading plugin (' + name + ')] Must supply a function parameter.');
  }

  var plugin = new Plugin(name, description, options, fn, this.app, this.logger);

  var events = (fn.options && (fn.options.event || fn.options.events)) || options.event || options.events || [];
  this.addListeners(events, plugin);
  this.setCache(name, plugin);
  return plugin;
};

/**
 * Find plugins and load them based on the list of plugins
 * @param  {[type]} app     [description]
 * @param  {[type]} _plugins [description]
 * @param  {[type]} options  [description]
 * @return {[type]}          [description]
 */
Dovetail.prototype.resolve = function (_plugins, options) {
  var self = this;
  options = options || {};
  _plugins = _plugins || [];
  if (!_.isArray(_plugins)) {
    _plugins = [_plugins];
  }
  var actualPlugins = [];

  _plugins.forEach(function (plugin) {
    // if plugin is a string, attempt to resolve to module
    if (_.isString(plugin)) {
      var resolved = resolve.all(plugin);
      // if resolved to an npm module then use it, otherwise assume local file/pattern so expand
      var relPaths = resolve.length ? resolved : glob.find(plugin);
      var resolvedPlugins = relPaths.map(function (relPath) {
        // normalize the relative path given current working directory
        var fullPath = path.normalize(path.join(process.cwd(), relPath));
        try {
          var required = require(fullPath);
          return required;
        } catch (ex) {
          self.logger.error('Error requiring plugin "' + plugin + '"');
          self.logger.error(ex);
        }
      });
      actualPlugins = actualPlugins.concat(resolvedPlugins || []);
    }
    // otherwise, assume plugin is already a function
    else {
      actualPlugins.push(plugin);
    }
  });

  // set plugin options
  _.map(actualPlugins, function (plugin) {
    plugin.options = plugin.options || {};
    plugin.options.event = plugin.options.event || (plugin.options.event = plugin.options.events || plugins.events.renderPrePage);
    plugin(self.app);
  });
};

Dovetail.prototype.run = function (params, done) {
  var self = this;
  async.forEachSeries(_.keys(plugins.events), function (key, next) {
      var event = plugins.events[key];
      self.runevent(event, params, next);
    },
    function (err) {
      if (err) {
        self.logger.error(err);
        done();
      } else {
        done();
      }
    });
};

Dovetail.prototype.runEvent = function (event, params, done) {
  var self = this;
  var eventCache = self.getEventCache(event);
  if (eventCache && eventCache.length) {

    ewait.waitForAll(eventCache, function (err) {
      if (err) {
        self.logger.error(err);
      }
      done();
    });

    params = _.extend({event: event}, params);
    self.app.emit(event, params);
  } else {

    done();
  }
};<|endoftext|>


<commit_before>import {
  getQueryStringParam, substanceGlobals, platform, VfsStorageClient, HttpStorageClient, InMemoryDarBuffer
} from 'substance'
import { TextureWebApp, TextureArchive } from 'substance-texture'

window.addEventListener('load', () => {
  substanceGlobals.DEBUG_RENDERING = platform.devtools
  let app = DevTextureWebApp.mount({
    archiveId: getQueryStringParam('archive') || 'kitchen-sink',
    storageType: getQueryStringParam('storage') || 'vfs',
    storageUrl: getQueryStringParam('storageUrl') || '/archives'
  }, window.document.body)

  // put the archive and some more things into global scope, for debugging
  setTimeout(() => {
    window.app = app
  }, 500)
})

// This uses a monkey-patched VfsStorageClient that checks immediately
// if the stored data could be loaded again, or if there is a bug in
// Textures exporter
class DevTextureWebApp extends TextureWebApp {
  _loadArchive(archiveId, context) {
    let storage
    if (this.props.storageType==='vfs') {
      storage = new VfsStorageClient(window.vfs, './data/')
      // monkey patch VfsStorageClient so that we can check if the stored data
      // can be loaded
      storage.write = (archiveId, rawArchive) => {
        console.log(rawArchive)
        return storage.read(archiveId)
        .then((originalRawArchive) => {
          Object.assign(rawArchive.resources, originalRawArchive.resources)
          let testArchive = new TextureArchive()
          try {
            debugger
            testArchive._ingest(rawArchive)
          } catch (error) {
            window.alert('Exported TextureArchive is corrupt') //eslint-disable-line no-alert
            console.error(error)
          }
        })
        .then(() => {
          return false
        })
      }
    } else {
      storage = new HttpStorageClient(this.props.storageUrl)
    }
    let buffer = new InMemoryDarBuffer()
    let archive = new TextureArchive(storage, buffer, context)
    return archive.load(archiveId)
  }
}<commit_msg>Fix web app save hook.<commit_after>import {
  getQueryStringParam, substanceGlobals, platform,
  VfsStorageClient, HttpStorageClient, InMemoryDarBuffer
} from 'substance'
import { TextureWebApp, TextureArchive } from 'substance-texture'

window.addEventListener('load', () => {
  substanceGlobals.DEBUG_RENDERING = platform.devtools
  let app = DevTextureWebApp.mount({
    archiveId: getQueryStringParam('archive') || 'kitchen-sink',
    storageType: getQueryStringParam('storage') || 'vfs',
    storageUrl: getQueryStringParam('storageUrl') || '/archives'
  }, window.document.body)

  // put the archive and some more things into global scope, for debugging
  setTimeout(() => {
    window.app = app
  }, 500)
})

// This uses a monkey-patched VfsStorageClient that checks immediately
// if the stored data could be loaded again, or if there is a bug in
// Textures exporter
class DevTextureWebApp extends TextureWebApp {
  _loadArchive(archiveId, context) {
    let storage
    if (this.props.storageType==='vfs') {
      storage = new VfsStorageClient(window.vfs, './data/')
      // monkey patch VfsStorageClient so that we can check if the stored data
      // can be loaded
      storage.write = (archiveId, rawArchive) => {
        console.log('Writing archive:', rawArchive) // eslint-disable-line
        return storage.read(archiveId)
        .then((originalRawArchive) => {
          rawArchive.resources = Object.assign({}, originalRawArchive.resources, rawArchive.resources)
          let testArchive = new TextureArchive()
          try {
            testArchive._ingest(rawArchive)
          } catch (error) {
            window.alert('Exported TextureArchive is corrupt') //eslint-disable-line no-alert
            console.error(error)
          }
        })
        .then(() => {
          return false
        })
      }
    } else {
      storage = new HttpStorageClient(this.props.storageUrl)
    }
    let buffer = new InMemoryDarBuffer()
    let archive = new TextureArchive(storage, buffer, context)
    return archive.load(archiveId)
  }
}<|endoftext|>