<commit_before>import React from 'react';
import ReactDOM from 'react-dom';

import createStore from './store';
import { reducers } from './reducers';
import Provider from './components/util/provider';
import Notebook from './components/notebook';

import {
  setNotebook,
  setExecutionState,
} from './actions';

import { initKeymap } from './keys/keymap';
import { ipcRenderer as ipc } from 'electron';

import { initMenuHandlers } from './menu';

const Rx = require('@reactivex/rxjs');

ipc.on('main:load', (e, launchData) => {
  const { store, dispatch } = createStore({
    notebook: null,
    filename: launchData.filename,
    executionState: 'prestart',
  }, reducers);

  store
    .pluck('channels')
    .distinctUntilChanged()
    .switchMap(channels => {
      if (!channels || !channels.iopub) {
        return Rx.Observable.of('not connected');
      }
      return channels
        .iopub
        .ofMessageType('status')
        .pluck('content', 'execution_state');
    })
    .subscribe(st => {
      dispatch(setExecutionState(st));
    });

  store
    .pluck('executionState')
    .subscribe(executionState => {
      console.warn(`kernel status: ${executionState}`);
      // TODO: Update the app title with the execution state.
    });

  initKeymap(window, dispatch);
  initMenuHandlers(store, dispatch);

  class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {};
      store.subscribe(state => this.setState(state));
    }
    componentDidMount() {
      dispatch(setNotebook(launchData.notebook));
    }
    render() {
      return (
        <Provider rx={{ dispatch, store }}>

            {
              this.state.err &&

{this.state.err.toString()}

            }
            {
              this.state.notebook &&
              <Notebook
                notebook={this.state.notebook}
                channels={this.state.channels}
              />
            }

        </Provider>
      );
    }
  }

  ReactDOM.render(
    <App />,
    document.querySelector('#app')
  );
});
<commit_msg>keep executionState prestart consistent<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

import createStore from './store';
import { reducers } from './reducers';
import Provider from './components/util/provider';
import Notebook from './components/notebook';

import {
  setNotebook,
  setExecutionState,
} from './actions';

import { initKeymap } from './keys/keymap';
import { ipcRenderer as ipc } from 'electron';

import { initMenuHandlers } from './menu';

const Rx = require('@reactivex/rxjs');

ipc.on('main:load', (e, launchData) => {
  const { store, dispatch } = createStore({
    notebook: null,
    filename: launchData.filename,
    executionState: 'not connected',
  }, reducers);

  store
    .pluck('channels')
    .distinctUntilChanged()
    .switchMap(channels => {
      if (!channels || !channels.iopub) {
        return Rx.Observable.of('not connected');
      }
      return channels
        .iopub
        .ofMessageType('status')
        .pluck('content', 'execution_state');
    })
    .subscribe(st => {
      dispatch(setExecutionState(st));
    });

  store
    .pluck('executionState')
    .subscribe(executionState => {
      console.warn(`kernel status: ${executionState}`);
      // TODO: Update the app title with the execution state.
    });

  initKeymap(window, dispatch);
  initMenuHandlers(store, dispatch);

  class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {};
      store.subscribe(state => this.setState(state));
    }
    componentDidMount() {
      dispatch(setNotebook(launchData.notebook));
    }
    render() {
      return (
        <Provider rx={{ dispatch, store }}>

            {
              this.state.err &&

{this.state.err.toString()}

            }
            {
              this.state.notebook &&
              <Notebook
                notebook={this.state.notebook}
                channels={this.state.channels}
              />
            }

        </Provider>
      );
    }
  }

  ReactDOM.render(
    <App />,
    document.querySelector('#app')
  );
});
<|endoftext|>


<commit_before>/*global describe, beforeEach, it*/
'use strict';

var path = require('path');
var temp = require('temp');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-generator').assert;

describe('Test prompt validations', function () {

  var app;

  after(function () {
    temp.cleanup();
  });

  it('App name has invalid character and should fail', function(done){
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'Test App',
        'appDescription': 'Test App Description',
        'githubUser': 'someuser',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;

      app.run({}, function () {
        assert.ok(typeof app.errors !== 'undefined', 'This should fail if the app name contains a space.');
        assert.ok(app.errors.length === 1, 'There should be only 1 error.');
        assert.ok(app.errors[0].name === 'appName', 'The appName property should be wrong.');
        assert.ok(app.errors[0].message === 'The application name should only consist of the following characters a-z, A-Z and 0-9.', 'The appName property should be wrong.');
        done();
      });
    });
  });
});

describe('node-webkit generator', function () {
  var app;

  after(function () {
    temp.cleanup();
  });

  beforeEach(function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'TestApp',
        'appDescription': 'Test App Description',
        'githubUser': 'someuser',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;
      done();
    });
  });

  it('Creates dot files', function (done) {
    var expected = [
      '.jshintrc',
      '.editorconfig'
    ];

    app.run({}, function () {
      assert.ok(typeof app.errors === 'undefined', 'Validation errors in prompt values');
      helpers.assertFile(expected);
      done();
    });
  });

  it('Creates main package files', function (done) {
    var expected = [
      // add files you expect to exist here.
      'Gruntfile.js',
      'package.json',
      'bower.json'
    ];

    app.run({}, function () {
      assert.ok(typeof app.errors === 'undefined', 'Validation errors in prompt values');
      helpers.assertFile(expected);
      done();
    });
  });
});
<commit_msg>* fix errors: * undefined methods * formatting<commit_after>/*global describe, beforeEach, it, after*/
'use strict';

var path = require('path');
var temp = require('temp');
var helpers = require('yeoman-generator').test;
var assert = require('yeoman-generator').assert;

describe('Test prompt validations', function () {

  var app;

  after(function () {
    temp.cleanup();
  });

  it('App name has invalid character and should fail', function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'Test App',
        'appDescription': 'Test App Description',
        'githubUser': 'someuser',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;

      app.run({}, function () {
        assert.ok(typeof app.errors !== 'undefined', 'This should fail if the app name contains a space.');
        assert.ok(app.errors.length === 1, 'There should be only 1 error.');
        assert.ok(app.errors[0].name === 'appName', 'The appName property should be wrong.');
        assert.ok(app.errors[0].message === 'The application name should only consist of the following characters a-z, A-Z and 0-9.', 'The appName property should be wrong.');
        done();
      });
    });
  });
});

describe('node-webkit generator', function () {
  var app;

  after(function () {
    temp.cleanup();
  });

  beforeEach(function (done) {
    var workspace = temp.mkdirSync();
    helpers.testDirectory(workspace, function (err) {
      if (err) {
        return done(err);
      }

      app = helpers.createGenerator('node-webkit:app', [
        path.resolve(__dirname, '../app')
      ]);

      helpers.mockPrompt(app, {
        'appName': 'TestApp',
        'appDescription': 'Test App Description',
        'githubUser': 'someuser',
        downloadNodeWebkit: false,
        'platforms': ['Linux64']
      });
      app.options['skip-install'] = true;
      done();
    });
  });

  it('Creates dot files', function (done) {
    var expected = [
      '.jshintrc',
      '.editorconfig'
    ];

    app.run({}, function () {
      assert.ok(typeof app.errors === 'undefined', 'Validation errors in prompt values');
      helpers.assertFile(expected);
      done();
    });
  });

  it('Creates main package files', function (done) {
    var expected = [
      // add files you expect to exist here.
      'Gruntfile.js',
      'package.json',
      'bower.json'
    ];

    app.run({}, function () {
      assert.ok(typeof app.errors === 'undefined', 'Validation errors in prompt values');
      helpers.assertFile(expected);
      done();
    });
  });
});
<|endoftext|>


<commit_before>var BottomPanel = {
    init: function() {
        // TITLE
        EventSystem.addEventListener('video_info_fetched', function(info) {
            BottomPanel.setTitleText(info.title);
        });

        $('#bottom .info .i').click(function() {
            if (player.currentVideo) {
                $(this).arrowPopup('#video-info-popup', 'down');
            }
        });
        $('#bottom .info .title').bind('contextmenu', function(event) {
            if (player.currentVideo) {
                showResultsItemContextMenu(event, player.currentVideo.listView);
            }
            return false;
        });
        $('#bottom .info .title').click(function() {
            Utils.showWhatIsCurrentlyPlaying();
        });

        // CONTROLS
        $('#bottom .controls .playpause').click(player.playPause);
        $('#bottom .controls .next').click(player.next);
        $('#bottom .controls .prev').click(player.prev);

        // FULLSCREEN is set in FullScreen.js

        // SHUFFLE
        if (new Settings().shuffle) {
            $('#bottom .shuffle').addClass('on');
        }

        $('#bottom .shuffle').click(function() {
            var settings = new Settings(),
                $this = $(this);
            $this.toggleClass('on');
            settings.shuffle = $this.hasClass('on');
            settings.saveLocal();

            if (player.currentVideo && player.currentVideo.listView) {
                Queue.addSiblingsToPlayorder(player.currentVideo.listView);
            }
        });
    },
    setTitleText: function(titleText) {
        $('#bottom .info .i').css({'display': 'inline-block'});
        $('#bottom .info .title')
            .text(titleText)
            .attr('title', titleText);
    }
};
<commit_msg>Added show and hide to BottomPanel<commit_after>var BottomPanel = {
    init: function() {
        // TITLE
        EventSystem.addEventListener('video_info_fetched', function(info) {
            BottomPanel.setTitleText(info.title);
        });

        $('#bottom .info .i').click(function() {
            if (player.currentVideo) {
                $(this).arrowPopup('#video-info-popup', 'down');
            }
        });
        $('#bottom .info .title').bind('contextmenu', function(event) {
            if (player.currentVideo) {
                showResultsItemContextMenu(event, player.currentVideo.listView);
            }
            return false;
        });
        $('#bottom .info .title').click(function() {
            Utils.showWhatIsCurrentlyPlaying();
        });

        // CONTROLS
        $('#bottom .controls .playpause').click(player.playPause);
        $('#bottom .controls .next').click(player.next);
        $('#bottom .controls .prev').click(player.prev);

        // FULLSCREEN is set in FullScreen.js

        // SHUFFLE
        if (new Settings().shuffle) {
            $('#bottom .shuffle').addClass('on');
        }

        $('#bottom .shuffle').click(function() {
            var settings = new Settings(),
                $this = $(this);
            $this.toggleClass('on');
            settings.shuffle = $this.hasClass('on');
            settings.saveLocal();

            if (player.currentVideo && player.currentVideo.listView) {
                Queue.addSiblingsToPlayorder(player.currentVideo.listView);
            }
        });
    },
    setTitleText: function(titleText) {
        $('#bottom .info .i').css({'display': 'inline-block'});
        $('#bottom .info .title')
            .text(titleText)
            .attr('title', titleText);
    },
    show: function() {
        $('#bottom').show();
    },
    hide: function() {
        $('#bottom').hide();
    }
};
<|endoftext|>


<commit_before>var test = require('tape');
var proxyquire = require('proxyquire');
var mockSerial = require('./helpers/mockSerial');
var sinon = require('sinon');

// module to test
var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', {SerialPort: mockSerial});

// default options
var DEF_OPTS1 = {
  debug: false,
  board: 'uno',
  port: ''
};

test('[ Connection ]  - new creation', function(t) {
  t.plan(2);
  var c = new ConnectionTest(DEF_OPTS1);
  t.ok(c.board, 'board exists');
  t.equal(c.board.protocol, 'stk500v1', 'random board property is as expected');
});

test('[ Connection ] ::_listPorts (UNIX)', function(t) {
  t.plan(3);
  var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', { serialport: {
      list: function(callback) {
        callback(null, [
          { comName: '/dev/cu.sierravsp', manufacturer: '', serialNumber: '',
            pnpId: '', locationId: '', vendorId: '', productId: '' },
          { comName: '/dev/cu.Bluetooth-Incoming-Port', manufacturer: '',
            serialNumber: '', pnpId: '', locationId: '', vendorId: '',
            productId: '' },
          { comName: '/dev/cu.usbmodem1421', manufacturer: 'Arduino (www.arduino.cc)',
            serialNumber: '55432333038351F03170', pnpId: '', locationId: '0x14200000',
            vendorId: '0x2341', productId: '0x0043' }
        ]);
      },

      SerialPort: require('./helpers/mockSerial').SerialPort
    }});

  var c = new ConnectionTest(DEF_OPTS1);
  c._listPorts(function(error, ports) {
    t.ok(ports.length, 'got a list of ports');
    t.ok(ports[2]._standardPid, 'added _standardPid property');
    t.error(error, 'no error on listing');
  });
});

test('[ Connection ] ::_listPorts (WINDOWS)', function(t) {
  t.plan(3);
  var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', { serialport: {
      list: function(callback) {
        callback(null, [
          { comName: 'COM3', manufacturer: 'Microsoft', serialNumber: '',
            pnpId: 'USB\\\\VID_2341&PID_0043\\\\55432333038351F03170',
            locationId: '', vendorId: '', productId: '' }
        ]);
      },

      SerialPort: require('./helpers/mockSerial').SerialPort
    }});

  var c = new ConnectionTest(DEF_OPTS1);
  c._listPorts(function(error, ports) {
    t.ok(ports.length, 'got a list of ports');
    t.ok(ports[0]._standardPid, 'added _standardPid property');
    t.error(error, 'no error on listing');
  });
});

test('[ Connection ] ::_sniffPort (UNIX)', function(t) {
  t.plan(3);
  var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', { serialport: {
      list: function(callback) {
        callback(null, [
          { comName: '/dev/cu.sierravsp', manufacturer: '', serialNumber: '',
            pnpId: '', locationId: '', vendorId: '', productId: '' },
          { comName: '/dev/cu.Bluetooth-Incoming-Port', manufacturer: '',
            serialNumber: '', pnpId: '', locationId: '', vendorId: '',
            productId: '' },
          { comName: '/dev/cu.usbmodem1421', manufacturer: 'Arduino (www.arduino.cc)',
            serialNumber: '55432333038351F03170', pnpId: '', locationId: '0x14200000',
            vendorId: '0x2341', productId: '0x0043' }
        ]);
      },

      SerialPort: require('./helpers/mockSerial').SerialPort
    }});

  var c = new ConnectionTest(DEF_OPTS1);
  c._sniffPort(function(error, match) {
    t.ok(match.length, 'board was detected');
    t.equal(match[0].comName, '/dev/cu.usbmodem1421', 'correct comName to match against');
    t.error(error, 'no error on return');
  });
});

test('[ Connection ] ::_sniffPort (WINDOWS)', function(t) {
  t.plan(3);
  var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', { serialport: {
      list: function(callback) {
        callback(null, [
          { comName: 'COM3', manufacturer: 'Microsoft', serialNumber: '',
            pnpId: 'USB\\\\VID_2341&PID_0043\\\\55432333038351F03170',
            locationId: '', vendorId: '', productId: '' }
        ]);
      },

      SerialPort: require('./helpers/mockSerial').SerialPort
    }});

  var c = new ConnectionTest(DEF_OPTS1);
  c._sniffPort(function(error, match) {
    t.ok(match.length, 'board was detected');
    t.equal(match[0].comName, 'COM3', 'correct comName to match against');
    t.error(error, 'no error on return');
  });
});

test('[ Connection ] ::_cycleDTR', function(t) {
  t.plan(2);
  var options = {
    debug: false,
    board: 'uno',
    port: '/dev/cu.usbmodem1421'
  };
  var c = new ConnectionTest(options);
  var stub = sinon.stub(c, '_setDTR', function(bool, timeout, callback) {
    return callback(null);
  });

  c._cycleDTR(function(error) {
    t.ok(stub.calledTwice, '_setDTR was called twice');
    t.error(error, 'no error');
  });
});

test('[ Connection ] ::_pollForPort', function(t) {
  t.plan(1);
  var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', { serialport: {
      list: function(callback) {
        callback(null, [
          { comName: '/dev/cu.sierravsp', manufacturer: '', serialNumber: '',
            pnpId: '', locationId: '', vendorId: '', productId: '' },
          { comName: '/dev/cu.Bluetooth-Incoming-Port', manufacturer: '',
            serialNumber: '', pnpId: '', locationId: '', vendorId: '',
            productId: '' },
          { comName: '/dev/cu.usbmodem1421', manufacturer: 'Arduino (www.arduino.cc)',
            serialNumber: '55432333038351F03170', pnpId: '', locationId: '0x14200000',
            vendorId: '0x2341', productId: '0x0043' }
        ]);
      },

      SerialPort: require('./helpers/mockSerial').SerialPort
    }});

  var options = {
    debug: false,
    board: 'uno',
    port: '/dev/cu.usbmodem1421'
  };

  var c = new ConnectionTest(options);
  c._pollForPort(function(error) {
    t.error(error, 'no error on polling result');
  });
});
<commit_msg>fix indentation<commit_after>var test = require('tape');
var proxyquire = require('proxyquire');
var mockSerial = require('./helpers/mockSerial');
var sinon = require('sinon');

// module to test
var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', {SerialPort: mockSerial});

// default options
var DEF_OPTS1 = {
  debug: false,
  board: 'uno',
  port: ''
};

test('[ Connection ]  - new creation', function(t) {
  t.plan(2);
  var c = new ConnectionTest(DEF_OPTS1);
  t.ok(c.board, 'board exists');
  t.equal(c.board.protocol, 'stk500v1', 'random board property is as expected');
});

test('[ Connection ] ::_listPorts (UNIX)', function(t) {
  t.plan(3);
  var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', { serialport: {
      list: function(callback) {
        callback(null, [
          { comName: '/dev/cu.sierravsp', manufacturer: '', serialNumber: '',
            pnpId: '', locationId: '', vendorId: '', productId: '' },
          { comName: '/dev/cu.Bluetooth-Incoming-Port', manufacturer: '',
            serialNumber: '', pnpId: '', locationId: '', vendorId: '',
            productId: '' },
          { comName: '/dev/cu.usbmodem1421', manufacturer: 'Arduino (www.arduino.cc)',
            serialNumber: '55432333038351F03170', pnpId: '', locationId: '0x14200000',
            vendorId: '0x2341', productId: '0x0043' }
        ]);
      },

      SerialPort: require('./helpers/mockSerial').SerialPort
    }});

  var c = new ConnectionTest(DEF_OPTS1);
  c._listPorts(function(error, ports) {
    t.ok(ports.length, 'got a list of ports');
    t.ok(ports[2]._standardPid, 'added _standardPid property');
    t.error(error, 'no error on listing');
  });
});

test('[ Connection ] ::_listPorts (WINDOWS)', function(t) {
  t.plan(3);
  var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', { serialport: {
      list: function(callback) {
        callback(null, [
          { comName: 'COM3', manufacturer: 'Microsoft', serialNumber: '',
            pnpId: 'USB\\\\VID_2341&PID_0043\\\\55432333038351F03170',
            locationId: '', vendorId: '', productId: '' }
        ]);
      },

      SerialPort: require('./helpers/mockSerial').SerialPort
    }});

  var c = new ConnectionTest(DEF_OPTS1);
  c._listPorts(function(error, ports) {
    t.ok(ports.length, 'got a list of ports');
    t.ok(ports[0]._standardPid, 'added _standardPid property');
    t.error(error, 'no error on listing');
  });
});

test('[ Connection ] ::_sniffPort (UNIX)', function(t) {
  t.plan(3);
  var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', { serialport: {
      list: function(callback) {
        callback(null, [
          { comName: '/dev/cu.sierravsp', manufacturer: '', serialNumber: '',
            pnpId: '', locationId: '', vendorId: '', productId: '' },
          { comName: '/dev/cu.Bluetooth-Incoming-Port', manufacturer: '',
            serialNumber: '', pnpId: '', locationId: '', vendorId: '',
            productId: '' },
          { comName: '/dev/cu.usbmodem1421', manufacturer: 'Arduino (www.arduino.cc)',
            serialNumber: '55432333038351F03170', pnpId: '', locationId: '0x14200000',
            vendorId: '0x2341', productId: '0x0043' }
        ]);
      },

      SerialPort: require('./helpers/mockSerial').SerialPort
    }});

  var c = new ConnectionTest(DEF_OPTS1);
  c._sniffPort(function(error, match) {
    t.ok(match.length, 'board was detected');
    t.equal(match[0].comName, '/dev/cu.usbmodem1421', 'correct comName to match against');
    t.error(error, 'no error on return');
  });
});

test('[ Connection ] ::_sniffPort (WINDOWS)', function(t) {
  t.plan(3);
  var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', { serialport: {
    list: function(callback) {
      callback(null, [
        { comName: 'COM3', manufacturer: 'Microsoft', serialNumber: '',
          pnpId: 'USB\\\\VID_2341&PID_0043\\\\55432333038351F03170',
          locationId: '', vendorId: '', productId: '' }
      ]);
    },

    SerialPort: require('./helpers/mockSerial').SerialPort
  }});

  var c = new ConnectionTest(DEF_OPTS1);
  c._sniffPort(function(error, match) {
    t.ok(match.length, 'board was detected');
    t.equal(match[0].comName, 'COM3', 'correct comName to match against');
    t.error(error, 'no error on return');
  });
});

test('[ Connection ] ::_cycleDTR', function(t) {
  t.plan(2);
  var options = {
    debug: false,
    board: 'uno',
    port: '/dev/cu.usbmodem1421'
  };
  var c = new ConnectionTest(options);
  var stub = sinon.stub(c, '_setDTR', function(bool, timeout, callback) {
    return callback(null);
  });

  c._cycleDTR(function(error) {
    t.ok(stub.calledTwice, '_setDTR was called twice');
    t.error(error, 'no error');
  });
});

test('[ Connection ] ::_pollForPort', function(t) {
  t.plan(1);
  var ConnectionTest = proxyquire.noCallThru().load('../lib/connection', { serialport: {
    list: function(callback) {
      callback(null, [
        { comName: '/dev/cu.sierravsp', manufacturer: '', serialNumber: '',
          pnpId: '', locationId: '', vendorId: '', productId: '' },
        { comName: '/dev/cu.Bluetooth-Incoming-Port', manufacturer: '',
          serialNumber: '', pnpId: '', locationId: '', vendorId: '',
          productId: '' },
        { comName: '/dev/cu.usbmodem1421', manufacturer: 'Arduino (www.arduino.cc)',
          serialNumber: '55432333038351F03170', pnpId: '', locationId: '0x14200000',
          vendorId: '0x2341', productId: '0x0043' }
      ]);
    },

    SerialPort: require('./helpers/mockSerial').SerialPort
  }});

  var options = {
    debug: false,
    board: 'uno',
    port: '/dev/cu.usbmodem1421'
  };

  var c = new ConnectionTest(options);
  c._pollForPort(function(error) {
    t.error(error, 'no error on polling result');
  });
});
<|endoftext|>


<commit_before>angular.module('oauth.withings', ['oauth.utils'])
  .factory('$withings', withings);

function withings($q, $http, $cordovaOauthUtility) {
  return { signin: oauthWithings };

  /*
   * Sign into the Withings service
   * Note that this service requires jsSHA for generating HMAC-SHA1 Oauth 1.0 signatures
   *
   * @param    string clientId
   * @param    string clientSecret
   * @return   promise
   */
  function oauthWithings(clientId, clientSecret) {
    var deferred = $q.defer();
    if(window.cordova) {
      var cordovaMetadata = cordova.require("cordova/plugin_list").metadata;
      if($cordovaOauthUtility.isInAppBrowserInstalled(cordovaMetadata) === true) {
        if(typeof jsSHA !== "undefined") {

          // Step 1 : get a oAuth "request token"
          var oauthObject = $cordovaOauthUtility.generateOauthParametersInstance(clientId);
          oauthObject.oauth_callback = 'http://localhost/callback';

          var requestTokenUrlBase = "https://oauth.withings.com/account/request_token";
          var signatureObj = $cordovaOauthUtility.createSignature("GET", requestTokenUrlBase, {}, oauthObject, clientSecret);
          oauthObject.oauth_signature = signatureObj.signature;

          var requestTokenParameters = $cordovaOauthUtility.generateUrlParameters(oauthObject);

          $http({method: "get", url: requestTokenUrlBase + "?" + requestTokenParameters })
            .success(function(requestTokenResult) {

              // Step 2 : End-user authorization
              var parameterMap = $cordovaOauthUtility.parseResponseParameters(requestTokenResult);
              if(parameterMap.hasOwnProperty("oauth_token") === false) {
                deferred.reject("Oauth request token was not received");
              }
              var oauthObject = $cordovaOauthUtility.generateOauthParametersInstance(clientId);
              oauthObject.oauth_token = parameterMap.oauth_token;

              // used in step 3
              var oauthTokenSecret = parameterMap.oauth_token_secret;

              var authorizeUrlBase = "https://oauth.withings.com/account/authorize";
              var signatureObj = $cordovaOauthUtility.createSignature("GET", authorizeUrlBase, {}, oauthObject, clientSecret);
              oauthObject.oauth_signature = signatureObj.signature;

              var authorizeParameters = $cordovaOauthUtility.generateUrlParameters(oauthObject);
              var browserRef = window.open(authorizeUrlBase + '?' + authorizeParameters, '_blank', 'location=no,clearsessioncache=yes,clearcache=yes');

              // STEP 3: User Data Access token
              browserRef.addEventListener('loadstart', function(event) {
                if((event.url).indexOf("http://localhost/callback") === 0) {
                  var callbackResponse = (event.url).split("?")[1];
                  parameterMap = $cordovaOauthUtility.parseResponseParameters(callbackResponse);
                  if(parameterMap.hasOwnProperty("oauth_verifier") === false) {
                    deferred.reject("Browser authentication failed to complete.  No oauth_verifier was returned");
                  }

                  var oauthObject = $cordovaOauthUtility.generateOauthParametersInstance(clientId);
                  oauthObject.oauth_token = parameterMap.oauth_token;

                  var accessTokenUrlBase = "https://oauth.withings.com/account/access_token";
                  var signatureObj = $cordovaOauthUtility.createSignature("GET", accessTokenUrlBase, {}, oauthObject, clientSecret, oauthTokenSecret);
                  oauthObject.oauth_signature = signatureObj.signature;

                  var accessTokenParameters = $cordovaOauthUtility.generateUrlParameters(oauthObject);

                  $http({method: "get", url: accessTokenUrlBase + '?' + accessTokenParameters})
                    .success(function(result) {
                      var parameterMap = $cordovaOauthUtility.parseResponseParameters(result);
                      if(parameterMap.hasOwnProperty("oauth_token_secret") === false) {
                        deferred.reject("Oauth access token was not received");
                      }
                      deferred.resolve(parameterMap);
                    })
                    .error(function(error) {
                      deferred.reject(error);
                    })
                    .finally(function() {
                      setTimeout(function() {
                        browserRef.close();
                      }, 10);
                    });
                }
              });
              browserRef.addEventListener('exit', function(event) {
                deferred.reject("The sign in flow was canceled");
              });
            })
            .error(function(error) {
                deferred.reject(error);
            });
        } else {
            deferred.reject("Missing jsSHA JavaScript library");
        }
      } else {
        deferred.reject("Could not find InAppBrowser plugin");
      }
    } else {
      deferred.reject("Cannot authenticate via a web browser");
    }

    return deferred.promise;
  }
}

withings.$inject = ['$q', '$http', '$cordovaOauthUtility'];
<commit_msg>Improving withings oauth code<commit_after>angular.module('oauth.withings', ['oauth.utils'])
  .factory('$withings', withings);

function withings($q, $http, $cordovaOauthUtility) {
  return { signin: oauthWithings };

  /*
   * Sign into the Withings service
   * Note that this service requires jsSHA for generating HMAC-SHA1 Oauth 1.0 signatures
   *
   * @param    string clientId
   * @param    string clientSecret
   * @return   promise
   */
  function oauthWithings(clientId, clientSecret) {
    var deferred = $q.defer();
    if(window.cordova) {
      var cordovaMetadata = cordova.require("cordova/plugin_list").metadata;
      if($cordovaOauthUtility.isInAppBrowserInstalled(cordovaMetadata) === true) {
        if(typeof jsSHA !== "undefined") {

          // Step 1 : get a oAuth "request token"
          var oauthObject = $cordovaOauthUtility.generateOauthParametersInstance(clientId);
          oauthObject.oauth_callback = 'http://localhost/callback';

          var requestTokenUrlBase = "https://oauth.withings.com/account/request_token";
          var signatureObj = $cordovaOauthUtility.createSignature("GET", requestTokenUrlBase, {}, oauthObject, clientSecret);
          oauthObject.oauth_signature = signatureObj.signature;

          var requestTokenParameters = $cordovaOauthUtility.generateUrlParameters(oauthObject);

          $http({method: "get", url: requestTokenUrlBase + "?" + requestTokenParameters })
            .success(function(requestTokenResult) {

              // Step 2 : End-user authorization
              var parameterMap = $cordovaOauthUtility.parseResponseParameters(requestTokenResult);
              if(!parameterMap.oauth_token) {
                deferred.reject("Oauth request token was not received");
              }
              var oauthObject = $cordovaOauthUtility.generateOauthParametersInstance(clientId);
              oauthObject.oauth_token = parameterMap.oauth_token;

              // used in step 3
              var oauthTokenSecret = parameterMap.oauth_token_secret;

              var authorizeUrlBase = "https://oauth.withings.com/account/authorize";
              var signatureObj = $cordovaOauthUtility.createSignature("GET", authorizeUrlBase, {}, oauthObject, clientSecret);
              oauthObject.oauth_signature = signatureObj.signature;

              var authorizeParameters = $cordovaOauthUtility.generateUrlParameters(oauthObject);
              var browserRef = window.open(authorizeUrlBase + '?' + authorizeParameters, '_blank', 'location=no,clearsessioncache=yes,clearcache=yes');

              // STEP 3: User Data Access token
              browserRef.addEventListener('loadstart', function(event) {
                if((event.url).indexOf("http://localhost/callback") === 0) {
                  var callbackResponse = (event.url).split("?")[1];
                  parameterMap = $cordovaOauthUtility.parseResponseParameters(callbackResponse);
                  if(!parameterMap.oauth_verifier) {
                    deferred.reject("Browser authentication failed to complete.  No oauth_verifier was returned");
                  }

                  var oauthObject = $cordovaOauthUtility.generateOauthParametersInstance(clientId);
                  oauthObject.oauth_token = parameterMap.oauth_token;

                  var accessTokenUrlBase = "https://oauth.withings.com/account/access_token";
                  var signatureObj = $cordovaOauthUtility.createSignature("GET", accessTokenUrlBase, {}, oauthObject, clientSecret, oauthTokenSecret);
                  oauthObject.oauth_signature = signatureObj.signature;

                  var accessTokenParameters = $cordovaOauthUtility.generateUrlParameters(oauthObject);

                  $http({method: "get", url: accessTokenUrlBase + '?' + accessTokenParameters})
                    .success(function(result) {
                      var parameterMap = $cordovaOauthUtility.parseResponseParameters(result);
                      if(!parameterMap.oauth_token_secret) {
                        deferred.reject("Oauth access token was not received");
                      }
                      deferred.resolve(parameterMap);
                    })
                    .error(function(error) {
                      deferred.reject(error);
                    })
                    .finally(function() {
                      setTimeout(function() {
                        browserRef.close();
                      }, 10);
                    });
                }
              });
              browserRef.addEventListener('exit', function(event) {
                deferred.reject("The sign in flow was canceled");
              });
            })
            .error(function(error) {
                deferred.reject(error);
            });
        } else {
            deferred.reject("Missing jsSHA JavaScript library");
        }
      } else {
        deferred.reject("Could not find InAppBrowser plugin");
      }
    } else {
      deferred.reject("Cannot authenticate via a web browser");
    }

    return deferred.promise;
  }
}

withings.$inject = ['$q', '$http', '$cordovaOauthUtility'];
<|endoftext|>


<commit_before>let foo = 1;
export { foo as default };
foo = 2;
<commit_msg>let -> var<commit_after>var foo = 1;
export { foo as default };
foo = 2;
<|endoftext|>


<commit_before>var assert = require('assert'),
    sys = require('sys'),
    fs = require('fs'),
    path = require('path'),
    nodeunit = require('../lib/nodeunit');

var setup = function (fn) {
    return function (test) {
        process.chdir(__dirname);
        require.paths.push(__dirname);
        var env = {
            mock_module1: require('./fixtures/mock_module1'),
            mock_module2: require('./fixtures/mock_module2'),
            mock_module3: require('./fixtures/dir/mock_module3'),
            mock_module4: require('./fixtures/dir/mock_module4')
        };
        fn.call(env, test);
    };
};

exports.testRunFiles = setup(function (test) {
    test.expect(24);
    var runModule_copy = nodeunit.runModule;

    var runModule_calls = [];
    var modules = [];

    var opts = {
        moduleStart: function () {
            return 'moduleStart';
        },
        testDone: function () {
            return 'testDone';
        },
        testStart: function () {
            return 'testStart';
        },
        log: function () {
            return 'log';
        },
        done: function (assertions) {
            test.equals(assertions.failures(), 0, 'failures');
            test.equals(assertions.length, 4, 'length');
            test.ok(typeof assertions.duration === "number");

            var called_with = function (name) {
                return runModule_calls.some(function (m) {
                    return m.name === name;
                });
            };
            test.ok(called_with('mock_module1'), 'mock_module1 ran');
            test.ok(called_with('mock_module2'), 'mock_module2 ran');
            test.ok(called_with('mock_module3'), 'mock_module3 ran');
            test.ok(called_with('mock_module4'), 'mock_module4 ran');
            test.equals(runModule_calls.length, 4);

            nodeunit.runModule = runModule_copy;
            test.done();
        }
    };

    nodeunit.runModule = function (name, mod, options, callback) {
        test.equals(options.testDone, opts.testDone);
        test.equals(options.testStart, opts.testStart);
        test.equals(options.log, opts.log);
        test.ok(typeof name === "string");
        runModule_calls.push(mod);
        var m = [{failed: function () {
            return false;
        }}];
        modules.push(m);
        callback(null, m);
    };

    nodeunit.runFiles(
        ['fixtures/mock_module1.js', 'fixtures/mock_module2.js', 'fixtures/dir'],
        opts
    );
});

exports.testRunFilesEmpty = function (test) {
    test.expect(3);
    nodeunit.runFiles([], {
        moduleStart: function () {
            test.ok(false, 'should not be called');
        },
        testDone: function () {
            test.ok(false, 'should not be called');
        },
        testStart: function () {
            test.ok(false, 'should not be called');
        },
        log: function () {
            test.ok(false, 'should not be called');
        },
        done: function (assertions) {
            test.equals(assertions.failures(), 0, 'failures');
            test.equals(assertions.length, 0, 'length');
            test.ok(typeof assertions.duration === "number");
            test.done();
        }
    });
};

exports.testEmptyDir = function (test) {
    var dir2 = __dirname + '/fixtures/dir2';

    // git doesn't like empty directories, so we have to create one
    path.exists(dir2, function (exists) {
        if (!exists) {
            fs.mkdirSync(dir2, 777);
        }

        // runFiles on empty directory:
        nodeunit.runFiles([dir2], {
            moduleStart: function () {
                test.ok(false, 'should not be called');
            },
            testDone: function () {
                test.ok(false, 'should not be called');
            },
            testStart: function () {
                test.ok(false, 'should not be called');
            },
            log: function () {
                test.ok(false, 'should not be called');
            },
            done: function (assertions) {
                test.equals(assertions.failures(), 0, 'failures');
                test.equals(assertions.length, 0, 'length');
                test.ok(typeof assertions.duration === "number");
                test.done();
            }
        });
    });
};

var CoffeeScript;
try {
    CoffeeScript = require('coffee-script');
} catch (e) {
}

if (CoffeeScript) {
    exports.testCoffeeScript = function (test) {
        process.chdir(__dirname);
        require.paths.push(__dirname);
        var env = {
            mock_coffee_module: require('./fixtures/coffee/mock_coffee_module')
        };

        test.expect(9);
        var runModule_copy = nodeunit.runModule;

        var runModule_calls = [];
        var modules = [];

        var opts = {
            moduleStart: function () {
                return 'moduleStart';
            },
            testDone: function () {
                return 'testDone';
            },
            testStart: function () {
                return 'testStart';
            },
            log: function () {
                return 'log';
            },
            done: function (assertions) {
                test.equals(assertions.failures(), 0, 'failures');
                test.equals(assertions.length, 1, 'length');
                test.ok(typeof assertions.duration === "number");

                var called_with = function (name) {
                    return runModule_calls.some(function (m) {
                        return m.name === name;
                    });
                };
                test.ok(
                    called_with('mock_coffee_15'),
                    'mock_coffee_module ran'
                );
                test.equals(runModule_calls.length, 1);

                nodeunit.runModule = runModule_copy;
                test.done();
            }
        };

        nodeunit.runModule = function (name, mod, options, callback) {
            test.equals(options.testDone, opts.testDone);
            test.equals(options.testStart, opts.testStart);
            test.equals(options.log, opts.log);
            test.ok(typeof name === "string");
            runModule_calls.push(mod);
            var m = [{failed: function () {
                return false;
            }}];
            modules.push(m);
            callback(null, m);
        };

        nodeunit.runFiles(
            ['fixtures/coffee/mock_coffee_module.coffee'],
            opts
        );
    };
}
<commit_msg>update permissions when creating fixtures dir2<commit_after>var assert = require('assert'),
    sys = require('sys'),
    fs = require('fs'),
    path = require('path'),
    nodeunit = require('../lib/nodeunit');

var setup = function (fn) {
    return function (test) {
        process.chdir(__dirname);
        require.paths.push(__dirname);
        var env = {
            mock_module1: require('./fixtures/mock_module1'),
            mock_module2: require('./fixtures/mock_module2'),
            mock_module3: require('./fixtures/dir/mock_module3'),
            mock_module4: require('./fixtures/dir/mock_module4')
        };
        fn.call(env, test);
    };
};

exports.testRunFiles = setup(function (test) {
    test.expect(24);
    var runModule_copy = nodeunit.runModule;

    var runModule_calls = [];
    var modules = [];

    var opts = {
        moduleStart: function () {
            return 'moduleStart';
        },
        testDone: function () {
            return 'testDone';
        },
        testStart: function () {
            return 'testStart';
        },
        log: function () {
            return 'log';
        },
        done: function (assertions) {
            test.equals(assertions.failures(), 0, 'failures');
            test.equals(assertions.length, 4, 'length');
            test.ok(typeof assertions.duration === "number");

            var called_with = function (name) {
                return runModule_calls.some(function (m) {
                    return m.name === name;
                });
            };
            test.ok(called_with('mock_module1'), 'mock_module1 ran');
            test.ok(called_with('mock_module2'), 'mock_module2 ran');
            test.ok(called_with('mock_module3'), 'mock_module3 ran');
            test.ok(called_with('mock_module4'), 'mock_module4 ran');
            test.equals(runModule_calls.length, 4);

            nodeunit.runModule = runModule_copy;
            test.done();
        }
    };

    nodeunit.runModule = function (name, mod, options, callback) {
        test.equals(options.testDone, opts.testDone);
        test.equals(options.testStart, opts.testStart);
        test.equals(options.log, opts.log);
        test.ok(typeof name === "string");
        runModule_calls.push(mod);
        var m = [{failed: function () {
            return false;
        }}];
        modules.push(m);
        callback(null, m);
    };

    nodeunit.runFiles(
        ['fixtures/mock_module1.js', 'fixtures/mock_module2.js', 'fixtures/dir'],
        opts
    );
});

exports.testRunFilesEmpty = function (test) {
    test.expect(3);
    nodeunit.runFiles([], {
        moduleStart: function () {
            test.ok(false, 'should not be called');
        },
        testDone: function () {
            test.ok(false, 'should not be called');
        },
        testStart: function () {
            test.ok(false, 'should not be called');
        },
        log: function () {
            test.ok(false, 'should not be called');
        },
        done: function (assertions) {
            test.equals(assertions.failures(), 0, 'failures');
            test.equals(assertions.length, 0, 'length');
            test.ok(typeof assertions.duration === "number");
            test.done();
        }
    });
};

exports.testEmptyDir = function (test) {
    var dir2 = __dirname + '/fixtures/dir2';

    // git doesn't like empty directories, so we have to create one
    path.exists(dir2, function (exists) {
        if (!exists) {
            fs.mkdirSync(dir2, 0777);
        }

        // runFiles on empty directory:
        nodeunit.runFiles([dir2], {
            moduleStart: function () {
                test.ok(false, 'should not be called');
            },
            testDone: function () {
                test.ok(false, 'should not be called');
            },
            testStart: function () {
                test.ok(false, 'should not be called');
            },
            log: function () {
                test.ok(false, 'should not be called');
            },
            done: function (assertions) {
                test.equals(assertions.failures(), 0, 'failures');
                test.equals(assertions.length, 0, 'length');
                test.ok(typeof assertions.duration === "number");
                test.done();
            }
        });
    });
};

var CoffeeScript;
try {
    CoffeeScript = require('coffee-script');
} catch (e) {
}

if (CoffeeScript) {
    exports.testCoffeeScript = function (test) {
        process.chdir(__dirname);
        require.paths.push(__dirname);
        var env = {
            mock_coffee_module: require('./fixtures/coffee/mock_coffee_module')
        };

        test.expect(9);
        var runModule_copy = nodeunit.runModule;

        var runModule_calls = [];
        var modules = [];

        var opts = {
            moduleStart: function () {
                return 'moduleStart';
            },
            testDone: function () {
                return 'testDone';
            },
            testStart: function () {
                return 'testStart';
            },
            log: function () {
                return 'log';
            },
            done: function (assertions) {
                test.equals(assertions.failures(), 0, 'failures');
                test.equals(assertions.length, 1, 'length');
                test.ok(typeof assertions.duration === "number");

                var called_with = function (name) {
                    return runModule_calls.some(function (m) {
                        return m.name === name;
                    });
                };
                test.ok(
                    called_with('mock_coffee_15'),
                    'mock_coffee_module ran'
                );
                test.equals(runModule_calls.length, 1);

                nodeunit.runModule = runModule_copy;
                test.done();
            }
        };

        nodeunit.runModule = function (name, mod, options, callback) {
            test.equals(options.testDone, opts.testDone);
            test.equals(options.testStart, opts.testStart);
            test.equals(options.log, opts.log);
            test.ok(typeof name === "string");
            runModule_calls.push(mod);
            var m = [{failed: function () {
                return false;
            }}];
            modules.push(m);
            callback(null, m);
        };

        nodeunit.runFiles(
            ['fixtures/coffee/mock_coffee_module.coffee'],
            opts
        );
    };
}
<|endoftext|>


<commit_before>/*global window: false */
module.exports = function(ngModule) {
  'use strict';

  ngModule.service('Pouch', function ($rootScope, $q, rooConfig, LocalStorageService) {

    var dbCache = {};

    function getDB(name) {
      if(!dbCache[name]){
        dbCache[name] = new PouchDB(name, rooConfig.getDbOptions());
      }
      return dbCache[name];
    }

    /**
     * Function to update the records that are read-only
     * from the server with whatever changes have been
     * made on the client but have not yet been synced
     * to the server, for ui display purposes. This
     * is called currently from the MasterCtrl, so
     * basically on app load. change_id is dbname::id;
     * so, for example, looks something like this:
     *"gemini_cushion_fist::WO-20150226-2949689"
     */
    function shimRecords(downDbName, downDocs) {
      var deferred = $q.defer();
      var promises = [];
      var jorgeNames = rooConfig.getUpDbs();
      // Loop through all of the write databases
      _.each(jorgeNames, function (jorgeName) {
        // Get all the documents in the current write db
        getDB(jorgeName).allDocs({
          include_docs: true
        })
          .then(function (jorgeDocs) {
            if (jorgeDocs.total_rows > 0) {
              _.each(downDocs.rows, function(doc) {
                // If the current write db has any documents, loop through
                // them and see if any of the documents have a change_id that
                // matches the current read-only db
                _.each(jorgeDocs.rows, function (row) {
                  var d = $q.defer();
                  var change_id = row.doc.change_id;
                  var split = change_id.split('::');
                  var dbName = split[0];
                  var id = split[1];
                  if (dbName === downDbName) {
                    // Find if any document matches
                    if(doc.id === id) {
                      _.extend(doc.doc, JSON.parse(row.doc.change));

                      // Handle attachments
                      if(row.doc._attachments) {
                        if(doc._attachments) {
                          _.extend(doc._attachments, row.doc._attachments);
                        }
                        else {
                          doc._attachments = row.doc._attachments;
                        }
                      }
                    }
                  }
                  d.resolve(doc);
                  promises.push(d.promise);
                });
              });
            }
            $q.all(promises).then(function () {
              deferred.resolve(downDocs);
            });
          });
      });

      return deferred.promise;
    }

    /**
     * Function to update a given read-only record
     * from the server with whatever changes have been
     * made on the client but have not yet been synced
     * to the server, for ui display purposes. This
     * is called currently from the MasterCtrl, so
     * basically on app load. change_id is dbname::id;
     * so, for example, looks something like this:
     * "gemini_cushion_fist::WO-20150226-2949689"
     */
    function shimRecord(downDbName, downDoc) {
      var deferred = $q.defer();
      var jorgeNames = rooConfig.getUpDbs();
      // Loop through all of the write databases
      _.each(jorgeNames, function (jorgeName) {
        // Get all the documents in the current write db
        getDB(jorgeName).allDocs({
          include_docs: true
        }).then(function (jorgeDocs) {
            if (jorgeDocs.total_rows > 0) {
              // The the current write db has any documents, loop through
              // them and see if any of the documents have a change_id that
              // matches the current read-only db
              _.each(jorgeDocs.rows, function (row) {
                var change_id = row.doc.change_id;
                var split = change_id.split('::');
                var dbName = split[0];
                var id = split[1];
                if (dbName === downDbName) {
                  // Find if any document matches
                  if(downDoc._id === id) {
                    _.extend(downDoc, JSON.parse(row.doc.change));

                    // Handle attachments
                    if(row.doc._attachments) {
                      if(downDoc._attachments) {
                        _.extend(downDoc._attachments, row.doc._attachments);
                      }
                      else {
                        downDoc._attachments = row.doc._attachments;
                      }
                    }
                  }
                }
              });
            }
            deferred.resolve(downDoc);
          });
        });
      return deferred.promise;
    }

  return function (db) {

    this.db = db;

    this.getAll = function (options) {
      var self = this;
      var deferred = $q.defer();

      var o = _.extend({include_docs: true}, options);

      getDB(self.db)
      .allDocs(o)
      .then(function (docs) {
        return shimRecords(self.db, docs);
      }).then(function (docs) {
        deferred.resolve(_.pluck(docs.rows, 'doc'));
      });

      return deferred.promise;
    };

    this.query = function(query, options){
      var self = this;
      var deferred = $q.defer();

      var o = options || {};

      getDB(self.db).query(query, o)
      .then(function (doc) {
        return shimRecord(self.db, doc);
      }).then(function (doc) {
        deferred.resolve(doc);
      });
      return deferred.promise;
    };

    this.getAll = function () {
      var self = this;
      var deferred = $q.defer();
      getDB(self.db).allDocs({
        include_docs: true
      }).then(function (docs) {
        return shimRecords(self.db, docs);
      }).then(function (docs) {
        deferred.resolve(_.pluck(docs.rows, 'doc'));
      });
      return deferred.promise;
    };

    this.get = function (docId) {
      var self = this;
      var deferred = $q.defer();
      getDB(self.db).get(docId, {
        include_docs: true
      }).then(function (doc) {
        return shimRecord(self.db, doc);
      }).then(function (doc) {
        deferred.resolve(doc);
      });
      return deferred.promise;
    };

      /**
       * Retrieve attachment's local url
       * @param {string} docId - Document's id were the attachment exists.
       * @param {string} attrId - The id for the attachment itself.
       */
      this.getAttachment = function (docId, attrId) {
        var self = this;
        var deferred = $q.defer();
        var URL = window.URL;
        getDB(self.db).getAttachment(docId, attrId)
        .then(function (blob) {
          var url = URL.createObjectURL(blob);
          deferred.resolve(url);
        });
        return deferred.promise;
      };

      this.putEntry = function(originTable, originId, changes, method, endpoint, data, headers, user, attachment) {
        var entry = {
            _id: new moment().unix().toString(),
            change_id: '' + originTable + '::' + originId,
            change: JSON.stringify(changes),
            method: method,
            endpoint: endpoint,
            data: data,
            headers: headers,
            user: user
          },
          self = this,
          db = getDB(self.db);

        return db.put(entry)
        .then(function(doc) {
          if(attachment){
            return db.putAttachment(entry._id, attachment.name, doc.rev, attachment, attachment.type);
          }
        });
      };

      /**
       * Replicate db with predefined CouchDB
       * @param {object} user - Any User object to be passed into getParams.
       * @param {object} options - functions to determine params and filters.
       */
      this.replicateDB = function(user, opts) {
        var self = this;

        if(rooConfig.getOptions().destoryOnSync){
            console.log('removing table', self.db);
	          getDB(self.db)
              .destroy()
              .then(function(){
                self.performReplication(user, opts);
              });
	        }else{
            self.performReplication(user, opts);
          }
      };

      this.performReplication = function(user, opts){
          var self = this;
          var deferred = $q.defer();

          // Initialize the remote and local databases
          var remote = new PouchDB(rooConfig.getCouchConfig().couchUrl + '/' + self.db);
          var local = getDB(self.db);
          console.log('Replicating', self.db);
          var replicationOptions = _.extend({batch_size: 5}, opts);

          if(opts.getParams){
            replicationOptions.query_params = opts.getParams(user);
          }

          // Perform replication
          console.time(self.db);
          $rootScope.$broadcast('replicating', true, self.db);
          var rep = local.replicate.from(remote, replicationOptions)
            .on('complete', function (result) {
              console.timeEnd(self.db);
	            $rootScope.$broadcast('replicating', false, self.db);
              rep.cancel();
              try {
                // Make an entry in the logs
                LocalStorageService.addEntryToLog(user.employeeID, self.db, result);
                deferred.resolve();
              } catch(error) {
                console.log(error);
                deferred.reject(error);
              }
              return deferred.promise;
            })
            .on('paused', function(){
              rep.cancel();
            });
        };

      this.performSync = function(user, opts){
        var self = this;
        var deferred = $q.defer();

        console.log('Syncing', self.db);
        var syncOptions = _.extend({batch_size: 5, live: true}, opts);

        if(opts.getParams){
          syncOptions.query_params = opts.getParams(user);
        }

        // Perform replication
        var sync = PouchDB.sync(self.db, rooConfig.getCouchConfig().couchUrl + '/' + self.db, syncOptions)
          .on('complete', function (result) {
            try {
              // Make an entry in the logs
              LocalStorageService.addEntryToLog(user.employeeID, self.db, result);
              deferred.resolve();
            } catch(error) {
              console.log(error);
              deferred.reject(error);
            }
            return deferred.promise;
          })
            .on('paused', function(){
              sync.cancel();
            });
      };

      this.update = function(db, obj, id) {
        var deferred = $q.defer();
        var cushiondb = getDB(db);
        cushiondb.get(id).then(function success(doc) {
          var newDoc = _.extend(doc, obj);
          cushiondb.put(newDoc).then(function success(result) {
            deferred.resolve(result);
          }, function error(result) {
            deferred.reject(result);
          });
        }, function error(result) {
          deferred.reject(result);
        });
        return deferred.promise;
      };

      this.sendJorgeDB = function(db, user) {
        console.log('syncing ' + db + ' for user ' + user.displayName);
        var deferred = $q.defer();
        var promises = [];
        // Do some stuff here.
        getDB(db).allDocs({
          include_docs: true
        }).then(function (docs) {
          // Make an entry in the logs
          _.forEach(docs.rows, function(row) {
            promises.push(LocalStorageService.addEntryToLog(user.employeeID, db, row));
          });

          $q.all(promises).then(function(result) {
            deferred.resolve(result);
          });
        });
        return deferred.promise;
      };
    };

  });
};
<commit_msg>Put back all the catches that got blown away on merge<commit_after>/*global window: false */
module.exports = function(ngModule) {
  'use strict';

  ngModule.service('Pouch', function ($rootScope, $q, rooConfig, LocalStorageService) {

    var dbCache = {};

    function getDB(name) {
      if(!dbCache[name]){
        dbCache[name] = new PouchDB(name, rooConfig.getDbOptions());
      }
      return dbCache[name];
    }

    /**
     * Function to update the records that are read-only
     * from the server with whatever changes have been
     * made on the client but have not yet been synced
     * to the server, for ui display purposes. This
     * is called currently from the MasterCtrl, so
     * basically on app load. change_id is dbname::id;
     * so, for example, looks something like this:
     *"gemini_cushion_fist::WO-20150226-2949689"
     */
    function shimRecords(downDbName, downDocs) {
      var deferred = $q.defer();
      var promises = [];
      var jorgeNames = rooConfig.getUpDbs();
      // Loop through all of the write databases
      _.each(jorgeNames, function (jorgeName) {
        // Get all the documents in the current write db
        getDB(jorgeName).allDocs({
          include_docs: true
        })
          .then(function (jorgeDocs) {
            if (jorgeDocs.total_rows > 0) {
              _.each(downDocs.rows, function(doc) {
                // If the current write db has any documents, loop through
                // them and see if any of the documents have a change_id that
                // matches the current read-only db
                _.each(jorgeDocs.rows, function (row) {
                  var d = $q.defer();
                  var change_id = row.doc.change_id;
                  var split = change_id.split('::');
                  var dbName = split[0];
                  var id = split[1];
                  if (dbName === downDbName) {
                    // Find if any document matches
                    if(doc.id === id) {
                      _.extend(doc.doc, JSON.parse(row.doc.change));

                      // Handle attachments
                      if(row.doc._attachments) {
                        if(doc._attachments) {
                          _.extend(doc._attachments, row.doc._attachments);
                        }
                        else {
                          doc._attachments = row.doc._attachments;
                        }
                      }
                    }
                  }
                  d.resolve(doc);
                  promises.push(d.promise);
                });
              });
            }
            $q.all(promises).then(function () {
              deferred.resolve(downDocs);
            });
          });
      });

      return deferred.promise;
    }

    /**
     * Function to update a given read-only record
     * from the server with whatever changes have been
     * made on the client but have not yet been synced
     * to the server, for ui display purposes. This
     * is called currently from the MasterCtrl, so
     * basically on app load. change_id is dbname::id;
     * so, for example, looks something like this:
     * "gemini_cushion_fist::WO-20150226-2949689"
     */
    function shimRecord(downDbName, downDoc) {
      var deferred = $q.defer();
      var jorgeNames = rooConfig.getUpDbs();
      // Loop through all of the write databases
      _.each(jorgeNames, function (jorgeName) {
        // Get all the documents in the current write db
        getDB(jorgeName).allDocs({
          include_docs: true
        }).then(function (jorgeDocs) {
            if (jorgeDocs.total_rows > 0) {
              // The the current write db has any documents, loop through
              // them and see if any of the documents have a change_id that
              // matches the current read-only db
              _.each(jorgeDocs.rows, function (row) {
                var change_id = row.doc.change_id;
                var split = change_id.split('::');
                var dbName = split[0];
                var id = split[1];
                if (dbName === downDbName) {
                  // Find if any document matches
                  if(downDoc._id === id) {
                    _.extend(downDoc, JSON.parse(row.doc.change));

                    // Handle attachments
                    if(row.doc._attachments) {
                      if(downDoc._attachments) {
                        _.extend(downDoc._attachments, row.doc._attachments);
                      }
                      else {
                        downDoc._attachments = row.doc._attachments;
                      }
                    }
                  }
                }
              });
            }
            deferred.resolve(downDoc);
          });
        });
      return deferred.promise;
    }

  return function (db) {

    this.db = db;

    this.getAll = function (options) {
      var self = this;
      var deferred = $q.defer();

      var o = _.extend({include_docs: true}, options);

      getDB(self.db)
      .allDocs(o)
      .then(function (docs) {
        return shimRecords(self.db, docs);
      }).then(function (docs) {
        deferred.resolve(_.pluck(docs.rows, 'doc'));
      }).catch(function(err) {
        deferred.reject(err);
      });

      return deferred.promise;
    };

    this.query = function(query, options){
      var self = this;
      var deferred = $q.defer();

      var o = options || {};

      getDB(self.db).query(query, o)
      .then(function (doc) {
        return shimRecord(self.db, doc);
      }).then(function (doc) {
        deferred.resolve(doc);
      }).catch(function(err) {
        deferred.reject(err);
      });
      return deferred.promise;
    };

    this.getAll = function () {
      var self = this;
      var deferred = $q.defer();
      getDB(self.db).allDocs({
        include_docs: true
      }).then(function (docs) {
        return shimRecords(self.db, docs);
      }).then(function (docs) {
        deferred.resolve(_.pluck(docs.rows, 'doc'));
      }).catch(function(err) {
        deferred.reject(err);
      });
      return deferred.promise;
    };

    this.get = function (docId) {
      var self = this;
      var deferred = $q.defer();
      getDB(self.db).get(docId, {
        include_docs: true
      }).then(function (doc) {
        return shimRecord(self.db, doc);
      }).then(function (doc) {
        deferred.resolve(doc);
      }).catch(function(err) {
        deferred.reject(err);
      });
      return deferred.promise;
    };

      /**
       * Retrieve attachment's local url
       * @param {string} docId - Document's id were the attachment exists.
       * @param {string} attrId - The id for the attachment itself.
       */
      this.getAttachment = function (docId, attrId) {
        var self = this;
        var deferred = $q.defer();
        var URL = window.URL;
        getDB(self.db).getAttachment(docId, attrId)
        .then(function (blob) {
          var url = URL.createObjectURL(blob);
          deferred.resolve(url);
        }).catch(function(err) {
          deferred.reject(err);
        });
        return deferred.promise;
      };

      this.putEntry = function(originTable, originId, changes, method, endpoint, data, headers, user, attachment) {
        var entry = {
            _id: new moment().unix().toString(),
            change_id: '' + originTable + '::' + originId,
            change: JSON.stringify(changes),
            method: method,
            endpoint: endpoint,
            data: data,
            headers: headers,
            user: user
          },
          self = this,
          db = getDB(self.db);

        return db.put(entry)
        .then(function(doc) {
          if(attachment){
            return db.putAttachment(entry._id, attachment.name, doc.rev, attachment, attachment.type);
          }
        });
      };

      /**
       * Replicate db with predefined CouchDB
       * @param {object} user - Any User object to be passed into getParams.
       * @param {object} options - functions to determine params and filters.
       */
      this.replicateDB = function(user, opts) {
        var self = this;

        if(rooConfig.getOptions().destoryOnSync){
            console.log('removing table', self.db);
	          getDB(self.db)
              .destroy()
              .then(function(){
                self.performReplication(user, opts);
              });
	        }else{
            self.performReplication(user, opts);
          }
      };

      this.performReplication = function(user, opts){
          var self = this;
          var deferred = $q.defer();

          // Initialize the remote and local databases
          var remote = new PouchDB(rooConfig.getCouchConfig().couchUrl + '/' + self.db);
          var local = getDB(self.db);
          console.log('Replicating', self.db);
          var replicationOptions = _.extend({batch_size: 5}, opts);

          if(opts.getParams){
            replicationOptions.query_params = opts.getParams(user);
          }

          // Perform replication
          console.time(self.db);
          $rootScope.$broadcast('replicating', true, self.db);
          var rep = local.replicate.from(remote, replicationOptions)
            .on('complete', function (result) {
              console.timeEnd(self.db);
	            $rootScope.$broadcast('replicating', false, self.db);
              rep.cancel();
              try {
                // Make an entry in the logs
                LocalStorageService.addEntryToLog(user.employeeID, self.db, result);
                deferred.resolve();
              } catch(error) {
                console.log(error);
                deferred.reject(error);
              }
              return deferred.promise;
            })
            .on('paused', function(){
              rep.cancel();
            });
        };

      this.performSync = function(user, opts){
        var self = this;
        var deferred = $q.defer();

        console.log('Syncing', self.db);
        var syncOptions = _.extend({batch_size: 5, live: true}, opts);

        if(opts.getParams){
          syncOptions.query_params = opts.getParams(user);
        }

        // Perform replication
        var sync = PouchDB.sync(self.db, rooConfig.getCouchConfig().couchUrl + '/' + self.db, syncOptions)
          .on('complete', function (result) {
            try {
              // Make an entry in the logs
              LocalStorageService.addEntryToLog(user.employeeID, self.db, result);
              deferred.resolve();
            } catch(error) {
              console.log(error);
              deferred.reject(error);
            }
            return deferred.promise;
          })
            .on('paused', function(){
              sync.cancel();
            });
      };

      this.update = function(db, obj, id) {
        var deferred = $q.defer();
        var cushiondb = getDB(db);
        cushiondb.get(id).then(function success(doc) {
          var newDoc = _.extend(doc, obj);
          cushiondb.put(newDoc).then(function success(result) {
            deferred.resolve(result);
          }, function error(result) {
            deferred.reject(result);
          });
        }, function error(result) {
          deferred.reject(result);
        });
        return deferred.promise;
      };

      this.sendJorgeDB = function(db, user) {
        console.log('syncing ' + db + ' for user ' + user.displayName);
        var deferred = $q.defer();
        var promises = [];
        // Do some stuff here.
        getDB(db).allDocs({
          include_docs: true
        }).then(function (docs) {
          // Make an entry in the logs
          _.forEach(docs.rows, function(row) {
            promises.push(LocalStorageService.addEntryToLog(user.employeeID, db, row));
          });

          $q.all(promises).then(function(result) {
            deferred.resolve(result);
          }).catch(function(err) {
            deferred.reject(err);
          });
        });
        return deferred.promise;
      };
    };
  });
};
<|endoftext|>


<commit_before>"use strict";

var q = require('q');
var userData = require('./user');
var Hero = require('./models/Hero');
var _ = require('underscore');

function processHeroCreate(heroInfo, defer) {
    userData.findByUsername(heroInfo.username)
        .then(function (user) {
            var newHero = {
                userId: user.id,
                name: heroInfo.name,
                id: heroInfo.id,
                status: heroInfo.status,
                heroSprite: _.sample(['knight', 'female_peasant', 'male_gold', 'female_thief'], 1) + '.png',
            };

            Hero.create(newHero, function (err, createdHero) {
                if (err) {
                    defer.reject(err);
                } else {
                    defer.resolve(createdHero);
                }
            });
        })
        .fail(function (err) {
            defer.reject(err);
        });
}

function updateHeroStats(hero, statsToAdd, defer) {

    hero.health += (statsToAdd.health || 0);
    hero.attack += (statsToAdd.attack || 0);
    hero.defense += (statsToAdd.defense || 0);

    hero.currentHealth += (statsToAdd.currentHealth || 0);
    hero.currentHealth += (statsToAdd.health || 0);

    hero.save(function (err, heroSaved) {
        if (err) {
            defer.reject(err);
        } else {
            defer.resolve(heroSaved);
        }
    });
}

module.exports = {
    createHero: function (heroInfo) {
        // heroInfo - username, name, status.
        var defer = q.defer();

        var self = this;
        // if the hero is already created, return the hero from database
        // either way create new hero
        this.findByName(heroInfo.name)
            .then(function (hero) {
                if (hero) {
                    self.setHeroStatus(hero.id, heroInfo.status)
                        .then(function () {
                            defer.resolve(hero);
                        });
                } else {
                    processHeroCreate(heroInfo, defer);
                }
            })
            .fail(function (err) {
                defer.reject(err);
            });

        return defer.promise;
    },
    findByName: function (heroName) {
        var defer = q.defer();

        if (heroName) {
            Hero.findOne()
                .where('name').equals(heroName)
                .exec(function (err, hero) {
                    if (err) {
                        defer.reject(err);
                    } else {
                        defer.resolve(hero);
                    }
                });
        } else {
            defer.reject({message: 'You should provide username.'});
        }

        return defer.promise;
    },
    findById: function (heroId) {
        var defer = q.defer();

         Hero.findOne()
            .where('id').equals(heroId)
            .exec(function (err, hero) {
                if (err) {
                    defer.reject(err);
                } else {
                    defer.resolve(hero);
                }
            });

        return defer.promise;
    },
    updateHeroPosition: function (heroId, newPosition) {
        var defer = q.defer();

        Hero.findOneAndUpdate({id: heroId}, {'position.x': newPosition.x, 'position.y': newPosition.y}, function (err, numberAffected, raw) {
            if (err) {
                defer.reject(err);
            }
            else {
                defer.resolve();
            }
        });

        return defer.promise;
    },
    setHeroStatus: function (heroId, status) {
        // eventdata: username, hero_id

        var defer = q.defer();

        Hero.findOneAndUpdate({id: heroId}, {status: status}, function (err, numberAffected, raw) {
            if (err) {
                defer.reject(err);
            }
            else {
                defer.resolve();
            }
        });

        return defer.promise;
    },
    updateHeroStatsWith: function (heroId, statsToAdd) {
        // statsToAdd: health, attack, defense
        var defer = q.defer();

        Hero.findOne()
            .where('id').equals(heroId)
            .exec(function (err, hero) {
                if (err) {
                    defer.reject(err);
                } else if (hero) {
                    updateHeroStats(hero, statsToAdd, defer);
                } else {
                    defer.reject({message: 'There is no such hero in the database.'});
                }
            });

        return defer.promise;
    },
    findOnlineHeroesForMap: function (mapKey) {
        var defer = q.defer();

        Hero.find()
            .where('status').equals('online')
            .where('position.map').equals(mapKey)
            .exec(function (err, heroes) {
                if (err) {
                    defer.reject(err);
                } else {
                    defer.resolve(heroes);
                }
            });

        return defer.promise;
    },
    setHeroMapPosition: function (heroId, newMapKey) {
        var defer = q.defer();

        Hero.findOneAndUpdate({id: heroId}, {'position.map': newMapKey, 'position.x': 320, 'position.y': 320}, function (err, numberAffected, raw) {
            if (err) {
                defer.reject(err);
            }
            else {
                defer.resolve();
            }
        });

        return defer.promise;

    },

    addItemToBackpack: function (heroId, itemKey) {
        var defer = q.defer();

        Hero.findOneAndUpdate({id: heroId}, {$addToSet: {inventoryItems: itemKey}}, function (err, numberAffected, raw) {
            if (err) {
                defer.reject(err);
            }
            else {
                defer.resolve();
            }
        });

        return defer.promise;

    },

    dropItem: function (heroId, itemKey) {
        var defer = q.defer();

        Hero.findOneAndUpdate({id: heroId}, {$pull: {inventoryItems: itemKey}}, function (err, numberAffected, raw) {
            if (err) {
                defer.reject(err);
            }
            else {
                defer.resolve();
            }
        });

        return defer.promise;
    }
};<commit_msg>[server] Fixed bug where current health could go over max health<commit_after>"use strict";

var q = require('q');
var userData = require('./user');
var Hero = require('./models/Hero');
var _ = require('underscore');

function processHeroCreate(heroInfo, defer) {
    userData.findByUsername(heroInfo.username)
        .then(function (user) {
            var newHero = {
                userId: user.id,
                name: heroInfo.name,
                id: heroInfo.id,
                status: heroInfo.status,
                heroSprite: _.sample(['knight', 'female_peasant', 'male_gold', 'female_thief'], 1) + '.png',
            };

            Hero.create(newHero, function (err, createdHero) {
                if (err) {
                    defer.reject(err);
                } else {
                    defer.resolve(createdHero);
                }
            });
        })
        .fail(function (err) {
            defer.reject(err);
        });
}

function updateHeroStats(hero, statsToAdd, defer) {

    hero.health += (statsToAdd.health || 0);
    hero.attack += (statsToAdd.attack || 0);
    hero.defense += (statsToAdd.defense || 0);

    hero.currentHealth += (statsToAdd.currentHealth || 0);
    hero.currentHealth += (statsToAdd.health || 0);

    if (hero.currentHealth > hero.health) {
        hero.currentHealth = hero.health;
    }

    hero.save(function (err, heroSaved) {
        if (err) {
            defer.reject(err);
        } else {
            defer.resolve(heroSaved);
        }
    });
}

module.exports = {
    createHero: function (heroInfo) {
        // heroInfo - username, name, status.
        var defer = q.defer();

        var self = this;
        // if the hero is already created, return the hero from database
        // either way create new hero
        this.findByName(heroInfo.name)
            .then(function (hero) {
                if (hero) {
                    self.setHeroStatus(hero.id, heroInfo.status)
                        .then(function () {
                            defer.resolve(hero);
                        });
                } else {
                    processHeroCreate(heroInfo, defer);
                }
            })
            .fail(function (err) {
                defer.reject(err);
            });

        return defer.promise;
    },
    findByName: function (heroName) {
        var defer = q.defer();

        if (heroName) {
            Hero.findOne()
                .where('name').equals(heroName)
                .exec(function (err, hero) {
                    if (err) {
                        defer.reject(err);
                    } else {
                        defer.resolve(hero);
                    }
                });
        } else {
            defer.reject({message: 'You should provide username.'});
        }

        return defer.promise;
    },
    findById: function (heroId) {
        var defer = q.defer();

         Hero.findOne()
            .where('id').equals(heroId)
            .exec(function (err, hero) {
                if (err) {
                    defer.reject(err);
                } else {
                    defer.resolve(hero);
                }
            });

        return defer.promise;
    },
    updateHeroPosition: function (heroId, newPosition) {
        var defer = q.defer();

        Hero.findOneAndUpdate({id: heroId}, {'position.x': newPosition.x, 'position.y': newPosition.y}, function (err, numberAffected, raw) {
            if (err) {
                defer.reject(err);
            }
            else {
                defer.resolve();
            }
        });

        return defer.promise;
    },
    setHeroStatus: function (heroId, status) {
        // eventdata: username, hero_id

        var defer = q.defer();

        Hero.findOneAndUpdate({id: heroId}, {status: status}, function (err, numberAffected, raw) {
            if (err) {
                defer.reject(err);
            }
            else {
                defer.resolve();
            }
        });

        return defer.promise;
    },
    updateHeroStatsWith: function (heroId, statsToAdd) {
        // statsToAdd: health, attack, defense
        var defer = q.defer();

        Hero.findOne()
            .where('id').equals(heroId)
            .exec(function (err, hero) {
                if (err) {
                    defer.reject(err);
                } else if (hero) {
                    updateHeroStats(hero, statsToAdd, defer);
                } else {
                    defer.reject({message: 'There is no such hero in the database.'});
                }
            });

        return defer.promise;
    },
    findOnlineHeroesForMap: function (mapKey) {
        var defer = q.defer();

        Hero.find()
            .where('status').equals('online')
            .where('position.map').equals(mapKey)
            .exec(function (err, heroes) {
                if (err) {
                    defer.reject(err);
                } else {
                    defer.resolve(heroes);
                }
            });

        return defer.promise;
    },
    setHeroMapPosition: function (heroId, newMapKey) {
        var defer = q.defer();

        Hero.findOneAndUpdate({id: heroId}, {'position.map': newMapKey, 'position.x': 320, 'position.y': 320}, function (err, numberAffected, raw) {
            if (err) {
                defer.reject(err);
            }
            else {
                defer.resolve();
            }
        });

        return defer.promise;

    },

    addItemToBackpack: function (heroId, itemKey) {
        var defer = q.defer();

        Hero.findOneAndUpdate({id: heroId}, {$addToSet: {inventoryItems: itemKey}}, function (err, numberAffected, raw) {
            if (err) {
                defer.reject(err);
            }
            else {
                defer.resolve();
            }
        });

        return defer.promise;

    },

    dropItem: function (heroId, itemKey) {
        var defer = q.defer();

        Hero.findOneAndUpdate({id: heroId}, {$pull: {inventoryItems: itemKey}}, function (err, numberAffected, raw) {
            if (err) {
                defer.reject(err);
            }
            else {
                defer.resolve();
            }
        });

        return defer.promise;
    }
};<|endoftext|>