<commit_before>/* global describe, it */
/* eslint-disable camelcase, max-nested-callbacks, import/no-unassigned-import */

require('should');
const unifi = require('../unifi.js');

let CONTROLLER_IP = '127.0.0.1';
if (process.env.CONTROLLER_IP) {
  CONTROLLER_IP = process.env.CONTROLLER_IP;
}
let CONTROLLER_PORT = 8443;
if (process.env.CONTROLLER_PORT) {
  CONTROLLER_PORT = process.env.CONTROLLER_PORT;
}
let CONTROLLER_USER = 'ubnt';
if (process.env.CONTROLLER_USER) {
  CONTROLLER_USER = process.env.CONTROLLER_USER;
}
let CONTROLLER_PASS = 'ubnt';
if (process.env.CONTROLLER_PASS) {
  CONTROLLER_PASS = process.env.CONTROLLER_PASS;
}

// Run the tests
describe('Running tests', () => {
  const controller = new unifi.Controller(CONTROLLER_IP, CONTROLLER_PORT);

  // LOGIN
  it('login()', done => {
    if (controller !== null) {
      controller.login(CONTROLLER_USER, CONTROLLER_PASS, err => {
        if (err) {
          done(err);
        } else {
          done();
        }
      });
    }
  });

  // GET SITE STATS
  let controller_sites = null;
  it('getSitesStats()', done => {
    controller.getSitesStats((err, sites) => {
      if (err) {
        done(err);
      } else if (typeof (sites) === 'undefined' || sites.length <= 0) {
        done('ERROR: getSitesStats()');
      } else {
        controller_sites = sites;
        done();
      }
    });
  });

  // AUTHORIZE GUEST
  it('authorizeGuest()', done => {
    controller.authorizeGuest(controller_sites[0].name, 'aa:bb:CC:DD:EE:FF', 100, (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: authorizeGuest()');
      } else {
        result[0][0].mac.should.equal('aa:bb:cc:dd:ee:ff');
        result[0][0].end.should.aboveOrEqual(result[0][0].start + (100 * 60));
        result[0][0].end.should.belowOrEqual(result[0][0].start + (140 * 60));
        result[0][0].qos_rate_max_up.should.equal(20);
        result[0][0].qos_rate_max_down.should.equal(30);
        result[0][0].qos_usage_quota.should.equal(40);
        done();
      }
    }, 20, 30, 40, 'ff:ee:dd:cc:BB:AA');
  });

  // UN-AUTHORIZE GUEST
  it('unauthorizeGuest()', done => {
    controller.unauthorizeGuest(controller_sites[0].name, 'aa:bb:CC:DD:EE:FF', (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: unauthorizeGuest()');
      } else {
        done();
      }
    });
  });

  // Reconnect a client device
  it('reconnectClient()', done => {
    controller.unauthorizeGuest(controller_sites[0].name, 'aa:bb:CC:DD:EE:FF', (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: reconnectClient()');
      } else {
        done();
      }
    });
  });

  // Block a client device
  it('blockClient()', done => {
    controller.blockClient(controller_sites[0].name, 'aa:bb:CC:DD:EE:FF', (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: blockClient()');
      } else {
        result[0][0].mac.should.equal('aa:bb:cc:dd:ee:ff');
        result[0][0].blocked.should.equal(true);
        done();
      }
    });
  });

  // Unblock a client device
  it('unblockClient()', done => {
    controller.unblockClient(controller_sites[0].name, 'aa:bb:CC:DD:EE:FF', (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: unblockClient()');
      } else {
        result[0][0].mac.should.equal('aa:bb:cc:dd:ee:ff');
        result[0][0].blocked.should.equal(false);
        done();
      }
    });
  });

  // Forget one or more client devices
  it('forgetClient()', done => {
    controller.forgetClient(controller_sites[0].name, ['aa:bb:CC:DD:EE:FF'], (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: forgetClient()');
      } else {
        done();
      }
    });
  });

  // List user groups
  let defaultGroupID = null;
  it('getUserGroups()', done => {
    controller.getUserGroups(controller_sites[0].name, (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: getUserGroups()');
      } else {
        result[0][0].name.should.equal('Default');
        result[0][0].attr_no_delete.should.equal(true);
        defaultGroupID = result[0][0]._id;
        done();
      }
    });
  });

  // Create a new user/client-device
  it('createUser()', done => {
    controller.createUser(controller_sites[0].name, 'FF:EE:DD:CC:bb:aa', defaultGroupID, (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: createUser()');
      } else {
        result[0][0].meta.rc.should.equal('ok');
        result[0][0].data[0].mac.should.equal('ff:ee:dd:cc:bb:aa');
        result[0][0].data[0].name.should.equal('createUserTest');
        result[0][0].data[0].note.should.equal('createUserTest note');
        result[0][0].data[0].is_wired.should.equal(true);
        result[0][0].data[0].is_guest.should.equal(false);
        done();
      }
    }, 'createUserTest', 'createUserTest note', true, false);
  });

  // GET SITE SYSINFO
  it('getSiteSysinfo()', done => {
    controller.getSiteSysinfo(controller_sites[0].name, (err, sysinfo) => {
      if (err) {
        done(err);
      } else if (typeof (sysinfo) === 'undefined' || sysinfo.length <= 0) {
        done('ERROR: getSiteSysinfo()');
      } else {
        done();
      }
    });
  });

  // GET CLIENT DEVICES
  it('getClientDevices()', done => {
    controller.getClientDevices(controller_sites[0].name, (err, client_data) => {
      if (err) {
        done(err);
      } else if (typeof (client_data) === 'undefined' || client_data.length < 0) {
        done('ERROR: getClientDevices()');
      } else {
        done();
      }
    });
  });

  // GET ALL USERS EVER CONNECTED
  it('getAllUsers()', done => {
    controller.getAllUsers(controller_sites[0].name, (err, users_data) => {
      if (err) {
        done(err);
      } else if (typeof (users_data) === 'undefined' || users_data.length < 0) {
        done('ERROR: getAllUsers()');
      } else {
        done();
      }
    });
  });

  // GET ALL ACCESS DEVICES
  it('getAccessDevices()', done => {
    controller.getAccessDevices(controller_sites[0].name, (err, access_data) => {
      if (err) {
        done(err);
      } else if (typeof (access_data) === 'undefined' || access_data.length < 0) {
        done('ERROR: getAccessDevices()');
      } else {
        done();
      }
    });
  });

  // GET ALL SESSIONS
  it('getSessions()', done => {
    controller.getSessions(controller_sites[0].name, (err, session_data) => {
      if (err) {
        done(err);
      } else if (typeof (session_data) === 'undefined' || session_data.length < 0) {
        done('ERROR: getSessions()');
      } else {
        done();
      }
    });
  });

  // GET ALL AUTHORIZATIONS
  it('getAllAuthorizations()', done => {
    controller.getAllAuthorizations(controller_sites[0].name, (err, auth_data) => {
      if (err) {
        done(err);
      } else if (typeof (auth_data) === 'undefined' || auth_data.length < 0) {
        done('ERROR: getSessions()');
      } else {
        done();
      }
    });
  });

  // GET USERS
  it('getUsers()', done => {
    controller.getUsers(controller_sites[0].name, (err, user_data) => {
      if (err) {
        done(err);
      } else if (typeof (user_data) === 'undefined' || user_data.length < 0) {
        done('ERROR: getUsers()');
      } else {
        done();
      }
    });
  });

  // GET SELF
  it('getSelf()', done => {
    controller.getSelf(controller_sites[0].name, (err, self_data) => {
      if (err) {
        done(err);
      } else if (typeof (self_data) === 'undefined' || self_data.length < 0) {
        done('ERROR: getSelf()');
      } else {
        done();
      }
    });
  });

  // LOGOUT
  it('logout()', done => {
    controller.logout(err => {
      if (err) {
        done(err);
      } else {
        done();
      }
    });
  });
});
<commit_msg>added more API tests.<commit_after>/* global describe, it */
/* eslint-disable camelcase, max-nested-callbacks, import/no-unassigned-import */

require('should');
const unifi = require('../unifi.js');

let CONTROLLER_IP = '127.0.0.1';
if (process.env.CONTROLLER_IP) {
  CONTROLLER_IP = process.env.CONTROLLER_IP;
}
let CONTROLLER_PORT = 8443;
if (process.env.CONTROLLER_PORT) {
  CONTROLLER_PORT = process.env.CONTROLLER_PORT;
}
let CONTROLLER_USER = 'ubnt';
if (process.env.CONTROLLER_USER) {
  CONTROLLER_USER = process.env.CONTROLLER_USER;
}
let CONTROLLER_PASS = 'ubnt';
if (process.env.CONTROLLER_PASS) {
  CONTROLLER_PASS = process.env.CONTROLLER_PASS;
}

// Run the tests
describe('Running tests', () => {
  const controller = new unifi.Controller(CONTROLLER_IP, CONTROLLER_PORT);

  // LOGIN
  it('login()', done => {
    if (controller !== null) {
      controller.login(CONTROLLER_USER, CONTROLLER_PASS, err => {
        if (err) {
          done(err);
        } else {
          done();
        }
      });
    }
  });

  // GET SITE STATS
  let controller_sites = null;
  it('getSitesStats()', done => {
    controller.getSitesStats((err, sites) => {
      if (err) {
        done(err);
      } else if (typeof (sites) === 'undefined' || sites.length <= 0) {
        done('ERROR: getSitesStats()');
      } else {
        controller_sites = sites;
        done();
      }
    });
  });

  // AUTHORIZE GUEST
  it('authorizeGuest()', done => {
    controller.authorizeGuest(controller_sites[0].name, 'aa:bb:CC:DD:EE:FF', 100, (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: authorizeGuest()');
      } else {
        result[0][0].mac.should.equal('aa:bb:cc:dd:ee:ff');
        result[0][0].end.should.aboveOrEqual(result[0][0].start + (100 * 60));
        result[0][0].end.should.belowOrEqual(result[0][0].start + (140 * 60));
        result[0][0].qos_rate_max_up.should.equal(20);
        result[0][0].qos_rate_max_down.should.equal(30);
        result[0][0].qos_usage_quota.should.equal(40);
        done();
      }
    }, 20, 30, 40, 'aa:bb:cc:dd:ee:fa');
  });

  // UN-AUTHORIZE GUEST
  it('unauthorizeGuest()', done => {
    controller.unauthorizeGuest(controller_sites[0].name, 'aa:bb:CC:DD:EE:FF', (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: unauthorizeGuest()');
      } else {
        done();
      }
    });
  });

  // Reconnect a client device
  it('reconnectClient()', done => {
    controller.unauthorizeGuest(controller_sites[0].name, 'aa:bb:CC:DD:EE:FF', (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: reconnectClient()');
      } else {
        done();
      }
    });
  });

  // Block a client device
  it('blockClient()', done => {
    controller.blockClient(controller_sites[0].name, 'aa:bb:CC:DD:EE:FF', (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: blockClient()');
      } else {
        result[0][0].mac.should.equal('aa:bb:cc:dd:ee:ff');
        result[0][0].blocked.should.equal(true);
        done();
      }
    });
  });

  // Unblock a client device
  it('unblockClient()', done => {
    controller.unblockClient(controller_sites[0].name, 'aa:bb:CC:DD:EE:FF', (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: unblockClient()');
      } else {
        result[0][0].mac.should.equal('aa:bb:cc:dd:ee:ff');
        result[0][0].blocked.should.equal(false);
        done();
      }
    });
  });

  // List user groups
  let defaultGroupID = null;
  it('getUserGroups()', done => {
    controller.getUserGroups(controller_sites[0].name, (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: getUserGroups()');
      } else {
        result[0][0].name.should.equal('Default');
        result[0][0].attr_no_delete.should.equal(true);
        defaultGroupID = result[0][0]._id;
        done();
      }
    });
  });

  // Create a new user/client-device
  let createdUserID = null;
  it('createUser()', done => {
    controller.createUser(controller_sites[0].name, 'FF:EE:DD:CC:bb:aa', defaultGroupID, (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: createUser()');
      } else if (typeof (result[0][0].meta.msg) === 'undefined') {
        result[0][0].meta.rc.should.equal('ok');
        result[0][0].data[0].mac.should.equal('ff:ee:dd:cc:bb:aa');
        result[0][0].data[0].name.should.equal('createUserTest');
        result[0][0].data[0].note.should.equal('createUserTest note');
        result[0][0].data[0].is_wired.should.equal(true);
        result[0][0].data[0].is_guest.should.equal(false);
        createdUserID = result[0][0].data[0]._id;
        done();
      } else {
        done(result[0][0].meta.msg);
      }
    }, 'createUserTest', 'createUserTest note', true, false);
  });

  // Add/modify/remove a client device not
  it('setClientNote()', done => {
    controller.setClientNote(controller_sites[0].name, createdUserID, (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: createUser()');
      } else {
        console.log(result);
        result[0][0].note.should.equal('createUserTest note changed');
        result[0][0].name.should.equal('createUserTest');
        result[0][0].data[0].is_wired.should.equal(true);
        result[0][0].data[0].is_guest.should.equal(false);
        done();
      }
    }, 'createUserTest note changed');
  });

  // Forget one or more client devices
  it('forgetClient()', done => {
    controller.forgetClient(controller_sites[0].name, ['aa:bb:cc:dd:ee:ff', 'FF:EE:DD:CC:bb:aa'], (err, result) => {
      if (err) {
        done(err);
      } else if (typeof (result) === 'undefined') {
        done('ERROR: forgetClient()');
      } else {
        done();
      }
    });
  });

  // GET SITE SYSINFO
  it('getSiteSysinfo()', done => {
    controller.getSiteSysinfo(controller_sites[0].name, (err, sysinfo) => {
      if (err) {
        done(err);
      } else if (typeof (sysinfo) === 'undefined' || sysinfo.length <= 0) {
        done('ERROR: getSiteSysinfo()');
      } else {
        done();
      }
    });
  });

  // GET CLIENT DEVICES
  it('getClientDevices()', done => {
    controller.getClientDevices(controller_sites[0].name, (err, client_data) => {
      if (err) {
        done(err);
      } else if (typeof (client_data) === 'undefined' || client_data.length < 0) {
        done('ERROR: getClientDevices()');
      } else {
        done();
      }
    });
  });

  // GET ALL USERS EVER CONNECTED
  it('getAllUsers()', done => {
    controller.getAllUsers(controller_sites[0].name, (err, users_data) => {
      if (err) {
        done(err);
      } else if (typeof (users_data) === 'undefined' || users_data.length < 0) {
        done('ERROR: getAllUsers()');
      } else {
        done();
      }
    });
  });

  // GET ALL ACCESS DEVICES
  it('getAccessDevices()', done => {
    controller.getAccessDevices(controller_sites[0].name, (err, access_data) => {
      if (err) {
        done(err);
      } else if (typeof (access_data) === 'undefined' || access_data.length < 0) {
        done('ERROR: getAccessDevices()');
      } else {
        done();
      }
    });
  });

  // GET ALL SESSIONS
  it('getSessions()', done => {
    controller.getSessions(controller_sites[0].name, (err, session_data) => {
      if (err) {
        done(err);
      } else if (typeof (session_data) === 'undefined' || session_data.length < 0) {
        done('ERROR: getSessions()');
      } else {
        done();
      }
    });
  });

  // GET ALL AUTHORIZATIONS
  it('getAllAuthorizations()', done => {
    controller.getAllAuthorizations(controller_sites[0].name, (err, auth_data) => {
      if (err) {
        done(err);
      } else if (typeof (auth_data) === 'undefined' || auth_data.length < 0) {
        done('ERROR: getSessions()');
      } else {
        done();
      }
    });
  });

  // GET USERS
  it('getUsers()', done => {
    controller.getUsers(controller_sites[0].name, (err, user_data) => {
      if (err) {
        done(err);
      } else if (typeof (user_data) === 'undefined' || user_data.length < 0) {
        done('ERROR: getUsers()');
      } else {
        done();
      }
    });
  });

  // GET SELF
  it('getSelf()', done => {
    controller.getSelf(controller_sites[0].name, (err, self_data) => {
      if (err) {
        done(err);
      } else if (typeof (self_data) === 'undefined' || self_data.length < 0) {
        done('ERROR: getSelf()');
      } else {
        done();
      }
    });
  });

  // LOGOUT
  it('logout()', done => {
    controller.logout(err => {
      if (err) {
        done(err);
      } else {
        done();
      }
    });
  });
});
<|endoftext|>


<commit_before>'use strict'

const IPFS = require('ipfs')
const IPFSRepo = require('ipfs-repo')
const DatastoreLevel = require('datastore-level')
const Keystore = require('orbit-db-keystore')
const Log = require('../src/log')
const { AccessController, IdentityProvider } = Log

// State
let ipfs
let log1, log2

// Metrics
let totalQueries = 0
let seconds = 0
let queriesPerSecond = 0
let lastTenSeconds = 0

const queryLoop = async () => {
  try {
    await Promise.all([
      log1.append('a' + totalQueries),
      log2.append('b' + totalQueries)
    ])

    await log1.join(log2)
    await log2.join(log1)
    totalQueries++
    lastTenSeconds++
    queriesPerSecond++
    setImmediate(queryLoop)
  } catch (e) {
    console.error(e)
    process.exit(0)
  }
}

let run = (() => {
  console.log('Starting benchmark...')

  const repoConf = {
    storageBackends: {
      blocks: DatastoreLevel
    }
  }

  ipfs = new IPFS({
    repo: new IPFSRepo('./ipfs-log-benchmarks/ipfs', repoConf),
    start: false,
    EXPERIMENTAL: {
      pubsub: true
    }
  })

  ipfs.on('error', (err) => {
    console.error(err)
    process.exit(1)
  })

  ipfs.on('ready', async () => {
    // Use memory store to test without disk IO
    // const memstore = new MemStore()
    // ipfs.object.put = memstore.put.bind(memstore)
    // ipfs.object.get = memstore.get.bind(memstore)

    const testKeysPath = './test/fixtures/keys'
    const keystore = Keystore.create(testKeysPath)
    const identitySignerFn = (id, data) => {
      const key = keystore.getKey(id)
      return keystore.sign(key, data)
    }
    const access = new AccessController()
    const identity = await IdentityProvider.createIdentity(keystore, 'userA', identitySignerFn)
    const identity2 = await IdentityProvider.createIdentity(keystore, 'userB', identitySignerFn)

    log1 = new Log(ipfs, access, identity, 'A')
    log2 = new Log(ipfs, access, identity2, 'B')

    // Output metrics at 1 second interval
    setInterval(() => {
      seconds++
      if (seconds % 10 === 0) {
        console.log(`--> Average of ${lastTenSeconds / 10} q/s in the last 10 seconds`)
        if (lastTenSeconds === 0) throw new Error('Problems!')
        lastTenSeconds = 0
      }
      console.log(`${queriesPerSecond} queries per second, ${totalQueries} queries in ${seconds} seconds. log1: ${log1.length}, log2: ${log2.length}`)
      queriesPerSecond = 0
    }, 1000)

    queryLoop()
  })
})()

module.exports = run
<commit_msg>Fix benchmark-join<commit_after>'use strict'

const IPFS = require('ipfs')
const IPFSRepo = require('ipfs-repo')
const DatastoreLevel = require('datastore-level')
const Keystore = require('orbit-db-keystore')
const Log = require('../src/log')
const { AccessController, IdentityProvider } = Log

// State
let ipfs
let log1, log2

// Metrics
let totalQueries = 0
let seconds = 0
let queriesPerSecond = 0
let lastTenSeconds = 0

const queryLoop = async () => {
  try {
    await Promise.all([
      log1.append('a' + totalQueries),
      log2.append('b' + totalQueries)
    ])

    await log1.join(log2)
    await log2.join(log1)
    totalQueries++
    lastTenSeconds++
    queriesPerSecond++
    setImmediate(queryLoop)
  } catch (e) {
    console.error(e)
    process.exit(0)
  }
}

let run = (() => {
  console.log('Starting benchmark...')

  const repoConf = {
    storageBackends: {
      blocks: DatastoreLevel
    }
  }

  ipfs = new IPFS({
    repo: new IPFSRepo('./ipfs-log-benchmarks/ipfs', repoConf),
    start: false,
    EXPERIMENTAL: {
      pubsub: true
    }
  })

  ipfs.on('error', (err) => {
    console.error(err)
    process.exit(1)
  })

  ipfs.on('ready', async () => {
    // Use memory store to test without disk IO
    // const memstore = new MemStore()
    // ipfs.object.put = memstore.put.bind(memstore)
    // ipfs.object.get = memstore.get.bind(memstore)

    const testKeysPath = './test/fixtures/keys'
    const keystore = Keystore.create(testKeysPath)
    const identitySignerFn = (id, data) => {
      const key = keystore.getKey(id)
      return keystore.sign(key, data)
    }
    const access = new AccessController()
    const identity = await IdentityProvider.createIdentity(keystore, 'userA', identitySignerFn)
    const identity2 = await IdentityProvider.createIdentity(keystore, 'userB', identitySignerFn)

    log1 = new Log(ipfs, access, identity, 'A')
    log2 = new Log(ipfs, access, identity2, 'A')

    // Output metrics at 1 second interval
    setInterval(() => {
      seconds++
      if (seconds % 10 === 0) {
        console.log(`--> Average of ${lastTenSeconds / 10} q/s in the last 10 seconds`)
        if (lastTenSeconds === 0) throw new Error('Problems!')
        lastTenSeconds = 0
      }
      console.log(`${queriesPerSecond} queries per second, ${totalQueries} queries in ${seconds} seconds. log1: ${log1.length}, log2: ${log2.length}`)
      queriesPerSecond = 0
    }, 1000)

    queryLoop()
  })
})()

module.exports = run
<|endoftext|>


<commit_before>import {modalText, alertsModalConfig} from 'js/config';
import ModalWrapper from 'components/Modals/ModalWrapper';
import {modalActions} from 'actions/ModalActions';
import TextInput from 'components/Forms/TextInput';
import CheckboxInput from 'components/Forms/CheckboxInput';
import {clone} from 'utils/AppUtils';
import GeoHelper from 'helpers/GeoHelper';
import {analysisStore} from 'stores/AnalysisStore';

import React from 'react';
import {Form} from 'formsy-react';
import Deferred from 'dojo/Deferred';
import all from 'dojo/promise/all';
import Graphic from 'esri/graphic';
import xhr from 'dojo/request/xhr';

const alertsText = modalText.alerts;
export default class AlertsModal extends React.Component {

  constructor (props) {
    super(props);
    this.state = {
      textValid: false,
      formaSubscription: false,
      fireSubscription: false,
      validationErrors: {}
    };
  }

  validateText () {
    this.setState({textValid: true});
  }

  invalidateText () {
    this.setState({textValid: false});
  }

  toggleForma () {
    this.setState({formaSubscription: !this.state.formaSubscription});
  }

  togglefire () {
    this.setState({fireSubscription: !this.state.fireSubscription});
  }

  close () {
    modalActions.hideModal(React.findDOMNode(this).parentElement);
  }

  formaSubmit (geoJson, subscriptionName, email) {
    var deferred = new Deferred(),
        url = alertsModalConfig.requests.forma.url,
        options = clone(alertsModalConfig.requests.forma.options),
        data = JSON.stringify({
          topic: options.data.topic,
          email: email,
          geom: '{"type": "' + geoJson.type + '", "coordinates":[' + JSON.stringify(geoJson.geom) + ']}'
        }),
        request = new XMLHttpRequest();

    request.onreadystatechange = function () {
      if (request.readyState === 4) {
        deferred.resolve((JSON.parse(request.response).subscribe) ? alertsText.messages.formaSuccess : alertsText.messages.formaFail);
      }
    };
    request.addEventListener('error', function () {
      deferred.resolve(false);
    }, false);
    request.open(options.method, url, true);
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    request.send(data);

    // Analytics.sendEvent('Subscribe', 'Monthly Clearance Alerts', 'User is subscribing to Monthly Clearance Alerts.');
    return deferred.promise;
  }

  fireSubmit (feature, subscriptionName, email) {
    var deferred = new Deferred(),
        firesConfig = alertsModalConfig.requests.fires,
        url = firesConfig.url,
        options = clone(firesConfig.options);

    options.data.features = JSON.stringify({
      rings: feature.geometry.rings,
      spatialReference: feature.geometry.spatialReference
    });
    options.data.msg_addr = email;
    options.data.area_name = subscriptionName;

    xhr(url, options).then(function (response) {
      deferred.resolve((response.message && response.message === firesConfig.successMessage) ? alertsText.messages.fireSuccess : alertsText.messages.fireFail);
    });

    //Analytics.sendEvent('Subscribe', 'Fire Alerts', 'User is subscribing to Fire Alerts.');
    return deferred.promise;
  }

  submit (model) {
    let subscriptions = [],
        feature = analysisStore.getState().activeWatershed,
        subscriptionName = model['subscription-name'] || 'My Subscription';

    feature = new Graphic(GeoHelper.simplify(feature.geometry));

    if (this.state.formaSubscription === true) {
      subscriptions.push(this.formaSubmit(GeoHelper.convertGeometryToGeometric(feature.geometry), subscriptionName, model.email));
    }
    if (this.state.fireSubscription === true) {
      subscriptions.push(this.fireSubmit(feature, subscriptionName, model.email));
    }

    all(subscriptions).then(function (responses) {
      alert(responses.join('\n'));
    });

    ::this.close();
  }

  render () {
    const subscriptionValid = this.state.formaSubscription === true || this.state.fireSubscription === true;
    return (
      <ModalWrapper>

{alertsText.title}

          <Form onSubmit={::this.submit} onChange={this.validateForm} onValid={::this.validateText} onInvalid={::this.invalidateText}>
            <TextInput name='email' type='text' label={alertsText.descriptions.email} validations='isEmail' validationErrors={{isEmail: 'Invalid address'}} required />

            <TextInput name='subscription-name' type='text' label={alertsText.descriptions.subscription} placeholder='My Subscription' maxLength={50}/>

            {alertsText.descriptions.subscriptionTypes}
            <CheckboxInput label='Monthly Clearance Alerts' className='tree-cover' checked={this.state.formaSubscription} clickHandle={::this.toggleForma} />
            <CheckboxInput label='Fire Alerts' className='active-fires' checked={this.state.fireSubscription} clickHandle={::this.togglefire} />
            {subscriptionValid === true ? null :
Required
}

            <button className='alerts-modal__button--blue' type='submit' disabled={!subscriptionValid || !this.state.textValid}>Subscribe</button>
          </Form>

      </ModalWrapper>
    );
  }

}
// TODO: move static text to config
<commit_msg>added honeypot<commit_after>import {modalText, alertsModalConfig} from 'js/config';
import ModalWrapper from 'components/Modals/ModalWrapper';
import {modalActions} from 'actions/ModalActions';
import TextInput from 'components/Forms/TextInput';
import CheckboxInput from 'components/Forms/CheckboxInput';
import {clone} from 'utils/AppUtils';
import GeoHelper from 'helpers/GeoHelper';
import {analysisStore} from 'stores/AnalysisStore';

import React from 'react';
import {Form} from 'formsy-react';
import Deferred from 'dojo/Deferred';
import all from 'dojo/promise/all';
import Graphic from 'esri/graphic';
import xhr from 'dojo/request/xhr';

const alertsText = modalText.alerts;
export default class AlertsModal extends React.Component {

  constructor (props) {
    super(props);
    this.state = {
      textValid: false,
      formaSubscription: false,
      fireSubscription: false,
      validationErrors: {}
    };
  }

  validateText () {
    this.setState({textValid: true});
  }

  invalidateText () {
    this.setState({textValid: false});
  }

  toggleForma () {
    this.setState({formaSubscription: !this.state.formaSubscription});
  }

  togglefire () {
    this.setState({fireSubscription: !this.state.fireSubscription});
  }

  close () {
    modalActions.hideModal(React.findDOMNode(this).parentElement);
  }

  formaSubmit (geoJson, subscriptionName, email) {
    var deferred = new Deferred(),
        url = alertsModalConfig.requests.forma.url,
        options = clone(alertsModalConfig.requests.forma.options),
        data = JSON.stringify({
          topic: options.data.topic,
          email: email,
          geom: '{"type": "' + geoJson.type + '", "coordinates":[' + JSON.stringify(geoJson.geom) + ']}'
        }),
        request = new XMLHttpRequest();

    request.onreadystatechange = function () {
      if (request.readyState === 4) {
        deferred.resolve((JSON.parse(request.response).subscribe) ? alertsText.messages.formaSuccess : alertsText.messages.formaFail);
      }
    };
    request.addEventListener('error', function () {
      deferred.resolve(false);
    }, false);
    request.open(options.method, url, true);
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    request.send(data);

    // Analytics.sendEvent('Subscribe', 'Monthly Clearance Alerts', 'User is subscribing to Monthly Clearance Alerts.');
    return deferred.promise;
  }

  fireSubmit (feature, subscriptionName, email) {
    var deferred = new Deferred(),
        firesConfig = alertsModalConfig.requests.fires,
        url = firesConfig.url,
        options = clone(firesConfig.options);

    options.data.features = JSON.stringify({
      rings: feature.geometry.rings,
      spatialReference: feature.geometry.spatialReference
    });
    options.data.msg_addr = email;
    options.data.area_name = subscriptionName;

    xhr(url, options).then(function (response) {
      deferred.resolve((response.message && response.message === firesConfig.successMessage) ? alertsText.messages.fireSuccess : alertsText.messages.fireFail);
    });

    //Analytics.sendEvent('Subscribe', 'Fire Alerts', 'User is subscribing to Fire Alerts.');
    return deferred.promise;
  }

  submit (model) {
    let subscriptions = [],
        feature = analysisStore.getState().activeWatershed,
        subscriptionName = model['subscription-name'] || 'My Subscription';

    feature = new Graphic(GeoHelper.simplify(feature.geometry));

    if (this.state.formaSubscription === true) {
      subscriptions.push(this.formaSubmit(GeoHelper.convertGeometryToGeometric(feature.geometry), subscriptionName, model.email));
    }
    if (this.state.fireSubscription === true) {
      subscriptions.push(this.fireSubmit(feature, subscriptionName, model.email));
    }

    all(subscriptions).then(function (responses) {
      alert(responses.join('\n'));
    });

    ::this.close();
  }

  render () {
    const subscriptionValid = this.state.formaSubscription === true || this.state.fireSubscription === true;
    //- Final input with name password is hidden because it is not used, it is used as a honeypot
    return (
      <ModalWrapper>

{alertsText.title}

          <Form onSubmit={::this.submit} onChange={this.validateForm} onValid={::this.validateText} onInvalid={::this.invalidateText}>
            <TextInput name='email' type='text' label={alertsText.descriptions.email} validations='isEmail' validationErrors={{isEmail: 'Invalid address'}} required />

            <TextInput name='subscription-name' type='text' label={alertsText.descriptions.subscription} placeholder='My Subscription' maxLength={50}/>

            {alertsText.descriptions.subscriptionTypes}
            <CheckboxInput label='Monthly Clearance Alerts' className='tree-cover' checked={this.state.formaSubscription} clickHandle={::this.toggleForma} />
            <CheckboxInput label='Fire Alerts' className='active-fires' checked={this.state.fireSubscription} clickHandle={::this.togglefire} />
            {subscriptionValid === true ? null :
Required
}

            <button className='alerts-modal__button--blue' type='submit' disabled={!subscriptionValid || !this.state.textValid}>Subscribe</button>
            <input name='password' type='password' hidden />
          </Form>

      </ModalWrapper>
    );
  }

}
// TODO: move static text to config
<|endoftext|>


<commit_before>export default function (babel) {
    return {
        visitor: {
            CallExpression(path) {
                if (path.get("callee").matchesPattern("this.lineLog") ||
                    (babel.types.isIdentifier(path.node.callee) && path.node.callee.name === "timeLog") ||
                    (babel.types.isIdentifier(path.node.callee) && path.node.callee.name === "timeLogStart")) {
                    path.remove();
                }
            }
        }
    };
}
<commit_msg>Delete babel plugin to strip logging calls<commit_after><|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import {Grid, Row, Col, FormControl, FormGroup, ControlLabel, Button} from 'react-bootstrap'
import {Link} from 'react-router'
import moment from 'moment'

import Fieldset from 'components/Fieldset'
import Messages from 'components/Messages'
import HopscotchPage from 'components/HopscotchPage'
import HopscotchLauncher from 'components/HopscotchLauncher'
import Breadcrumbs from 'components/Breadcrumbs'
import SavedSearchTable from 'components/SavedSearchTable'
import NoPositionWarning from 'components/NoPositionWarning'

import API from 'api'
import autobind from 'autobind-decorator'

export default class Home extends HopscotchPage {
	static contextTypes = {
		app: PropTypes.object.isRequired,
	}

	constructor(props) {
		super(props)
		this.state = {
			tileCounts: [],
			savedSearches: [],
			selectedSearch: null,
			showGettingStartedPanel: window.localStorage.showGettingStartedPanel
		}
	}

	adminQueries(currentUser) {
		return [ this.allDraft(), this.allPending(), this.pendingMe(currentUser), this.allUpcoming() ]
	}

	approverQueries(currentUser) {
		return [ this.pendingMe(currentUser), this.myDraft(currentUser), this.myOrgRecent(currentUser), this.myOrgFuture(currentUser) ]
	}

	advisorQueries(currentUser) {
		return [ this.myDraft(currentUser), this.myPending(currentUser), this.myOrgRecent(currentUser), this.myOrgFuture(currentUser) ]
	}

	allDraft() { return {
		title: "All draft reports",
		query: { state: ["DRAFT"] }
	}}

	myDraft(currentUser) {
		return {
			title: "My draft reports",
			query: { state: ["DRAFT"], authorId: currentUser.id }
		}
	}

	myPending(currentUser) {
		return {
			title: "My reports pending approval",
			query: { authorId: currentUser.id, state: ["PENDING_APPROVAL"]}
		}
	}

	pendingMe(currentUser) {
		return {
			title: "Reports pending my approval",
			query: { pendingApprovalOf: currentUser.id }
		}
	}

	allPending() {
		return {
			title: "All reports pending approval",
			query: { state: ["PENDING_APPROVAL"] }
		}
	}

	myOrgRecent(currentUser) {
		if (!currentUser.position || !currentUser.position.organization) { return { query: {}} }
		let lastWeek = moment().subtract(7, 'days').startOf('day').valueOf()
		return {
			title: currentUser.position.organization.shortName + "'s reports in the last 7 days",
			query: {
				authorOrgId: currentUser.position.organization.id,
				createdAtStart: lastWeek,
				state: ["RELEASED", "CANCELLED", "PENDING_APPROVAL"]
			}
		}
	}

	myOrgFuture(currentUser) {
		if (!currentUser.position || !currentUser.position.organization) { return { query: {}} }
		let start = moment().endOf('day').valueOf()
		return {
			title: currentUser.position.organization.shortName + "'s upcoming engagements",
			query: {
				authorOrgId: currentUser.position.organization.id,
				engagementDateStart: start
			}
		}
	}

	allUpcoming() {
		return {
			title: "All upcoming engagements",
			query: { engagementDateStart: moment().endOf('day').valueOf() }
		}
	}

	getQueriesForUser() {
		let user = this.context.app.state.currentUser
		if (user.isAdmin()) {
			return this.adminQueries(user)
		} else if (user.position && user.position.isApprover) {
			return this.approverQueries(user)
		} else {
			return this.advisorQueries(user)
		}
	}

	fetchData() {
		//If we don't have the currentUser yet (ie page is still loading, don't run these queries)
		let currentUser = this.context.app.state.currentUser
		if (!currentUser || !currentUser._loaded) { return }

		//queries will contain the four queries that will show up on the home tiles
		//Based on the users role. They are all report searches
		let queries = this.getQueriesForUser()
		//Run those four queries
		let graphQL = /* GraphQL */`
			tileOne: reportList(f:search, query:$queryOne) { totalCount},
			tileTwo: reportList(f:search, query: $queryTwo) { totalCount},
			tileThree: reportList(f:search, query: $queryThree) { totalCount },
			tileFour: reportList(f:search, query: $queryFour) { totalCount },
			savedSearches: savedSearchs(f:mine) {id, name, objectType, query}`
		let variables = {
			queryOne: queries[0].query,
			queryTwo: queries[1].query,
			queryThree: queries[2].query,
			queryFour: queries[3].query
		}

		API.query(graphQL, variables,
			"($queryOne: ReportSearchQuery, $queryTwo: ReportSearchQuery, $queryThree: ReportSearchQuery, $queryFour: ReportSearchQuery)")
		.then(data => {
			let selectedSearch = data.savedSearches && data.savedSearches.length > 0 ? data.savedSearches[0] : null
			this.setState({
				tileCounts: [data.tileOne.totalCount, data.tileTwo.totalCount, data.tileThree.totalCount, data.tileFour.totalCount],
				savedSearches: data.savedSearches,
				selectedSearch: selectedSearch
			})
		})
	}

	render() {
		let queries = this.getQueriesForUser()

		return (

				<Breadcrumbs />
				<Messages error={this.state.error} success={this.state.success} />

				<NoPositionWarning
					position={this.context.app.state.currentUser && this.context.app.state.currentUser.position} />

				{this.state.showGettingStartedPanel === 'true' &&
					<Fieldset title="Getting started" className="home-tile-row">
						<Grid fluid className="getting-started-grid">
							Close ✕
							<Row>

Welcome to ANET!

							</Row>
							<Row>
								<Col xs={12}>

Get started with a self-guided tour.

								</Col>
							</Row>
							<Row>
								<Col xs={12}>
									<Button bsStyle="primary" onClick={this.startWelcomeTour}>Take the tour</Button>
								</Col>
							</Row>
						</Grid>
					</Fieldset>
				}

				<Fieldset className="home-tile-row" title="My ANET snapshot" action={
					this.state.showGettingStartedPanel !== 'true' && <HopscotchLauncher onClick={this.startWelcomeTour} />
				}>

					<Grid fluid>
						<Row>
							{queries.map((query, index) =>{
								query.query.type = "reports"
									return <Link to={{pathname: '/search', query: query.query, }} className="col-md-3 home-tile" key={index}>

{this.state.tileCounts[index]}

										{query.title}
									</Link>
							})}
						</Row>
					</Grid>
				</Fieldset>

				<Fieldset title="Saved searches">
					<FormGroup controlId="savedSearchSelect">
						<ControlLabel>Select a saved search</ControlLabel>
						<FormControl componentClass="select" onChange={this.onSaveSearchSelect}>
							{this.state.savedSearches && this.state.savedSearches.map( savedSearch =>
								<option value={savedSearch.id} key={savedSearch.id}>{savedSearch.name}</option>
							)}
						</FormControl>
					</FormGroup>

					{this.state.selectedSearch &&

								<Button bsStyle="danger" bsSize="small" onClick={this.deleteSearch} >
									Delete Search
								</Button>

							<SavedSearchTable search={this.state.selectedSearch} />

					}
				</Fieldset>

		)
	}

	@autobind
	onSaveSearchSelect(event) {
		let id = event && event.target ? event.target.value : event
		let search = this.state.savedSearches.find(el => Number(el.id) === Number(id))
		this.setState({selectedSearch: search})
	}

	@autobind
	deleteSearch() {
		let search = this.state.selectedSearch
		let index = this.state.savedSearches.findIndex(s => s.id === search.id)
		if (confirm("Are you sure you want to delete '" + search.name + "'?")) {
			API.send(`/api/savedSearches/${search.id}`, {}, {method: 'DELETE'})
				.then(data => {
					let savedSearches = this.state.savedSearches
					savedSearches.splice(index, 1)
					let nextSelect = savedSearches.length > 0 ? savedSearches[0] : null
					this.setState({ savedSearches: savedSearches, selectedSearch : nextSelect })
				}, data => {
					this.setState({success:null, error: data})
				})
		}
	}

	@autobind
	onDismissGettingStarted() {
		window.localStorage.showGettingStartedPanel = 'false'
		this.setState({showGettingStartedPanel: 'false'})
	}

	@autobind
	startWelcomeTour() {
		this.hopscotch.endTour()
		this.hopscotch.startTour(this.hopscotchTour)
	}
}
<commit_msg>Fix HopscotchLauncher on Home<commit_after>import React, {PropTypes} from 'react'
import {Grid, Row, Col, FormControl, FormGroup, ControlLabel, Button} from 'react-bootstrap'
import {Link} from 'react-router'
import moment from 'moment'

import Fieldset from 'components/Fieldset'
import Messages from 'components/Messages'
import HopscotchPage from 'components/HopscotchPage'
import HopscotchLauncher from 'components/HopscotchLauncher'
import Breadcrumbs from 'components/Breadcrumbs'
import SavedSearchTable from 'components/SavedSearchTable'
import NoPositionWarning from 'components/NoPositionWarning'

import API from 'api'
import autobind from 'autobind-decorator'

export default class Home extends HopscotchPage {
	static contextTypes = {
		app: PropTypes.object.isRequired,
	}

	constructor(props) {
		super(props)
		this.state = {
			tileCounts: [],
			savedSearches: [],
			selectedSearch: null,
			showGettingStartedPanel: window.localStorage.showGettingStartedPanel
		}
	}

	adminQueries(currentUser) {
		return [ this.allDraft(), this.allPending(), this.pendingMe(currentUser), this.allUpcoming() ]
	}

	approverQueries(currentUser) {
		return [ this.pendingMe(currentUser), this.myDraft(currentUser), this.myOrgRecent(currentUser), this.myOrgFuture(currentUser) ]
	}

	advisorQueries(currentUser) {
		return [ this.myDraft(currentUser), this.myPending(currentUser), this.myOrgRecent(currentUser), this.myOrgFuture(currentUser) ]
	}

	allDraft() { return {
		title: "All draft reports",
		query: { state: ["DRAFT"] }
	}}

	myDraft(currentUser) {
		return {
			title: "My draft reports",
			query: { state: ["DRAFT"], authorId: currentUser.id }
		}
	}

	myPending(currentUser) {
		return {
			title: "My reports pending approval",
			query: { authorId: currentUser.id, state: ["PENDING_APPROVAL"]}
		}
	}

	pendingMe(currentUser) {
		return {
			title: "Reports pending my approval",
			query: { pendingApprovalOf: currentUser.id }
		}
	}

	allPending() {
		return {
			title: "All reports pending approval",
			query: { state: ["PENDING_APPROVAL"] }
		}
	}

	myOrgRecent(currentUser) {
		if (!currentUser.position || !currentUser.position.organization) { return { query: {}} }
		let lastWeek = moment().subtract(7, 'days').startOf('day').valueOf()
		return {
			title: currentUser.position.organization.shortName + "'s reports in the last 7 days",
			query: {
				authorOrgId: currentUser.position.organization.id,
				createdAtStart: lastWeek,
				state: ["RELEASED", "CANCELLED", "PENDING_APPROVAL"]
			}
		}
	}

	myOrgFuture(currentUser) {
		if (!currentUser.position || !currentUser.position.organization) { return { query: {}} }
		let start = moment().endOf('day').valueOf()
		return {
			title: currentUser.position.organization.shortName + "'s upcoming engagements",
			query: {
				authorOrgId: currentUser.position.organization.id,
				engagementDateStart: start
			}
		}
	}

	allUpcoming() {
		return {
			title: "All upcoming engagements",
			query: { engagementDateStart: moment().endOf('day').valueOf() }
		}
	}

	getQueriesForUser() {
		let user = this.context.app.state.currentUser
		if (user.isAdmin()) {
			return this.adminQueries(user)
		} else if (user.position && user.position.isApprover) {
			return this.approverQueries(user)
		} else {
			return this.advisorQueries(user)
		}
	}

	fetchData() {
		//If we don't have the currentUser yet (ie page is still loading, don't run these queries)
		let currentUser = this.context.app.state.currentUser
		if (!currentUser || !currentUser._loaded) { return }

		//queries will contain the four queries that will show up on the home tiles
		//Based on the users role. They are all report searches
		let queries = this.getQueriesForUser()
		//Run those four queries
		let graphQL = /* GraphQL */`
			tileOne: reportList(f:search, query:$queryOne) { totalCount},
			tileTwo: reportList(f:search, query: $queryTwo) { totalCount},
			tileThree: reportList(f:search, query: $queryThree) { totalCount },
			tileFour: reportList(f:search, query: $queryFour) { totalCount },
			savedSearches: savedSearchs(f:mine) {id, name, objectType, query}`
		let variables = {
			queryOne: queries[0].query,
			queryTwo: queries[1].query,
			queryThree: queries[2].query,
			queryFour: queries[3].query
		}

		API.query(graphQL, variables,
			"($queryOne: ReportSearchQuery, $queryTwo: ReportSearchQuery, $queryThree: ReportSearchQuery, $queryFour: ReportSearchQuery)")
		.then(data => {
			let selectedSearch = data.savedSearches && data.savedSearches.length > 0 ? data.savedSearches[0] : null
			this.setState({
				tileCounts: [data.tileOne.totalCount, data.tileTwo.totalCount, data.tileThree.totalCount, data.tileFour.totalCount],
				savedSearches: data.savedSearches,
				selectedSearch: selectedSearch
			})
		})
	}

	render() {
		let queries = this.getQueriesForUser()

		return (

				{this.state.showGettingStartedPanel !== 'true' &&

					<HopscotchLauncher onClick={this.startWelcomeTour} />

}

				<Breadcrumbs />
				<Messages error={this.state.error} success={this.state.success} />

				<NoPositionWarning
					position={this.context.app.state.currentUser && this.context.app.state.currentUser.position} />

				{this.state.showGettingStartedPanel === 'true' &&
					<Fieldset title="Getting started" className="home-tile-row">
						<Grid fluid className="getting-started-grid">
							Close ✕
							<Row>

Welcome to ANET!

							</Row>
							<Row>
								<Col xs={12}>

Get started with a self-guided tour.

								</Col>
							</Row>
							<Row>
								<Col xs={12}>
									<Button bsStyle="primary" onClick={this.startWelcomeTour}>Take the tour</Button>
								</Col>
							</Row>
						</Grid>
					</Fieldset>
				}

				<Fieldset className="home-tile-row" title="My ANET snapshot">

					<Grid fluid>
						<Row>
							{queries.map((query, index) =>{
								query.query.type = "reports"
									return <Link to={{pathname: '/search', query: query.query, }} className="col-md-3 home-tile" key={index}>

{this.state.tileCounts[index]}

										{query.title}
									</Link>
							})}
						</Row>
					</Grid>
				</Fieldset>

				<Fieldset title="Saved searches">
					<FormGroup controlId="savedSearchSelect">
						<ControlLabel>Select a saved search</ControlLabel>
						<FormControl componentClass="select" onChange={this.onSaveSearchSelect}>
							{this.state.savedSearches && this.state.savedSearches.map( savedSearch =>
								<option value={savedSearch.id} key={savedSearch.id}>{savedSearch.name}</option>
							)}
						</FormControl>
					</FormGroup>

					{this.state.selectedSearch &&

								<Button bsStyle="danger" bsSize="small" onClick={this.deleteSearch} >
									Delete Search
								</Button>

							<SavedSearchTable search={this.state.selectedSearch} />

					}
				</Fieldset>

		)
	}

	@autobind
	onSaveSearchSelect(event) {
		let id = event && event.target ? event.target.value : event
		let search = this.state.savedSearches.find(el => Number(el.id) === Number(id))
		this.setState({selectedSearch: search})
	}

	@autobind
	deleteSearch() {
		let search = this.state.selectedSearch
		let index = this.state.savedSearches.findIndex(s => s.id === search.id)
		if (confirm("Are you sure you want to delete '" + search.name + "'?")) {
			API.send(`/api/savedSearches/${search.id}`, {}, {method: 'DELETE'})
				.then(data => {
					let savedSearches = this.state.savedSearches
					savedSearches.splice(index, 1)
					let nextSelect = savedSearches.length > 0 ? savedSearches[0] : null
					this.setState({ savedSearches: savedSearches, selectedSearch : nextSelect })
				}, data => {
					this.setState({success:null, error: data})
				})
		}
	}

	@autobind
	onDismissGettingStarted() {
		window.localStorage.showGettingStartedPanel = 'false'
		this.setState({showGettingStartedPanel: 'false'})
	}

	@autobind
	startWelcomeTour() {
		this.hopscotch.endTour()
		this.hopscotch.startTour(this.hopscotchTour)
	}
}
<|endoftext|>


<commit_before>"use strict";

//Load dependencies
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var characterModel = process.require("characters/characterModel.js");
var guildModel = process.require("guilds/guildModel.js");
var wowProgressAPI = process.require("core/api/wowProgress.js");

/**
 * CleanerProcess constructor
 * @param autoStop
 * @constructor
 */
function CleanerProcess(autoStop) {
    this.autoStop = autoStop;
}

/**
 * Clean Ads
 */
CleanerProcess.prototype.cleanAds = function () {
    var logger = applicationStorage.logger;
    var self = this;
    async.parallel([
            function (callback) {
                //Disable lfg for old character ads
                logger.info("Set LFG to false for old character ads");
                characterModel.disableLfgForOldAds(function (error) {
                    if (error) {
                        logger.error(error.message);
                    }
                    callback();
                })
            },
            function (callback) {
                //Disable lfg for old guild ads
                logger.info("Set LFG to false for old guild ads");
                guildModel.disableLfgForOldAds(function (error) {
                    if (error) {
                        logger.error(error.message);
                    }
                    callback();
                })
            },
            function (callback) {
                //Refresh all wowprogress guildAds
                async.waterfall([
                    function (callback) {
                        guildModel.find(
                            {
                                "ad.lfg": true, id: {$exists:false}
                            }, {region: 1, realm: 1, name: 1}, {"ad.updated": 1}, function (error, guilds) {
                                callback(error, guilds);
                            });
                    },
                    function (guilds, callback) {
                        async.each(guilds, function (guild, callback) {
                            logger.info("Checking for wowprogress Guild Ad update %s-%s-%s", guild.region, guild.realm, guild.name);

                            wowProgressAPI.parseGuild(guild.region, guild.realm, guild.name, function (error, ad) {
                                if (error) {
                                    logger.error(error.message);
                                    callback();
                                }
                                else if (ad && ad.lfg == false) {
                                    logger.info("Set LFG to false for wowprogress Guild Ad %s-%s-%s", guild.region, guild.realm, guild.name);
                                    guildModel.upsert(guild.region, guild.realm, guild.name, {"ad": ad}, function (error) {
                                        if (error) {
                                            logger.error(error.message);
                                        }
                                        callback();
                                    });
                                }
                                else {
                                    callback();
                                }
                            });
                        }, function () {
                            callback();
                        });
                    }
                ], function (error) {
                    if (error) {
                        logger.error(error.message);
                    }
                    callback();
                });
            },
            function (callback) {
                //Refresh all wowprogress characterAds
                async.waterfall([
                    function (callback) {
                        characterModel.find(
                            {
                                "ad.lfg": true, id: {$exists:false}
                            }, {region: 1, realm: 1, name: 1}, {"ad.updated": 1}, function (error, characters) {
                                callback(error, characters);

                            });
                    },
                    function (characters, callback) {
                        async.each(characters, function (character, callback) {
                            logger.info("Checking wowprogress Character Ad update %s-%s-%s", character.region, character.realm, character.name);
                            wowProgressAPI.parseCharacter(character.region, character.realm, character.name, function (error, ad) {
                                if (error) {
                                    logger.error(error.message);
                                    callback();
                                }
                                else if (ad && ad.lfg == false) {
                                    logger.info("Set LFG to false for wowprogress Character Ad %s-%s-%s", character.region, character.realm, character.name);
                                    characterModel.upsert(character.region, character.realm, character.name, {"ad": ad}, function (error) {
                                        if (error) {
                                            logger.error(error.message);
                                        }
                                        callback();
                                    });
                                }
                                else {
                                    callback();
                                }
                            });
                        }, function () {
                            callback();
                        });
                    }
                ], function (error) {
                    if (error) {
                        logger.error(error.message);
                    }
                    callback();
                });
            }
        ],
        function () {
            if (self.autoStop) {
                process.exit();
            }
        }
    )
    ;

}
;

/**
 * Start the CleanerProcess
 * @param callback
 */
CleanerProcess.prototype.start = function (callback) {
    applicationStorage.logger.info("Starting CleanerProcess");
    this.cleanAds();
    callback();

};

module.exports = CleanerProcess;<commit_msg>Add wowProgress lfg update<commit_after>"use strict";

//Load dependencies
var async = require("async");
var applicationStorage = process.require("core/applicationStorage.js");
var characterModel = process.require("characters/characterModel.js");
var guildModel = process.require("guilds/guildModel.js");
var wowProgressAPI = process.require("core/api/wowProgress.js");

/**
 * CleanerProcess constructor
 * @param autoStop
 * @constructor
 */
function CleanerProcess(autoStop) {
    this.autoStop = autoStop;
}

/**
 * Clean Ads
 */
CleanerProcess.prototype.cleanAds = function () {
    var logger = applicationStorage.logger;
    var self = this;
    async.series([
            function (callback) {
                //Disable lfg for old character ads
                logger.info("Set LFG to false for old character ads");
                characterModel.disableLfgForOldAds(function (error) {
                    if (error) {
                        logger.error(error.message);
                    }
                    callback();
                })
            },
            function (callback) {
                //Disable lfg for old guild ads
                logger.info("Set LFG to false for old guild ads");
                guildModel.disableLfgForOldAds(function (error) {
                    if (error) {
                        logger.error(error.message);
                    }
                    callback();
                })
            },
            function (callback) {
                //Refresh all wowprogress guildAds
                async.waterfall([
                    function (callback) {
                        guildModel.find(
                            {
                                "ad.lfg": true, id: {$exists:false}
                            }, {region: 1, realm: 1, name: 1}, {"ad.updated": 1}, function (error, guilds) {
                                callback(error, guilds);
                            });
                    },
                    function (guilds, callback) {
                        async.forEachSeries(guilds, function (guild, callback) {
                            logger.info("Checking for wowprogress Guild Ad update %s-%s-%s", guild.region, guild.realm, guild.name);

                            wowProgressAPI.parseGuild(guild.region, guild.realm, guild.name, function (error, ad) {
                                if (error) {
                                    logger.error(error.message);
                                    callback();
                                }
                                else if (ad && ad.lfg == false) {
                                    logger.info("Set LFG to false for wowprogress Guild Ad %s-%s-%s", guild.region, guild.realm, guild.name);
                                    guildModel.upsert(guild.region, guild.realm, guild.name, {"ad": ad}, function (error) {
                                        if (error) {
                                            logger.error(error.message);
                                        }
                                        callback();
                                    });
                                }
                                else {
                                    callback();
                                }
                            });
                        }, function () {
                            callback();
                        });
                    }
                ], function (error) {
                    if (error) {
                        logger.error(error.message);
                    }
                    callback();
                });
            },
            function (callback) {
                //Refresh all wowprogress characterAds
                async.waterfall([
                    function (callback) {
                        characterModel.find(
                            {
                                "ad.lfg": true, id: {$exists:false}
                            }, {region: 1, realm: 1, name: 1}, {"ad.updated": 1}, function (error, characters) {
                                callback(error, characters);

                            });
                    },
                    function (characters, callback) {
                        async.forEachSeries(characters, function (character, callback) {
                            logger.info("Checking wowprogress Character Ad update %s-%s-%s", character.region, character.realm, character.name);
                            wowProgressAPI.parseCharacter(character.region, character.realm, character.name, function (error, ad) {
                                if (error) {
                                    logger.error(error.message);
                                    callback();
                                }
                                else if (ad && ad.lfg == false) {
                                    logger.info("Set LFG to false for wowprogress Character Ad %s-%s-%s", character.region, character.realm, character.name);
                                    characterModel.upsert(character.region, character.realm, character.name, {"ad": ad}, function (error) {
                                        if (error) {
                                            logger.error(error.message);
                                        }
                                        callback();
                                    });
                                }
                                else {
                                    callback();
                                }
                            });
                        }, function () {
                            callback();
                        });
                    }
                ], function (error) {
                    if (error) {
                        logger.error(error.message);
                    }
                    callback();
                });
            }
        ],
        function () {
            if (self.autoStop) {
                process.exit();
            }
        }
    )
    ;

}
;

/**
 * Start the CleanerProcess
 * @param callback
 */
CleanerProcess.prototype.start = function (callback) {
    applicationStorage.logger.info("Starting CleanerProcess");
    this.cleanAds();
    callback();

};

module.exports = CleanerProcess;<|endoftext|>


<commit_before>/*jshint esversion: 6 */
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as actionCreators from './actions/actionCreators';

function mapStateToProps(state) {
  return {
    notes: state.notes
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

const Connection = function (view){
  return connect(mapStateToProps, mapDispatchToProps)(view);
};

export default Connection;<commit_msg>Update Connection.js<commit_after>/*jshint esversion: 6 */
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as actionCreators from './actions/actionCreators';

function mapStateToProps(state) {
  return {
    notes: state.notes
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

const Connection = (view)=> connect(mapStateToProps, mapDispatchToProps)(view);

export default Connection;
<|endoftext|>


<commit_before>/**
 * Created by esanchez on 24/04/2017.
 */
Ext.define('M5.view.main.PanelM5', {
    extend: 'Ext.panel.Panel',
    xtype: 'panelm5',
    layout: {
        type: 'vbox',
        align: 'stretch'
    },
    defaults: {
        flex: 1,
        margin: 10
    },

    bodyCls: "redcolor",
    items: [{
        title: 'Formulario',

        tbar: [{
            text: "Guardar",
            handler: function (btn) {
                var values = btn.up('form').getValues();
                btn.up('form').reset();
                var grid = btn.up('panel').up().down('grid');
                grid.getStore().add(values);
            }
        }, {
            text: "Cancelar",
            handler: function (btn) {
                btn.up('form').reset();
            }
        }],
        border: true,
        bodyPadding: 10,
        xtype: 'form',
        defaultType: 'textfield',
        items: [{
            fieldLabel: 'First Name',
            name: 'first',
            allowBlank: false
        }, {
            fieldLabel: 'Last Name',
            name: 'last',
            allowBlank: false
        }, {
            name: 'email',
            fieldLabel: 'Email Address',
            vtype: 'email'  // requires value to be a valid email address format
        }, {
            anchor: '100%',
            name: 'phone',
            fieldLabel: 'Phone'
        }]

    }, {
        title: 'Panel',
        xtype: 'panel',
        border: true,
        refenrence: 'griduser',
        items: [{
            xtype: 'grid',
            store: new Ext.data.Store({
                autoLoad: true,
                storeId: 'usuarios',
                fields: [
                    { name: 'first', type: 'string' },
                    { name: 'last', type: 'string' },
                    { name: 'email', type: 'string' },
                    { name: 'phone', type: 'string' }

                ],
                proxy: {
                    type: 'ajax',
                    url: 'http://localhost:3000/user/current',
                    actionMethods: {
                        create: 'POST',
                        read: 'POST',
                        update: 'POST',
                        destroy: 'POST'
                    },
                    paramsAsJson: true,
                    reader: {
                        type: 'json',
                        rootProperty: 'data'
                    }
                }
            }),
            columns: [
                {text: 'First Name', dataIndex: 'first'},
                {text: 'Last Name', dataIndex: 'last'},
                {text: 'Email', dataIndex: 'email', flex: 1},
                {text: 'Phone', dataIndex: 'phone'}
            ],
            listeners: {
                cellclick: function (grid, td, cellIndex, record, tr, rowIndex) {
                    var form = grid.up().up().up().down("form");
                    form.getForm().setValues(record.getData());
                }
            }
        }]
    }]
});<commit_msg>add updates<commit_after>/**
 * Created by esanchez on 24/04/2017.
 */
Ext.define('M5.view.main.PanelM5', {
    extend: 'Ext.panel.Panel',
    xtype: 'panelm5',
    layout: {
        type: 'vbox',
        align: 'stretch'
    },
    defaults: {
        flex: 1,
        margin: 10
    },

    bodyCls: "redcolor",
    items: [{
        title: 'Formulario',

        tbar: [{
            text: "Guardar",
            handler: function (btn) {
                var form = btn.up('form');
                btn.up('form').reset();
                var grid = btn.up('panel').up().down('grid');
                if (form.isSelection) {
                    form.isSelection = false;
                    var record = grid.getStore().getAt(form.currentSelection);
                    Ext.Object.each(from.getValues(), function(key, value) {
                        record.set(key, value);
                    });
                    record.commit();
                    //record.beginEdit();
                    //endEdit ( [silent] , [modifiedFieldNames] )
                    //record.endEdit();
                } else {
                    grid.getStore().add(form.getValues());
                }
            }
        }, {
            text: "Cancelar",
            handler: function (btn) {
                btn.up('form').reset();
            }
        }],
        border: true,
        bodyPadding: 10,
        xtype: 'form',
        defaultType: 'textfield',
        items: [{
            fieldLabel: 'First Name',
            name: 'first',
            allowBlank: false
        }, {
            fieldLabel: 'Last Name',
            name: 'last',
            allowBlank: false
        }, {
            name: 'email',
            fieldLabel: 'Email Address',
            vtype: 'email'  // requires value to be a valid email address format
        }, {
            anchor: '100%',
            name: 'phone',
            fieldLabel: 'Phone'
        }]

    }, {
        title: 'Panel',
        xtype: 'panel',
        border: true,
        refenrence: 'griduser',
        items: [{
            xtype: 'grid',
            store: new Ext.data.Store({
                autoLoad: true,
                storeId: 'usuarios',
                fields: [
                    { name: 'first', type: 'string' },
                    { name: 'last', type: 'string' },
                    { name: 'email', type: 'string' },
                    { name: 'phone', type: 'string' }

                ],
                proxy: {
                    type: 'ajax',
                    url: 'http://localhost:3000/user/current',
                    actionMethods: {
                        create: 'POST',
                        read: 'POST',
                        update: 'POST',
                        destroy: 'POST'
                    },
                    paramsAsJson: true,
                    reader: {
                        type: 'json',
                        rootProperty: 'data'
                    }
                }
            }),
            columns: [
                {text: 'First Name', dataIndex: 'first'},
                {text: 'Last Name', dataIndex: 'last'},
                {text: 'Email', dataIndex: 'email', flex: 1},
                {text: 'Phone', dataIndex: 'phone'}
            ],
            listeners: {
                cellclick: function (grid, td, cellIndex, record, tr, rowIndex) {
                    var form = grid.up().up().up().down("form");
                    form.isSelection = true;
                    form.currentSelection = rowIndex;
                    form.getForm().setValues(record.getData());
                }
            }
        }]
    }]
});
<|endoftext|>


<commit_before>import { isWithinInterval } from 'date-fns';

import { BLACK_FRIDAY } from '../constants';

export const isBlackFridayPeriod = () => {
    return isWithinInterval(new Date(), { start: BLACK_FRIDAY.START, end: BLACK_FRIDAY.END });
};
<commit_msg>Hotfix date for BF<commit_after>import { isWithinInterval } from 'date-fns';

import { BLACK_FRIDAY } from '../constants';

export const isBlackFridayPeriod = () => {
    return isWithinInterval(new Date(), { start: new Date(BLACK_FRIDAY.START), end: new Date(BLACK_FRIDAY.END) });
};
<|endoftext|>


<commit_before>var _ = require('lodash')
var Device = require('./Device')

module.exports =  _.merge(_.cloneDeep(Device), {
  attributes: {
    getStatus: function () {
      this.insteonClient().level()
      .then((result) => {
        if (result !== undefined && result !== null && result !== '') {
          var level = parseInt(result)
          var status = (level === 0 ? 'off' : 'on')
          console.log(`[${this.insteonId}] Dimmer is ${status.toUpperCase()}`)
          this.sendSmartThingsUpdate({ command: 'get_status', status: status, level: level })
        } else {
          console.log(`Unable to get status for dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error getting status for dimmer ${this.insteonId}`)
      })
    },

    turnOn: function () {
      this.insteonClient().turnOn()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'turn_on', status: 'on', level: '100' })
        } else {
          console.log(`Unable to turn on dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error turning on dimmer ${this.insteonId}`)
      })
    },

    turnOff: function () {
      this.insteonClient().turnOff()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'turn_off', status: 'off', level: 0 })
        } else {
          console.log(`Unable to turn off dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error turning off dimmer ${this.insteonId}`)
      })
    },

    setLevel: function (level) {
      this.insteonClient().level(level)
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          var status = level === 0 ? 'off' : 'on'
          this.sendSmartThingsUpdate({ command: 'set_level', status: status, level: level })
        } else {
          console.log(`Unable to set level for dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error setting level for dimmer ${this.insteonId}`)
      })
    },

    brighten: function () {
      this.insteonClient().brighten()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'brighten' })
        } else {
          console.log(`Unable to brighten dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error brightening dimmer ${this.insteonId}`)
      })
    },

    dim: function () {
      this.insteonClient().dim()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
        } else {
          console.log(`Unable to lower dimmer ${this.insteonId}`)
          this.sendSmartThingsUpdate({ command: 'dim' })
        }
      }, reason => {
        console.log(`Error lowering dimmer ${this.insteonId}`)
      })
    },

    subscribeEvents: function () {
      console.log(`[${this.insteonId}] Subscribing to dimmer events...`)
      var light = this.insteonClient()

      light.on('turnOn', (group, level) => {
        console.log(`[${this.insteonId}] Dimmer turned ON`)
        this.sendSmartThingsUpdate({ event: 'turn_on', status: 'on', level: level })
      })

      light.on('turnOnFast', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned ON FAST`)
        this.sendSmartThingsUpdate({ event: 'turn_on_fast', status: 'on', level: 100 })
      })

      light.on('turnOff', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned OFF`)
        this.sendSmartThingsUpdate({ event: 'turn_off', status: 'off', level: 0 })
      })

      light.on('turnOffFast', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned OFF FAST`)
        this.sendSmartThingsUpdate({ event: 'turn_off_fast', status: 'off', level: 0 })
      })

      light.on('brightening', (group) => {
        console.log(`[${this.insteonId}] Dimmer brightening`)
        this.sendSmartThingsUpdate({ event: 'brightening' })
      })

      light.on('brightened', (group) => {
        console.log(`[${this.insteonId}] Dimmer brightened`)
        this.sendSmartThingsUpdate({ event: 'brightened' })
      })

      light.on('dimming', (group) => {
        console.log(`[${this.insteonId}] Dimmer dimming`)
        this.sendSmartThingsUpdate({ event: 'dimming' })
      })

      light.on('dimmed', (group) => {
        console.log(`[${this.insteonId}] Dimmer dimmed`)
        this.sendSmartThingsUpdate({ event: 'dimmed' })
      })

      console.log(`[${this.insteonId}] Subscribed to dimmer events`)
    },

    startPolling: function () {
      this.getStatus()
      setInterval(() => {
        this.getStatus()
      }, this.refreshSeconds * 1000)
    }
  },

  beforeValidate: function (attrs, cb) {
    attrs.type = 'dimmer'
    cb()
  }
})
<commit_msg>Added new status checks for dimmers<commit_after>var _ = require('lodash')
var Device = require('./Device')

module.exports =  _.merge(_.cloneDeep(Device), {
  attributes: {
    getStatus: function () {
      this.insteonClient().level()
      .then((result) => {
        if (result !== undefined && result !== null && result !== '') {
          var level = parseInt(result)
          var status = (level === 0 ? 'off' : 'on')
          console.log(`[${this.insteonId}] Dimmer is ${status.toUpperCase()}`)
          this.sendSmartThingsUpdate({ command: 'get_status', status: status, level: level })
        } else {
          console.log(`Unable to get status for dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error getting status for dimmer ${this.insteonId}`)
      })
    },

    turnOn: function () {
      this.insteonClient().turnOn()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'turn_on', status: 'on', level: '100' })
        } else {
          console.log(`Unable to turn on dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error turning on dimmer ${this.insteonId}`)
      })
    },

    turnOff: function () {
      this.insteonClient().turnOff()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'turn_off', status: 'off', level: 0 })
        } else {
          console.log(`Unable to turn off dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error turning off dimmer ${this.insteonId}`)
      })
    },

    setLevel: function (level) {
      this.insteonClient().level(level)
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          var status = level === 0 ? 'off' : 'on'
          this.sendSmartThingsUpdate({ command: 'set_level', status: status, level: level })
        } else {
          console.log(`Unable to set level for dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error setting level for dimmer ${this.insteonId}`)
      })
    },

    brighten: function () {
      this.insteonClient().brighten()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
          this.sendSmartThingsUpdate({ command: 'brighten' })
        } else {
          console.log(`Unable to brighten dimmer ${this.insteonId}`)
        }
      }, reason => {
        console.log(`Error brightening dimmer ${this.insteonId}`)
      })
    },

    dim: function () {
      this.insteonClient().dim()
      .then((result) => {
        if (result.response) {
          console.log(`[${this.insteonId}] Insteon response: ${JSON.stringify(result.response)}`)
        } else {
          console.log(`Unable to lower dimmer ${this.insteonId}`)
          this.sendSmartThingsUpdate({ command: 'dim' })
        }
      }, reason => {
        console.log(`Error lowering dimmer ${this.insteonId}`)
      })
    },

    subscribeEvents: function () {
      console.log(`[${this.insteonId}] Subscribing to dimmer events...`)
      var light = this.insteonClient()

      light.on('turnOn', (group, level) => {
        console.log(`[${this.insteonId}] Dimmer turned ON`)
        this.sendSmartThingsUpdate({ event: 'turn_on', status: 'on', level: level })
        if (level === null) {
          this.getStatus()
        }
      })

      light.on('turnOnFast', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned ON FAST`)
        this.sendSmartThingsUpdate({ event: 'turn_on_fast', status: 'on', level: 100 })
      })

      light.on('turnOff', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned OFF`)
        this.sendSmartThingsUpdate({ event: 'turn_off', status: 'off', level: 0 })
      })

      light.on('turnOffFast', (group) => {
        console.log(`[${this.insteonId}] Dimmer turned OFF FAST`)
        this.sendSmartThingsUpdate({ event: 'turn_off_fast', status: 'off', level: 0 })
      })

      light.on('brightening', (group) => {
        console.log(`[${this.insteonId}] Dimmer brightening`)
        this.sendSmartThingsUpdate({ event: 'brightening' })
      })

      light.on('brightened', (group) => {
        console.log(`[${this.insteonId}] Dimmer brightened`)
        this.sendSmartThingsUpdate({ event: 'brightened' })
        this.getStatus()
      })

      light.on('dimming', (group) => {
        console.log(`[${this.insteonId}] Dimmer dimming`)
        this.sendSmartThingsUpdate({ event: 'dimming' })
      })

      light.on('dimmed', (group) => {
        console.log(`[${this.insteonId}] Dimmer dimmed`)
        this.sendSmartThingsUpdate({ event: 'dimmed' })
        this.getStatus()
      })

      console.log(`[${this.insteonId}] Subscribed to dimmer events`)
    },

    startPolling: function () {
      this.getStatus()
      setInterval(() => {
        this.getStatus()
      }, this.refreshSeconds * 1000)
    }
  },

  beforeValidate: function (attrs, cb) {
    attrs.type = 'dimmer'
    cb()
  }
})
<|endoftext|>


<commit_before>describe('Connector', function () {
    var testConnector;

    before(function () {
        require('./init.js');
        var settings = getSettings();
        settings.log = 'error';
        var datasource = getDataSource(settings);
        testConnector = datasource.connector;
    });

    it('should configure defaults when building filters', function (done) {
        var modelName = 'MockLoopbackModel';
        var defaults = testConnector.addDefaults(modelName);

        expect(defaults.index).to.be.a('string').to.have.length.above(1).to.match(/^[a-z0-9.-_]+$/i);
        expect(defaults.type).to.be.a('string').to.have.length.above(1).to.match(/^[a-z0-9.-_]+$/i);

        done();
    });

    it('should build a query for the WHERE filter', function (done) {
        var criteria, size, offset, modelName, modelIdName;
        criteria = {
            'where': {
                'title': 'Futuro'
            }
        };
        size = 100;
        offset = 10;
        modelName = 'MockLoopbackModel';
        modelIdName = 'id';

        var filterCriteria = testConnector.buildFilter(modelName, modelIdName, criteria, size, offset);
        expect(filterCriteria).not.to.be.null;
        expect(filterCriteria).to.have.property('index')
            .that.is.a('string');
        expect(filterCriteria).to.have.property('type')
            .that.is.a('string')
            .that.equals(modelName);
        expect(filterCriteria).to.have.property('body')
            .that.is.an('object')
            .that.deep.equals({
                sort: [
                  'id'
                ],
                query: {
                    bool: {
                        must: [
                            {
                                match: {
                                    title: 'Futuro'
                                }
                            }
                        ]
                    }
                }
            });
        expect(filterCriteria).to.have.property('size')
            .that.is.a('number');
        expect(filterCriteria).to.have.property('from')
            .that.is.a('number');

        done();
    });

    it('should use a NATIVE filter query as-is', function (done) {
        var criteria, size, offset, modelName, modelIdName;
        criteria = {
            'native': {
                query: {
                    bool: {
                        must: [
                            {
                                match: {
                                    title: 'Futuro'
                                }
                            }
                        ]
                    }
                }
            }
        };
        size = 100;
        offset = 10;
        modelName = 'MockLoopbackModel';
        modelIdName = 'id';

        var filterCriteria = testConnector.buildFilter(modelName, modelIdName, criteria, size, offset);
        expect(filterCriteria).not.to.be.null;
        expect(filterCriteria).to.have.property('index')
            .that.is.a('string');
        expect(filterCriteria).to.have.property('type')
            .that.is.a('string')
            .that.equals(modelName);
        expect(filterCriteria).to.have.property('body')
            .that.is.an('object')
            .that.deep.equals({
                query: {
                    bool: {
                        must: [
                            {
                                match: {
                                    title: 'Futuro'
                                }
                            }
                        ]
                    }
                }
            });
        expect(filterCriteria).to.have.property('size')
            .that.is.a('number');
        expect(filterCriteria).to.have.property('from')
            .that.is.a('number');

        done();
    });
});<commit_msg>fix test - add missing model definition<commit_after>describe('Connector', function () {
    var testConnector;

    before(function () {
        require('./init.js');
        var settings = getSettings();
        settings.log = 'error';
        var datasource = getDataSource(settings);
        testConnector = datasource.connector;

        /*MockLoopbackModel = */datasource.define('MockLoopbackModel', {
            id: {type: String, generated: true, id: true}
        });
    });

    it('should configure defaults when building filters', function (done) {
        var modelName = 'MockLoopbackModel';
        var defaults = testConnector.addDefaults(modelName);

        expect(defaults.index).to.be.a('string').to.have.length.above(1).to.match(/^[a-z0-9.-_]+$/i);
        expect(defaults.type).to.be.a('string').to.have.length.above(1).to.match(/^[a-z0-9.-_]+$/i);

        done();
    });

    it('should build a query for the WHERE filter', function (done) {
        var criteria, size, offset, modelName, modelIdName;
        criteria = {
            'where': {
                'title': 'Futuro'
            }
        };
        size = 100;
        offset = 10;
        modelName = 'MockLoopbackModel';
        modelIdName = 'id';

        var filterCriteria = testConnector.buildFilter(modelName, modelIdName, criteria, size, offset);
        expect(filterCriteria).not.to.be.null;
        expect(filterCriteria).to.have.property('index')
            .that.is.a('string');
        expect(filterCriteria).to.have.property('type')
            .that.is.a('string')
            .that.equals(modelName);
        expect(filterCriteria).to.have.property('body')
            .that.is.an('object')
            .that.deep.equals({
                sort: [
                  'id'
                ],
                query: {
                    bool: {
                        must: [
                            {
                                match: {
                                    title: 'Futuro'
                                }
                            }
                        ]
                    }
                }
            });
        expect(filterCriteria).to.have.property('size')
            .that.is.a('number');
        expect(filterCriteria).to.have.property('from')
            .that.is.a('number');

        done();
    });

    it('should use a NATIVE filter query as-is', function (done) {
        var criteria, size, offset, modelName, modelIdName;
        criteria = {
            'native': {
                query: {
                    bool: {
                        must: [
                            {
                                match: {
                                    title: 'Futuro'
                                }
                            }
                        ]
                    }
                }
            }
        };
        size = 100;
        offset = 10;
        modelName = 'MockLoopbackModel';
        modelIdName = 'id';

        var filterCriteria = testConnector.buildFilter(modelName, modelIdName, criteria, size, offset);
        expect(filterCriteria).not.to.be.null;
        expect(filterCriteria).to.have.property('index')
            .that.is.a('string');
        expect(filterCriteria).to.have.property('type')
            .that.is.a('string')
            .that.equals(modelName);
        expect(filterCriteria).to.have.property('body')
            .that.is.an('object')
            .that.deep.equals({
                query: {
                    bool: {
                        must: [
                            {
                                match: {
                                    title: 'Futuro'
                                }
                            }
                        ]
                    }
                }
            });
        expect(filterCriteria).to.have.property('size')
            .that.is.a('number');
        expect(filterCriteria).to.have.property('from')
            .that.is.a('number');

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


<commit_before>/* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */
import FormUtil from '../../utils/FormUtil';

const Networking = {
  type: 'object',
  title: 'Network',
  description: 'Configure the networking for your service.',
  properties: {
    networkType: {
      fieldType: 'select',
      title: 'Network Type',
      options: [
        {html: 'Host (Default)', id: 'host'},
        {html: 'Bridge', id: 'bridge'}
      ],
      getter: function (service) {
        let ipAddress = service.getIpAddress();
        if (ipAddress) {

          return ipAddress.networkName;
        }

        let container = service.getContainerSettings();
        if (container && container.docker && container.docker.network) {

          return container.docker.network.toLowerCase();
        }

        return 'host';
      },
      filterProperties: function (currentValue, definition, model) {
        // Hide this definition when model values dictate
        if (model.containerSettings
          && model.containerSettings.image != null
          && model.containerSettings.image.length) {

          definition.formElementClass = '';
        } else {
          definition.formElementClass = 'hidden-form-element';
          model.networking.networkType = 'host';
        }
      }
    },
    ports: {
      title: 'Service Endpoints',
      description: (

          Configure the ports and endpoints you would like to use to talk to your service, or we can assign a random port for you. Learn more about ports.

      ),
      type: 'array',
      duplicable: true,
      addLabel: 'Add an endpoint',
      getter: function (service) {
        let container = service.getContainerSettings();
        let portMappings = null;
        if (container && container.docker && container.docker.portMappings) {
          portMappings = container.docker.portMappings;
        }

        if (portMappings == null) {
          portMappings = service.getPortDefinitions();

          if (portMappings == null) {
            return null;
          }
        }

        return portMappings.map(function (portMapping) {
          return {
            lbPort: portMapping.port || portMapping.containerPort,
            name: portMapping.name,
            protocol: portMapping.protocol,
            discovery: portMapping.labels &&
              Object.keys(portMapping.labels).length > 0,
            expose: portMapping.hostPort != null
          };
        });
      },
      filterProperties: function (service = {}, instanceDefinition, model) {
        let properties = Networking
          .properties
          .ports
          .itemShape
          .properties;

        instanceDefinition.forEach(function (definition) {
          let prop = definition.name;
          if (FormUtil.isFieldInstanceOfProp('ports', definition)) {
            prop = FormUtil.getPropKey(definition.name);
          }

          if (properties[prop].shouldShow) {
            definition.formElementClass = {
              'hidden-form-element': !properties[prop].shouldShow(
                service, model || {networking: {}})
            };
          }

          let disabledLBPortFieldValue = service.lbPort || 'Not Enabled';
          if (prop === 'lbPort' && model && model.networking) {
            if (model.networking.networkType !== 'host') {
              definition.showLabel = 'Container Port';
              if (definition.value === disabledLBPortFieldValue) {
                definition.value = null;
              }
            } else {
              definition.showLabel = 'LB Port';

              if (service.discovery) {
                // show as input
                if (definition.value === disabledLBPortFieldValue) {
                  definition.value = null;
                  definition.disabled = false;
                  definition.className = 'form-control';
                  definition.fieldType = 'number';
                }
              } else {
                // show as disabled
                definition.value = disabledLBPortFieldValue;
                definition.disabled = true;
                definition.fieldType = 'text';
                definition.className = 'form-control lb-port-input-field-disabled';
              }

            }
          }
        });
      },
      itemShape: {
        properties: {
          lbPort: {
            title: 'LB Port',
            type: 'number'
          },
          name: {
            title: 'Name',
            type: 'string'
          },
          protocol: {
            title: 'Protocol',
            type: 'string',
            fieldType: 'select',
            default: 'tcp',
            options: ['tcp', 'udp', 'udp,tcp']
          },
          discovery: {
            label: 'Discovery',
            showLabel: false,
            title: 'Discovery',
            type: 'boolean'
          }
        }
      }
    }
  }
};

module.exports = Networking;
<commit_msg>Fix networking port input<commit_after>/* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */
import FormUtil from '../../utils/FormUtil';

const Networking = {
  type: 'object',
  title: 'Network',
  description: 'Configure the networking for your service.',
  properties: {
    networkType: {
      fieldType: 'select',
      title: 'Network Type',
      options: [
        {html: 'Host (Default)', id: 'host'},
        {html: 'Bridge', id: 'bridge'}
      ],
      getter: function (service) {
        let ipAddress = service.getIpAddress();
        if (ipAddress) {

          return ipAddress.networkName;
        }

        let container = service.getContainerSettings();
        if (container && container.docker && container.docker.network) {

          return container.docker.network.toLowerCase();
        }

        return 'host';
      },
      filterProperties: function (currentValue, definition, model) {
        // Hide this definition when model values dictate
        if (model.containerSettings
          && model.containerSettings.image != null
          && model.containerSettings.image.length) {

          definition.formElementClass = '';
        } else {
          definition.formElementClass = 'hidden-form-element';
          model.networking.networkType = 'host';
        }
      }
    },
    ports: {
      title: 'Service Endpoints',
      description: (

          Configure the ports and endpoints you would like to use to talk to your service, or we can assign a random port for you. Learn more about ports.

      ),
      type: 'array',
      duplicable: true,
      addLabel: 'Add an endpoint',
      getter: function (service) {
        let container = service.getContainerSettings();
        let portMappings = null;
        if (container && container.docker && container.docker.portMappings) {
          portMappings = container.docker.portMappings;
        }

        if (portMappings == null) {
          portMappings = service.getPortDefinitions();

          if (portMappings == null) {
            return null;
          }
        }

        return portMappings.map(function (portMapping) {
          return {
            lbPort: portMapping.port || portMapping.containerPort,
            name: portMapping.name,
            protocol: portMapping.protocol,
            discovery: portMapping.labels &&
              Object.keys(portMapping.labels).length > 0,
            expose: portMapping.hostPort != null
          };
        });
      },
      filterProperties: function (service = {}, instanceDefinition, model) {
        let properties = Networking
          .properties
          .ports
          .itemShape
          .properties;

        instanceDefinition.forEach(function (definition) {
          let prop = definition.name;
          if (FormUtil.isFieldInstanceOfProp('ports', definition)) {
            prop = FormUtil.getPropKey(definition.name);
          }

          if (properties[prop].shouldShow) {
            definition.formElementClass = {
              'hidden-form-element': !properties[prop].shouldShow(
                service, model || {networking: {}})
            };
          }

          let disabledLBPortFieldValue = service.lbPort || 'Not Enabled';
          if (prop === 'lbPort' && model && model.networking) {
            if (model.networking.networkType !== 'host') {
              definition.showLabel = 'Container Port';
              if (definition.value === 'Not Enabled') {
                definition.value = null;
              }
            } else {
              definition.showLabel = 'LB Port';

              if (service.discovery) {
                // show as input
                if (definition.value === disabledLBPortFieldValue) {
                  definition.value = null;
                  definition.disabled = false;
                  definition.className = 'form-control';
                  definition.fieldType = 'number';
                }
              } else {
                // show as disabled
                definition.value = disabledLBPortFieldValue;
                definition.disabled = true;
                definition.fieldType = 'text';
                definition.className = 'form-control lb-port-input-field-disabled';
              }

            }
          }
        });
      },
      itemShape: {
        properties: {
          lbPort: {
            title: 'LB Port',
            type: 'number'
          },
          name: {
            title: 'Name',
            type: 'string'
          },
          protocol: {
            title: 'Protocol',
            type: 'string',
            fieldType: 'select',
            default: 'tcp',
            options: ['tcp', 'udp', 'udp,tcp']
          },
          discovery: {
            label: 'Discovery',
            showLabel: false,
            title: 'Discovery',
            type: 'boolean'
          }
        }
      }
    }
  }
};

module.exports = Networking;
<|endoftext|>