<commit_before>var _ = require('lodash'),
    parse = require('../parse'),
    $ = require('../static'),
    updateDOM = parse.update,
    evaluate = parse.evaluate,
    utils = require('../utils'),
    domEach = utils.domEach,
    encode = utils.encode,
    slice = Array.prototype.slice;

// Create an array of nodes, recursing into arrays and parsing strings if
// necessary
exports._makeDomArray = function makeDomArray(elem) {
  if (elem == null) {
    return [];
  } else if (elem.cheerio) {
    return elem.get();
  } else if (Array.isArray(elem)) {
    return _.flatten(elem.map(makeDomArray, this));
  } else if (typeof elem === 'string') {
    return evaluate(elem, this.options);
  } else {
    return [elem];
  }
};

var _insert = function(concatenator) {
  return function() {
    var self = this,
        elems = slice.call(arguments),
        dom = this._makeDomArray(elems);

    if (typeof elems[0] === 'function') {
      return domEach(this, function(i, el) {
        dom = self._makeDomArray(elems[0].call(el, i, $.html(el.children)));
        concatenator(dom, el.children, el);
      });
    } else {
      return domEach(this, function(i, el) {
        concatenator(dom, el.children, el);
      });
    }
  };
};

/*
 * Modify an array in-place, removing some number of elements and adding new
 * elements directly following them.
 *
 * @param {Array} array Target array to splice.
 * @param {Number} spliceIdx Index at which to begin changing the array.
 * @param {Number} spliceCount Number of elements to remove from the array.
 * @param {Array} newElems Elements to insert into the array.
 *
 * @api private
 */
var uniqueSplice = function(array, spliceIdx, spliceCount, newElems, parent) {
  var spliceArgs = [spliceIdx, spliceCount].concat(newElems),
      prev = array[spliceIdx - 1] || null,
      next = array[spliceIdx] || null;
  var idx, len, prevIdx, node;

  // Before splicing in new elements, ensure they do not already appear in the
  // current array.
  for (idx = 0, len = newElems.length; idx < len; ++idx) {
    node = newElems[idx];
    prevIdx = node.parent && array.indexOf(newElems[idx]);

    if (node.parent && prevIdx > -1) {
      array.splice(prevIdx, 1);
      if (spliceIdx > prevIdx) {
        spliceArgs[0]--;
      }
    }

    node.parent = parent;
    node.prev = newElems[idx - 1] || prev;
    node.next = newElems[idx + 1] || next;
  }

  if (prev) {
    prev.next = newElems[0];
  }
  if (next) {
    next.prev = newElems[newElems.length - 1];
  }

  return array.splice.apply(array, spliceArgs);
};

var append = exports.append = _insert(function(dom, children, parent) {
  uniqueSplice(children, children.length, 0, dom, parent);
});

var prepend = exports.prepend = _insert(function(dom, children, parent) {
  uniqueSplice(children, 0, 0, dom, parent);
});

var after = exports.after = function() {
  var elems = slice.call(arguments),
      dom = this._makeDomArray(elems),
      self = this;

  domEach(this, function(i, el) {
    var parent = el.parent || el.root,
        siblings = parent.children,
        index = siblings.indexOf(el);

    // If not found, move on
    if (!~index) return;

    if (typeof elems[0] === 'function') {
      dom = self._makeDomArray(elems[0].call(el, i));
    }

    // Add element after `this` element
    uniqueSplice(siblings, ++index, 0, dom, parent);
  });

  return this;
};

var before = exports.before = function() {
  var elems = slice.call(arguments),
      dom = this._makeDomArray(elems),
      self = this;

  domEach(this, function(i, el) {
    var parent = el.parent || el.root,
        siblings = parent.children,
        index = siblings.indexOf(el);

    // If not found, move on
    if (!~index) return;

    if (typeof elems[0] === 'function') {
      dom = self._makeDomArray(elems[0].call(el, i));
    }

    // Add element before `el` element
    uniqueSplice(siblings, index, 0, dom, parent);
  });

  return this;
};

/*
  remove([selector])
*/
var remove = exports.remove = function(selector) {
  var elems = this;

  // Filter if we have selector
  if (selector)
    elems = elems.filter(selector);

  domEach(elems, function(i, el) {
    var parent = el.parent || el.root,
        siblings = parent.children,
        index = siblings.indexOf(el);

    if (!~index) return;

    siblings.splice(index, 1);
    if (el.prev) {
      el.prev.next = el.next;
    }
    if (el.next) {
      el.next.prev = el.prev;
    }
    el.prev = el.next = el.parent = null;
  });

  return this;
};

var replaceWith = exports.replaceWith = function(content) {
  var self = this;

  domEach(this, function(i, el) {
    var parent = el.parent || el.root,
        siblings = parent.children,
        dom = self._makeDomArray(typeof content === 'function' ? content.call(el, i, el) : content),
        index;

    // In the case that `dom` contains nodes that already exist in other
    // structures, ensure those nodes are properly removed.
    updateDOM(dom, null);

    index = siblings.indexOf(el);

    // Completely remove old element
    uniqueSplice(siblings, index, 1, dom, parent);
    el.parent = el.prev = el.next = null;
  });

  return this;
};

var empty = exports.empty = function() {
  domEach(this, function(i, el) {
    _.each(el.children, function(el) {
      el.next = el.prev = el.parent = null;
    });

    el.children.length = 0;
  });
  return this;
};

/**
 * Set/Get the HTML
 */
var html = exports.html = function(str) {
  if (str === undefined) {
    if (!this[0] || !this[0].children) return null;
    return $.html(this[0].children);
  }

  domEach(this, function(i, el) {
    _.each(el.children, function(el) {
      el.next = el.prev = el.parent = null;
    });

    var content = str.cheerio ? str.clone().get() : evaluate(str, this.options);

    updateDOM(content, el);
  });

  return this;
};

var toString = exports.toString = function() {
  return $.html(this);
};

var text = exports.text = function(str) {
  // If `str` is undefined, act as a "getter"
  if (str === undefined) {
    return $.text(this);
  } else if (typeof str === 'function') {
    // Function support
    return domEach(this, function(i, el) {
      var $el = [el];
      return text.call($el, str.call(el, i, $.text($el)));
    });
  }

  // Append text node to each selected elements
  domEach(this, function(i, el) {
    _.each(el.children, function(el) {
      el.next = el.prev = el.parent = null;
    });

    var elem = {
      data: str,
      type: 'text',
      parent: el,
      prev: null,
      next: null,
      children: []
    };

    updateDOM(elem, el);
  });

  return this;
};

var clone = exports.clone = function() {
  // Turn it into HTML, then recreate it,
  // Seems to be the easiest way to reconnect everything correctly
  return this._make($.html(this));
};
<commit_msg>fixed context of `this` in .html<commit_after>var _ = require('lodash'),
    parse = require('../parse'),
    $ = require('../static'),
    updateDOM = parse.update,
    evaluate = parse.evaluate,
    utils = require('../utils'),
    domEach = utils.domEach,
    encode = utils.encode,
    slice = Array.prototype.slice;

// Create an array of nodes, recursing into arrays and parsing strings if
// necessary
exports._makeDomArray = function makeDomArray(elem) {
  if (elem == null) {
    return [];
  } else if (elem.cheerio) {
    return elem.get();
  } else if (Array.isArray(elem)) {
    return _.flatten(elem.map(makeDomArray, this));
  } else if (typeof elem === 'string') {
    return evaluate(elem, this.options);
  } else {
    return [elem];
  }
};

var _insert = function(concatenator) {
  return function() {
    var self = this,
        elems = slice.call(arguments),
        dom = this._makeDomArray(elems);

    if (typeof elems[0] === 'function') {
      return domEach(this, function(i, el) {
        dom = self._makeDomArray(elems[0].call(el, i, $.html(el.children)));
        concatenator(dom, el.children, el);
      });
    } else {
      return domEach(this, function(i, el) {
        concatenator(dom, el.children, el);
      });
    }
  };
};

/*
 * Modify an array in-place, removing some number of elements and adding new
 * elements directly following them.
 *
 * @param {Array} array Target array to splice.
 * @param {Number} spliceIdx Index at which to begin changing the array.
 * @param {Number} spliceCount Number of elements to remove from the array.
 * @param {Array} newElems Elements to insert into the array.
 *
 * @api private
 */
var uniqueSplice = function(array, spliceIdx, spliceCount, newElems, parent) {
  var spliceArgs = [spliceIdx, spliceCount].concat(newElems),
      prev = array[spliceIdx - 1] || null,
      next = array[spliceIdx] || null;
  var idx, len, prevIdx, node;

  // Before splicing in new elements, ensure they do not already appear in the
  // current array.
  for (idx = 0, len = newElems.length; idx < len; ++idx) {
    node = newElems[idx];
    prevIdx = node.parent && array.indexOf(newElems[idx]);

    if (node.parent && prevIdx > -1) {
      array.splice(prevIdx, 1);
      if (spliceIdx > prevIdx) {
        spliceArgs[0]--;
      }
    }

    node.parent = parent;
    node.prev = newElems[idx - 1] || prev;
    node.next = newElems[idx + 1] || next;
  }

  if (prev) {
    prev.next = newElems[0];
  }
  if (next) {
    next.prev = newElems[newElems.length - 1];
  }

  return array.splice.apply(array, spliceArgs);
};

var append = exports.append = _insert(function(dom, children, parent) {
  uniqueSplice(children, children.length, 0, dom, parent);
});

var prepend = exports.prepend = _insert(function(dom, children, parent) {
  uniqueSplice(children, 0, 0, dom, parent);
});

var after = exports.after = function() {
  var elems = slice.call(arguments),
      dom = this._makeDomArray(elems),
      self = this;

  domEach(this, function(i, el) {
    var parent = el.parent || el.root,
        siblings = parent.children,
        index = siblings.indexOf(el);

    // If not found, move on
    if (!~index) return;

    if (typeof elems[0] === 'function') {
      dom = self._makeDomArray(elems[0].call(el, i));
    }

    // Add element after `this` element
    uniqueSplice(siblings, ++index, 0, dom, parent);
  });

  return this;
};

var before = exports.before = function() {
  var elems = slice.call(arguments),
      dom = this._makeDomArray(elems),
      self = this;

  domEach(this, function(i, el) {
    var parent = el.parent || el.root,
        siblings = parent.children,
        index = siblings.indexOf(el);

    // If not found, move on
    if (!~index) return;

    if (typeof elems[0] === 'function') {
      dom = self._makeDomArray(elems[0].call(el, i));
    }

    // Add element before `el` element
    uniqueSplice(siblings, index, 0, dom, parent);
  });

  return this;
};

/*
  remove([selector])
*/
var remove = exports.remove = function(selector) {
  var elems = this;

  // Filter if we have selector
  if (selector)
    elems = elems.filter(selector);

  domEach(elems, function(i, el) {
    var parent = el.parent || el.root,
        siblings = parent.children,
        index = siblings.indexOf(el);

    if (!~index) return;

    siblings.splice(index, 1);
    if (el.prev) {
      el.prev.next = el.next;
    }
    if (el.next) {
      el.next.prev = el.prev;
    }
    el.prev = el.next = el.parent = null;
  });

  return this;
};

var replaceWith = exports.replaceWith = function(content) {
  var self = this;

  domEach(this, function(i, el) {
    var parent = el.parent || el.root,
        siblings = parent.children,
        dom = self._makeDomArray(typeof content === 'function' ? content.call(el, i, el) : content),
        index;

    // In the case that `dom` contains nodes that already exist in other
    // structures, ensure those nodes are properly removed.
    updateDOM(dom, null);

    index = siblings.indexOf(el);

    // Completely remove old element
    uniqueSplice(siblings, index, 1, dom, parent);
    el.parent = el.prev = el.next = null;
  });

  return this;
};

var empty = exports.empty = function() {
  domEach(this, function(i, el) {
    _.each(el.children, function(el) {
      el.next = el.prev = el.parent = null;
    });

    el.children.length = 0;
  });
  return this;
};

/**
 * Set/Get the HTML
 */
var html = exports.html = function(str) {
  if (str === undefined) {
    if (!this[0] || !this[0].children) return null;
    return $.html(this[0].children);
  }

  var opts = this.options;

  domEach(this, function(i, el) {
    _.each(el.children, function(el) {
      el.next = el.prev = el.parent = null;
    });

    var content = str.cheerio ? str.clone().get() : evaluate(str, opts);

    updateDOM(content, el);
  });

  return this;
};

var toString = exports.toString = function() {
  return $.html(this);
};

var text = exports.text = function(str) {
  // If `str` is undefined, act as a "getter"
  if (str === undefined) {
    return $.text(this);
  } else if (typeof str === 'function') {
    // Function support
    return domEach(this, function(i, el) {
      var $el = [el];
      return text.call($el, str.call(el, i, $.text($el)));
    });
  }

  // Append text node to each selected elements
  domEach(this, function(i, el) {
    _.each(el.children, function(el) {
      el.next = el.prev = el.parent = null;
    });

    var elem = {
      data: str,
      type: 'text',
      parent: el,
      prev: null,
      next: null,
      children: []
    };

    updateDOM(elem, el);
  });

  return this;
};

var clone = exports.clone = function() {
  // Turn it into HTML, then recreate it,
  // Seems to be the easiest way to reconnect everything correctly
  return this._make($.html(this));
};
<|endoftext|>


<commit_before>'use strict';

var bcrypt = require('bcrypt');

module.exports = function(sequelize, DataTypes) {
    var User = sequelize.define("User", {
        username: DataTypes.STRING,
        email: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
                isEmail: true
            }
        },
        password_digest: {
            type: DataTypes.STRING,
            validate: {
                notEmpty: true
            }
        },
        password: {
            type: DataTypes.VIRTUAL,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        password_confirmation: {
            type: DataTypes.VIRTUAL
        },
        school: DataTypes.STRING,
        university: DataTypes.STRING,
        }
    }, {
        indexes: [
            {unique: true, fields: ['email']}
        ],
        instanceMethods: {
            authenticate: function(value) {
                if (bcrypt.compareSync(value, this.password_digest))
                    return this;
                else
                    return false;
            }
        }
    });

    const hasSecurePassword = (user, options, callback) => {
        if (user.password != user.password_confirmation) {
            throw new sequelize.ValidationError("Password confirmation: Password confirmation doesn't match Password");
        }
        if (user.password.length < 6) {
            throw new sequelize.ValidationError("Password should be at least 6 characters");
        }
        bcrypt.hash(user.get('password'), 10, function(err, hash) {
            if (err) return callback(err);
            user.set('password_digest', hash);
            return callback(null, options);
        });
    };

    User.beforeCreate(function(user, options, callback) {
        user.email = user.email.toLowerCase();
        if (user.password)
            hasSecurePassword(user, options, callback);
        else
            return callback(null, options);
    });

    User.beforeUpdate(function(user, options, callback) {
        user.email = user.email.toLowerCase();
        if (user.password)
            hasSecurePassword(user, options, callback);
        else
            return callback(null, options);
    });

    return User;
};
<commit_msg>Add isChatting field to User<commit_after>'use strict';

var bcrypt = require('bcrypt');

module.exports = function(sequelize, DataTypes) {
    var User = sequelize.define("User", {
        username: DataTypes.STRING,
        email: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
                isEmail: true
            }
        },
        password_digest: {
            type: DataTypes.STRING,
            validate: {
                notEmpty: true
            }
        },
        password: {
            type: DataTypes.VIRTUAL,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        password_confirmation: {
            type: DataTypes.VIRTUAL
        },
        school: DataTypes.STRING,
        university: DataTypes.STRING,
        isChatting: {
            type: DataTypes.BOOLEAN,
            allowNull: false,
            defaultValue: false
        }
    }, {
        indexes: [
            {unique: true, fields: ['email']}
        ],
        instanceMethods: {
            authenticate: function(value) {
                if (bcrypt.compareSync(value, this.password_digest))
                    return this;
                else
                    return false;
            }
        }
    });

    const hasSecurePassword = (user, options, callback) => {
        if (user.password != user.password_confirmation) {
            throw new sequelize.ValidationError("Password confirmation: Password confirmation doesn't match Password");
        }
        if (user.password.length < 6) {
            throw new sequelize.ValidationError("Password should be at least 6 characters");
        }
        bcrypt.hash(user.get('password'), 10, function(err, hash) {
            if (err) return callback(err);
            user.set('password_digest', hash);
            return callback(null, options);
        });
    };

    User.beforeCreate(function(user, options, callback) {
        user.email = user.email.toLowerCase();
        if (user.password)
            hasSecurePassword(user, options, callback);
        else
            return callback(null, options);
    });

    User.beforeUpdate(function(user, options, callback) {
        user.email = user.email.toLowerCase();
        if (user.password)
            hasSecurePassword(user, options, callback);
        else
            return callback(null, options);
    });

    return User;
};
<|endoftext|>


<commit_before>var mouse;

// shots selector are after executing passed actions
function shot (selector, actions, eventName) {
    return function () {

    	if (typeof actions === 'function')
    		actions()
    	else eventName = actions;

        phantomcss.screenshot(selector, blockName + selector + '.' + eventName);
    }
}

// shot current state of selector area
function shotCurrent (selector, name) {
	return phantomcss.screenshot.bind(phantomcss, selector, blockName + '.' + name);
}

// runs an array of functions
function sequence (steps) {
    steps.forEach(function (step) {
        casper.then(step);
    });
}

// applies arbitrary number of actions to selector
// for the full list of actions see spec of "mouse" Class
function actions (selector) {
	var args = arguments;
	return function () {
		Array.prototype.slice.call(args, 1).forEach(function (action) {
			console.log('mouse' + action + ' ' + selector);
			mouse[action](selector);
		});
	};
}

function click (selector) {
	return actions(selector, 'move', 'down');
}

function clickNShot (selector) {
	return shot(selector, click(selector), 'click');
}

module.exports = function () {
	// casper, phantomcss, blockName is in global
	mouse = casper.mouse;
	return {
		shotCurrent: shotCurrent,
		shot: shot,
		sequence: sequence,
		actions: actions,
		click: click,
		clickNShot: clickNShot
	};
}<commit_msg>added actual click and mousedown hot function<commit_after>var mouse;

// shots selector are after executing passed actions
function shot (selector, actions, eventName) {
    return function () {

    	if (typeof actions === 'function')
    		actions()
    	else eventName = actions;

        phantomcss.screenshot(selector, blockName + selector + '.' + eventName);
    }
}

// shot current state of selector area
function shotCurrent (selector, name) {
	return phantomcss.screenshot.bind(phantomcss, selector, blockName + '.' + name);
}

// runs an array of functions
function sequence (steps) {
    steps.forEach(function (step) {
        casper.then(step);
    });
}

// applies arbitrary number of actions to selector
// for the full list of actions see spec of "mouse" Class
function actions (selector) {
	var args = arguments;
	return function () {
		Array.prototype.slice.call(args, 1).forEach(function (action) {
			console.log('mouse' + action + ' ' + selector);
			mouse[action](selector);
		});
	};
}

function click (selector) {
	return actions(selector, 'move', 'click');
}

function down (selector) {
	return actions(selector, 'move', 'down');
}

function clickNShot (selector) {
	return shot(selector, click(selector), 'click');
}

function downNShot (selector) {
	return shot(selector, down(selector), 'down');
}

module.exports = function () {
	// casper, phantomcss, blockName are in global
	mouse = casper.mouse;
	return {
		shotCurrent: shotCurrent,
		shot: shot,
		sequence: sequence,
		actions: actions,
		click: click,
		clickNShot: clickNShot,
		downNShot: downNShot
	};
}<|endoftext|>


<commit_before>'use strict';

var request = require('request');
var _ = require('lodash');

const defaultOptions = (options) => {
  const defaults = {
    timeout: 30000,
    headers: {
      'Content-Type': 'application/json'
    }
  };
  if(!options) {
    options = defaults;
  } else {
    options = _.assign(defaults, options);
  }

  return options;
};

class CartoDBMapClient {
  constructor(user, apiKey) {
    this.user = user;
  	this.apiKey = apiKey;
    this.baseURL = 'https://' + this.user + '.cartodb.com/';
  }

  createNamedMap(options) {
    this.existsNamedMap(options.name).then(() => {

    });
  }

  existsNamedMap(name, options) {
    var $this = this;
    options = defaultOptions(options);
    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'GET',
        uri: $this.baseURL + 'tiles/template/' + name,
        qs: {
          'api_key': $this.apiKey,
        },
        json: {}
      }), (error, response, body) => {
        if(error) {
          reject(error);
        }
        resolve({
          exists: response.statusCode !== 404,
          data: body
        });
      });
    });
    return promise;
  }

  searchDatasets(text, page, size, options) {
    var $this = this;
    page = page || 1;
    size = size || 20;
    options = defaultOptions(options);
    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'GET',
        uri: $this.baseURL + 'api/v1/viz/',
        qs: {
          'api_key': $this.apiKey,
          deepInsights: false,
          'exclude_shared': false,
          types: 'table,remote',
          shared: 'yes',
          q: text,
          page,
          'per_page': size
        },
        json: {}
      }), (error, response, body) => {
        if(error) {
          reject(error);
        }
        resolve(body);
      });
    });
    return promise;
  }

  searchMaps(text, page, size, options) {
    var $this = this;
    page = page || 1;
    size = size || 20;
    options = defaultOptions(options);
    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'GET',
        uri: $this.baseURL + 'api/v1/viz/',
        qs: {
          'api_key': $this.apiKey,
          deepInsights: false,
          'exclude_shared': false,
          types: 'derived',
          shared: 'yes',
          q: text,
          page,
          'per_page': size
        },
        json: {}
      }), (error, response, body) => {
        if(error) {
          reject(error);
        }
        resolve(body);
      });
    });
    return promise;
  }

  getGroupID(name, options) {
    var $this = this;
    options = defaultOptions(options);

    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'POST',
        uri: $this.baseURL + 'tiles/template/' + name,
        qs: {
          'api_key': $this.apiKey,
        },
        json: {}
      }), (error, response, body) => {
        if(error) {
          reject(error);
        }
        resolve(body);
      });
    });
    return promise;
  }

  get(suffixUrl, params, options) {
    var $this = this;
    if(!params) {
      params = {};
    }
    options = defaultOptions(options);
    // jshint camelcase: false
    params.api_key = this.apiKey;
    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'GET',
        uri: $this.baseURL + suffixUrl,
        qs: params,
        json: {}
      }), (error, response, body) => {
        if(error) {
          reject(error);
        }
        resolve(body);
      });
    });
    return promise;
  }

  post(suffixUrl, params, body, options) {
    var $this = this;
    if(!params) {
      params = {};
    }
    if(!body) {
      body = {};
    }
    options = defaultOptions(options);
    // jshint camelcase: false
    params.api_key = this.apiKey;
    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'POST',
        uri: $this.baseURL + suffixUrl,
        qs: params,
        json: body
      }), (error, response, body) => {
        if(error) {
          reject(error);
        }
        resolve(body);
      });
    });
    return promise;
  }
}

module.exports = CartoDBMapClient;
<commit_msg>change to carto url and fix reject errors<commit_after>'use strict';

var request = require('request');
var _ = require('lodash');

const defaultOptions = (options) => {
  const defaults = {
    timeout: 30000,
    headers: {
      'Content-Type': 'application/json'
    }
  };
  if(!options) {
    options = defaults;
  } else {
    options = _.assign(defaults, options);
  }

  return options;
};

class CartoDBMapClient {
  constructor(user, apiKey) {
    this.user = user;
  	this.apiKey = apiKey;
    this.baseURL = 'https://' + this.user + '.carto.com/';
  }

  createNamedMap(options) {
    this.existsNamedMap(options.name).then(() => {

    });
  }

  existsNamedMap(name, options) {
    var $this = this;
    options = defaultOptions(options);
    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'GET',
        uri: $this.baseURL + 'tiles/template/' + name,
        qs: {
          'api_key': $this.apiKey,
        },
        json: {}
      }), (error, response, body) => {
        if(error) {
          reject(error);
          return;
        }
        resolve({
          exists: response.statusCode !== 404,
          data: body
        });
      });
    });
    return promise;
  }

  searchDatasets(text, page, size, options) {
    var $this = this;
    page = page || 1;
    size = size || 20;
    options = defaultOptions(options);
    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'GET',
        uri: $this.baseURL + 'api/v1/viz/',
        qs: {
          'api_key': $this.apiKey,
          deepInsights: false,
          'exclude_shared': false,
          types: 'table,remote',
          shared: 'yes',
          q: text,
          page,
          'per_page': size
        },
        json: {}
      }), (error, response, body) => {
        if(error) {
          reject(error);
          return;
        }
        resolve(body);
      });
    });
    return promise;
  }

  searchMaps(text, page, size, options) {
    var $this = this;
    page = page || 1;
    size = size || 20;
    options = defaultOptions(options);
    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'GET',
        uri: $this.baseURL + 'api/v1/viz/',
        qs: {
          'api_key': $this.apiKey,
          deepInsights: false,
          'exclude_shared': false,
          types: 'derived',
          shared: 'yes',
          q: text,
          page,
          'per_page': size
        },
        json: {}
      }), (error, response, body) => {
        if(error) {
          reject(error);
          return;
        }
        resolve(body);
      });
    });
    return promise;
  }

  getGroupID(name, options) {
    var $this = this;
    options = defaultOptions(options);

    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'POST',
        uri: $this.baseURL + 'tiles/template/' + name,
        qs: {
          'api_key': $this.apiKey,
        },
        json: {}
      }), (error, response, body) => {
        if(error) {
          reject(error);
          return;
        }
        resolve(body);
      });
    });
    return promise;
  }

  get(suffixUrl, params, options) {
    var $this = this;
    if(!params) {
      params = {};
    }
    options = defaultOptions(options);
    // jshint camelcase: false
    params.api_key = this.apiKey;
    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'GET',
        uri: $this.baseURL + suffixUrl,
        qs: params,
        json: {}
      }), (error, response, body) => {
        if(error) {
          reject(error);
          return;
        }
        resolve(body);
      });
    });
    return promise;
  }

  post(suffixUrl, params, body, options) {
    var $this = this;
    if(!params) {
      params = {};
    }
    if(!body) {
      body = {};
    }
    options = defaultOptions(options);
    // jshint camelcase: false
    params.api_key = this.apiKey;
    const promise = new Promise((resolve, reject) => {
      request(_.assign(options, {
        method: 'POST',
        uri: $this.baseURL + suffixUrl,
        qs: params,
        json: body
      }), (error, response, body) => {
        if(error) {
          reject(error);
          return;
        }
        resolve(body);
      });
    });
    return promise;
  }
}

module.exports = CartoDBMapClient;
<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

"use strict";

module.metadata = {
  "stability": "unstable"
};

var self = require("sdk/self");

const { Cu } = require("chrome");
const { Panel } = require("../sdk/panel.js");
const { Class } = require("sdk/core/heritage");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { PanelToolbar, ToolbarButton } = require("./panelToolbar.js");
const { Xul } = require("../core/xul.js");
const { when } = require("sdk/event/utils");
const { Theme } = require("./theme.js");
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { ToolSidebar } = devtools["require"]("devtools/framework/sidebar");

const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

const { BOX, VBOX, HBOX, SPLITTER, TABBOX, TABS, TABPANELS } = Xul;

/**
 * Base object for {@Toolbox} panels. Every Panel object should be derived
 * from this object.
 */
const BasePanel = Class(
/** @lends BasePanel */
{
  extends: Panel,

  initialize: function(options) {
    // xxxHonza: custom panels doesn't pass the 'panelFrame',
    // we might need a new hook in the SDK or different concept.
    let frame = options ? options.panelFrame : null;

    // Panel callback is executed only if the theme event has been
    // fired from a frame that is associated with the panel.
    let apply = (win, newTheme) => {
      if (frame && frame.contentWindow === win)
        this.onApplyTheme(win, newTheme);
    };

    let unapply = (win, newTheme) => {
      if (frame && frame.contentWindow === win)
        this.onUnapplyTheme(win, newTheme);
    };

    // Register theme listener to receive notifications
    // when Firebug theme is activated or deactivated.
    Theme.addThemeListeners(apply, unapply);

    this.sidePanels = new Map();
  },

  /**
   * Executed by the framework when event "load" is fired for the document.
   * (`document.readySate === "complete"`).
   */
  onLoad: function() {
    Trace.sysout("basePanel.onLoad;", this);
  },

  /**
   * This method is called to setup new panels. It isn't executed
   * for Panel overlays. Built in panel are already setup.
   */
  setup: function({debuggee, frame, toolbox}) {
    Trace.sysout("basePanel.setup;", arguments);

    this.panelFrame = frame;
    this.debuggee = debuggee;
    this.toolbox = toolbox;

    let parentNode = frame.parentNode;
    parentNode.style.MozBoxOrient = "horizontal";
    frame.style.visibility = "visible";

    // Definition of the new panel content layout.
    var content =
      HBOX({"class": "panelContent", "flex": "1"},
        VBOX({"id": "panelMainBox", "flex": "1"}),
        SPLITTER({"id": "panelSplitter", "valign": "top"},
          BOX({"id": "panelSplitterBox"})
        ),
        TABBOX({"id": "panelSideBox",
          "class": "devtools-sidebar-tabs",
          /*"width": "300px", default hide doesn't work*/
          "handleCtrlTab": "false"},
            TABS(),
            TABPANELS({"flex": "1"})
        )
      );

    // Build XUL DOM structure.
    var panelContent = content.build(parentNode);

    // Append a (inner) toolbar into the main panel.
    let mainBox = panelContent.querySelector("#panelMainBox");
    let mainToolbar = new PanelToolbar({
      parentNode: mainBox,
    });

    // Append the existing frame into the right location within
    // the new layout.
    mainBox.appendChild(frame);

    let items = this.getPanelToolbarButtons();
    if (items)
      mainToolbar.createItems(items);

    let sideBox = panelContent.querySelector("#panelSideBox");
    this.sidebar = new ToolSidebar(sideBox, this, "helloworldpanel-sidebar");
    this.sidebar.on("select", (event, toolId) => {
      // TODO: remember the last selected side panel.
    });

    this.setupSidePanels();
  },

  /**
   * Executed by the framework after document in the panel becomes
   * interactive (`document.readyState === "interactive"`).
   */
  onReady: function(options) {
    Trace.sysout("basePanel.onReady;", options);

    if (this.panelFrame)
      this.panelNode = this.panelFrame.contentDocument.body;
    else
      TraceError.sysout("basePanel.onReady; ERROR no frame", this);
  },

  // Side panels API

  getSidePanels: function() {
    return [];
  },

  setupSidePanels: function() {
    let sidePanels = this.getSidePanels();

    Trace.sysout("basePanel.setupSidePanels; " + this.sidebar, sidePanels);

    if (!this.sidebar)
      return;

    if (!sidePanels || !sidePanels.length) {
      this.sidebar.hide();
      return;
    }

    // Iterate all provided side panel constructors and build
    // corresponding structure in the side-bar.
    for (let ctor of sidePanels) {
      const { id } = ctor.prototype;
      if (!this.sidebar.getTab(id))
        this.buildSidePanel(ctor);
    }
  },

  buildSidePanel: function(ctor) {
    const { id, label, tooltip, icon, url } = ctor.prototype;

    Trace.sysout("basePanel.buildSidePanel; " + id, ctor);

    // Append new tab into the side bar.
    this.sidebar.addTab(id, self.data.url(url), false);

    let xulPanel = this.sidebar.getTab(id);
    let panelFrame = xulPanel.querySelector("iframe");

    // Create instance of the side panel object and setup it.
    // xxxHonza: when main panels are created the frame is
    // not passed into the setup method (SDK design, see also issue #65).
    // Side panels API should behave similarly FIX ME.
    let panel = new ctor();
    this.sidePanels.set(id, panel);
    panel.setup({frame: panelFrame, toolbox: this.toolbox});

    let onLoad = (event) => {
      panelFrame.removeEventListener("load", onLoad, true);
      this.onSidePanelLoad(event, id);
    };

    panelFrame.addEventListener("load", onLoad, true);
  },

  onSidePanelLoad: function(event, id) {
    // Update panel tab title with localized version
    // xxxHonza: report request for better (localizable) API.
    let tab = this.sidebar._tabs.get(id);
    let panel = this.sidePanels.get(id);
    tab.setAttribute("label", panel.label);

    Trace.sysout("basePanel.onSidePanelLoad; " + id, panel);

    // Get the side panel window from the target since
    // panelFrame.contentWindow isn't set when the <tabbox> is hidden.
    panel.onReady(event.target.defaultView);
  },

  removeSidePanels: function() {
    let sidePanels = this.getSidePanels();
    if (!this.sidebar || !sidePanels || !sidePanels.length) {
      return;
    }

    for (let Panel of sidePanels) {
      const { id } = Panel.prototype;

      // xxxHonza:
      // Missing API, blocked by: Bug 1055571 - New API: ToolSidebar.removeTab
      // https://bugzilla.mozilla.org/show_bug.cgi?id=1055571
      if (this.sidebar.removeTab) {
        Trace.sysout("removeSidePanel: " + id)
        this.sidebar.removeTab(id);
      }

      this.sidePanels.delete(id);
    }
  },

  selectSidePanel: function(id) {
    this.sidebar.select(id);
  },

  // Panel toolbar

  getPanelToolbarButtons: function() {
    return null;
  },

  dispose: function() {
    Trace.sysout("basePanel.dispose;");
    delete this.debuggee;
  },

  show: function() {
    Trace.sysout("basePanel.show;");
  },

  /**
   * Returns a list of menu items for panel options menu.
   */
  getOptionsMenuItems: function() {
    return [];
  },

  /**
   * Returns a number indicating the view's ability to inspect the object.
   * Zero means not supported, and higher numbers indicate specificity.
   */
  supportsObject: function(object) {
    return 0;
  },

  // Selection
  select: function(object) {
  },

  // Theme

  /**
   * Executed by the framework when Firebug theme is applied.
   */
  onApplyTheme: function(iframeWin, oldTheme) {
  },

  /**
   * Executed by the framework when Firebug theme is unapplied.
   */
  onUnapplyTheme: function(iframeWin, newTheme) {
  },
});

// Exports from this module
exports.BasePanel = BasePanel;
<commit_msg>Remove obsolete constant<commit_after>/* See license.txt for terms of usage */

"use strict";

module.metadata = {
  "stability": "unstable"
};

var self = require("sdk/self");

const { Cu } = require("chrome");
const { Panel } = require("../sdk/panel.js");
const { Class } = require("sdk/core/heritage");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { PanelToolbar, ToolbarButton } = require("./panelToolbar.js");
const { Xul } = require("../core/xul.js");
const { when } = require("sdk/event/utils");
const { Theme } = require("./theme.js");
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { ToolSidebar } = devtools["require"]("devtools/framework/sidebar");

const { BOX, VBOX, HBOX, SPLITTER, TABBOX, TABS, TABPANELS } = Xul;

/**
 * Base object for {@Toolbox} panels. Every Panel object should be derived
 * from this object.
 */
const BasePanel = Class(
/** @lends BasePanel */
{
  extends: Panel,

  initialize: function(options) {
    // xxxHonza: custom panels doesn't pass the 'panelFrame',
    // we might need a new hook in the SDK or different concept.
    let frame = options ? options.panelFrame : null;

    // Panel callback is executed only if the theme event has been
    // fired from a frame that is associated with the panel.
    let apply = (win, newTheme) => {
      if (frame && frame.contentWindow === win)
        this.onApplyTheme(win, newTheme);
    };

    let unapply = (win, newTheme) => {
      if (frame && frame.contentWindow === win)
        this.onUnapplyTheme(win, newTheme);
    };

    // Register theme listener to receive notifications
    // when Firebug theme is activated or deactivated.
    Theme.addThemeListeners(apply, unapply);

    this.sidePanels = new Map();
  },

  /**
   * Executed by the framework when event "load" is fired for the document.
   * (`document.readySate === "complete"`).
   */
  onLoad: function() {
    Trace.sysout("basePanel.onLoad;", this);
  },

  /**
   * This method is called to setup new panels. It isn't executed
   * for Panel overlays. Built in panel are already setup.
   */
  setup: function({debuggee, frame, toolbox}) {
    Trace.sysout("basePanel.setup;", arguments);

    this.panelFrame = frame;
    this.debuggee = debuggee;
    this.toolbox = toolbox;

    let parentNode = frame.parentNode;
    parentNode.style.MozBoxOrient = "horizontal";
    frame.style.visibility = "visible";

    // Definition of the new panel content layout.
    var content =
      HBOX({"class": "panelContent", "flex": "1"},
        VBOX({"id": "panelMainBox", "flex": "1"}),
        SPLITTER({"id": "panelSplitter", "valign": "top"},
          BOX({"id": "panelSplitterBox"})
        ),
        TABBOX({"id": "panelSideBox",
          "class": "devtools-sidebar-tabs",
          /*"width": "300px", default hide doesn't work*/
          "handleCtrlTab": "false"},
            TABS(),
            TABPANELS({"flex": "1"})
        )
      );

    // Build XUL DOM structure.
    var panelContent = content.build(parentNode);

    // Append a (inner) toolbar into the main panel.
    let mainBox = panelContent.querySelector("#panelMainBox");
    let mainToolbar = new PanelToolbar({
      parentNode: mainBox,
    });

    // Append the existing frame into the right location within
    // the new layout.
    mainBox.appendChild(frame);

    let items = this.getPanelToolbarButtons();
    if (items)
      mainToolbar.createItems(items);

    let sideBox = panelContent.querySelector("#panelSideBox");
    this.sidebar = new ToolSidebar(sideBox, this, "helloworldpanel-sidebar");
    this.sidebar.on("select", (event, toolId) => {
      // TODO: remember the last selected side panel.
    });

    this.setupSidePanels();
  },

  /**
   * Executed by the framework after document in the panel becomes
   * interactive (`document.readyState === "interactive"`).
   */
  onReady: function(options) {
    Trace.sysout("basePanel.onReady;", options);

    if (this.panelFrame)
      this.panelNode = this.panelFrame.contentDocument.body;
    else
      TraceError.sysout("basePanel.onReady; ERROR no frame", this);
  },

  // Side panels API

  getSidePanels: function() {
    return [];
  },

  setupSidePanels: function() {
    let sidePanels = this.getSidePanels();

    Trace.sysout("basePanel.setupSidePanels; " + this.sidebar, sidePanels);

    if (!this.sidebar)
      return;

    if (!sidePanels || !sidePanels.length) {
      this.sidebar.hide();
      return;
    }

    // Iterate all provided side panel constructors and build
    // corresponding structure in the side-bar.
    for (let ctor of sidePanels) {
      const { id } = ctor.prototype;
      if (!this.sidebar.getTab(id))
        this.buildSidePanel(ctor);
    }
  },

  buildSidePanel: function(ctor) {
    const { id, label, tooltip, icon, url } = ctor.prototype;

    Trace.sysout("basePanel.buildSidePanel; " + id, ctor);

    // Append new tab into the side bar.
    this.sidebar.addTab(id, self.data.url(url), false);

    let xulPanel = this.sidebar.getTab(id);
    let panelFrame = xulPanel.querySelector("iframe");

    // Create instance of the side panel object and setup it.
    // xxxHonza: when main panels are created the frame is
    // not passed into the setup method (SDK design, see also issue #65).
    // Side panels API should behave similarly FIX ME.
    let panel = new ctor();
    this.sidePanels.set(id, panel);
    panel.setup({frame: panelFrame, toolbox: this.toolbox});

    let onLoad = (event) => {
      panelFrame.removeEventListener("load", onLoad, true);
      this.onSidePanelLoad(event, id);
    };

    panelFrame.addEventListener("load", onLoad, true);
  },

  onSidePanelLoad: function(event, id) {
    // Update panel tab title with localized version
    // xxxHonza: report request for better (localizable) API.
    let tab = this.sidebar._tabs.get(id);
    let panel = this.sidePanels.get(id);
    tab.setAttribute("label", panel.label);

    Trace.sysout("basePanel.onSidePanelLoad; " + id, panel);

    // Get the side panel window from the target since
    // panelFrame.contentWindow isn't set when the <tabbox> is hidden.
    panel.onReady(event.target.defaultView);
  },

  removeSidePanels: function() {
    let sidePanels = this.getSidePanels();
    if (!this.sidebar || !sidePanels || !sidePanels.length) {
      return;
    }

    for (let Panel of sidePanels) {
      const { id } = Panel.prototype;

      // xxxHonza:
      // Missing API, blocked by: Bug 1055571 - New API: ToolSidebar.removeTab
      // https://bugzilla.mozilla.org/show_bug.cgi?id=1055571
      if (this.sidebar.removeTab) {
        Trace.sysout("removeSidePanel: " + id)
        this.sidebar.removeTab(id);
      }

      this.sidePanels.delete(id);
    }
  },

  selectSidePanel: function(id) {
    this.sidebar.select(id);
  },

  // Panel toolbar

  getPanelToolbarButtons: function() {
    return null;
  },

  dispose: function() {
    Trace.sysout("basePanel.dispose;");
    delete this.debuggee;
  },

  show: function() {
    Trace.sysout("basePanel.show;");
  },

  /**
   * Returns a list of menu items for panel options menu.
   */
  getOptionsMenuItems: function() {
    return [];
  },

  /**
   * Returns a number indicating the view's ability to inspect the object.
   * Zero means not supported, and higher numbers indicate specificity.
   */
  supportsObject: function(object) {
    return 0;
  },

  // Selection
  select: function(object) {
  },

  // Theme

  /**
   * Executed by the framework when Firebug theme is applied.
   */
  onApplyTheme: function(iframeWin, oldTheme) {
  },

  /**
   * Executed by the framework when Firebug theme is unapplied.
   */
  onUnapplyTheme: function(iframeWin, newTheme) {
  },
});

// Exports from this module
exports.BasePanel = BasePanel;
<|endoftext|>


<commit_before>
var Collection = module.exports = require('./collection')

var Query = require('./query')
var Insert = require('./insert')
var Aggregate = require('./aggregate')

require('./batch')

Collection.prototype.find = function (criteria, value) {
  return Query(this.collection).find(criteria, value)
}

Collection.prototype.findOne = function (criteria, value) {
  return Query(this.collection).findOne(criteria, value)
}

Collection.prototype.aggregate = function (options) {
  return Aggregate(this.collection, options)
}

Collection.prototype.insert = function (documents, options) {
  return Insert(this.collection, documents, options)
}

Collection.prototype.remove = function (criteria, options) {
  return Query(this.collection, options).find(criteria).remove()
}
<commit_msg>add ensure index<commit_after>
var Promise = require('native-or-bluebird')

var Collection = module.exports = require('./collection')

var Query = require('./query')
var Insert = require('./insert')
var Aggregate = require('./aggregate')

require('./batch')

Collection.prototype.find = function (criteria, value) {
  return Query(this.collection).find(criteria, value)
}

Collection.prototype.findOne = function (criteria, value) {
  return Query(this.collection).findOne(criteria, value)
}

Collection.prototype.aggregate = function (options) {
  return Aggregate(this.collection, options)
}

Collection.prototype.insert = function (documents, options) {
  return Insert(this.collection, documents, options)
}

Collection.prototype.remove = function (criteria, options) {
  return Query(this.collection, options).find(criteria).remove()
}

Collection.prototype.ensureIndex = function (spec, options) {
  var collection = this.collection
  return new Promise(function (resolve, reject) {
    collection.ensureIndex(spec, options || {}, function (err, res) {
      if (err) return reject(err)
      resolve()
    })
  })
}
<|endoftext|>


<commit_before>//
// Copyright (c) Adam Anderly.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// NOTICE: Based on azure-cli (https://github.com/Azure/azure-sdk-tools-xplat/)
//
'use strict';

/* jshint unused: false */

var __ = require('underscore');
var util = require('util');
var wrap = require('wordwrap').hard(0, 75);
var datejs = require('datejs');

var Constants = require('../util/constants');
var profile = require('../util/profile');
var tokenCache = require('../util/authentication/dnsimpleAuth').tokenCache;
var utils = require('../util/utils');

var $ = utils.getLocaleString;

var DomainClient = require('./domain/domainclient');

exports.init = function (cli) {
  var log = cli.output;

  var domain = cli.category('domain')
    .description($('Commands to manage domains'));

  var domainClient = new DomainClient(cli);

  domain.command('list [name]')
    .description($('List domains'))
    .option('-e --expiring', $('only show expiring domains'))
    .execute(function (name, options, _) {
      var context = {
        subscription: profile.current.getSubscription(options.subscription).id,
        expiring: options.expiring
      };

      context.skipCache = true;
      var domains = domain.doDomainsGet(context, _);

      if (name) {
        domains = domains.filter(function (s) {
          return utils.ignoreCaseEquals(s.name, name);
        });
      }

      if (options.expiring) {
        domains = domains.filter(function (s) {
          var within30Days = (30).days().fromNow();
          var expires = Date.parse(s.expires_on);
          return expires >= Date.today() && expires <= within30Days;
        });
      }

      cli.interaction.formatOutput(domains, function (data) {
        if (data.length > 0) {
          log.table(data, function (row, item) {
            //var parsedName = WebsitesClient.parseSiteName(item.name);
            row.cell($('Name'), item.name);
            row.cell($('Records'), item.record_count);
            row.cell($('Expires'), item.expires_on);
            row.cell($('Auto-Renew'), item.auto_renew);
            row.cell($('Whois-Protected'), item.whois_protected);
          });
        } else {
          log.info($('No domains added yet. You can add new domains using "dnsimple domain add" or through the portal'));
        }
      });
    });

  domain.command('show <name>')
    .description($('Show details about a domain'))
    .option('-s --domain <domain>', $('The domain to show'))
    .option('-d --details', $('Show extra information about the domain'))
    .execute(function (subscription, options, _) {
      var sub = profile.current.getSubscription(subscription);
      var format = [
        [$('Name'), 'name'],
        [$('ID'), 'id'],
        [$('Is Default'), 'isDefault'],
        [$('Environment'), 'environment.name'],
        [$('Has Certificate'), null, function (value) {
          if (value.managementCertificate) {
            return $('Yes');
          }
          return $('No');
        }],
        [$('Has Access Token'), null, function (value) {
          if (value.user) {
            return $('Yes');
          }
          return $('No');
        }],
        [$('User name'), 'user.name']
      ];

      var detailsFormat = [
        [$('Registered ASM Providers'), 'registeredProviders'],
        [$('Registered ARM Namespaces'), 'registeredResourceNamespaces']
      ];

      log.report(format.concat(options.details ? detailsFormat : []), sub);
    });

  domain.command('add <domain>')
    .description($('Add the domain to your account'))
    .execute(function (subscription, options, _) {
      var newSubscription = profile.current.getSubscription(subscription);
      if (!newSubscription) {
        throw new Error(util.format($('Invalid subscription "%s"'), subscription));
      }
      log.info(util.format($('Setting subscription to "%s"'), subscription));
      profile.current.currentSubscription = newSubscription;
      profile.current.save();
      log.info($('Changes saved'));
    });

  domain.command('delete')
    .description($('Remove a domain from your account.'))
    .option('-s --domain <domain>', $('Domain name or id to remove'))
    .option('-q --quiet', $('quiet mode, do not ask for delete confirmation'))
    .execute(function (options, _) {
      var matchSubscription = function () { return false; };
      var matchEnvironment = function () { return false; };
      var clearAll = false;

      if(!options.subscription && !options.environment) {
        clearAll = true;
        var shouldClear = options.quiet || cli.interaction.confirm($('This will clear all domain information. Are you sure? '), _);
        if (!shouldClear) {
          return;
        }
        matchSubscription = function () { return true; };
        matchEnvironment = function () { return true; };
      } else {
        if (options.subscription) {
          matchSubscription = function (s) {
            return s.id === options.subscription || utils.ignoreCaseEquals(s.name, options.subscription);
          };
        }
        if (options.environment) {
          matchEnvironment = function (e) {
            return utils.ignoreCaseEquals(e.name, options.environment);
          };
        }
      }

      __.values(profile.current.subscriptions)
        .filter(matchSubscription)
        .forEach(function (subscription) {
          profile.current.deleteSubscription(subscription.name);
        });

      __.values(profile.current.environments)
        .filter(matchEnvironment)
        .forEach(function (env) {
          profile.current.deleteEnvironment(env.name);
        });

      profile.current.save();
      if (clearAll) {
        profile.clearDnsimpleDir();
        tokenCache.clear(_);
      }
    });

  domain.doDomainsGet = function (options, callback) {
    var domainClient = new DomainClient(cli, options.subscription);
    return domainClient.getDomains(options, callback);
  };

  domain.doRecordsGet = function (options, callback) {
    var domainClient = new DomainClient(cli, options.subscription);
    return domainClient.getRecords(options, callback);
  };

  // TODO: remove all these "site."" function and just call websiteClient directly.
  domain.lookupDomainName = function (options, callback) {
    var domainClient = new DomainClient(cli, options.subscription);
    return domainClient.lookupDomainName(options, callback);
  };

};
<commit_msg>Added support for wildcard filters on domain list method.<commit_after>//
// Copyright (c) Adam Anderly.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// NOTICE: Based on azure-cli (https://github.com/Azure/azure-sdk-tools-xplat/)
//
'use strict';

/* jshint unused: false */

var __ = require('underscore');
var util = require('util');
var wrap = require('wordwrap').hard(0, 75);
var datejs = require('datejs');

var Constants = require('../util/constants');
var profile = require('../util/profile');
var tokenCache = require('../util/authentication/dnsimpleAuth').tokenCache;
var utils = require('../util/utils');

var $ = utils.getLocaleString;

var DomainClient = require('./domain/domainclient');

exports.init = function (cli) {
  var log = cli.output;

  var domain = cli.category('domain')
    .description($('Commands to manage domains'));

  var domainClient = new DomainClient(cli);

  domain.command('list [name]')
    .description($('List domains'))
    .option('-e --expiring', $('only show expiring domains'))
    .execute(function (name, options, _) {
      var context = {
        subscription: profile.current.getSubscription(options.subscription).id,
        expiring: options.expiring
      };

      context.skipCache = true;
      var domains = domain.doDomainsGet(context, _);

      if (name) {

        domains = domains.filter(function (s) {
          if (name.indexOf('*') !== -1) {
            var pattern = '^'+name.replace(/\*/gi,'(.*)')+'$';
            var regEx = new RegExp(pattern, 'gi');
            return regEx.test(s.name);
          } else {
            return utils.ignoreCaseEquals(s.name, name);
          }
        });
      }

      if (options.expiring) {
        domains = domains.filter(function (s) {
          var within30Days = (30).days().fromNow();
          var expires = Date.parse(s.expires_on);
          return expires >= Date.today() && expires <= within30Days;
        });
      }

      cli.interaction.formatOutput(domains, function (data) {
        if (data.length > 0) {
          log.table(data, function (row, item) {
            //var parsedName = WebsitesClient.parseSiteName(item.name);
            row.cell($('Name'), item.name);
            row.cell($('Records'), item.record_count);
            row.cell($('Expires'), item.expires_on);
            row.cell($('Auto-Renew'), item.auto_renew);
            row.cell($('Whois-Protected'), item.whois_protected);
          });
        } else {
          log.info($('No domains added yet. You can add new domains using "dnsimple domain add" or through the portal'));
        }
      });
    });

  domain.command('show <name>')
    .description($('Show details about a domain'))
    .option('-s --domain <domain>', $('The domain to show'))
    .option('-d --details', $('Show extra information about the domain'))
    .execute(function (subscription, options, _) {
      var sub = profile.current.getSubscription(subscription);
      var format = [
        [$('Name'), 'name'],
        [$('ID'), 'id'],
        [$('Is Default'), 'isDefault'],
        [$('Environment'), 'environment.name'],
        [$('Has Certificate'), null, function (value) {
          if (value.managementCertificate) {
            return $('Yes');
          }
          return $('No');
        }],
        [$('Has Access Token'), null, function (value) {
          if (value.user) {
            return $('Yes');
          }
          return $('No');
        }],
        [$('User name'), 'user.name']
      ];

      var detailsFormat = [
        [$('Registered ASM Providers'), 'registeredProviders'],
        [$('Registered ARM Namespaces'), 'registeredResourceNamespaces']
      ];

      log.report(format.concat(options.details ? detailsFormat : []), sub);
    });

  domain.command('add <domain>')
    .description($('Add the domain to your account'))
    .execute(function (subscription, options, _) {
      var newSubscription = profile.current.getSubscription(subscription);
      if (!newSubscription) {
        throw new Error(util.format($('Invalid subscription "%s"'), subscription));
      }
      log.info(util.format($('Setting subscription to "%s"'), subscription));
      profile.current.currentSubscription = newSubscription;
      profile.current.save();
      log.info($('Changes saved'));
    });

  domain.command('delete')
    .description($('Remove a domain from your account.'))
    .option('-s --domain <domain>', $('Domain name or id to remove'))
    .option('-q --quiet', $('quiet mode, do not ask for delete confirmation'))
    .execute(function (options, _) {
      var matchSubscription = function () { return false; };
      var matchEnvironment = function () { return false; };
      var clearAll = false;

      if(!options.subscription && !options.environment) {
        clearAll = true;
        var shouldClear = options.quiet || cli.interaction.confirm($('This will clear all domain information. Are you sure? '), _);
        if (!shouldClear) {
          return;
        }
        matchSubscription = function () { return true; };
        matchEnvironment = function () { return true; };
      } else {
        if (options.subscription) {
          matchSubscription = function (s) {
            return s.id === options.subscription || utils.ignoreCaseEquals(s.name, options.subscription);
          };
        }
        if (options.environment) {
          matchEnvironment = function (e) {
            return utils.ignoreCaseEquals(e.name, options.environment);
          };
        }
      }

      __.values(profile.current.subscriptions)
        .filter(matchSubscription)
        .forEach(function (subscription) {
          profile.current.deleteSubscription(subscription.name);
        });

      __.values(profile.current.environments)
        .filter(matchEnvironment)
        .forEach(function (env) {
          profile.current.deleteEnvironment(env.name);
        });

      profile.current.save();
      if (clearAll) {
        profile.clearDnsimpleDir();
        tokenCache.clear(_);
      }
    });

  domain.doDomainsGet = function (options, callback) {
    var domainClient = new DomainClient(cli, options.subscription);
    return domainClient.getDomains(options, callback);
  };

  domain.doRecordsGet = function (options, callback) {
    var domainClient = new DomainClient(cli, options.subscription);
    return domainClient.getRecords(options, callback);
  };

  // TODO: remove all these "site."" function and just call websiteClient directly.
  domain.lookupDomainName = function (options, callback) {
    var domainClient = new DomainClient(cli, options.subscription);
    return domainClient.lookupDomainName(options, callback);
  };

};
<|endoftext|>


<commit_before>var readYaml = require('read-yaml');
var fs = require('fs');
var toposort = require('toposort');

ContractsConfig = function(blockchainConfig, compiler) {
  this.blockchainConfig = blockchainConfig;
  this.compiler = compiler;
  this.contractFiles = [];
}

ContractsConfig.prototype.init = function(files, env) {
  this.all_contracts = [];
  this.contractDB = {};
  this.contractFiles = files;
  this.contractDependencies = {};
  this.contractStubs = {};

  //TODO: have to specify environment otherwise wouldn't work with staging
  if (this.blockchainConfig.config != undefined) {
    //this.blockchainConfig = this.blockchainConfig.config('development');
    this.blockchainConfig = this.blockchainConfig.config(env);
  }
};

ContractsConfig.prototype.loadConfigFile = function(filename) {
  try {
    this.contractConfig = readYaml.sync(filename);
  } catch (e) {
    throw new Error("error reading " + filename);
  }
  return this;
};

ContractsConfig.prototype.loadConfig = function(config) {
  this.contractConfig = config;
  return this;
};

ContractsConfig.prototype.config = function(env) {
  return this.contractConfig[env];
};

ContractsConfig.prototype.is_a_token = function(target, compiled_contracts) {
  for (var className in compiled_contracts) {
    if (this.contractStubs[className] && this.contractStubs[className].indexOf(target) >= 0) {
      return true;
    }
  }
  return false;
};

ContractsConfig.prototype.compileContracts = function(env) {
  var contractFile, source, j;
  var contractsConfig = this.config(env);
  this.compiler.init(env);

  // determine dependencies
  if (contractsConfig != null) {
    for (className in contractsConfig) {
      options = contractsConfig[className];
      if (options.args == null) continue;

      ref = options.args;
      for (j = 0; j < ref.length; j++) {
        arg = ref[j];
        if (arg[0] === "$") {
          if (this.contractDependencies[className] === void 0) {
            this.contractDependencies[className] = [];
          }
          this.contractDependencies[className].push(arg.substr(1));
        }
      }

      this.contractStubs[className] = options.stubs;
    }
  }

  var all_compiled_contracts = {};
  // compile files
  for (j = 0; j < this.contractFiles.length; j++) {
    contractFile = this.contractFiles[j];

    compiled_contracts = this.compiler.compile(contractFile);
    for (var className in compiled_contracts) {
      var contract = compiled_contracts[className];

      if (this.is_a_token(className, compiled_contracts)) {
        continue;
      }

      all_compiled_contracts[className] = contract;
      this.all_contracts.push(className);
      this.contractDB[className] = {
        args: [],
        types: ['file'],
        gasPrice: this.blockchainConfig.gasPrice,
        gasLimit: this.blockchainConfig.gasLimit,
        compiled: contract
      }
    }
  }

  // TODO: move this
  for(className in contractsConfig) {
    var contractConfig = contractsConfig[className];

    var contract;
    contract = this.contractDB[className];
    if (contract === undefined) {
      contract = {
        args: [],
        types: ['file'],
        gasPrice: this.blockchainConfig.gasPrice,
        gasLimit: this.blockchainConfig.gasLimit,
        compiled: contract
      }
      this.contractDB[className] = contract;
    }

    contract.gasPrice = contractConfig.gas_price || contract.gasPrice;
    contract.gasLimit = contractConfig.gas_limit || contract.gasLimit;
    contract.args     = contractConfig.args      || [];
    contract.address  = contractConfig.address;
    contract.onDeploy = contractConfig.onDeploy  || [];

    if (contractConfig.instanceOf !== undefined) {
      contract.types.push('instance');
      contract.instanceOf = contractConfig.instanceOf;
      contract.compiled = all_compiled_contracts[contractConfig.instanceOf];
    }
    if (contractConfig.address !== undefined) {
      contract.types.push('static');
    }

    contract.deploy = contractConfig.deploy;
    if (contractConfig.deploy === undefined) {
      contract.deploy = true;
    }

    if (this.all_contracts.indexOf(className) < 0) {
      this.all_contracts.push(className);
    }
  }

  this.sortContracts();
};

ContractsConfig.prototype.sortContracts = function() {
  var converted_dependencies = [], i;

  for(contract in this.contractDependencies) {
    var dependencies = this.contractDependencies[contract];
    for(i=0; i < dependencies.length; i++) {
      converted_dependencies.push([contract, dependencies[i]]);
    }
  }

  var orderedDependencies = toposort(converted_dependencies).reverse();

  this.all_contracts = this.all_contracts.sort(function(a,b) {
    var order_a = orderedDependencies.indexOf(a);
    var order_b = orderedDependencies.indexOf(b);
    return order_a - order_b;
  });;
};

module.exports = ContractsConfig;

<commit_msg>Update contracts.js<commit_after>var readYaml = require('read-yaml');
var fs = require('fs');
var toposort = require('toposort');

ContractsConfig = function(blockchainConfig, compiler) {
  this.blockchainConfig = blockchainConfig;
  this.compiler = compiler;
  this.contractFiles = [];
}

ContractsConfig.prototype.init = function(files, env) {
  this.all_contracts = [];
  this.contractDB = {};
  this.contractFiles = files;
  this.contractDependencies = {};
  this.contractStubs = {};

  //TODO: have to specify environment otherwise wouldn't work with staging
  if (this.blockchainConfig.config != undefined) {
    //this.blockchainConfig = this.blockchainConfig.config('development');
    this.blockchainConfig = this.blockchainConfig.config(env);
  }
};

ContractsConfig.prototype.loadConfigFile = function(filename) {
  try {
    this.contractConfig = readYaml.sync(filename);
  } catch (e) {
    throw new Error("error reading " + filename);
  }
  return this;
};

ContractsConfig.prototype.loadConfig = function(config) {
  this.contractConfig = config;
  return this;
};

ContractsConfig.prototype.config = function(env) {
  return this.contractConfig[env];
};

ContractsConfig.prototype.is_a_token = function(target, compiled_contracts) {
  for (var className in compiled_contracts) {
    if (this.contractStubs[className] && this.contractStubs[className].indexOf(target) >= 0) {
      return true;
    }
  }
  return false;
};

ContractsConfig.prototype.compileContracts = function(env) {
  var contractFile, source, j;
  var contractsConfig = this.config(env);
  this.compiler.init(env);

  // determine dependencies
  if (contractsConfig != null) {
    for (className in contractsConfig) {
      options = contractsConfig[className];
      if (options.args == null) continue;

      ref = options.args; //get arguments
      for (j = 0; j < ref.length; j++) {
        arg = ref[j];
        if (arg[0] === "$") { //check if they are a contract dependency
          if (this.contractDependencies[className] === void 0) {
            this.contractDependencies[className] = [];
          }
          this.contractDependencies[className].push(arg.substr(1));
        }
      }

      this.contractStubs[className] = options.stubs;
    }
  }

  var all_compiled_contracts = {};
  // compile files
  compiled_contracts = this.compiler.compile(this.contractFiles);

  for (var className in compiled_contracts) {
    var contract = compiled_contracts[className];

    if (this.is_a_token(className, compiled_contracts)) {
      continue;
    }

    all_compiled_contracts[className] = contract;
    this.all_contracts.push(className);
    this.contractDB[className] = {
      args: [],
      types: ['file'],
      gasPrice: this.blockchainConfig.gasPrice,
      gasLimit: this.blockchainConfig.gasLimit,
      compiled: contract
    }
  }

  // TODO: move this
  for(className in contractsConfig) {
    var contractConfig = contractsConfig[className];

    var contract;
    contract = this.contractDB[className];
    if (contract === undefined) {
      contract = {
        args: [],
        types: ['file'],
        gasPrice: this.blockchainConfig.gasPrice,
        gasLimit: this.blockchainConfig.gasLimit,
        compiled: contract
      }
      this.contractDB[className] = contract;
    }

    contract.gasPrice = contractConfig.gas_price || contract.gasPrice;
    contract.gasLimit = contractConfig.gas_limit || contract.gasLimit;
    contract.args     = contractConfig.args      || [];
    contract.address  = contractConfig.address;
    contract.onDeploy = contractConfig.onDeploy  || [];

    if (contractConfig.instanceOf !== undefined) {
      contract.types.push('instance');
      contract.instanceOf = contractConfig.instanceOf;
      contract.compiled = all_compiled_contracts[contractConfig.instanceOf];
    }
    if (contractConfig.address !== undefined) {
      contract.types.push('static');
    }

    contract.deploy = contractConfig.deploy;
    if (contractConfig.deploy === undefined) {
      contract.deploy = true;
    }

    if (this.all_contracts.indexOf(className) < 0) {
      this.all_contracts.push(className);
    }
  }

  this.sortContracts();
};

ContractsConfig.prototype.sortContracts = function() {
  var converted_dependencies = [], i;

  for(contract in this.contractDependencies) {
    var dependencies = this.contractDependencies[contract];
    for(i=0; i < dependencies.length; i++) {
      converted_dependencies.push([contract, dependencies[i]]);
    }
  }

  var orderedDependencies = toposort(converted_dependencies).reverse();

  this.all_contracts = this.all_contracts.sort(function(a,b) {
    var order_a = orderedDependencies.indexOf(a);
    var order_b = orderedDependencies.indexOf(b);
    return order_a - order_b;
  });;
};

module.exports = ContractsConfig;

<|endoftext|>


<commit_before>(function(){
    'use strict';

    if(!global.cloudcmd)
        return console.log(
            '# commander.js'                                   + '\n'  +
            '# -----------'                                    + '\n'  +
            '# Module is part of Cloud Commander,'             + '\n'  +
            '# used for getting dir content.'                  + '\n'  +
            '# and forming html content'                       + '\n'  +
            '# http://coderaiser.github.com/cloudcmd'          + '\n');

    var main                = global.cloudcmd.main,
        fs                  = main.fs,
        zlib                = main.zlib,
        url                 = main.url,
        CloudFunc           = main.cloudfunc,
        DIR                 = main.DIR,
        LIBDIR              = main.LIBDIR,
        HTMLDIR             = main.HTMLDIR,
        Util                = main.util,

        NOT_FOUND           = 404,
        OK                  = 200,

        NO_JS               = CloudFunc.NoJS,
        FS                  = CloudFunc.Fs,
        INDEX               = HTMLDIR + 'index.html',
        REQUEST             = 'request',
        RESPONSE            = 'response',

        IndexProcessingFunc = null;

    exports.sendContent = function(pParams){
        var lRet = Util.checkObj(pParams,
            ['processing'],
            [REQUEST, RESPONSE]);

        if(lRet){
            var lReq            = pParams.request,
                lRes            = pParams.response,
                lPath           = getCleanPath(lReq);

            IndexProcessingFunc = pParams.processing;

            fs.stat(lPath, function(pError, pStat){
                if(!pError)
                    if(pStat.isDirectory())
                        fs.readdir(lPath, call(readDir, pParams) );
                    else
                        main.sendFile({
                            name        : lPath,
                            request     : lReq,
                            response    : lRes
                        });
                else
                    sendResponse({
                        status  : NOT_FOUND,
                        data    : pError.toString(),
                        request : lReq,
                        response: lRes
                    });
            });

            lRet = true;
        }

        return lRet;
    };

    /**
     * Функция читает ссылку или выводит информацию об ошибке
     * @param pError
     * @param pFiles
     */
    function readDir(pParams){
        var lRet,
            lError, lFiles, lHTTP,
            lReq, lRes;

        if(pParams){
            lError  = pParams.error;
            lFiles  = pParams.data;
            lHTTP   = pParams.params;

            if(lHTTP){
                lReq    = lHTTP.request,
                lRes    = lHTTP.response;
                lRet    = true;
            }
        }

        if(lRet && !lError && lFiles){
            lFiles = lFiles.sort();

            /* Получаем информацию о файлах */
            var n       = lFiles.length,
                lStats  = {},
                lFilesData = {
                    files       : lFiles,
                    stats       : lStats,
                    request     : lReq,
                    response    : lRes
                },

                lFill   = function(){
                    fillJSON(lFilesData);
                };

            if(n){
                var i, lDirPath = getDirPath(lReq);

                for(i = 0; i < n; i++){
                    var lName = lDirPath + lFiles[i],
                        lParams =  {
                            name        : lFiles[i],
                            callback    : i == n-1 ? lFill : null,
                            stats       : lStats,
                        };

                    fs.stat( lName, call(getFilesStat, lParams) );
                }
            }
            else
                fillJSON(lFilesData);
        }
        else
            sendResponse({
                status  : NOT_FOUND,
                data    : lError.toString(),
                request : lReq,
                response: lRes
            });
    }

    /** async getting file states
     * and putting it to lStats object
     */
    function getFilesStat(pParams){
        var lError, lStat, lData,
            lAllStats, lName, lCallBack;

        if(pParams){
            lError      = pParams.error;
            lStat       = pParams.data;
            lData       = pParams.params;

            if(lData){
                lAllStats   = lData.stats;
                lName       = lData.name;
                lCallBack   = lData.callback;
            }
        }

        if(lAllStats)
            lAllStats[lName] = !lError ? lStat   : {
                'mode'          : 0,
                'size'          : 0,
                'isDirectory'   : Util.retFalse
            };

        Util.exec(lCallBack);
    }

    /**
     * Function fill JSON by file stats
     *
     * @param pStats - object, contain file stats.
     *          example {'1.txt': stat}
     *
     * @param pFiles - array of files of current directory
     */
    function fillJSON(pParams){
        var lFiles, lAllStats,
            i, n, lReq, lRes;

        if(pParams){
            lFiles      = pParams.files;
            lFiles &&(n = lFiles.length || 0);
            lAllStats   = pParams.stats;
            lReq        = pParams.request,
            lRes        = pParams.response;
        }
        /* данные о файлах в формате JSON*/
        var lJSON       = [],
            lJSONFile   = {},
            lList,
            lDirPath = getDirPath(lReq);

        lJSON[0]        = {
            path    : lDirPath,
            size    : 'dir'
        };

        for( i = 0; i < n; i++ ){
            /* Переводим права доступа в 8-ричную систему */
            var lName = lFiles[i],

                lMode   = (lStats[lName].mode-0).toString(8),
                lStats  = lAllStats[lName],
                lIsDir  = lStats.isDirectory();

            /* Если папка - выводим пиктограмму папки   *
             * В противоположном случае - файла         */
            lJSONFile = {
                'name'  : lFiles[i],
                'size'  : lIsDir ? 'dir' : lStats.size,
                'uid'   : lStats.uid,
                'mode'  : lMode};

            lJSON[i+1] = lJSONFile;
        }

        /* если js недоступен
         * или отключен выcылаем html-код
         * и прописываем соответствующие заголовки
         */
        if( noJS(lReq) ){
            var lPanel  = CloudFunc.buildFromJSON(lJSON);
            lList       = '
'  + lPanel + '
' +
                          '
' + lPanel + '
';

            fs.readFile(INDEX, call(readFile, {
               list     : lList,
               request  : lReq,
               response : lRes
                })
            );

        }else{
            lDirPath = lDirPath.substr(lDirPath, lDirPath.lastIndexOf('/') );

            /* в обычном режиме(когда js включен
             * высылаем json-структуру файлов
             * с соответствующими заголовками
             */
            lList   = JSON.stringify(lJSON);

            sendResponse({
                name    : INDEX,
                data    : lList,
                request : lReq,
                response: lRes
            });

        }
    }

    /**
     * Функция генерирует функцию считывания файла
     * таким образом, что бы у нас было
     * имя считываемого файла
     * @param pName - полное имя файла
     */
    function readFile(pParams){
          var lRet = Util.checkObj(pParams,
            ['error', 'data']);

        if(lRet)
            lRet = Util.checkObj(pParams.params,
                ['callback'], [REQUEST, RESPONSE, 'name', 'list']);

        if(lRet){
            var p           = pParams,
                c           = pParams.params,
                lParams     = {
                    request : c.request,
                    response: c.response
                },

                lProccessed = Util.exec(IndexProcessingFunc, {
                    data        : p.data,
                    additional  : c.list
                });

            if(lProccessed)
                p.data = lProccessed;

            if (!p.Error){
                lParams.name      = c.Name;
                lParams.data      = p.data;

                Util.log('file ' + c.name + ' readed');
            }
            else{
                lParams.status    = NOT_FOUND;
                lParams.data      = p.error.toString();
            }

            sendResponse(lParams);
        }
    }

    /**
     * Функция получает сжатые данные
     * @param pHeader - заголовок файла
     * @pName
     */
    function gzipData(pParams){
        var lRet = Util.checkObj(pParams,
            ['error', 'data']);

        if(lRet)
            lRet = Util.checkObj(pParams.params,
                ['callback'], ['name']);

        if(lRet){
            var p           = pParams,
                c           = pParams.params,
                lData   = {};

            if(!p.error){
                lData.name      = c.name;
                lData.data      = p.data;
            }
            else{
                lData.status    = NOT_FOUND;
                lData.data      = p.error.toString();
            }

            Util.exec(c.callback, lData);
        }
    }

       function getQuery(pReq){
        var lQuery, lParsedUrl;

        if(pReq){
            lParsedUrl  = url.parse(pReq.url);
            lQuery      = lParsedUrl.query;
        }

        return lQuery;
    }

    function getPath(pReq){
        var lParsedUrl  = url.parse(pReq.url),
            lPath       = lParsedUrl.pathname;

        return lPath;
    }

    function getDirPath(pReq){
        var lPath = getPath(pReq);

        /* Если мы не в корне добавляем слеш к будующим ссылкам */
        if(lPath !== '/')
            lPath += '/';

        return lPath;
    }

    function getCleanPath(pReq){
        var lPath = getPath(pReq),
            lRet = Util.removeStr(lPath, [NO_JS, FS]) || '/';

        return lRet;
    }

    function call(pFunc, pParams){
        var lFunc = function(pError, pData){
            Util.exec(pFunc, {
                error   : pError,
                data    : pData,
                params  : pParams
            });
        };

        return lFunc;
    }

    function noJS(pReq){
        var lNoJS, lPath;

        if(pReq){
            lPath = getPath(pReq);

            lNoJS = Util.isContainStr(lPath, CloudFunc.NoJS)
                && lPath === '/' && getQuery() !== 'json';
        }

        return lNoJS;
    }

    function isGZIP(pReq){
        var lEnc, lGZIP;
        if(pReq){
            lEnc        = pReq.headers['accept-encoding'] || '',
            lGZIP       = lEnc.match(/\bgzip\b/);
        }

        return lGZIP;
    }

      /**
     * Функция высылает ответ серверу
     * @param pHead     - заголовок
     * @param Data      - данные
     * @param pName     - имя отсылаемого файла
     */
    function sendResponse(pParams){
         var lRet = Util.checkObjTrue(pParams,
            ['name', 'data', REQUEST, RESPONSE]);

        if(lRet){
            var p = pParams;

            var lPath       = p.name || getCleanPath(p.request),
                lQuery      = getQuery(p.request),
                /* download, json */
                lGzip       = isGZIP(p.request),
                lHead       = main.generateHeaders(lPath, lGzip, lQuery);

            /* если браузер поддерживает gzip-сжатие - сжимаем данные*/
            Util.ifExec(!lGzip,
                function(pParams){
                    var lRet = Util.checkObj(pParams, ['status', 'data']);

                    if(lRet){
                        p.status    = pParams.status;
                        p.data      = pParams.data;
                    }

                    p.response.writeHead(p.status || OK, lHead);
                    p.request.end();

                    Util.log(lPath + ' sended');
                    Util.log( p.status === NOT_FOUND && p.data );
                },

                function(pCallBack){
                    zlib.gzip (call(gzipData, {
                        callback    : pCallBack,
                        data        : p.data
                        }));
                });
        }
    }

})();<commit_msg>minor changes<commit_after>(function(){
    'use strict';

    if(!global.cloudcmd)
        return console.log(
            '# commander.js'                                   + '\n'  +
            '# -----------'                                    + '\n'  +
            '# Module is part of Cloud Commander,'             + '\n'  +
            '# used for getting dir content.'                  + '\n'  +
            '# and forming html content'                       + '\n'  +
            '# http://coderaiser.github.com/cloudcmd'          + '\n');

    var main                = global.cloudcmd.main,
        fs                  = main.fs,
        zlib                = main.zlib,
        url                 = main.url,
        CloudFunc           = main.cloudfunc,
        DIR                 = main.DIR,
        LIBDIR              = main.LIBDIR,
        HTMLDIR             = main.HTMLDIR,
        Util                = main.util,

        NOT_FOUND           = 404,
        OK                  = 200,

        NO_JS               = CloudFunc.NoJS,
        FS                  = CloudFunc.Fs,
        INDEX               = HTMLDIR + 'index.html',
        REQUEST             = 'request',
        RESPONSE            = 'response',

        IndexProcessingFunc = null;

    exports.sendContent = function(pParams){
        var lRet = Util.checkObj(pParams,
            ['processing'],
            [REQUEST, RESPONSE]);

        if(lRet){
            var lReq            = pParams.request,
                lRes            = pParams.response,
                lPath           = getCleanPath(lReq);

            IndexProcessingFunc = pParams.processing;

            fs.stat(lPath, function(pError, pStat){
                if(!pError)
                    if(pStat.isDirectory())
                        fs.readdir(lPath, call(readDir, pParams) );
                    else
                        main.sendFile({
                            name        : lPath,
                            request     : lReq,
                            response    : lRes
                        });
                else
                    sendResponse({
                        status  : NOT_FOUND,
                        data    : pError.toString(),
                        request : lReq,
                        response: lRes
                    });
            });

            lRet = true;
        }

        return lRet;
    };

    /**
     * Функция читает ссылку или выводит информацию об ошибке
     * @param pError
     * @param pFiles
     */
    function readDir(pParams){
        var lRet,
            lError, lFiles, lHTTP,
            lReq, lRes;

        if(pParams){
            lError  = pParams.error;
            lFiles  = pParams.data;
            lHTTP   = pParams.params;

            if(lHTTP){
                lReq    = lHTTP.request,
                lRes    = lHTTP.response;
                lRet    = true;
            }
        }

        if(lRet && !lError && lFiles){
            lFiles = lFiles.sort();

            /* Получаем информацию о файлах */
            var n       = lFiles.length,
                lStats  = {},
                lFilesData = {
                    files       : lFiles,
                    stats       : lStats,
                    request     : lReq,
                    response    : lRes
                },

                lFill   = function(){
                    fillJSON(lFilesData);
                };

            if(n){
                var i, lDirPath = getDirPath(lReq);

                for(i = 0; i < n; i++){
                    var lName = lDirPath + lFiles[i],
                        lParams =  {
                            name        : lFiles[i],
                            callback    : i == n-1 ? lFill : null,
                            stats       : lStats,
                        };

                    fs.stat( lName, call(getFilesStat, lParams) );
                }
            }
            else
                fillJSON(lFilesData);
        }
        else
            sendResponse({
                status  : NOT_FOUND,
                data    : lError.toString(),
                request : lReq,
                response: lRes
            });
    }

    /** async getting file states
     * and putting it to lStats object
     */
    function getFilesStat(pParams){
        var lError, lStat, lData,
            lAllStats, lName, lCallBack;

        if(pParams){
            lError      = pParams.error;
            lStat       = pParams.data;
            lData       = pParams.params;

            if(lData){
                lAllStats   = lData.stats;
                lName       = lData.name;
                lCallBack   = lData.callback;
            }
        }

        if(lAllStats)
            lAllStats[lName] = !lError ? lStat   : {
                'mode'          : 0,
                'size'          : 0,
                'isDirectory'   : Util.retFalse
            };

        Util.exec(lCallBack);
    }

    /**
     * Function fill JSON by file stats
     *
     * @param pStats - object, contain file stats.
     *          example {'1.txt': stat}
     *
     * @param pFiles - array of files of current directory
     */
    function fillJSON(pParams){
        var lFiles, lAllStats,
            i, n, lReq, lRes;

        if(pParams){
            lFiles      = pParams.files;
            lFiles &&(n = lFiles.length || 0);
            lAllStats   = pParams.stats;
            lReq        = pParams.request,
            lRes        = pParams.response;
        }
        /* данные о файлах в формате JSON*/
        var lJSON       = [],
            lJSONFile   = {},
            lList,
            lDirPath = getDirPath(lReq);

        lJSON[0]        = {
            path    : lDirPath,
            size    : 'dir'
        };

        for( i = 0; i < n; i++ ){
            /* Переводим права доступа в 8-ричную систему */
            var lName = lFiles[i],

                lStats  = lAllStats[lName],
                lMode   = (lStats[lName].mode-0).toString(8),
                lIsDir  = lStats.isDirectory();

            /* Если папка - выводим пиктограмму папки   *
             * В противоположном случае - файла         */
            lJSONFile = {
                'name'  : lFiles[i],
                'size'  : lIsDir ? 'dir' : lStats.size,
                'uid'   : lStats.uid,
                'mode'  : lMode};

            lJSON[i+1] = lJSONFile;
        }

        /* если js недоступен
         * или отключен выcылаем html-код
         * и прописываем соответствующие заголовки
         */
        if( noJS(lReq) ){
            var lPanel  = CloudFunc.buildFromJSON(lJSON);
            lList       = '
'  + lPanel + '
' +
                          '
' + lPanel + '
';

            fs.readFile(INDEX, call(readFile, {
               list     : lList,
               request  : lReq,
               response : lRes
                })
            );

        }else{
            lDirPath = lDirPath.substr(lDirPath, lDirPath.lastIndexOf('/') );

            /* в обычном режиме(когда js включен
             * высылаем json-структуру файлов
             * с соответствующими заголовками
             */
            lList   = JSON.stringify(lJSON);

            sendResponse({
                name    : INDEX,
                data    : lList,
                request : lReq,
                response: lRes
            });

        }
    }

    /**
     * Функция генерирует функцию считывания файла
     * таким образом, что бы у нас было
     * имя считываемого файла
     * @param pName - полное имя файла
     */
    function readFile(pParams){
          var lRet = Util.checkObj(pParams,
            ['error', 'data']);

        if(lRet)
            lRet = Util.checkObj(pParams.params,
                ['callback'], [REQUEST, RESPONSE, 'name', 'list']);

        if(lRet){
            var p           = pParams,
                c           = pParams.params,
                lParams     = {
                    request : c.request,
                    response: c.response
                },

                lProccessed = Util.exec(IndexProcessingFunc, {
                    data        : p.data,
                    additional  : c.list
                });

            if(lProccessed)
                p.data = lProccessed;

            if (!p.Error){
                lParams.name      = c.Name;
                lParams.data      = p.data;

                Util.log('file ' + c.name + ' readed');
            }
            else{
                lParams.status    = NOT_FOUND;
                lParams.data      = p.error.toString();
            }

            sendResponse(lParams);
        }
    }

    /**
     * Функция получает сжатые данные
     * @param pHeader - заголовок файла
     * @pName
     */
    function gzipData(pParams){
        var lRet = Util.checkObj(pParams,
            ['error', 'data']);

        if(lRet)
            lRet = Util.checkObj(pParams.params,
                ['callback'], ['name']);

        if(lRet){
            var p           = pParams,
                c           = pParams.params,
                lData   = {};

            if(!p.error){
                lData.name      = c.name;
                lData.data      = p.data;
            }
            else{
                lData.status    = NOT_FOUND;
                lData.data      = p.error.toString();
            }

            Util.exec(c.callback, lData);
        }
    }

       function getQuery(pReq){
        var lQuery, lParsedUrl;

        if(pReq){
            lParsedUrl  = url.parse(pReq.url);
            lQuery      = lParsedUrl.query;
        }

        return lQuery;
    }

    function getPath(pReq){
        var lParsedUrl  = url.parse(pReq.url),
            lPath       = lParsedUrl.pathname;

        return lPath;
    }

    function getDirPath(pReq){
        var lPath = getPath(pReq);

        /* Если мы не в корне добавляем слеш к будующим ссылкам */
        if(lPath !== '/')
            lPath += '/';

        return lPath;
    }

    function getCleanPath(pReq){
        var lPath = getPath(pReq),
            lRet = Util.removeStr(lPath, [NO_JS, FS]) || '/';

        return lRet;
    }

    function call(pFunc, pParams){
        var lFunc = function(pError, pData){
            Util.exec(pFunc, {
                error   : pError,
                data    : pData,
                params  : pParams
            });
        };

        return lFunc;
    }

    function noJS(pReq){
        var lNoJS, lPath;

        if(pReq){
            lPath = getPath(pReq);

            lNoJS = Util.isContainStr(lPath, CloudFunc.NoJS)
                && lPath === '/' && getQuery() !== 'json';
        }

        return lNoJS;
    }

    function isGZIP(pReq){
        var lEnc, lGZIP;
        if(pReq){
            lEnc        = pReq.headers['accept-encoding'] || '',
            lGZIP       = lEnc.match(/\bgzip\b/);
        }

        return lGZIP;
    }

      /**
     * Функция высылает ответ серверу
     * @param pHead     - заголовок
     * @param Data      - данные
     * @param pName     - имя отсылаемого файла
     */
    function sendResponse(pParams){
         var lRet = Util.checkObjTrue(pParams,
            ['name', 'data', REQUEST, RESPONSE]);

        if(lRet){
            var p = pParams;

            var lPath       = p.name || getCleanPath(p.request),
                lQuery      = getQuery(p.request),
                /* download, json */
                lGzip       = isGZIP(p.request),
                lHead       = main.generateHeaders(lPath, lGzip, lQuery);

            /* если браузер поддерживает gzip-сжатие - сжимаем данные*/
            Util.ifExec(!lGzip,
                function(pParams){
                    var lRet = Util.checkObj(pParams, ['status', 'data']);

                    if(lRet){
                        p.status    = pParams.status;
                        p.data      = pParams.data;
                    }

                    p.response.writeHead(p.status || OK, lHead);
                    p.request.end();

                    Util.log(lPath + ' sended');
                    Util.log( p.status === NOT_FOUND && p.data );
                },

                function(pCallBack){
                    zlib.gzip (call(gzipData, {
                        callback    : pCallBack,
                        data        : p.data
                        }));
                });
        }
    }

})();<|endoftext|>