<commit_before>(function($) {
    DjangoMapWidgetBase = $.Class.extend({

        init: function(options){
            $.extend(this, options);
            this.coordinatesOverlayToggleBtn.on("click", this.toggleCoordinatesOverlay.bind(this));
            this.coordinatesOverlayDoneBtn.on("click", this.handleCoordinatesOverlayDoneBtnClick.bind(this));
            this.coordinatesOverlayInputs.on("change", this.handleCoordinatesInputsChange.bind(this));
            this.addMarkerBtn.on("click", this.handleAddMarkerBtnClick.bind(this));
            this.myLocationBtn.on("click", this.handleMyLocationBtnClick.bind(this));
            this.deleteBtn.on("click", this.deleteMarker.bind(this));
            console.log(this.AutocompleteOptions);
            var autocomplete = new google.maps.places.Autocomplete(this.addressAutoCompleteInput, this.AutocompleteOptions);
            google.maps.event.addListener(autocomplete, 'place_changed', this.handleAutoCompletePlaceChange.bind(this, autocomplete));
            google.maps.event.addDomListener(this.addressAutoCompleteInput, 'keydown', this.handleAutoCompleteInputKeyDown.bind(this));
            this.initializeMap();
        },

        initializeMap: function(){
            console.warn("Implement initializeMap method.");
        },

        updateMap: function(lat, lng){
            console.warn("Implement updateMap method.");
        },

        addMarkerToMap: function(lat, lng){
            console.warn("Implement this method for your map js library.");
        },

        fitBoundMarker: function(){
            console.warn("Implement this method for your map js library.");
        },

        removeMarker: function(){
            console.warn("Implement this method for your map js library.");
        },

        dragMarker: function(e){
            console.warn("Implement dragMarker method.");
        },

        handleMapClick: function(e){
            console.warn("Implement handleMapClick method.");
        },

        handleAddMarkerBtnClick: function(e){
            console.warn("Implement handleAddMarkerBtnClick method.");
        },

        getLocationValues: function(){
            var latlng = this.locationInput.val().split(' ');
            var lat = latlng[2].replace(/[\(\)]/g, '');
            var lng = latlng[1].replace(/[\(\)]/g, '');
            return {
                "lat": lat,
                "lng": lng
            }
        },

        updateLocationInput: function(lat, lng){
            this.showOverlay();
            var location_input_val = "POINT (" + lng + " " + lat + ")";
            this.locationInput.val(location_input_val);
            this.updateCoordinatesInputs(lat, lng);
            this.addMarkerToMap(lat, lng);
            if ($.isEmptyObject(this.locationFieldValue)){
                $(document).trigger(this.markerCreateTriggerNameSpace,
                    [lat, lng, this.wrapElemSelector, this.locationInput]
                );
            }else{
                $(document).trigger(this.markerChangeTriggerNameSpace,
                    [lat, lng, this.wrapElemSelector, this.locationInput]
                );
            }

            this.locationFieldValue = {
                "lng": lng,
                "lat": lat
            };
            this.deleteBtn.removeClass("btn-default disabled").addClass("btn-danger");
            this.hideOverlay();
        },

        deleteMarker: function(){
            if (!$.isEmptyObject(this.locationFieldValue)) {
                console.log(this.locationFieldValue);
                this.hideOverlay();
                this.locationInput.val("");
                this.coordinatesOverlayInputs.val("");
                this.removeMarker();
                this.deleteBtn.removeClass("btn-danger").addClass("btn-default disabled");
                $(document).trigger(this.markerDeleteTriggerNameSpace,
                    [
                        this.locationFieldValue.lat,
                        this.locationFieldValue.lng,
                        this.wrapElemSelector,
                        this.locationInput
                    ]
                );
                this.locationFieldValue = null;
            }
        },

        toggleCoordinatesOverlay: function(){
            this.coordinatesOverlayToggleBtn.toggleClass("active");
            $(".mw-coordinates-overlay", this.wrapElemSelector).toggleClass("hide");
        },

        updateCoordinatesInputs: function(lat, lng){
            $(".mw-overlay-latitude", this.wrapElemSelector).val(lat || "");
            $(".mw-overlay-longitude", this.wrapElemSelector).val(lng || "");
        },

        handleCoordinatesInputsChange: function (e) {
            var lat = $(".mw-overlay-latitude", this.wrapElemSelector).val();
            var lng = $(".mw-overlay-longitude", this.wrapElemSelector).val();
            if (lat && lng){
                this.updateLocationInput(lat, lng);
                this.fitBoundMarker();
            }
        },

        handleCoordinatesOverlayDoneBtnClick: function(){
            $(".mw-coordinates-overlay", this.wrapElemSelector).addClass("hide");
        },

        handleMyLocationBtnClick: function(){
            this.showOverlay();
            if(navigator.geolocation){
                navigator.geolocation.getCurrentPosition(
                    this.handleCurrentPosition.bind(this),
                    this.handlecurrentPositionError.bind(this)
                );
            }else{
                this.handlecurrentPositionError();
            }
        },

        handleCurrentPosition: function(location){
            this.updateLocationInput(location.coords.latitude, location.coords.longitude);
            this.fitBoundMarker();
        },

        handlecurrentPositionError: function(){
            this.hideOverlay();
            alert("Your location could not be found.");
        },

        handleAutoCompleteInputKeyDown: function (e) {
            if (e.keyCode == 13){  // pressed enter key
                e.preventDefault();
            }
        },

        handleAutoCompletePlaceChange: function (autocomplete) {
            var place = autocomplete.getPlace();
            var lat = place.geometry.location.lat();
            var lng = place.geometry.location.lng();
            this.updateLocationInput(lat, lng);
            this.fitBoundMarker()
        },

        showOverlay: function(){
            this.loaderOverlayElem.removeClass("hide")
        },

        hideOverlay: function(){
            this.loaderOverlayElem.addClass("hide")
        }
    });

})(jQuery || django.jQuery);<commit_msg>added setting to add AutocompleteOptions to GooglePointFieldWidget autocomplete<commit_after>(function($) {
    DjangoMapWidgetBase = $.Class.extend({

        init: function(options){
            $.extend(this, options);
            this.coordinatesOverlayToggleBtn.on("click", this.toggleCoordinatesOverlay.bind(this));
            this.coordinatesOverlayDoneBtn.on("click", this.handleCoordinatesOverlayDoneBtnClick.bind(this));
            this.coordinatesOverlayInputs.on("change", this.handleCoordinatesInputsChange.bind(this));
            this.addMarkerBtn.on("click", this.handleAddMarkerBtnClick.bind(this));
            this.myLocationBtn.on("click", this.handleMyLocationBtnClick.bind(this));
            this.deleteBtn.on("click", this.deleteMarker.bind(this));
            var autocomplete = new google.maps.places.Autocomplete(this.addressAutoCompleteInput, this.AutocompleteOptions);
            google.maps.event.addListener(autocomplete, 'place_changed', this.handleAutoCompletePlaceChange.bind(this, autocomplete));
            google.maps.event.addDomListener(this.addressAutoCompleteInput, 'keydown', this.handleAutoCompleteInputKeyDown.bind(this));
            this.initializeMap();
        },

        initializeMap: function(){
            console.warn("Implement initializeMap method.");
        },

        updateMap: function(lat, lng){
            console.warn("Implement updateMap method.");
        },

        addMarkerToMap: function(lat, lng){
            console.warn("Implement this method for your map js library.");
        },

        fitBoundMarker: function(){
            console.warn("Implement this method for your map js library.");
        },

        removeMarker: function(){
            console.warn("Implement this method for your map js library.");
        },

        dragMarker: function(e){
            console.warn("Implement dragMarker method.");
        },

        handleMapClick: function(e){
            console.warn("Implement handleMapClick method.");
        },

        handleAddMarkerBtnClick: function(e){
            console.warn("Implement handleAddMarkerBtnClick method.");
        },

        getLocationValues: function(){
            var latlng = this.locationInput.val().split(' ');
            var lat = latlng[2].replace(/[\(\)]/g, '');
            var lng = latlng[1].replace(/[\(\)]/g, '');
            return {
                "lat": lat,
                "lng": lng
            }
        },

        updateLocationInput: function(lat, lng){
            this.showOverlay();
            var location_input_val = "POINT (" + lng + " " + lat + ")";
            this.locationInput.val(location_input_val);
            this.updateCoordinatesInputs(lat, lng);
            this.addMarkerToMap(lat, lng);
            if ($.isEmptyObject(this.locationFieldValue)){
                $(document).trigger(this.markerCreateTriggerNameSpace,
                    [lat, lng, this.wrapElemSelector, this.locationInput]
                );
            }else{
                $(document).trigger(this.markerChangeTriggerNameSpace,
                    [lat, lng, this.wrapElemSelector, this.locationInput]
                );
            }

            this.locationFieldValue = {
                "lng": lng,
                "lat": lat
            };
            this.deleteBtn.removeClass("btn-default disabled").addClass("btn-danger");
            this.hideOverlay();
        },

        deleteMarker: function(){
            if (!$.isEmptyObject(this.locationFieldValue)) {
                console.log(this.locationFieldValue);
                this.hideOverlay();
                this.locationInput.val("");
                this.coordinatesOverlayInputs.val("");
                this.removeMarker();
                this.deleteBtn.removeClass("btn-danger").addClass("btn-default disabled");
                $(document).trigger(this.markerDeleteTriggerNameSpace,
                    [
                        this.locationFieldValue.lat,
                        this.locationFieldValue.lng,
                        this.wrapElemSelector,
                        this.locationInput
                    ]
                );
                this.locationFieldValue = null;
            }
        },

        toggleCoordinatesOverlay: function(){
            this.coordinatesOverlayToggleBtn.toggleClass("active");
            $(".mw-coordinates-overlay", this.wrapElemSelector).toggleClass("hide");
        },

        updateCoordinatesInputs: function(lat, lng){
            $(".mw-overlay-latitude", this.wrapElemSelector).val(lat || "");
            $(".mw-overlay-longitude", this.wrapElemSelector).val(lng || "");
        },

        handleCoordinatesInputsChange: function (e) {
            var lat = $(".mw-overlay-latitude", this.wrapElemSelector).val();
            var lng = $(".mw-overlay-longitude", this.wrapElemSelector).val();
            if (lat && lng){
                this.updateLocationInput(lat, lng);
                this.fitBoundMarker();
            }
        },

        handleCoordinatesOverlayDoneBtnClick: function(){
            $(".mw-coordinates-overlay", this.wrapElemSelector).addClass("hide");
        },

        handleMyLocationBtnClick: function(){
            this.showOverlay();
            if(navigator.geolocation){
                navigator.geolocation.getCurrentPosition(
                    this.handleCurrentPosition.bind(this),
                    this.handlecurrentPositionError.bind(this)
                );
            }else{
                this.handlecurrentPositionError();
            }
        },

        handleCurrentPosition: function(location){
            this.updateLocationInput(location.coords.latitude, location.coords.longitude);
            this.fitBoundMarker();
        },

        handlecurrentPositionError: function(){
            this.hideOverlay();
            alert("Your location could not be found.");
        },

        handleAutoCompleteInputKeyDown: function (e) {
            if (e.keyCode == 13){  // pressed enter key
                e.preventDefault();
            }
        },

        handleAutoCompletePlaceChange: function (autocomplete) {
            var place = autocomplete.getPlace();
            var lat = place.geometry.location.lat();
            var lng = place.geometry.location.lng();
            this.updateLocationInput(lat, lng);
            this.fitBoundMarker()
        },

        showOverlay: function(){
            this.loaderOverlayElem.removeClass("hide")
        },

        hideOverlay: function(){
            this.loaderOverlayElem.addClass("hide")
        }
    });

})(jQuery || django.jQuery);<|endoftext|>


<commit_before>import React, {PropTypes} from 'react';

import{
  Image,
  Text,
  View,
  StyleSheet,
}from 'react-native';

import * as NavigationState from '../../modules/navigation/NavigationState';

const MapView = React.createClass({
  PropTypes: {
    dispatch: PropTypes.func.isRequired
  },
  popRoute(){
    this.props.dispatch(NavigationState.popRoute({
      key:'CounterView',
    }));
  },

  getInitialState(){
    return{
      background: '#ed746a'
    };
  },

  render(){
    const text = 'kartta';

    return(
      <View style={[styles.MapContainer]}>

      <Image
        style={[styles.MapImage]}
        source={require('../../../images/HHkartta.png')}
      />

      </View>
    );
  }
});

const styles = StyleSheet.create({

  MapContainer: {

  },

  MapImage: {

  },

});
export default MapView;
<commit_msg>GANGSTARAPPERMADEMEDOTHIS<commit_after>import React, {PropTypes, Dimensions} from 'react';

import{
  Image,
  Text,
  View,
  StyleSheet,
}from 'react-native';

import * as NavigationState from '../../modules/navigation/NavigationState';

const MapView = React.createClass({
  PropTypes: {
    dispatch: PropTypes.func.isRequired
  },
  popRoute(){
    this.props.dispatch(NavigationState.popRoute({
      key:'CounterView',
    }));
  },

  getInitialState(){
    return{
      background: '#ed746a'
    };
  },

  render(){
    const text = 'kartta';

    return(
      <View style={styles.MapContainer}>

      <Image
        style={styles.MapImage}
        source={require('../../../images/HHkartta.png')}
      />

      </View>
    );
  }
});

const styles = StyleSheet.create({

  MapContainer: {
    flex: 1,
     justifyContent: 'center',
     backgroundColor: '#F5FCFF',
     position: 'relative',
     height: undefined,
     width: undefined,

  },

  MapImage: {
    height: 290,
    width: undefined,

  },

});
export default MapView;
<|endoftext|>


<commit_before>'use strict';

var Worker = require('worker-loader?inline&fallback=false!./worker.js');
var worker = new Worker()

var auth = require('./auth')
var utils = require('./utils')
var walletDb = require('./db')
var emitter = require('lib/emitter')
var crypto = require('crypto')
var AES = require('lib/aes')
var denomination = require('lib/denomination')
var CsWallet = require('cs-wallet')
var validateSend = require('./validator')
var rng = require('secure-random').randomBuffer
var bitcoin = CsWallet.bitcoin
var request = require('lib/request')
var EthereumWallet = require('cs-ethereum-wallet');
var RippleWallet = require('cs-ripple-wallet');
var StellarWallet = require('cs-stellar-wallet');
var EOSWallet = require('cs-eos-wallet');
var convert = require('lib/convert');
var getToken = require('lib/token').getToken;
var setToken = require('lib/token').setToken;
var db = require('lib/db');
var _ = require('lodash');
var HDKey = require('hdkey');
var Buffer = require('safe-buffer').Buffer;
var bchaddr = require('bchaddrjs');

var wallet = null
var seed = null
var mnemonic = null
var id = null
var availableTouchId = false

var Wallet = {
  bitcoin: CsWallet,
  bitcoincash: CsWallet,
  bitcoinsv: CsWallet,
  litecoin: CsWallet,
  ethereum: EthereumWallet,
  ripple: RippleWallet,
  stellar: StellarWallet,
  eos: EOSWallet,
  dogecoin: CsWallet,
  dash: CsWallet
}

var urlRoot = window.urlRoot

function createWallet(passphrase, network, callback) {
  var data = {passphrase: passphrase}
  if(!passphrase){
   data.entropy = rng(128 / 8).toString('hex')
  }

  worker.onmessage = function(e) {
    assignSeedAndId(e.data.seed)

    mnemonic = e.data.mnemonic
    auth.exist(id, function(err, userExists){
      if(err) return callback(err);

      callback(null, {userExists: userExists, mnemonic: mnemonic})
    })
  }

  worker.onerror = function(e) {
    return callback({message: e.message.split(': ')[1]})
  }

  worker.postMessage(data)
}

function callbackError(err, callbacks) {
  callbacks.forEach(function (callback) {
    if (!callback) return;
    return callback(err);
  });
}

function setPin(pin, network, done, txSyncDone) {
  var callbacks = [done, txSyncDone]
  auth.register(id, pin, function(err, token) {
    if (err) return callbackError(err, callbacks);

    savePin(pin);
    walletDb.saveEncrypedSeed(id, AES.encrypt(seed, token));

    emitter.emit('wallet-opening', 'Synchronizing Wallet');
    emitter.emit('db-init');

    emitter.once('db-ready', function(err) {
      if (err) return callbackError(err, callbacks);
      initWallet(network, done, txSyncDone);
    });
  })
}

function removeAccount(callback) {
  auth.remove(id, callback);
}

function setUsername(username, callback) {
  auth.setUsername(id, username, callback);
}

function openWalletWithPin(pin, network, done, txSyncDone) {
  var callbacks = [done, txSyncDone]
  var credentials = walletDb.getCredentials();
  var id = credentials.id
  var encryptedSeed = credentials.seed
  auth.login(id, pin, function(err, token) {
    if (err) {
      if (err.message === 'user_deleted') {
        walletDb.deleteCredentials();
      }
      return callbackError(err, callbacks);
    }

    savePin(pin)
    assignSeedAndId(AES.decrypt(encryptedSeed, token));

    emitter.emit('wallet-opening', 'Synchronizing Wallet');
    emitter.emit('db-init');

    emitter.once('db-ready', function(err) {
      if (err) return callbackError(err, callbacks);
      initWallet(network, done, txSyncDone);
    });
  })
}

function savePin(pin){
    if (availableTouchId) window.localStorage.setItem('_pin_cs', AES.encrypt(pin, 'pinCoinSpace'));
}

function setAvailableTouchId(){
    availableTouchId = true
}

function getPin(){
    var pin = window.localStorage.getItem('_pin_cs')
    return pin ? AES.decrypt(pin, 'pinCoinSpace') : null
}

function resetPin(){
    window.localStorage.removeItem('_pin_cs')
}

function assignSeedAndId(s) {
  seed = s
  id = crypto.createHash('sha256').update(seed).digest('hex')
  emitter.emit('wallet-init', {seed: seed, id: id})
}

function initWallet(networkName, done, txDone) {
  var token = getToken();
  if (!isValidWalletToken(token)) {
    setToken(networkName);
    token = false;
  }

  var options = {
    networkName: networkName,
    done: done,
    txDone: function(err) {
      if (err) return txDone(err)
      var txObjs = wallet.getTransactionHistory()
      txDone(null, txObjs.map(function(tx) {
        return parseHistoryTx(tx)
      }))
    }
  }

  if (networkName === 'ethereum') {
    options.seed = seed;
    options.minConf = 12;
    options.token = token;
    convert.setDecimals(token ? token.decimals : 18);
  } else if (['bitcoin', 'bitcoincash', 'bitcoinsv', 'litecoin', 'dogecoin', 'dash'].indexOf(networkName) !== -1) {
    var accounts = getDerivedAccounts(networkName);
    options.externalAccount = accounts.externalAccount;
    options.internalAccount = accounts.internalAccount;
    options.minConf = 4;
    if (networkName === 'bitcoincash') {
      options.minConf = 0;
    }
    options.getDynamicFees = function() {
      return request({
        url: urlRoot + 'fees',
        params: { network: networkName },
      }).catch(console.error);
    }
    options.getCsFee = function() {
      return request({
        url: urlRoot + 'csFee',
        params: { network: networkName },
      }).catch(console.error);
    }
    convert.setDecimals(8);
  } else if (networkName === 'ripple') {
    options.seed = seed;
    convert.setDecimals(0);
  } else if (networkName === 'stellar') {
    options.seed = seed;
    convert.setDecimals(0);
  } else if (networkName === 'eos') {
    options.seed = seed;
    options.accountName = db.get('eosAccountName') || '';
    if (process.env.NODE_ENV === 'development') {
      options.chainId = 'e70aaab8997e1dfce58fbfac80cbbb8fecec7b99cf982a9444273cbc64c41473';
    }
    convert.setDecimals(0);
  }

  wallet = new Wallet[networkName](options);
  wallet.denomination = token ? denomination(token) : denomination(networkName);
}

function isValidWalletToken(token) {
  if (token && token.isDefault) return true;
  var walletTokens = db.get('walletTokens') || [];
  var isFound = _.find(walletTokens, function(item) {
    return _.isEqual(token, item);
  });
  return !!isFound;
}

function getDerivedAccounts(networkName) {
  if (wallet && wallet.networkName === networkName && wallet.externalAccount && wallet.internalAccount) {
    return {
      externalAccount: wallet.externalAccount,
      internalAccount: wallet.internalAccount
    }
  }
  var network = bitcoin.networks[networkName]
  var accountZero = HDKey.fromMasterSeed(new Buffer(seed, 'hex'), network.bip32).deriveChild(HDKey.HARDENED_OFFSET)
  return {
    externalAccount: accountZero.deriveChild(0),
    internalAccount: accountZero.deriveChild(1)
  }
}

function parseHistoryTx(tx) {
  var networkName = wallet.networkName;
  if (networkName === 'ethereum') {
    return utils.parseEthereumTx(tx);
  } else if (networkName === 'ripple') {
    return tx;
  } else if (networkName === 'stellar') {
    return tx;
  } else if (networkName === 'eos') {
    return tx;
  } else if (['bitcoin', 'bitcoincash', 'bitcoinsv', 'litecoin', 'dogecoin', 'dash'].indexOf(networkName) !== -1) {
    return utils.parseBtcLtcTx(tx, networkName);
  }
}

function sync(done, txDone) {
  initWallet(wallet.networkName, done, txDone)
}

function getWallet() {
  return wallet;
}

function getId() {
  return id;
}

function walletExists() {
  return !!walletDb.getCredentials();
}

function reset() {
  walletDb.deleteCredentials();
}

function getDestinationInfo(to) {
  if (wallet.networkName === 'ripple' || wallet.networkName === 'stellar') {
    return wallet.getDestinationInfo(to);
  } else {
    return Promise.resolve();
  }
}

function setToAlias(data) {
  if (wallet.networkName !== 'bitcoincash') return;
  try {
    var legacy = bchaddr.toLegacyAddress(data.to);
    if (legacy !== data.to) {
      data.alias = data.to;
      data.to = legacy;
    }
  } catch (e) {}
}

module.exports = {
  openWalletWithPin: openWalletWithPin,
  createWallet: createWallet,
  setPin: setPin,
  removeAccount: removeAccount,
  setUsername: setUsername,
  getWallet: getWallet,
  getId: getId,
  walletExists: walletExists,
  reset: reset,
  sync: sync,
  initWallet: initWallet,
  validateSend: validateSend,
  parseHistoryTx: parseHistoryTx,
  getPin: getPin,
  resetPin: resetPin,
  setAvailableTouchId: setAvailableTouchId,
  getDestinationInfo: getDestinationInfo,
  setToAlias: setToAlias
}
<commit_msg>Update minConf<commit_after>'use strict';

var Worker = require('worker-loader?inline&fallback=false!./worker.js');
var worker = new Worker()

var auth = require('./auth')
var utils = require('./utils')
var walletDb = require('./db')
var emitter = require('lib/emitter')
var crypto = require('crypto')
var AES = require('lib/aes')
var denomination = require('lib/denomination')
var CsWallet = require('cs-wallet')
var validateSend = require('./validator')
var rng = require('secure-random').randomBuffer
var bitcoin = CsWallet.bitcoin
var request = require('lib/request')
var EthereumWallet = require('cs-ethereum-wallet');
var RippleWallet = require('cs-ripple-wallet');
var StellarWallet = require('cs-stellar-wallet');
var EOSWallet = require('cs-eos-wallet');
var convert = require('lib/convert');
var getToken = require('lib/token').getToken;
var setToken = require('lib/token').setToken;
var db = require('lib/db');
var _ = require('lodash');
var HDKey = require('hdkey');
var Buffer = require('safe-buffer').Buffer;
var bchaddr = require('bchaddrjs');

var wallet = null
var seed = null
var mnemonic = null
var id = null
var availableTouchId = false

var Wallet = {
  bitcoin: CsWallet,
  bitcoincash: CsWallet,
  bitcoinsv: CsWallet,
  litecoin: CsWallet,
  ethereum: EthereumWallet,
  ripple: RippleWallet,
  stellar: StellarWallet,
  eos: EOSWallet,
  dogecoin: CsWallet,
  dash: CsWallet
}

var urlRoot = window.urlRoot

function createWallet(passphrase, network, callback) {
  var data = {passphrase: passphrase}
  if(!passphrase){
   data.entropy = rng(128 / 8).toString('hex')
  }

  worker.onmessage = function(e) {
    assignSeedAndId(e.data.seed)

    mnemonic = e.data.mnemonic
    auth.exist(id, function(err, userExists){
      if(err) return callback(err);

      callback(null, {userExists: userExists, mnemonic: mnemonic})
    })
  }

  worker.onerror = function(e) {
    return callback({message: e.message.split(': ')[1]})
  }

  worker.postMessage(data)
}

function callbackError(err, callbacks) {
  callbacks.forEach(function (callback) {
    if (!callback) return;
    return callback(err);
  });
}

function setPin(pin, network, done, txSyncDone) {
  var callbacks = [done, txSyncDone]
  auth.register(id, pin, function(err, token) {
    if (err) return callbackError(err, callbacks);

    savePin(pin);
    walletDb.saveEncrypedSeed(id, AES.encrypt(seed, token));

    emitter.emit('wallet-opening', 'Synchronizing Wallet');
    emitter.emit('db-init');

    emitter.once('db-ready', function(err) {
      if (err) return callbackError(err, callbacks);
      initWallet(network, done, txSyncDone);
    });
  })
}

function removeAccount(callback) {
  auth.remove(id, callback);
}

function setUsername(username, callback) {
  auth.setUsername(id, username, callback);
}

function openWalletWithPin(pin, network, done, txSyncDone) {
  var callbacks = [done, txSyncDone]
  var credentials = walletDb.getCredentials();
  var id = credentials.id
  var encryptedSeed = credentials.seed
  auth.login(id, pin, function(err, token) {
    if (err) {
      if (err.message === 'user_deleted') {
        walletDb.deleteCredentials();
      }
      return callbackError(err, callbacks);
    }

    savePin(pin)
    assignSeedAndId(AES.decrypt(encryptedSeed, token));

    emitter.emit('wallet-opening', 'Synchronizing Wallet');
    emitter.emit('db-init');

    emitter.once('db-ready', function(err) {
      if (err) return callbackError(err, callbacks);
      initWallet(network, done, txSyncDone);
    });
  })
}

function savePin(pin){
    if (availableTouchId) window.localStorage.setItem('_pin_cs', AES.encrypt(pin, 'pinCoinSpace'));
}

function setAvailableTouchId(){
    availableTouchId = true
}

function getPin(){
    var pin = window.localStorage.getItem('_pin_cs')
    return pin ? AES.decrypt(pin, 'pinCoinSpace') : null
}

function resetPin(){
    window.localStorage.removeItem('_pin_cs')
}

function assignSeedAndId(s) {
  seed = s
  id = crypto.createHash('sha256').update(seed).digest('hex')
  emitter.emit('wallet-init', {seed: seed, id: id})
}

function initWallet(networkName, done, txDone) {
  var token = getToken();
  if (!isValidWalletToken(token)) {
    setToken(networkName);
    token = false;
  }

  var options = {
    networkName: networkName,
    done: done,
    txDone: function(err) {
      if (err) return txDone(err)
      var txObjs = wallet.getTransactionHistory()
      txDone(null, txObjs.map(function(tx) {
        return parseHistoryTx(tx)
      }))
    }
  }

  if (networkName === 'ethereum') {
    options.seed = seed;
    options.minConf = 12;
    options.token = token;
    convert.setDecimals(token ? token.decimals : 18);
  } else if (['bitcoin', 'bitcoincash', 'bitcoinsv', 'litecoin', 'dogecoin', 'dash'].indexOf(networkName) !== -1) {
    var accounts = getDerivedAccounts(networkName);
    options.externalAccount = accounts.externalAccount;
    options.internalAccount = accounts.internalAccount;
    options.minConf = 3;
    if (networkName === 'bitcoincash') {
      options.minConf = 0;
    }
    options.getDynamicFees = function() {
      return request({
        url: urlRoot + 'fees',
        params: { network: networkName },
      }).catch(console.error);
    }
    options.getCsFee = function() {
      return request({
        url: urlRoot + 'csFee',
        params: { network: networkName },
      }).catch(console.error);
    }
    convert.setDecimals(8);
  } else if (networkName === 'ripple') {
    options.seed = seed;
    convert.setDecimals(0);
  } else if (networkName === 'stellar') {
    options.seed = seed;
    convert.setDecimals(0);
  } else if (networkName === 'eos') {
    options.seed = seed;
    options.accountName = db.get('eosAccountName') || '';
    if (process.env.NODE_ENV === 'development') {
      options.chainId = 'e70aaab8997e1dfce58fbfac80cbbb8fecec7b99cf982a9444273cbc64c41473';
    }
    convert.setDecimals(0);
  }

  wallet = new Wallet[networkName](options);
  wallet.denomination = token ? denomination(token) : denomination(networkName);
}

function isValidWalletToken(token) {
  if (token && token.isDefault) return true;
  var walletTokens = db.get('walletTokens') || [];
  var isFound = _.find(walletTokens, function(item) {
    return _.isEqual(token, item);
  });
  return !!isFound;
}

function getDerivedAccounts(networkName) {
  if (wallet && wallet.networkName === networkName && wallet.externalAccount && wallet.internalAccount) {
    return {
      externalAccount: wallet.externalAccount,
      internalAccount: wallet.internalAccount
    }
  }
  var network = bitcoin.networks[networkName]
  var accountZero = HDKey.fromMasterSeed(new Buffer(seed, 'hex'), network.bip32).deriveChild(HDKey.HARDENED_OFFSET)
  return {
    externalAccount: accountZero.deriveChild(0),
    internalAccount: accountZero.deriveChild(1)
  }
}

function parseHistoryTx(tx) {
  var networkName = wallet.networkName;
  if (networkName === 'ethereum') {
    return utils.parseEthereumTx(tx);
  } else if (networkName === 'ripple') {
    return tx;
  } else if (networkName === 'stellar') {
    return tx;
  } else if (networkName === 'eos') {
    return tx;
  } else if (['bitcoin', 'bitcoincash', 'bitcoinsv', 'litecoin', 'dogecoin', 'dash'].indexOf(networkName) !== -1) {
    return utils.parseBtcLtcTx(tx, networkName);
  }
}

function sync(done, txDone) {
  initWallet(wallet.networkName, done, txDone)
}

function getWallet() {
  return wallet;
}

function getId() {
  return id;
}

function walletExists() {
  return !!walletDb.getCredentials();
}

function reset() {
  walletDb.deleteCredentials();
}

function getDestinationInfo(to) {
  if (wallet.networkName === 'ripple' || wallet.networkName === 'stellar') {
    return wallet.getDestinationInfo(to);
  } else {
    return Promise.resolve();
  }
}

function setToAlias(data) {
  if (wallet.networkName !== 'bitcoincash') return;
  try {
    var legacy = bchaddr.toLegacyAddress(data.to);
    if (legacy !== data.to) {
      data.alias = data.to;
      data.to = legacy;
    }
  } catch (e) {}
}

module.exports = {
  openWalletWithPin: openWalletWithPin,
  createWallet: createWallet,
  setPin: setPin,
  removeAccount: removeAccount,
  setUsername: setUsername,
  getWallet: getWallet,
  getId: getId,
  walletExists: walletExists,
  reset: reset,
  sync: sync,
  initWallet: initWallet,
  validateSend: validateSend,
  parseHistoryTx: parseHistoryTx,
  getPin: getPin,
  resetPin: resetPin,
  setAvailableTouchId: setAvailableTouchId,
  getDestinationInfo: getDestinationInfo,
  setToAlias: setToAlias
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    if (prompt() === 'rock') || (prompt()=== 'paper') || (prompt()=== 'scissors'){
    return prompt();
    } else {
        return "error";
    }
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>attempted to solve full project lets see<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    if (prompt() === 'rock') || (prompt()=== 'paper') || (prompt()=== 'scissors'){
    return prompt();
    } else {
        return "error";
    }
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    if (move==undefined){
        return getInput();
    } else if (move==="rock")||(move==="paper")||(move==="scissors"){
        return this.move;
    } else {
        console.log("hmm I'm not understanding something!");
        return getInput();
    }
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    if (move==undefined){
        return randomPlay();
    } else if (move==="rock")||(move==="paper")||(move==="scissors"){
        return this.move;
    } else {
        console.log("hmm I'm not understanding something!");
        return randomPlay();
    }
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    var compWins=0;
    var playerWins=0;
    if (playerMove===computerMove){
        return tie;
    } else if (playerMove==="rock"){
        if (computerMove==="paper"){
            return compWins++;
        } else if (computerMove==="scissors"){
        return playerWins++;
        }
    } else if (playerMove==="paper"){
        if (computerMove==="scissors"){
            return compWins++;
        } else if (computerMove==="rock"){
            return playerWins++;
        }
    } else if (playerMove==="scissors"){
        if (computerMove==="rock"){
            return compWins++;
        } else if (computerMove==="paper"){
            return playerWins++;
        }
    } else {
        return "error";
    }
    return compWins;
    return playerWins;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    var compWins=0;
    var playerWins=0;
    while (compWins<5===true)&&(playerWins<5===true) {
        getWinner(getPlayerMove, getComputerMove);
        }
    return [playerWins, compWins];
}
playToFive();

<|endoftext|>


<commit_before>'use strict';
/* global require */
var crypto              =   require('crypto'),
    fs                  =   require('fs'),
    mime                =   require('mime'),
    request             =   require('request'),
    s3                  =   require('s3'),
    Answer              =   require('mongoose').model('Answer'),
    Doc                 =   require('mongoose').model('Documents'),
    FileUploadStatus    =   require('mongoose').model('FileUploadStatus'),
    phantom             =   require('phantom'),
    //MendeleyToken     =   require('mongoose').model('MendeleyToken'),
    upload_bucket       =   process.env.DOC_BUCKET,
    client              =   s3.createClient({
                                maxAsyncS3: 20,     // this is the default
                                s3RetryCount: 3,    // this is the default
                                s3RetryDelay: 1000, // this is the default
                                multipartUploadThreshold: 20971520, // this is the default (20 MB)
                                multipartUploadSize: 15728640, // this is the default (15 MB)
                                s3Options: {
                                    accessKeyId: process.env.DOC_AWS_ACCESS_KEY,
                                    secretAccessKey: process.env.DOC_AWS_SECRET_KEY
                                    // any other options are passed to new AWS.S3()
                                    // See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Config.html#constructor-property
                                }
                            });

var uploadFile = function(file, req, callback) {
    var hash = crypto.createHash('sha1'),
        timestamp = new Date().toISOString(),
        file_extension = getFileExtension(file.path);

    fs.readFile(file.path, {encoding: 'utf8'}, function (err, data) {
        hash.update(data);
        // get hashed value of file as fingerprint
        var file_hash = hash.digest('hex');
        // search documents for hashed file
        Doc.findOne({file_hash: file_hash}, function (err, document) {
            // if file exists tag for reference
            if (document !== null) {
                callback(null, document);
                // if not upload to s3 with hashed value as file name,
                // create record with hash value and end url
            } else {
                // upload parameters
                var params = {
                    localFile: file.path,
                    s3Params: {
                        Bucket: upload_bucket,
                        Key: String(file_hash) + '.' + file_extension
                        // other options supported by putObject, except Body and ContentLength.
                        // See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property
                    }
                };

                var uploader = client.uploadFile(params);
                uploader.on('error', function(err) {
                    console.error("unable to upload:", err.stack);
                });
                uploader.on('progress', function() {
                    console.log("progress", uploader.progressMd5Amount, uploader.progressAmount, uploader.progressTotal);
                });
                uploader.on('end', function() {
                    console.log("done uploading");
                });

                Doc.create({
                    file_hash: file_hash,
                    mime_type: file.type,
                    s3_url: 'https://s3.amazonaws.com/' + upload_bucket + '/' + file_hash + '.' + file_extension,
                    modified: [{
                        modified_by: req.user._id,
                        modified_date: timestamp
                    }],
                    createdBy: req.user._id,
                    creationDate: timestamp
                }, callback);
            }
        });
    });
};

var getFileExtension = function(filePath) {
    return filePath.split('.')[filePath.split('.').length - 1];
};

var getFileName = function(timestamp, user, extension) {
    return user + '-' + timestamp + (extension ? ('.' + extension) : '');
};

exports.getRemoteFileUploadStatus = function (req, res) {
    FileUploadStatus.findOne({_id: req.params.statusId}, function(err, uploadStatus) {
        res.send(uploadStatus);
    });
};

exports.uploadUrlSnapshot = function(req, res) {
    var width = 1024, height = 768;

    phantom.create().then(function(ph) {
        ph.createPage().then(function(page) {
            page.property('viewportSize', {width: width, height: height}).then(function() {
                page.open(req.query.url).then(function() {
                    page.evaluate(function() {
                        return document.body.offsetHeight;
                    }).then(function(actualHeight) {
                        if(actualHeight > 3000) {
                            res.send({error: 'TOO_LARGE_SIZE'});
                        } else {
                            page.property('viewportSize', {width: width, height: actualHeight}).then(function() {
                                page.open(req.query.url).then(function() {
                                    var filePath = '/tmp/' + getFileName(new Date().getTime(), req.user._id, 'png');
                                    page.render(filePath);

                                    uploadFile({path: filePath, type: mime.lookup(filePath)}, req,
                                        function (errorUpload, doc) {
                                            fs.unlink(filePath);

                                            if(errorUpload) {
                                                res.send({error: 'S3_TRANSFER_FAILURE'});
                                            } else {
                                                res.send({result: doc});
                                            }
                                        }
                                    );

                                    page.close();
                                    ph.exit();
                                }).catch(function() {
                                    res.send({error: 'PAGE_CONNECT_FAILURE'});
                                });
                            }).catch(function() {
                                res.send({error: 'VIEWPORT_RESIZE_FAILURE'});
                            });
                        }
                    }).catch(function() {
                        res.send({error: 'PAGE_DEFINE_HEIGHT_FAILURE'});
                    });
                }).catch(function() {
                    res.send({error: 'PAGE_CONNECT_FAILURE'});
                });
            }).catch(function() {
                res.send({error: 'VIEWPORT_RESIZE_FAILURE'});
            });
        }).catch(function() {
            res.send({error: 'PAGE_OPEN_FAILURE'});
        });
    }).catch(function() {
        res.send({error: 'PHANTOM_INITIALIZATION_FAILURE'});
    });
};

exports.uploadRemoteFile = function (req, res) {
    FileUploadStatus.create({}, function(err, fileUploadStatus) {
        var timeoutId,
            timeoutPeriod = 20000,
            remoteFileRequest = request({
                method: 'GET',
                timeout: timeoutPeriod,
                uri: req.query.url
            }, function () {})
                .on('response', function(response) {
                    clearTimeout(timeoutId);

                    if (response.statusCode === 200) {
                        var fileTotalSize = response.headers['content-length'] ? parseInt(response.headers['content-length'], 10) : -1;
                        var receivedDataSized = 0;
                        var filePath = '/tmp/' +
                            getFileName(new Date().getTime(), req.user._id, getFileExtension(req.query.url));

                        var file = fs.createWriteStream(filePath);
                        response.pipe(file);

                        response
                            .on('data', function(data) {
                                receivedDataSized += data.length;
                                fileUploadStatus.setCompletion(fileTotalSize > 0 ? receivedDataSized / fileTotalSize : 0);
                            })
                            .on('end', function() {
                                file.close(function() {
                                    fileUploadStatus.setCompletion(1);
                                    uploadFile({path: filePath, type: mime.lookup(filePath)}, req, function (err, doc) {
                                        if (!err) {
                                            fileUploadStatus.setDocument(doc);
                                        }
                                    });
                                });
                            })
                            .on('error', function(err) {
                                file.close(function() {
                                    fs.unlink(filePath);
                                    res.send({reason: err.toString()});
                                });
                            });

                        res.send({
                            _id: fileUploadStatus._id,
                            completion: fileUploadStatus.completion,
                            size: fileTotalSize
                        });

                    } else {
                        res.send({reason: 'The file is not found'});
                    }
                })
                .on('error', function(err) {
                    clearTimeout(timeoutId);
                    res.send({reason: err.toString()});
                });

            timeoutId = setTimeout(function() {
                remoteFileRequest.abort();
                res.send({reason: 'File request timeout'});
            }, timeoutPeriod);
    });
};

exports.fileCheck = function (req, res) {
    uploadFile(req.files.file, req, function (err, document) {
        if (err) {
            res.status(400);
            res.send({reason: err.toString()});
        } else {
            res.send(document);
        }
    });
};

exports.getDocuments = function (req, res) {
    var query = Doc.find(req.query);
    query.exec(function (err, collection) {
        res.send(collection);
    });
};

exports.getDocumentsByID = function (req, res) {
    Doc.findOne({_id: req.params.id}).exec(function (err, document) {
        res.send(document);
    });
};

exports.getUploadStatusDocument = function (req, res) {
    FileUploadStatus.findOne({_id: req.params.statusId}).exec(function (errorUploadStatus, uploadStatus) {
        if (errorUploadStatus) {
            res.status(500).send({reason: errorUploadStatus.toString()});
        } else if (!uploadStatus || (uploadStatus.document === undefined)) {
            res.status(404).send({reason: 'not found'});
        } else {
            Doc.findOne({_id: uploadStatus.document}).exec(function (errorDocument, document) {
                if (errorDocument) {
                    res.status(500).send({reason: errorDocument.toString()});
                } else if (!document) {
                    res.status(404).send({reason: 'not found'});
                } else {
                    res.send(document);
                }
            });
        }
    });
};

// exports.getUsersByID = function (req, res) {
//     User.findOne({_id: req.params.id}).exec(function (err, user) {
//         res.send(user);
//     });
// };

exports.updateDocument = function (req, res) {
    var document_update, timestamp;

    document_update = req.body;
    timestamp = new Date().toISOString();

    Doc.findOne({_id: document_update._id}).exec(function (err, document) {
        document.title = document_update.title;
        document.authors = document_update.authors;
        document.type = document_update.type;
        document.assessments = document_update.assessments;
        document.questions = document_update.questions;
        document.answers = document_update.answers;
        document.users = document_update.users;
        document.modified = document_update.modified;
        document.status = document_update.status;
        document.last_modified = {
            modified_by: req.user._id,
            modified_date: timestamp};

        var input_array = ['source', 'year', 'date_published', 'pages', 'volume', 'issue', 'websites', 'publisher', 'city', 'edition', 'institution', 'series', 'chapter', 'editors', 'country', 'translators', 'series_editor'];
        input_array.forEach(function (el) {
            if (el in document_update) {
                document[el] = document_update[el];
            }
        });

        document.save(function (err) {
            if (err) {
                res.status(400);
                res.send({reason: err.toString()});
            }
        });
    });
    // res.send();
};

exports.deleteDocument = function (req, res) {
    Doc.remove({_id: req.params.id}, function (err) {
        res.send(err ? {reason: err.toString()} : {});
    });
};
<commit_msg>exit PhantomJS on any error of web page generation<commit_after>'use strict';
/* global require */
var crypto              =   require('crypto'),
    fs                  =   require('fs'),
    mime                =   require('mime'),
    request             =   require('request'),
    s3                  =   require('s3'),
    Answer              =   require('mongoose').model('Answer'),
    Doc                 =   require('mongoose').model('Documents'),
    FileUploadStatus    =   require('mongoose').model('FileUploadStatus'),
    phantom             =   require('phantom'),
    //MendeleyToken     =   require('mongoose').model('MendeleyToken'),
    upload_bucket       =   process.env.DOC_BUCKET,
    client              =   s3.createClient({
                                maxAsyncS3: 20,     // this is the default
                                s3RetryCount: 3,    // this is the default
                                s3RetryDelay: 1000, // this is the default
                                multipartUploadThreshold: 20971520, // this is the default (20 MB)
                                multipartUploadSize: 15728640, // this is the default (15 MB)
                                s3Options: {
                                    accessKeyId: process.env.DOC_AWS_ACCESS_KEY,
                                    secretAccessKey: process.env.DOC_AWS_SECRET_KEY
                                    // any other options are passed to new AWS.S3()
                                    // See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Config.html#constructor-property
                                }
                            });

var uploadFile = function(file, req, callback) {
    var hash = crypto.createHash('sha1'),
        timestamp = new Date().toISOString(),
        file_extension = getFileExtension(file.path);

    fs.readFile(file.path, {encoding: 'utf8'}, function (err, data) {
        hash.update(data);
        // get hashed value of file as fingerprint
        var file_hash = hash.digest('hex');
        // search documents for hashed file
        Doc.findOne({file_hash: file_hash}, function (err, document) {
            // if file exists tag for reference
            if (document !== null) {
                callback(null, document);
                // if not upload to s3 with hashed value as file name,
                // create record with hash value and end url
            } else {
                // upload parameters
                var params = {
                    localFile: file.path,
                    s3Params: {
                        Bucket: upload_bucket,
                        Key: String(file_hash) + '.' + file_extension
                        // other options supported by putObject, except Body and ContentLength.
                        // See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property
                    }
                };

                var uploader = client.uploadFile(params);
                uploader.on('error', function(err) {
                    console.error("unable to upload:", err.stack);
                });
                uploader.on('progress', function() {
                    console.log("progress", uploader.progressMd5Amount, uploader.progressAmount, uploader.progressTotal);
                });
                uploader.on('end', function() {
                    console.log("done uploading");
                });

                Doc.create({
                    file_hash: file_hash,
                    mime_type: file.type,
                    s3_url: 'https://s3.amazonaws.com/' + upload_bucket + '/' + file_hash + '.' + file_extension,
                    modified: [{
                        modified_by: req.user._id,
                        modified_date: timestamp
                    }],
                    createdBy: req.user._id,
                    creationDate: timestamp
                }, callback);
            }
        });
    });
};

var getFileExtension = function(filePath) {
    return filePath.split('.')[filePath.split('.').length - 1];
};

var getFileName = function(timestamp, user, extension) {
    return user + '-' + timestamp + (extension ? ('.' + extension) : '');
};

exports.getRemoteFileUploadStatus = function (req, res) {
    FileUploadStatus.findOne({_id: req.params.statusId}, function(err, uploadStatus) {
        res.send(uploadStatus);
    });
};

exports.uploadUrlSnapshot = function(req, res) {
    var width = 1024, height = 768,
        terminateWithError = function(errorCode, ph) {
            res.send({error: errorCode});
            console.log(errorCode);

            if(ph) {
                ph.exit();
            }
        };

    phantom.create().then(function(ph) {
        ph.createPage().then(function(page) {
            page.property('viewportSize', {width: width, height: height}).then(function() {
                page.open(req.query.url).then(function() {
                    page.evaluate(function() {
                        return document.body.offsetHeight;
                    }).then(function(actualHeight) {
                        if(actualHeight > 3000) {
                            terminateWithError('TOO_LARGE_SIZE', ph);
                        } else {
                            page.property('viewportSize', {width: width, height: actualHeight}).then(function() {
                                page.open(req.query.url).then(function() {
                                    var filePath = '/tmp/' + getFileName(new Date().getTime(), req.user._id, 'png');
                                    page.render(filePath);

                                    uploadFile({path: filePath, type: mime.lookup(filePath)}, req,
                                        function (errorUpload, doc) {
                                            fs.unlink(filePath);

                                            if(errorUpload) {
                                                terminateWithError('S3_TRANSFER_FAILURE', ph);
                                            } else {
                                                res.send({result: doc});
                                            }
                                        }
                                    );

                                    page.close();
                                    ph.exit();
                                }).catch(function() {
                                    terminateWithError('PAGE_CONNECT_FAILURE', ph);
                                });
                            }).catch(function() {
                                terminateWithError('VIEWPORT_RESIZE_FAILURE', ph);
                            });
                        }
                    }).catch(function() {
                        terminateWithError('PAGE_DEFINE_HEIGHT_FAILURE', ph);
                    });
                }).catch(function() {
                    terminateWithError('PAGE_CONNECT_FAILURE', ph);
                });
            }).catch(function() {
                terminateWithError('VIEWPORT_RESIZE_FAILURE', ph);
            });
        }).catch(function() {
            terminateWithError('PAGE_OPEN_FAILURE', ph);
        });
    }).catch(function() {
        terminateWithError('PHANTOM_INITIALIZATION_FAILURE');
    });
};

exports.uploadRemoteFile = function (req, res) {
    FileUploadStatus.create({}, function(err, fileUploadStatus) {
        var timeoutId,
            timeoutPeriod = 20000,
            remoteFileRequest = request({
                method: 'GET',
                timeout: timeoutPeriod,
                uri: req.query.url
            }, function () {})
                .on('response', function(response) {
                    clearTimeout(timeoutId);

                    if (response.statusCode === 200) {
                        var fileTotalSize = response.headers['content-length'] ? parseInt(response.headers['content-length'], 10) : -1;
                        var receivedDataSized = 0;
                        var filePath = '/tmp/' +
                            getFileName(new Date().getTime(), req.user._id, getFileExtension(req.query.url));

                        var file = fs.createWriteStream(filePath);
                        response.pipe(file);

                        response
                            .on('data', function(data) {
                                receivedDataSized += data.length;
                                fileUploadStatus.setCompletion(fileTotalSize > 0 ? receivedDataSized / fileTotalSize : 0);
                            })
                            .on('end', function() {
                                file.close(function() {
                                    fileUploadStatus.setCompletion(1);
                                    uploadFile({path: filePath, type: mime.lookup(filePath)}, req, function (err, doc) {
                                        if (!err) {
                                            fileUploadStatus.setDocument(doc);
                                        }
                                    });
                                });
                            })
                            .on('error', function(err) {
                                file.close(function() {
                                    fs.unlink(filePath);
                                    res.send({reason: err.toString()});
                                });
                            });

                        res.send({
                            _id: fileUploadStatus._id,
                            completion: fileUploadStatus.completion,
                            size: fileTotalSize
                        });

                    } else {
                        res.send({reason: 'The file is not found'});
                    }
                })
                .on('error', function(err) {
                    clearTimeout(timeoutId);
                    res.send({reason: err.toString()});
                });

            timeoutId = setTimeout(function() {
                remoteFileRequest.abort();
                res.send({reason: 'File request timeout'});
            }, timeoutPeriod);
    });
};

exports.fileCheck = function (req, res) {
    uploadFile(req.files.file, req, function (err, document) {
        if (err) {
            res.status(400);
            res.send({reason: err.toString()});
        } else {
            res.send(document);
        }
    });
};

exports.getDocuments = function (req, res) {
    var query = Doc.find(req.query);
    query.exec(function (err, collection) {
        res.send(collection);
    });
};

exports.getDocumentsByID = function (req, res) {
    Doc.findOne({_id: req.params.id}).exec(function (err, document) {
        res.send(document);
    });
};

exports.getUploadStatusDocument = function (req, res) {
    FileUploadStatus.findOne({_id: req.params.statusId}).exec(function (errorUploadStatus, uploadStatus) {
        if (errorUploadStatus) {
            res.status(500).send({reason: errorUploadStatus.toString()});
        } else if (!uploadStatus || (uploadStatus.document === undefined)) {
            res.status(404).send({reason: 'not found'});
        } else {
            Doc.findOne({_id: uploadStatus.document}).exec(function (errorDocument, document) {
                if (errorDocument) {
                    res.status(500).send({reason: errorDocument.toString()});
                } else if (!document) {
                    res.status(404).send({reason: 'not found'});
                } else {
                    res.send(document);
                }
            });
        }
    });
};

// exports.getUsersByID = function (req, res) {
//     User.findOne({_id: req.params.id}).exec(function (err, user) {
//         res.send(user);
//     });
// };

exports.updateDocument = function (req, res) {
    var document_update, timestamp;

    document_update = req.body;
    timestamp = new Date().toISOString();

    Doc.findOne({_id: document_update._id}).exec(function (err, document) {
        document.title = document_update.title;
        document.authors = document_update.authors;
        document.type = document_update.type;
        document.assessments = document_update.assessments;
        document.questions = document_update.questions;
        document.answers = document_update.answers;
        document.users = document_update.users;
        document.modified = document_update.modified;
        document.status = document_update.status;
        document.last_modified = {
            modified_by: req.user._id,
            modified_date: timestamp};

        var input_array = ['source', 'year', 'date_published', 'pages', 'volume', 'issue', 'websites', 'publisher', 'city', 'edition', 'institution', 'series', 'chapter', 'editors', 'country', 'translators', 'series_editor'];
        input_array.forEach(function (el) {
            if (el in document_update) {
                document[el] = document_update[el];
            }
        });

        document.save(function (err) {
            if (err) {
                res.status(400);
                res.send({reason: err.toString()});
            }
        });
    });
    // res.send();
};

exports.deleteDocument = function (req, res) {
    Doc.remove({_id: req.params.id}, function (err) {
        res.send(err ? {reason: err.toString()} : {});
    });
};
<|endoftext|>


<commit_before>"use strict";

meta.class("Resource.Font", "Resource.Basic",
{
	init: function(path, tag)
	{
		if(path) {
			this.load(Resource.ctrl.rootPath + path);
		}
	},

	load: function(path)
	{
		if(this.loading) { return; }
		this.loaded = false;

		if(!path) { return; }
		this.path = path;

		// Check if path is missing it's extension:
		var wildCardIndex = this.path.lastIndexOf(".");
		if(wildCardIndex === -1 || this.path.length - wildCardIndex > 4) {
			this.path += ".fnt";
			this.format = "fnt";
		}
		else {
			this.format = this.path.substr(wildCardIndex + 1)
		}

		var parseFunc = this["parse_" + this.format];
		if(!parseFunc) {
			console.warn("(Resource.Font.load) Unsupported format: " + this.format);
			return;
		}

		this.chars = new Array(256);

		Resource.ctrl.addToLoad(this);

		this.texture = new Resource.Texture(path);
		this.texture.subscribe(this, this._onTextureEvent);

		var self = this;
		meta.ajax({
			url: this.path,
			success: function(data) { parseFunc.call(self, data); },
			error: function() { self._onError(); }
		});
	},

	parse_fnt: function(data)
	{
		this.tokenizer.setup(data);
		this.tokenizer.nextToken();
		while(this.tokenizer.token.type !== 0) {
			this._parseToken_fnt();
		}

		this._loadedFormat = true;
		if(this.texture._loaded) {
			Resource.ctrl.loadSuccess(self);
			this.loaded = true;
		}
	},

	_parseToken_fnt: function()
	{
		var token = this.tokenizer.token;
		var line = token.line;

		switch(token.str)
		{
			case "char":
			{
				var rect = new this.Rect();

				for(;;)
				{
					token = this.tokenizer.nextToken();
					if(token.line !== line) { break; }

					switch(token.str)
					{
						case "id":
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							this.chars[token.value] = rect;
							break;

						case "x":
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							rect.x = token.value;
							break;

						case "y":
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							rect.y = token.value;
							break;

						case "width":
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							rect.width = token.value;
							break;

						case "height":
						{
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							rect.height = token.value;

							if(this.height < token.value) {
								this.height = token.value;
							}
						} break;

						case "xadvance":
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							rect.kerning = token.value;
							break;
					}
				}
			} break;

			default:
				this.tokenizer.nextToken();
				break;
		}
	},

	_onTextureEvent: function(data, event)
	{
		switch(event)
		{
			case Resource.Event.LOADED:
			{
				this._loadedFormat = true;
				if(this.texture._loaded) {
					Resource.ctrl.loadSuccess(self);
					this.loaded = true;
				}
			} break;

			case Resource.Event.FAILED: {

			} break;
		}
	},

	Rect: function() {
		this.x = 0;
		this.y = 0;
		this.width = 0;
		this.height = 0;
		this.kerning = 0;
	},

	//
	tokenizer: meta.tokenizer,

	type: Resource.Type.FONT,
	format: "",

	texture: null,
	chars: null,
	height: 1,

	_loadedFormat: false
});

<commit_msg>Fixed bitmap font creation and loading.<commit_after>"use strict";

meta.class("Resource.Font", "Resource.Basic",
{
	init: function(path, tag)
	{
		if(path) {
			this.load(meta.resources.rootPath + path);
		}
	},

	load: function(path)
	{
		if(this.loading) { return; }
		this.loaded = false;

		if(!path) { return; }
		this.path = path;

		// Check if path is missing it's extension:
		var wildCardIndex = this.path.lastIndexOf(".");
		if(wildCardIndex === -1 || this.path.length - wildCardIndex > 4) {
			this.path += ".fnt";
			this.format = "fnt";
		}
		else {
			this.format = this.path.substr(wildCardIndex + 1)
		}

		var parseFunc = this["parse_" + this.format];
		if(!parseFunc) {
			console.warn("(Resource.Font.load) Unsupported format: " + this.format);
			return;
		}

		this.chars = new Array(256);

		meta.resources.addToLoad(this);

		this.texture = new Resource.Texture(path);
		this.texture.subscribe(this, this._onTextureEvent);

		var self = this;
		meta.ajax({
			url: this.path,
			success: function(data) { parseFunc.call(self, data); },
			error: function() { self._onError(); }
		});
	},

	_onError: function() {
		meta.resources.loadFailed(self);
	},

	parse_fnt: function(data)
	{
		this.tokenizer.setup(data);
		this.tokenizer.nextToken();
		while(this.tokenizer.token.type !== 0) {
			this._parseToken_fnt();
		}

		this._loadedFormat = true;
		if(this.texture._loaded) {
			meta.resources.loadSuccess(self);
			this.loaded = true;
		}
	},

	_parseToken_fnt: function()
	{
		var token = this.tokenizer.token;
		var line = token.line;

		switch(token.str)
		{
			case "char":
			{
				var rect = new this.Rect();

				for(;;)
				{
					token = this.tokenizer.nextToken();
					if(token.line !== line) { break; }

					switch(token.str)
					{
						case "id":
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							this.chars[token.value] = rect;
							break;

						case "x":
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							rect.x = token.value;
							break;

						case "y":
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							rect.y = token.value;
							break;

						case "width":
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							rect.width = token.value;
							break;

						case "height":
						{
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							rect.height = token.value;

							if(this.height < token.value) {
								this.height = token.value;
							}
						} break;

						case "xadvance":
							this.tokenizer.nextToken();
							token = this.tokenizer.nextToken();
							rect.kerning = token.value;
							break;
					}
				}
			} break;

			default:
				this.tokenizer.nextToken();
				break;
		}
	},

	_onTextureEvent: function(data, event)
	{
		switch(event)
		{
			case Resource.Event.LOADED:
			{
				if(this._loadedFormat) {
					meta.resources.loadSuccess(self);
					this.loaded = true;
				}
			} break;

			case Resource.Event.FAILED: {

			} break;
		}
	},

	Rect: function() {
		this.x = 0;
		this.y = 0;
		this.width = 0;
		this.height = 0;
		this.kerning = 0;
	},

	//
	tokenizer: meta.tokenizer,

	type: Resource.Type.FONT,
	format: "",

	texture: null,
	chars: null,
	height: 1,

	_loadedFormat: false
});

<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var jscs = require('gulp-jscs');
var jshint = require('gulp-jshint');
var mocha = require('gulp-mocha');

var javascriptGlobs = ['*.js', 'src/**/*.js', 'test/**/*.js'];
var testGlobs = ['test/**/*.js'];

gulp.task('style', function() {
  gulp.src(javascriptGlobs)
    .pipe(jscs())
    .pipe(jscs.reporter())
    .pipe(jscs.reporter('fail'));
});

gulp.task('lint', function() {
  gulp.src(javascriptGlobs)
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter())
    .pipe(jshint.reporter('fail'));
});

gulp.task('test', function() {
  gulp.src(testGlobs)
    .pipe(mocha());
});

gulp.task('build', ['lint', 'style', 'test'], function() {
  gulp.src('/');
});

gulp.task('default', ['build']);
<commit_msg>fix(lint): rename var mocha to fix redefinition<commit_after>'use strict';

var gulp = require('gulp');
var jscs = require('gulp-jscs');
var jshint = require('gulp-jshint');
var gulpMocha = require('gulp-mocha');

var javascriptGlobs = ['*.js', 'src/**/*.js', 'test/**/*.js'];
var testGlobs = ['test/**/*.js'];

gulp.task('style', function() {
  gulp.src(javascriptGlobs)
    .pipe(jscs())
    .pipe(jscs.reporter())
    .pipe(jscs.reporter('fail'));
});

gulp.task('lint', function() {
  gulp.src(javascriptGlobs)
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter())
    .pipe(jshint.reporter('fail'));
});

gulp.task('test', function() {
  gulp.src(testGlobs)
    .pipe(gulpMocha());
});

gulp.task('build', ['lint', 'style', 'test'], function() {
  gulp.src('/');
});

gulp.task('default', ['build']);
<|endoftext|>


<commit_before>'use strict';
angular.module('arethusa.hist').service('history', [
  'configurator',
  'keyCapture',
  'state',
  function (configurator, keyCapture, state) {
    var self = this;

    function configure() {
      configurator.getConfAndDelegate('history', self);
      self.maxSize = self.maxSize || 20;
    }

    // Use this variable to temporarily silence the event saving
    this.silence = false;

    function doSilent(fn) {
      self.silence = true;
      fn();
      self.silence = false;
      checkAvailability();
    }

    this.undo = function() {
      if (self.canUndo) {
        doSilent(function() {
          current().undo();
          self.position++;
        });
      }
    };

    this.redo = function() {
      if (self.canRedo) {
        doSilent(function() {
          self.position--;
          current().exec();
        });
      }
    };

    keyCapture.initCaptures(function(kC) {
      return {
        history: [
          kC.create('undo', self.undo),
          kC.create('redo', self.redo)
        ]
      };
    });

    function current() {
      return self.events[self.position];
    }

    function saveEvent(event) {
      if (self.silence) return;

      self.events.splice(0, self.position);
      self.position = 0;
      self.events.unshift(event);
      checkAvailability();
    }

    function checkAvailability() {
      var any = self.events.length > 0;
      self.canUndo = any && self.position < self.events.length;
      self.canRedo = any && self.position > 0;
    }

    state.watch('*', function(n, o, event) {
      saveEvent(event);
    });

    function HistEvent(token, type) {
      var id = token.id;

      this.token = token;
      this.type = type;
      this.time = new Date();

      if (type === 'add') {
        this.exec = function() {
          state.addToken(token, id);
        };
        this.undo = function() {
          state.removeToken(id);
        };
      } else { // type === removed
        this.exec = function() {
          state.removeToken(id);
        };
        this.undo = function() {
          state.addToken(token, id);
        };
      }
    }

    state.on('tokenAdded', function(event, token) {
      var histEvent = new HistEvent(token, 'add');
      saveEvent(histEvent);
    });

    state.on('tokenRemoved', function(event, token) {
      var histEvent = new HistEvent(token, 'remove');
      saveEvent(histEvent);
    });

    this.init = function() {
      configure();
      self.canRedo = false;
      self.canUndo = false;
      self.events = [];
      self.position = 0;
    };
  }
]);
<commit_msg>Honor maxSize in history<commit_after>'use strict';
angular.module('arethusa.hist').service('history', [
  'configurator',
  'keyCapture',
  'state',
  function (configurator, keyCapture, state) {
    var self = this;

    function configure() {
      configurator.getConfAndDelegate('history', self);
      self.maxSize = self.maxSize || 20;
    }

    // Use this variable to temporarily silence the event saving
    this.silence = false;

    function doSilent(fn) {
      self.silence = true;
      fn();
      self.silence = false;
      checkAvailability();
    }

    this.undo = function() {
      if (self.canUndo) {
        doSilent(function() {
          current().undo();
          self.position++;
        });
      }
    };

    this.redo = function() {
      if (self.canRedo) {
        doSilent(function() {
          self.position--;
          current().exec();
        });
      }
    };

    keyCapture.initCaptures(function(kC) {
      return {
        history: [
          kC.create('undo', self.undo),
          kC.create('redo', self.redo)
        ]
      };
    });

    function current() {
      return self.events[self.position];
    }

    function saveEvent(event) {
      if (self.silence) return;

      var events = self.events;
      if (events.length === self.maxSize) events.pop();
      events.splice(0, self.position);
      self.position = 0;
      events.unshift(event);
      checkAvailability();
    }

    function checkAvailability() {
      var any = self.events.length > 0;
      self.canUndo = any && self.position < self.events.length;
      self.canRedo = any && self.position > 0;
    }

    state.watch('*', function(n, o, event) {
      saveEvent(event);
    });

    function HistEvent(token, type) {
      var id = token.id;

      this.token = token;
      this.type = type;
      this.time = new Date();

      if (type === 'add') {
        this.exec = function() {
          state.addToken(token, id);
        };
        this.undo = function() {
          state.removeToken(id);
        };
      } else { // type === removed
        this.exec = function() {
          state.removeToken(id);
        };
        this.undo = function() {
          state.addToken(token, id);
        };
      }
    }

    state.on('tokenAdded', function(event, token) {
      var histEvent = new HistEvent(token, 'add');
      saveEvent(histEvent);
    });

    state.on('tokenRemoved', function(event, token) {
      var histEvent = new HistEvent(token, 'remove');
      saveEvent(histEvent);
    });

    this.init = function() {
      configure();
      self.canRedo = false;
      self.canUndo = false;
      self.events = [];
      self.position = 0;
    };
  }
]);
<|endoftext|>


<commit_before>// @flow

/**
 *
 */
export function assertValidRequestData(rd: any): void {
  if (typeof rd !== 'object' || rd === null) {
    throw new Error(`RequestData must be an object. ${typeof rd} given.`)
  }
  const { method } = rd
  if (!method) {
    throw new Error(`RequestData must have "method" property.`)
  }

  try {
    switch(method) {
      case 'find':
        return assertValidWhereQuery(rd.payload)
      case 'findOne':
        return assertValidWhereQuery(rd.payload)
      case 'get':
        return assertValidIdQuery(rd.payload)
      case 'getByIds':
        return assertValidIdsQuery(rd.payload)
      case 'insert':
        return assertValidInsertCommand(rd.payload)
      case 'insertAndGet':
        return assertValidInsertCommand(rd.payload)
      case 'insertAndGetMulti':
        return assertValidInsertCommand(rd.payload)
      case 'update':
        return assertValidUpdateCommand(rd.payload)
      case 'updateAndGet':
        return assertValidUpdateCommand(rd.payload)
      case 'updateAndFetch':
        return assertValidUpdateCommand(rd.payload)
      case 'delete':
        return assertValidDeleteCommand(rd.payload)
      case 'runCustomQuery':
        return assertValidCustomQuery(rd.payload)
      case 'runCustomCommand':
        return assertValidCustomCommand(rd.payload)
      case 'login':
        return assertValidLoginCommand(rd.payload)
      case 'logout':
        return assertValidLogoutCommand(rd.payload)
      default:
        throw new Error(`Invalid method name.`)
    }
  }
  catch (e) {
    throw new Error(`Error in "requestData.${method}": ${e.message}`)
  }
}

/**
 *
 */
export function assertValidWhereQuery(q: any): void {
  if (typeof q !== 'object' || q === null) {
    throw new Error(`whereQuery must be an object. ${typeof q} given.`)
  }
  const { entityName, where } = q

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`whereQuery.entityName must be a non-empty string. "${entityName}" given.`)
  }

  if (typeof where !== 'object' || where === null) {
    throw new Error(`whereQuery.where must be an object. "${where}" given.`)
  }
}

/**
 *
 */
export function assertValidIdQuery(q: any): void {
  if (typeof q !== 'object' || q === null) {
    throw new Error(`idQuery must be an object. ${typeof q} given.`)
  }
  const { entityName, id } = q

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`idQuery.entityName must be a non-empty string. "${entityName}" given.`)
  }

  if (typeof id !== 'string' || !id) {
    throw new Error(`idQuery.id must be a non-empty string. "${id}" given.`)
  }
}

/**
 *
 */
export function assertValidIdsQuery(q: any): void {
  if (typeof q !== 'object' || q === null) {
    throw new Error(`idsQuery must be an object. ${typeof q} given.`)
  }
  const { entityName, ids } = q

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`idsQuery.entityName must be a non-empty string. "${entityName}" given.`)
  }

  if (!Array.isArray(ids)) {
    throw new Error(`idsQuery.ids must be an array. "${typeof ids}" given.`)
  }

  if (typeof ids[0] !== 'string' || !ids[0]) {
    throw new Error(`idsQuery.ids must be a non-empty array.`)
  }
}

/**
 *
 */
export function assertValidInsertCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`insertCommand must be an object. ${typeof com} given.`)
  }

  const { entityName, value, values } = com

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`insertCommand.entityName must be a non-empty string. "${entityName}" given.`)
  }

  if (value != null) {
    if (typeof value !== 'object') {
      throw new Error(`insertCommand.value must be an object.`)
    }
    return
  }

  if (values != null) {
    if (!Array.isArray(values)) {
      throw new Error(`insertCommand.values must be an array. "${typeof values}" given.`)
    }

    if (typeof values[0] !== 'object') {
      throw new Error(`insertCommand.values must be an non-empty array<Object>.`)
    }
    return
  }

  throw new Error('insertCommand must have key "value" or "values". Neither given.')
}

/**
 *
 */
export function assertValidUpdateCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`updateCommand must be an object. ${typeof com} given.`)
  }

  const { entityName, operation, id, where } = com

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`updateCommand.entityName must be a non-empty string. "${entityName}" given.`)
  }

  assertValidUpdateOperation(operation)

  if (id != null) {
    if (typeof id !== 'string' || !id) {
      throw new Error(`updateCommand.id must be a non-empty string. "${id}" given.`)
    }
    return
  }

  if (where != null) {
    if (typeof where !== 'object') {
      throw new Error(`updateCommand.where must be an object. "${where}" given.`)
    }
    return
  }
  throw new Error('updateCommand must have key "id" or "where". Neither given.')
}

/**
 *
 */
export function assertValidDeleteCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`deleteCommand must be an object. ${typeof com} given.`)
  }

  const { entityName, id, where } = com

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`deleteCommand.entityName must be a non-empty string. "${entityName}" given.`)
  }

  if (id != null) {
    if (typeof id !== 'string' || !id) {
      throw new Error(`deleteCommand.id must be a non-empty string. "${id}" given.`)
    }
    return
  }

  if (where != null) {
    if (typeof where !== 'object') {
      throw new Error(`deleteCommand.where must be an object. "${where}" given.`)
    }
    return
  }
  throw new Error('deleteCommand must have key "id" or "where". Neither given.')
}

/**
 *
 */
export function assertValidCustomQuery(q: any): void {
  if (typeof q !== 'object' || q === null) {
    throw new Error(`customQuery must be an object. ${typeof q} given.`)
  }
  const { name, params } = q

  if (typeof name !== 'string' || !name) {
    throw new Error(`customQuery.name must be a non-empty string. "${name}" given.`)
  }

  // params can be null
  if (params == null) {
    return
  }

  // if params exists, it must be an object
  if (typeof params !== 'object') {
    throw new Error(`customQuery.params must be an object or null. ${typeof params} given.`)
  }
}

/**
 *
 */
export function assertValidCustomCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`customCommand must be an object. ${typeof com} given.`)
  }

  const { name, params } = com

  if (typeof name !== 'string' || !name) {
    throw new Error(`customCommand.name must be a non-empty string. "${name}" given.`)
  }

  // params can be null
  if (params == null) {
    return
  }

  // if params exists, it must be an object
  if (typeof params !== 'object') {
    throw new Error(`customCommand.params must be an object or null. ${typeof params} given.`)
  }
}

/**
 *
 */
export function assertValidLoginCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`loginCommand must be an object. ${typeof com} given.`)
  }

  const { credentials, entityName } = com

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`loginCommand.entityName must be a non-empty string. "${entityName}" given.`)
  }

  // credentials must be an object
  if (typeof credentials !== 'object' || com === null) {
    throw new Error(`loginCommand.credentials must be an object or null. ${typeof credentials} given.`)
  }
  // values in credentials must be strings
  Object.keys(credentials).forEach(credKey => {
    if (credentials[credKey] !== 'string' || !credentials[credKey]) {
      throw new Error(`loginCommand.credentials['${credKey}'] must be a non-empty string.`)
    }
  })
}

/**
 *
 */
export function assertValidLogoutCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`logoutCommand must be an object. ${typeof com} given.`)
  }

  const { sessionId, entityName } = com

  if (typeof sessionId !== 'string' || !sessionId) {
    throw new Error(`logoutCommand.sessionId must be a non-empty string. "${sessionId}" given.`) // ISSUE: sessionId is explicitly shown (but not string...).
  }

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`loginCommand.entityName must be a non-empty string. "${entityName}" given.`)
  }
}

/**
 *
 */
export function assertValidUpdateOperation(ope: any): void {
  if (typeof ope !== 'object' || ope === null) {
    throw new Error(`update operation must be an object. "${ope}" given.`)
  }
}
<commit_msg>[phenyl-utils] improve error log<commit_after>// @flow

/**
 *
 */
export function assertValidRequestData(rd: any): void {
  if (typeof rd !== 'object' || rd === null) {
    throw new Error(`RequestData must be an object. ${typeof rd} given.`)
  }
  const { method } = rd
  if (!method) {
    throw new Error(`RequestData must have "method" property.`)
  }

  try {
    switch(method) {
      case 'find':
        return assertValidWhereQuery(rd.payload)
      case 'findOne':
        return assertValidWhereQuery(rd.payload)
      case 'get':
        return assertValidIdQuery(rd.payload)
      case 'getByIds':
        return assertValidIdsQuery(rd.payload)
      case 'insert':
        return assertValidInsertCommand(rd.payload)
      case 'insertAndGet':
        return assertValidInsertCommand(rd.payload)
      case 'insertAndGetMulti':
        return assertValidInsertCommand(rd.payload)
      case 'update':
        return assertValidUpdateCommand(rd.payload)
      case 'updateAndGet':
        return assertValidUpdateCommand(rd.payload)
      case 'updateAndFetch':
        return assertValidUpdateCommand(rd.payload)
      case 'delete':
        return assertValidDeleteCommand(rd.payload)
      case 'runCustomQuery':
        return assertValidCustomQuery(rd.payload)
      case 'runCustomCommand':
        return assertValidCustomCommand(rd.payload)
      case 'login':
        return assertValidLoginCommand(rd.payload)
      case 'logout':
        return assertValidLogoutCommand(rd.payload)
      default:
        throw new Error(`Invalid method name.`)
    }
  }
  catch (e) {
    throw new Error(`Error in "RequestData(method=${method})": ${e.message}`)
  }
}

/**
 *
 */
export function assertValidWhereQuery(q: any): void {
  if (typeof q !== 'object' || q === null) {
    throw new Error(`WhereQuery must be an object. ${typeof q} given.`)
  }
  const { entityName, where } = q

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`WhereQuery.entityName must be a non-empty string. "${entityName}" given.`)
  }

  if (typeof where !== 'object' || where === null) {
    throw new Error(`WhereQuery.where must be an object. "${where}" given.`)
  }
}

/**
 *
 */
export function assertValidIdQuery(q: any): void {
  if (typeof q !== 'object' || q === null) {
    throw new Error(`IdQuery must be an object. ${typeof q} given.`)
  }
  const { entityName, id } = q

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`IdQuery.entityName must be a non-empty string. "${entityName}" given.`)
  }

  if (typeof id !== 'string' || !id) {
    throw new Error(`IdQuery.id must be a non-empty string. "${id}" given.`)
  }
}

/**
 *
 */
export function assertValidIdsQuery(q: any): void {
  if (typeof q !== 'object' || q === null) {
    throw new Error(`IdsQuery must be an object. ${typeof q} given.`)
  }
  const { entityName, ids } = q

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`IdsQuery.entityName must be a non-empty string. "${entityName}" given.`)
  }

  if (!Array.isArray(ids)) {
    throw new Error(`IdsQuery.ids must be an array. "${typeof ids}" given.`)
  }

  if (typeof ids[0] !== 'string' || !ids[0]) {
    throw new Error(`IdsQuery.ids must be a non-empty array.`)
  }
}

/**
 *
 */
export function assertValidInsertCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`InsertCommand must be an object. ${typeof com} given.`)
  }

  const { entityName, value, values } = com

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`InsertCommand.entityName must be a non-empty string. "${entityName}" given.`)
  }

  if (value != null) {
    if (typeof value !== 'object') {
      throw new Error(`InsertCommand.value must be an object.`)
    }
    return
  }

  if (values != null) {
    if (!Array.isArray(values)) {
      throw new Error(`InsertCommand.values must be an array. "${typeof values}" given.`)
    }

    if (typeof values[0] !== 'object') {
      throw new Error(`InsertCommand.values must be an non-empty array<Object>.`)
    }
    return
  }

  throw new Error('InsertCommand must have key "value" or "values". Neither given.')
}

/**
 *
 */
export function assertValidUpdateCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`UpdateCommand must be an object. ${typeof com} given.`)
  }

  const { entityName, operation, id, where } = com

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`UpdateCommand.entityName must be a non-empty string. "${entityName}" given.`)
  }

  assertValidUpdateOperation(operation)

  if (id != null) {
    if (typeof id !== 'string' || !id) {
      throw new Error(`UpdateCommand.id must be a non-empty string. "${id}" given.`)
    }
    return
  }

  if (where != null) {
    if (typeof where !== 'object') {
      throw new Error(`UpdateCommand.where must be an object. "${where}" given.`)
    }
    return
  }
  throw new Error('UpdateCommand must have key "id" or "where". Neither given.')
}

/**
 *
 */
export function assertValidDeleteCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`DeleteCommand must be an object. ${typeof com} given.`)
  }

  const { entityName, id, where } = com

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`DeleteCommand.entityName must be a non-empty string. "${entityName}" given.`)
  }

  if (id != null) {
    if (typeof id !== 'string' || !id) {
      throw new Error(`DeleteCommand.id must be a non-empty string. "${id}" given.`)
    }
    return
  }

  if (where != null) {
    if (typeof where !== 'object') {
      throw new Error(`DeleteCommand.where must be an object. "${where}" given.`)
    }
    return
  }
  throw new Error('DeleteCommand must have key "id" or "where". Neither given.')
}

/**
 *
 */
export function assertValidCustomQuery(q: any): void {
  if (typeof q !== 'object' || q === null) {
    throw new Error(`CustomQuery must be an object. ${typeof q} given.`)
  }
  const { name, params } = q

  if (typeof name !== 'string' || !name) {
    throw new Error(`CustomQuery.name must be a non-empty string. "${name}" given.`)
  }

  // params can be null
  if (params == null) {
    return
  }

  // if params exists, it must be an object
  if (typeof params !== 'object') {
    throw new Error(`CustomQuery.params must be an object or null. ${typeof params} given.`)
  }
}

/**
 *
 */
export function assertValidCustomCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`CustomCommand must be an object. ${typeof com} given.`)
  }

  const { name, params } = com

  if (typeof name !== 'string' || !name) {
    throw new Error(`CustomCommand.name must be a non-empty string. "${name}" given.`)
  }

  // params can be null
  if (params == null) {
    return
  }

  // if params exists, it must be an object
  if (typeof params !== 'object') {
    throw new Error(`CustomCommand.params must be an object or null. ${typeof params} given.`)
  }
}

/**
 *
 */
export function assertValidLoginCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`LoginCommand must be an object. ${typeof com} given.`)
  }

  const { credentials, entityName } = com

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`LoginCommand.entityName must be a non-empty string. "${entityName}" given.`)
  }

  // credentials must be an object
  if (typeof credentials !== 'object' || com === null) {
    throw new Error(`LoginCommand.credentials must be an object or null. ${typeof credentials} given.`)
  }
  // values in credentials must be strings
  Object.keys(credentials).forEach(credKey => {
    if (credentials[credKey] !== 'string' || !credentials[credKey]) {
      throw new Error(`LoginCommand.credentials['${credKey}'] must be a non-empty string.`)
    }
  })
}

/**
 *
 */
export function assertValidLogoutCommand(com: any): void {
  if (typeof com !== 'object' || com === null) {
    throw new Error(`LogoutCommand must be an object. ${typeof com} given.`)
  }

  const { sessionId, entityName } = com

  if (typeof sessionId !== 'string' || !sessionId) {
    throw new Error(`LogoutCommand.sessionId must be a non-empty string. "${sessionId}" given.`) // ISSUE: sessionId is explicitly shown (but not string...).
  }

  if (typeof entityName !== 'string' || !entityName) {
    throw new Error(`LoginCommand.entityName must be a non-empty string. "${entityName}" given.`)
  }
}

/**
 *
 */
export function assertValidUpdateOperation(ope: any): void {
  if (typeof ope !== 'object' || ope === null) {
    throw new Error(`Update operation must be an object. "${ope}" given.`)
  }
}
<|endoftext|>