<commit_before>var Command = require('ronin').Command
var fs = require('fs')
var path = require('path')
var webshot = require('webshot')
var ipfsAPI = require('ipfs-api')
var open = require('open')

module.exports = Command.extend({
  desc: 'View or generate screenshots for your application',

  options: {
    gen: 'boolean'
  },

  run: function (gen, name) {
    try {
      var configPath = path.resolve(process.cwd() + '/ipscend.json')
      fs.statSync(configPath)
      snapshot()
    } catch (err) {
      // console.log(err)
      console.log('Project must be initiated first, run `ipscend init`')
    }

    function snapshot () {
      var config = JSON.parse(fs.readFileSync(configPath))
      if (config.versions.length === 0) {
        return console.log('You need to publish at least once with <ipscend publish>')
      }

      var ipfs = ipfsAPI('localhost', '5001')

      if (!gen) {
        ipfs.add(new Buffer(JSON.stringify(config.versions)), function (err, res) {
          if (err || !res) {
            return console.error('err', err)
          }
          var previewAppHash = 'QmSoJahy5TXavAA19t23tTxtSZ2qoRE9uXwigJTZSVNTTw'
          var versionsHash = res[0].Hash
          var base = 'http://localhost:8080/ipfs/'
          open(base + previewAppHash + '/#' + versionsHash)
        })
        return
      }

      if (gen) {
        var len = config.versions.length
        config.versions.forEach(function (version) {
          if (!version.snapshot) {
            webshot('http://localhost:8080/ipfs/' + version.hash,
                '/tmp/' + version.hash + '.png', {
                  shotSize: {
                    width: 'all',
                    height: 'all'
                  }
                }, function (err) {
              if (err) {
                return console.log(err)
              }

              ipfs.add('/tmp/' + version.hash + '.png', function (err, res) {
                if (err || !res) {
                  return console.error('err', err)
                }
                version.snapshot = res[0].Hash
                len--
                if (len === 0) {
                  var fd = fs.openSync(configPath, 'w')
                  fs.writeSync(fd, JSON.stringify(config, null, '  '), 0, 'utf-8')
                }
              })
            })
          } else {
            len--
          }
        })
      }
    }
  }
})
<commit_msg>point to newer ipscend-preview<commit_after>var Command = require('ronin').Command
var fs = require('fs')
var path = require('path')
var webshot = require('webshot')
var ipfsAPI = require('ipfs-api')
var open = require('open')

module.exports = Command.extend({
  desc: 'View or generate screenshots for your application',

  options: {
    gen: 'boolean'
  },

  run: function (gen, name) {
    try {
      var configPath = path.resolve(process.cwd() + '/ipscend.json')
      fs.statSync(configPath)
      snapshot()
    } catch (err) {
      // console.log(err)
      console.log('Project must be initiated first, run `ipscend init`')
    }

    function snapshot () {
      var config = JSON.parse(fs.readFileSync(configPath))
      if (config.versions.length === 0) {
        return console.log('You need to publish at least once with <ipscend publish>')
      }

      var ipfs = ipfsAPI('localhost', '5001')

      if (!gen) {
        ipfs.add(new Buffer(JSON.stringify(config.versions)), function (err, res) {
          if (err || !res) {
            return console.error('err', err)
          }
          var previewAppHash = 'QmWSdGhfB6CbgvKzksaUSumjKyc5QWtoTiZciWSoNBNJcw'
          var versionsHash = res[0].Hash
          var base = 'http://localhost:8080/ipfs/'
          open(base + previewAppHash + '/#' + versionsHash)
        })
        return
      }

      if (gen) {
        var len = config.versions.length
        config.versions.forEach(function (version) {
          if (!version.snapshot) {
            webshot('http://localhost:8080/ipfs/' + version.hash,
                '/tmp/' + version.hash + '.png', {
                  shotSize: {
                    width: 'all',
                    height: 'all'
                  }
                }, function (err) {
              if (err) {
                return console.log(err)
              }

              ipfs.add('/tmp/' + version.hash + '.png', function (err, res) {
                if (err || !res) {
                  return console.error('err', err)
                }
                version.snapshot = res[0].Hash
                len--
                if (len === 0) {
                  var fd = fs.openSync(configPath, 'w')
                  fs.writeSync(fd, JSON.stringify(config, null, '  '), 0, 'utf-8')
                }
              })
            })
          } else {
            len--
          }
        })
      }
    }
  }
})
<|endoftext|>


<commit_before>/**
 * Pages selector with search (plain table)
 *
 * @author Tyutyunkov Vyacheslav (tve@softmotions.com)
 * @version $Id$
 */
qx.Class.define("ncms.pgs.PagesSearchSelector", {
    extend : qx.ui.core.Widget,

    events : {
        /**
         * DATA: var item = {
         *        "id"     : {Object} Optional Node ID
         *        "label"  : {String} Item name.
         *        "path"   : {String} Path to the item (from tree root)
         *       };
         * or null if selection cleared
         */
        itemSelected : "qx.event.type.Data"
    },

    properties : {
        constViewSpec : {
            check : "Object",
            nullable : true,
            apply : "__applyConstViewSpec"
        }
    },

    construct : function(constViewSpec, allowModify) {
        this.base(arguments);
        this._setLayout(new qx.ui.layout.VBox());

        var sf = this.__sf = new sm.ui.form.SearchField();
        sf.addListener("clear", function() {
            this.__search(null);
        }, this);
        sf.addListener("input", function(ev) {
            this.__search(ev.getData());
        }, this);
        sf.addListener("keypress", function(ev) {
            if ("Down" == ev.getKeyIdentifier()) {
                this.__table.handleFocus();
            }
        }, this);

        this.__table = new ncms.pgs.PagesTable().set({
            "statusBarVisible" : false,
            "showCellFocusIndicator" : false});

        this.__table.getSelectionModel().addListener("changeSelection", function() {
            var page = this.__table.getSelectedPage();
            this.fireDataEvent("itemSelected", page ? page : null);
        }, this);

        this._add(this.__sf);
        this._add(this.__table, {flex : 1});

        this.setConstViewSpec(constViewSpec || null);

        this._add(this.__sf);
        this._add(this.__table, {flex : 1});
    },

    members : {
        __sf : null,
        __table : null,

        setViewSpec : function(vspec) {
            this.__table.resetSelection();
            this.__table.getTableModel().setViewSpec(this.__createViewSpec(vspec));
        },

        updateViewSpec : function(vspec) {
            this.__table.resetSelection();
            this.__table.getTableModel().updateViewSpec(this.__createViewSpec(vspec));
        },

        __createViewSpec : function(vspec) {
            if (this.getConstViewSpec() == null) {
                return vspec;
            }
            var nspec = {};
            qx.Bootstrap.objectMergeWith(nspec, this.getConstViewSpec(), false);
            qx.Bootstrap.objectMergeWith(nspec, vspec, false);
            return nspec;
        },

        __search : function(val) {
            this.updateViewSpec({name : val || ""});
        },

        __applyConstViewSpec : function() {
            this.__search();
        }
    },

    destruct : function() {
    }
});
<commit_msg>pages search<commit_after>/**
 * Pages selector with search (plain table)
 *
 * @author Tyutyunkov Vyacheslav (tve@softmotions.com)
 * @version $Id$
 */
qx.Class.define("ncms.pgs.PagesSearchSelector", {
    extend : qx.ui.core.Widget,

    events : {
        /**
         * DATA: var item = {
         *        "id"     : {Object} Optional Node ID
         *        "label"  : {String} Item name.
         *        "path"   : {String} Path to the item (from tree root)
         *       };
         * or null if selection cleared
         */
        itemSelected : "qx.event.type.Data"
    },

    properties : {
        constViewSpec : {
            check : "Object",
            nullable : true,
            apply : "__applyConstViewSpec"
        }
    },

    construct : function(constViewSpec, allowModify) {
        this.base(arguments);
        this._setLayout(new qx.ui.layout.VBox());

        var sf = this.__sf = new sm.ui.form.SearchField();
        sf.addListener("clear", this.__search, this);
        sf.addListener("input", this.__search, this);
        sf.addListener("keypress", function(ev) {
            if ("Down" == ev.getKeyIdentifier()) {
                this.__table.handleFocus();
            }
        }, this);

        this.__table = new ncms.pgs.PagesTable().set({
            "statusBarVisible" : false,
            "showCellFocusIndicator" : false});

        this.__table.getSelectionModel().addListener("changeSelection", function() {
            var page = this.__table.getSelectedPage();
            this.fireDataEvent("itemSelected", page ? page : null);
        }, this);

        this._add(this.__sf);
        this._add(this.__table, {flex : 1});

        this.setConstViewSpec(constViewSpec || null);

        this.addListener("appear", this.__search, this);
    },

    members : {
        __sf : null,
        __table : null,

        setViewSpec : function(vspec) {
            this.__table.resetSelection();
            this.__table.getTableModel().setViewSpec(vspec);
        },

        updateViewSpec : function(vspec) {
            this.__table.resetSelection();
            this.__table.getTableModel().updateViewSpec(vspec);
        },

        __search : function() {
            var val = this.__sf.getValue();
            if (!val) {
                this.__table.cleanup();
            } else {
                this.updateViewSpec({name : val || ""});
            }
        },

        __applyConstViewSpec : function() {
            this.__search();
        }
    },

    destruct : function() {
    }
});
<|endoftext|>


<commit_before>var React = require('react');
var builder = require('focus').component.builder
//var i18nMixin = require('../i18n').mixin;
var StickyNavigation = require('../sticky-navigation').component
var type = require('focus').component.types;
var stylable = require('../../mixin/stylable')
/**
 * Mixin used in order to create a Detail.
 * @type {Object}
 */
var detailMixin = {
  mixins: [stylable],
  /** @inheritedDoc */
  getDefaultProps: function getDetailDefaultProps(){
    return {
      /**
       * Activate the presence of the sticky navigation component.
       * @type {Boolean}
       */
      navigation: true
    }
  },
  /** @inheritedDoc */
  propTypes: {
    navigation: type('bool')
  },
  /**
   * Render the navigation component if the props navigation is true.
   * @returns {Object} - The jsx component.
   */
  renderNavigation: function(){
    if(this.props.navigation){
      return <StickyNavigation/>;
    } return;
  },
  /** @inheritedDoc */
  render: function renderDetail(){
    return(
      <div className={`${this._getStyleClassName()}`}  data-focus='detail'>
        {this.renderNavigation()}

          {this.props.children}

    );
  }
}
module.exports = builder(detailMixin);
<commit_msg>[back-to-top] Automatically add the component to the Detail tag.<commit_after>var React = require('react');
var builder = require('focus').component.builder;
//var i18nMixin = require('../i18n').mixin;
var StickyNavigation = require('../sticky-navigation').component;
var type = require('focus').component.types;
var stylable = require('../../mixin/stylable')
var BackToTopComponent = require('../button/back-to-top').component;
/**
 * Mixin used in order to create a Detail.
 * @type {Object}
 */
var detailMixin = {
  mixins: [stylable],
  /** @inheritedDoc */
  getDefaultProps: function getDetailDefaultProps(){
    return {
      /**
       * Activate the presence of the sticky navigation component.
       * @type {Boolean}
       */
      navigation: true,
      hasBackToTop: true,
      BackToTopComponent: BackToTopComponent
    };
  },
  /** @inheritedDoc */
  propTypes: {
    navigation: type('bool'),
    hasBackToTop: type('bool'),
    BackToTopComponent: type(['function', 'object'])
  },
  /**
   * Render the navigation component if the props navigation is true.
   * @returns {Object} - The jsx component.
   */
  renderNavigation: function(){
    if(this.props.navigation){
      return <StickyNavigation/>;
    } return;
  },
  /** @inheritedDoc */
  render: function renderDetail(){
    return(
      <div className={`${this._getStyleClassName()}`}  data-focus='detail'>
        {this.renderNavigation()}

          {this.props.children}

        {this.props.hasBackToTop && <this.props.BackToTopComponent/>}

    );
  }
}
module.exports = builder(detailMixin);
<|endoftext|>


<commit_before>angular.module('ot.view.build', [
    'ui.router',
    'ot.service.core',
    'ot.service.structure'
])
    .config(function ($stateProvider) {
        $stateProvider.state('build', {
            url: '/build/{buildId}',
            templateUrl: 'app/view/view.build.tpl.html',
            controller: 'BuildCtrl'
        });
    })
    .controller('BuildCtrl', function ($scope, $stateParams, $http, ot, otStructureService) {
        var view = ot.view();
        // Build's id
        var buildId = $stateParams.buildId;

        // Loads the build
        function loadBuild() {
            otStructureService.getBuild(buildId).then(function (build) {
                $scope.build = build;
                // View configuration
                view.title = "Build " + build.name;
                view.description = build.description;
                // Commands
                view.commands = [
                    {
                        condition: function () {
                            return build.promote;
                        },
                        id: 'promote',
                        name: "Promote",
                        cls: 'ot-command-promote',
                        action: promote
                    },
                    ot.viewCloseCommand('/branch/' + build.branch.id)
                ];
            });
        }

        loadBuild();

        // Promotion
        function promote() {

        }
    })
;<commit_msg>Promotion: form skeleton<commit_after>angular.module('ot.view.build', [
    'ui.router',
    'ot.service.core',
    'ot.service.structure'
])
    .config(function ($stateProvider) {
        $stateProvider.state('build', {
            url: '/build/{buildId}',
            templateUrl: 'app/view/view.build.tpl.html',
            controller: 'BuildCtrl'
        });
    })
    .controller('BuildCtrl', function ($scope, $stateParams, $http, ot, otStructureService) {
        var view = ot.view();
        // Build's id
        var buildId = $stateParams.buildId;

        // Loads the build
        function loadBuild() {
            otStructureService.getBuild(buildId).then(function (build) {
                $scope.build = build;
                // View configuration
                view.title = "Build " + build.name;
                view.description = build.description;
                // Commands
                view.commands = [
                    {
                        condition: function () {
                            return build.promote;
                        },
                        id: 'promote',
                        name: "Promote",
                        cls: 'ot-command-promote',
                        action: promote
                    },
                    ot.viewCloseCommand('/branch/' + build.branch.id)
                ];
            });
        }

        loadBuild();

        // Promotion
        function promote() {
            otStructureService.create($scope.build.promote.href, 'Promotion for the build').then(loadBuild);
        }
    })
;<|endoftext|>


<commit_before>module.exports = {
  I: 'Я',
  actions: {
    waitForElement: 'ожидаю_элемент',
    waitForVisible: 'ожидаю_увидеть',
    waitForText: 'ожидаю_текст',
    amOnPage: 'на_странице',
    click: 'кликаю',
    doubleClick: 'дважды_кликаю',
    see: 'вижу',
    dontSee: 'не_вижу',
    selectOption: 'выбираю_опцию',
    fillField: 'заполнаю_поле',
    pressKey: 'нажимаю_кнопку',
    triggerMouseEvent: 'триггерное_событие_мыши',
    attachFile: 'загружаю_файл',
    seeInField: 'вижу_в_поле',
    dontSeeInField: 'не_вижу_в_поле',
    appendField: 'дописываю_в_поле',
    checkOption: 'выбираю_опцию',
    seeCheckboxIsChecked: 'вижу_галочку',
    dontSeeCheckboxIsChecked: 'не_вижу_галочку',
    grabTextFrom: 'беру_текст_из',
    grabValueFrom: 'беру_значение_из',
    grabAttributeFrom: 'беру_атрибут_из',
    seeInTitle: 'вижу_в_заголовке',
    dontSeeInTitle: 'не_вижу_в_заголовке',
    grabTitle: 'беру_заголовок',
    seeElement: 'вижу_элемент',
    dontSeeElement: 'не_вижу_элемент',
    seeInSource: 'вижу_в_коде',
    dontSeeInSource: 'не_вижу_в_коде',
    executeScript: 'выполняю_скрипт',
    executeAsyncScript: 'выполняю_скрипт_асинхронно',
    seeInCurrentUrl: 'вижу_в_адресе',
    dontSeeInCurrentUrl: 'не_вижу_в_адресе',
    seeCurrentUrlEquals: 'вижу_адрес_равен',
    dontSeeCurrentUrlEquals: 'не_вижу_адрес',
    saveScreenshot: 'делаю_скриншот',
    setCookie: 'устанавливаю_куки',
    clearCookie: 'очищаю_куки',
    seeCookie: 'вижу_в_куки',
    dontSeeCookie: 'не_вижу_в_куки',
    grabCookie: 'беру_куки',
    resizeWindow: 'растягиваю_окно',
    wait: 'жду',
  },
};
<commit_msg>small translate fix (#1283)<commit_after>module.exports = {
  I: 'Я',
  actions: {
    waitForElement: 'ожидаю_элемент',
    waitForVisible: 'ожидаю_увидеть',
    waitForText: 'ожидаю_текст',
    amOnPage: 'на_странице',
    click: 'кликаю',
    doubleClick: 'дважды_кликаю',
    see: 'вижу',
    dontSee: 'не_вижу',
    selectOption: 'выбираю_опцию',
    fillField: 'заполняю_поле',
    pressKey: 'нажимаю_кнопку',
    triggerMouseEvent: 'триггерное_событие_мыши',
    attachFile: 'загружаю_файл',
    seeInField: 'вижу_в_поле',
    dontSeeInField: 'не_вижу_в_поле',
    appendField: 'дописываю_в_поле',
    checkOption: 'выбираю_опцию',
    seeCheckboxIsChecked: 'вижу_галочку',
    dontSeeCheckboxIsChecked: 'не_вижу_галочку',
    grabTextFrom: 'беру_текст_из',
    grabValueFrom: 'беру_значение_из',
    grabAttributeFrom: 'беру_атрибут_из',
    seeInTitle: 'вижу_в_заголовке',
    dontSeeInTitle: 'не_вижу_в_заголовке',
    grabTitle: 'беру_заголовок',
    seeElement: 'вижу_элемент',
    dontSeeElement: 'не_вижу_элемент',
    seeInSource: 'вижу_в_коде',
    dontSeeInSource: 'не_вижу_в_коде',
    executeScript: 'выполняю_скрипт',
    executeAsyncScript: 'выполняю_скрипт_асинхронно',
    seeInCurrentUrl: 'вижу_в_адресе',
    dontSeeInCurrentUrl: 'не_вижу_в_адресе',
    seeCurrentUrlEquals: 'вижу_адрес_равен',
    dontSeeCurrentUrlEquals: 'не_вижу_адрес',
    saveScreenshot: 'делаю_скриншот',
    setCookie: 'устанавливаю_куки',
    clearCookie: 'очищаю_куки',
    seeCookie: 'вижу_в_куки',
    dontSeeCookie: 'не_вижу_в_куки',
    grabCookie: 'беру_куки',
    resizeWindow: 'растягиваю_окно',
    wait: 'жду',
  },
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import ReactDOMServer from 'react-dom/server';
import TestUtils from 'react-addons-test-utils';
import Input from '../src/Input';
import Icon from '../src/Icon';

describe('Input', function() {
  it('renders a text field by default', function() {
    let instance = TestUtils.renderIntoDocument(<Input />);
    let input = TestUtils.findRenderedDOMComponentWithTag(instance, 'input');
    input = ReactDOM.findDOMNode(input);
    assert.equal(input.nodeName, 'INPUT');
    assert.equal(input.getAttribute('type'), 'text');
  });

  it('renders a textarea when type is textarea', function() {
    let instance = TestUtils.renderIntoDocument(<Input type='textarea'/>);
    let textarea = TestUtils.findRenderedDOMComponentWithTag(instance, 'textarea');
    assert.ok(textarea);
  });

  it('renders a select element when type is select', function() {
    let instance = TestUtils.renderIntoDocument(
      <Input type='select' defaultValue='v'>
        <option value='v'/>
        <option value='w'/>
      </Input>);
    let select = TestUtils.findRenderedDOMComponentWithTag(instance, 'select');
    assert.equal(ReactDOM.findDOMNode(select).nodeName, 'SELECT');
  });

  it('renders an icon with prefix class name when icon prefix is used', () => {
    let instance = TestUtils.renderIntoDocument(
      <Input type='text'><Icon>account_circle</Icon></Input>
    );
    let input = TestUtils.findRenderedDOMComponentWithTag(instance, 'i');
    assert.include(ReactDOM.findDOMNode(input).className, 'prefix');
  });

  it('renders placeholder as the default disabled option for select', () => {
    let defaultOption = 'Choose your option';
    let instance = TestUtils.renderIntoDocument(
        <Input type='select' placeholder={defaultOption}>
            <option value='1'>Option 1</option>
            <option value='2'>Option 2</option>
            <option value='3'>Option 3</option>
        </Input>);
    let options = TestUtils.scryRenderedDOMComponentsWithTag(instance, 'option');
    assert.ok(options);
    assert.equal(options.length, 4);
    assert.equal(options[0].getAttribute('disabled'), '');
    assert.equal(options[0].value, defaultOption);
  });
});
<commit_msg>Add/refactor Input spec<commit_after>/* global describe, it, expect */

import React from 'react';
import { shallow, mount } from 'enzyme';

import Input from '../src/Input';
import Icon from '../src/Icon';

describe('<Input />', () => {
  let wrapper = shallow(<Input />);

  it('renders a text field by default', () => {
    expect(wrapper.find('.input-field')).to.have.length(1);
  });

  it('renders a textarea when type is textarea', () => {
    wrapper = shallow(<Input type='textarea' />);
    expect(wrapper.find('textarea')).to.have.length(1);
  });

  it('renders a select element when type is select', () => {
    wrapper = mount(
      <Input type='select' defaultValue='v'>
        <option value='v' />
        <option value='w' />
      </Input>);
    expect(wrapper.find('select')).to.have.length(1);
  });

  it('renders an icon with prefix class name when icon prefix is used', () => {
    wrapper = mount(
      <Input type='text'><Icon>account_circle</Icon></Input>
    );
    expect(wrapper.find('i.prefix')).to.have.length(1);
  });

  it('renders placeholder as the default disabled option for select', () => {
    let defaultOption = 'Choose your option';
    wrapper = mount(
      <Input type='select' placeholder={defaultOption}>
        <option value='1'>Option 1</option>
        <option value='2'>Option 2</option>
        <option value='3'>Option 3</option>
      </Input>);
    expect(wrapper.find('option')).to.have.length(4);
  });

  it('renders a select with multiple', () => {
    let defaultOption = 'Choose your option';
    wrapper = mount(
      <Input type='select' multiple placeholder={defaultOption}>
        <option value='1'>Option 1</option>
        <option value='2'>Option 2</option>
        <option value='3'>Option 3</option>
      </Input>);
    expect(wrapper.find('select[multiple]')).to.have.length(1);
  });
});
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

var expect = require("chai").expect;
var supertest = require("supertest");
var sinon = require("sinon");

var hmac = require('../loop/hmac');
var loop = require("../loop");
var conf = loop.conf;
var app = loop.app;
var apiRouter = loop.apiRouter;
var apiPrefix = loop.apiPrefix;
var storage = loop.storage;
var requireRoomSessionToken = loop.auth.requireRoomSessionToken;

describe("auth.js", function() {
  var sandbox;

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });

  afterEach(function() {
    sandbox.restore();
  });

  describe('#requireRoomSessionToken', function() {
    var jsonReq, expectedToken, expectedTokenHmac;

    // Create a route with the auth middleware installed.
    apiRouter.post('/with-requireRoomSessionToken',
      requireRoomSessionToken, function(req, res) {
      res.status(200).json(req.participantTokenHmac);
    });

    beforeEach(function() {
      jsonReq = supertest(app)
        .post(apiPrefix + '/with-requireRoomSessionToken');

      expectedToken = "valid-token";
      expectedTokenHmac = hmac(expectedToken, conf.get('userMacSecret'));

      sandbox.stub(storage, "isValidRoomToken",
        function(roomToken, tokenHmac, cb) {
          if (tokenHmac === expectedTokenHmac) {
            cb(null, true);
          } else {
            cb(null, false);
          }
        });
    });

    it("should require user authentication", function(done) {
      jsonReq
        .expect(401)
        .end(function(err, res) {
          if (err) throw err;
          expect(res.headers['www-authenticate']).to.eql('Token');
          done();
        });
    });

    it("should reject invalid tokens", function(done) {
      // Mock the calls to the external BrowserID verifier.
      jsonReq
        .set('Authorization', 'Token ' + "invalid-token")
        .expect(401)
        .end(function(err, res) {
          if (err) throw err;
          expect(res.headers['www-authenticate'])
            .to.eql('Token error="Invalid token; it as probably expired."');
          done();
        });
    });

    it("should accept valid token", function(done) {
      jsonReq
        .set('Authorization', 'Token ' + expectedToken)
        .expect(200)
        .end(function(err) {
          if (err) throw err;
          done();
        });
    });

    it("should set an 'participantTokenHmac' property on the request object",
      function(done) {
        jsonReq
          .set('Authorization', 'Token ' + expectedToken)
          .expect(200)
          .end(function(err, res) {
            if (err) throw err;
            expect(res.body).eql(expectedTokenHmac);
            done();
          });
      });
  });
});
<commit_msg>Add tests for the authenticateWithHawkOrToken middleware.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";

var expect = require("chai").expect;
var supertest = require("supertest");
var sinon = require("sinon");
var assert = sinon.assert;
var randomBytes = require("crypto").randomBytes;

var hmac = require('../loop/hmac');
var loop = require("../loop");
var conf = loop.conf;
var app = loop.app;
var apiRouter = loop.apiRouter;
var apiPrefix = loop.apiPrefix;
var storage = loop.storage;
var requireRoomSessionToken = loop.auth.requireRoomSessionToken;
var authenticateWithHawkOrToken = loop.auth.authenticateWithHawkOrToken;
var Token = require("express-hawkauth").Token;

describe("auth.js", function() {
  var sandbox;

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });

  afterEach(function() {
    sandbox.restore();
  });

  describe('#requireRoomSessionToken', function() {
    var jsonReq, expectedToken, expectedTokenHmac;

    // Create a route with the auth middleware installed.
    apiRouter.post('/with-requireRoomSessionToken',
      requireRoomSessionToken, function(req, res) {
      res.status(200).json(req.participantTokenHmac);
    });

    beforeEach(function() {
      jsonReq = supertest(app)
        .post(apiPrefix + '/with-requireRoomSessionToken');

      expectedToken = "valid-token";
      expectedTokenHmac = hmac(expectedToken, conf.get('userMacSecret'));

      sandbox.stub(storage, "isValidRoomToken",
        function(roomToken, tokenHmac, cb) {
          if (tokenHmac === expectedTokenHmac) {
            cb(null, true);
          } else {
            cb(null, false);
          }
        });
    });

    it("should require user authentication", function(done) {
      jsonReq
        .expect(401)
        .end(function(err, res) {
          if (err) throw err;
          expect(res.headers['www-authenticate']).to.eql('Token');
          done();
        });
    });

    it("should reject invalid tokens", function(done) {
      // Mock the calls to the external BrowserID verifier.
      jsonReq
        .set('Authorization', 'Token ' + "invalid-token")
        .expect(401)
        .end(function(err, res) {
          if (err) throw err;
          expect(res.headers['www-authenticate'])
            .to.eql('Token error="Invalid token; it as probably expired."');
          done();
        });
    });

    it("should accept valid token", function(done) {
      jsonReq
        .set('Authorization', 'Token ' + expectedToken)
        .expect(200)
        .end(function(err) {
          if (err) throw err;
          done();
        });
    });

    it("should set an 'participantTokenHmac' property on the request object",
      function(done) {
        jsonReq
          .set('Authorization', 'Token ' + expectedToken)
          .expect(200)
          .end(function(err, res) {
            if (err) throw err;
            expect(res.body).eql(expectedTokenHmac);
            done();
          });
      });
  });

  describe("authenticationWithHawkOrToken middleware", function() {
    var expectedToken, expectedTokenHmac;

    apiRouter.post("/authenticateWithHawkOrToken", authenticateWithHawkOrToken,
      function(req, res) {
        res.status(200).json(req.participantTokenHmac || req.hawkIdHmac);
      });

    describe("Token", function() {
      beforeEach(function() {
        expectedToken = "valid-token";
        expectedTokenHmac = hmac(expectedToken, conf.get('userMacSecret'));

        sandbox.stub(storage, "isValidRoomToken",
          function(roomToken, tokenHmac, cb) {
            if (tokenHmac === expectedTokenHmac) {
              cb(null, true);
            } else {
              cb(null, false);
            }
          });
      });

      it("should accept token", function(done) {
        supertest(app)
          .post(apiPrefix + "/authenticateWithHawkOrToken")
          .set('Authorization', 'Token ' + expectedToken)
          .expect(200)
          .end(function(err, res) {
            if (err) {
              throw err;
            }
            expect(res.body).to.eql(expectedTokenHmac);
            done();
          });
      });

      it("shouldn't accept invalid token", function(done) {
          supertest(app)
            .post(apiPrefix + "/authenticateWithHawkOrToken")
            .set('Authorization', 'Token wrongAssertion')
            .expect(401)
            .end(done);
        });
    });

    describe("Hawk", function() {
      var hawkCredentials, userHmac;

      beforeEach(function(done) {
        // Generate Hawk credentials.
        var token = new Token();
        token.getCredentials(function(tokenId, authKey) {
          hawkCredentials = {
            id: tokenId,
            key: authKey,
            algorithm: "sha256"
          };
          userHmac = hmac(tokenId, conf.get('hawkIdSecret'));
          storage.setHawkSession(userHmac, authKey, done);
        });
      });

      it("should accept valid hawk sessions", function(done) {
          supertest(app)
            .post(apiPrefix + "/authenticateWithHawkOrToken")
            .hawk(hawkCredentials)
            .expect(200)
            .end(done);
        });

      it("shouldn't accept invalid hawk credentials", function(done) {
          hawkCredentials.id = randomBytes(16).toString("hex");
          supertest(app)
            .post(apiPrefix + "/authenticateWithHawkOrToken")
            .hawk(hawkCredentials)
            .expect(401)
            .end(done);
        });

      it("should update session expiration time on auth", function(done) {
        sandbox.spy(storage, "touchHawkSession");
        supertest(app)
          .post(apiPrefix + "/authenticateWithHawkOrToken")
          .hawk(hawkCredentials)
          .expect(200)
          .end(function(err) {
            if (err) {
              throw err;
            }
            assert.calledWithExactly(
              storage.touchHawkSession,
              userHmac
            );
            done();
          });
      });
    });

    it("should accept no Token nor Hawk",
      function(done) {
        supertest(app)
          .post(apiPrefix + "/authenticateWithHawkOrToken")
          .expect(200)
          .end(function(err, res) {
            if (err) {
              throw err;
            }
            expect(res.body).to.eql({});
            done();
          });
      });
  });
});
<|endoftext|>


<commit_before>// Copyright (C) 2011 - Texas Instruments, Jason Kridner
//
//
var fs = require('fs');
var child_process = require('child_process');
var http = require('http');
var url = require('url');
var path = require('path');
var events = require('events');
bone = require('./bone').bone;

var myrequire = function(packageName, onfail) {
    var y = {};
    try {
        y = require(packageName);
        y.exists = true;
    } catch(ex) {
        y.exists = false;
        console.log("'" + packageName + "' not loaded");
        console.log("If desired, try installing it with:");
        console.log("  curl http://npmjs.org/install.sh | bash");
        console.log("  npm install " + packageName);
        onfail();
    }
    return(y);
};

var socket = myrequire('socket.io', function() {
    console.log("Dynamic web features not enabled");
});

var binary = myrequire('binary', function() { });
var inotify = myrequire('inotify', function() { });

var fibers = myrequire('fibers', function() {
    console.log("Delay operations loops will consume CPU cycles");
    console.log("Invoke using 'node-fibers' if node version < 0.5.2");
});

OUTPUT = exports.OUTPUT = "out";
INPUT = exports.INPUT = "in";
HIGH = exports.HIGH = 1;
LOW = exports.LOW = 0;
LSBFIRST = 1;  // used in: shiftOut(dataPin, clockPin, bitOrder, val)
MSBFIRST = 0;

var gpio = [];

pinMode = exports.pinMode = function(pin, mode)
{
    var n = pin.gpio;

    if(!gpio[n] || !gpio[n].path) {
        gpio[n] = {};

        // Ensure the pin is in GPIO mode
        if(pin.mux) {
            try {
                var muxfile = fs.openSync(
                    "/sys/kernel/debug/omap_mux/" + pin.mux, "w"
                );
                if(mode == OUTPUT)  fs.writeSync(muxfile, "7", null);
                    else fs.writeSync(muxfile, "27", null);
            } catch(ex3) {
                console.log("" + ex3);
                console.log("Unable to configure pinmux for: " + pin.name +
                    " (" + pin.mux + ")");
                console.log("Trying: mount -t debugfs none /sys/kernel/debug");
                //var state =
                //    fs.readFileSync("/sys/kernel/debug/omap_mux/" + pin.mux);
                //console.log("pinmux state: ");
                //console.log("" + state);

                // Configure the pinmux later once mount has run
                child_process.exec("mount -t debugfs none /sys/kernel/debug",
                    function(error, stderr, stdout) {
                        if(mode == OUTPUT) var muxfile = fs.writeFile("/sys/kernel/debug/omap_mux/" + pin.mux, "7");
                            else var muxfile = fs.writeFile("/sys/kernel/debug/omap_mux/" + pin.mux, "27");
                    }
                );
            }
        }

        // Export the GPIO controls
        try {
              var exists = path.existsSync("/sys/class/gpio/gpio" + n);
              if(exists) {
                      console.log("gpio: " + n + " already exported.");
                  } else {
                      try {
                          fs.writeFileSync("/sys/class/gpio/export", "" + n,null);
                      } catch(ex2) {
                          console.log(ex2);
                          console.log("Unable to export gpio: " + n);
                      }
                  }
            fs.writeFileSync("/sys/class/gpio/gpio" + n + "/direction",
                mode);
            gpio[n].path = "/sys/class/gpio/gpio" + n + "/value";
            return(true);
        } catch(ex) {
            // Perhaps we couldn't open it because it was allocated as an LED
            if(pin.led) {
                fs.writeFileSync(
                    "/sys/class/leds/beaglebone::" + pin.led + "/trigger",
                    "gpio");
                if(mode == OUTPUT) {
                    gpio[n].path =
                        "/sys/class/leds/beaglebone::" + pin.led +
                        "/brightness";
                } else {
                    gpio[n].path =
                        "/sys/class/leds/beaglebone::" + pin.led +
                        "/gpio";
                }
                return(true);
            }
        }
    }
};

digitalWrite = exports.digitalWrite = function(pin, value)
{
    fs.writeFileSync(gpio[pin.gpio].path, "" + value, null);
};

digitalRead = exports.digitalRead = function(pin)
{
    return fs.readFileSync(gpio[pin.gpio].path, null);
};

analogRead = exports.analogRead = function(pin)
{
    return fs.readFileSync("/sys/bus/platform/devices/tsc/ain" + (pin+1), null);
};

shiftOut = exports.shiftOut = function(dataPin, clockPin, bitOrder, val)
{
  var i;
  var bit;
  for (i = 0; i < 8; i++)
  {
    if (bitOrder == LSBFIRST)
    {
         bit = val & (1 << i);
    } else
    {
         bit = val & (1 << (7 - i));
    }

    digitalWrite(dataPin, bit);
    digitalWrite(clockPin, HIGH);
    digitalWrite(clockPin, LOW);
  }
};

// Wait for some time
if(fibers.exists) {
    delay = exports.delay = function(milliseconds)
    {
        var fiber = Fiber.current;
        setTimeout(function() {
            fiber.run();
        }, milliseconds);
        yield();
    };
} else {
    delay = exports.delay = function(milliseconds)
    {
        var startTime = new Date().getTime();
        while(new Date().getTime() < startTime + milliseconds) {
        }
    };
}

// This is where everything is meant to happen
if(fibers.exists) {
    run = exports.run = function()
    {
        Fiber(function() {
            var fiber = Fiber.current;
            setup();
            if(typeof loop === "function") {
                while(true) {
                    loop();
                    setTimeout(function() {
                        fiber.run();
                    }, 0);
		            yield();
		        }
            }
        }).run();
    };
} else {
    run = exports.run = function()
    {
        setup();
        if(typeof loop === "function") {
            process.nextTick(function repeat() {
                loop();
                process.nextTick(repeat);
            });
        }
    };
}

// This is a helper function for web servers
var loadFile = function(uri, subdir, res, type) {
    var filename = path.join(subdir, uri);
    path.exists(
        filename,
        function(exists) {
            if(!exists) {
                res.writeHead(404, {"Content-Type": "text/plain"});
                res.write("Error 404: '" + uri + "' Not Found\n");
                res.end();
                return;
            }
            if(type == "binary") {
                fs.readFile(
                    filename,
                    "binary",
                    function(err, file) {
                        if(err) {
                            res.writeHead(500, {"Content-Type": "text/plain"});
                            res.write(err + "\n");
                            res.end();
                            return;
                        }
                        res.writeHead(200);
                        res.write(file, "binary");
                        res.end();
                    }
                );
            } else {
                fs.readFile(
                    filename,
                    encoding='utf8',
                    function(err, file) {
                        if(err) {
                            res.writeHead(500, {"Content-Type": "text/plain"});
                            res.write(err + "\n");
                            res.end();
                            return;
                        }
                        res.writeHead(200, {"Content-Type": type});
                        res.write("" + file);
                        res.end();
                    }
                );
            }
        }
    );
};

// most heavily borrowed from https://github.com/itchyny/browsershell
var spawn = function(socket) {
    var stream = '';
    var timer;
    var len = 0;
    var c;

    var send = function (data) {
       // add data to the stream
       stream += data.toString();
       ++len;

       // clear any existing timeout if it exists
       if(timer) clearTimeout(timer);

       // set new timeout
       timer = setTimeout(function () {
           socket.emit('shell', stream);
           stream = '';
           len = 0;
       }, 100);

       // send data if over threshold
       if(len > 1000)
       {
           clearTimeout(timer);
           socket.emit('shell', stream);
           stream = '';
           len = 0;
       }
    };

    var receive = function (msg) {
        if(!c) {
            try {
                console.log('Spawning bash');
                c = child_process.spawn('/bin/bash', ['-i']);
                c.stdout.on('data', send);
                c.stderr.on('data', send);
                c.on('exit', function() {
                    socket.emit('shell', send('\nexited\n'));
                    c = undefined;
                });
            } catch(ex) {
                c = undefined;
                send('Error invoking bash');
                console.log('Error invoking bash');
            }
        }
        if(c) {
            if(msg) {
                c.stdin.write(msg + '\n', encoding='utf-8');
            }
        } else {
            console.log('Unable to invoke child process');
        }
    };
    receive();

    return(receive);
};

var addSocketListeners = function() {};
if(socket.exists) {
    addSocketListeners = function(server, onconnect) {
        var io = socket.listen(server);
        io.sockets.on('connection', function(socket) {
            var sessionId = socket.sessionId;
            console.log('Client connected: ' + sessionId);

            // on message
            socket.on('message', function(data) {
                console.log("Got message from client:", data);
            });

            // on disconnect
            socket.on('disconnect', function() {
                console.log("Client disconnected:" + sessionId);
            });

            // send expansion pin info
            socket.emit('muxstruct', bone);

            // send eeprom info
            var EepromFiles = {
                '/sys/bus/i2c/drivers/at24/1-0050/eeprom': { type: 'bone' },
                '/sys/bus/i2c/drivers/at24/3-0054/eeprom': { type: 'cape' },
                '/sys/bus/i2c/drivers/at24/3-0055/eeprom': { type: 'cape' },
                '/sys/bus/i2c/drivers/at24/3-0056/eeprom': { type: 'cape' },
                '/sys/bus/i2c/drivers/at24/3-0057/eeprom': { type: 'cape' },
            };
            var eeproms = eeprom.readEeproms(EepromFiles);
            if(eeproms == {}) {
                console.warn('No valid EEPROM contents found');
            } else {
                socket.emit('eeproms', eeproms);
            }

            // listen for requests and reads the debugfs entry async
            socket.on('listMux', function(pinname, fn) {
                console.log(pinname + ": " + bone[pinname].mux);
                path.exists("/sys/kernel/debug/omap_mux/" + bone[pinname].mux, function(exists) {
                    if(exists) {
                        fs.readFile("/sys/kernel/debug/omap_mux/" + bone[pinname].mux, 'utf8', function (err, data) {
                            fn(data, pinname);
                        });
                    } else {
                        // default mux
                        console.log(bone[pinname].mux + ": default mux");
                        fn("0", pinname);
                    }
                });
            });

            // listen for shell commands
            var myshell = spawn(socket);
            socket.on('shell', function(shellMsg) {
                console.log('shell: ' + shellMsg);
                myshell(shellMsg);
            });

            // call user-provided on-connect function
            if(typeof onconnect == 'function')
                onconnect(socket);

            // provide client basic platform information
            socket.emit('init', { 'platform': bone });
        });
    };
}

exports.Server = function(port, subdir, onconnect) {
    subdir = path.join(process.cwd(), subdir);
    var handler = function(req, res) {
        var uri = url.parse(req.url).pathname;
        if(uri == '/') {
            loadFile('index.html', subdir, res, "text/html");
        } else {
            if(uri.match(/\.js$/i)) {
                loadFile(uri, subdir, res, "application/javascript");
            } else if(uri.match(/\.css$/i)) {
                loadFile(uri, subdir, res, "text/css");
            } else if(uri.match(/\.htm(.)$/i)) {
                loadFile(uri, subdir, res, "text/html");
            } else if(uri.match(/\.(jpg|png|ico)$/i)) {
                loadFile(uri, subdir, res, "binary");
            } else {
                loadFile(uri, subdir, res, "text/plain");
            }
        }
    };
    this.server6 = http.createServer();
    this.server6.addListener('request', handler);
    addSocketListeners(this.server6, onconnect);
    this.server = http.createServer();
    this.server.addListener('request', handler);
    addSocketListeners(this.server, onconnect);
    this.begin = function() {
        this.server6.listen(port, '::0');
        this.server.listen(port);
    };
};
<commit_msg>bonescript: fix reference to eeprom<commit_after>// Copyright (C) 2011 - Texas Instruments, Jason Kridner
//
//
var fs = require('fs');
var child_process = require('child_process');
var http = require('http');
var url = require('url');
var path = require('path');
var events = require('events');
var eeprom = require('./eeprom');
bone = require('./bone').bone;

var myrequire = function(packageName, onfail) {
    var y = {};
    try {
        y = require(packageName);
        y.exists = true;
    } catch(ex) {
        y.exists = false;
        console.log("'" + packageName + "' not loaded");
        console.log("If desired, try installing it with:");
        console.log("  curl http://npmjs.org/install.sh | bash");
        console.log("  npm install " + packageName);
        onfail();
    }
    return(y);
};

var socket = myrequire('socket.io', function() {
    console.log("Dynamic web features not enabled");
});

var binary = myrequire('binary', function() { });
var inotify = myrequire('inotify', function() { });

var fibers = myrequire('fibers', function() {
    console.log("Delay operations loops will consume CPU cycles");
    console.log("Invoke using 'node-fibers' if node version < 0.5.2");
});

OUTPUT = exports.OUTPUT = "out";
INPUT = exports.INPUT = "in";
HIGH = exports.HIGH = 1;
LOW = exports.LOW = 0;
LSBFIRST = 1;  // used in: shiftOut(dataPin, clockPin, bitOrder, val)
MSBFIRST = 0;

var gpio = [];

pinMode = exports.pinMode = function(pin, mode)
{
    var n = pin.gpio;

    if(!gpio[n] || !gpio[n].path) {
        gpio[n] = {};

        // Ensure the pin is in GPIO mode
        if(pin.mux) {
            try {
                var muxfile = fs.openSync(
                    "/sys/kernel/debug/omap_mux/" + pin.mux, "w"
                );
                if(mode == OUTPUT)  fs.writeSync(muxfile, "7", null);
                    else fs.writeSync(muxfile, "27", null);
            } catch(ex3) {
                console.log("" + ex3);
                console.log("Unable to configure pinmux for: " + pin.name +
                    " (" + pin.mux + ")");
                console.log("Trying: mount -t debugfs none /sys/kernel/debug");
                //var state =
                //    fs.readFileSync("/sys/kernel/debug/omap_mux/" + pin.mux);
                //console.log("pinmux state: ");
                //console.log("" + state);

                // Configure the pinmux later once mount has run
                child_process.exec("mount -t debugfs none /sys/kernel/debug",
                    function(error, stderr, stdout) {
                        if(mode == OUTPUT) var muxfile = fs.writeFile("/sys/kernel/debug/omap_mux/" + pin.mux, "7");
                            else var muxfile = fs.writeFile("/sys/kernel/debug/omap_mux/" + pin.mux, "27");
                    }
                );
            }
        }

        // Export the GPIO controls
        try {
              var exists = path.existsSync("/sys/class/gpio/gpio" + n);
              if(exists) {
                      console.log("gpio: " + n + " already exported.");
                  } else {
                      try {
                          fs.writeFileSync("/sys/class/gpio/export", "" + n,null);
                      } catch(ex2) {
                          console.log(ex2);
                          console.log("Unable to export gpio: " + n);
                      }
                  }
            fs.writeFileSync("/sys/class/gpio/gpio" + n + "/direction",
                mode);
            gpio[n].path = "/sys/class/gpio/gpio" + n + "/value";
            return(true);
        } catch(ex) {
            // Perhaps we couldn't open it because it was allocated as an LED
            if(pin.led) {
                fs.writeFileSync(
                    "/sys/class/leds/beaglebone::" + pin.led + "/trigger",
                    "gpio");
                if(mode == OUTPUT) {
                    gpio[n].path =
                        "/sys/class/leds/beaglebone::" + pin.led +
                        "/brightness";
                } else {
                    gpio[n].path =
                        "/sys/class/leds/beaglebone::" + pin.led +
                        "/gpio";
                }
                return(true);
            }
        }
    }
};

digitalWrite = exports.digitalWrite = function(pin, value)
{
    fs.writeFileSync(gpio[pin.gpio].path, "" + value, null);
};

digitalRead = exports.digitalRead = function(pin)
{
    return fs.readFileSync(gpio[pin.gpio].path, null);
};

analogRead = exports.analogRead = function(pin)
{
    return fs.readFileSync("/sys/bus/platform/devices/tsc/ain" + (pin+1), null);
};

shiftOut = exports.shiftOut = function(dataPin, clockPin, bitOrder, val)
{
  var i;
  var bit;
  for (i = 0; i < 8; i++)
  {
    if (bitOrder == LSBFIRST)
    {
         bit = val & (1 << i);
    } else
    {
         bit = val & (1 << (7 - i));
    }

    digitalWrite(dataPin, bit);
    digitalWrite(clockPin, HIGH);
    digitalWrite(clockPin, LOW);
  }
};

// Wait for some time
if(fibers.exists) {
    delay = exports.delay = function(milliseconds)
    {
        var fiber = Fiber.current;
        setTimeout(function() {
            fiber.run();
        }, milliseconds);
        yield();
    };
} else {
    delay = exports.delay = function(milliseconds)
    {
        var startTime = new Date().getTime();
        while(new Date().getTime() < startTime + milliseconds) {
        }
    };
}

// This is where everything is meant to happen
if(fibers.exists) {
    run = exports.run = function()
    {
        Fiber(function() {
            var fiber = Fiber.current;
            setup();
            if(typeof loop === "function") {
                while(true) {
                    loop();
                    setTimeout(function() {
                        fiber.run();
                    }, 0);
		            yield();
		        }
            }
        }).run();
    };
} else {
    run = exports.run = function()
    {
        setup();
        if(typeof loop === "function") {
            process.nextTick(function repeat() {
                loop();
                process.nextTick(repeat);
            });
        }
    };
}

// This is a helper function for web servers
var loadFile = function(uri, subdir, res, type) {
    var filename = path.join(subdir, uri);
    path.exists(
        filename,
        function(exists) {
            if(!exists) {
                res.writeHead(404, {"Content-Type": "text/plain"});
                res.write("Error 404: '" + uri + "' Not Found\n");
                res.end();
                return;
            }
            if(type == "binary") {
                fs.readFile(
                    filename,
                    "binary",
                    function(err, file) {
                        if(err) {
                            res.writeHead(500, {"Content-Type": "text/plain"});
                            res.write(err + "\n");
                            res.end();
                            return;
                        }
                        res.writeHead(200);
                        res.write(file, "binary");
                        res.end();
                    }
                );
            } else {
                fs.readFile(
                    filename,
                    encoding='utf8',
                    function(err, file) {
                        if(err) {
                            res.writeHead(500, {"Content-Type": "text/plain"});
                            res.write(err + "\n");
                            res.end();
                            return;
                        }
                        res.writeHead(200, {"Content-Type": type});
                        res.write("" + file);
                        res.end();
                    }
                );
            }
        }
    );
};

// most heavily borrowed from https://github.com/itchyny/browsershell
var spawn = function(socket) {
    var stream = '';
    var timer;
    var len = 0;
    var c;

    var send = function (data) {
       // add data to the stream
       stream += data.toString();
       ++len;

       // clear any existing timeout if it exists
       if(timer) clearTimeout(timer);

       // set new timeout
       timer = setTimeout(function () {
           socket.emit('shell', stream);
           stream = '';
           len = 0;
       }, 100);

       // send data if over threshold
       if(len > 1000)
       {
           clearTimeout(timer);
           socket.emit('shell', stream);
           stream = '';
           len = 0;
       }
    };

    var receive = function (msg) {
        if(!c) {
            try {
                console.log('Spawning bash');
                c = child_process.spawn('/bin/bash', ['-i']);
                c.stdout.on('data', send);
                c.stderr.on('data', send);
                c.on('exit', function() {
                    socket.emit('shell', send('\nexited\n'));
                    c = undefined;
                });
            } catch(ex) {
                c = undefined;
                send('Error invoking bash');
                console.log('Error invoking bash');
            }
        }
        if(c) {
            if(msg) {
                c.stdin.write(msg + '\n', encoding='utf-8');
            }
        } else {
            console.log('Unable to invoke child process');
        }
    };
    receive();

    return(receive);
};

var addSocketListeners = function() {};
if(socket.exists) {
    addSocketListeners = function(server, onconnect) {
        var io = socket.listen(server);
        io.sockets.on('connection', function(socket) {
            var sessionId = socket.sessionId;
            console.log('Client connected: ' + sessionId);

            // on message
            socket.on('message', function(data) {
                console.log("Got message from client:", data);
            });

            // on disconnect
            socket.on('disconnect', function() {
                console.log("Client disconnected:" + sessionId);
            });

            // send expansion pin info
            socket.emit('muxstruct', bone);

            // send eeprom info
            var EepromFiles = {
                '/sys/bus/i2c/drivers/at24/1-0050/eeprom': { type: 'bone' },
                '/sys/bus/i2c/drivers/at24/3-0054/eeprom': { type: 'cape' },
                '/sys/bus/i2c/drivers/at24/3-0055/eeprom': { type: 'cape' },
                '/sys/bus/i2c/drivers/at24/3-0056/eeprom': { type: 'cape' },
                '/sys/bus/i2c/drivers/at24/3-0057/eeprom': { type: 'cape' },
            };
            var eeproms = eeprom.readEeproms(EepromFiles);
            if(eeproms == {}) {
                console.warn('No valid EEPROM contents found');
            } else {
                socket.emit('eeproms', eeproms);
            }

            // listen for requests and reads the debugfs entry async
            socket.on('listMux', function(pinname, fn) {
                console.log(pinname + ": " + bone[pinname].mux);
                path.exists("/sys/kernel/debug/omap_mux/" + bone[pinname].mux, function(exists) {
                    if(exists) {
                        fs.readFile("/sys/kernel/debug/omap_mux/" + bone[pinname].mux, 'utf8', function (err, data) {
                            fn(data, pinname);
                        });
                    } else {
                        // default mux
                        console.log(bone[pinname].mux + ": default mux");
                        fn("0", pinname);
                    }
                });
            });

            // listen for shell commands
            var myshell = spawn(socket);
            socket.on('shell', function(shellMsg) {
                console.log('shell: ' + shellMsg);
                myshell(shellMsg);
            });

            // call user-provided on-connect function
            if(typeof onconnect == 'function')
                onconnect(socket);

            // provide client basic platform information
            socket.emit('init', { 'platform': bone });
        });
    };
}

exports.Server = function(port, subdir, onconnect) {
    subdir = path.join(process.cwd(), subdir);
    var handler = function(req, res) {
        var uri = url.parse(req.url).pathname;
        if(uri == '/') {
            loadFile('index.html', subdir, res, "text/html");
        } else {
            if(uri.match(/\.js$/i)) {
                loadFile(uri, subdir, res, "application/javascript");
            } else if(uri.match(/\.css$/i)) {
                loadFile(uri, subdir, res, "text/css");
            } else if(uri.match(/\.htm(.)$/i)) {
                loadFile(uri, subdir, res, "text/html");
            } else if(uri.match(/\.(jpg|png|ico)$/i)) {
                loadFile(uri, subdir, res, "binary");
            } else {
                loadFile(uri, subdir, res, "text/plain");
            }
        }
    };
    this.server6 = http.createServer();
    this.server6.addListener('request', handler);
    addSocketListeners(this.server6, onconnect);
    this.server = http.createServer();
    this.server.addListener('request', handler);
    addSocketListeners(this.server, onconnect);
    this.begin = function() {
        this.server6.listen(port, '::0');
        this.server.listen(port);
    };
};
<|endoftext|>


<commit_before>'use strict';

var m = require('mithril');
var parseDomain = require('parse-domain');
var app = 'com.dannyvankooten.browserpass';
var activeTab;
var searching = false;
var logins = null;
var domain, urlDuringSearch;

m.mount(document.getElementById('mount'), { "view": view });

chrome.browserAction.setIcon({ path: 'icon-lock.svg' });
chrome.tabs.onActivated.addListener(init);
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
  init(tabs[0]);
});

function view() {
  var results = '';

  if( searching ) {
    results = m('div.loader');
  } else if( logins !== null ) {
    if( typeof(logins) === "undefined" ) {
      results = m('div.status-text', "Error talking to Browserpass host");
    } else if( logins.length === 0 ) {
      results = m('div.status-text',  m.trust(`No passwords found for <strong>${domain}</strong>.`));
    } else if( logins.length > 0 ) {
        results = logins.map(function(l) {
          var faviconUrl = getFaviconUrl(domain);
          return m('button.login', {
            "onclick": getLoginData.bind(l),
            "style": `background-image: url('${faviconUrl}')`
          },
          l)
        });
    }
  }

  return [
    // search form
    m('div.search', [
      m('form', {
        "onsubmit": submitSearchForm
      }, [
        m('input', {
          "type": "text",
          "name": "s",
          "placeholder": "Search password..",
          "autocomplete": "off",
          "autofocus": "on"
        }),
        m('input', {
          "type": "submit",
          "value": "Search",
          "style": "display: none;"
        })
      ])
    ]),

    // results
    m('div.results', results)
  ];
}

function submitSearchForm(e) {
  e.preventDefault();

  // don't search without input.
  if( ! this.s.value.length ) {
      return;
  }

  searchPassword(this.s.value);
}

function init(tab) {
  // do nothing if called from a non-tab context
  if( ! tab || ! tab.url ) {
    return;
  }

  activeTab = tab;
  var parsedDomain = parseDomain(tab.url, {
    customTlds:/localhost/,
  });

  if( parsedDomain ) {
    var searchDomain = [parsedDomain.domain, parsedDomain.tld]
      .filter(function (x) { return x; })
      .join('.');

    if( searchDomain ) {
      searchPassword(searchDomain);
    }
  }
}

function searchPassword(_domain) {
  searching = true;
  logins = null;
  domain = _domain;
  urlDuringSearch = activeTab.url;
  m.redraw();

  chrome.runtime.sendNativeMessage(app, { "action": "search", "domain": _domain }, function(response) {
    if( chrome.runtime.lastError ) {
      console.log(chrome.runtime.lastError);
    }

    searching = false;
    logins = response;
    m.redraw();
  });
}

function getFaviconUrl(domain){

  // use current favicon when searching for current tab
  if(activeTab && activeTab.favIconUrl && activeTab.favIconUrl.indexOf(domain) > -1) {
    return activeTab.favIconUrl;
  }

  return 'icon-key.png';
}

function getLoginData() {
  searching = true;
  logins = null;
  m.redraw();

  chrome.runtime.sendNativeMessage(app, { "action": "get", "entry": this }, function(response) {
    if( chrome.runtime.lastError) {
      console.log(chrome.runtime.lastError);
    }

    searching = false;
    fillLoginForm(response);
  });
}

// fill login form & submit
function fillLoginForm(login) {
  // do not send login data to page if URL changed during search.
  if( activeTab.url != urlDuringSearch ) {
    return false;
  }

  var code = `
  (function(d) {
    function queryFirstVisible(parent, selector) {
      var elems = parent.querySelectorAll(selector);
      for (var i=0; i < elems.length; i++) {
        var style = window.getComputedStyle(elems[i]);
        if (style.visibility !== 'hidden' && style.display !== 'none') {
          return elems[i];
        }
      }
    }

    function form() {
      var passwordField = queryFirstVisible(d, 'input[type=password]');
      return (passwordField && passwordField.form) ? passwordField.form : undefined;
    }

    function field(selector) {
      return queryFirstVisible(form(), selector) || document.createElement('input');
    }

    function update(el, value) {
      if( ! value.length ) {
        return false;
      }

      el.setAttribute('value', value);
      el.value = value;

      var eventNames = [ 'click', 'focus', 'keyup', 'keydown', 'change', 'blur' ];
      eventNames.forEach(function(eventName) {
        el.dispatchEvent(new Event(eventName, {"bubbles":true}));
      });
      return true;
    }

    if (typeof form() === 'undefined') {
      return;
    }

    update(field('input[type=password]'), ${JSON.stringify(login.p)});
    update(field('input[type=email], input[type=text]'), ${JSON.stringify(login.u)});

    var password_inputs = document.querySelectorAll('input[type=password]');
    if (password_inputs.length > 1) {
      password_inputs[1].select();
    } else {
      field('[type=submit]').click();
    }
  })(document);
  `;
  chrome.tabs.executeScript({ code: code, allFrames: true });
  window.close();
}
<commit_msg>Add extra cases: element's parent is hidden, element is too narrow<commit_after>'use strict';

var m = require('mithril');
var parseDomain = require('parse-domain');
var app = 'com.dannyvankooten.browserpass';
var activeTab;
var searching = false;
var logins = null;
var domain, urlDuringSearch;

m.mount(document.getElementById('mount'), { "view": view });

chrome.browserAction.setIcon({ path: 'icon-lock.svg' });
chrome.tabs.onActivated.addListener(init);
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
  init(tabs[0]);
});

function view() {
  var results = '';

  if( searching ) {
    results = m('div.loader');
  } else if( logins !== null ) {
    if( typeof(logins) === "undefined" ) {
      results = m('div.status-text', "Error talking to Browserpass host");
    } else if( logins.length === 0 ) {
      results = m('div.status-text',  m.trust(`No passwords found for <strong>${domain}</strong>.`));
    } else if( logins.length > 0 ) {
        results = logins.map(function(l) {
          var faviconUrl = getFaviconUrl(domain);
          return m('button.login', {
            "onclick": getLoginData.bind(l),
            "style": `background-image: url('${faviconUrl}')`
          },
          l)
        });
    }
  }

  return [
    // search form
    m('div.search', [
      m('form', {
        "onsubmit": submitSearchForm
      }, [
        m('input', {
          "type": "text",
          "name": "s",
          "placeholder": "Search password..",
          "autocomplete": "off",
          "autofocus": "on"
        }),
        m('input', {
          "type": "submit",
          "value": "Search",
          "style": "display: none;"
        })
      ])
    ]),

    // results
    m('div.results', results)
  ];
}

function submitSearchForm(e) {
  e.preventDefault();

  // don't search without input.
  if( ! this.s.value.length ) {
      return;
  }

  searchPassword(this.s.value);
}

function init(tab) {
  // do nothing if called from a non-tab context
  if( ! tab || ! tab.url ) {
    return;
  }

  activeTab = tab;
  var parsedDomain = parseDomain(tab.url, {
    customTlds:/localhost/,
  });

  if( parsedDomain ) {
    var searchDomain = [parsedDomain.domain, parsedDomain.tld]
      .filter(function (x) { return x; })
      .join('.');

    if( searchDomain ) {
      searchPassword(searchDomain);
    }
  }
}

function searchPassword(_domain) {
  searching = true;
  logins = null;
  domain = _domain;
  urlDuringSearch = activeTab.url;
  m.redraw();

  chrome.runtime.sendNativeMessage(app, { "action": "search", "domain": _domain }, function(response) {
    if( chrome.runtime.lastError ) {
      console.log(chrome.runtime.lastError);
    }

    searching = false;
    logins = response;
    m.redraw();
  });
}

function getFaviconUrl(domain){

  // use current favicon when searching for current tab
  if(activeTab && activeTab.favIconUrl && activeTab.favIconUrl.indexOf(domain) > -1) {
    return activeTab.favIconUrl;
  }

  return 'icon-key.png';
}

function getLoginData() {
  searching = true;
  logins = null;
  m.redraw();

  chrome.runtime.sendNativeMessage(app, { "action": "get", "entry": this }, function(response) {
    if( chrome.runtime.lastError) {
      console.log(chrome.runtime.lastError);
    }

    searching = false;
    fillLoginForm(response);
  });
}

// fill login form & submit
function fillLoginForm(login) {
  // do not send login data to page if URL changed during search.
  if( activeTab.url != urlDuringSearch ) {
    return false;
  }

  var code = `
  (function(d) {
    function queryFirstVisible(parent, selector) {
      var elems = parent.querySelectorAll(selector);
      for (var i=0; i < elems.length; i++) {
        // Elem or its parent has a style 'display: none',
        // or it is just too narrow to be a real field (a trap for spammers?).
        if (elems[i].offsetWidth < 50 || elems[i].offsetHeight < 10) { continue; }

        var style = window.getComputedStyle(elems[i]);
        // Elem takes space on the screen, but it or its parent is hidden with a visibility style.
        if (style.visibility == 'hidden') { continue; }

        // This element is visible, will use it.
        return elems[i];
      }
    }

    function form() {
      var passwordField = queryFirstVisible(d, 'input[type=password]');
      return (passwordField && passwordField.form) ? passwordField.form : undefined;
    }

    function field(selector) {
      return queryFirstVisible(form(), selector) || document.createElement('input');
    }

    function update(el, value) {
      if( ! value.length ) {
        return false;
      }

      el.setAttribute('value', value);
      el.value = value;

      var eventNames = [ 'click', 'focus', 'keyup', 'keydown', 'change', 'blur' ];
      eventNames.forEach(function(eventName) {
        el.dispatchEvent(new Event(eventName, {"bubbles":true}));
      });
      return true;
    }

    if (typeof form() === 'undefined') {
      return;
    }

    update(field('input[type=password]'), ${JSON.stringify(login.p)});
    update(field('input[type=email], input[type=text]'), ${JSON.stringify(login.u)});

    var password_inputs = document.querySelectorAll('input[type=password]');
    if (password_inputs.length > 1) {
      password_inputs[1].select();
    } else {
      field('[type=submit]').click();
    }
  })(document);
  `;
  chrome.tabs.executeScript({ code: code, allFrames: true });
  window.close();
}
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var randu = require( '@stdlib/math/base/random/randu' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
var skewness = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof skewness, 'function', 'main export is a function' );
	t.end();
});

tape( 'if provided `NaN` for any parameter, the function returns `NaN`', function test( t ) {
	var y = skewness( NaN, 1.0 );
	t.equal( isnan( y ), true, 'returns NaN' );
	y = skewness( 1.0, NaN );
	t.equal( isnan( y ), true, 'returns NaN' );
	t.end();
});

tape( 'if provided a nonpositive `beta`, the function returns `NaN`', function test( t ) {
	var y;

	y = skewness( 2.0, 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( 2.0, -1.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( 2.0, -1.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( 1.0, NINF );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( PINF, NINF );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( NINF, NINF );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( NaN, NINF );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'the function returns `~1.14` as the skewness of a uniform distribution ', function test( t ) {
	var a;
	var b;
	var i;
	var v;

	for ( i = 0; i < 10; i++ ) {
		a = ( randu()*10.0 );
		b = ( randu()*10.0 ) + a;
		v = skewness( a, b );
		t.equal( v, 1.1395470994046488, 'returns ~1.14' );
	}
	t.end();
});
<commit_msg>Fix copy-paste errors<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var randu = require( '@stdlib/math/base/random/randu' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
var skewness = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof skewness, 'function', 'main export is a function' );
	t.end();
});

tape( 'if provided `NaN` for any parameter, the function returns `NaN`', function test( t ) {
	var y = skewness( NaN, 1.0 );
	t.equal( isnan( y ), true, 'returns NaN' );
	y = skewness( 1.0, NaN );
	t.equal( isnan( y ), true, 'returns NaN' );
	t.end();
});

tape( 'if provided a nonpositive `beta`, the function returns `NaN`', function test( t ) {
	var y;

	y = skewness( 2.0, 0.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( 2.0, -1.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( 2.0, -1.0 );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( 1.0, NINF );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( PINF, NINF );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( NINF, NINF );
	t.equal( isnan( y ), true, 'returns NaN' );

	y = skewness( NaN, NINF );
	t.equal( isnan( y ), true, 'returns NaN' );

	t.end();
});

tape( 'the function returns `~1.14` as the skewness of a Gumbel distribution ', function test( t ) {
	var a;
	var b;
	var i;
	var v;

	for ( i = 0; i < 10; i++ ) {
		a = ( randu()*10.0 );
		b = ( randu()*10.0 ) + a;
		v = skewness( a, b );
		t.equal( v, 1.1395470994046488, 'returns ~1.14' );
	}
	t.end();
});
<|endoftext|>


<commit_before>'use strict';

/*
* The original C++ code and copyright notice is from the [Boost library]{@link http://www.boost.org/doc/libs/1_48_0/boost/math/special_functions/gamma.hpp}.
*
* This implementation follows the original, but has been modified for JavaScript.
*/

/*
* (C) Copyright John Maddock 2006.
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/

// MODULES //

var gammaln = require( '@stdlib/math/base/special/gammaln' );
var gamma = require( '@stdlib/math/base/special/gamma' );
var expm1 = require( '@stdlib/math/base/special/expm1' );
var log1p = require( '@stdlib/math/base/special/log1p' );

// MAIN //

/**
* Computes `Γ(x+1) - 1`.
*
* @private
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var v = gammap1m1( 1e-3 );
* // returns ~-0.001
*
* @example
* var v = gammap1m1( -3/2 );
* // returns ~-4.545
*
* @example
* var v = gammap1m1( 4.0 );
* // returns 23
*
* @example
* var v = gammap1m1( 1/2 );
* // returns ~-0.114
*
* @example
* var v = gammap1m1( NaN );
* // returns NaN
*/
function gammap1m1( x ) {
	var result;
	if ( x < 0.0 ) {
		if ( x < -0.5 ) {
			// Best method is simply to subtract 1 from gamma:
			result = gamma( 1.0 + x ) - 1.0;
		} else {
			// Use expm1 on gammaln:
			result = expm1( -log1p(x) + gammaln( x + 2.0 ) );
		}
	} else {
		/* eslint-disable no-lonely-if */
		if ( x < 2.0 ) {
			// Use expm1 on gammaln:
			result = expm1( gammaln( x + 1.0 ) );
		} else {
			// Best method is simply to subtract 1 from gamma:
			result = gamma( 1.0 + x ) - 1.0;
		}
	}
	return result;
} // end FUNCTION gammap1m1()

// EXPORTS //

module.exports = gammap1m1;
<commit_msg>Refactor to avoid nested if-clauses<commit_after>'use strict';

/*
* The original C++ code and copyright notice is from the [Boost library]{@link http://www.boost.org/doc/libs/1_48_0/boost/math/special_functions/gamma.hpp}.
*
* This implementation follows the original, but has been modified for JavaScript.
*/

/*
* (C) Copyright John Maddock 2006.
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/

// MODULES //

var gammaln = require( '@stdlib/math/base/special/gammaln' );
var gamma = require( '@stdlib/math/base/special/gamma' );
var expm1 = require( '@stdlib/math/base/special/expm1' );
var log1p = require( '@stdlib/math/base/special/log1p' );

// MAIN //

/**
* Computes `Γ(x+1) - 1`.
*
* @private
* @param {number} x - input value
* @returns {number} function value
*
* @example
* var v = gammap1m1( 1e-3 );
* // returns ~-0.001
*
* @example
* var v = gammap1m1( -3/2 );
* // returns ~-4.545
*
* @example
* var v = gammap1m1( 4.0 );
* // returns 23
*
* @example
* var v = gammap1m1( 1/2 );
* // returns ~-0.114
*
* @example
* var v = gammap1m1( NaN );
* // returns NaN
*/
function gammap1m1( x ) {
	if ( x < -0.5 ) {
		// Best method is simply to subtract 1 from gamma:
		return gamma( 1.0 + x ) - 1.0;
	}
	if ( x < 0.0 ) {
		// Use expm1 on gammaln:
		return expm1( -log1p(x) + gammaln( x + 2.0 ) );
	}
	if ( x < 2.0 ) {
		// Use expm1 on gammaln:
		return expm1( gammaln( x + 1.0 ) );
	}
	// Best method is simply to subtract 1 from gamma:
	return gamma( 1.0 + x ) - 1.0;
} // end FUNCTION gammap1m1()

// EXPORTS //

module.exports = gammap1m1;
<|endoftext|>


<commit_before>let status_label = {running: 'success', 'shut off': 'danger', 'paused': 'info'};

function enum_virsh() {
    $('.computer').each(function(i, a) {
        ws.emit('enum virsh', {device: a.id});
    });
}

function buttons(device) {
    let btn = '
';
    btn += '<button id="{}:start" type="button" class="btn btn-sm btn-success vm-control">Start</button>';
    btn += '<button id="{}:shutdown" type="button" class="btn btn-sm btn-danger vm-control">Stop</button>';
    btn += '<button id="{}:restart" type="button" class="btn btn-sm btn-warning vm-control">Restart</button>';
    btn += '
';
    return btn.replace(/{}/g, device);
}

$('body').on('click', 'button.vm-control', function(a) {
    let s = a.target.id.split(':');
    ws.emit('vm ctrl', {
        device: s[0],
        vm: s[1],
        action: s[2]
    });
    setInterval(enum_virsh, 3000);
    setInterval(enum_virsh, 5000);
});

ws.on('vms', function(data) {
    var device = $('#' + data.device + '-table');
    device.html('');
    $.each(data.vms, function(a, b) {
        var status = '' + b[1] + '';
        device.append('
' + b[0] + '	' + status + '	' + buttons(data.device + '-' + b[0]) + '
');
    });
});

$('.refresh-vms').click(function() {
    enum_virsh();
    message({content: 'Refreshing...', class: 'alert-info'});
});

enum_virsh();
setInterval(enum_virsh, 15000);
<commit_msg>Actually fix #84<commit_after>let status_label = {running: 'success', 'shut off': 'danger', 'paused': 'info'};

function enum_virsh() {
    $('.computer').each(function(i, a) {
        ws.emit('enum virsh', {device: a.id});
    });
}

function buttons(device) {
    let btn = '
';
    btn += '<button id="{}:start" type="button" class="btn btn-sm btn-success vm-control">Start</button>';
    btn += '<button id="{}:shutdown" type="button" class="btn btn-sm btn-danger vm-control">Stop</button>';
    btn += '<button id="{}:restart" type="button" class="btn btn-sm btn-warning vm-control">Restart</button>';
    btn += '
';
    return btn.replace(/{}/g, device);
}

$('body').on('click', 'button.vm-control', function(a) {
    let s = a.target.id.split(':');
    ws.emit('vm ctrl', {
        device: s[0],
        vm: s[1],
        action: s[2]
    });
    setInterval(enum_virsh, 3000);
    setInterval(enum_virsh, 5000);
});

ws.on('vms', function(data) {
    let device = $('#' + data.device + '-table');
    device.html('');
    $.each(data.vms, function(a, b) {
        let status = '' + b[1] + '';
        device.append('
' + b[0] + '	' + status + '	' + buttons(data.device + ':' + b[0]) + '
');
    });
});

$('.refresh-vms').click(function() {
    enum_virsh();
    message({content: 'Refreshing...', class: 'alert-info'});
});

enum_virsh();
setInterval(enum_virsh, 15000);
<|endoftext|>


<commit_before>adminApp.AdminContributionsListPaymentDetailBox = {
  view: function(ctrl, args) {
    var contribution = args.contribution;
    return m("#admin-contribution-detail-box",[
      m(".w-row.u-marginbottom-30",[
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary[data-ix='show-dropdown'][href='#']", {style: {"transition": " all 0.5s ease 0s", " -webkit-transition": " all 0.5s ease 0s"}}, "Pedir reembolso"),
          m(".dropdown-list.card.u-radius.dropdown-list-medium.zindex-10[data-ix='display-none-on-load'][id='transfer']", {style: {"display": " none"}},[
            m(".fontsize-smaller.fontweight-semibold.u-text-center.u-marginbottom-20", "Quer efetuar o reembolso?"),
            m("a.btn.btn-small[href='#']", "Solicitar reembolso")
          ])
        ]),
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary[data-ix='show-dropdown'][href='#']", {style: {"transition": " all 0.5s ease 0s", " -webkit-transition": " all 0.5s ease 0s"}}, "Estornar"),
          m(".dropdown-list.card.u-radius.dropdown-list-medium.zindex-10[data-ix='display-none-on-load'][id='transfer']", {style: {"display": " none"}},[
            m(".fontsize-smaller.fontweight-semibold.u-text-center.u-marginbottom-20", "Quer efetuar o estorno?"),
            m("a.btn.btn-small[href='#']", "Solicitar estorno")
          ])
        ]),
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary.btn-desactivated[href='#']", "2a via")
        ]),
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary[data-ix='show-dropdown'][href='#']", {style: {"transition": " all 0.5s ease 0s", " -webkit-transition": " all 0.5s ease 0s"}}, "Transferir apoio"),
          m(".dropdown-list.card.u-radius.dropdown-list-medium.zindex-10[data-ix='display-none-on-load'][id='transfer']", {style: {"display": " none"}},[
            m(".w-form",[
              m("form[data-name='Email Form 4'][id='email-form-4'][name='email-form-4']",[
                m("label[for='name-2']", "Id do novo apoiador:"),
                m("input.w-input.text-field[data-name='Name 2'][id='name-2'][name='name'][placeholder='ex: 129908'][type='text']"),
                m("input.w-button.btn.btn-small[data-wait='Please wait...'][type='submit'][value='Transferir']")
              ])
            ])
          ])
        ]),
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary[data-ix='show-dropdown'][href='#']", {style: {"transition": " all 0.5s ease 0s", " -webkit-transition": " all 0.5s ease 0s"}}, "Trocar recompensa"),
          m(".dropdown-list.card.u-radius.dropdown-list-medium.zindex-10[data-ix='display-none-on-load'][id='transfer']", {style: {"display": " none"}},[
            m(".w-form",[
              m("form[data-name='Email Form 4'][id='email-form-4'][name='email-form-4']",[
                m(".w-radio",[
                  m("input.w-radio-input[data-name='Radio'][id='radio'][name='radio'][type='radio'][value='Radio']"),
                  m("label.w-form-label[for='radio']", "R$ 10")
                ]),
                m(".w-radio",[
                  m("input.w-radio-input[data-name='Radio 2'][id='radio'][name='radio-2'][type='radio'][value='Radio']"),
                  m("label.w-form-label[for='radio']", "R$ 10")]),
                  m(".w-radio",[
                    m("input.w-radio-input[data-name='Radio 2'][id='radio'][name='radio-2'][type='radio'][value='Radio']"),
                    m("label.w-form-label[for='radio']", "R$ 10")
                  ]),
                  m(".w-radio",[
                    m("input.w-radio-input[data-name='Radio 2'][id='radio'][name='radio-2'][type='radio'][value='Radio']"),
                    m("label.w-form-label[for='radio']", "R$ 10")
                  ]),
                  m(".w-radio",[
                    m("input.w-radio-input[data-name='Radio 2'][id='radio'][name='radio-2'][type='radio'][value='Radio']"),
                    m("label.w-form-label[for='radio']", "R$ 10")
                  ])
              ])
            ])
          ])
        ]),
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary[data-ix='show-dropdown'][href='#']", {style: {"transition": " all 0.5s ease 0s", " -webkit-transition": " all 0.5s ease 0s"}}, "Anonimato"),
          m(".dropdown-list.card.u-radius.dropdown-list-medium.zindex-10[data-ix='display-none-on-load'][id='transfer']", {style: {"display": " none"}},[
            m(".w-form",[
              m("form[data-name='Email Form 4'][id='email-form-4'][name='email-form-4']",[
                m(".w-radio",[
                  m("input.w-radio-input[data-name='Radio'][id='radio'][name='radio'][type='radio'][value='Radio']"),
                  m("label.w-form-label[for='radio']", "Anônimo")
                ]),
                m(".w-radio",[
                  m("input.w-radio-input[data-name='Radio 2'][id='radio'][name='radio-2'][type='radio'][value='Radio']"),
                  m("label.w-form-label[for='radio']", "Público")
                ])
              ])
            ])
          ])
        ])
      ]),
      m(".w-row.card.card-terciary.u-radius",[
        m(".w-col.w-col-4",[
          m(".fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-20", "Detalhes do apoio"),
          m(".fontsize-smallest.lineheight-looser",[
            "Valor: R$80\n",
            m("br"),
            "Taxa: R$3,35\n",
            m("br"),"Recompensa: R$80\n",
            m("br"),
            "Anônimo: Não\n",
            m("br"),
            "Id pagamento: 638912",
            m("br"),
            "Apoio: 54545454",
            m("br"),
            "Chave: \n",
            m("br"),
            "7809d09d-6325-442e-876e-b9a0846c526f\n",
            m("br"),
            "Meio: Pagarme\n",
            m("br"),
            "Operadora: STONE",
            m("br"),
            m("a.link-hidden[href='#']", "Boleto bancário"),
            " ",
            m("span.badge", "2a via")
          ])
        ]),
        m(".w-col.w-col-4",[
          m(".fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-20", "Histórico da transação"),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div", "Apoio criado")
            ])
          ]),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div", "Apoio criado")
            ])
          ]),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div",[
                m("span.badge.badge-attention.fontsize-smallest", "Estorno realizado")
              ])
            ])
          ]),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div", "Apoio criado")
            ])
          ]),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div", "Apoio criado")
            ])
          ]),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div", "Apoio criado"),
              m(".fontsize-smallest.lineheight-tighter",[
                m("span.badge", "Luis Otavio Ribeiro")
              ])
            ])
          ])
        ]),
        m(".w-col.w-col-4")
      ])
    ]);
  }
}

<commit_msg>create AdminContributionsListPaymentDetailBox component<commit_after>// AdminContributionsListPaymentDetailBox this component is used to
// create a box with more contribution details and actions like refund, 2via,
// change reward and a lot more... :)
adminApp.AdminContributionsListPaymentDetailBox = {
  view: function(ctrl, args) {
    var contribution = args.contribution;
    return m("#admin-contribution-detail-box", {style: {"transition": " all 0.5s ease 0s", " -webkit-transition": " all 0.5s ease 0s"}}, [
      m(".w-row.u-marginbottom-30",[
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary[data-ix='show-dropdown'][href='#']", "Pedir reembolso"),
          m(".dropdown-list.card.u-radius.dropdown-list-medium.zindex-10",[
            m(".fontsize-smaller.fontweight-semibold.u-text-center.u-marginbottom-20", "Quer efetuar o reembolso?"),
            m("a.btn.btn-small[href='#']", "Solicitar reembolso")
          ])
        ]),
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary[data-ix='show-dropdown'][href='#']", "Estornar"),
          m(".dropdown-list.card.u-radius.dropdown-list-medium.zindex-10",[
            m(".fontsize-smaller.fontweight-semibold.u-text-center.u-marginbottom-20", "Quer efetuar o estorno?"),
            m("a.btn.btn-small[href='#']", "Solicitar estorno")
          ])
        ]),
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary.btn-desactivated[href='#']", "2a via")
        ]),
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary[data-ix='show-dropdown'][href='#']", "Transferir apoio"),
          m(".dropdown-list.card.u-radius.dropdown-list-medium.zindex-10",[
            m(".w-form",[
              m("form[data-name='Email Form 4'][id='email-form-4'][name='email-form-4']",[
                m("label[for='name-2']", "Id do novo apoiador:"),
                m("input.w-input.text-field[data-name='Name 2'][id='name-2'][name='name'][placeholder='ex: 129908'][type='text']"),
                m("input.w-button.btn.btn-small[data-wait='Please wait...'][type='submit'][value='Transferir']")
              ])
            ])
          ])
        ]),
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary[data-ix='show-dropdown'][href='#']", "Trocar recompensa"),
          m(".dropdown-list.card.u-radius.dropdown-list-medium.zindex-10",[
            m(".w-form",[
              m("form[data-name='Email Form 4'][id='email-form-4'][name='email-form-4']",[
                m(".w-radio",[
                  m("input.w-radio-input[data-name='Radio'][id='radio'][name='radio'][type='radio'][value='Radio']"),
                  m("label.w-form-label[for='radio']", "R$ 10")
                ]),
                m(".w-radio",[
                  m("input.w-radio-input[data-name='Radio 2'][id='radio'][name='radio-2'][type='radio'][value='Radio']"),
                  m("label.w-form-label[for='radio']", "R$ 10")]),
                  m(".w-radio",[
                    m("input.w-radio-input[data-name='Radio 2'][id='radio'][name='radio-2'][type='radio'][value='Radio']"),
                    m("label.w-form-label[for='radio']", "R$ 10")
                  ]),
                  m(".w-radio",[
                    m("input.w-radio-input[data-name='Radio 2'][id='radio'][name='radio-2'][type='radio'][value='Radio']"),
                    m("label.w-form-label[for='radio']", "R$ 10")
                  ]),
                  m(".w-radio",[
                    m("input.w-radio-input[data-name='Radio 2'][id='radio'][name='radio-2'][type='radio'][value='Radio']"),
                    m("label.w-form-label[for='radio']", "R$ 10")
                  ])
              ])
            ])
          ])
        ]),
        m(".w-col.w-col-2",[
          m("a.btn.btn-small.btn-terciary[data-ix='show-dropdown'][href='#']", "Anonimato"),
          m(".dropdown-list.card.u-radius.dropdown-list-medium.zindex-10",[
            m(".w-form",[
              m("form[data-name='Email Form 4'][id='email-form-4'][name='email-form-4']",[
                m(".w-radio",[
                  m("input.w-radio-input[data-name='Radio'][id='radio'][name='radio'][type='radio'][value='Radio']"),
                  m("label.w-form-label[for='radio']", "Anônimo")
                ]),
                m(".w-radio",[
                  m("input.w-radio-input[data-name='Radio 2'][id='radio'][name='radio-2'][type='radio'][value='Radio']"),
                  m("label.w-form-label[for='radio']", "Público")
                ])
              ])
            ])
          ])
        ])
      ]),
      m(".w-row.card.card-terciary.u-radius",[
        m(".w-col.w-col-4",[
          m(".fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-20", "Detalhes do apoio"),
          m(".fontsize-smallest.lineheight-looser",[
            "Valor: R$80\n",
            m("br"),
            "Taxa: R$3,35\n",
            m("br"),"Recompensa: R$80\n",
            m("br"),
            "Anônimo: Não\n",
            m("br"),
            "Id pagamento: 638912",
            m("br"),
            "Apoio: 54545454",
            m("br"),
            "Chave: \n",
            m("br"),
            "7809d09d-6325-442e-876e-b9a0846c526f\n",
            m("br"),
            "Meio: Pagarme\n",
            m("br"),
            "Operadora: STONE",
            m("br"),
            m("a.link-hidden[href='#']", "Boleto bancário"),
            " ",
            m("span.badge", "2a via")
          ])
        ]),
        m(".w-col.w-col-4",[
          m(".fontweight-semibold.fontsize-smaller.lineheight-tighter.u-marginbottom-20", "Histórico da transação"),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div", "Apoio criado")
            ])
          ]),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div", "Apoio criado")
            ])
          ]),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div",[
                m("span.badge.badge-attention.fontsize-smallest", "Estorno realizado")
              ])
            ])
          ]),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div", "Apoio criado")
            ])
          ]),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div", "Apoio criado")
            ])
          ]),
          m(".w-row.fontsize-smallest.lineheight-looser",[
            m(".w-col.w-col-6",[
              m(".fontcolor-secondary", "19/05/2015, 01:20 h")
            ]),
            m(".w-col.w-col-6",[
              m("div", "Apoio criado"),
              m(".fontsize-smallest.lineheight-tighter",[
                m("span.badge", "Luis Otavio Ribeiro")
              ])
            ])
          ])
        ]),
        m(".w-col.w-col-4")
      ])
    ]);
  }
}

<|endoftext|>