<commit_before>
/*!
 * knox - Client
 * Copyright(c) 2010 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var utils = require('./utils')
  , auth = require('./auth')
  , http = require('http')
  , join = require('path').join
  , mime = require('./mime')
  , fs = require('fs');

/**
 * Initialize a `Client` with the given `options`.
 *
 * Required:
 *
 *  - `key`     amazon api key
 *  - `secret`  amazon secret
 *  - `bucket`  bucket name string, ex: "learnboost"
 *
 * @param {Object} options
 * @api public
 */

var Client = module.exports = exports = function Client(options) {
  this.host = 's3.amazonaws.com';
  utils.merge(this, options);
  if (!this.key) throw new Error('aws "key" required');
  if (!this.secret) throw new Error('aws "secret" required');
  if (!this.bucket) throw new Error('aws "bucket" required');
};

/**
 * Request with `filename` the given `method`, and optional `headers`.
 *
 * @param {String} method
 * @param {String} filename
 * @param {Object} headers
 * @return {ClientRequest}
 * @api private
 */

Client.prototype.request = function(method, filename, headers){
  var client = http.createClient(80, this.host)
    , path = join('/', this.bucket, filename)
    , date = new Date
    , headers = headers || {};

  // Default headers
  utils.merge(headers, {
      Date: date.toUTCString()
    , Host: this.host
  });

  // Authorization header
  headers.Authorization = auth.authorization({
      key: this.key
    , secret: this.secret
    , verb: method
    , date: date
    , resource: path
    , contentType: headers['Content-Type']
    , amazonHeaders: auth.canonicalizeHeaders(headers)
  });

  client.on('error', function(err){
    // TODO: should self.emit('error')
    req.emit('error', err);
  });

  var req = client.request(method, path, headers);
  req.url = this.url(filename);
  return req;
};

/**
 * PUT data to `filename` with optional `headers`.
 *
 * Example:
 *
 *     // Fetch the size
 *     fs.stat('Readme.md', function(err, stat){
 *      // Create our request
 *      var req = client.put('/test/Readme.md', {
 *          'Content-Length': stat.size
 *        , 'Content-Type': 'text/plain'
 *      });
 *      fs.readFile('Readme.md', function(err, buf){
 *        // Output response
 *        req.on('response', function(res){
 *          console.log(res.statusCode);
 *          console.log(res.headers);
 *          res.on('data', function(chunk){
 *            console.log(chunk.toString());
 *          });
 *        });
 *        // Send the request with the file's Buffer obj
 *        req.end(buf);
 *      });
 *     });
 *
 * @param {String} filename
 * @param {Object} headers
 * @return {ClientRequest}
 * @api public
 */

Client.prototype.put = function(filename, headers){
  headers = utils.merge({
      Expect: '100-continue'
    , 'x-amz-acl': 'public-read'
  }, headers || {});
  return this.request('PUT', filename, headers);
};

/**
 * PUT the file at `src` to `filename`, with callback `fn`
 * receiving a possible exception, and the response object.
 *
 * NOTE: this method reads the _entire_ file into memory using
 * fs.readFile(), and is not recommended or large files.
 *
 * Example:
 *
 *    client
 *     .putFile('package.json', '/test/package.json', function(err, res){
 *       if (err) throw err;
 *       console.log(res.statusCode);
 *       console.log(res.headers);
 *     });
 *
 * @param {String} src
 * @param {String} filename
 * @param {Object|Function} headers
 * @param {Function} fn
 * @api public
 */

Client.prototype.putFile = function(src, filename, headers, fn){
  var self = this;
  if ('function' == typeof headers) {
    fn = headers;
    headers = {};
  };
  fs.readFile(src, function(err, buf){
    if (err) return fn(err);
    headers = utils.merge({
        'Content-Length': buf.length
      , 'Content-Type': mime.lookup(src)
    }, headers);
    self.put(filename, headers).on('response', function(res){
      fn(null, res);
    }).end(buf);
  });
};

/**
 * PUT the given `stream` as `filename` with optional `headers`.
 *
 * @param {Stream} stream
 * @param {String} filename
 * @param {Object|Function} headers
 * @param {Function} fn
 * @api public
 */

Client.prototype.putStream = function(stream, filename, headers, fn){
  var self = this;
  if ('function' == typeof headers) {
    fn = headers;
    headers = {};
  };
  fs.stat(stream.path, function(err, stat){
    if (err) return fn(err);
    // TODO: sys.pump() wtf?
    var req = self.put(filename, utils.merge({
        'Content-Length': stat.size
      , 'Content-Type': mime.lookup(stream.path)
    }, headers));
    req.on('response', function(res){
      fn(null, res);
    });
    stream
      .on('error', function(err){fn(null, err); })
      .on('data', function(chunk){ req.write(chunk); })
      .on('end', function(){ req.end(); });
  });
};

/**
 * GET `filename` with optional `headers`.
 *
 * @param {String} filename
 * @param {Object} headers
 * @return {ClientRequest}
 * @api public
 */

Client.prototype.get = function(filename, headers){
  return this.request('GET', filename, headers);
};

/**
 * GET `filename` with optional `headers` and callback `fn`
 * with a possible exception and the response.
 *
 * @param {String} filename
 * @param {Object|Function} headers
 * @param {Function} fn
 * @api public
 */

Client.prototype.getFile = function(filename, headers, fn){
  if ('function' == typeof headers) {
    fn = headers;
    headers = {};
  }
  return this.get(filename, headers).on('response', function(res){
    fn(null, res);
  }).end();
};

/**
 * Issue a HEAD request on `filename` with optional `headers.
 *
 * @param {String} filename
 * @param {Object} headers
 * @return {ClientRequest}
 * @api public
 */

Client.prototype.head = function(filename, headers){
  return this.request('HEAD', filename, headers);
};

/**
 * Issue a HEAD request on `filename` with optional `headers`
 * and callback `fn` with a possible exception and the response.
 *
 * @param {String} filename
 * @param {Object|Function} headers
 * @param {Function} fn
 * @api public
 */

Client.prototype.headFile = function(filename, headers, fn){
  if ('function' == typeof headers) {
    fn = headers;
    headers = {};
  }
  return this.head(filename, headers).on('response', function(res){
    fn(null, res);
  }).end();
};

/**
 * DELETE `filename` with optional `headers.
 *
 * @param {String} filename
 * @param {Object} headers
 * @return {ClientRequest}
 * @api public
 */

Client.prototype.del = function(filename, headers){
  return this.request('DELETE', filename, headers);
};

/**
 * DELETE `filename` with optional `headers`
 * and callback `fn` with a possible exception and the response.
 *
 * @param {String} filename
 * @param {Object|Function} headers
 * @param {Function} fn
 * @api public
 */

Client.prototype.deleteFile = function(filename, headers, fn){
  if ('function' == typeof headers) {
    fn = headers;
    headers = {};
  }
  return this.del(filename, headers).on('response', function(res){
    fn(null, res);
  }).end();
};

/**
 * Return a url to the given `filename`.
 *
 * @param {String} filename
 * @return {String}
 * @api public
 */

Client.prototype.url = function(filename){
  return 'http://' + this.bucket + '.' + this.host + join('/', filename);
};

/**
 * Shortcut for `new Client()`.
 *
 * @param {Object} options
 * @see Client()
 * @api public
 */

exports.createClient = function(options){
  return new Client(options);
};<commit_msg>Allowing use of URL parameters in signing mechanism<commit_after>
/*!
 * knox - Client
 * Copyright(c) 2010 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var utils = require('./utils')
  , auth = require('./auth')
  , http = require('http')
  , url = require('url')
  , join = require('path').join
  , mime = require('./mime')
  , fs = require('fs');

/**
 * Initialize a `Client` with the given `options`.
 *
 * Required:
 *
 *  - `key`     amazon api key
 *  - `secret`  amazon secret
 *  - `bucket`  bucket name string, ex: "learnboost"
 *
 * @param {Object} options
 * @api public
 */

var Client = module.exports = exports = function Client(options) {
  this.host = 's3.amazonaws.com';
  utils.merge(this, options);
  if (!this.key) throw new Error('aws "key" required');
  if (!this.secret) throw new Error('aws "secret" required');
  if (!this.bucket) throw new Error('aws "bucket" required');
};

/**
 * Request with `filename` the given `method`, and optional `headers`.
 *
 * @param {String} method
 * @param {String} filename
 * @param {Object} headers
 * @return {ClientRequest}
 * @api private
 */

Client.prototype.request = function(method, filename, headers){
  var client = http.createClient(80, this.host)
    , path = join('/', this.bucket, filename)
    , date = new Date
    , headers = headers || {};

  // Default headers
  utils.merge(headers, {
      Date: date.toUTCString()
    , Host: this.host
  });

  // Authorization header
  headers.Authorization = auth.authorization({
      key: this.key
    , secret: this.secret
    , verb: method
    , date: date
    , resource: url.parse(path).pathname
    , contentType: headers['Content-Type']
    , amazonHeaders: auth.canonicalizeHeaders(headers)
  });

  client.on('error', function(err){
    // TODO: should self.emit('error')
    req.emit('error', err);
  });

  var req = client.request(method, path, headers);
  req.url = this.url(filename);
  return req;
};

/**
 * PUT data to `filename` with optional `headers`.
 *
 * Example:
 *
 *     // Fetch the size
 *     fs.stat('Readme.md', function(err, stat){
 *      // Create our request
 *      var req = client.put('/test/Readme.md', {
 *          'Content-Length': stat.size
 *        , 'Content-Type': 'text/plain'
 *      });
 *      fs.readFile('Readme.md', function(err, buf){
 *        // Output response
 *        req.on('response', function(res){
 *          console.log(res.statusCode);
 *          console.log(res.headers);
 *          res.on('data', function(chunk){
 *            console.log(chunk.toString());
 *          });
 *        });
 *        // Send the request with the file's Buffer obj
 *        req.end(buf);
 *      });
 *     });
 *
 * @param {String} filename
 * @param {Object} headers
 * @return {ClientRequest}
 * @api public
 */

Client.prototype.put = function(filename, headers){
  headers = utils.merge({
      Expect: '100-continue'
    , 'x-amz-acl': 'public-read'
  }, headers || {});
  return this.request('PUT', filename, headers);
};

/**
 * PUT the file at `src` to `filename`, with callback `fn`
 * receiving a possible exception, and the response object.
 *
 * NOTE: this method reads the _entire_ file into memory using
 * fs.readFile(), and is not recommended or large files.
 *
 * Example:
 *
 *    client
 *     .putFile('package.json', '/test/package.json', function(err, res){
 *       if (err) throw err;
 *       console.log(res.statusCode);
 *       console.log(res.headers);
 *     });
 *
 * @param {String} src
 * @param {String} filename
 * @param {Object|Function} headers
 * @param {Function} fn
 * @api public
 */

Client.prototype.putFile = function(src, filename, headers, fn){
  var self = this;
  if ('function' == typeof headers) {
    fn = headers;
    headers = {};
  };
  fs.readFile(src, function(err, buf){
    if (err) return fn(err);
    headers = utils.merge({
        'Content-Length': buf.length
      , 'Content-Type': mime.lookup(src)
    }, headers);
    self.put(filename, headers).on('response', function(res){
      fn(null, res);
    }).end(buf);
  });
};

/**
 * PUT the given `stream` as `filename` with optional `headers`.
 *
 * @param {Stream} stream
 * @param {String} filename
 * @param {Object|Function} headers
 * @param {Function} fn
 * @api public
 */

Client.prototype.putStream = function(stream, filename, headers, fn){
  var self = this;
  if ('function' == typeof headers) {
    fn = headers;
    headers = {};
  };
  fs.stat(stream.path, function(err, stat){
    if (err) return fn(err);
    // TODO: sys.pump() wtf?
    var req = self.put(filename, utils.merge({
        'Content-Length': stat.size
      , 'Content-Type': mime.lookup(stream.path)
    }, headers));
    req.on('response', function(res){
      fn(null, res);
    });
    stream
      .on('error', function(err){fn(null, err); })
      .on('data', function(chunk){ req.write(chunk); })
      .on('end', function(){ req.end(); });
  });
};

/**
 * GET `filename` with optional `headers`.
 *
 * @param {String} filename
 * @param {Object} headers
 * @return {ClientRequest}
 * @api public
 */

Client.prototype.get = function(filename, headers){
  return this.request('GET', filename, headers);
};

/**
 * GET `filename` with optional `headers` and callback `fn`
 * with a possible exception and the response.
 *
 * @param {String} filename
 * @param {Object|Function} headers
 * @param {Function} fn
 * @api public
 */

Client.prototype.getFile = function(filename, headers, fn){
  if ('function' == typeof headers) {
    fn = headers;
    headers = {};
  }
  return this.get(filename, headers).on('response', function(res){
    fn(null, res);
  }).end();
};

/**
 * Issue a HEAD request on `filename` with optional `headers.
 *
 * @param {String} filename
 * @param {Object} headers
 * @return {ClientRequest}
 * @api public
 */

Client.prototype.head = function(filename, headers){
  return this.request('HEAD', filename, headers);
};

/**
 * Issue a HEAD request on `filename` with optional `headers`
 * and callback `fn` with a possible exception and the response.
 *
 * @param {String} filename
 * @param {Object|Function} headers
 * @param {Function} fn
 * @api public
 */

Client.prototype.headFile = function(filename, headers, fn){
  if ('function' == typeof headers) {
    fn = headers;
    headers = {};
  }
  return this.head(filename, headers).on('response', function(res){
    fn(null, res);
  }).end();
};

/**
 * DELETE `filename` with optional `headers.
 *
 * @param {String} filename
 * @param {Object} headers
 * @return {ClientRequest}
 * @api public
 */

Client.prototype.del = function(filename, headers){
  return this.request('DELETE', filename, headers);
};

/**
 * DELETE `filename` with optional `headers`
 * and callback `fn` with a possible exception and the response.
 *
 * @param {String} filename
 * @param {Object|Function} headers
 * @param {Function} fn
 * @api public
 */

Client.prototype.deleteFile = function(filename, headers, fn){
  if ('function' == typeof headers) {
    fn = headers;
    headers = {};
  }
  return this.del(filename, headers).on('response', function(res){
    fn(null, res);
  }).end();
};

/**
 * Return a url to the given `filename`.
 *
 * @param {String} filename
 * @return {String}
 * @api public
 */

Client.prototype.url = function(filename){
  return 'http://' + this.bucket + '.' + this.host + join('/', filename);
};

/**
 * Shortcut for `new Client()`.
 *
 * @param {Object} options
 * @see Client()
 * @api public
 */

exports.createClient = function(options){
  return new Client(options);
};<|endoftext|>


<commit_before>coinpunk.Wallet = function(walletKey, walletId) {

console.log('[wallet.js.2]', coinpunk.config); //TODO
  this.network = coinpunk.config.network || 'prod';
console.log('[wallet.js.3]', coinpunk.config); //TODO
  this.walletKey = walletKey;
  this.walletId = walletId;
  this.defaultIterations = 1000;
  this.serverKey = undefined;
  this.transactions = [];
  this.unspent = [];
  this.minimumConfirmations = 1;
  this.unspentConfirmations = [];
  var keyPairs = [];

  this.loadPayloadWithLogin = function(id, password, payload) {
    this.createWalletKey(id, password);
    this.loadPayload(payload);
    return true;
  };

  this.loadPayload = function(encryptedJSON) {
    var payloadJSON = sjcl.decrypt(this.walletKey, encryptedJSON);
    this.payloadHash = this.computePayloadHash(payloadJSON);
    var payload = JSON.parse(payloadJSON);
    keyPairs = payload.keyPairs;
    this.transactions = payload.transactions || [];
    this.unspent = payload.unspent || [];
    return true;
  };

  this.mergePayload = function(wallet) {
    var payloadJSON = sjcl.decrypt(this.walletKey, wallet);
    var payload = JSON.parse(payloadJSON);

    keyPairs = _.uniq(_.union(payload.keyPairs, keyPairs), false, function(item, key, a) {
      return item.key;
    });

    this.transactions = _.uniq(_.union(payload.transactions, this.transactions), false, function(item, key, a) {
      return item.hash;
    });

    this.unspent = _.uniq(_.union(payload.unspent, this.unspent), false, function(item, key, a) {
      return item.hash;
    });

    this.payloadHash  = this.computePayloadHash(payloadJSON);

    return true;
  };

  this.createNewAddress = function(name, isChange) {
    var eckey      = new Bitcoin.ECKey();
    var newKeyPair = {
      key: eckey.getExportedPrivateKey(this.network),
      publicKey: Bitcoin.convert.bytesToHex(eckey.getPubKeyHash()),
      address: eckey.getBitcoinAddress(this.network).toString(),
      isChange: (isChange == true)
    };

    if(name)
      newKeyPair.name = name;

    keyPairs.push(newKeyPair);
    return newKeyPair.address;
  };

  this.removeAddress = function(address) {
    var i=0;
    for(i=0;i<keyPairs.length;i++)
      if(keyPairs[i].address == address)
        keyPairs.splice(i, 1)
  };

  this.getAddressName = function(address) {
    for(var i=0;i<keyPairs.length;i++)
      if(keyPairs[i].address == address)
        return keyPairs[i].name;
  };

  this.addresses = function() {
    var addrs = [];
    for(var i=0; i<keyPairs.length; i++) {
      addrs.push({address: keyPairs[i].address, name: keyPairs[i].name, isChange: keyPairs[i].isChange});
    }
    return addrs;
  };

  this.receiveAddresses = function() {
    var addrs = [];
    for(var i=0; i<keyPairs.length; i++) {
      if(keyPairs[i].isChange != true)
        addrs.push({address: keyPairs[i].address, name: keyPairs[i].name});
    }
    return addrs;
  };

  this.receiveAddressHashes = function() {
    var addrHashes = [];
    for(var i=0; i<keyPairs.length; i++) {
      if(keyPairs[i].isChange != true)
        addrHashes.push(keyPairs[i].address);
    }

    return addrHashes;
  };

  this.changeAddressHashes = function() {
    var addrHashes = [];
    for(var i=0; i<keyPairs.length; i++) {
      if(keyPairs[i].isChange == true)
        addrHashes.push(keyPairs[i].address);
    }

    return addrHashes;
  };

  this.addressHashes = function() {
    var addresses = this.addresses();
    var addressHashes = [];
    for(var i=0;i<addresses.length;i++)
      addressHashes.push(addresses[i].address);
    return addressHashes;
  }

  this.createServerKey = function() {
    this.serverKey = sjcl.codec.base64.fromBits(sjcl.misc.pbkdf2(this.walletKey, this.walletId, this.defaultIterations));
    return this.serverKey;
  };

  this.createWalletKey = function(id, password) {
    this.walletKey = sjcl.codec.base64.fromBits(sjcl.misc.pbkdf2(password, id, this.defaultIterations));
    this.walletId = id;
    this.createServerKey();
    return this.walletKey;
  };

  this.computePayloadHash = function(payloadJSON) {
    return sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(payloadJSON));
  };

  this.encryptPayload = function() {
    var payload = {keyPairs: keyPairs, transactions: this.transactions, unspent: this.unspent};
    var payloadJSON = JSON.stringify(payload);
    this.newPayloadHash = this.computePayloadHash(payloadJSON);
    return sjcl.encrypt(this.walletKey, payloadJSON);
  };

  this.mergeUnspent = function(newUnspent) {
    var changed = false;
    this.unspentConfirmations = this.unspentConfirmations || {};

    for(var i=0;i<newUnspent.length;i++) {
      var match = false;

      for(var j=0;j<this.unspent.length;j++) {
        if(this.unspent[j].hash == newUnspent[i].hash)
          match = true;
      }

      this.unspentConfirmations[newUnspent[i].hash] = newUnspent[i].confirmations;

      if(match == true)
        continue;

      changed = true;

      this.unspent.push({
        hash: newUnspent[i].hash,
        vout: newUnspent[i].vout,
        address: newUnspent[i].address,
        scriptPubKey: newUnspent[i].scriptPubKey,
        amount: newUnspent[i].amount
      });

      // todo: time should probably not be generated here

      var txMatch = false;

      for(var k=0;k<this.transactions.length;k++) {
        if(this.transactions[k].hash == newUnspent[i].hash)
          txMatch = true;
      }

      if(txMatch == false) {
        this.transactions.push({
          hash: newUnspent[i].hash,
          type: 'receive',
          address: newUnspent[i].address,
          amount: newUnspent[i].amount,
          time: new Date().getTime()
        });
      }
    }

    return changed;
  };

  this.getUnspent = function(confirmations) {
    var confirmations = confirmations || 0;
    var unspent = [];

    for(var i=0; i<this.unspent.length; i++)
      if(this.unspentConfirmations[this.unspent[i].hash] >= confirmations)
        unspent.push(this.unspent[i]);
    return unspent;
  };

  this.pendingUnspentBalance = function() {
    var unspent = this.getUnspent(0);
    var changeAddresses = this.changeAddressHashes();
    var balance = new BigNumber(0);

    for(var u=0;u<unspent.length;u++) {
      if(this.unspentConfirmations[unspent[u].hash] == 0 && _.contains(changeAddresses, unspent[u].address) == false)
        balance = balance.plus(unspent[u].amount);
    }
    return balance;
  };

  this.safeUnspentBalance = function() {
    var safeUnspent = this.safeUnspent();
    var amount = new BigNumber(0);
    for(var i=0;i<safeUnspent.length;i++)
      amount = amount.plus(safeUnspent[i].amount);
    return amount;
  };

  // Safe to spend unspent txs.
  this.safeUnspent = function() {
    var unspent = this.getUnspent();
    var changeAddresses = this.changeAddressHashes();
    var safeUnspent = [];
    for(var u=0;u<unspent.length;u++) {
      if(_.contains(changeAddresses, unspent[u].address) == true || this.unspentConfirmations[unspent[u].hash] >= this.minimumConfirmations)
        safeUnspent.push(unspent[u]);
    }

    return safeUnspent;
  };

  this.receivedAmountTotal = function() {
    var addresses = this.addresses();
    var amount = new BigNumber(0);

    for(var a=0;a<addresses.length;a++)
      amount = amount.plus(this.addressReceivedAmount(addresses[a]));

    return amount;
  }

  this.addressReceivedAmount = function(address) {
    var amount = new BigNumber(0.00);

    for(var t=0; t<this.transactions.length;t++)
      if(this.transactions[t].address == address)
        amount = amount.plus(this.transactions[t].amount);

    return amount;
  };

  this.createTx = function(amtString, feeString, addressString, changeAddress) {
    var amt = Bitcoin.util.parseValue(amtString);

    if(amt == Bitcoin.BigInteger.ZERO)
      throw "spend amount must be greater than zero";

    if(!changeAddress)
      throw "change address was not provided";

    var fee = Bitcoin.util.parseValue(feeString || '0');
    var total = Bitcoin.BigInteger.ZERO.add(amt).add(fee);

    var address = new Bitcoin.Address(addressString, this.network);
    var sendTx = new Bitcoin.Transaction();
    var i;

    var unspent = [];
    var unspentAmt = Bitcoin.BigInteger.ZERO;

    var safeUnspent = this.safeUnspent();

    for(i=0;i<safeUnspent.length;i++) {
      unspent.push(safeUnspent[i]);

      var amountSatoshiString = new BigNumber(safeUnspent[i].amount).times(Math.pow(10,8)).toString();

      unspentAmt = unspentAmt.add(new Bitcoin.BigInteger(amountSatoshiString));

      // If > -1, we have enough to send the requested amount
      if(unspentAmt.compareTo(total) > -1) {
        break;
      }
    }

    if(unspentAmt.compareTo(total) < 0) {
      throw "you do not have enough bitcoins to send this amount";
    }

    for(i=0;i<unspent.length;i++) {
      sendTx.addInput({hash: unspent[i].hash}, unspent[i].vout);
    }

    // The address you are sending to, and the amount:
    sendTx.addOutput(address, amt);

    var remainder = unspentAmt.subtract(total);

    if(!remainder.equals(Bitcoin.BigInteger.ZERO)) {
      sendTx.addOutput(changeAddress, remainder);
    }

    var hashType = 1; // SIGHASH_ALL

    // Here will be the beginning of your signing for loop

    for(i=0;i<unspent.length;i++) {
      var unspentOutScript = new Bitcoin.Script(Bitcoin.convert.hexToBytes(unspent[i].scriptPubKey));
      var hash = sendTx.hashTransactionForSignature(unspentOutScript, i, hashType);
      var pubKeyHash = unspentOutScript.simpleOutHash();
      var pubKeyHashHex = Bitcoin.convert.bytesToHex(pubKeyHash);

      for(var j=0;j<keyPairs.length;j++) {
        if(_.isEqual(keyPairs[j].publicKey, pubKeyHashHex)) {
          var key = new Bitcoin.Key(keyPairs[j].key);
          var signature = key.sign(hash);
          signature.push(parseInt(hashType, 10));

          sendTx.ins[i].script = Bitcoin.Script.createInputScript(signature, key.getPub());
          break;
        }
      }
    }

    return {unspentsUsed: unspent, obj: sendTx, raw: Bitcoin.convert.bytesToHex(sendTx.serialize())};
  };

  this.calculateFee = function(amtString, addressString, changeAddress) {
    var tx = this.createTx(amtString, 0, addressString, changeAddress);
    var txSize = tx.raw.length / 2;
    // console.log(txSize);
    return Math.ceil(txSize/1000)*0.0001;
  };

  this.createSend = function(amtString, feeString, addressString, changeAddress) {
    var tx = this.createTx(amtString, feeString, addressString, changeAddress);

    this.transactions.push({
      hash: Bitcoin.convert.bytesToHex(tx.obj.getHash()),
      type: 'send',
      address: addressString,
      amount: amtString,
      fee: feeString,
      time: new Date().getTime()
    });

    // Remove unspent elements now that we have a tx that uses them
    for(var i=0;i<tx.unspentsUsed.length;i++)
      this.unspent = _.reject(this.unspentsUsed, function(u) { return u.hash == tx.unspentsUsed[i].hash })

    return tx.raw;
  };

  if(walletKey && walletId)
    this.createServerKey();
};
<commit_msg>remove debug messages<commit_after>coinpunk.Wallet = function(walletKey, walletId) {
  this.network = coinpunk.config.network || 'prod';
  this.walletKey = walletKey;
  this.walletId = walletId;
  this.defaultIterations = 1000;
  this.serverKey = undefined;
  this.transactions = [];
  this.unspent = [];
  this.minimumConfirmations = 1;
  this.unspentConfirmations = [];
  var keyPairs = [];

  this.loadPayloadWithLogin = function(id, password, payload) {
    this.createWalletKey(id, password);
    this.loadPayload(payload);
    return true;
  };

  this.loadPayload = function(encryptedJSON) {
    var payloadJSON = sjcl.decrypt(this.walletKey, encryptedJSON);
    this.payloadHash = this.computePayloadHash(payloadJSON);
    var payload = JSON.parse(payloadJSON);
    keyPairs = payload.keyPairs;
    this.transactions = payload.transactions || [];
    this.unspent = payload.unspent || [];
    return true;
  };

  this.mergePayload = function(wallet) {
    var payloadJSON = sjcl.decrypt(this.walletKey, wallet);
    var payload = JSON.parse(payloadJSON);

    keyPairs = _.uniq(_.union(payload.keyPairs, keyPairs), false, function(item, key, a) {
      return item.key;
    });

    this.transactions = _.uniq(_.union(payload.transactions, this.transactions), false, function(item, key, a) {
      return item.hash;
    });

    this.unspent = _.uniq(_.union(payload.unspent, this.unspent), false, function(item, key, a) {
      return item.hash;
    });

    this.payloadHash  = this.computePayloadHash(payloadJSON);

    return true;
  };

  this.createNewAddress = function(name, isChange) {
    var eckey      = new Bitcoin.ECKey();
    var newKeyPair = {
      key: eckey.getExportedPrivateKey(this.network),
      publicKey: Bitcoin.convert.bytesToHex(eckey.getPubKeyHash()),
      address: eckey.getBitcoinAddress(this.network).toString(),
      isChange: (isChange == true)
    };

    if(name)
      newKeyPair.name = name;

    keyPairs.push(newKeyPair);
    return newKeyPair.address;
  };

  this.removeAddress = function(address) {
    var i=0;
    for(i=0;i<keyPairs.length;i++)
      if(keyPairs[i].address == address)
        keyPairs.splice(i, 1)
  };

  this.getAddressName = function(address) {
    for(var i=0;i<keyPairs.length;i++)
      if(keyPairs[i].address == address)
        return keyPairs[i].name;
  };

  this.addresses = function() {
    var addrs = [];
    for(var i=0; i<keyPairs.length; i++) {
      addrs.push({address: keyPairs[i].address, name: keyPairs[i].name, isChange: keyPairs[i].isChange});
    }
    return addrs;
  };

  this.receiveAddresses = function() {
    var addrs = [];
    for(var i=0; i<keyPairs.length; i++) {
      if(keyPairs[i].isChange != true)
        addrs.push({address: keyPairs[i].address, name: keyPairs[i].name});
    }
    return addrs;
  };

  this.receiveAddressHashes = function() {
    var addrHashes = [];
    for(var i=0; i<keyPairs.length; i++) {
      if(keyPairs[i].isChange != true)
        addrHashes.push(keyPairs[i].address);
    }

    return addrHashes;
  };

  this.changeAddressHashes = function() {
    var addrHashes = [];
    for(var i=0; i<keyPairs.length; i++) {
      if(keyPairs[i].isChange == true)
        addrHashes.push(keyPairs[i].address);
    }

    return addrHashes;
  };

  this.addressHashes = function() {
    var addresses = this.addresses();
    var addressHashes = [];
    for(var i=0;i<addresses.length;i++)
      addressHashes.push(addresses[i].address);
    return addressHashes;
  }

  this.createServerKey = function() {
    this.serverKey = sjcl.codec.base64.fromBits(sjcl.misc.pbkdf2(this.walletKey, this.walletId, this.defaultIterations));
    return this.serverKey;
  };

  this.createWalletKey = function(id, password) {
    this.walletKey = sjcl.codec.base64.fromBits(sjcl.misc.pbkdf2(password, id, this.defaultIterations));
    this.walletId = id;
    this.createServerKey();
    return this.walletKey;
  };

  this.computePayloadHash = function(payloadJSON) {
    return sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(payloadJSON));
  };

  this.encryptPayload = function() {
    var payload = {keyPairs: keyPairs, transactions: this.transactions, unspent: this.unspent};
    var payloadJSON = JSON.stringify(payload);
    this.newPayloadHash = this.computePayloadHash(payloadJSON);
    return sjcl.encrypt(this.walletKey, payloadJSON);
  };

  this.mergeUnspent = function(newUnspent) {
    var changed = false;
    this.unspentConfirmations = this.unspentConfirmations || {};

    for(var i=0;i<newUnspent.length;i++) {
      var match = false;

      for(var j=0;j<this.unspent.length;j++) {
        if(this.unspent[j].hash == newUnspent[i].hash)
          match = true;
      }

      this.unspentConfirmations[newUnspent[i].hash] = newUnspent[i].confirmations;

      if(match == true)
        continue;

      changed = true;

      this.unspent.push({
        hash: newUnspent[i].hash,
        vout: newUnspent[i].vout,
        address: newUnspent[i].address,
        scriptPubKey: newUnspent[i].scriptPubKey,
        amount: newUnspent[i].amount
      });

      // todo: time should probably not be generated here

      var txMatch = false;

      for(var k=0;k<this.transactions.length;k++) {
        if(this.transactions[k].hash == newUnspent[i].hash)
          txMatch = true;
      }

      if(txMatch == false) {
        this.transactions.push({
          hash: newUnspent[i].hash,
          type: 'receive',
          address: newUnspent[i].address,
          amount: newUnspent[i].amount,
          time: new Date().getTime()
        });
      }
    }

    return changed;
  };

  this.getUnspent = function(confirmations) {
    var confirmations = confirmations || 0;
    var unspent = [];

    for(var i=0; i<this.unspent.length; i++)
      if(this.unspentConfirmations[this.unspent[i].hash] >= confirmations)
        unspent.push(this.unspent[i]);
    return unspent;
  };

  this.pendingUnspentBalance = function() {
    var unspent = this.getUnspent(0);
    var changeAddresses = this.changeAddressHashes();
    var balance = new BigNumber(0);

    for(var u=0;u<unspent.length;u++) {
      if(this.unspentConfirmations[unspent[u].hash] == 0 && _.contains(changeAddresses, unspent[u].address) == false)
        balance = balance.plus(unspent[u].amount);
    }
    return balance;
  };

  this.safeUnspentBalance = function() {
    var safeUnspent = this.safeUnspent();
    var amount = new BigNumber(0);
    for(var i=0;i<safeUnspent.length;i++)
      amount = amount.plus(safeUnspent[i].amount);
    return amount;
  };

  // Safe to spend unspent txs.
  this.safeUnspent = function() {
    var unspent = this.getUnspent();
    var changeAddresses = this.changeAddressHashes();
    var safeUnspent = [];
    for(var u=0;u<unspent.length;u++) {
      if(_.contains(changeAddresses, unspent[u].address) == true || this.unspentConfirmations[unspent[u].hash] >= this.minimumConfirmations)
        safeUnspent.push(unspent[u]);
    }

    return safeUnspent;
  };

  this.receivedAmountTotal = function() {
    var addresses = this.addresses();
    var amount = new BigNumber(0);

    for(var a=0;a<addresses.length;a++)
      amount = amount.plus(this.addressReceivedAmount(addresses[a]));

    return amount;
  }

  this.addressReceivedAmount = function(address) {
    var amount = new BigNumber(0.00);

    for(var t=0; t<this.transactions.length;t++)
      if(this.transactions[t].address == address)
        amount = amount.plus(this.transactions[t].amount);

    return amount;
  };

  this.createTx = function(amtString, feeString, addressString, changeAddress) {
    var amt = Bitcoin.util.parseValue(amtString);

    if(amt == Bitcoin.BigInteger.ZERO)
      throw "spend amount must be greater than zero";

    if(!changeAddress)
      throw "change address was not provided";

    var fee = Bitcoin.util.parseValue(feeString || '0');
    var total = Bitcoin.BigInteger.ZERO.add(amt).add(fee);

    var address = new Bitcoin.Address(addressString, this.network);
    var sendTx = new Bitcoin.Transaction();
    var i;

    var unspent = [];
    var unspentAmt = Bitcoin.BigInteger.ZERO;

    var safeUnspent = this.safeUnspent();

    for(i=0;i<safeUnspent.length;i++) {
      unspent.push(safeUnspent[i]);

      var amountSatoshiString = new BigNumber(safeUnspent[i].amount).times(Math.pow(10,8)).toString();

      unspentAmt = unspentAmt.add(new Bitcoin.BigInteger(amountSatoshiString));

      // If > -1, we have enough to send the requested amount
      if(unspentAmt.compareTo(total) > -1) {
        break;
      }
    }

    if(unspentAmt.compareTo(total) < 0) {
      throw "you do not have enough bitcoins to send this amount";
    }

    for(i=0;i<unspent.length;i++) {
      sendTx.addInput({hash: unspent[i].hash}, unspent[i].vout);
    }

    // The address you are sending to, and the amount:
    sendTx.addOutput(address, amt);

    var remainder = unspentAmt.subtract(total);

    if(!remainder.equals(Bitcoin.BigInteger.ZERO)) {
      sendTx.addOutput(changeAddress, remainder);
    }

    var hashType = 1; // SIGHASH_ALL

    // Here will be the beginning of your signing for loop

    for(i=0;i<unspent.length;i++) {
      var unspentOutScript = new Bitcoin.Script(Bitcoin.convert.hexToBytes(unspent[i].scriptPubKey));
      var hash = sendTx.hashTransactionForSignature(unspentOutScript, i, hashType);
      var pubKeyHash = unspentOutScript.simpleOutHash();
      var pubKeyHashHex = Bitcoin.convert.bytesToHex(pubKeyHash);

      for(var j=0;j<keyPairs.length;j++) {
        if(_.isEqual(keyPairs[j].publicKey, pubKeyHashHex)) {
          var key = new Bitcoin.Key(keyPairs[j].key);
          var signature = key.sign(hash);
          signature.push(parseInt(hashType, 10));

          sendTx.ins[i].script = Bitcoin.Script.createInputScript(signature, key.getPub());
          break;
        }
      }
    }

    return {unspentsUsed: unspent, obj: sendTx, raw: Bitcoin.convert.bytesToHex(sendTx.serialize())};
  };

  this.calculateFee = function(amtString, addressString, changeAddress) {
    var tx = this.createTx(amtString, 0, addressString, changeAddress);
    var txSize = tx.raw.length / 2;
    // console.log(txSize);
    return Math.ceil(txSize/1000)*0.0001;
  };

  this.createSend = function(amtString, feeString, addressString, changeAddress) {
    var tx = this.createTx(amtString, feeString, addressString, changeAddress);

    this.transactions.push({
      hash: Bitcoin.convert.bytesToHex(tx.obj.getHash()),
      type: 'send',
      address: addressString,
      amount: amtString,
      fee: feeString,
      time: new Date().getTime()
    });

    // Remove unspent elements now that we have a tx that uses them
    for(var i=0;i<tx.unspentsUsed.length;i++)
      this.unspent = _.reject(this.unspentsUsed, function(u) { return u.hash == tx.unspentsUsed[i].hash })

    return tx.raw;
  };

  if(walletKey && walletId)
    this.createServerKey();
};
<|endoftext|>


<commit_before>'use strict';

/**
 * This method initializes a web server with certificates if needed and returns a promise
 * @param app
 * @param settings
 * @param certificates
 * @param leSettings
 * @param log
 * @param adapter
 * @returns {Promise<unknown>}
 */
function createServerAsync(app, settings, certificates, leSettings, log, adapter) {
    return new Promise((resolve, reject) => {
        if (!settings.secure) {
            log.debug('Using http createServer');
            resolve(require('http').createServer(app));
        } else if (!settings.leEnabled) {
            log.debug('Using https createServer');
            resolve(require('https').createServer(certificates, app));
        } else {
            // prepare domains
            if (typeof leSettings.domains === 'string') {
                leSettings.domains = leSettings.domains.split(',').map(d => d.trim()).filter(d => d);
            }

            if (!leSettings || !leSettings.email || !Array.isArray(leSettings.domains) || !leSettings.domains.length) {
                reject(new Error('Please specify the email address and domains to use Let\'s Encrypt certificates!'));
            }

            const tools = require('./tools');
            const fs = require('fs');
            let leDir;

            let configPath = tools.getConfigFileName().replace(/\\/g, '/');
            const parts = configPath.split('/');
            parts.pop();
            configPath = parts.join('/');

            if (leSettings.path && (leSettings.path[0] === '/' || leSettings.path.match(/^[A-Za-z]:/))) {
                leDir = leSettings.path;
            } else {
                leDir = configPath + '/' + (leSettings.path || 'letsencrypt');
            }

            try {
                if (!fs.existsSync(leDir)) {
                    fs.mkdirSync(leDir);
                }
            } catch (err) {
                reject(new Error(`Lets encrypt Directory does not exist and can not be created as ${leDir}: ${err}`));
            }

            // TODO? Tried adding sites in the gl create but that didn't work so is below with gl.add.

            const pkg = require('../package.json');
            const glOpts = {
                packageRoot: __dirname,
                configDir: leDir,
                maintainerEmail: leSettings.email,
                cluster: false,
                packageAgent: pkg.name + '/' + pkg.version,
                notify: (event, details) => {
                    let severityFn;
                    switch (event) {
                        case 'warning':
                            severityFn = function (text, arg1, arg2) {
                                if (typeof text === 'object') {
                                    log.warn('[LE] ' + JSON.stringify(text) + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                } else {
                                    log.warn(text + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                }
                            };
                            break;
                        case 'error':
                            severityFn = function (text, arg1, arg2) {
                                if (typeof text === 'object') {
                                    log.error('[LE] ' + JSON.stringify(text) + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                } else {
                                    log.error(text + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                }
                            };
                            break;
                        default:
                            severityFn = function (text, arg1, arg2) {
                                if (typeof text === 'object') {
                                    log.debug('[LE] ' + JSON.stringify(text) + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                    if (text.status === 'valid' && text.altname) {
                                        log.info(`Received new certificate for ${text.altname} via ${text.type}`);
                                    } else if (text.renewAt) {
                                        log.info(`Certificate for ${text.subject} is valid till ${new Date(text.renewAt).toISOString()}`);
                                        adapter && adapter.sendToHost(adapter.host, 'certsUpdated', {validTill: text.renewAt, domain: text.subject, instance: adapter.namespace});
                                    }
                                } else {
                                    log.debug(text + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                }
                            };
                    }
                    severityFn(details);
                }
            };

            if (settings.leStaging) {
                log.debug('Greenlock staging enabled');
                glOpts.staging = true;
            }

            const gl = require('greenlock').create(glOpts);
            gl.manager.defaults({
                agreeToTerms: true,
                subscriberEmail: leSettings.email
            }).then(() => {
                // Add sites.
                // TODO: something seems fishy with the timing of this because on the first run
                // a warning about no sites being configured is found, even though things go on to
                // work perfectly.
                for (const domain of leSettings.domains) {
                    log.debug(`Adding to Greenlock: ${domain}`);
                    gl.add({ subject: domain, altnames: [domain] });
                }

                require('greenlock-express')
                    .init({
                        greenlock: gl
                    }).ready(glx => {
                        // The below is from greenlock-express examples/https/server.js

                        // Start the challenge server if configured
                        if (settings.leUpdate) {
                            const httpServer = glx.httpServer();
                            settings.lePort = parseInt(settings.lePort, 10) || 80;
                            const bind = (!settings.bind || settings.bind === '0.0.0.0') ? undefined : settings.bind || undefined;
                            httpServer.listen(settings.lePort, bind, () =>
                                log.info('Challenge server is started on ' + httpServer.address()));
                        }

                        // Don't call listen here because caller will do that
                        resolve(glx.httpsServer(null, app));
                    });
            }).catch(err => {
                reject(new Error(`Failed to set Greenlock manager defaults: ${err}`));
            });
        }
    });
}

/**
 * This method initializes a web server with certificates if needed. No Let's encrypt support anymore
 * @param app
 * @param settings
 * @param certificates
 * @param leSettings
 * @param log
 * @deprecated
 * @returns {Server}
 */
function createServer(app, settings, certificates, leSettings, log) {
    let server;

    if (settings.secure) {
        if (leSettings && settings.leEnabled) {
            log.info('Please update this adapter to the latest version to allow again to update your certificates.  Using the current certificates');
        }

        try {
            server = require('https').createServer(certificates, app);
        } catch (err) {
            log.error('HTTPS server could not be started: ' + err);
        }
    } else {
        server = require('http').createServer(app);
    }

    return server;
}

module.exports = {
    createServerAsync: createServerAsync,
    createServer: createServer
};<commit_msg>* adjust code a bit<commit_after>'use strict';

/**
 * This method initializes a web server with certificates if needed and returns a promise
 * @param app
 * @param settings
 * @param certificates
 * @param leSettings
 * @param log
 * @param adapter
 * @returns {Promise<unknown>}
 */
function createServerAsync(app, settings, certificates, leSettings, log, adapter) {
    return new Promise((resolve, reject) => {
        if (!settings.secure) {
            log.debug('Using http createServer');
            resolve(require('http').createServer(app));
        } else if (!settings.leEnabled) {
            log.debug('Using https createServer');
            resolve(require('https').createServer(certificates, app));
        } else {
            // prepare domains
            if (typeof leSettings.domains === 'string') {
                leSettings.domains = leSettings.domains.split(',').map(d => d.trim()).filter(d => d);
            }

            if (!leSettings || !leSettings.email || !Array.isArray(leSettings.domains) || !leSettings.domains.length) {
                reject(new Error('Please specify the email address and domains to use Let\'s Encrypt certificates!'));
            }

            const tools = require('./tools');
            const fs = require('fs');
            let leDir;

            let configPath = tools.getConfigFileName().replace(/\\/g, '/');
            const parts = configPath.split('/');
            parts.pop();
            configPath = parts.join('/');

            if (leSettings.path && (leSettings.path[0] === '/' || leSettings.path.match(/^[A-Za-z]:/))) {
                leDir = leSettings.path;
            } else {
                leDir = configPath + '/' + (leSettings.path || 'letsencrypt');
            }

            try {
                if (!fs.existsSync(leDir)) {
                    fs.mkdirSync(leDir);
                }
            } catch (err) {
                reject(new Error(`Lets encrypt Directory does not exist and can not be created as ${leDir}: ${err}`));
            }

            // TODO? Tried adding sites in the gl create but that didn't work so is below with gl.add.

            const pkg = require('../package.json');
            const glOpts = {
                packageRoot: __dirname,
                configDir: leDir,
                maintainerEmail: leSettings.email,
                cluster: false,
                packageAgent: pkg.name + '/' + pkg.version,
                notify: (event, details) => {
                    let severityFn;
                    switch (event) {
                        case 'warning':
                            severityFn = function (text, arg1, arg2) {
                                if (typeof text === 'object') {
                                    log.warn('[LE] ' + JSON.stringify(text) + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                } else {
                                    log.warn(text + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                }
                            };
                            break;
                        case 'error':
                            severityFn = function (text, arg1, arg2) {
                                if (typeof text === 'object') {
                                    log.error('[LE] ' + JSON.stringify(text) + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                } else {
                                    log.error(text + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                }
                            };
                            break;
                        default:
                            severityFn = function (text, arg1, arg2) {
                                if (typeof text === 'object') {
                                    log.debug('[LE] ' + JSON.stringify(text) + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                    if (text.status === 'valid' && text.altname) {
                                        log.info(`Received new certificate for ${text.altname} via ${text.type}`);
                                    } else if (text.renewAt) {
                                        log.info(`Certificate for ${text.subject} is valid till ${new Date(text.renewAt).toISOString()}`);
                                        adapter && adapter.sendToHost(adapter.host, 'certsUpdated', {validTill: text.renewAt, domain: text.subject, instance: adapter.namespace});
                                    }
                                } else {
                                    log.debug(text + (arg1 !== undefined ? ' ' + arg1 : '') + (arg2 !== undefined ? ' ' + arg2 : ''));
                                }
                            };
                    }
                    severityFn(details);
                }
            };

            if (settings.leStaging) {
                log.debug('Greenlock staging enabled');
                glOpts.staging = true;
            }

            const gl = require('greenlock').create(glOpts);
            gl.manager.defaults({
                agreeToTerms: true,
                subscriberEmail: leSettings.email
            }).then(() => {
                // Add sites.
                // TODO: something seems fishy with the timing of this because on the first run
                // a warning about no sites being configured is found, even though things go on to
                // work perfectly.
                for (const domain of leSettings.domains) {
                    log.debug(`Adding to Greenlock: ${domain}`);
                    gl.add({ subject: domain, altnames: [domain] });
                }

                require('greenlock-express')
                    .init({
                        greenlock: gl
                    }).ready(glx => {
                        // The below is from greenlock-express examples/https/server.js

                        // Start the challenge server if configured
                        if (settings.leUpdate) {
                            const httpServer = glx.httpServer();
                            settings.lePort = parseInt(settings.lePort, 10) || 80;
                            const bind = (!settings.bind || settings.bind === '0.0.0.0') ? undefined : settings.bind || undefined;
                            httpServer.listen(settings.lePort, bind, () =>
                                log.info('Challenge server is started on ' + httpServer.address()));
                        }

                        // Don't call listen here because caller will do that
                        resolve(glx.httpsServer(null, app));
                    });
            }).catch(err => {
                reject(new Error(`Failed to set Greenlock manager defaults: ${err}`));
            });
        }
    });
}

/**
 * This method initializes a web server with certificates if needed. No Let's encrypt support anymore
 * @param app
 * @param settings
 * @param certificates
 * @param leSettings
 * @param log
 * @deprecated
 * @returns {Server}
 */
function createServer(app, settings, certificates, leSettings, log) {
    let server;

    if (settings.secure) {
        if (leSettings && settings.leEnabled) {
            log.info('Please update this adapter to the latest version to allow again to update your certificates.  Using the current certificates');
        }

        try {
            server = require('https').createServer(certificates, app);
        } catch (err) {
            log.error('HTTPS server could not be started: ' + err);
        }
    } else {
        server = require('http').createServer(app);
    }

    return server;
}

module.exports = {
    createServerAsync,
    createServer
};<|endoftext|>


<commit_before>/*
Copyright (c) 2005-2010 Sam Stephenson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* Based on Alex Arnell's inheritance implementation. */
/** section: Language
 * class Class
 *
 *  Manages Prototype's class-based OOP system.
 *
 *  Refer to Prototype's web site for a [tutorial on classes and
 *  inheritance](http://prototypejs.org/learn/class-inheritance).
**/
(function(globalContext) {
/* ------------------------------------ */
/* Import from object.js                */
/* ------------------------------------ */
var _toString = Object.prototype.toString,
    NULL_TYPE = 'Null',
    UNDEFINED_TYPE = 'Undefined',
    BOOLEAN_TYPE = 'Boolean',
    NUMBER_TYPE = 'Number',
    STRING_TYPE = 'String',
    OBJECT_TYPE = 'Object',
    FUNCTION_CLASS = '[object Function]';
function isFunction(object) {
  return _toString.call(object) === FUNCTION_CLASS;
}
function extend(destination, source) {
  for (var property in source) if (source.hasOwnProperty(property)) // modify protect primitive slaughter
    destination[property] = source[property];
  return destination;
}
function keys(object) {
  if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); }
  var results = [];
  for (var property in object) {
    if (object.hasOwnProperty(property)) {
      results.push(property);
    }
  }
  return results;
}
function Type(o) {
  switch(o) {
    case null: return NULL_TYPE;
    case (void 0): return UNDEFINED_TYPE;
  }
  var type = typeof o;
  switch(type) {
    case 'boolean': return BOOLEAN_TYPE;
    case 'number':  return NUMBER_TYPE;
    case 'string':  return STRING_TYPE;
  }
  return OBJECT_TYPE;
}
function isUndefined(object) {
  return typeof object === "undefined";
}
/* ------------------------------------ */
/* Import from Function.js              */
/* ------------------------------------ */
var slice = Array.prototype.slice;
function argumentNames(fn) {
  var names = fn.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
    .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
    .replace(/\s+/g, '').split(',');
  return names.length == 1 && !names[0] ? [] : names;
}
function wrap(fn, wrapper) {
  var __method = fn;
  return function() {
    var a = update([bind(__method, this)], arguments);
    return wrapper.apply(this, a);
  };

}
function update(array, args) {
  var arrayLength = array.length, length = args.length;
  while (length--) array[arrayLength + length] = args[length];
  return array;
}
function merge(array, args) {
  array = slice.call(array, 0);
  return update(array, args);
}
function bind(fn, context) {
  if (arguments.length < 2 && isUndefined(arguments[0])) return this;
  var __method = fn, args = slice.call(arguments, 2);
  return function() {
    var a = merge(args, arguments);
    return __method.apply(context, a);
  };
}

/* ------------------------------------ */
/* Import from Prototype.js             */
/* ------------------------------------ */
var emptyFunction = function(){};

var Class = (function() {

  // Some versions of JScript fail to enumerate over properties, names of which
  // correspond to non-enumerable properties in the prototype chain
  var IS_DONTENUM_BUGGY = (function(){
    for (var p in { toString: 1 }) {
      // check actual property name, so that it works with augmented Object.prototype
      if (p === 'toString') return false;
    }
    return true;
  })();

  /**
   *  Class.create([superclass][, methods...]) -> Class
   *    - superclass (Class): The optional superclass to inherit methods from.
   *    - methods (Object): An object whose properties will be "mixed-in" to the
   *        new class. Any number of mixins can be added; later mixins take
   *        precedence.
   *
   *  [[Class.create]] creates a class and returns a constructor function for
   *  instances of the class. Calling the constructor function (typically as
   *  part of a `new` statement) will invoke the class's `initialize` method.
   *
   *  [[Class.create]] accepts two kinds of arguments. If the first argument is
   *  a [[Class]], it's used as the new class's superclass, and all its methods
   *  are inherited. Otherwise, any arguments passed are treated as objects,
   *  and their methods are copied over ("mixed in") as instance methods of the
   *  new class. In cases of method name overlap, later arguments take
   *  precedence over earlier arguments.
   *
   *  If a subclass overrides an instance method declared in a superclass, the
   *  subclass's method can still access the original method. To do so, declare
   *  the subclass's method as normal, but insert `$super` as the first
   *  argument. This makes `$super` available as a method for use within the
   *  function.
   *
   *  To extend a class after it has been defined, use [[Class#addMethods]].
   *
   *  For details, see the
   *  [inheritance tutorial](http://prototypejs.org/learn/class-inheritance)
   *  on the Prototype website.
  **/
  function subclass() {};
  function create() {
    var parent = null, properties = [].slice.apply(arguments);
    if (isFunction(properties[0]))
      parent = properties.shift();

    function klass() {
      this.initialize.apply(this, arguments);
    }

    extend(klass, Class.Methods);
    klass.superclass = parent;
    klass.subclasses = [];

    if (parent) {
      subclass.prototype = parent.prototype;
      klass.prototype = new subclass;
      parent.subclasses.push(klass);
    }

    for (var i = 0, length = properties.length; i < length; i++)
      klass.addMethods(properties[i]);

    if (!klass.prototype.initialize)
      klass.prototype.initialize = emptyFunction;

    klass.prototype.constructor = klass;
    return klass;
  }

  /**
   *  Class#addMethods(methods) -> Class
   *    - methods (Object): The methods to add to the class.
   *
   *  Adds methods to an existing class.
   *
   *  [[Class#addMethods]] is a method available on classes that have been
   *  defined with [[Class.create]]. It can be used to add new instance methods
   *  to that class, or overwrite existing methods, after the class has been
   *  defined.
   *
   *  New methods propagate down the inheritance chain. If the class has
   *  subclasses, those subclasses will receive the new methods — even in
   *  the context of `$super` calls. The new methods also propagate to instances
   *  of the class and of all its subclasses, even those that have already been
   *  instantiated.
   *
   *  ##### Examples
   *
   *      var Animal = Class.create({
   *        initialize: function(name, sound) {
   *          this.name  = name;
   *          this.sound = sound;
   *        },
   *
   *        speak: function() {
   *          alert(this.name + " says: " + this.sound + "!");
   *        }
   *      });
   *
   *      // subclassing Animal
   *      var Snake = Class.create(Animal, {
   *        initialize: function($super, name) {
   *          $super(name, 'hissssssssss');
   *        }
   *      });
   *
   *      var ringneck = new Snake("Ringneck");
   *      ringneck.speak();
   *
   *      //-> alerts "Ringneck says: hissssssss!"
   *
   *      // adding Snake#speak (with a supercall)
   *      Snake.addMethods({
   *        speak: function($super) {
   *          $super();
   *          alert("You should probably run. He looks really mad.");
   *        }
   *      });
   *
   *      ringneck.speak();
   *      //-> alerts "Ringneck says: hissssssss!"
   *      //-> alerts "You should probably run. He looks really mad."
   *
   *      // redefining Animal#speak
   *      Animal.addMethods({
   *        speak: function() {
   *          alert(this.name + 'snarls: ' + this.sound + '!');
   *        }
   *      });
   *
   *      ringneck.speak();
   *      //-> alerts "Ringneck snarls: hissssssss!"
   *      //-> alerts "You should probably run. He looks really mad."
  **/
  function addMethods(source) {
    var ancestor   = this.superclass && this.superclass.prototype,
        properties = keys(source);

    // IE6 doesn't enumerate `toString` and `valueOf` (among other built-in `Object.prototype`) properties,
    // Force copy if they're not Object.prototype ones.
    // Do not copy other Object.prototype.* for performance reasons
    if (IS_DONTENUM_BUGGY) {
      if (source.toString != Object.prototype.toString)
        properties.push("toString");
      if (source.valueOf != Object.prototype.valueOf)
        properties.push("valueOf");
    }

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && isFunction(value) &&
          argumentNames(value)[0] == "$super") {
        var method = value;
        value = wrap((function(m) {
          return function() { return ancestor[m].apply(this, arguments); };
        })(property), method);

        value.valueOf = bind(method.valueOf, method);
        value.toString = bind(method.toString, method);
      }
      this.prototype[property] = value;
    }

    return this;
  }

  // TEMP
  addPrivileged = function(scope, method, fn) {

    var temp = scope[method],
      useSuper = (argumentNames(fn)[0] == "$super") ? true : false;

    return function() {
      args = [].slice.call(arguments);
      if (useSuper) {
        args.unshift(temp);
      }
      if (temp) {
        fn.apply(scope, args);
      }
    };
  };
  // end TEMP

  return {
    create: create,
    Methods: {
      addMethods: addMethods,
      addPrivileged: addPrivileged
    }
  };
})();

if (globalContext.exports) {
  globalContext.exports.Class = Class;
}
else {
  globalContext.Class = Class;
}

if ( typeof module !== 'undefined' && module.exports ) {
  module.exports = Class;
}

})(this);<commit_msg>adding temporary support for priviledged methods via addPriviledged<commit_after>/*
Copyright (c) 2005-2010 Sam Stephenson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* Based on Alex Arnell's inheritance implementation. */
/** section: Language
 * class Class
 *
 *  Manages Prototype's class-based OOP system.
 *
 *  Refer to Prototype's web site for a [tutorial on classes and
 *  inheritance](http://prototypejs.org/learn/class-inheritance).
**/
(function(globalContext) {
/* ------------------------------------ */
/* Import from object.js                */
/* ------------------------------------ */
var _toString = Object.prototype.toString,
    NULL_TYPE = 'Null',
    UNDEFINED_TYPE = 'Undefined',
    BOOLEAN_TYPE = 'Boolean',
    NUMBER_TYPE = 'Number',
    STRING_TYPE = 'String',
    OBJECT_TYPE = 'Object',
    FUNCTION_CLASS = '[object Function]';
function isFunction(object) {
  return _toString.call(object) === FUNCTION_CLASS;
}
function extend(destination, source) {
  for (var property in source) if (source.hasOwnProperty(property)) // modify protect primitive slaughter
    destination[property] = source[property];
  return destination;
}
function keys(object) {
  if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); }
  var results = [];
  for (var property in object) {
    if (object.hasOwnProperty(property)) {
      results.push(property);
    }
  }
  return results;
}
function Type(o) {
  switch(o) {
    case null: return NULL_TYPE;
    case (void 0): return UNDEFINED_TYPE;
  }
  var type = typeof o;
  switch(type) {
    case 'boolean': return BOOLEAN_TYPE;
    case 'number':  return NUMBER_TYPE;
    case 'string':  return STRING_TYPE;
  }
  return OBJECT_TYPE;
}
function isUndefined(object) {
  return typeof object === "undefined";
}
/* ------------------------------------ */
/* Import from Function.js              */
/* ------------------------------------ */
var slice = Array.prototype.slice;
function argumentNames(fn) {
  var names = fn.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1]
    .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '')
    .replace(/\s+/g, '').split(',');
  return names.length == 1 && !names[0] ? [] : names;
}
function wrap(fn, wrapper) {
  var __method = fn;
  return function() {
    var a = update([bind(__method, this)], arguments);
    return wrapper.apply(this, a);
  };

}
function update(array, args) {
  var arrayLength = array.length, length = args.length;
  while (length--) array[arrayLength + length] = args[length];
  return array;
}
function merge(array, args) {
  array = slice.call(array, 0);
  return update(array, args);
}
function bind(fn, context) {
  if (arguments.length < 2 && isUndefined(arguments[0])) return this;
  var __method = fn, args = slice.call(arguments, 2);
  return function() {
    var a = merge(args, arguments);
    return __method.apply(context, a);
  };
}

/* ------------------------------------ */
/* Import from Prototype.js             */
/* ------------------------------------ */
var emptyFunction = function(){};

var Class = (function() {

  // Some versions of JScript fail to enumerate over properties, names of which
  // correspond to non-enumerable properties in the prototype chain
  var IS_DONTENUM_BUGGY = (function(){
    for (var p in { toString: 1 }) {
      // check actual property name, so that it works with augmented Object.prototype
      if (p === 'toString') return false;
    }
    return true;
  })();

  /**
   *  Class.create([superclass][, methods...]) -> Class
   *    - superclass (Class): The optional superclass to inherit methods from.
   *    - methods (Object): An object whose properties will be "mixed-in" to the
   *        new class. Any number of mixins can be added; later mixins take
   *        precedence.
   *
   *  [[Class.create]] creates a class and returns a constructor function for
   *  instances of the class. Calling the constructor function (typically as
   *  part of a `new` statement) will invoke the class's `initialize` method.
   *
   *  [[Class.create]] accepts two kinds of arguments. If the first argument is
   *  a [[Class]], it's used as the new class's superclass, and all its methods
   *  are inherited. Otherwise, any arguments passed are treated as objects,
   *  and their methods are copied over ("mixed in") as instance methods of the
   *  new class. In cases of method name overlap, later arguments take
   *  precedence over earlier arguments.
   *
   *  If a subclass overrides an instance method declared in a superclass, the
   *  subclass's method can still access the original method. To do so, declare
   *  the subclass's method as normal, but insert `$super` as the first
   *  argument. This makes `$super` available as a method for use within the
   *  function.
   *
   *  To extend a class after it has been defined, use [[Class#addMethods]].
   *
   *  For details, see the
   *  [inheritance tutorial](http://prototypejs.org/learn/class-inheritance)
   *  on the Prototype website.
  **/
  function subclass() {};
  function create() {
    var parent = null, properties = [].slice.apply(arguments);
    if (isFunction(properties[0]))
      parent = properties.shift();

    function klass() {
      this.initialize.apply(this, arguments);
    }

    extend(klass, Class.Methods);
    klass.superclass = parent;
    klass.subclasses = [];

    if (parent) {
      subclass.prototype = parent.prototype;
      klass.prototype = new subclass;
      parent.subclasses.push(klass);
    }

    for (var i = 0, length = properties.length; i < length; i++)
      klass.addMethods(properties[i]);

    if (!klass.prototype.initialize)
      klass.prototype.initialize = emptyFunction;

    klass.prototype.constructor = klass;
    return klass;
  }

  /**
   *  Class#addMethods(methods) -> Class
   *    - methods (Object): The methods to add to the class.
   *
   *  Adds methods to an existing class.
   *
   *  [[Class#addMethods]] is a method available on classes that have been
   *  defined with [[Class.create]]. It can be used to add new instance methods
   *  to that class, or overwrite existing methods, after the class has been
   *  defined.
   *
   *  New methods propagate down the inheritance chain. If the class has
   *  subclasses, those subclasses will receive the new methods — even in
   *  the context of `$super` calls. The new methods also propagate to instances
   *  of the class and of all its subclasses, even those that have already been
   *  instantiated.
   *
   *  ##### Examples
   *
   *      var Animal = Class.create({
   *        initialize: function(name, sound) {
   *          this.name  = name;
   *          this.sound = sound;
   *        },
   *
   *        speak: function() {
   *          alert(this.name + " says: " + this.sound + "!");
   *        }
   *      });
   *
   *      // subclassing Animal
   *      var Snake = Class.create(Animal, {
   *        initialize: function($super, name) {
   *          $super(name, 'hissssssssss');
   *        }
   *      });
   *
   *      var ringneck = new Snake("Ringneck");
   *      ringneck.speak();
   *
   *      //-> alerts "Ringneck says: hissssssss!"
   *
   *      // adding Snake#speak (with a supercall)
   *      Snake.addMethods({
   *        speak: function($super) {
   *          $super();
   *          alert("You should probably run. He looks really mad.");
   *        }
   *      });
   *
   *      ringneck.speak();
   *      //-> alerts "Ringneck says: hissssssss!"
   *      //-> alerts "You should probably run. He looks really mad."
   *
   *      // redefining Animal#speak
   *      Animal.addMethods({
   *        speak: function() {
   *          alert(this.name + 'snarls: ' + this.sound + '!');
   *        }
   *      });
   *
   *      ringneck.speak();
   *      //-> alerts "Ringneck snarls: hissssssss!"
   *      //-> alerts "You should probably run. He looks really mad."
  **/
  function addMethods(source) {
    var ancestor   = this.superclass && this.superclass.prototype,
        properties = keys(source);

    // IE6 doesn't enumerate `toString` and `valueOf` (among other built-in `Object.prototype`) properties,
    // Force copy if they're not Object.prototype ones.
    // Do not copy other Object.prototype.* for performance reasons
    if (IS_DONTENUM_BUGGY) {
      if (source.toString != Object.prototype.toString)
        properties.push("toString");
      if (source.valueOf != Object.prototype.valueOf)
        properties.push("valueOf");
    }

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && isFunction(value) &&
          argumentNames(value)[0] == "$super") {
        var method = value;
        value = wrap((function(m) {
          return function() { return ancestor[m].apply(this, arguments); };
        })(property), method);

        value.valueOf = bind(method.valueOf, method);
        value.toString = bind(method.toString, method);
      }
      this.prototype[property] = value;
    }

    return this;
  }

  // TEMP
  function addPrivileged (scope, method, fn) {

    var temp = scope[method],
      useSuper = (argumentNames(fn)[0] == "$super") ? true : false;

    return function() {
      args = [].slice.call(arguments);
      if (useSuper) {
        args.unshift(temp);
      }
      if (temp) {
        fn.apply(scope, args);
      }
    };
  };
  // end TEMP

  return {
    create: create,
    Methods: {
      addMethods: addMethods,
      addPrivileged: addPrivileged
    }
  };
})();

if (globalContext.exports) {
  globalContext.exports.Class = Class;
}
else {
  globalContext.Class = Class;
}

if ( typeof module !== 'undefined' && module.exports ) {
  module.exports = Class;
}

})(this);<|endoftext|>


<commit_before>"use strict";
let path = require("path");
let fs = require("fs-extra-async");

let newPath = ["bin", "node_modules/.bin"].map(subDir => path.join(__dirname, "..", subDir));

// windows用户，尝试把git目录下的bin目录写入环境变量的path中
if (process.platform === "win32") {
	["%ProgramFiles%/Git", "%ProgramFiles(x86)%/Git", "%USERPROFILE%/AppData/Local/Programs/Git", "%CMDER_ROOT%/vendor/git-for-windows"].some(dir => {
		dir = dir.replace(/%(.+?)%/g, (s, env) => {
			return process.env[env] || s;
		});
		try {
			fs.statSync(dir);
		} catch (ex) {
			return false;
		}
		newPath.push.apply(newPath, ["bin", "usr/bin", "usr/share/vim/vim74"].map(subDir => path.join(dir, subDir)));
		return true;
	});
}

let paths = process.env.Path.split(/\s*;\s*/);
newPath = newPath.filter(dir => paths.indexOf(dir) < 0);
process.env.Path = newPath.concat(paths).join(";");
<commit_msg>修复环境变量path写入在mac下报错<commit_after>"use strict";
if(process.env.PATH){
	let path = require("path");
	let fs = require("fs-extra-async");

	let newPath = ["bin", "node_modules/.bin"].map(subDir => path.join(__dirname, "..", subDir));
	let strSplit;
	// windows用户，尝试把git目录下的bin目录写入环境变量的path中
	if (process.platform === "win32") {
		["%ProgramFiles%/Git", "%ProgramFiles(x86)%/Git", "%USERPROFILE%/AppData/Local/Programs/Git", "%CMDER_ROOT%/vendor/git-for-windows"].some(dir => {
			dir = dir.replace(/%(.+?)%/g, (s, env) => {
				return process.env[env] || s;
			});
			try {
				fs.statSync(dir);
			} catch (ex) {
				return false;
			}
			newPath.push.apply(newPath, ["bin", "usr/bin", "usr/share/vim/vim74"].map(subDir => path.join(dir, subDir)));
			return true;
		});
		strSplit = ";";
	} else {
		strSplit = ":";
	}

	let paths = process.env.PATH.split(strSplit);
	newPath = newPath.filter(dir => paths.indexOf(dir) < 0);
	process.env.PATH = newPath.concat(paths).join(strSplit);
}
<|endoftext|>


<commit_before>"use strict";
angular.module('smartBusiness')
	.controller('SalesCtrl', ['$scope', 'SalesService', '$filter', SalesCtrl]);

function SalesCtrl ($scope, SalesService, $filter) {
    $scope.totalSell = 0;
    $scope.products = [];
	$scope.options = {
    	showWeeks: true,
    	maxDate: new Date(),
    	dateFormat: 'dd-MMMM-yyyy'
  	};

  	$scope.open1 = function() {
    	$scope.popup1.opened = true;
  	};

  	$scope.open2 = function() {
    	$scope.popup2.opened = true;
  	};

  	$scope.popup1 = {
  		opened: false
  	};

  	$scope.popup2 = {
  		opened: false
  	};

  	$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'shortDate'];
    $scope.format = $scope.formats[0];

	$scope.getSales = function () {
        $scope.totalSell = 0;
        $scope.products = [];
        $('.chart').empty();
        var query = {
            from: $filter('date')($scope.dateOne, 'yyyy-MM-d'),
            to: $filter('date')($scope.dateTwo, 'yyyy-MM-d')
        };

        SalesService.get(query).then(function(data) {
            if(data) {
                console.log(data);
                var totals = [];

                angular.forEach(data, function (value, key) {
                    var objGrap = {
                        total: value.total,
                        createdAt: value.createdAt
                    };
                    $scope.totalSell = $scope.totalSell + value.total;
                    // pass each product to the scope
                    angular.forEach(value.product, function (item, key) {
                        item.username = value.username;
                        $scope.products.push(item);
                    });
                    totals.push(objGrap);
                });
                graphicData(totals);
            }
        });
	};

    function graphicData(obj) {
        var totals = [];
        var cont = 0;
        angular.forEach(obj, function (value, key) {
            totals.push(value.total);
        });

        var data = totals;
        var x = d3.scale.linear()
            .domain([0, d3.max(data)])
            .range([0, 420]);

        d3.select(".chart")
            .selectAll("div")
            .data(data)
            .enter().append("div")
            .style("width", function(d) { return x(d) + "px"; })
            .text(function(d) {
                var text = 'Fecha de venta: ' + obj[cont].createdAt + ' Total de la venta: $ ' + d;
                cont++;
                return text
            });
    }
}	<commit_msg>Date error debuging<commit_after>"use strict";
angular.module('smartBusiness')
	.controller('SalesCtrl', ['$scope', 'SalesService', '$filter', SalesCtrl]);

function SalesCtrl ($scope, SalesService, $filter) {
    $scope.totalSell = 0;
    $scope.products = [];
	$scope.options = {
    	showWeeks: true,
    	maxDate: new Date(),
    	dateFormat: 'dd-MMMM-yyyy'
  	};

  	$scope.open1 = function() {
    	$scope.popup1.opened = true;
  	};

  	$scope.open2 = function() {
    	$scope.popup2.opened = true;
  	};

  	$scope.popup1 = {
  		opened: false
  	};

  	$scope.popup2 = {
  		opened: false
  	};

  	$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'shortDate'];
    $scope.format = $scope.formats[0];

	$scope.getSales = function () {
        $scope.totalSell = 0;
        $scope.products = [];
        $('.chart').empty();
        var query = {
            from: $filter('date')($scope.dateOne, 'yyyy-MM-dd'),
            to: $filter('date')($scope.dateTwo, 'yyyy-MM-dd')
        };
        SalesService.get(query).then(function(data) {
            if(data) {
                var totals = [];

                angular.forEach(data, function (value, key) {
                    var objGrap = {
                        total: value.total,
                        createdAt: value.createdAt
                    };
                    $scope.totalSell = $scope.totalSell + value.total;
                    // pass each product to the scope
                    angular.forEach(value.product, function (item, key) {
                        item.username = value.username;
                        $scope.products.push(item);
                    });
                    totals.push(objGrap);
                });
                graphicData(totals);
            }
        });
	};

    function graphicData(obj) {
        var totals = [];
        var cont = 0;
        angular.forEach(obj, function (value, key) {
            totals.push(value.total);
        });

        var data = totals;
        var x = d3.scale.linear()
            .domain([0, d3.max(data)])
            .range([0, 420]);

        d3.select(".chart")
            .selectAll("div")
            .data(data)
            .enter().append("div")
            .style("width", function(d) { return x(d) + "px"; })
            .text(function(d) {
                var text = 'Fecha de venta: ' + obj[cont].createdAt + ' Total de la venta: $ ' + d;
                cont++;
                return text
            });
    }
}	<|endoftext|>


<commit_before>var util = require('util')
  , Transform = require('stream').Transform
  , LF = '\n'.charCodeAt(0);

/**
 *  Reads stream buffers and writes arrays of lines.
 *
 *  Designed to be piped to another transform stream that
 *  operates on the array of lines.
 *
 *  ## Options
 *
 *  @param encoding The encoding to use when converting buffers to strings.
 */
function LineReader(options) {
  Transform.call(this);
  this._writableState.objectMode = false;
  this._readableState.objectMode = true;
  options = options || {};
  this.encoding = options.encoding || 'utf8';
  this.eol = /\r?\n/;
}

util.inherits(LineReader, Transform);

/**
 *  Transform function.
 */
function _transform(chunk, encoding, cb) {
  var str, lines, i = chunk.length - 1, b;

  if(this.buffer && this.buffer.length) {
    chunk = Buffer.concat(
      [this.buffer, chunk], this.buffer.length + chunk.length);
  }

  // end with line feed, safe to split the lot
  if(chunk[chunk.length - 1] === LF) {
    str = chunk.toString(this.encoding);
  }else{
    // reverse search for line feed
    while((b = chunk[i]) !== undefined) {
      if(b === LF) {
        // get what we can split now
        str = chunk.toString(this.encoding, 0, i);
        // stash the remainder for the next transform or flush
        this.buffer = chunk.slice(i);
        break;
      }
      i--;
    }
  }

  // no newline found, possibly very long line
  if(!str) {
    this.buffer = !this.buffer
      ? chunk
      : Buffer.concat([this.buffer, chunk], this.buffer.length + chunk.length);
    return cb();
  }

  lines = str.split(this.eol);
  this.push(lines);
  this.emit('lines', lines);
  cb();
}

function _flush() {
  var lines;
  // unterminated last line, need to flush it
  if(this.buffer) {
    lines = [this.buffer.toString(this.encoding)];
    this.push(lines);
    this.emit('lines', lines);
  }
  this.buffer = null;
}

LineReader.prototype._transform = _transform;
LineReader.prototype._flush = _flush;

module.exports = LineReader;
<commit_msg>Return instance on function call.<commit_after>var util = require('util')
  , Transform = require('stream').Transform
  , LF = '\n'.charCodeAt(0);

/**
 *  Reads stream buffers and writes arrays of lines.
 *
 *  Designed to be piped to another transform stream that
 *  operates on the array of lines.
 *
 *  ## Options
 *
 *  @param encoding The encoding to use when converting buffers to strings.
 */
function LineReader(options) {
  if(!(this instanceof LineReader)) {
    return new LineReader(options);
  }
  Transform.call(this);
  this._writableState.objectMode = false;
  this._readableState.objectMode = true;
  options = options || {};
  this.encoding = options.encoding || 'utf8';
  this.eol = /\r?\n/;
}

util.inherits(LineReader, Transform);

/**
 *  Transform function.
 */
function _transform(chunk, encoding, cb) {
  var str, lines, i = chunk.length - 1, b;

  if(this.buffer && this.buffer.length) {
    chunk = Buffer.concat(
      [this.buffer, chunk], this.buffer.length + chunk.length);
  }

  // end with line feed, safe to split the lot
  if(chunk[chunk.length - 1] === LF) {
    str = chunk.toString(this.encoding);
  }else{
    // reverse search for line feed
    while((b = chunk[i]) !== undefined) {
      if(b === LF) {
        // get what we can split now
        str = chunk.toString(this.encoding, 0, i);
        // stash the remainder for the next transform or flush
        this.buffer = chunk.slice(i);
        break;
      }
      i--;
    }
  }

  // no newline found, possibly very long line
  if(!str) {
    this.buffer = !this.buffer
      ? chunk
      : Buffer.concat([this.buffer, chunk], this.buffer.length + chunk.length);
    return cb();
  }

  lines = str.split(this.eol);
  this.push(lines);
  this.emit('lines', lines);
  cb();
}

function _flush() {
  var lines;
  // unterminated last line, need to flush it
  if(this.buffer) {
    lines = [this.buffer.toString(this.encoding)];
    this.push(lines);
    this.emit('lines', lines);
  }
  this.buffer = null;
}

LineReader.prototype._transform = _transform;
LineReader.prototype._flush = _flush;

module.exports = LineReader;
<|endoftext|>


<commit_before>var http = require('http');
var url = require('url');
var Scrapper = require('./scrapper.js');

function Server() {

  this.start = function() {
    http.createServer(function(request, response) {
      var urlParams = url.parse(request.url, true);
      if (request.method === 'GET' && urlParams.pathname === '/I/want/title/') {
        var addresses = (urlParams.query.address instanceof String) ? [urlParams.query.address] : urlParams.query.address;
        var titles = [];
        var body = [];

        function scrapTitle(index, callback) {
          new Scrapper(addresses[index], function(result){
            callback(result.url + " - " + result.dom('title').text(), index);
          }, function(error){
            callback(error.url + " - NO RESPONSE", index);
          });
        }

        function processTitle(title, index){
          titles.push(title);
          if(index < addresses.length - 1){
              scrapTitle(index + 1, processTitle);
          } else {
            response.statusCode = 200;
            response.write("");
            response.write("");
            response.write("");
            response.write("
");
            response.write(titles.map(function(title){ return "
" + title + "
"; }).join(' '));
            response.write("
");
            response.write("");
            response.write("");
            response.end();
          }
        }
        scrapTitle(0, processTitle);

      } else {
        response.statusCode = 404;
        response.end();
      }
    }).listen(8080);
  }
}

module.exports = Server;
<commit_msg>Fixed: Single address type check<commit_after>var http = require('http');
var url = require('url');
var Scrapper = require('./scrapper.js');

function Server() {

  this.start = function() {
    http.createServer(function(request, response) {
      var urlParams = url.parse(request.url, true);
      if (request.method === 'GET' && urlParams.pathname === '/I/want/title/') {
        var addresses = (typeof(urlParams.query.address) == 'string') ? [urlParams.query.address] : urlParams.query.address;
        var titles = [];
        var body = [];

        function scrapTitle(index, callback) {
          new Scrapper(addresses[index], function(result){
            callback(result.url + " - " + result.dom('title').text(), index);
          }, function(error){
            callback(error.url + " - NO RESPONSE", index);
          });
        }

        function processTitle(title, index){
          titles.push(title);
          if(index < addresses.length - 1){
              scrapTitle(index + 1, processTitle);
          } else {
            response.statusCode = 200;
            response.write("");
            response.write("");
            response.write("");
            response.write("
");
            response.write(titles.map(function(title){ return "
" + title + "
"; }).join(' '));
            response.write("
");
            response.write("");
            response.write("");
            response.end();
          }
        }
        scrapTitle(0, processTitle);

      } else {
        response.statusCode = 404;
        response.end();
      }
    }).listen(8080);
  }
}

module.exports = Server;
<|endoftext|>


<commit_before>"use strict";
var fs            = require("fs"),
    path          = require("path"),
    child_process = require("child_process"),
    Module        = require("module");

var protobuf = require("..");

function basenameCompare(a, b) {
    var aa = String(a).replace(/\.\w+$/, "").split(/(-?\d*\.?\d+)/g),
        bb = String(b).replace(/\.\w+$/, "").split(/(-?\d*\.?\d+)/g);
    for (var i = 0, k = Math.min(aa.length, bb.length); i < k; i++) {
        var x = parseFloat(aa[i]) || aa[i].toLowerCase(),
            y = parseFloat(bb[i]) || bb[i].toLowerCase();
        if (x < y)
            return -1;
        if (x > y)
            return 1;
    }
    return a.length < b.length ? -1 : 0;
};

exports.requireAll = function requireAll(dirname) {
    dirname   = path.join(__dirname, dirname);
    var files = fs.readdirSync(dirname).sort(basenameCompare),
        all = {};
    files.forEach(function(file) {
        var basename = path.basename(file, ".js"),
            extname  = path.extname(file);
        if (extname === ".js")
            all[basename] = require(path.join(dirname, file));
    });
    return all;
};

exports.inspect = function inspect(object, indent) {
    if (!object)
        return "";
    var chalk = require("chalk");
    var sb = [];
    if (!indent)
        indent = "";
    var ind = indent ? indent.substring(0, indent.length - 2) + "└ " : "";
    sb.push(
        ind + chalk.bold(object.toString()) + (object.visible ? " (visible)" : ""),
        indent + chalk.gray("parent: ") + object.parent
    );
    if (object instanceof protobuf.Field) {
        if (object.extend !== undefined)
            sb.push(indent + chalk.gray("extend: ") + object.extend);
        if (object.partOf)
            sb.push(indent + chalk.gray("oneof : ") + object.oneof);
    }
    sb.push("");
    if (object.fieldsArray)
        object.fieldsArray.forEach(function(field) {
            sb.push(inspect(field, indent + "  "));
        });
    if (object.oneofsArray)
        object.oneofsArray.forEach(function(oneof) {
            sb.push(inspect(oneof, indent + "  "));
        });
    if (object.methodsArray)
        object.methodsArray.forEach(function(service) {
            sb.push(inspect(service, indent + "  "));
        });
    if (object.nestedArray)
        object.nestedArray.forEach(function(nested) {
            sb.push(inspect(nested, indent + "  "));
        });
    return sb.join("\n");
};

exports.setup = function() {
    // this one is important. without it, this folder won't be searched anymore.
    try { fs.mkdirSync(path.join(__dirname, "node_modules")); } catch (e) {}

    // find out which modules are missing
    var pkg = require(path.join(__dirname, "..", "package.json"));
    var install = [];
    pkg.cliDependencies.forEach(function(name) {
        try {
            require.resolve(name + "/package.json"); // jsdoc has no main file
        } catch (e) {
            var version = pkg.dependencies[name] || pkg.devDependencies[name];
            install.push(version ? name + "@" + version : name);
        }
    });
    if (!install.length) {
        try { fs.rmdirSync(path.join(__dirname, "node_modules")); } catch (e) {}
        return;
    }

    // if any are missing, install them. this relies on an empty package.json in cli/.
    process.stderr.write("installing CLI dependencies: " + install.join(", ") + "\n");
    child_process.execSync("npm --silent install " + install.join(" "), {
        cwd: __dirname,
        stdio: "ignore"
    });
};

exports.wrap = function(OUTPUT, options) {
    var name = options.wrap || "default";
    var wrap;
    try {
        // try built-in wrappers first
        wrap = fs.readFileSync(path.join(__dirname, "wrappers", name + ".js")).toString("utf8");
    } catch (e) {
        // otherwise fetch the custom one
        wrap = fs.readFileSync(path.resolve(process.cwd(), name)).toString("utf8");
    }
    wrap = wrap.replace(/%ROOT%/g, JSON.stringify(options.root || "default"));
    wrap = wrap.replace(/%DEPENDENCY%/g, JSON.stringify(options.dependency || "protobufjs"));
    wrap = wrap.replace(/( *)%OUTPUT%/, function($0, $1) {
        return $1.length ? OUTPUT.replace(/^/mg, $1) : OUTPUT;
    });
    if (options.lint !== "")
        wrap = "/*" + options.lint + "*/\n" + wrap;
    return wrap.replace(/\r?\n/, "\n");
};

exports.pad = function(str, len, l) {
    while (str.length < len)
        str = l ? str + " " : " " + str;
    return str;
};

exports.reserved = function(name) {
    return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);
};
<commit_msg>CLI: Use semver to validate that CLI dependencies actually satisfy the required version, see #637<commit_after>"use strict";
var fs            = require("fs"),
    path          = require("path"),
    child_process = require("child_process"),
    Module        = require("module");

var protobuf = require("..");

function basenameCompare(a, b) {
    var aa = String(a).replace(/\.\w+$/, "").split(/(-?\d*\.?\d+)/g),
        bb = String(b).replace(/\.\w+$/, "").split(/(-?\d*\.?\d+)/g);
    for (var i = 0, k = Math.min(aa.length, bb.length); i < k; i++) {
        var x = parseFloat(aa[i]) || aa[i].toLowerCase(),
            y = parseFloat(bb[i]) || bb[i].toLowerCase();
        if (x < y)
            return -1;
        if (x > y)
            return 1;
    }
    return a.length < b.length ? -1 : 0;
};

exports.requireAll = function requireAll(dirname) {
    dirname   = path.join(__dirname, dirname);
    var files = fs.readdirSync(dirname).sort(basenameCompare),
        all = {};
    files.forEach(function(file) {
        var basename = path.basename(file, ".js"),
            extname  = path.extname(file);
        if (extname === ".js")
            all[basename] = require(path.join(dirname, file));
    });
    return all;
};

exports.inspect = function inspect(object, indent) {
    if (!object)
        return "";
    var chalk = require("chalk");
    var sb = [];
    if (!indent)
        indent = "";
    var ind = indent ? indent.substring(0, indent.length - 2) + "└ " : "";
    sb.push(
        ind + chalk.bold(object.toString()) + (object.visible ? " (visible)" : ""),
        indent + chalk.gray("parent: ") + object.parent
    );
    if (object instanceof protobuf.Field) {
        if (object.extend !== undefined)
            sb.push(indent + chalk.gray("extend: ") + object.extend);
        if (object.partOf)
            sb.push(indent + chalk.gray("oneof : ") + object.oneof);
    }
    sb.push("");
    if (object.fieldsArray)
        object.fieldsArray.forEach(function(field) {
            sb.push(inspect(field, indent + "  "));
        });
    if (object.oneofsArray)
        object.oneofsArray.forEach(function(oneof) {
            sb.push(inspect(oneof, indent + "  "));
        });
    if (object.methodsArray)
        object.methodsArray.forEach(function(service) {
            sb.push(inspect(service, indent + "  "));
        });
    if (object.nestedArray)
        object.nestedArray.forEach(function(nested) {
            sb.push(inspect(nested, indent + "  "));
        });
    return sb.join("\n");
};

exports.setup = function() {
    // this one is important. without it, this folder won't be searched anymore.
    try { fs.mkdirSync(path.join(__dirname, "node_modules")); } catch (e) {}

    // find out which modules are missing
    var pkg = require(path.join(__dirname, "..", "package.json"));
    var install = [];
    var semver;
    pkg.cliDependencies.forEach(function(name) {
        var version = pkg.dependencies[name] || pkg.devDependencies[name];
        try {
            var mPath = require.resolve(name + "/package.json"); // jsdoc has no main file
            var mPkg  = JSON.parse(fs.readFileSync(mPath));
            if (semver && !semver.satisfies(mPkg.version, version))
                throw Error(mPkg.version + " is outdated");
        } catch (e) {
            process.stderr.write("installing " + name + "@" + version + " (" + e.message + ")\n");
            install.push(version ? name + "@" + version : name);
        }
        if (name === "semver")
            semver = require("semver");
    });
    if (!install.length) {
        try { fs.rmdirSync(path.join(__dirname, "node_modules")); } catch (e) {}
        return;
    }

    // if any are missing, install them. this relies on an empty package.json in cli/.
    child_process.execSync("npm --silent install " + install.join(" "), {
        cwd: __dirname,
        stdio: "ignore"
    });
};

exports.wrap = function(OUTPUT, options) {
    var name = options.wrap || "default";
    var wrap;
    try {
        // try built-in wrappers first
        wrap = fs.readFileSync(path.join(__dirname, "wrappers", name + ".js")).toString("utf8");
    } catch (e) {
        // otherwise fetch the custom one
        wrap = fs.readFileSync(path.resolve(process.cwd(), name)).toString("utf8");
    }
    wrap = wrap.replace(/%ROOT%/g, JSON.stringify(options.root || "default"));
    wrap = wrap.replace(/%DEPENDENCY%/g, JSON.stringify(options.dependency || "protobufjs"));
    wrap = wrap.replace(/( *)%OUTPUT%/, function($0, $1) {
        return $1.length ? OUTPUT.replace(/^/mg, $1) : OUTPUT;
    });
    if (options.lint !== "")
        wrap = "/*" + options.lint + "*/\n" + wrap;
    return wrap.replace(/\r?\n/, "\n");
};

exports.pad = function(str, len, l) {
    while (str.length < len)
        str = l ? str + " " : " " + str;
    return str;
};

exports.reserved = function(name) {
    return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);
};
<|endoftext|>