<commit_before>#! /usr/bin/env node

"use strict";

var sh = require('shelljs');
var argv = require('minimist')(process.argv.slice(2));

var hostname = sh.exec('hostname', { silent: true }).output;
hostname = hostname.replace('\n', '');
if (argv._.length < 1) {
    sh.echo('Expect a new name!');
    sh.exit(1);
}
var newname = argv._[0];

sh.echo('Change Hostname: ' + hostname + ' -> ' + newname);
sh.sed('-i', hostname, newname, '/etc/hostname');
sh.exec('sudo hostname ' + newname);
sh.sed('-i', hostname, newname, '/etc/hosts');<commit_msg>refactor<commit_after>#! /usr/bin/env node

"use strict";

var sh = require('shelljs');
var fs = require('fs');
var argv = require('minimist')(process.argv.slice(2));

var hostname = sh.exec('hostname', { silent: true }).output;
hostname = hostname.replace('\n', '');
if (argv._.length < 1) {
    sh.echo('Expect a new name!');
    sh.exit(1);
}
var newname = argv._[0];

sh.echo('Change Hostname: ' + hostname + ' -> ' + newname);
fs.writeFileSync('/etc/hostname', newname);
sh.exec('sudo hostname ' + newname);
sh.sed('-i', hostname, newname, '/etc/hosts');<|endoftext|>


<commit_before>import {createAction} from '../utils/obsUtils'

/*set active designs data/fields */
export let setDesignData$ = createAction();
<commit_msg>- added "createDesign" action<commit_after>import {createAction} from '../utils/obsUtils'

/*create new design */
export let newDesign$ = createAction();

/*set active designs data/fields */
export let setDesignData$ = createAction();
<|endoftext|>


<commit_before>import alt from './../alt';

import Photo from './../models/photo';
import Tag from './../models/tag';

class PhotoActions {

  constructor() {
    this.generateActions(
      'getPhotosSuccess',
      'getDatesSuccess',
      'setDateFilterSuccess',
      'updatedPhotoSuccess',
      'setImporting'
    );
  }

  updatedPhoto(e, version) {
    console.log('photo actions new version', version, this);

    new Photo({ id: version.attributes.photo_id })
      .fetch({ withRelated: ['versions', 'tags'] })
      .then((photo) => {
        this.actions.updatedPhotoSuccess(photo);
      });
  }

  getPhotos() {
    Photo
      .query(function (qb) {
        qb.limit(100).offset(0);
      })
      .fetchAll({ withRelated: ['versions', 'tags'] })
      .then((photos) => {
        this.actions.getPhotosSuccess(photos);
      });
  }

  getDates() {
    Photo.getDates().then((dates) => {
      this.actions.getDatesSuccess(dates);
    });
  }

  getFlagged() {
    new Photo()
      .where({ flag: true })
      .fetchAll({ withRelated: ['versions', 'tags'] })
      .then((photos) => {
        this.actions.getPhotosSuccess(photos);
      });
  }

  setDateFilter(date) {
    new Photo()
      .where({ date: date })
      .fetchAll({ withRelated: ['versions', 'tags'] })
      .then((photos) => {
        this.actions.getPhotosSuccess(photos);
      });
  }

  setTagFilter(tag) {
    new Tag({ id: tag.id })
      .fetch({ withRelated: ['photos'] })
      .then((tag) => {
        let photos = tag.related('photos');
        this.actions.getPhotosSuccess(photos);
      });
  }

  startImport() {
    this.actions.setImporting(true);
  }

  toggleFlag(photo) {
    console.log('photo', photo);

    new Photo({ id: photo.id })
      .save('flag', !photo.flag, { patch: true })
      .then(() => {
        return new Photo({ id: photo.id })
          .fetch({ withRelated: ['versions', 'tags'] });
      })
      .then((photoModel) => {
        this.actions.updatedPhotoSuccess(photoModel);
      })
      .catch((err) => {
        console.log('err toggle flag', err);
      });
  }
}

export default alt.createActions(PhotoActions);
<commit_msg>Order photos by date<commit_after>import alt from './../alt';

import Photo from './../models/photo';
import Tag from './../models/tag';

class PhotoActions {

  constructor() {
    this.generateActions(
      'getPhotosSuccess',
      'getDatesSuccess',
      'setDateFilterSuccess',
      'updatedPhotoSuccess',
      'setImporting'
    );
  }

  updatedPhoto(e, version) {
    console.log('photo actions new version', version, this);

    new Photo({ id: version.attributes.photo_id })
      .fetch({ withRelated: ['versions', 'tags'] })
      .then((photo) => {
        this.actions.updatedPhotoSuccess(photo);
      });
  }

  getPhotos() {
    Photo
      .query(function (qb) {
        qb.limit(100).offset(0).orderBy('created_at', 'desc');
      })
      .fetchAll({ withRelated: ['versions', 'tags'] })
      .then((photos) => {
        this.actions.getPhotosSuccess(photos);
      });
  }

  getDates() {
    Photo.getDates().then((dates) => {
      this.actions.getDatesSuccess(dates);
    });
  }

  getFlagged() {
    new Photo()
      .where({ flag: true })
      .fetchAll({ withRelated: ['versions', 'tags'] })
      .then((photos) => {
        this.actions.getPhotosSuccess(photos);
      });
  }

  setDateFilter(date) {
    new Photo()
      .where({ date: date })
      .fetchAll({ withRelated: ['versions', 'tags'] })
      .then((photos) => {
        this.actions.getPhotosSuccess(photos);
      });
  }

  setTagFilter(tag) {
    new Tag({ id: tag.id })
      .fetch({ withRelated: ['photos'] })
      .then((tag) => {
        let photos = tag.related('photos');
        this.actions.getPhotosSuccess(photos);
      });
  }

  startImport() {
    this.actions.setImporting(true);
  }

  toggleFlag(photo) {
    console.log('photo', photo);

    new Photo({ id: photo.id })
      .save('flag', !photo.flag, { patch: true })
      .then(() => {
        return new Photo({ id: photo.id })
          .fetch({ withRelated: ['versions', 'tags'] });
      })
      .then((photoModel) => {
        this.actions.updatedPhotoSuccess(photoModel);
      })
      .catch((err) => {
        console.log('err toggle flag', err);
      });
  }
}

export default alt.createActions(PhotoActions);
<|endoftext|>


<commit_before>import { BigInteger } from 'jsbn';

import {
  fetchSummaries,
  fetchVAC,
  fetchFriendlist,
  fetchPlayedGames,
  fetchOpenDotaPlayer,
  fetchOpenDotaCounts,
  fetchOpenDotaHeroes,
  updateComments,
  } from './';
import { getComment } from '../db';

const { remote } = window.require('electron');

const fs = remote.require('fs-extra');

export const UPDATE_PLAYERS = 'UPDATE_PLAYERS';

const serverLogFile = './test/server_log.test.txt';
// '/home/kkurz/.steam/steam/steamapps/common/dota 2 beta/game/dota/server_log.txt';
// FIXME: dynamic location

function splitLines(data) {
  return data.toString().split(/\r?\n|\r/);
}

function filterLoopback(array) { // TODO filter all non valid lines
  return array.filter(item => item && !(/.*loopback.*/.test(item)));
}

function extractSteamID(string) {
  return string.match(/\d+/g)[2];
}

function convertToSteamID64(val) {
  return new BigInteger('76561197960265728').add(new BigInteger(val.toString()));
}

function getPlayer(idString, partyArray) {
  return {
    steamID3: idString,
    steamID64: convertToSteamID64(+idString).toString(),
    inMyParty: partyArray.includes(idString),
  };
}

function extractGameData(line) {
  const lobbyString = line.match(/\(Lobby.*?\)/)[0];
  const partyString = line.match(/\(Party.*?\)/)[0];

  const steamID = /\d:\[U:1:\d+\]/g;

  const partyArray = partyString.match(steamID).map(extractSteamID);

  return lobbyString.match(steamID).map(extractSteamID)
  .map(item => getPlayer(item, partyArray));
}

function joinID64(acc, player, i) {
  const separator = i === 0 ? '' : ','; // no separator on first value
  return `${acc}${separator}${player.steamID64.toString()}`;
}

function getIdString(players) {
  return players.reduce(joinID64, '');
}

const fetchFriendLists = players => (dispatch) => {
  players.forEach(p => dispatch(fetchFriendlist(p)));
  // TODO dont fetch from private profiles
};
const fetchPlayedGamesPrivate = players => (dispatch) => {
  players.forEach(p => dispatch(fetchPlayedGames(p)));
  // TODO dont fetch from private profiles
};
const fetchOpenDotaPlayers = players => (dispatch) => {
  players.forEach(p => dispatch(fetchOpenDotaPlayer(p)));
  // TODO when to fetch?
};
const fetchOpenDotaCountsPrivate = players => (dispatch) => {
  players.forEach(p => dispatch(fetchOpenDotaCounts(p)));
  // TODO when to fetch?
};
const fetchOpenDotaHeroesPrivate = players => (dispatch) => {
  players.forEach(p => dispatch(fetchOpenDotaHeroes(p)));
  // TODO when to fetch?
};

const updatePlayers = players => ({
  type: UPDATE_PLAYERS,
  payload: players,
});

const loadComments = players => (dispatch) => {
  players.forEach(player => getComment(player.steamID64)
    .then(comment => dispatch(updateComments({ [player.steamID64]: comment }))));
};

const startPlayerUpdate = players => (dispatch) => {
  // FIXME force order with promise and make sure hero ids exist
  dispatch(updatePlayers(players));

  dispatch(loadComments(players));

  const idString = getIdString(players);
  dispatch(fetchSummaries(idString));
  dispatch(fetchVAC(idString));
  dispatch(fetchFriendLists(players));
  dispatch(fetchPlayedGamesPrivate(players));
  dispatch(fetchOpenDotaPlayers(players));
  dispatch(fetchOpenDotaCountsPrivate(players));
  dispatch(fetchOpenDotaHeroesPrivate(players));
};

export const readServerLog = (line = 0) => (dispatch) => {
  fs.readFile(serverLogFile)
    .then(splitLines)
    .then(filterLoopback)
    .then(array => array[(array.length - 1) - line])
    .then(extractGameData)
    .then(players => dispatch(startPlayerUpdate(players)));
};
<commit_msg>getIdString join with lodash<commit_after>import { BigInteger } from 'jsbn';
import _ from 'lodash';

import {
  fetchSummaries,
  fetchVAC,
  fetchFriendlist,
  fetchPlayedGames,
  fetchOpenDotaPlayer,
  fetchOpenDotaCounts,
  fetchOpenDotaHeroes,
  updateComments,
  } from './';
import { getComment } from '../db';

const { remote } = window.require('electron');

const fs = remote.require('fs-extra');

export const UPDATE_PLAYERS = 'UPDATE_PLAYERS';

const serverLogFile = './test/server_log.test.txt';
// '/home/kkurz/.steam/steam/steamapps/common/dota 2 beta/game/dota/server_log.txt';
// FIXME: dynamic location

function splitLines(data) {
  return data.toString().split(/\r?\n|\r/);
}

function filterLoopback(array) { // TODO filter all non valid lines
  return array.filter(item => item && !(/.*loopback.*/.test(item)));
}

function extractSteamID(string) {
  return string.match(/\d+/g)[2];
}

function convertToSteamID64(val) {
  return new BigInteger('76561197960265728').add(new BigInteger(val.toString()));
}

function getPlayer(idString, partyArray) {
  return {
    steamID3: idString,
    steamID64: convertToSteamID64(+idString).toString(),
    inMyParty: partyArray.includes(idString),
  };
}

function extractGameData(line) {
  const lobbyString = line.match(/\(Lobby.*?\)/)[0];
  const partyString = line.match(/\(Party.*?\)/)[0];

  const steamID = /\d:\[U:1:\d+\]/g;

  const partyArray = partyString.match(steamID).map(extractSteamID);

  return lobbyString.match(steamID).map(extractSteamID)
  .map(item => getPlayer(item, partyArray));
}

function getIdString(players) {
  return _.join(players.reduce((acc, player) => _.concat(acc, player.steamID64.toString()), []), ',');
}

const fetchFriendLists = players => (dispatch) => {
  players.forEach(p => dispatch(fetchFriendlist(p)));
  // TODO dont fetch from private profiles
};
const fetchPlayedGamesPrivate = players => (dispatch) => {
  players.forEach(p => dispatch(fetchPlayedGames(p)));
  // TODO dont fetch from private profiles
};
const fetchOpenDotaPlayers = players => (dispatch) => {
  players.forEach(p => dispatch(fetchOpenDotaPlayer(p)));
  // TODO when to fetch?
};
const fetchOpenDotaCountsPrivate = players => (dispatch) => {
  players.forEach(p => dispatch(fetchOpenDotaCounts(p)));
  // TODO when to fetch?
};
const fetchOpenDotaHeroesPrivate = players => (dispatch) => {
  players.forEach(p => dispatch(fetchOpenDotaHeroes(p)));
  // TODO when to fetch?
};

const updatePlayers = players => ({
  type: UPDATE_PLAYERS,
  payload: players,
});

const loadComments = players => (dispatch) => {
  players.forEach(player => getComment(player.steamID64)
    .then(comment => dispatch(updateComments({ [player.steamID64]: comment }))));
};

const startPlayerUpdate = players => (dispatch) => {
  // FIXME force order with promise and make sure hero ids exist
  dispatch(updatePlayers(players));

  dispatch(loadComments(players));

  const idString = getIdString(players);
  dispatch(fetchSummaries(idString));
  dispatch(fetchVAC(idString));
  dispatch(fetchFriendLists(players));
  dispatch(fetchPlayedGamesPrivate(players));
  dispatch(fetchOpenDotaPlayers(players));
  dispatch(fetchOpenDotaCountsPrivate(players));
  dispatch(fetchOpenDotaHeroesPrivate(players));
};

export const readServerLog = (line = 0) => (dispatch) => {
  fs.readFile(serverLogFile)
    .then(splitLines)
    .then(filterLoopback)
    .then(array => array[(array.length - 1) - line])
    .then(extractGameData)
    .then(players => dispatch(startPlayerUpdate(players)));
};
<|endoftext|>


<commit_before>/**
 * Breadcrumb handlers
 */

module.exports = {
  /**
   * Middleware for select the breadcrumb middleware handler
   */
  middleware: function metatagMiddleware(req, res, next) {
    if (res.locals.breadcrumbHandler) {
      if (typeof res.locals.breadcrumbHandler === 'function') {
        return res.locals.breadcrumbHandler(req, res, next);
      } else if (req.we.router.breadcrumb.middlewares[res.locals.breadcrumbHandler]) {
        return req.we.router.breadcrumb.middlewares[res.locals.breadcrumbHandler](req, res, next);
      }
    }

    next();
  },

  /**
   * Middleware handlers
   *
   * @type {Object}
   */
  middlewares: {
    /**
     * Default create breadcrumb function
     * @return {Array} Links array with href and text
     */
    create: function createBreadcrumb(req, res, next) {
      res.locals.breadcrumb =
        '
'+
          '
'+res.locals.__('Home')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.find')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.create')+'
'+
        '
';

      next();
    },

    /**
     * Default find breadcrumb function
     * @return {Array} Links array with href and text
     */
    find: function findBreadcrumb(req, res, next) {
      res.locals.breadcrumb =
        '
'+
          '
'+res.locals.__('Home')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.find')+'
'+
        '
';

      next();
    },

    /**
     * Default findOne breadcrumb function
     * @return {Array} Links array with href and text
     */
    findOne: function findOneBreadcrumb(req, res, next) {
      res.locals.breadcrumb =
        '
'+
          '
'+res.locals.__('Home')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.find')+'
'+
          '
'+req.we.utils.string(res.locals.title || '').truncate(25).s+'
'+
        '
';

      next();
    },

    /**
     * Default edit / update breadcrumb function
     * @return {Array} Links array with href and text
     */
    edit: function editBreadcrumb(req, res, next) {
      if (!res.locals.data) return next();

      res.locals.breadcrumb =
        '
'+
          '
'+res.locals.__('Home')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.find')+'
'+
          '
'+
            req.we.utils.string(res.locals.title || '').truncate(25).s+
          '
'+
          '
'+res.locals.__('edit')+'
'+
        '
';

      next();
    },

    /**
     * Default delete breadcrumb function
     * @return {Array} Links array with href and text
     */
    delete: function deleteBreadcrumb(req, res, next) {
      if (!res.locals.data) return next();

      res.locals.breadcrumb =
        '
'+
          '
'+res.locals.__('Home')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.find')+'
'+
          '
'+
            req.we.utils.string(res.locals.title || '').truncate(25).s+
          '
'+
          '
'+res.locals.__('delete')+'
'+
        '
';

      next();
    }
  }
}<commit_msg>fix default find breadcrumb<commit_after>/**
 * Breadcrumb handlers
 */

module.exports = {
  /**
   * Middleware for select the breadcrumb middleware handler
   */
  middleware: function metatagMiddleware(req, res, next) {
    if (res.locals.breadcrumbHandler) {
      if (typeof res.locals.breadcrumbHandler === 'function') {
        return res.locals.breadcrumbHandler(req, res, next);
      } else if (req.we.router.breadcrumb.middlewares[res.locals.breadcrumbHandler]) {
        return req.we.router.breadcrumb.middlewares[res.locals.breadcrumbHandler](req, res, next);
      }
    }

    next();
  },

  /**
   * Middleware handlers
   *
   * @type {Object}
   */
  middlewares: {
    /**
     * Default create breadcrumb function
     * @return {Array} Links array with href and text
     */
    create: function createBreadcrumb(req, res, next) {
      res.locals.breadcrumb =
        '
'+
          '
'+res.locals.__('Home')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.find')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.create')+'
'+
        '
';

      next();
    },

    /**
     * Default find breadcrumb function
     * @return {Array} Links array with href and text
     */
    find: function findBreadcrumb(req, res, next) {
      res.locals.breadcrumb =
        '
'+
          '
'+res.locals.__('Home')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.find')+'
'+
        '
';

      next();
    },

    /**
     * Default findOne breadcrumb function
     * @return {Array} Links array with href and text
     */
    findOne: function findOneBreadcrumb(req, res, next) {
      res.locals.breadcrumb =
        '
'+
          '
'+res.locals.__('Home')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.find')+'
'+
          '
'+req.we.utils.string(res.locals.title || '').truncate(25).s+'
'+
        '
';

      next();
    },

    /**
     * Default edit / update breadcrumb function
     * @return {Array} Links array with href and text
     */
    edit: function editBreadcrumb(req, res, next) {
      if (!res.locals.data) return next();

      res.locals.breadcrumb =
        '
'+
          '
'+res.locals.__('Home')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.find')+'
'+
          '
'+
            req.we.utils.string(res.locals.title || '').truncate(25).s+
          '
'+
          '
'+res.locals.__('edit')+'
'+
        '
';

      next();
    },

    /**
     * Default delete breadcrumb function
     * @return {Array} Links array with href and text
     */
    delete: function deleteBreadcrumb(req, res, next) {
      if (!res.locals.data) return next();

      res.locals.breadcrumb =
        '
'+
          '
'+res.locals.__('Home')+'
'+
          '
'+res.locals.__(res.locals.resourceName + '.find')+'
'+
          '
'+
            req.we.utils.string(res.locals.title || '').truncate(25).s+
          '
'+
          '
'+res.locals.__('delete')+'
'+
        '
';

      next();
    }
  }
}<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash'),
  filename = __filename.split('/').pop().split('.').shift(),
  lib = require('./' + filename),
  responses = require('../responses'),
  sinon = require('sinon'),
  log = require('../log');

describe(_.startCase(filename), function () {
  var sandbox;

  function createMockReq() {
    return {};
  }

  function createMockRes() {
    return {};
  }

  /**
   * Fail unit test immediately with message;
   * @param {string} msg
   * @param {string} [actual]
   * @param {string} [expected]
   * @param {string} [operator]
   */
  function fail(msg, actual, expected, operator) {
    require('chai').assert.fail(actual, expected, msg, operator);
  }

  /**
   * Shortcut
   */
  function expectNoLogging() {
    var logExpectations = sandbox.mock(log);
    logExpectations.expects('info').never();
    logExpectations.expects('warn').never();
    logExpectations.expects('error').never();
  }

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

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

  describe('onlyJSONLists', function () {
    var fn = lib[this.title];

    it('allows undefined body', function (done) {
      var req = createMockReq(),
        res = createMockRes();

      expectNoLogging();
      sandbox.mock(responses).expects('clientError').never();

      fn(req, res, function () {
        done();
      });

      sandbox.verify();
    });

    it('allows array body', function (done) {
      var req = createMockReq(),
        res = createMockRes();

      expectNoLogging();
      req.body = [];
      sandbox.mock(responses).expects('clientError').never();

      fn(req, res, function () {
        done();
      });

      sandbox.verify();
    });

    it('error when req.body is object', function () {
      var req = createMockReq(),
        res = createMockRes();

      expectNoLogging();
      req.body = {};
      sandbox.mock(responses).expects('clientError').once();

      fn(req, res, function () {
        fail('next() should not be called.');
      });

      sandbox.verify();
    });
  });
});<commit_msg>remove extra functions from list.test.js<commit_after>'use strict';

var _ = require('lodash'),
  filename = __filename.split('/').pop().split('.').shift(),
  lib = require('./' + filename),
  responses = require('../responses'),
  sinon = require('sinon'),
  expect = require('chai').expect,
  log = require('../log');

describe(_.startCase(filename), function () {
  var sandbox;

  /**
   * Shortcut
   */
  function expectNoLogging() {
    var logExpectations = sandbox.mock(log);
    logExpectations.expects('info').never();
    logExpectations.expects('warn').never();
    logExpectations.expects('error').never();
  }

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

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

  describe('onlyJSONLists', function () {
    var fn = lib[this.title];

    it('allows undefined body', function () {
      var next = sandbox.spy(),
        req = {},
        res = {};

      expectNoLogging();
      sandbox.stub(responses, 'clientError');

      fn(req, res, next);

      expect(next.called).to.equal(true);
      expect(responses.clientError.called).to.equal(false);
    });

    it('allows array body', function () {
      var next = sandbox.spy(),
        req = {},
        res = {};

      expectNoLogging();
      req.body = [];
      sandbox.stub(responses, 'clientError');

      fn(req, res, next);

      expect(next.called).to.equal(true);
      expect(responses.clientError.called).to.equal(false);
    });

    it('error when req.body is object', function () {
      var next = sandbox.spy(),
        req = {},
        res = {};

      expectNoLogging();
      req.body = {};
      sandbox.stub(responses, 'clientError');

      fn(req, res, next);

      expect(next.called).to.equal(false);
      expect(responses.clientError.callCount).to.equal(1);
    });
  });
});<|endoftext|>


<commit_before>// Process ==highlighted text==

'use strict';

module.exports = function del(state, silent) {
  var found,
      pos,
      stack,
      max = state.posMax,
      start = state.pos,
      lastChar,
      nextChar;

  if (state.src.charCodeAt(start) !== 0x3D/* = */) { return false; }
  if (silent) { return false; } // don't run any pairs in validation mode
  if (start + 4 >= max) { return false; }
  if (state.src.charCodeAt(start + 1) !== 0x3D/* = */) { return false; }
  if (state.level >= state.options.maxNesting) { return false; }

  lastChar = start > 0 ? state.src.charCodeAt(start - 1) : -1;
  nextChar = state.src.charCodeAt(start + 2);

  if (lastChar === 0x3D/* = */) { return false; }
  if (nextChar === 0x3D/* = */) { return false; }
  if (nextChar === 0x20 || nextChar === 0x0A) { return false; }

  pos = start + 2;
  while (pos < max && state.src.charCodeAt(pos) === 0x3D/* = */) { pos++; }
  if (pos !== start + 2) {
    // sequence of 3+ markers taking as literal, same as in a emphasis
    state.pos += pos - start;
    if (!silent) { state.pending += state.src.slice(start, pos); }
    return true;
  }

  state.pos = start + 2;
  stack = 1;

  while (state.pos + 1 < max) {
    if (state.src.charCodeAt(state.pos) === 0x3D/* = */) {
      if (state.src.charCodeAt(state.pos + 1) === 0x3D/* = */) {
        lastChar = state.src.charCodeAt(state.pos - 1);
        nextChar = state.pos + 2 < max ? state.src.charCodeAt(state.pos + 2) : -1;
        if (nextChar !== 0x3D/* = */ && lastChar !== 0x3D/* = */) {
          if (lastChar !== 0x20 && lastChar !== 0x0A) {
            // closing '=='
            stack--;
          } else if (nextChar !== 0x20 && nextChar !== 0x0A) {
            // opening '=='
            stack++;
          } // else {
            //  // standalone ' == ' indented with spaces
            // }
          if (stack <= 0) {
            found = true;
            break;
          }
        }
      }
    }

    state.parser.skipToken(state);
  }

  if (!found) {
    // parser failed to find ending tag, so it's not valid emphasis
    state.pos = start;
    return false;
  }

  // found!
  state.posMax = state.pos;
  state.pos = start + 2;

  if (!silent) {
    state.push({ type: 'mark_open', level: state.level++ });
    state.parser.tokenize(state);
    state.push({ type: 'mark_close', level: --state.level });
  }

  state.pos = state.posMax + 2;
  state.posMax = max;
  return true;
};
<commit_msg>Update mark.js<commit_after>// Process ==highlighted text==

'use strict';

module.exports = function mark(state, silent) {
  var found,
      pos,
      stack,
      max = state.posMax,
      start = state.pos,
      lastChar,
      nextChar;

  if (state.src.charCodeAt(start) !== 0x3D/* = */) { return false; }
  if (silent) { return false; } // don't run any pairs in validation mode
  if (start + 4 >= max) { return false; }
  if (state.src.charCodeAt(start + 1) !== 0x3D/* = */) { return false; }
  if (state.level >= state.options.maxNesting) { return false; }

  lastChar = start > 0 ? state.src.charCodeAt(start - 1) : -1;
  nextChar = state.src.charCodeAt(start + 2);

  if (lastChar === 0x3D/* = */) { return false; }
  if (nextChar === 0x3D/* = */) { return false; }
  if (nextChar === 0x20 || nextChar === 0x0A) { return false; }

  pos = start + 2;
  while (pos < max && state.src.charCodeAt(pos) === 0x3D/* = */) { pos++; }
  if (pos !== start + 2) {
    // sequence of 3+ markers taking as literal, same as in a emphasis
    state.pos += pos - start;
    if (!silent) { state.pending += state.src.slice(start, pos); }
    return true;
  }

  state.pos = start + 2;
  stack = 1;

  while (state.pos + 1 < max) {
    if (state.src.charCodeAt(state.pos) === 0x3D/* = */) {
      if (state.src.charCodeAt(state.pos + 1) === 0x3D/* = */) {
        lastChar = state.src.charCodeAt(state.pos - 1);
        nextChar = state.pos + 2 < max ? state.src.charCodeAt(state.pos + 2) : -1;
        if (nextChar !== 0x3D/* = */ && lastChar !== 0x3D/* = */) {
          if (lastChar !== 0x20 && lastChar !== 0x0A) {
            // closing '=='
            stack--;
          } else if (nextChar !== 0x20 && nextChar !== 0x0A) {
            // opening '=='
            stack++;
          } // else {
            //  // standalone ' == ' indented with spaces
            // }
          if (stack <= 0) {
            found = true;
            break;
          }
        }
      }
    }

    state.parser.skipToken(state);
  }

  if (!found) {
    // parser failed to find ending tag, so it's not valid emphasis
    state.pos = start;
    return false;
  }

  // found!
  state.posMax = state.pos;
  state.pos = start + 2;

  if (!silent) {
    state.push({ type: 'mark_open', level: state.level++ });
    state.parser.tokenize(state);
    state.push({ type: 'mark_close', level: --state.level });
  }

  state.pos = state.posMax + 2;
  state.posMax = max;
  return true;
};
<|endoftext|>


<commit_before>angular.module('Aggie')

.value('mediaOptions', ['twitter', 'facebook', 'rss', 'elmo', 'smsgh', 'whatsapp'])

.value('apiSettingsOptions', ['twitter', 'facebook', 'elmo', 'gplaces'])

.value('widgetSettingsOptions', ['incident map'])

.value('statusOptions', ['Read', 'Unread', 'Flagged', 'Unflagged', 'Read & Unflagged'])

.value('linkedtoIncidentOptions', [{ _id: 'any', title: '* Any Incident' },
                                   { _id: 'none', title: '* Without Incident' }])

.value('userRoles', ['viewer', 'monitor', 'admin'])

.value('incidentStatusOptions', ['open', 'closed'])

.value('veracityOptions', ['unconfirmed', 'confirmed true', 'confirmed false'])

.value('escalatedOptions', ['escalated', 'unescalated'])

.value('publicOptions', ['public', 'private'])

.value('paginationOptions', { perPage: 25 })

.value('emailTransportOptions', {
  SES: ['accessKeyId', 'secretAccessKey', 'region'],
  SMTP: ['host', 'port', 'secure', 'user', 'pass'],
  SendGrid: ['api_key'] });

<commit_msg>update frontend variables to reflect backend<commit_after>angular.module('Aggie')

.value('mediaOptions', ['twitter', 'facebook', 'rss', 'elmo', 'smsgh', 'whatsapp'])

.value('apiSettingsOptions', ['twitter', 'facebook', 'elmo', 'gplaces'])

.value('widgetSettingsOptions', ['incident map'])

.value('statusOptions', ['Read', 'Unread', 'Flagged', 'Unflagged', 'Read & Unflagged'])

.value('linkedtoIncidentOptions', [{ _id: 'any', title: '* Any Incident' },
                                   { _id: 'none', title: '* Without Incident' }])

.value('userRoles', ['viewer', 'monitor', 'admin'])

.value('incidentStatusOptions', ['open', 'closed'])

.value('veracityOptions', ['unconfirmed', 'confirmed true', 'confirmed false'])

.value('escalatedOptions', ['escalated', 'unescalated'])

.value('publicOptions', ['public', 'private'])

.value('paginationOptions', { perPage: 25 })

.value('emailTransportOptions', {
  SES: ['accessKeyId', 'secretAccessKey', 'region'],
  SMTP: ['host', 'port', 'secure', 'user', 'pass'],
  SendGrid: ['apiKey'] });

<|endoftext|>


<commit_before>function Upload(options) {
    var fs     = require('fs');
    var tools  = require(__dirname + '/../tools.js');

    var that = this;

    options = options || {};

    if (!options.states)      throw 'Invalid arguments: states is missing';
    if (!options.objects)     throw 'Invalid arguments: objects is missing';
    if (!options.processExit) throw 'Invalid arguments: processExit is missing';

    var states      = options.states;
    var objects     = options.objects;
    var processExit = options.processExit;
    var mime;

    // get all instances of one adapter
    function getInstances(adapter, callback) {
        objects.getObjectList({startkey: 'system.adapter.' + adapter + '.', endkey: 'system.adapter.' + adapter + '.\u9999'}, function (err, arr) {
            var instances = [];
            if (!err && arr && arr.rows) {
                var files = [];
                var count = 0;
                for (var i = 0; i < arr.rows.length; i++) {
                    if (arr.rows[i].value.type != 'instance') continue;
                    instances.push(arr.rows[i].value._id);
                }
            }
            callback(instances);
        });
    }

    // get all instances of all adapters in the list
    function getAllInstances(adapters, callback) {
        var instances = [];
        var count = adapters.length;
        for (var i = 0; i < adapters.length; i++) {
            if (!adapters[i]) continue;
            if (adapters[i].indexOf('.') == -1) {
                getInstances(adapters[i], function (inst) {
                    for (var j = 0; j < inst.length; j++) {
                        if (instances.indexOf(inst[j]) == -1) instances.push(inst[j]);
                    }
                    if (!--count) callback(instances);
                });
            } else {
                if (instances.indexOf(adapters[i]) == -1) instances.push(adapters[i]);
            }
        }
        if (!count) callback(instances);
    }

    // Check if some adapters must be restarted and restart them
    function checkRestartOther(adapter, callback) {
        var adapterDir = tools.getAdapterDir(adapter);
        var isRestarting = false;
        try {
            var adapterConf = JSON.parse(fs.readFileSync(adapterDir + '/io-package.json').toString());
            if (adapterConf.common.restartAdapters) {
                if (typeof adapterConf.common.restartAdapters !== 'object') adapterConf.common.restartAdapters = [adapterConf.common.restartAdapters];

                if (adapterConf.common.restartAdapters.length && adapterConf.common.restartAdapters[0]) {
                    isRestarting = true;
                    getAllInstances(adapterConf.common.restartAdapters, function (instances) {
                        isRestarting = false;
                        for (var r = 0; r < instances.length; r++) {
                            isRestarting = true;

                            objects.getObject(instances[r], function (err, obj) {
                                // if instance is enabled
                                if (!err && obj && obj.common.enabled) {

                                    obj.common.enabled = false; // disable instance

                                    objects.setObject(obj._id, obj, function (err) {
                                        if (!err) {

                                            obj.common.enabled = true; // enable instance

                                            objects.setObject(obj._id, obj, function (err) {
                                                console.log('Adapter "' + obj._id + '" restarted.');
                                                callback();
                                            });
                                        } else {
                                            if (err) {
                                                console.error('Cannot restart adapter "' + obj._id + '": ' + err);
                                            } else {
                                                console.warn('Adapter "' + obj._id + '" is disabled and cannot be restarted.');
                                            }
                                            callback();
                                        }
                                    });
                                } else {
                                    callback();
                                }
                            });
                        }
                        if (!isRestarting) {
                            callback();
                        }
                    });

                }
             }
        } catch (e) {
            console.error('Cannot parse ' + adapterDir + '/io-package.json:' + e);
            if (isRestarting) callback();
        }
        if (!isRestarting) callback();
    }

    this.uploadAdapterFull = function (adapters, callback) {
        if (!adapters || !adapters.length) {
            if (callback) callback();
            return;
        }
        var adapter = adapters.pop();
        that.uploadAdapter(adapter, true, true, function () {
            that.upgradeAdapterObjects(adapter, function () {
                that.uploadAdapter(adapter, false, true, function () {
                    setTimeout(function () {
                        that.uploadAdapterFull(adapters, callback);
                    }, 0);
                });
            });
        });
    };

    this.uploadFile = function (source, target, callback) {
        var request = require('request');
        target = target.replace(/\\/g, '/');
        source = source.replace(/\\/g, '/');
        if (target[0] === '/') target = target.substring(1);
        if (target[target.length - 1] == '/') {
            var name = source.split('/').pop();
            name = name.split('?')[0];
            if (name.indexOf('.') === -1) name = 'index.html';
            target += name;
        }
        var parts = target.split('/');
        var adapter = parts[0];
        parts.splice(0, 1);
        target = parts.join('/');

        if (source.match(/^http:\/\/|^https:\/\//)) {
            request(source, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    objects.writeFile(adapter, target, body, function (err) {
                        if (err) console.error(err);
                        if (typeof callback === 'function') callback(err, adapter + '/' + target);
                    });
                } else {
                    console.error('Cannot get URL: ' + error || response.statusCode);
                    if (typeof callback === 'function') callback(error || response.statusCode, adapter + '/' + target);
                }
            });
        } else {
            try {
                objects.writeFile(adapter, target, fs.readFileSync(source), function (err) {
                    if (err) console.error(err);
                    if (typeof callback === 'function') callback(err, adapter + '/' + target);
                });
            } catch (err) {
                console.error('Cannot read file "' + source + '": ' + err);
                if (typeof callback === 'function') callback(err, adapter + '/' + target);
            }
        }
    };

    // Upload www folder of adapter into ObjectsDB
    this.uploadAdapter = function (adapter, isAdmin, forceUpload, subTree, callback) {
        var rev;
        var id = adapter + (isAdmin ? '.admin' : '');
        var adapterDir = tools.getAdapterDir(adapter);
        var dir = adapterDir + (isAdmin ? '/admin' : '/www');
        var files = [];
        if (typeof subTree == 'function') {
            callback = subTree;
            subTree = null;
        }
        if (subTree) {
            dir += '/' + subTree;
        }

        if (!isAdmin) {
            var cfg;
            // check for common.wwwDontUpload (required for legacy adapter)
            if (fs.existsSync(adapterDir + '/io-package.json')) {
                cfg = require(adapterDir + '/io-package.json');
            }
            if (cfg && cfg.common && cfg.common.wwwDontUpload) {
                if (typeof callback === 'function') callback(adapter);
                return;
            }
        }
        // do not upload www dir of admin adapter
        if (adapter === 'admin' && !isAdmin) {
            // To DO remove after a while
            console.log('This should never happens!');
            if (typeof callback === 'function') callback(adapter);
            return;
        }

        // Create "upload progress" object if not exists
        if (!isAdmin) {
            objects.getObject('system.adapter.' + adapter + '.upload', function (err, obj) {
                if (err || !obj) {
                    objects.setObject('system.adapter.' + adapter + '.upload',
                        {
                            _id:   'system.adapter.' + adapter + '.upload',
                            type:   'state',
                            common: {
                                name: adapter + '.upload',
                                type: 'number',
                                role: 'indicator.state',
                                unit: '%',
                                def:  0,
                                desc: 'Upload process indicator'
                            },
                            native: {}
                        }
                    );
                }
            });
            // Set indicator to 0
            states.setState('system.adapter.' + adapter + '.upload', 0, true);
        }

        if (!mime) mime = require('mime');

        function done(err, res) {
            if (err) {
                console.log('error in upload: ' + err);
                callback();
            } else {
                console.log('got ' + dir);
                files = res;
                setTimeout(function (_adapter) {
                    maxFiles = files.length || 1;
                    upload(_adapter);
                }, 25, adapter);
            }
        }

        var maxFiles = 0;
        var lastProgressUpdate = (new Date()).getTime();

        function upload(adapter) {
            var file;
            if (!files.length) {
                console.log('call callback after finished upload');
                if (!isAdmin) {
                    states.setState('system.adapter.' + adapter + '.upload', {val: 0, ack: true}, function () {
                        if (typeof callback === 'function') callback(adapter);
                    });
                } else {
                    if (typeof callback === 'function') callback(adapter);
                }
            } else {
                file = files.pop();
                if (file == '.gitignore') {
                    upload(adapter);
                    return;
                }

                var mimeType = mime.lookup(file);
                var attName;
                attName = file.split('/' + tools.appName + '.');
                if (attName.length === 1) {
                    // try to find anyway if adapter is not lower case
                    var pos = file.toLowerCase().indexOf(tools.appName.toLowerCase());
                    if (pos !== -1) attName = ['', file.substring(tools.appName.length + 2)];
                }

                attName = attName.pop();
                attName = attName.split('/').slice(2).join('/');
                console.log('upload [' + files.length + ']', id, file, attName, mimeType);

                // Update upload indicator
                if (!isAdmin) {
                    var now = (new Date()).getTime();
                    if (now - lastProgressUpdate > 1000) {
                        lastProgressUpdate = now;
                        states.setState('system.adapter.' + adapter + '.upload', {val: parseInt(1000 * (maxFiles - files.length) / maxFiles) / 10, ack: true});
                    }
                }

                fs.createReadStream(file).pipe(
                    objects.insert(id, attName, null, mimeType, {
                        rev: rev
                    }, function (err, res) {
                        if (err) {
                            console.log(err);
                            if (typeof callback === 'function') callback(adapter);
                        }
                        if (res) rev = res.rev;
                        setTimeout(function () {
                            upload(adapter);
                        }, 50);
                    })
                );
            }
        }

        function walk(dir, done) {
            var results = [];
            fs.readdir(dir, function (err, list) {
                if (err) return done(err);
                var i = 0;
                (function next() {
                    var file = list[i++];
                    if (!file) return done(null, results);
                    file = dir + '/' + file;
                    fs.stat(file, function (err, stat) {
                        if (stat && stat.isDirectory()) {
                            walk(file, function (err, res) {
                                results = results.concat(res);
                                next();
                            });
                        } else {
                            if (!file.match(/\.npmignore$/) && !file.match(/\.gitignore$/)) results.push(file);
                            next();
                        }
                    });
                })();
            });
        }

        objects.getObject(id, function (err, res) {
            if (err || !res) {
                objects.setObject(id, {
                    type: 'meta',
                    common: {
                        name: id.split('.').pop(),
                        type: isAdmin ? 'admin' : 'www'
                    },
                    native: {}
                }, function (err, res) {
                    if (res) rev = res.rev;
                    if (!isAdmin) {
                        checkRestartOther(adapter, function () {
                            walk(dir, done);
                        });
                    } else {
                        walk(dir, done);
                    }
                });
            } else {
                if (!forceUpload) {
                    if (typeof callback === 'function') callback(adapter);
                } else {
                    rev = res.rev;
                    if (!isAdmin) {
                        checkRestartOther(adapter, function () {
                            walk(dir, done);
                        });
                    } else {
                        walk(dir, done);
                    }
                }
            }
        });
    };

    function extendNative(target, additional) {
        for (var attr in additional) {
            if (target[attr] === undefined) {
                target[attr] = additional[attr];
            } else if (typeof additional[attr] === 'object' && !(additional[attr] instanceof Array)) {
                target[attr] = target[attr] || {};
                extendNative(target[attr], additional[attr]);
            }
        }
        return target;
    }

    function extendCommon(target, additional) {
        for (var attr in additional) {
            if (attr === 'title' || attr === 'schedule' || attr === 'mode' || attr === 'loglevel' || attr === 'enabled') {
                if (target[attr] === undefined) target[attr] = additional[attr];
            } else
            if (typeof additional[attr] !== 'object' || (additional[attr] instanceof Array)) {
                target[attr] = additional[attr];
            } else {
                target[attr] = target[attr] || {};
                extendCommon(target[attr], additional[attr]);
            }
        }
        return target;
    }

    this.upgradeAdapterObjects = function (name, iopack, callback) {
        if (typeof iopack == 'function') {
            callback = iopack;
            iopack = null;
        }
        if (!iopack) {
            var adapterDir = tools.getAdapterDir(name);
            try {
                iopack = JSON.parse(fs.readFileSync(adapterDir + '/io-package.json'));
            } catch (e) {
                console.error('Cannot find io-package.json in ' + adapterDir);
                iopack = null;
            }
        }

        if (!iopack) {
            callback(name);
        } else {
            objects.getObject('system.adapter.' + name, function (err, obj) {
                if (err || !obj) {
                    console.error('system.adapter.' + name + ' does not exist');
                    callback(name);
                } else {
                    obj.common = iopack.common || {};
                    obj.native = iopack.native || {};

                    obj.common.installedVersion = iopack.common.version;

                    var hostname = tools.getHostName();

                    objects.setObject('system.adapter.' + name, obj, function () {
                        // Update all instances of this host
                        objects.getObjectView('system', 'instance', {startkey: 'system.adapter.' + name + '.', endkey: 'system.adapter.' + name + '.\u9999'}, null, function (err, res) {
                            var cntr = 0;

                            if (res) {
                                for (var i = 0; i < res.rows.length; i++) {
                                    if (res.rows[i].value.common.host === hostname) {
                                        cntr++;
                                        objects.getObject(res.rows[i].id, function (err, _obj) {
                                            var newObject = JSON.parse(JSON.stringify(_obj));

                                            // all common settings should be taken from new one
                                            newObject.common = extendCommon(newObject.common, iopack.common);
                                            newObject.native = extendNative(newObject.native, iopack.native);

                                            newObject.common.installedVersion = iopack.common.version;
                                            newObject.common.version          = iopack.common.version;

                                            // Compare objects to reduce restarts of instances
                                            if (JSON.stringify(newObject) !== JSON.stringify(_obj)) {
                                                console.log('Update "' + newObject._id + '"');
                                                objects.setObject(newObject._id, newObject, function () {
                                                    if (!--cntr && callback) callback(name);
                                                });
                                            } else {
                                                if (!--cntr && callback) callback(name);
                                            }
                                        });
                                    }
                                }
                            }

                            // updates "_design/system" and co
                            if (iopack.objects && typeof iopack.objects === 'object') {
                                for (var _id in iopack.objects) {
                                    if (!iopack.objects.hasOwnProperty(_id)) continue;
                                    cntr++;
                                    objects.setObject(iopack.objects[_id]._id, iopack.objects[_id], function (err) {
                                        if (err) console.error('Cannot update object: ' + err);
                                        if (!--cntr && callback) callback(name);
                                    });
                                }
                            }

                            if (!cntr && callback) callback(name);
                        });
                    });
                }
            });
        }
    };
}

module.exports = Upload;
<commit_msg>debugging<commit_after>function Upload(options) {
    var fs     = require('fs');
    var tools  = require(__dirname + '/../tools.js');

    var that = this;

    options = options || {};

    if (!options.states)      throw 'Invalid arguments: states is missing';
    if (!options.objects)     throw 'Invalid arguments: objects is missing';
    if (!options.processExit) throw 'Invalid arguments: processExit is missing';

    var states      = options.states;
    var objects     = options.objects;
    var processExit = options.processExit;
    var mime;

    // get all instances of one adapter
    function getInstances(adapter, callback) {
        objects.getObjectList({startkey: 'system.adapter.' + adapter + '.', endkey: 'system.adapter.' + adapter + '.\u9999'}, function (err, arr) {
            var instances = [];
            if (!err && arr && arr.rows) {
                var files = [];
                var count = 0;
                for (var i = 0; i < arr.rows.length; i++) {
                    if (arr.rows[i].value.type != 'instance') continue;
                    instances.push(arr.rows[i].value._id);
                }
            }
            callback(instances);
        });
    }

    // get all instances of all adapters in the list
    function getAllInstances(adapters, callback) {
        var instances = [];
        var count = adapters.length;
        for (var i = 0; i < adapters.length; i++) {
            if (!adapters[i]) continue;
            if (adapters[i].indexOf('.') == -1) {
                getInstances(adapters[i], function (inst) {
                    for (var j = 0; j < inst.length; j++) {
                        if (instances.indexOf(inst[j]) == -1) instances.push(inst[j]);
                    }
                    if (!--count) callback(instances);
                });
            } else {
                if (instances.indexOf(adapters[i]) == -1) instances.push(adapters[i]);
            }
        }
        if (!count) callback(instances);
    }

    // Check if some adapters must be restarted and restart them
    function checkRestartOther(adapter, callback) {
        console.log('checkRestartOther start');
        var adapterDir = tools.getAdapterDir(adapter);
        var isRestarting = false;
        try {
            var adapterConf = JSON.parse(fs.readFileSync(adapterDir + '/io-package.json').toString());
            if (adapterConf.common.restartAdapters) {
                if (typeof adapterConf.common.restartAdapters !== 'object') adapterConf.common.restartAdapters = [adapterConf.common.restartAdapters];

                if (adapterConf.common.restartAdapters.length && adapterConf.common.restartAdapters[0]) {
                    isRestarting = true;
                    getAllInstances(adapterConf.common.restartAdapters, function (instances) {
                        isRestarting = false;
                        for (var r = 0; r < instances.length; r++) {
                            isRestarting = true;

                            objects.getObject(instances[r], function (err, obj) {
                                // if instance is enabled
                                if (!err && obj && obj.common.enabled) {

                                    obj.common.enabled = false; // disable instance

                                    objects.setObject(obj._id, obj, function (err) {
                                        if (!err) {

                                            obj.common.enabled = true; // enable instance

                                            objects.setObject(obj._id, obj, function (err) {
                                                console.log('Adapter "' + obj._id + '" restarted.');
                                                callback();
                                            });
                                        } else {
                                            if (err) {
                                                console.error('Cannot restart adapter "' + obj._id + '": ' + err);
                                            } else {
                                                console.warn('Adapter "' + obj._id + '" is disabled and cannot be restarted.');
                                            }
                                            callback();
                                        }
                                    });
                                } else {
                                    console.log('checkRestartOther callback ' + objs._id);
                                    callback();
                                }
                            });
                        }
                        if (!isRestarting) {
                            console.log('checkRestartOther callback else 1');
                            callback();
                        }
                    });

                }
             }
        } catch (e) {
            console.error('Cannot parse ' + adapterDir + '/io-package.json:' + e);
            if (isRestarting) {
                console.log('checkRestartOther callback error 1');
                callback();
            }
        }
        if (!isRestarting) {
            console.log('checkRestartOther callback error 1');
            callback();
        }
    }

    this.uploadAdapterFull = function (adapters, callback) {
        if (!adapters || !adapters.length) {
            if (callback) callback();
            return;
        }
        var adapter = adapters.pop();
        that.uploadAdapter(adapter, true, true, function () {
            that.upgradeAdapterObjects(adapter, function () {
                that.uploadAdapter(adapter, false, true, function () {
                    setTimeout(function () {
                        that.uploadAdapterFull(adapters, callback);
                    }, 0);
                });
            });
        });
    };

    this.uploadFile = function (source, target, callback) {
        var request = require('request');
        target = target.replace(/\\/g, '/');
        source = source.replace(/\\/g, '/');
        if (target[0] === '/') target = target.substring(1);
        if (target[target.length - 1] == '/') {
            var name = source.split('/').pop();
            name = name.split('?')[0];
            if (name.indexOf('.') === -1) name = 'index.html';
            target += name;
        }
        var parts = target.split('/');
        var adapter = parts[0];
        parts.splice(0, 1);
        target = parts.join('/');

        if (source.match(/^http:\/\/|^https:\/\//)) {
            request(source, function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    objects.writeFile(adapter, target, body, function (err) {
                        if (err) console.error(err);
                        if (typeof callback === 'function') callback(err, adapter + '/' + target);
                    });
                } else {
                    console.error('Cannot get URL: ' + error || response.statusCode);
                    if (typeof callback === 'function') callback(error || response.statusCode, adapter + '/' + target);
                }
            });
        } else {
            try {
                objects.writeFile(adapter, target, fs.readFileSync(source), function (err) {
                    if (err) console.error(err);
                    if (typeof callback === 'function') callback(err, adapter + '/' + target);
                });
            } catch (err) {
                console.error('Cannot read file "' + source + '": ' + err);
                if (typeof callback === 'function') callback(err, adapter + '/' + target);
            }
        }
    };

    // Upload www folder of adapter into ObjectsDB
    this.uploadAdapter = function (adapter, isAdmin, forceUpload, subTree, callback) {
        var rev;
        var id = adapter + (isAdmin ? '.admin' : '');
        var adapterDir = tools.getAdapterDir(adapter);
        var dir = adapterDir + (isAdmin ? '/admin' : '/www');
        var files = [];
        if (typeof subTree == 'function') {
            callback = subTree;
            subTree = null;
        }
        if (subTree) {
            dir += '/' + subTree;
        }

        if (!isAdmin) {
            var cfg;
            // check for common.wwwDontUpload (required for legacy adapter)
            if (fs.existsSync(adapterDir + '/io-package.json')) {
                cfg = require(adapterDir + '/io-package.json');
            }
            if (cfg && cfg.common && cfg.common.wwwDontUpload) {
                if (typeof callback === 'function') callback(adapter);
                return;
            }
        }
        // do not upload www dir of admin adapter
        if (adapter === 'admin' && !isAdmin) {
            // To DO remove after a while
            console.log('This should never happens!');
            if (typeof callback === 'function') callback(adapter);
            return;
        }

        // Create "upload progress" object if not exists
        if (!isAdmin) {
            objects.getObject('system.adapter.' + adapter + '.upload', function (err, obj) {
                if (err || !obj) {
                    objects.setObject('system.adapter.' + adapter + '.upload',
                        {
                            _id:   'system.adapter.' + adapter + '.upload',
                            type:   'state',
                            common: {
                                name: adapter + '.upload',
                                type: 'number',
                                role: 'indicator.state',
                                unit: '%',
                                def:  0,
                                desc: 'Upload process indicator'
                            },
                            native: {}
                        }
                    );
                }
            });
            // Set indicator to 0
            states.setState('system.adapter.' + adapter + '.upload', 0, true);
        }

        if (!mime) mime = require('mime');

        function done(err, res) {
            if (err) {
                console.log('error in upload: ' + err);
                callback();
            } else {
                console.log('got ' + dir);
                files = res;
                setTimeout(function (_adapter) {
                    maxFiles = files.length || 1;
                    upload(_adapter);
                }, 25, adapter);
            }
        }

        var maxFiles = 0;
        var lastProgressUpdate = (new Date()).getTime();

        function upload(adapter) {
            var file;
            if (!files.length) {
                console.log('call callback after finished upload');
                if (!isAdmin) {
                    states.setState('system.adapter.' + adapter + '.upload', {val: 0, ack: true}, function () {
                        if (typeof callback === 'function') callback(adapter);
                    });
                } else {
                    if (typeof callback === 'function') callback(adapter);
                }
            } else {
                file = files.pop();
                if (file == '.gitignore') {
                    upload(adapter);
                    return;
                }

                var mimeType = mime.lookup(file);
                var attName;
                attName = file.split('/' + tools.appName + '.');
                if (attName.length === 1) {
                    // try to find anyway if adapter is not lower case
                    var pos = file.toLowerCase().indexOf(tools.appName.toLowerCase());
                    if (pos !== -1) attName = ['', file.substring(tools.appName.length + 2)];
                }

                attName = attName.pop();
                attName = attName.split('/').slice(2).join('/');
                console.log('upload [' + files.length + ']', id, file, attName, mimeType);

                // Update upload indicator
                if (!isAdmin) {
                    var now = (new Date()).getTime();
                    if (now - lastProgressUpdate > 1000) {
                        lastProgressUpdate = now;
                        states.setState('system.adapter.' + adapter + '.upload', {val: parseInt(1000 * (maxFiles - files.length) / maxFiles) / 10, ack: true});
                    }
                }

                fs.createReadStream(file).pipe(
                    objects.insert(id, attName, null, mimeType, {
                        rev: rev
                    }, function (err, res) {
                        if (err) {
                            console.log(err);
                            if (typeof callback === 'function') callback(adapter);
                        }
                        if (res) rev = res.rev;
                        setTimeout(function () {
                            upload(adapter);
                        }, 50);
                    })
                );
            }
        }

        function walk(dir, done) {
            var results = [];
            fs.readdir(dir, function (err, list) {
                if (err) return done(err);
                var i = 0;
                (function next() {
                    var file = list[i++];
                    if (!file) return done(null, results);
                    file = dir + '/' + file;
                    fs.stat(file, function (err, stat) {
                        if (stat && stat.isDirectory()) {
                            walk(file, function (err, res) {
                                results = results.concat(res);
                                next();
                            });
                        } else {
                            if (!file.match(/\.npmignore$/) && !file.match(/\.gitignore$/)) results.push(file);
                            next();
                        }
                    });
                })();
            });
        }

        objects.getObject(id, function (err, res) {
            if (err || !res) {
                objects.setObject(id, {
                    type: 'meta',
                    common: {
                        name: id.split('.').pop(),
                        type: isAdmin ? 'admin' : 'www'
                    },
                    native: {}
                }, function (err, res) {
                    if (res) rev = res.rev;
                    if (!isAdmin) {
                        checkRestartOther(adapter, function () {
                            walk(dir, done);
                        });
                    } else {
                        walk(dir, done);
                    }
                });
            } else {
                if (!forceUpload) {
                    if (typeof callback === 'function') callback(adapter);
                } else {
                    rev = res.rev;
                    if (!isAdmin) {
                        checkRestartOther(adapter, function () {
                            walk(dir, done);
                        });
                    } else {
                        walk(dir, done);
                    }
                }
            }
        });
    };

    function extendNative(target, additional) {
        for (var attr in additional) {
            if (target[attr] === undefined) {
                target[attr] = additional[attr];
            } else if (typeof additional[attr] === 'object' && !(additional[attr] instanceof Array)) {
                target[attr] = target[attr] || {};
                extendNative(target[attr], additional[attr]);
            }
        }
        return target;
    }

    function extendCommon(target, additional) {
        for (var attr in additional) {
            if (attr === 'title' || attr === 'schedule' || attr === 'mode' || attr === 'loglevel' || attr === 'enabled') {
                if (target[attr] === undefined) target[attr] = additional[attr];
            } else
            if (typeof additional[attr] !== 'object' || (additional[attr] instanceof Array)) {
                target[attr] = additional[attr];
            } else {
                target[attr] = target[attr] || {};
                extendCommon(target[attr], additional[attr]);
            }
        }
        return target;
    }

    this.upgradeAdapterObjects = function (name, iopack, callback) {
        if (typeof iopack == 'function') {
            callback = iopack;
            iopack = null;
        }
        if (!iopack) {
            var adapterDir = tools.getAdapterDir(name);
            try {
                iopack = JSON.parse(fs.readFileSync(adapterDir + '/io-package.json'));
            } catch (e) {
                console.error('Cannot find io-package.json in ' + adapterDir);
                iopack = null;
            }
        }

        if (!iopack) {
            callback(name);
        } else {
            objects.getObject('system.adapter.' + name, function (err, obj) {
                if (err || !obj) {
                    console.error('system.adapter.' + name + ' does not exist');
                    callback(name);
                } else {
                    obj.common = iopack.common || {};
                    obj.native = iopack.native || {};

                    obj.common.installedVersion = iopack.common.version;

                    var hostname = tools.getHostName();

                    objects.setObject('system.adapter.' + name, obj, function () {
                        // Update all instances of this host
                        objects.getObjectView('system', 'instance', {startkey: 'system.adapter.' + name + '.', endkey: 'system.adapter.' + name + '.\u9999'}, null, function (err, res) {
                            var cntr = 0;

                            if (res) {
                                for (var i = 0; i < res.rows.length; i++) {
                                    if (res.rows[i].value.common.host === hostname) {
                                        cntr++;
                                        objects.getObject(res.rows[i].id, function (err, _obj) {
                                            var newObject = JSON.parse(JSON.stringify(_obj));

                                            // all common settings should be taken from new one
                                            newObject.common = extendCommon(newObject.common, iopack.common);
                                            newObject.native = extendNative(newObject.native, iopack.native);

                                            newObject.common.installedVersion = iopack.common.version;
                                            newObject.common.version          = iopack.common.version;

                                            // Compare objects to reduce restarts of instances
                                            if (JSON.stringify(newObject) !== JSON.stringify(_obj)) {
                                                console.log('Update "' + newObject._id + '"');
                                                objects.setObject(newObject._id, newObject, function () {
                                                    if (!--cntr && callback) callback(name);
                                                });
                                            } else {
                                                if (!--cntr && callback) callback(name);
                                            }
                                        });
                                    }
                                }
                            }

                            // updates "_design/system" and co
                            if (iopack.objects && typeof iopack.objects === 'object') {
                                for (var _id in iopack.objects) {
                                    if (!iopack.objects.hasOwnProperty(_id)) continue;
                                    cntr++;
                                    objects.setObject(iopack.objects[_id]._id, iopack.objects[_id], function (err) {
                                        if (err) console.error('Cannot update object: ' + err);
                                        if (!--cntr && callback) callback(name);
                                    });
                                }
                            }

                            if (!cntr && callback) callback(name);
                        });
                    });
                }
            });
        }
    };
}

module.exports = Upload;
<|endoftext|>


<commit_before>const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const chaiArrays = require('chai-arrays');

const utils = require('./utils.js');
const tokens = require('./tokens.js');
const defaultTokens = require('./default-tokens.js');

const isVisible = utils.isVisible;

chai.use(chaiAsPromised);
chai.use(chaiArrays);
const expect = chai.expect;

describe.only('Editor', function() {
  before(utils.launchBrowser);

  after(utils.closeBrowser);

  it('Displays editor when clicking on navbar', async function() {
    await this.page.click('a[href="#debugger-io"]');
    // Wait for scroll
    await this.page.waitFor(3000);
    expect(await this.page.$eval('#debugger-io', isVisible)).to.be.true;
  });

  it('HS256 should be selected by default', async function() {
    const selected = await this.page.$eval('#algorithm-select', select => {
      return select.options[select.selectedIndex].value;
    });

    expect(selected).to.equal('HS256');
  });

  it('Should select default tokens when no changes have ' +
     'been made', async function() {
    try {
      await this.page.select('#algorithm-select', 'HS256');

      const algs = await this.page.$eval('#algorithm-select', select => {
        return Array.prototype.map.call(select.options, opt => opt.value);
      });

      for(const alg of algs) {
        await this.page.select('#algorithm-select', alg);
        const token = await this.page.evaluate(() => {
          return window.test.tokenEditor.getValue();
        });

        expect(defaultTokens[alg.toLowerCase()].token).to.equal(token);
      }
    } finally {
      await this.page.select('#algorithm-select', 'HS256');
    }
  });

  it('Should display a tooltip with a human readable ' +
     'date on claim hover', async function() {
    await this.page.mouse.move(0, 0);

    expect(await this.page.$eval('#js-payload-tooltip', isVisible)).to.be.false;

    const iatPos = await this.page.evaluate(() => {
      return window.test.payloadEditor.charCoords({
        line: 4,
        pos: 3
      }, 'window');
    });

    await this.page.mouse.move(iatPos.left, iatPos.top);

    expect(await this.page.$eval('#js-payload-tooltip', isVisible)).to.be.true;
  });

  it('Displays a valid token by default', async function() {
    const valid = await this.page.$eval('.validation-status', status => {
      return status.classList.contains('valid-token') &&
             status.textContent.indexOf('verified') !== -1;
    });

    expect(valid).to.be.true;
  });

  it('Shows invalid token when a valid token is edited ' +
     'in the left pane', async function() {
    await this.page.evaluate(() => {
      let token = window.test.tokenEditor.getValue();
      token += 'asdf23';
      window.test.tokenEditor.setValue(token);
    });

    const invalid = await this.page.$eval('.validation-status', status => {
      return status.classList.contains('invalid-token') &&
             status.textContent.indexOf('invalid') !== -1;
    });

    expect(invalid).to.be.true;
  });

  it('Updates the token when the header is edited', async function() {
    const oldToken = await this.page.evaluate(() => {
      return window.test.tokenEditor.getValue()
    });

    await this.page.click('.js-header');
    await this.page.keyboard.down('ControlLeft');
    await this.page.keyboard.press('KeyA');
    await this.page.keyboard.up('ControlLeft');

    const header = {
      alg: 'HS256',
      typ: 'JWT',
      test: 'test'
    };
    await this.page.keyboard.type(JSON.stringify(header, null, 2), {
      delay: 5
    });

    const newToken = await this.page.evaluate(() => {
      return window.test.tokenEditor.getValue()
    });

    expect(newToken).to.not.equal(oldToken);

    const valid = await this.page.$eval('.validation-status', status => {
      return status.classList.contains('valid-token') &&
             status.textContent.indexOf('verified') !== -1;
    });

    expect(valid).to.be.true;
  });

  it('Updates the token when the payload is edited', async function() {
    const oldToken = await this.page.evaluate(() => {
      return window.test.tokenEditor.getValue()
    });

    await this.page.click('.js-payload');
    await this.page.keyboard.down('ControlLeft');
    await this.page.keyboard.press('KeyA');
    await this.page.keyboard.up('ControlLeft');

    const payload = {
      "sub": "1234567890",
      "name": "John Doe",
      "admin": true,
      "iat": 1516239022,
      "test": "test"
    };
    await this.page.keyboard.type(JSON.stringify(payload, null, 2), {
      delay: 5
    });

    const newToken = await this.page.evaluate(() => {
      return window.test.tokenEditor.getValue()
    });

    expect(newToken).to.not.equal(oldToken);

    const valid = await this.page.$eval('.validation-status', status => {
      return status.classList.contains('valid-token') &&
             status.textContent.indexOf('verified') !== -1;
    });

    expect(valid).to.be.true;
  });

  it('Selects algorithm when header is edited', async function() {
    const selectedBefore =
      await this.page.$eval('#algorithm-select', select => {
        return select.options[select.selectedIndex].value;
      });

    await this.page.click('.js-header');
    await this.page.keyboard.down('ControlLeft');
    await this.page.keyboard.press('KeyA');
    await this.page.keyboard.up('ControlLeft');

    const header = {
      alg: 'HS384',
      typ: 'JWT',
    };
    await this.page.keyboard.type(JSON.stringify(header, null, 2), {
      delay: 5
    });

    const selectedAfter =
      await this.page.$eval('#algorithm-select', select => {
        return select.options[select.selectedIndex].value;
      });

    expect(selectedBefore).to.not.equal(selectedAfter);
    expect(selectedAfter).to.equal('HS384');

    const valid = await this.page.$eval('.validation-status', status => {
      return status.classList.contains('valid-token') &&
             status.textContent.indexOf('verified') !== -1;
    });

    expect(valid).to.be.true;
  });

  it('Should never revert to a default token after a non-default token ' +
     'is generated', async function() {
    await this.page.select('#algorithm-select', 'HS256');

    await this.page.click('.js-payload');
    await this.page.keyboard.down('ControlLeft');
    await this.page.keyboard.press('KeyA');
    await this.page.keyboard.up('ControlLeft');

    const payload = {
      sub: 'test'
    };
    await this.page.keyboard.type(JSON.stringify(payload, null, 2), {
      delay: 5
    });

    const algs = await this.page.$eval('#algorithm-select', select => {
      return Array.prototype.map.call(select.options, opt => opt.value);
    });

    for(const alg of algs) {
      await this.page.select('#algorithm-select', alg);
    }

    const payloadInEditor = await this.page.evaluate(() => {
      return JSON.parse(window.test.payloadEditor.getValue());
    });

    expect(payload).to.deep.equal(payloadInEditor);
  });

  describe('HMAC', function() {
    before(async function() {
      await this.page.select('#algorithm-select', 'HS256');
    });

    it('Updates the token when the secret changes', async function() {
      const oldToken = await this.page.evaluate(() => {
        return window.test.tokenEditor.getValue()
      });

      const secretInput = await this.page.$('input[name="secret"]');

      await secretInput.type('asdfasdf');

      const newToken = await this.page.evaluate(() => {
        return window.test.tokenEditor.getValue()
      });

      expect(oldToken).to.not.equal(newToken);
    });

    it('Updates the token when the Base64 checkbox changes', async function() {
      const oldToken = await this.page.evaluate(() => {
        return window.test.tokenEditor.getValue()
      });

      await this.page.click('#is-base64-encoded');

      let newToken = await this.page.evaluate(() => {
        return window.test.tokenEditor.getValue()
      });

      expect(oldToken).to.not.equal(newToken);

      await this.page.click('#is-base64-encoded');

      newToken = await this.page.evaluate(() => {
        return window.test.tokenEditor.getValue()
      });

      expect(oldToken).to.equal(newToken);
    });

    describe('Decodes HS256/384/512 tokens', async function() {
      const algs = Object.keys(tokens).filter(alg => alg.includes('hs'));

      for(const alg of algs) {
        it(alg.toUpperCase(), async function() {
          const secretInput = await this.page.$('input[name="secret"]');
          await secretInput.click();
          await this.page.keyboard.down('ControlLeft');
          await this.page.keyboard.press('KeyA');
          await this.page.keyboard.up('ControlLeft');
          await secretInput.type(tokens[alg].secret, {
            delay: 5
          });

          await this.page.click('.js-input');
          await this.page.keyboard.down('ControlLeft');
          await this.page.keyboard.press('KeyA');
          await this.page.keyboard.up('ControlLeft');
          await this.page.keyboard.type(tokens[alg].token, {
            delay: 5
          });

          const valid = await this.page.$eval('.validation-status', status => {
            return status.classList.contains('valid-token') &&
                  status.textContent.indexOf('verified') !== -1;
          });

          expect(valid).to.be.true;

          const payload = await this.page.evaluate(() => {
            return window.test.payloadEditor.getValue();
          });

          expect(payload).to.include(alg + 'test');
        });
      }
    });
  });
});
<commit_msg>Remove '.only()' used for debugging.<commit_after>const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const chaiArrays = require('chai-arrays');

const utils = require('./utils.js');
const tokens = require('./tokens.js');
const defaultTokens = require('./default-tokens.js');

const isVisible = utils.isVisible;

chai.use(chaiAsPromised);
chai.use(chaiArrays);
const expect = chai.expect;

describe('Editor', function() {
  before(utils.launchBrowser);

  after(utils.closeBrowser);

  it('Displays editor when clicking on navbar', async function() {
    await this.page.click('a[href="#debugger-io"]');
    // Wait for scroll
    await this.page.waitFor(3000);
    expect(await this.page.$eval('#debugger-io', isVisible)).to.be.true;
  });

  it('HS256 should be selected by default', async function() {
    const selected = await this.page.$eval('#algorithm-select', select => {
      return select.options[select.selectedIndex].value;
    });

    expect(selected).to.equal('HS256');
  });

  it('Should select default tokens when no changes have ' +
     'been made', async function() {
    try {
      await this.page.select('#algorithm-select', 'HS256');

      const algs = await this.page.$eval('#algorithm-select', select => {
        return Array.prototype.map.call(select.options, opt => opt.value);
      });

      for(const alg of algs) {
        await this.page.select('#algorithm-select', alg);
        const token = await this.page.evaluate(() => {
          return window.test.tokenEditor.getValue();
        });

        expect(defaultTokens[alg.toLowerCase()].token).to.equal(token);
      }
    } finally {
      await this.page.select('#algorithm-select', 'HS256');
    }
  });

  it('Should display a tooltip with a human readable ' +
     'date on claim hover', async function() {
    await this.page.mouse.move(0, 0);

    expect(await this.page.$eval('#js-payload-tooltip', isVisible)).to.be.false;

    const iatPos = await this.page.evaluate(() => {
      return window.test.payloadEditor.charCoords({
        line: 4,
        pos: 3
      }, 'window');
    });

    await this.page.mouse.move(iatPos.left, iatPos.top);

    expect(await this.page.$eval('#js-payload-tooltip', isVisible)).to.be.true;
  });

  it('Displays a valid token by default', async function() {
    const valid = await this.page.$eval('.validation-status', status => {
      return status.classList.contains('valid-token') &&
             status.textContent.indexOf('verified') !== -1;
    });

    expect(valid).to.be.true;
  });

  it('Shows invalid token when a valid token is edited ' +
     'in the left pane', async function() {
    await this.page.evaluate(() => {
      let token = window.test.tokenEditor.getValue();
      token += 'asdf23';
      window.test.tokenEditor.setValue(token);
    });

    const invalid = await this.page.$eval('.validation-status', status => {
      return status.classList.contains('invalid-token') &&
             status.textContent.indexOf('invalid') !== -1;
    });

    expect(invalid).to.be.true;
  });

  it('Updates the token when the header is edited', async function() {
    const oldToken = await this.page.evaluate(() => {
      return window.test.tokenEditor.getValue()
    });

    await this.page.click('.js-header');
    await this.page.keyboard.down('ControlLeft');
    await this.page.keyboard.press('KeyA');
    await this.page.keyboard.up('ControlLeft');

    const header = {
      alg: 'HS256',
      typ: 'JWT',
      test: 'test'
    };
    await this.page.keyboard.type(JSON.stringify(header, null, 2), {
      delay: 5
    });

    const newToken = await this.page.evaluate(() => {
      return window.test.tokenEditor.getValue()
    });

    expect(newToken).to.not.equal(oldToken);

    const valid = await this.page.$eval('.validation-status', status => {
      return status.classList.contains('valid-token') &&
             status.textContent.indexOf('verified') !== -1;
    });

    expect(valid).to.be.true;
  });

  it('Updates the token when the payload is edited', async function() {
    const oldToken = await this.page.evaluate(() => {
      return window.test.tokenEditor.getValue()
    });

    await this.page.click('.js-payload');
    await this.page.keyboard.down('ControlLeft');
    await this.page.keyboard.press('KeyA');
    await this.page.keyboard.up('ControlLeft');

    const payload = {
      "sub": "1234567890",
      "name": "John Doe",
      "admin": true,
      "iat": 1516239022,
      "test": "test"
    };
    await this.page.keyboard.type(JSON.stringify(payload, null, 2), {
      delay: 5
    });

    const newToken = await this.page.evaluate(() => {
      return window.test.tokenEditor.getValue()
    });

    expect(newToken).to.not.equal(oldToken);

    const valid = await this.page.$eval('.validation-status', status => {
      return status.classList.contains('valid-token') &&
             status.textContent.indexOf('verified') !== -1;
    });

    expect(valid).to.be.true;
  });

  it('Selects algorithm when header is edited', async function() {
    const selectedBefore =
      await this.page.$eval('#algorithm-select', select => {
        return select.options[select.selectedIndex].value;
      });

    await this.page.click('.js-header');
    await this.page.keyboard.down('ControlLeft');
    await this.page.keyboard.press('KeyA');
    await this.page.keyboard.up('ControlLeft');

    const header = {
      alg: 'HS384',
      typ: 'JWT',
    };
    await this.page.keyboard.type(JSON.stringify(header, null, 2), {
      delay: 5
    });

    const selectedAfter =
      await this.page.$eval('#algorithm-select', select => {
        return select.options[select.selectedIndex].value;
      });

    expect(selectedBefore).to.not.equal(selectedAfter);
    expect(selectedAfter).to.equal('HS384');

    const valid = await this.page.$eval('.validation-status', status => {
      return status.classList.contains('valid-token') &&
             status.textContent.indexOf('verified') !== -1;
    });

    expect(valid).to.be.true;
  });

  it('Should never revert to a default token after a non-default token ' +
     'is generated', async function() {
    await this.page.select('#algorithm-select', 'HS256');

    await this.page.click('.js-payload');
    await this.page.keyboard.down('ControlLeft');
    await this.page.keyboard.press('KeyA');
    await this.page.keyboard.up('ControlLeft');

    const payload = {
      sub: 'test'
    };
    await this.page.keyboard.type(JSON.stringify(payload, null, 2), {
      delay: 5
    });

    const algs = await this.page.$eval('#algorithm-select', select => {
      return Array.prototype.map.call(select.options, opt => opt.value);
    });

    for(const alg of algs) {
      await this.page.select('#algorithm-select', alg);
    }

    const payloadInEditor = await this.page.evaluate(() => {
      return JSON.parse(window.test.payloadEditor.getValue());
    });

    expect(payload).to.deep.equal(payloadInEditor);
  });

  describe('HMAC', function() {
    before(async function() {
      await this.page.select('#algorithm-select', 'HS256');
    });

    it('Updates the token when the secret changes', async function() {
      const oldToken = await this.page.evaluate(() => {
        return window.test.tokenEditor.getValue()
      });

      const secretInput = await this.page.$('input[name="secret"]');

      await secretInput.type('asdfasdf');

      const newToken = await this.page.evaluate(() => {
        return window.test.tokenEditor.getValue()
      });

      expect(oldToken).to.not.equal(newToken);
    });

    it('Updates the token when the Base64 checkbox changes', async function() {
      const oldToken = await this.page.evaluate(() => {
        return window.test.tokenEditor.getValue()
      });

      await this.page.click('#is-base64-encoded');

      let newToken = await this.page.evaluate(() => {
        return window.test.tokenEditor.getValue()
      });

      expect(oldToken).to.not.equal(newToken);

      await this.page.click('#is-base64-encoded');

      newToken = await this.page.evaluate(() => {
        return window.test.tokenEditor.getValue()
      });

      expect(oldToken).to.equal(newToken);
    });

    describe('Decodes HS256/384/512 tokens', async function() {
      const algs = Object.keys(tokens).filter(alg => alg.includes('hs'));

      for(const alg of algs) {
        it(alg.toUpperCase(), async function() {
          const secretInput = await this.page.$('input[name="secret"]');
          await secretInput.click();
          await this.page.keyboard.down('ControlLeft');
          await this.page.keyboard.press('KeyA');
          await this.page.keyboard.up('ControlLeft');
          await secretInput.type(tokens[alg].secret, {
            delay: 5
          });

          await this.page.click('.js-input');
          await this.page.keyboard.down('ControlLeft');
          await this.page.keyboard.press('KeyA');
          await this.page.keyboard.up('ControlLeft');
          await this.page.keyboard.type(tokens[alg].token, {
            delay: 5
          });

          const valid = await this.page.$eval('.validation-status', status => {
            return status.classList.contains('valid-token') &&
                  status.textContent.indexOf('verified') !== -1;
          });

          expect(valid).to.be.true;

          const payload = await this.page.evaluate(() => {
            return window.test.payloadEditor.getValue();
          });

          expect(payload).to.include(alg + 'test');
        });
      }
    });
  });
});
<|endoftext|>


<commit_before>import expect from 'expect';
import expectJSX from 'expect-jsx';
import React from 'react';
import {createRenderer} from 'react-addons-test-utils';

expect.extend(expectJSX);

export default function (ReactIntl) {
    describe('format', () => {
        const {
            IntlProvider,
            FormattedDate,
            FormattedTime,
            FormattedRelative,
            FormattedNumber,
            FormattedMessage,
        } = ReactIntl;

        let renderer;
        let intlProvider;

        beforeEach(() => {
            renderer     = createRenderer();
            intlProvider = new IntlProvider({locale: 'en'}, {});
        });

        it('formats dates', () => {
            const date = new Date();
            const el   = <FormattedDate value={date} month="numeric" />;

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(
                {date.getMonth() + 1}
            );
        });

        it('formats times', () => {
            const date = new Date();
            const el   = <FormattedTime value={date} />;

            const hours   = date.getHours();
            const minutes = date.getMinutes();

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(

                    {`${hours > 12 ? (hours % 12) : hours}:${minutes} ${hours < 12 ? 'AM' : 'PM'}`}

            );
        });

        it('formats dates relative to "now"', () => {
            const now = Date.now();
            const el  = <FormattedRelative value={now - 1000} initialNow={now} />;

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(
                1 second ago
            );
        });

        it('formats numbers with thousands separators', () => {
            const el = <FormattedNumber value={1000} />;

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(
                1,000
            );
        });

        it('formats numbers with decimal separators', () => {
            const el = <FormattedNumber value={0.1} minimumFractionDigits={2} />;

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(
                0.10
            );
        });

        it('pluralizes labels in strings', () => {
            const el = (
                <FormattedMessage
                    id="num_emails"
                    defaultMessage="You have {emails, plural, one {# email} other {# emails}}."
                    values={{
                        emails: 1000,
                    }}
                />
            );

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(
                You have 1,000 emails.
            );
        });
    });
}
<commit_msg>Fix unit test expected result<commit_after>import expect from 'expect';
import expectJSX from 'expect-jsx';
import React from 'react';
import {createRenderer} from 'react-addons-test-utils';

expect.extend(expectJSX);

export default function (ReactIntl) {
    describe('format', () => {
        const {
            IntlProvider,
            FormattedDate,
            FormattedTime,
            FormattedRelative,
            FormattedNumber,
            FormattedMessage,
        } = ReactIntl;

        let renderer;
        let intlProvider;

        beforeEach(() => {
            renderer     = createRenderer();
            intlProvider = new IntlProvider({locale: 'en'}, {});
        });

        it('formats dates', () => {
            const date = new Date();
            const el   = <FormattedDate value={date} month="numeric" />;

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(
                {date.getMonth() + 1}
            );
        });

        it('formats times', () => {
            const date = new Date();
            const el   = <FormattedTime value={date} />;

            const hours   = date.getHours();
            const minutes = date.getMinutes();

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(

                    {
                        `${hours > 12 ? (hours % 12) : hours}:` +
                        `${minutes < 10 ? `0${minutes}` : minutes} ` +
                        `${hours < 12 ? 'AM' : 'PM'}`
                    }

            );
        });

        it('formats dates relative to "now"', () => {
            const now = Date.now();
            const el  = <FormattedRelative value={now - 1000} initialNow={now} />;

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(
                1 second ago
            );
        });

        it('formats numbers with thousands separators', () => {
            const el = <FormattedNumber value={1000} />;

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(
                1,000
            );
        });

        it('formats numbers with decimal separators', () => {
            const el = <FormattedNumber value={0.1} minimumFractionDigits={2} />;

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(
                0.10
            );
        });

        it('pluralizes labels in strings', () => {
            const el = (
                <FormattedMessage
                    id="num_emails"
                    defaultMessage="You have {emails, plural, one {# email} other {# emails}}."
                    values={{
                        emails: 1000,
                    }}
                />
            );

            renderer.render(el, intlProvider.getChildContext());
            expect(renderer.getRenderOutput()).toEqualJSX(
                You have 1,000 emails.
            );
        });
    });
}
<|endoftext|>