<commit_before>var Blob = require('./blob')
  , CommandManager = require('./commandManager')
  , fs = require('fs')
  , Message = require('./message');

function CameraManager(camera) {
    this.camera = camera;
}

CameraManager.prototype = Object.create(CommandManager.prototype);

CameraManager.prototype.executeCommand = function() {
    if (!this.camera) return;

    var self = this;
    this.camera.snapshot({}, function(err, shot) {
        if (err) {
            self.executing = false;
            return console.log('execute: snapshot execution failed: ' + err);
        }

        var attributes = {};
        attributes.response_to = [];

        self.activeCommands().forEach(function(activeCommand) {
            attributes.response_to.push(activeCommand.id);

            // allow passing through attributes from commands to message
            if (activeCommand.body.message) {
                // TODO: need some way to intelligently combine attributes (max 'expires', etc.)
                for (key in activeCommand.body.message) {
                    attributes[key] = activeCommand.body.message[key];
                }
            }
        });

        self.sendImage(shot, attributes, function(err) {
            self.executing = false;
        });

    });
}

CameraManager.prototype.isRelevant = function(message) {
    return message.is('cameraCommand') || message.is('image');
}

CameraManager.prototype.obsoletes = function(downstreamMsg, upstreamMsg) {
    if (CommandManager.obsoletes(downstreamMsg, upstreamMsg)) return true;

    return downstreamMsg.is('cameraCommand') && downstreamMsg.body.command === "cancel" && downstreamMsg.isResponseTo(upstreamMsg.id) ||
        downstreamMsg.is('image') && downstreamMsg.isResponseTo(upstreamMsg);
};

CameraManager.prototype.sendImage = function(shot, attributes, callback) {
    var self = this;

    Blob.fromFile(shot.path, function(err, blob) {
        if (err) return callback(err);

        console.log('saving image blob.');

        blob.save(self.session, fs.createReadStream(shot.path), function(err, blob) {
            if (err) return callback(err);

            console.log('created blob with url: ' + blob.url);

            var message = new Message({
                type: blob.message_type,
                link: blob.link,

                body: {
                    url: blob.url
                }
            });

            for (var attribute in attributes) {
                console.log('setting attribute: ' + attribute + ' to ' + attributes[attribute]);
                message[attribute] = attributes[attribute];
            }

            message.send(self.session, function(err, message) {
                if (err) return callback("failed to send message for path: " + shot.path + " :" + err);

                console.log("sent message: " + JSON.stringify(message));
                fs.unlink(shot.path, callback);
            });
        });
    });
};

module.exports = CameraManager;
<commit_msg>log error for camera snapshot failure<commit_after>var Blob = require('./blob')
  , CommandManager = require('./commandManager')
  , fs = require('fs')
  , Message = require('./message');

function CameraManager(camera) {
    this.camera = camera;
}

CameraManager.prototype = Object.create(CommandManager.prototype);

CameraManager.prototype.executeCommand = function() {
    if (!this.camera) return;

    var self = this;
    this.camera.snapshot({}, function(err, shot) {
        if (err) {
            self.executing = false;
            return self.session.error('camera snapshot failed with error: ' + err);
        }

        var attributes = {};
        attributes.response_to = [];

        self.activeCommands().forEach(function(activeCommand) {
            attributes.response_to.push(activeCommand.id);

            // allow passing through attributes from commands to message
            if (activeCommand.body.message) {
                // TODO: need some way to intelligently combine attributes (max 'expires', etc.)
                for (key in activeCommand.body.message) {
                    attributes[key] = activeCommand.body.message[key];
                }
            }
        });

        self.sendImage(shot, attributes, function(err) {
            self.executing = false;
        });

    });
}

CameraManager.prototype.isRelevant = function(message) {
    return message.is('cameraCommand') || message.is('image');
}

CameraManager.prototype.obsoletes = function(downstreamMsg, upstreamMsg) {
    if (CommandManager.obsoletes(downstreamMsg, upstreamMsg)) return true;

    return downstreamMsg.is('cameraCommand') && downstreamMsg.body.command === "cancel" && downstreamMsg.isResponseTo(upstreamMsg.id) ||
        downstreamMsg.is('image') && downstreamMsg.isResponseTo(upstreamMsg);
};

CameraManager.prototype.sendImage = function(shot, attributes, callback) {
    var self = this;

    Blob.fromFile(shot.path, function(err, blob) {
        if (err) return callback(err);

        console.log('saving image blob.');

        blob.save(self.session, fs.createReadStream(shot.path), function(err, blob) {
            if (err) return callback(err);

            console.log('created blob with url: ' + blob.url);

            var message = new Message({
                type: blob.message_type,
                link: blob.link,

                body: {
                    url: blob.url
                }
            });

            for (var attribute in attributes) {
                console.log('setting attribute: ' + attribute + ' to ' + attributes[attribute]);
                message[attribute] = attributes[attribute];
            }

            message.send(self.session, function(err, message) {
                if (err) return callback("failed to send message for path: " + shot.path + " :" + err);

                console.log("sent message: " + JSON.stringify(message));
                fs.unlink(shot.path, callback);
            });
        });
    });
};

module.exports = CameraManager;
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var express = require('express');
var utils = require('lib/utils');
var accepts = require('lib/accepts');
var restrict = utils.restrict;
var pluck = utils.pluck;
var expose = utils.expose;
var api = require('lib/db-api');
var log = require('debug')('democracyos:citizen');

var app = module.exports = express();
var basicData = 'id fullName gravatar() about profilePictureUrl tags';

/**
 * Limit request to json format only
 */

app.use(accepts('application/json'));

app.get('/citizen/me', restrict, function (req, res) {
  log('Request /citizen/me');

  log('Serving citizen %j', req.user.id);

  res.json(expose(basicData + ' ' + 'firstName lastName email staff')(req.user));
});

app.get('/citizen/search', restrict, function (req, res) {
  var q = req.param('q');

  log('Request /citizen/search %j', q);

  api.citizen.search(q, function(err, citizens) {
    if (err) return _handleError(err, req, res);

    log('Serving citizens %j', pluck(citizens, 'id'));

    res.json(citizens.map(expose(basicData)));
  });
});

app.get('/citizen/lookup', function (req, res) {
  var ids = req.param('ids');

  log('Request /citizen/lookup %j', ids);

  if (!ids) return log('Cannot process without ids'), res.json(500,{});

  api.citizen.lookup(ids.split(','), function(err, citizens) {
    if (err) return _handleError(err, req, res);

    log('Serving citizens %j', pluck(citizens, 'id'));

    res.json(citizens.map(expose(basicData)));
  });
});

// This is a temporary hack while lookinf for a better solution to
// this error: 414 Request-URI Too Large
app.post('/citizen/lookup', function (req, res) {
  var ids = req.param('ids');

  log('Request /citizen/lookup %j', ids);

  if (!ids) return log('Cannot process without ids'), res.json(500,{});

  api.citizen.lookup(ids, function(err, citizens) {
    if (err) return _handleError(err, req, res);

    log('Serving citizens %j', pluck(citizens, 'id'));

    res.json(citizens.map(expose(basicData)));
  });
});

app.get('/citizen/:id', restrict, function (req, res) {
  log('Request /citizen/%s', req.params.id);

  api.citizen.get(req.params.id, function (err, citizen) {
    if (err) return _handleError(err, req, res);

    log('Serving citizen %j', citizen.id);

    res.json(expose(basicData)(citizen));
  });
});

function _handleError (err, req, res) {
  res.format({
    html: function() {
      // this should be handled better!
      // maybe with flash or even an
      // error page.
      log('Error found with html request %j', err);
      res.redirect('back');
    },
    json: function() {
      log("Error found: %j", err);
      res.json({ error: err });
    }
  })
}<commit_msg>Fix removed email to serv user profile. #35<commit_after>/**
 * Module dependencies.
 */

var express = require('express');
var utils = require('lib/utils');
var accepts = require('lib/accepts');
var restrict = utils.restrict;
var pluck = utils.pluck;
var expose = utils.expose;
var api = require('lib/db-api');
var log = require('debug')('democracyos:citizen');

var app = module.exports = express();
var basicData = 'id fullName gravatar() about profilePictureUrl tags';

/**
 * Limit request to json format only
 */

app.use(accepts('application/json'));

app.get('/citizen/me', restrict, function (req, res) {
  log('Request /citizen/me');

  log('Serving citizen %j', req.user.id);

  res.json(expose(basicData + ' ' + 'email firstName lastName staff')(req.user));
});

app.get('/citizen/search', restrict, function (req, res) {
  var q = req.param('q');

  log('Request /citizen/search %j', q);

  api.citizen.search(q, function(err, citizens) {
    if (err) return _handleError(err, req, res);

    log('Serving citizens %j', pluck(citizens, 'id'));

    res.json(citizens.map(expose(basicData)));
  });
});

app.get('/citizen/lookup', function (req, res) {
  var ids = req.param('ids');

  log('Request /citizen/lookup %j', ids);

  if (!ids) return log('Cannot process without ids'), res.json(500,{});

  api.citizen.lookup(ids.split(','), function(err, citizens) {
    if (err) return _handleError(err, req, res);

    log('Serving citizens %j', pluck(citizens, 'id'));

    res.json(citizens.map(expose(basicData)));
  });
});

// This is a temporary hack while lookinf for a better solution to
// this error: 414 Request-URI Too Large
app.post('/citizen/lookup', function (req, res) {
  var ids = req.param('ids');

  log('Request /citizen/lookup %j', ids);

  if (!ids) return log('Cannot process without ids'), res.json(500,{});

  api.citizen.lookup(ids, function(err, citizens) {
    if (err) return _handleError(err, req, res);

    log('Serving citizens %j', pluck(citizens, 'id'));

    res.json(citizens.map(expose(basicData)));
  });
});

app.get('/citizen/:id', restrict, function (req, res) {
  log('Request /citizen/%s', req.params.id);

  api.citizen.get(req.params.id, function (err, citizen) {
    if (err) return _handleError(err, req, res);

    log('Serving citizen %j', citizen.id);

    res.json(expose(basicData)(citizen));
  });
});

function _handleError (err, req, res) {
  res.format({
    html: function() {
      // this should be handled better!
      // maybe with flash or even an
      // error page.
      log('Error found with html request %j', err);
      res.redirect('back');
    },
    json: function() {
      log("Error found: %j", err);
      res.json({ error: err });
    }
  })
}<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var request = require('request');
var Stateful = require('stateful');
var config = require('config');

/**
 * Expose user model
 */

module.exports = Citizen;

/**
 * Citizen
 *
 * @param {String} path user's load path
 * @return {Citizen} `Citizen` instance
 * @api public
 */

function Citizen (path) {
  if (!(this instanceof Citizen)) {
    return new Citizen(path);
  };

  this.$_state = 'unloaded';
  this.$_path = path;
}

/**
 * Inherit from `Stateful`
 */

Stateful(Citizen);

/**
 * Loads user from path
 *
 * @param {String} path user's load path
 * @return {Citizen} `Citizen` instance.
 * @api public
 */

Citizen.prototype.load = function(path) {
  var self = this;
  this.$_path = path || this.$_path;
  this.state('loading');

  request
  .get('/api/citizen/'.concat(this.$_path))
  .end(function(err, res) {
    var u = res.body;

    if (err || !res.ok) {
      return _handleRequestError.bind(self)(err || res.error);
    }

    if (!(u.id || u._id)) {
      return _handleRequestError.bind(self)('Citizen not found');
    }

    self.set(u);
  });

  return this;
}

/**
 * Set user attributes
 *
 * @param {Hash} User attributes.
 * @return {Citizen} `Citizen` instance.
 * @api public
 */

Citizen.prototype.set = function(attrs) {
  var self = this;

  for (var prop in attrs) {
    if (attrs.hasOwnProperty(prop)) {
      self[prop] = attrs[prop];
    }
  }

  self.state('loaded');

  return this;
}

/**
 * Returns wether the receiver is logged (i.e.: sign in)
 *
 * @return {Boolean}
 * @api public
 */

Citizen.prototype.logged = function() {
  return !!this.id;
}

/**
 * Unloads instance and notifies observers.
 *
 * @return {Citizen}
 * @api public
 */

Citizen.prototype.unload = function(cb) {
  var self = this;
  this.cleanup();
  this.$_path = null;

  request
  .del('/signin')
  .send()
  .end(function(err, res) {
    if (!err) self.state('unloaded');
    cb || cb(err);
  });
};

/**
 * Cleans up citizen
 *
 * @api private
 */

Citizen.prototype.cleanup = function() {
  for (var i in this) {
    if ('_callbacks' == i) continue;
    if ('$' == i.charAt(0)) continue;
    if (!this.hasOwnProperty(i)) continue;
    if ('function' == typeof this[i]) continue;
    delete this[i];
  }
};

/**
 * Returns profile picture
 *
 * @api private
 */

Citizen.prototype.profilePicture = function() {
  return this.avatar;
};

/**
 * Handle error from requests
 *
 * @param {Object} err from request
 * @api private
 */

function _handleRequestError (err) {
  // FIXME: change this off for handling it on subscribers
  // Shut ready's down
  this.off('ready');
  this.emit('error', err);
}<commit_msg>[citizen] Fixed callback invoking error #846<commit_after>/**
 * Module dependencies.
 */

var request = require('request');
var Stateful = require('stateful');
var config = require('config');

/**
 * Expose user model
 */

module.exports = Citizen;

/**
 * Citizen
 *
 * @param {String} path user's load path
 * @return {Citizen} `Citizen` instance
 * @api public
 */

function Citizen (path) {
  if (!(this instanceof Citizen)) {
    return new Citizen(path);
  };

  this.$_state = 'unloaded';
  this.$_path = path;
}

/**
 * Inherit from `Stateful`
 */

Stateful(Citizen);

/**
 * Loads user from path
 *
 * @param {String} path user's load path
 * @return {Citizen} `Citizen` instance.
 * @api public
 */

Citizen.prototype.load = function(path) {
  var self = this;
  this.$_path = path || this.$_path;
  this.state('loading');

  request
  .get('/api/citizen/'.concat(this.$_path))
  .end(function(err, res) {
    var u = res.body;

    if (err || !res.ok) {
      return _handleRequestError.bind(self)(err || res.error);
    }

    if (!(u.id || u._id)) {
      return _handleRequestError.bind(self)('Citizen not found');
    }

    self.set(u);
  });

  return this;
}

/**
 * Set user attributes
 *
 * @param {Hash} User attributes.
 * @return {Citizen} `Citizen` instance.
 * @api public
 */

Citizen.prototype.set = function(attrs) {
  var self = this;

  for (var prop in attrs) {
    if (attrs.hasOwnProperty(prop)) {
      self[prop] = attrs[prop];
    }
  }

  self.state('loaded');

  return this;
}

/**
 * Returns wether the receiver is logged (i.e.: sign in)
 *
 * @return {Boolean}
 * @api public
 */

Citizen.prototype.logged = function() {
  return !!this.id;
}

/**
 * Unloads instance and notifies observers.
 *
 * @return {Citizen}
 * @api public
 */

Citizen.prototype.unload = function(cb) {
  var self = this;
  this.cleanup();
  this.$_path = null;

  request
  .del('/signin')
  .send()
  .end(function(err, res) {
    if (!err) self.state('unloaded');
    'function' === typeof cb && cb(err);
  });
};

/**
 * Cleans up citizen
 *
 * @api private
 */

Citizen.prototype.cleanup = function() {
  for (var i in this) {
    if ('_callbacks' == i) continue;
    if ('$' == i.charAt(0)) continue;
    if (!this.hasOwnProperty(i)) continue;
    if ('function' == typeof this[i]) continue;
    delete this[i];
  }
};

/**
 * Returns profile picture
 *
 * @api private
 */

Citizen.prototype.profilePicture = function() {
  return this.avatar;
};

/**
 * Handle error from requests
 *
 * @param {Object} err from request
 * @api private
 */

function _handleRequestError (err) {
  // FIXME: change this off for handling it on subscribers
  // Shut ready's down
  this.off('ready');
  this.emit('error', err);
}<|endoftext|>


<commit_before>'use babel';
/* @flow */

var related = require('./related');
var fs = require('fs');
var _ = require('underscore');

var wordRegExp = /^[	 ]*$|[^\s\/\\\(\)"':,;<>~!@\$%\^&\*\|\+=\[\]\{\}`\?\-…]+/g
// default :     /^[	 ]*$|[^\s\/\\\(\)"':,\.;<>~!@#\$%\^&\*\|\+=\[\]\{\}`\?\-…]+/g
// by atom.workspace.getActiveTextEditor().getLastCursor().wordRegExp({includeNonWordCharacters:false});

var alloyPathReg = /\/(controllers|views|styles)\/(.*)?\.(.*)/;
var selectorReg =  /(class|id)=\"[\sa-zA-Z-_^]*$/;

var fromXmlRegExps = [
  { // class
    regExp : /class=["'][\sa-zA-Z-_^]*$/,
    getTargetRegExp (text){
      return new RegExp(`["'].${text}`,'g');
    },
    targetType : 'tss'
  },
  { // id
    regExp : /id=["'][\sa-zA-Z-_^]*$/,
    getTargetRegExp (text){
      return new RegExp(`["']#${text}`,'g');
    },
    targetType : 'tss'
  },
  { // tag
    regExp : /<$/,
    getTargetRegExp (text){
      return new RegExp(`["']${text}`,'g');
    },
    targetType : 'tss'
  }
];

function findDefinition(path,regExp){
  var callbacks = [];
  var targetBuffer = _.find(atom.workspace.getTextEditors(), (editor) => {
    return editor.getPath() === path;
  });

  if(!targetBuffer){ // if targetFile not opened yet, use new buffer
    targetBuffer = atom.getActiveTextEditor().buffer.constructor; //require('text-buffer')
    targetBuffer.setPath(path);
    targetBuffer.loadSync();
  }

  targetBuffer.scan(regExp,function(item){
    callbacks.push({
      title : item.lineText,
      callback (){
        atom.workspace.open(path,{initialLine: item.range.start.row, initialColumn: item.range.start.column, searchAllPanes:true});
      }
    });
  });

  return callbacks.length?callbacks:false;
}

var xmlClickProvider = {
  wordRegExp ,
  getSuggestionForWord(textEditor: TextEditor, text: string, range: Range): HyperclickSuggestion {
    var [isAlloy=false,alloyType,filename,fileExt] = textEditor.getPath().match(alloyPathReg);
    if(!text || fileExt!='xml') return;

    var lineText = textEditor.getTextInBufferRange([[range.start.row,0],[range.start.row,range.start.column]]);
    var callbacks;

    var matchedExpItem = _.find(fromXmlRegExps,function(item){
      return item.regExp.test(lineText);
    });

    if(!matchedExpItem) return;

    callbacks = findDefinition(related.getTargetPath(matchedExpItem.targetType), matchedExpItem.getTargetRegExp(text));

    //if no definition, go last line of ther code
    if(!callbacks){
      callbacks = [{
        callback () {
          atom.workspace.open(related.getTargetPath(matchedExpItem.targetType),{initialLine: Number.MAX_VALUE, initialColumn: 0, searchAllPanes:true});
        }
      }];
    }

    return {
      range,
      callback : callbacks.length===1? callbacks[0].callback:callbacks
    };
  },
  priority: 1
}

module.exports = {
  getProvider() {
    return [xmlClickProvider];
  },
};
<commit_msg>support "jump to event handler definition"<commit_after>'use babel';
/* @flow */

var related = require('./related');
var fs = require('fs');
var _ = require('underscore');

var wordRegExp = /^[	 ]*$|[^\s\/\\\(\)"':,;<>~!@\$%\^&\*\|\+=\[\]\{\}`\?\-…]+/g
// default :     /^[	 ]*$|[^\s\/\\\(\)"':,\.;<>~!@#\$%\^&\*\|\+=\[\]\{\}`\?\-…]+/g
// by atom.workspace.getActiveTextEditor().getLastCursor().wordRegExp({includeNonWordCharacters:false});

var alloyPathReg = /\/(controllers|views|styles)\/(.*)?\.(.*)/;
var selectorReg =  /(class|id)=\"[\sa-zA-Z-_^]*$/;

var fromXmlRegExps = [
  { // class
    regExp : /class=["'][\sa-zA-Z-_^]*$/,
    getTargetRegExp (text){
      return new RegExp(`["'].${text}`,'g');
    },
    targetType : 'tss'
  },
  { // id
    regExp : /id=["'][\sa-zA-Z-_^]*$/,
    getTargetRegExp (text){
      return new RegExp(`["']#${text}`,'g');
    },
    targetType : 'tss'
  },
  { // tag
    regExp : /<$/,
    getTargetRegExp (text){
      return new RegExp(`["']${text}`,'g');
    },
    targetType : 'tss'
  },
  { //handler
    regExp : /on(.*?)=["']/,
    getTargetRegExp (text){
      return new RegExp(`function ${text}\s*?\\(`)
    },
    targetType : 'js'
  }
];

function findDefinition(path,regExp, textEditor){
  var callbacks = [];
  var targetBuffer = _.find(atom.workspace.getTextEditors(), (editor) => {
    return editor.getPath() === path;
  });

  if(!targetBuffer){ // if targetFile not opened yet, use new buffer
    targetBuffer = new textEditor.buffer.constructor; //require('text-buffer')
    targetBuffer.setPath(path);
    targetBuffer.loadSync();
  }

  targetBuffer.scan(regExp,function(item){
    callbacks.push({
      title : item.lineText,
      callback (){
        atom.workspace.open(path,{initialLine: item.range.start.row, initialColumn: item.range.start.column, searchAllPanes:true});
      }
    });
  });

  return callbacks.length?callbacks:false;
}

var xmlClickProvider = {
  wordRegExp ,
  getSuggestionForWord(textEditor: TextEditor, text: string, range: Range): HyperclickSuggestion {
    var [isAlloy=false,alloyType,filename,fileExt] = textEditor.getPath().match(alloyPathReg);
    if(!text || fileExt!='xml') return;

    var lineText = textEditor.getTextInBufferRange([[range.start.row,0],[range.start.row,range.start.column]]);
    var callbacks;

    var matchedExpItem = _.find(fromXmlRegExps,function(item){
      return item.regExp.test(lineText);
    });

    if(!matchedExpItem) return;

    callbacks = findDefinition(related.getTargetPath(matchedExpItem.targetType), matchedExpItem.getTargetRegExp(text), textEditor);

    //if no definition, go last line of ther code
    if(!callbacks){
      callbacks = [{
        callback () {
          atom.workspace.open(related.getTargetPath(matchedExpItem.targetType),{initialLine: Number.MAX_VALUE, initialColumn: 0, searchAllPanes:true});
        }
      }];
    }

    return {
      range,
      callback : callbacks.length===1? callbacks[0].callback:callbacks
    };
  },
  priority: 1
}

module.exports = {
  getProvider() {
    return [xmlClickProvider];
  },
};
<|endoftext|>


<commit_before>/* global
  AccountsTemplates: false,
  BlazeLayout: false,
  grecaptcha: false,
  FlowRouter: false,
  $: false
*/
'use strict';

// Previous path used for redirect after form submit
AccountsTemplates._prevPath = null;

// Possibly keeps reference to the handle for the timed out redirect
// set on some routes
AccountsTemplates.timedOutRedirect = null;

AccountsTemplates.clearState = function() {
  _.each(this._fields, function(field) {
    field.clearStatus();
  });
  var form = this.state.form;
  form.set('error', null);
  form.set('result', null);
  form.set('message', null);

  AccountsTemplates.setDisabled(false);

  // Possibly clears timed out redirects
  if (AccountsTemplates.timedOutRedirect !== null) {
    Meteor.clearTimeout(AccountsTemplates.timedOutRedirect);
    AccountsTemplates.timedOutRedirect = null;
  }
};

AccountsTemplates.getparamToken = function() {
  return FlowRouter.getParam('paramToken');
};

// Getter for previous route's path
AccountsTemplates.getPrevPath = function() {
  return this._prevPath;
};

// Setter for previous route's path
AccountsTemplates.setPrevPath = function(newPath) {
  check(newPath, String);
  this._prevPath = newPath;
};

AccountsTemplates.ensureSignedIn = function(context, redirect) {
  if (!Meteor.userId()) {
    // if we're not already on an AT route
    if (!_.contains(AccountsTemplates.knownRoutes, context.path)) {

      AccountsTemplates.setState(AccountsTemplates.options.defaultState, function() {
        var err = AccountsTemplates.texts.errors.mustBeLoggedIn;
        AccountsTemplates.state.form.set("error", [err]);
      });

      // redirect settings
      AccountsTemplates.avoidDefaultRedirect = true;
      AccountsTemplates.redirectToPrevPath = true;

      // redirect to defined sign-in route and then redirect back
      // to original route after successful sign in
      redirect('signIn');
    }
  }
};

// Stores previous path on path change...
FlowRouter.triggers.enter([
  function(context) {
    var isKnownRoute = _.map(AccountsTemplates.knownRoutes, function(path) {
      if (!path) {
        return false;
      }
      var known = RegExp(path).test(context.path);
      return known;
    });
    if (!_.some(isKnownRoute)) {
      AccountsTemplates.setPrevPath(context.path);
    }
  }
]);

AccountsTemplates.linkClick = function(route) {
  if (AccountsTemplates.disabled()) {
    return;
  }
  var path = AccountsTemplates.getRoutePath(route);
  if (path === '#' || AccountsTemplates.avoidDefaultRedirect || path === FlowRouter.current().path) {
    AccountsTemplates.setState(route);
  } else {
    Meteor.defer(function() {
      FlowRouter.go(path);
    });
  }

  var firstVisibleInput = _.find(this.getFields(), function(f) {
    return _.contains(f.visible, route);
  });
  if (firstVisibleInput) {
    $('input#at-field-' + firstVisibleInput._id).focus();
  }
};

AccountsTemplates.logout = function() {
  var onLogoutHook = AccountsTemplates.options.onLogoutHook;
  var homeRoutePath = AccountsTemplates.options.homeRoutePath;
  Meteor.logout(function() {
    if (onLogoutHook) {
      onLogoutHook();
    } else if (homeRoutePath) {
      FlowRouter.redirect(homeRoutePath);
    }
  });
};

AccountsTemplates.postSubmitRedirect = function(route) {
  if (AccountsTemplates.avoidDefaultRedirect) {
    AccountsTemplates.avoidDefaultRedirect = false;
    if (AccountsTemplates.redirectToPrevPath) {
      FlowRouter.redirect(AccountsTemplates.getPrevPath());
    }
  } else {
    var nextPath = AccountsTemplates.routes[route] && AccountsTemplates.routes[route].redirect;
    if (nextPath) {
      if (_.isFunction(nextPath)) {
        nextPath();
      } else {
        FlowRouter.go(nextPath);
      }
    } else {
      var previousPath = AccountsTemplates.getPrevPath();
      if (previousPath && FlowRouter.current().path !== previousPath) {
        FlowRouter.go(previousPath);
      } else {
        var homeRoutePath = AccountsTemplates.options.homeRoutePath;
        if (homeRoutePath) {
          FlowRouter.go(homeRoutePath);
        }
      }
    }
  }
};

AccountsTemplates.submitCallback = function(error, state, onSuccess) {

  var onSubmitHook = AccountsTemplates.options.onSubmitHook;
  if (onSubmitHook) {
    onSubmitHook(error, state);
  }

  if (error) {
    if (_.isObject(error.details)) {
      // If error.details is an object, we may try to set fields errors from it
      _.each(error.details, function(error, fieldId) {
        AccountsTemplates.getField(fieldId).setError(error);
      });
    } else {
      var err = 'error.accounts.Unknown error';
      if (error.reason) {
        err = error.reason;
      }
      if (err.substring(0, 15) !== 'error.accounts.') {
        err = 'error.accounts.' + err;
      }
      AccountsTemplates.state.form.set('error', [err]);
    }
    AccountsTemplates.setDisabled(false);
    // Possibly resets reCaptcha form
    if (state === 'signUp' && AccountsTemplates.options.showReCaptcha) {
      grecaptcha.reset();
    }
  } else {
    if (onSuccess) {
      onSuccess();
    }

    if (_.contains(['enrollAccount', 'forgotPwd', 'resetPwd', 'verifyEmail'], state)) {
      var redirectTimeout = AccountsTemplates.options.redirectTimeout;
      if (redirectTimeout > 0) {
        AccountsTemplates.timedOutRedirect = Meteor.setTimeout(function() {
          AccountsTemplates.timedOutRedirect = null;
          AccountsTemplates.setDisabled(false);
          AccountsTemplates.postSubmitRedirect(state);
        }, redirectTimeout);
      }
    } else if (state) {
      AccountsTemplates.setDisabled(false);
      AccountsTemplates.postSubmitRedirect(state);
    }
  }
};

// Initialization
if (FlowRouter && FlowRouter.initialize) {
  // In order for ensureSignIn triggers to work,
  // AccountsTemplates must be initialized before FlowRouter
  // (this is now true since useraccounts:core is being executed first...)
  var oldInitialize = FlowRouter.initialize;
  FlowRouter.initialize = function() {
    AccountsTemplates._init();
    oldInitialize.apply(this, arguments);
  };
}
<commit_msg>avoidRedirect no longer used<commit_after>/* global
  AccountsTemplates: false,
  BlazeLayout: false,
  grecaptcha: false,
  FlowRouter: false,
  $: false
*/
'use strict';

// Previous path used for redirect after form submit
AccountsTemplates._prevPath = null;

// Possibly keeps reference to the handle for the timed out redirect
// set on some routes
AccountsTemplates.timedOutRedirect = null;

AccountsTemplates.clearState = function() {
  _.each(this._fields, function(field) {
    field.clearStatus();
  });
  var form = this.state.form;
  form.set('error', null);
  form.set('result', null);
  form.set('message', null);

  AccountsTemplates.setDisabled(false);

  // Possibly clears timed out redirects
  if (AccountsTemplates.timedOutRedirect !== null) {
    Meteor.clearTimeout(AccountsTemplates.timedOutRedirect);
    AccountsTemplates.timedOutRedirect = null;
  }
};

AccountsTemplates.getparamToken = function() {
  return FlowRouter.getParam('paramToken');
};

// Getter for previous route's path
AccountsTemplates.getPrevPath = function() {
  return this._prevPath;
};

// Setter for previous route's path
AccountsTemplates.setPrevPath = function(newPath) {
  check(newPath, String);
  this._prevPath = newPath;
};

AccountsTemplates.ensureSignedIn = function(context, redirect) {
  if (!Meteor.userId()) {
    // if we're not already on an AT route
    if (!_.contains(AccountsTemplates.knownRoutes, context.path)) {

      AccountsTemplates.setState(AccountsTemplates.options.defaultState, function() {
        var err = AccountsTemplates.texts.errors.mustBeLoggedIn;
        AccountsTemplates.state.form.set("error", [err]);
      });

      // redirect settings
      AccountsTemplates.avoidDefaultRedirect = true;
      AccountsTemplates.redirectToPrevPath = true;

      // redirect to defined sign-in route and then redirect back
      // to original route after successful sign in
      redirect('signIn');
    }
  }
};

// Stores previous path on path change...
FlowRouter.triggers.enter([
  function(context) {
    var isKnownRoute = _.map(AccountsTemplates.knownRoutes, function(path) {
      if (!path) {
        return false;
      }
      var known = RegExp(path).test(context.path);
      return known;
    });
    if (!_.some(isKnownRoute)) {
      AccountsTemplates.setPrevPath(context.path);
    }
  }
]);

AccountsTemplates.linkClick = function(route) {
  if (AccountsTemplates.disabled()) {
    return;
  }
  var path = AccountsTemplates.getRoutePath(route);
  if (path === '#' || path === FlowRouter.current().path) {
    AccountsTemplates.setState(route);
  } else {
    Meteor.defer(function() {
      FlowRouter.go(path);
    });
  }

  var firstVisibleInput = _.find(this.getFields(), function(f) {
    return _.contains(f.visible, route);
  });
  if (firstVisibleInput) {
    $('input#at-field-' + firstVisibleInput._id).focus();
  }
};

AccountsTemplates.logout = function() {
  var onLogoutHook = AccountsTemplates.options.onLogoutHook;
  var homeRoutePath = AccountsTemplates.options.homeRoutePath;
  Meteor.logout(function() {
    if (onLogoutHook) {
      onLogoutHook();
    } else if (homeRoutePath) {
      FlowRouter.redirect(homeRoutePath);
    }
  });
};

AccountsTemplates.postSubmitRedirect = function(route) {
  if (AccountsTemplates.avoidDefaultRedirect) {
    AccountsTemplates.avoidDefaultRedirect = false;
    if (AccountsTemplates.redirectToPrevPath) {
      FlowRouter.redirect(AccountsTemplates.getPrevPath());
    }
  } else {
    var nextPath = AccountsTemplates.routes[route] && AccountsTemplates.routes[route].redirect;
    if (nextPath) {
      if (_.isFunction(nextPath)) {
        nextPath();
      } else {
        FlowRouter.go(nextPath);
      }
    } else {
      var previousPath = AccountsTemplates.getPrevPath();
      if (previousPath && FlowRouter.current().path !== previousPath) {
        FlowRouter.go(previousPath);
      } else {
        var homeRoutePath = AccountsTemplates.options.homeRoutePath;
        if (homeRoutePath) {
          FlowRouter.go(homeRoutePath);
        }
      }
    }
  }
};

AccountsTemplates.submitCallback = function(error, state, onSuccess) {

  var onSubmitHook = AccountsTemplates.options.onSubmitHook;
  if (onSubmitHook) {
    onSubmitHook(error, state);
  }

  if (error) {
    if (_.isObject(error.details)) {
      // If error.details is an object, we may try to set fields errors from it
      _.each(error.details, function(error, fieldId) {
        AccountsTemplates.getField(fieldId).setError(error);
      });
    } else {
      var err = 'error.accounts.Unknown error';
      if (error.reason) {
        err = error.reason;
      }
      if (err.substring(0, 15) !== 'error.accounts.') {
        err = 'error.accounts.' + err;
      }
      AccountsTemplates.state.form.set('error', [err]);
    }
    AccountsTemplates.setDisabled(false);
    // Possibly resets reCaptcha form
    if (state === 'signUp' && AccountsTemplates.options.showReCaptcha) {
      grecaptcha.reset();
    }
  } else {
    if (onSuccess) {
      onSuccess();
    }

    if (_.contains(['enrollAccount', 'forgotPwd', 'resetPwd', 'verifyEmail'], state)) {
      var redirectTimeout = AccountsTemplates.options.redirectTimeout;
      if (redirectTimeout > 0) {
        AccountsTemplates.timedOutRedirect = Meteor.setTimeout(function() {
          AccountsTemplates.timedOutRedirect = null;
          AccountsTemplates.setDisabled(false);
          AccountsTemplates.postSubmitRedirect(state);
        }, redirectTimeout);
      }
    } else if (state) {
      AccountsTemplates.setDisabled(false);
      AccountsTemplates.postSubmitRedirect(state);
    }
  }
};

// Initialization
if (FlowRouter && FlowRouter.initialize) {
  // In order for ensureSignIn triggers to work,
  // AccountsTemplates must be initialized before FlowRouter
  // (this is now true since useraccounts:core is being executed first...)
  var oldInitialize = FlowRouter.initialize;
  FlowRouter.initialize = function() {
    AccountsTemplates._init();
    oldInitialize.apply(this, arguments);
  };
}
<|endoftext|>


<commit_before>//client.js

var fs           = require('fs'),
    request      = require('request'),
    util         = require('util'),
    EventEmitter = require('events').EventEmitter,
    Client       = require('./client').Client,
    qs           = require('querystring'),
    async        = require('async');

var Client = exports.Client = function (options) {
  this.options = options;
  this._request = request;

  if (typeof this.options.get !== 'function') {
    this.options.get = function (key) {
      return this[key];
    };
  }

};

util.inherits(Client, EventEmitter);

Client.prototype.request = function (method, uri) {
  var options, params = '', last_element, url, args = Array.prototype.slice.call(arguments),
      callback = args.pop(),
      body     = typeof args[args.length - 1] === 'object' && !Array.isArray(args[args.length - 1]) && args.pop(),
      auth     = this.options.get('password') ? ':' + this.options.get('password') : '/token:' + this.options.get('token'),
      encoded  = new Buffer(this.options.get('username') + auth).toString('base64'),
      proxy    = this.options.get('proxy');

  if (typeof uri === 'object' && Array.isArray(uri)) {
    last_element = uri.pop();
    if (typeof last_element === 'object') {
      params = '?' + qs.stringify(last_element);
    } else {
      uri.push(last_element);
    }
    url = this.options.get('remoteUri') + '/' + uri.join('/') + '.json' + params;
  } else {
    if (uri.indexOf(this.options.get('remoteUri')) === -1) {
      url = this.options.get('remoteUri') + uri;
    } else {
      url = uri;
    }
  }

  if(!options){
    options = {
      method: method || 'GET',
      uri: url,
      headers: {
        'Authorization': 'Basic ' + encoded,
        'Content-Type' : 'application/json',
        'Accept'       : 'application/json'
      }
    };
  }

  if (body) {
    options.body = JSON.stringify(body);
  }
  else if (method !== 'GET') {
    options.body = '{}';
  }

  if (proxy) {
    options.proxy = proxy;
  }

  var self = this;

  self.emit('debug::request', options);

  this._request(options, function (err, response, body) {
    if (err) {
      return callback(err);
    }

    var statusCode, result, error;

    try {
      statusCode = response.statusCode;
      result = JSON.parse(body);
    }
    catch (ex) {
      // Ignore Errors
    }

    self.emit('debug::response', { statusCode: statusCode, result: result });

    var retryAfter = response.headers['Retry-After'];
    if (retryAfter) {
      error = new Error('Zendesk rate limits 200 requests per minute');
      error.statusCode = 429;
      error.result = retryAfter;
      return callback(error);
    }

    if (failCodes[statusCode]) {
      error = new Error('Zendesk Error (' + statusCode + '): ' + failCodes[statusCode]);
      error.statusCode = statusCode;
      error.result = result;
      return callback(error);
    }

    callback(null, response, result);
  });
};

Client.prototype.requestAll = function (method, uri) {
  var args       = Array.prototype.slice.call(arguments),
      callback   = args.pop(),
      nextPage   = 'Not Null!',
      fullResult =  [],
      fullRequest = [],
      self       = this;

  return Client.prototype.request.apply(this, args.concat(function (error, request, result) {
    if (error) {
      return callback(error);
    }

    fullRequest.push(request);
    fullResult.push(result);
    nextPage = result.next_page;

    async.whilst(
      function () {return nextPage !== null && nextPage !== 'undefined'; },
      function (cb) {
        Client.prototype.request.apply(self, ['GET', nextPage, function (err, req, res) {
          if (err) {
            return cb(err);
          }

          fullRequest.push(req);
          fullResult.push(res);
          nextPage = res.next_page;
          cb(null);
        }]);
      },
      function (err) {
        if (err) {
          callback(err);
        } else {
          return callback(null, fullRequest, fullResult);
        }
      }
      );
  }));
};

Client.prototype.upload = function (uri, file, fileToken, callback) {//TODO
  var self       = this,
      out,
      auth     = this.options.get('password') ? ':' + this.options.get('password') : '/token:' + this.options.get('token'),
      encoded  = new Buffer(this.options.get('username') + auth).toString('base64');

  fs.stat(file, function (err, stat) {
    if (err) {
      return callback(err);
    }

    this.options = {
      method: 'POST',
      uri: self.options.get('remoteUri') + '/' + uri.join('/'),
      headers: {
        'Authorization' : 'Basic ' + encoded,
        'Content-Type'  : 'application/octet-stream',
        'Content-Length': stat.size
      }
    };

    out  = Client.prototype.request.apply(this, ['POST', uri,  function (error, request, result) {
      if (error) {
        return callback(error);
      }

      callback(null, request, result);

    }]);

    fs.createReadStream(file).pipe(out);

  });
};

var failCodes = {
  400: 'Bad Request',
  401: 'Not Authorized',
  403: 'Forbidden',
  404: 'Item not found',
  405: 'Method not Allowed',
  409: 'Conflict',
  429: 'Too Many Requests',
  500: 'Internal Server Error',
  503: 'Service Unavailable'
};

<commit_msg>[api] fleshed out the upload function better to adhere to API and provided way to pass on tokens<commit_after>//client.js

var fs           = require('fs'),
    request      = require('request'),
    util         = require('util'),
    EventEmitter = require('events').EventEmitter,
    Client       = require('./client').Client,
    qs           = require('querystring'),
    async        = require('async'),
    path         = require('path');

var Client = exports.Client = function (options) {
  this.options = options;
  this._request = request;

  if (typeof this.options.get !== 'function') {
    this.options.get = function (key) {
      return this[key];
    };
  }

};

util.inherits(Client, EventEmitter);

Client.prototype.request = function (method, uri) {
  var options, params = '', last_element, url, self, args = Array.prototype.slice.call(arguments),
      callback = args.pop(),
      body     = typeof args[args.length - 1] === 'object' && !Array.isArray(args[args.length - 1]) && args.pop(),
      auth     = this.options.get('password') ? ':' + this.options.get('password') : '/token:' + this.options.get('token'),
      encoded  = new Buffer(this.options.get('username') + auth).toString('base64'),
      proxy    = this.options.get('proxy');

  if (typeof uri === 'object' && Array.isArray(uri)) {
    last_element = uri.pop();
    if (typeof last_element === 'object') {
      params = '?' + qs.stringify(last_element);
    } else {
      uri.push(last_element);
    }
    url = this.options.get('remoteUri') + '/' + uri.join('/') + '.json' + params;
  } else {
    if (uri.indexOf(this.options.get('remoteUri')) === -1) {
      url = this.options.get('remoteUri') + uri;
    } else {
      url = uri;
    }
  }

  if(!options){
    options = {
      method: method || 'GET',
      uri: url,
      headers: {
        'Authorization': 'Basic ' + encoded,
        'Content-Type' : 'application/json',
        'Accept'       : 'application/json'
      }
    };
  }

  if (body) {
    options.body = JSON.stringify(body);
  }
  else if (method !== 'GET') {
    options.body = '{}';
  }

  if (proxy) {
    options.proxy = proxy;
  }

  self = this;
  self.emit('debug::request', options);

  this._request(options, function (err, response, body) {
    if (err) {
      return callback(err);
    }

    var statusCode, result, error;

    try {
      statusCode = response.statusCode;
      result = JSON.parse(body);
    }
    catch (ex) {
      // Ignore Errors
    }

    self.emit('debug::response', { statusCode: statusCode, result: result });

    var retryAfter = response.headers['Retry-After'];
    if (retryAfter) {
      error = new Error('Zendesk rate limits 200 requests per minute');
      error.statusCode = 429;
      error.result = retryAfter;
      return callback(error);
    }

    if (failCodes[statusCode]) {
      error = new Error('Zendesk Error (' + statusCode + '): ' + failCodes[statusCode]);
      error.statusCode = statusCode;
      error.result = result;
      return callback(error);
    }

    callback(null, response, result);
  });
};

Client.prototype.requestAll = function (method, uri) {
  var args       = Array.prototype.slice.call(arguments),
      callback   = args.pop(),
      nextPage   = 'Not Null!',
      fullResult =  [],
      fullRequest = [],
      self       = this;

  return Client.prototype.request.apply(this, args.concat(function (error, request, result) {
    if (error) {
      return callback(error);
    }

    fullRequest.push(request);
    fullResult.push(result);
    nextPage = result.next_page;

    async.whilst(
      function () {return nextPage !== null && nextPage !== 'undefined'; },
      function (cb) {
        Client.prototype.request.apply(self, ['GET', nextPage, function (err, req, res) {
          if (err) {
            return cb(err);
          }

          fullRequest.push(req);
          fullResult.push(res);
          nextPage = res.next_page;
          cb(null);
        }]);
      },
      function (err) {
        if (err) {
          callback(err);
        } else {
          return callback(null, fullRequest, fullResult);
        }
      }
      );
  }));
};

Client.prototype.upload = function (uri, file, fileToken, callback) {//TODO
  var self       = this,
      out,
      auth     = this.options.get('password') ? ':' + this.options.get('password') : '/token:' + this.options.get('token'),
      encoded  = new Buffer(this.options.get('username') + auth).toString('base64');

  if (fileToken !== null && fileToken !== undefined && fileToken !== '') {
    uri.push({filename: path.basename(file), token: fileToken});
  } else {
    uri.push({filename: path.basename(file)});
  }

  fs.stat(file, function (err, stat) {
    if (err) {
      return callback(err);
    }

    this.options = {
      method: 'POST',
      uri: self.options.get('remoteUri') + '/' + uri.join('/'),
      headers: {
        'Authorization' : 'Basic ' + encoded,
        'Content-Type'  : 'application/octet-stream',
        'Content-Length': stat.size
      }
    };

    out  = Client.prototype.request.apply(this, ['POST', uri,  function (error, request, result) {
      if (error) {
        return callback(error);
      }

      callback(null, request, result);

    }]);

    fs.createReadStream(file).pipe(out);

  });
};

var failCodes = {
  400: 'Bad Request',
  401: 'Not Authorized',
  403: 'Forbidden',
  404: 'Item not found',
  405: 'Method not Allowed',
  409: 'Conflict',
  429: 'Too Many Requests',
  500: 'Internal Server Error',
  503: 'Service Unavailable'
};

<|endoftext|>


<commit_before>var CloudCmd, Util, DOM;

(function(CloudCmd, Util, DOM) {
    'use strict';

    CloudCmd.Config = ConfigProto;

    function ConfigProto() {
        var Loading     = true,
            Key         = CloudCmd.Key,
            Images      = DOM.Images,
            Events      = DOM.Events,
            showLoad    = Images.showLoad.bind(DOM, {
                top: true
            }),
            Element,
            INPUT       = 'INPUT',
            CONFIG,
            Template,
            Notify      = DOM.Notify,
            Config      = this;

        function init() {
            Loading     = true;

            showLoad();
            Util.exec.series([
                CloudCmd.View,
                function(callback) {
                    Loading = false;
                    Util.exec(callback);
                },
                Config.show
            ]);
        }

        this.show               = function() {
            var exec    = Util.exec,
                funcs   = [
                    exec.with(DOM.Files.get, 'config-tmpl'),
                    exec.with(DOM.load.css, '/css/config.css')
                ];

            if (!Loading) {
                showLoad();
                exec.parallel(funcs, fillTemplate);
            }
        };

        function fillTemplate(error, template) {
            if (!Template)
                Template = template;

            DOM.Files.get('config', function(error, config) {
                var div, data, inputs, inputFirst,
                    focus, obj;

                CONFIG  = config;
                obj     = Util.copyObj(CONFIG);
                changeConfig(obj);
                data    = Util.render(Template, obj);
                div     = DOM.load({
                    name        : 'div',
                    className   : 'config',
                    inner       : data,
                    attribute   : {
                        'data-name': 'js-config'
                    }
                });

                Element = div;

                inputs      = DOM.getByTag(INPUT, div);
                inputFirst  = inputs[0];

                if (inputFirst)
                    focus   = function() {
                        inputFirst.focus();
                    };

                Util.forEach(inputs, function(input) {
                    Events.add('change', input, onChange)
                          .addKey(input, onKey);
                });

                CloudCmd.View.show(div, {
                    autoSize: true,
                    afterShow: focus
                });
            });
        }

        this.hide               = function() {
            CloudCmd.View.hide();
        };

        function changeConfig(config) {
            Object.keys(config).forEach(function(name) {
                var item    = config[name],
                    isBool  = Util.isBoolean(item);

                if (isBool)
                    config[name] = setState(item);
            });
        }

        function setState(state) {
            var ret = '';

            if (state)
                ret = ' checked';

            return ret;
        }

        function onChange(event) {
            var data,
                Config  = DOM.RESTful.Config,
                obj     = {},
                el      = event.target,
                name    = el.id,
                type    = el.type;

            switch(type) {
            case 'checkbox':
                data = el.checked;

                if (el.id === 'localStorage')
                    onLocalStorageChange(data);
                else if (el.id === 'diff')
                    onDiffChange(data);

                break;
            case 'number':
                data = el.value - 0;
                break;
            default:
                data = el.value;
                break;
            }

            obj[name] = data;

            if (name === 'notifications') {
                if (data && !Notify.check())
                    Notify.request();
            }

            CONFIG[name] = data;

            DOM.Files.set('config', CONFIG, function() {
                Config.write(obj);
            });
        }

        function onLocalStorageChange(checked) {
            var element = DOM.getById('diff', Element),
                msg     = 'Diff would not working with no localStorage.\n' +
                          'Use Zip to improve save spead in Edit.';

            if (!checked && element.checked) {
                alert(msg);

                element.checked = false;
                onChange({
                    target: element
                });
            }
        }

        function onDiffChange(checked) {
            var element = DOM.getById('localStorage', Element);

            if (!element.checked && checked) {
                onLocalStorageChange(element.checked);
            }

            return element.checked;
        }

        function onKey(event) {
            var keyCode = event.keyCode,
                ESC     = Key.ESC;

            if (keyCode === ESC)
                Config.hide();
        }

        init();
    }

})(CloudCmd, Util, DOM);
<commit_msg>chore(config) onLocalStorageChange: change msg<commit_after>var CloudCmd, Util, DOM;

(function(CloudCmd, Util, DOM) {
    'use strict';

    CloudCmd.Config = ConfigProto;

    function ConfigProto() {
        var Loading     = true,
            Key         = CloudCmd.Key,
            Images      = DOM.Images,
            Events      = DOM.Events,
            showLoad    = Images.showLoad.bind(DOM, {
                top: true
            }),
            Element,
            INPUT       = 'INPUT',
            CONFIG,
            Template,
            Notify      = DOM.Notify,
            Config      = this;

        function init() {
            Loading     = true;

            showLoad();
            Util.exec.series([
                CloudCmd.View,
                function(callback) {
                    Loading = false;
                    Util.exec(callback);
                },
                Config.show
            ]);
        }

        this.show               = function() {
            var exec    = Util.exec,
                funcs   = [
                    exec.with(DOM.Files.get, 'config-tmpl'),
                    exec.with(DOM.load.css, '/css/config.css')
                ];

            if (!Loading) {
                showLoad();
                exec.parallel(funcs, fillTemplate);
            }
        };

        function fillTemplate(error, template) {
            if (!Template)
                Template = template;

            DOM.Files.get('config', function(error, config) {
                var div, data, inputs, inputFirst,
                    focus, obj;

                CONFIG  = config;
                obj     = Util.copyObj(CONFIG);
                changeConfig(obj);
                data    = Util.render(Template, obj);
                div     = DOM.load({
                    name        : 'div',
                    className   : 'config',
                    inner       : data,
                    attribute   : {
                        'data-name': 'js-config'
                    }
                });

                Element = div;

                inputs      = DOM.getByTag(INPUT, div);
                inputFirst  = inputs[0];

                if (inputFirst)
                    focus   = function() {
                        inputFirst.focus();
                    };

                Util.forEach(inputs, function(input) {
                    Events.add('change', input, onChange)
                          .addKey(input, onKey);
                });

                CloudCmd.View.show(div, {
                    autoSize: true,
                    afterShow: focus
                });
            });
        }

        this.hide               = function() {
            CloudCmd.View.hide();
        };

        function changeConfig(config) {
            Object.keys(config).forEach(function(name) {
                var item    = config[name],
                    isBool  = Util.isBoolean(item);

                if (isBool)
                    config[name] = setState(item);
            });
        }

        function setState(state) {
            var ret = '';

            if (state)
                ret = ' checked';

            return ret;
        }

        function onChange(event) {
            var data,
                Config  = DOM.RESTful.Config,
                obj     = {},
                el      = event.target,
                name    = el.id,
                type    = el.type;

            switch(type) {
            case 'checkbox':
                data = el.checked;

                if (el.id === 'localStorage')
                    onLocalStorageChange(data);
                else if (el.id === 'diff')
                    onDiffChange(data);

                break;
            case 'number':
                data = el.value - 0;
                break;
            default:
                data = el.value;
                break;
            }

            obj[name] = data;

            if (name === 'notifications') {
                if (data && !Notify.check())
                    Notify.request();
            }

            CONFIG[name] = data;

            DOM.Files.set('config', CONFIG, function() {
                Config.write(obj);
            });
        }

        function onLocalStorageChange(checked) {
            var element = DOM.getById('diff', Element),
                msg     = 'Diff do not work without localStorage';

            if (!checked && element.checked) {
                alert(msg);

                element.checked = false;
                onChange({
                    target: element
                });
            }
        }

        function onDiffChange(checked) {
            var element = DOM.getById('localStorage', Element);

            if (!element.checked && checked) {
                onLocalStorageChange(element.checked);
            }

            return element.checked;
        }

        function onKey(event) {
            var keyCode = event.keyCode,
                ESC     = Key.ESC;

            if (keyCode === ESC)
                Config.hide();
        }

        init();
    }

})(CloudCmd, Util, DOM);
<|endoftext|>


<commit_before>var utils = require('./utils');

// Event stream factory
module.exports = function factory (instance, context) {

    // create stream object
    var stream = utils.clone(Stream);
    stream._ = instance;
    stream._h = [];
    stream._o = [];
    stream._i = [];

    // merge context into steam
    if (context) {
        for (var prop in context) {
            stream[prop] = context[prop];
        }
    }

    return stream;
};

/**
 * Stream like events.
 *
 * @class Stream
 */
var Stream = {

    // handler for incoming data
    data: function (handler, options) {
        this._h.push([handler, options]);
        return this;
    },

    // send data
    write: function (err, data) {

        // call handlers on output streams
        for (var o = 0, ol = this._o.length, stream, handlers; o < ol; ++o) {

            // get ouputs input handlers
            stream = this._o[o];
            handlers = stream._h;

            // call data handlers with err and data as arguments
            for (var i = 0, l = handlers.length; i < l; ++i) {

                //call data handler with stream instance as function scope
                var newData = handlers[i][0].call(stream, err, data, handlers[i][1]);

                // overwrite data with transformed data
                if (newData !== undefined) {
                    data = newData;
                }
            }
        }

        // call custom write handler
        if (typeof this._write === 'function') {
            this._write(err, data);
        }

        return this;
    },

    end: function () {

        // remove from output streams
        for (var i = 0, l = this._i.length; i < l; ++i) {
            // end input stream if all outputs ended
            if (!this._i[i][0]._o.length) {
                this._i[i][0].end();
            } else {
                this._i[i][0]._o.splice(this._i[i][1], 1);
            }
        }

        // remove refs
        this._ = this._i = this._o = undefined;

        // call custom end handler
        if (typeof this._end === 'function') {
            this._end.apply(this, arguments);
        }
    },

    // pipe data to an stream
    pipe: function (stream) {

        // save input stream and output index on output stream
        stream._i.push([this, this._o.length]);

        // push output stream
        this._o.push(stream);

        // return out stream for unix like piping (a.pipe(b).pipe(a))
        return stream;
    }
};
<commit_msg>set an empty array to prevent errors<commit_after>var utils = require('./utils');

// Event stream factory
module.exports = function factory (instance, context) {

    // create stream object
    var stream = utils.clone(Stream);
    stream._ = instance;
    stream._h = [];
    stream._o = [];
    stream._i = [];

    // merge context into steam
    if (context) {
        for (var prop in context) {
            stream[prop] = context[prop];
        }
    }

    return stream;
};

/**
 * Stream like events.
 *
 * @class Stream
 */
var Stream = {

    // handler for incoming data
    data: function (handler, options) {
        this._h.push([handler, options]);
        return this;
    },

    // send data
    write: function (err, data) {

        // call handlers on output streams
        for (var o = 0, ol = this._o.length, stream, handlers; o < ol; ++o) {

            // get ouputs input handlers
            stream = this._o[o];
            handlers = stream._h;

            // call data handlers with err and data as arguments
            for (var i = 0, l = handlers.length; i < l; ++i) {

                //call data handler with stream instance as function scope
                var newData = handlers[i][0].call(stream, err, data, handlers[i][1]);

                // overwrite data with transformed data
                if (newData !== undefined) {
                    data = newData;
                }
            }
        }

        // call custom write handler
        if (typeof this._write === 'function') {
            this._write(err, data);
        }

        return this;
    },

    end: function () {

        // remove from output streams
        for (var i = 0, l = this._i.length; i < l; ++i) {
            // end input stream if all outputs ended
            if (!this._i[i][0]._o.length) {
                this._i[i][0].end();
            } else {
                this._i[i][0]._o.splice(this._i[i][1], 1);
            }
        }

        // remove refs
        this._ = this._i = this._o = [];

        // call custom end handler
        if (typeof this._end === 'function') {
            this._end.apply(this, arguments);
        }
    },

    // pipe data to an stream
    pipe: function (stream) {

        // save input stream and output index on output stream
        stream._i.push([this, this._o.length]);

        // push output stream
        this._o.push(stream);

        // return out stream for unix like piping (a.pipe(b).pipe(a))
        return stream;
    }
};
<|endoftext|>


<commit_before>var CloudCommander, Util, DOM, CloudFunc, $;
/* object contains viewer FancyBox
 * https://github.com/fancyapps/fancyBox
 */
(function(CloudCmd, Util, DOM, CloudFunc){
    'use strict';

    var KeyBinding                      = CloudCmd.KeyBinding,
        FancyBox                        = {},

        Config = {
            beforeShow  : function(){
                DOM.Images.hideLoad();
                KeyBinding.unSet();
            },

            afterShow   : function(){
                var lEditor = DOM.getById('CloudViewer');
                if(lEditor)
                    lEditor.focus();
            },

            beforeClose : Util.retFunc( KeyBinding.set ),

            openEffect      : 'none',
            closeEffect     : 'none',
            autoSize        : false,
            height          : window.innerHeight,
            helpers : {
                overlay : {
                    css : {
                        'background'  : 'rgba(255, 255, 255, 0.1)'
                    }
                }
            },
            padding : 0
        };

    CloudCmd.Viewer                     = {
        get: (function(){
            return this.FancyBox;
        })
    };

    /**
     * function loads css and js of FancyBox
     * @pParent     - this
     * @pCallBack   -  executes, when everything loaded
     */
    FancyBox.load                       = function(pCallBack){
        console.time('fancybox load');
        var lDir    = CloudCmd.LIBDIRCLIENT + 'viewer/fancyBox/source/',
            lFiles  = [ lDir + 'jquery.fancybox.css',
                        lDir + 'jquery.fancybox.js' ];

        DOM.anyLoadOnLoad([lFiles], function(){
            console.timeEnd('fancybox load');
            Util.exec( pCallBack );
        })
        .cssSet({id:'viewer',
            inner : '#CloudViewer{'                         +
                        'font-size: 16px;'                  +
                        'white-space :pre'                  +
                    '}'                                     +
                    '#CloudViewer::selection{'              +
                        /*
                            'background: #fe57a1;'
                            'color: #fff;'
                        */
                        'background: #b3d4fc;'              +
                        'text-shadow: none;'                +
                    '}'
        });

    };

    FancyBox.showHelp                   = function(){
        DOM.Images.showLoad();
        DOM.ajax({
            url: '/README.md',
            success:  function (pData){
                var lData = {text: pData};
                DOM.ajax({
                    method  : 'post',
                    url     : 'https://api.github.com/markdown',
                    data    : Util.stringifyJSON(lData),
                    success:function(pResult){
                        DOM.Images.hideLoad();
                        $.fancybox(pResult, Config);
                    },

                    error: DOM.Images.showError
                });
            },

            error:DOM.Images.showError
        });
    };

    /**
     * function shows FancyBox
     */
    FancyBox.show                       = function(pCallBack){
        var lPath = DOM.getCurrentPath();

        if( Util.checkExtension(CloudFunc.FS + lPath, ['png','jpg', 'gif','ico']) )
            $.fancybox.open({ href : lPath }, Config);
        else
           DOM.getCurrentData(function(pParams){
                $.fancybox('
' +
                    pParams.data + '
', Config);
            });

        Util.exec(pCallBack);
    };

    CloudCmd.Viewer.init                = function(pCallBack){
        Util.loadOnLoad([
            pCallBack,
            FancyBox.show,
            FancyBox.load,
            DOM.jqueryLoad
        ]);

        var lView = function(){
            DOM.Images.showLoad();
            FancyBox.show( DOM.getCurrentFile() );
        };

        var lKeyListener = function(pEvent){
            var lKEY        = CloudCmd.KEY,
                lF3         = lKEY.F3,
                lKeyBinded  = KeyBinding.get(),
                lKeyCode    = pEvent.keyCode,
                lShift      = pEvent.shiftKey;

            /* если клавиши можно обрабатывать */
            if( lKeyBinded){
                if(lKeyCode === lF3 && lShift){
                    lView();
                    pEvent.preventDefault();
                }
                else if(lKeyCode === lKEY.F1)
                    FancyBox.showHelp();
            }
        };

        /* добавляем обработчик клавишь */
        DOM.addKeyListener(lKeyListener)
            .setButtonKey('f3', lView);
    };

    CloudCmd.Viewer.FancyBox            = FancyBox;

})(CloudCommander, Util, DOM, CloudFunc);<commit_msg>minor changes<commit_after>var CloudCommander, Util, DOM, CloudFunc, $;
/* object contains viewer FancyBox
 * https://github.com/fancyapps/fancyBox
 */
(function(CloudCmd, Util, DOM, CloudFunc){
    'use strict';

    var KeyBinding                      = CloudCmd.KeyBinding,
        FancyBox                        = {},

        Config = {
            beforeShow  : function(){
                DOM.Images.hideLoad();
                KeyBinding.unSet();
            },

            afterShow   : function(){
                var lEditor = DOM.getById('CloudViewer');
                if(lEditor)
                    lEditor.focus();
            },

            beforeClose : Util.retFunc( KeyBinding.set ),

            openEffect      : 'none',
            closeEffect     : 'none',
            autoSize        : false,
            height          : window.innerHeight,
            helpers : {
                overlay : {
                    css : {
                        'background'  : 'rgba(255, 255, 255, 0.1)'
                    }
                }
            },
            padding : 0
        };

    CloudCmd.Viewer                     = {
        get: (function(){
            return this.FancyBox;
        })
    };

    /**
     * function loads css and js of FancyBox
     * @pParent     - this
     * @pCallBack   -  executes, when everything loaded
     */
    FancyBox.load                       = function(pCallBack){
        console.time('fancybox load');
        var lDir    = CloudCmd.LIBDIRCLIENT + 'viewer/fancyBox/source/',
            lFiles  = [ lDir + 'jquery.fancybox.css',
                        lDir + 'jquery.fancybox.js' ];

        DOM.anyLoadOnLoad([lFiles], function(){
            console.timeEnd('fancybox load');
            Util.exec( pCallBack );
        })
        .cssSet({id:'viewer',
            inner : '#CloudViewer{'                         +
                        'font-size: 16px;'                  +
                        'white-space :pre'                  +
                    '}'                                     +
                    '#CloudViewer::selection{'              +
                        /*
                            'background: #fe57a1;'
                            'color: #fff;'
                        */
                        'background: #b3d4fc;'              +
                        'text-shadow: none;'                +
                    '}'
        });

    };

    FancyBox.showHelp                   = function(){
        DOM.Images.showLoad();
        DOM.ajax({
            url: '/README.md',
            success:  function (pData){
                var lData = {text: pData};
                DOM.ajax({
                    method  : 'post',
                    url     : 'https://api.github.com/markdown',
                    data    : Util.stringifyJSON(lData),
                    success:function(pResult){
                        DOM.Images.hideLoad();
                        $.fancybox(pResult, Config);
                    },

                    error: DOM.Images.showError
                });
            },

            error:DOM.Images.showError
        });
    };

    /**
     * function shows FancyBox
     */
    FancyBox.show                       = function(pCallBack){
        var lPath = CloudFunc.FS + DOM.getCurrentPath();

        if( Util.checkExtension(lPath, ['png','jpg', 'gif','ico']) )
            $.fancybox.open({ href : lPath }, Config);
        else
           DOM.getCurrentData(function(pParams){
                $.fancybox('
' +
                    pParams.data + '
', Config);
            });

        Util.exec(pCallBack);
    };

    CloudCmd.Viewer.init                = function(pCallBack){
        Util.loadOnLoad([
            pCallBack,
            FancyBox.show,
            FancyBox.load,
            DOM.jqueryLoad
        ]);

        var lView = function(){
            DOM.Images.showLoad();
            FancyBox.show( DOM.getCurrentFile() );
        };

        var lKeyListener = function(pEvent){
            var lKEY        = CloudCmd.KEY,
                lF3         = lKEY.F3,
                lKeyBinded  = KeyBinding.get(),
                lKeyCode    = pEvent.keyCode,
                lShift      = pEvent.shiftKey;

            /* если клавиши можно обрабатывать */
            if( lKeyBinded){
                if(lKeyCode === lF3 && lShift){
                    lView();
                    pEvent.preventDefault();
                }
                else if(lKeyCode === lKEY.F1)
                    FancyBox.showHelp();
            }
        };

        /* добавляем обработчик клавишь */
        DOM.addKeyListener(lKeyListener)
            .setButtonKey('f3', lView);
    };

    CloudCmd.Viewer.FancyBox            = FancyBox;

})(CloudCommander, Util, DOM, CloudFunc);<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Intel Corporation

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
var util = require('./utils').init();

/**
 *
 * @param deviceId
 * @param gatewayId
 * @constructor
 */
module.exports.Metadata = function Metadata (gatewayId) {
    this.gatewayId = gatewayId ;
    this.loc =  util.getLocation();
    this.attributes =  util.getAgentAttr();
};

module.exports.metadataExtended = function  (gatewayId, callback) {
    /*
        It's retrieve the external info.
     */
    var att = {
        attributes :  util.getAgentAttr(),
        gatewayId : gatewayId
    };

    util.externalInfo(function (data) {
        if (data) {
            att.loc = data.loc.split(',');
            att.loc = att.loc.map(function (od){
                            return parseInt(od);
                        });
            att.tags = [data.region, data.country];
        } else {
            att.loc = util.getLocation();
        }
        callback(att);
    });

};
/*{ ip: '134.134.139.70',
    hostname: 'No Hostname',
    city: 'Santa Clara',
    region: 'California',
    country: 'US',
    loc: '37.3541,-121.9552',
    org: 'AS4983 Intel Corporation',
    postal: '95052',
    ip_local: '10.0.2.15' }
*/
<commit_msg>remove updating<commit_after>/*
Copyright (c) 2014, Intel Corporation

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    * Neither the name of Intel Corporation nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
"use strict";
var util = require('./utils').init();

/**
 *
 * @param deviceId
 * @param gatewayId
 * @constructor
 */
module.exports.Metadata = function Metadata (gatewayId) {
    this.gatewayId = gatewayId ;
    this.loc =  util.getLocation();
    this.attributes =  util.getAgentAttr();
};

module.exports.metadataExtended = function  (gatewayId, callback) {
    /*
        It's retrieve the external info.
     */
    var att = {
        attributes :  util.getAgentAttr(),
        gatewayId : gatewayId
    };

    util.externalInfo(function (data) {
        if (data) {
            att.loc = data.loc.split(',');
            att.loc = att.loc.map(function (od){
                            return parseInt(od);
                        });
            att.tags = [data.region, data.country];
        } else {
            att.loc = util.getLocation();
        }
        callback(att);
    });

};
<|endoftext|>


<commit_before>var _    = require('lodash');
var util = require('util');

module.exports = commandChart;

function commandChart (token, options) {
  this.token = token;
  this.options = options;
}

commandChart.prototype.handle = function (req, res, cb) {
  /*
  {
    "text": "<http://chart.finance.yahoo.com...>",
    "attachments": [
      { "image_url": "<http://chart.finance.yahoo.com...>" }
    ]
  }
  */
  res.setHeader('content-type', 'application/json');
  //var chartUrl = "http://chart.finance.yahoo.com/t?lang=en-US&region=US&width=300&height=180&s=";
  //var chartUrl = "http://www.marketwatch.com/kaavio.Webhost/charts/big.chart?&symb="
  var chartUrl = "http://www.pnglogo.com/wp-content/uploads/2015/10/Monsters-Inc.-James-P.-Sullivan-PNG-04025.png";
  var symbol = req.body.text;
  //chartUrl += symbol;
  console.log(chartUrl);
  //var output = '<'+chartUrl+'>';
  //var output = '{"text":' + ' "<' + chartUrl + '>"' + ', "unfurl_link": true}';
  var output = '{';
  output += '"text":' + ' "' + 'Daily Chart for : ' + symbol + '" ,';
  output += '"attachments":' + '[';
  output += '{';
  output += '"image_url":' + ' "' + chartUrl + '"';
  //output += '"image_url":' + ' "' + chartUrl + '" ,';
  //output += '"unfurl_media": true';
  output += '}';
  output += ']';
  output += '}';
  cb(null, output);
};
<commit_msg>Trying a png image<commit_after>var _    = require('lodash');
var util = require('util');

module.exports = commandChart;

function commandChart (token, options) {
  this.token = token;
  this.options = options;
}

commandChart.prototype.handle = function (req, res, cb) {
  /*
  {
    "text": "<http://chart.finance.yahoo.com...>",
    "attachments": [
      { "image_url": "<http://chart.finance.yahoo.com...>" }
    ]
  }
  */
  res.setHeader('content-type', 'application/json');
  //var chartUrl = "http://chart.finance.yahoo.com/t?lang=en-US&region=US&width=300&height=180&s=";
  //var chartUrl = "http://www.marketwatch.com/kaavio.Webhost/charts/big.chart?&symb="
  var chartUrl = "http://www.jameshedberg.com/img/samples/carbon-nanotube-3D-model-axial.png";
  var symbol = req.body.text;
  //chartUrl += symbol;
  console.log(chartUrl);
  //var output = '<'+chartUrl+'>';
  //var output = '{"text":' + ' "<' + chartUrl + '>"' + ', "unfurl_link": true}';
  var output = '{';
  output += '"text":' + ' "' + 'Daily Chart for : ' + symbol + '" ,';
  output += '"attachments":' + '[';
  output += '{';
  output += '"image_url":' + ' "' + chartUrl + '"';
  //output += '"image_url":' + ' "' + chartUrl + '" ,';
  //output += '"unfurl_media": true';
  output += '}';
  output += ']';
  output += '}';
  cb(null, output);
};
<|endoftext|>