<commit_before>var ConfigParser = require('../configParser'),
  q = require('q');

/**
 * Execute the Runner's test cases through Cucumber.
 *
 * @param {Runner} runner The current Protractor Runner.
 * @param {Array} specs Array of Directory Path Strings.
 * @return {q.Promise} Promise resolved with the test results
 */
exports.run = function(runner, specs) {
  // TODO - add the event interface for cucumber.
  var Cucumber = require('cucumber'),
      execOptions = ['node', 'node_modules/.bin/cucumber-js'],
      cucumberResolvedRequire;

  // Set up exec options for Cucumber
  execOptions = execOptions.concat(specs);
  if (runner.getConfig().cucumberOpts) {

    // Process Cucumber Require param
    if (runner.getConfig().cucumberOpts.require) {
      // TODO - this should move into the launcher.
      cucumberResolvedRequire =
          ConfigParser.resolveFilePatterns(
              runner.getConfig().cucumberOpts.require,
              false,
              runner.getConfig().configDir);
      if (cucumberResolvedRequire && cucumberResolvedRequire.length) {
          execOptions = cucumberResolvedRequire.reduce(function(a, fn) {
            return a.concat('-r', fn);
          }, execOptions);
      }
    }

    // Process Cucumber Tag param
    if (Array.isArray(runner.getConfig().cucumberOpts.tags)) {
        for (var i in runner.getConfig().cucumberOpts.tags) {
            var tags = runner.getConfig().cucumberOpts.tags[i];
            execOptions.push('-t');
            execOptions.push(tags);
        }
    } else if (runner.getConfig().cucumberOpts.tags) {
      execOptions.push('-t');
      execOptions.push(runner.getConfig().cucumberOpts.tags);
    }

    // Process Cucumber Format param
    if (runner.getConfig().cucumberOpts.format) {
      execOptions.push('-f');
      execOptions.push(runner.getConfig().cucumberOpts.format);
    }

    // Process Cucumber 'coffee' param
    if (runner.getConfig().cucumberOpts.coffee) {
      execOptions.push('--coffee');
    }
  }
  global.cucumber = Cucumber.Cli(execOptions);

  var testResult = [];
  var stepResults = {
    description: null,
    assertions: [],
    duration: 0
  };
  var scenarioFailed = false;

  var failedCount = 0;
  // Add a listener into cucumber so that protractor can find out which
  // steps passed/failed
  var addResultListener = function(formatter) {
    var feature = { getName: function() { return ''; } };
    var originalHandleBeforeFeatureEvent = formatter.handleBeforeFeatureEvent;
    formatter.handleBeforeFeatureEvent = function(event, callback) {
      feature = event.getPayloadItem('feature');
      if (typeof originalHandleAfterScenarioEvent == 'function') {
        originalHandleBeforeFeatureEvent.apply(formatter, arguments);
      } else {
        callback();
      }
    };
    var originalHandleAfterScenarioEvent = formatter.handleAfterScenarioEvent;
    formatter.handleAfterScenarioEvent = function(event, callback) {
      var scenarioInfo = {
        name: event.getPayloadItem('scenario').getName(),
        category: feature.getName()
      };
      stepResults.description = scenarioInfo.name;
      if (scenarioFailed) {
        ++failedCount;
        runner.emit('testFail', scenarioInfo);
      } else {
        runner.emit('testPass', scenarioInfo);
      }

      testResult.push(stepResults);
      stepResults = {
        description: null,
        assertions: [],
        duration: 0
      };
      scenarioFailed = false;

      if (originalHandleAfterScenarioEvent
          && typeof(originalHandleAfterScenarioEvent) === 'function') {
            originalHandleAfterScenarioEvent(event, callback);
      } else {
        callback();
      }
    };

    var originalHandleStepResultEvent = formatter.handleStepResultEvent;
    formatter.handleStepResultEvent = function(event, callback) {
      var stepResult = event.getPayloadItem('stepResult');
      if (stepResult.isSuccessful()) {
        stepResults.assertions.push({
          passed: true
        });
        stepResults.duration += stepResult.getDuration();
      } else if (stepResult.isFailed()) {
        scenarioFailed = true;
        var failureMessage = stepResult.getFailureException();
        stepResults.assertions.push({
          passed: false,
          errorMsg: failureMessage.message,
          stackTrace: failureMessage.stack
        });
        stepResults.duration += stepResult.getDuration();
      }

      if (originalHandleStepResultEvent
          && typeof(originalHandleStepResultEvent) === 'function') {
            originalHandleStepResultEvent(event, callback);
      } else {
        callback();
      }
    };
  };

  return runner.runTestPreparer().then(function() {
    return q.promise(function(resolve, reject) {
      var cucumberConf = Cucumber.Cli.Configuration(execOptions);
      var runtime = Cucumber.Runtime(cucumberConf);
      var formatter = cucumberConf.getFormatter();
      addResultListener(formatter);
      runtime.attachListener(formatter);
      runtime.start(function() {
        try {
          if (runner.getConfig().onComplete) {
            runner.getConfig().onComplete();
          }
          resolve({
            failedCount: failedCount,
            specResults: testResult
          });
        } catch (err) {
          reject(err);
        }
      });
    });
  });
};
<commit_msg>process no-snippets param for cucumber framework<commit_after>var ConfigParser = require('../configParser'),
  q = require('q');

/**
 * Execute the Runner's test cases through Cucumber.
 *
 * @param {Runner} runner The current Protractor Runner.
 * @param {Array} specs Array of Directory Path Strings.
 * @return {q.Promise} Promise resolved with the test results
 */
exports.run = function(runner, specs) {
  // TODO - add the event interface for cucumber.
  var Cucumber = require('cucumber'),
      execOptions = ['node', 'node_modules/.bin/cucumber-js'],
      cucumberResolvedRequire;

  // Set up exec options for Cucumber
  execOptions = execOptions.concat(specs);
  if (runner.getConfig().cucumberOpts) {

    // Process Cucumber Require param
    if (runner.getConfig().cucumberOpts.require) {
      // TODO - this should move into the launcher.
      cucumberResolvedRequire =
          ConfigParser.resolveFilePatterns(
              runner.getConfig().cucumberOpts.require,
              false,
              runner.getConfig().configDir);
      if (cucumberResolvedRequire && cucumberResolvedRequire.length) {
          execOptions = cucumberResolvedRequire.reduce(function(a, fn) {
            return a.concat('-r', fn);
          }, execOptions);
      }
    }

    // Process Cucumber Tag param
    if (Array.isArray(runner.getConfig().cucumberOpts.tags)) {
        for (var i in runner.getConfig().cucumberOpts.tags) {
            var tags = runner.getConfig().cucumberOpts.tags[i];
            execOptions.push('-t');
            execOptions.push(tags);
        }
    } else if (runner.getConfig().cucumberOpts.tags) {
      execOptions.push('-t');
      execOptions.push(runner.getConfig().cucumberOpts.tags);
    }

    // Process Cucumber Format param
    if (runner.getConfig().cucumberOpts.format) {
      execOptions.push('-f');
      execOptions.push(runner.getConfig().cucumberOpts.format);
    }

    // Process Cucumber 'coffee' param
    if (runner.getConfig().cucumberOpts.coffee) {
      execOptions.push('--coffee');
    }

    // Process Cucumber 'no-snippets' param
    if (runner.getConfig().cucumberOpts.noSnippets) {
      execOptions.push('--no-snippets');
    }
  }
  global.cucumber = Cucumber.Cli(execOptions);

  var testResult = [];
  var stepResults = {
    description: null,
    assertions: [],
    duration: 0
  };
  var scenarioFailed = false;

  var failedCount = 0;
  // Add a listener into cucumber so that protractor can find out which
  // steps passed/failed
  var addResultListener = function(formatter) {
    var feature = { getName: function() { return ''; } };
    var originalHandleBeforeFeatureEvent = formatter.handleBeforeFeatureEvent;
    formatter.handleBeforeFeatureEvent = function(event, callback) {
      feature = event.getPayloadItem('feature');
      if (typeof originalHandleAfterScenarioEvent == 'function') {
        originalHandleBeforeFeatureEvent.apply(formatter, arguments);
      } else {
        callback();
      }
    };
    var originalHandleAfterScenarioEvent = formatter.handleAfterScenarioEvent;
    formatter.handleAfterScenarioEvent = function(event, callback) {
      var scenarioInfo = {
        name: event.getPayloadItem('scenario').getName(),
        category: feature.getName()
      };
      stepResults.description = scenarioInfo.name;
      if (scenarioFailed) {
        ++failedCount;
        runner.emit('testFail', scenarioInfo);
      } else {
        runner.emit('testPass', scenarioInfo);
      }

      testResult.push(stepResults);
      stepResults = {
        description: null,
        assertions: [],
        duration: 0
      };
      scenarioFailed = false;

      if (originalHandleAfterScenarioEvent
          && typeof(originalHandleAfterScenarioEvent) === 'function') {
            originalHandleAfterScenarioEvent(event, callback);
      } else {
        callback();
      }
    };

    var originalHandleStepResultEvent = formatter.handleStepResultEvent;
    formatter.handleStepResultEvent = function(event, callback) {
      var stepResult = event.getPayloadItem('stepResult');
      if (stepResult.isSuccessful()) {
        stepResults.assertions.push({
          passed: true
        });
        stepResults.duration += stepResult.getDuration();
      } else if (stepResult.isFailed()) {
        scenarioFailed = true;
        var failureMessage = stepResult.getFailureException();
        stepResults.assertions.push({
          passed: false,
          errorMsg: failureMessage.message,
          stackTrace: failureMessage.stack
        });
        stepResults.duration += stepResult.getDuration();
      }

      if (originalHandleStepResultEvent
          && typeof(originalHandleStepResultEvent) === 'function') {
            originalHandleStepResultEvent(event, callback);
      } else {
        callback();
      }
    };
  };

  return runner.runTestPreparer().then(function() {
    return q.promise(function(resolve, reject) {
      var cucumberConf = Cucumber.Cli.Configuration(execOptions);
      var runtime = Cucumber.Runtime(cucumberConf);
      var formatter = cucumberConf.getFormatter();
      addResultListener(formatter);
      runtime.attachListener(formatter);
      runtime.start(function() {
        try {
          if (runner.getConfig().onComplete) {
            runner.getConfig().onComplete();
          }
          resolve({
            failedCount: failedCount,
            specResults: testResult
          });
        } catch (err) {
          reject(err);
        }
      });
    });
  });
};
<|endoftext|>


<commit_before>var _gpio,
  yellowLed = 40,
  redLed = 38,
  heartbeatDelayTime = 5000,
  heartbeatOnTime = 1000;
var fault = true;
var faultCount = 0;
var faultTotal = 13;
var blinklength = 100,
blinknumber = 1,
blinkcount = 0,
blinkpin,
blinkcallback;
var on = 1;
var deviceStatus = {
  "AM2302":false,
"ext1":false,
"ext2":false,
"ext3":false,
"wlan0":false,
"wlan1":false,
"imei":false,
"iccid":false,
"mic":false,
"MQ7":false,
"MQ135":false,
"Camera":false,
"Ethernet":false
}
exports.setup = function(gpio){
  _gpio = gpio;
  _gpio.setup(yellowLed, _gpio.DIR_OUT,yellowReady);
  _gpio.setup(redLed, _gpio.DIR_OUT);
}
exports.setFaultStatus = function(object,status){
  faultStatus[object] = status;
}
exports.faultCode = function(){
  for (var status in faultStatus) {
   if (faultStatus.hasOwnProperty(status)) {
     console.log(status + "="+faultStatus[status]);
    }
  }
}
function faultBlink(){

}
function yellowReady(){
  //console.log("yellow ready");
  blinkLed(yellowLed,5,250,function(){});
  //faultCode();
}
var blinkLed = function(pin,numblinks,speed,callback){
  blinkpin = pin;
  blinknumber = numblinks;
  blinklength = speed;
  blinkcallback = callback;
  blink();
}
//   var count = 0;
  function blink() {
      if(blinkcount>=blinknumber){
  	     blinkcount=0;
         blinkcallback();
  	     return;
      }
      _gpio.write(blinkpin, 1);
      setTimeout(function() {
          _gpio.write(blinkpin, 0, blinkoff);
          blinkcount += 1;
      }, blinklength);
  }

  function blinkoff() {
    setTimeout(function(){
      _gpio.write(blinkpin, 0,blink);
    },blinklength);
  }
// }

function heartbeat(){
  //_gpio.write(yellowLed, false);
  setTimeout(function() {
    _gpio.write(yellowLed, true, function(err) {
      if (err) throw err;
      off();
    });
  }, heartbeatDelayTime);
}
function off() {
    setTimeout(function() {
      _gpio.write(yellowLed, false, function(err) {
        if (err) throw err;
        heartbeat();
      });
    }, heartbeatOnTime);
}
<commit_msg>changed faultStatus to deviceStatus<commit_after>var _gpio,
  yellowLed = 40,
  redLed = 38,
  heartbeatDelayTime = 5000,
  heartbeatOnTime = 1000;
var fault = true;
var faultCount = 0;
var faultTotal = 13;
var blinklength = 100,
blinknumber = 1,
blinkcount = 0,
blinkpin,
blinkcallback;
var on = 1;
var deviceStatus = {
  "AM2302":false,
"ext1":false,
"ext2":false,
"ext3":false,
"wlan0":false,
"wlan1":false,
"imei":false,
"iccid":false,
"mic":false,
"MQ7":false,
"MQ135":false,
"Camera":false,
"Ethernet":false
}
exports.setup = function(gpio){
  _gpio = gpio;
  _gpio.setup(yellowLed, _gpio.DIR_OUT,yellowReady);
  _gpio.setup(redLed, _gpio.DIR_OUT);
}
exports.setFaultStatus = function(object,status){
  deviceStatus[object] = status;
}
exports.faultCode = function(){
  for (var status in faultStatus) {
   if (deviceStatus.hasOwnProperty(status)) {
     console.log(status + "="+deviceStatus[status]);
    }
  }
}
function faultBlink(){

}
function yellowReady(){
  //console.log("yellow ready");
  blinkLed(yellowLed,5,250,function(){});
  //faultCode();
}
var blinkLed = function(pin,numblinks,speed,callback){
  blinkpin = pin;
  blinknumber = numblinks;
  blinklength = speed;
  blinkcallback = callback;
  blink();
}
//   var count = 0;
  function blink() {
      if(blinkcount>=blinknumber){
  	     blinkcount=0;
         blinkcallback();
  	     return;
      }
      _gpio.write(blinkpin, 1);
      setTimeout(function() {
          _gpio.write(blinkpin, 0, blinkoff);
          blinkcount += 1;
      }, blinklength);
  }

  function blinkoff() {
    setTimeout(function(){
      _gpio.write(blinkpin, 0,blink);
    },blinklength);
  }
// }

function heartbeat(){
  //_gpio.write(yellowLed, false);
  setTimeout(function() {
    _gpio.write(yellowLed, true, function(err) {
      if (err) throw err;
      off();
    });
  }, heartbeatDelayTime);
}
function off() {
    setTimeout(function() {
      _gpio.write(yellowLed, false, function(err) {
        if (err) throw err;
        heartbeat();
      });
    }, heartbeatOnTime);
}
<|endoftext|>


<commit_before>/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";

/** @module interactive-auth */
const q = require("q");
const url = require("url");

const utils = require("./utils");

const EMAIL_STAGE_TYPE = "m.login.email.identity";
const MSISDN_STAGE_TYPE = "m.login.msisdn";

/**
 * Abstracts the logic used to drive the interactive auth process.
 *
 *
Components implementing an interactive auth flow should instantiate one of
 * these, passing in the necessary callbacks to the constructor. They should
 * then call attemptAuth, which will return a promise which will resolve or
 * reject when the interactive-auth process completes.
 *
 *
Meanwhile, calls will be made to the startAuthStage and doRequest
 * callbacks, and information gathered from the user can be submitted with
 * submitAuthDict.
 *
 * @constructor
 * @alias module:interactive-auth
 *
 * @param {object} opts  options object
 *
 * @param {object} opts.matrixClient A matrix client to use for the auth process
 *
 * @param {object?} opts.authData error response from the last request. If
 *    null, a request will be made with no auth before starting.
 *
 * @param {function(object?): module:client.Promise} opts.doRequest
 *     called with the new auth dict to submit the request. Should return a
 *     promise which resolves to the successful response or rejects with a
 *     MatrixError.
 *
 * @param {function(string, object?)} opts.stateUpdated
 *     called when the status of the UI auth changes, ie. when the state of
 *     an auth stage changes of when the auth flow moves to a new stage.
 *     The arguments are: the login type (eg m.login.password); and an object
 *     which is either an error or an informational object specific to the
 *     login type. If the 'errcode' key is defined, the object is an error,
 *     and has keys:
 *         errcode: string, the textual error code, eg. M_UNKNOWN
 *         error: string, human readable string describing the error
 *
 *     The login type specific objects are as follows:
 *         m.login.email.identity:
 *          * emailSid: string, the sid of the active email auth session
 *
 * @param {object?} opts.inputs Inputs provided by the user and used by different
 *     stages of the auto process. The inputs provided will affect what flow is chosen.
 *
 * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow
 *     using email verification will be chosen.
 *
 * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives
 *     the country that opts.phoneNumber should be resolved relative to.
 *
 * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow
 *     using phone number validation will be chosen.
 *
 * @param {string?} opts.sessionId If resuming an existing interactive auth session,
 *     the sessionId of that session.
 *
 * @param {string?} opts.clientSecret If resuming an existing interactive auth session,
 *     the client secret for that session
 *
 * @param {string?} opts.emailSid If returning from having completed m.login.email.identity
 *     auth, the sid for the email verification session.
 *
 */
function InteractiveAuth(opts) {
    this._matrixClient = opts.matrixClient;
    this._data = opts.authData || {};
    this._requestCallback = opts.doRequest;
    // startAuthStage included for backwards compat
    this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;
    this._completionDeferred = null;
    this._inputs = opts.inputs || {};

    if (opts.sessionId) this._data.session = opts.sessionId;
    this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();
    this._emailSid = opts.emailSid;
    if (this._emailSid === undefined) this._emailSid = null;

    this._currentStage = null;
}

InteractiveAuth.prototype = {
    /**
     * begin the authentication process.
     *
     * @return {module:client.Promise} which resolves to the response on success,
     * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if
     *     no suitable authentication flow can be found
     */
    attemptAuth: function() {
        this._completionDeferred = q.defer();

        // wrap in a promise so that if _startNextAuthStage
        // throws, it rejects the promise in a consistent way
        return q().then(() => {
            // if we have no flows, try a request (we'll have
            // just a session ID in _data if resuming)
            if (!this._data.flows) {
                this._doRequest(this._data);
            } else {
                this._startNextAuthStage();
            }
            return this._completionDeferred.promise;
        });
    },

    /**
     * Poll to check if the auth session or current stage has been
     * completed out-of-band. If so, the attemptAuth promise will
     * be resolved.
     */
    poll: function() {
        if (!this._data.session) return;

        let authDict = {};
        if (this._currentStage == EMAIL_STAGE_TYPE) {
            // The email can be validated out-of-band, but we need to provide the
            // creds so the HS can go & check it.
            if (this._emailSid) {
                const idServerParsedUrl = url.parse(
                    this._matrixClient.getIdentityServerUrl(),
                );
                authDict = {
                    type: EMAIL_STAGE_TYPE,
                    threepid_creds: {
                        sid: this._emailSid,
                        client_secret: this._clientSecret,
                        id_server: idServerParsedUrl.host,
                    },
                };
            }
        }

        this.submitAuthDict(authDict, true);
    },

    /**
     * get the auth session ID
     *
     * @return {string} session id
     */
    getSessionId: function() {
        return this._data ? this._data.session : undefined;
    },

    /**
     * get the client secret used for validation sessions
     * with the ID server.
     *
     * @return {string} client secret
     */
    getClientSecret: function() {
        return this._clientSecret;
    },

    /**
     * get the server params for a given stage
     *
     * @param {string} loginType login type for the stage
     * @return {object?} any parameters from the server for this stage
     */
    getStageParams: function(loginType) {
        let params = {};
        if (this._data && this._data.params) {
            params = this._data.params;
        }
        return params[loginType];
    },

    /**
     * submit a new auth dict and fire off the request. This will either
     * make attemptAuth resolve/reject, or cause the startAuthStage callback
     * to be called for a new stage.
     *
     * @param {object} authData new auth dict to send to the server. Should
     *    include a `type` propterty denoting the login type, as well as any
     *    other params for that stage.
     * @param {bool} ignoreFailure If true, this request failing will not result
     *    in the attemptAuth promise being rejected. This can be set to true
     *    for requests that just poll to see if auth has been completed elsewhere.
     */
    submitAuthDict: function(authData, ignoreFailure) {
        if (!this._completionDeferred) {
            throw new Error("submitAuthDict() called before attemptAuth()");
        }

        // use the sessionid from the last request.
        const auth = {
            session: this._data.session,
        };
        utils.extend(auth, authData);

        this._doRequest(auth, ignoreFailure);
    },

    /**
     * Gets the sid for the email validation session
     * Specific to m.login.email.identity
     *
     * @returns {string} The sid of the email auth session
     */
    getEmailSid: function() {
        return this._emailSid;
    },

    /**
     * Sets the sid for the email validation session
     * This must be set in order to successfully poll for completion
     * of the email validation.
     * Specific to m.login.email.identity
     *
     * @param {string} sid The sid for the email validation session
     */
    setEmailSid: function(sid) {
        this._emailSid = sid;
    },

    /**
     * Fire off a request, and either resolve the promise, or call
     * startAuthStage.
     *
     * @private
     * @param {object?} auth new auth dict, including session id
     * @param {bool?} ignoreFailure If true, this request failing will not result
     *    in the attemptAuth promise being rejected. This can be set to true
     *    for requests that just poll to see if auth has been completed elsewhere.
     */
    _doRequest: function(auth, ignoreFailure) {
        const self = this;

        // hackery to make sure that synchronous exceptions end up in the catch
        // handler (without the additional event loop entailed by q.fcall or an
        // extra q().then)
        let prom;
        try {
            prom = this._requestCallback(auth);
        } catch (e) {
            prom = q.reject(e);
        }

        prom = prom.then(
            function(result) {
                console.log("result from request: ", result);
                self._completionDeferred.resolve(result);
            }, function(error) {
                // sometimes UI auth errors don't come with flows
                const errorFlows = error.data ? error.data.flows : null;
                const haveFlows = Boolean(self._data.flows) || Boolean(errorFlows);
                if (error.httpStatus !== 401 || !error.data || !haveFlows) {
                    // doesn't look like an interactive-auth failure. fail the whole lot.
                    throw error;
                }
                // if the error didn't come with flows, completed flows or session ID,
                // copy over the ones we have. Synapse sometimes sends responses without
                // any UI auth data (eg. when polling for email validation, if the email
                // has not yet been validated). This appears to be a Synapse bug, which
                // we workaround here.
                if (!error.data.flows && !error.data.completed && !error.data.session) {
                    error.data.flows = self._data.flows;
                    error.data.completed = self._data.completed;
                    error.data.session = self._data.session;
                }
                self._data = error.data;
                self._startNextAuthStage();
            },
        );
        if (!ignoreFailure) {
            prom = prom.catch(this._completionDeferred.reject);
        } else {
            // We ignore all failures here (even non-UI auth related ones)
            // since we don't want to suddenly fail if the internet connection
            // had a blip whilst we were polling
            prom = prom.catch((error) => {
                console.log("Ignoring error from UI auth: " + error);
            });
        }
        prom.done();
    },

    /**
     * Pick the next stage and call the callback
     *
     * @private
     * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
     */
    _startNextAuthStage: function() {
        const nextStage = this._chooseStage();
        if (!nextStage) {
            throw new Error("No incomplete flows from the server");
        }
        this._currentStage = nextStage;

        if (this._data.errcode || this._data.error) {
            this._stateUpdatedCallback(nextStage, {
                errcode: this._data.errcode || "",
                error: this._data.error || "",
            });
            return;
        }

        const stageStatus = {};
        if (nextStage == EMAIL_STAGE_TYPE) {
            stageStatus.emailSid = this._emailSid;
        }
        this._stateUpdatedCallback(nextStage, stageStatus);
    },

    /**
     * Pick the next auth stage
     *
     * @private
     * @return {string?} login type
     * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
     */
    _chooseStage: function() {
        const flow = this._chooseFlow();
        console.log("Active flow => %s", JSON.stringify(flow));
        const nextStage = this._firstUncompletedStage(flow);
        console.log("Next stage: %s", nextStage);
        return nextStage;
    },

    /**
     * Pick one of the flows from the returned list
     * If a flow using all of the inputs is found, it will
     * be returned, otherwise, null will be returned.
     *
     * Only flows using all given inputs are chosen because it
     * is likley to be surprising if the user provides a
     * credential and it is not used. For example, for registration,
     * this could result in the email not being used which would leave
     * the account with no means to reset a password.
     *
     * @private
     * @return {object} flow
     * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
     */
    _chooseFlow: function() {
        const flows = this._data.flows || [];

        // we've been given an email or we've already done an email part
        const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);
        const haveMsisdn = (
            Boolean(this._inputs.phoneCountry) &&
            Boolean(this._inputs.phoneNumber)
        );

        for (const flow of flows) {
            let flowHasEmail = false;
            let flowHasMsisdn = false;
            for (const stage of flow.stages) {
                if (stage === EMAIL_STAGE_TYPE) {
                    flowHasEmail = true;
                } else if (stage == MSISDN_STAGE_TYPE) {
                    flowHasMsisdn = true;
                }
            }

            if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {
                return flow;
            }
        }
        // Throw an error with a fairly generic description, but with more
        // information such that the app can give a better one if so desired.
        const err = new Error("No appropriate authentication flow found");
        err.name = 'NoAuthFlowFoundError';
        err.required_stages = [];
        if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE);
        if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE);
        err.available_flows = flows;
        throw err;
    },

    /**
     * Get the first uncompleted stage in the given flow
     *
     * @private
     * @param {object} flow
     * @return {string} login type
     */
    _firstUncompletedStage: function(flow) {
        const completed = (this._data || {}).completed || [];
        for (let i = 0; i < flow.stages.length; ++i) {
            const stageType = flow.stages[i];
            if (completed.indexOf(stageType) === -1) {
                return stageType;
            }
        }
    },
};

/** */
module.exports = InteractiveAuth;
<commit_msg>Extend 'ignoreFailure' to be 'background'<commit_after>/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
"use strict";

/** @module interactive-auth */
const q = require("q");
const url = require("url");

const utils = require("./utils");

const EMAIL_STAGE_TYPE = "m.login.email.identity";
const MSISDN_STAGE_TYPE = "m.login.msisdn";

/**
 * Abstracts the logic used to drive the interactive auth process.
 *
 *
Components implementing an interactive auth flow should instantiate one of
 * these, passing in the necessary callbacks to the constructor. They should
 * then call attemptAuth, which will return a promise which will resolve or
 * reject when the interactive-auth process completes.
 *
 *
Meanwhile, calls will be made to the startAuthStage and doRequest
 * callbacks, and information gathered from the user can be submitted with
 * submitAuthDict.
 *
 * @constructor
 * @alias module:interactive-auth
 *
 * @param {object} opts  options object
 *
 * @param {object} opts.matrixClient A matrix client to use for the auth process
 *
 * @param {object?} opts.authData error response from the last request. If
 *    null, a request will be made with no auth before starting.
 *
 * @param {function(object?): module:client.Promise} opts.doRequest
 *     called with the new auth dict to submit the request. Should return a
 *     promise which resolves to the successful response or rejects with a
 *     MatrixError.
 *
 * @param {function(string, object?)} opts.stateUpdated
 *     called when the status of the UI auth changes, ie. when the state of
 *     an auth stage changes of when the auth flow moves to a new stage.
 *     The arguments are: the login type (eg m.login.password); and an object
 *     which is either an error or an informational object specific to the
 *     login type. If the 'errcode' key is defined, the object is an error,
 *     and has keys:
 *         errcode: string, the textual error code, eg. M_UNKNOWN
 *         error: string, human readable string describing the error
 *
 *     The login type specific objects are as follows:
 *         m.login.email.identity:
 *          * emailSid: string, the sid of the active email auth session
 *
 * @param {object?} opts.inputs Inputs provided by the user and used by different
 *     stages of the auto process. The inputs provided will affect what flow is chosen.
 *
 * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow
 *     using email verification will be chosen.
 *
 * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives
 *     the country that opts.phoneNumber should be resolved relative to.
 *
 * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow
 *     using phone number validation will be chosen.
 *
 * @param {string?} opts.sessionId If resuming an existing interactive auth session,
 *     the sessionId of that session.
 *
 * @param {string?} opts.clientSecret If resuming an existing interactive auth session,
 *     the client secret for that session
 *
 * @param {string?} opts.emailSid If returning from having completed m.login.email.identity
 *     auth, the sid for the email verification session.
 *
 */
function InteractiveAuth(opts) {
    this._matrixClient = opts.matrixClient;
    this._data = opts.authData || {};
    this._requestCallback = opts.doRequest;
    // startAuthStage included for backwards compat
    this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;
    this._completionDeferred = null;
    this._inputs = opts.inputs || {};

    if (opts.sessionId) this._data.session = opts.sessionId;
    this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();
    this._emailSid = opts.emailSid;
    if (this._emailSid === undefined) this._emailSid = null;

    this._currentStage = null;
}

InteractiveAuth.prototype = {
    /**
     * begin the authentication process.
     *
     * @return {module:client.Promise} which resolves to the response on success,
     * or rejects with the error on failure. Rejects with NoAuthFlowFoundError if
     *     no suitable authentication flow can be found
     */
    attemptAuth: function() {
        this._completionDeferred = q.defer();

        // wrap in a promise so that if _startNextAuthStage
        // throws, it rejects the promise in a consistent way
        return q().then(() => {
            // if we have no flows, try a request (we'll have
            // just a session ID in _data if resuming)
            if (!this._data.flows) {
                this._doRequest(this._data);
            } else {
                this._startNextAuthStage();
            }
            return this._completionDeferred.promise;
        });
    },

    /**
     * Poll to check if the auth session or current stage has been
     * completed out-of-band. If so, the attemptAuth promise will
     * be resolved.
     */
    poll: function() {
        if (!this._data.session) return;

        let authDict = {};
        if (this._currentStage == EMAIL_STAGE_TYPE) {
            // The email can be validated out-of-band, but we need to provide the
            // creds so the HS can go & check it.
            if (this._emailSid) {
                const idServerParsedUrl = url.parse(
                    this._matrixClient.getIdentityServerUrl(),
                );
                authDict = {
                    type: EMAIL_STAGE_TYPE,
                    threepid_creds: {
                        sid: this._emailSid,
                        client_secret: this._clientSecret,
                        id_server: idServerParsedUrl.host,
                    },
                };
            }
        }

        this.submitAuthDict(authDict, true);
    },

    /**
     * get the auth session ID
     *
     * @return {string} session id
     */
    getSessionId: function() {
        return this._data ? this._data.session : undefined;
    },

    /**
     * get the client secret used for validation sessions
     * with the ID server.
     *
     * @return {string} client secret
     */
    getClientSecret: function() {
        return this._clientSecret;
    },

    /**
     * get the server params for a given stage
     *
     * @param {string} loginType login type for the stage
     * @return {object?} any parameters from the server for this stage
     */
    getStageParams: function(loginType) {
        let params = {};
        if (this._data && this._data.params) {
            params = this._data.params;
        }
        return params[loginType];
    },

    /**
     * submit a new auth dict and fire off the request. This will either
     * make attemptAuth resolve/reject, or cause the startAuthStage callback
     * to be called for a new stage.
     *
     * @param {object} authData new auth dict to send to the server. Should
     *    include a `type` propterty denoting the login type, as well as any
     *    other params for that stage.
     * @param {bool} background If true, this request failing will not result
     *    in the attemptAuth promise being rejected. This can be set to true
     *    for requests that just poll to see if auth has been completed elsewhere.
     */
    submitAuthDict: function(authData, background) {
        if (!this._completionDeferred) {
            throw new Error("submitAuthDict() called before attemptAuth()");
        }

        // use the sessionid from the last request.
        const auth = {
            session: this._data.session,
        };
        utils.extend(auth, authData);

        this._doRequest(auth, background);
    },

    /**
     * Gets the sid for the email validation session
     * Specific to m.login.email.identity
     *
     * @returns {string} The sid of the email auth session
     */
    getEmailSid: function() {
        return this._emailSid;
    },

    /**
     * Sets the sid for the email validation session
     * This must be set in order to successfully poll for completion
     * of the email validation.
     * Specific to m.login.email.identity
     *
     * @param {string} sid The sid for the email validation session
     */
    setEmailSid: function(sid) {
        this._emailSid = sid;
    },

    /**
     * Fire off a request, and either resolve the promise, or call
     * startAuthStage.
     *
     * @private
     * @param {object?} auth new auth dict, including session id
     * @param {bool?} background If true, this request is a background poll, so it
     *    failing will not result in the attemptAuth promise being rejected.
     *    This can be set to true for requests that just poll to see if auth has
     *    been completed elsewhere.
     */
    _doRequest: function(auth, background) {
        const self = this;

        // hackery to make sure that synchronous exceptions end up in the catch
        // handler (without the additional event loop entailed by q.fcall or an
        // extra q().then)
        let prom;
        try {
            prom = this._requestCallback(auth, background);
        } catch (e) {
            prom = q.reject(e);
        }

        prom = prom.then(
            function(result) {
                console.log("result from request: ", result);
                self._completionDeferred.resolve(result);
            }, function(error) {
                // sometimes UI auth errors don't come with flows
                const errorFlows = error.data ? error.data.flows : null;
                const haveFlows = Boolean(self._data.flows) || Boolean(errorFlows);
                if (error.httpStatus !== 401 || !error.data || !haveFlows) {
                    // doesn't look like an interactive-auth failure. fail the whole lot.
                    throw error;
                }
                // if the error didn't come with flows, completed flows or session ID,
                // copy over the ones we have. Synapse sometimes sends responses without
                // any UI auth data (eg. when polling for email validation, if the email
                // has not yet been validated). This appears to be a Synapse bug, which
                // we workaround here.
                if (!error.data.flows && !error.data.completed && !error.data.session) {
                    error.data.flows = self._data.flows;
                    error.data.completed = self._data.completed;
                    error.data.session = self._data.session;
                }
                self._data = error.data;
                self._startNextAuthStage();
            },
        );
        if (!background) {
            prom = prom.catch(this._completionDeferred.reject);
        } else {
            // We ignore all failures here (even non-UI auth related ones)
            // since we don't want to suddenly fail if the internet connection
            // had a blip whilst we were polling
            prom = prom.catch((error) => {
                console.log("Ignoring error from UI auth: " + error);
            });
        }
        prom.done();
    },

    /**
     * Pick the next stage and call the callback
     *
     * @private
     * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
     */
    _startNextAuthStage: function() {
        const nextStage = this._chooseStage();
        if (!nextStage) {
            throw new Error("No incomplete flows from the server");
        }
        this._currentStage = nextStage;

        if (this._data.errcode || this._data.error) {
            this._stateUpdatedCallback(nextStage, {
                errcode: this._data.errcode || "",
                error: this._data.error || "",
            });
            return;
        }

        const stageStatus = {};
        if (nextStage == EMAIL_STAGE_TYPE) {
            stageStatus.emailSid = this._emailSid;
        }
        this._stateUpdatedCallback(nextStage, stageStatus);
    },

    /**
     * Pick the next auth stage
     *
     * @private
     * @return {string?} login type
     * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
     */
    _chooseStage: function() {
        const flow = this._chooseFlow();
        console.log("Active flow => %s", JSON.stringify(flow));
        const nextStage = this._firstUncompletedStage(flow);
        console.log("Next stage: %s", nextStage);
        return nextStage;
    },

    /**
     * Pick one of the flows from the returned list
     * If a flow using all of the inputs is found, it will
     * be returned, otherwise, null will be returned.
     *
     * Only flows using all given inputs are chosen because it
     * is likley to be surprising if the user provides a
     * credential and it is not used. For example, for registration,
     * this could result in the email not being used which would leave
     * the account with no means to reset a password.
     *
     * @private
     * @return {object} flow
     * @throws {NoAuthFlowFoundError} If no suitable authentication flow can be found
     */
    _chooseFlow: function() {
        const flows = this._data.flows || [];

        // we've been given an email or we've already done an email part
        const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);
        const haveMsisdn = (
            Boolean(this._inputs.phoneCountry) &&
            Boolean(this._inputs.phoneNumber)
        );

        for (const flow of flows) {
            let flowHasEmail = false;
            let flowHasMsisdn = false;
            for (const stage of flow.stages) {
                if (stage === EMAIL_STAGE_TYPE) {
                    flowHasEmail = true;
                } else if (stage == MSISDN_STAGE_TYPE) {
                    flowHasMsisdn = true;
                }
            }

            if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {
                return flow;
            }
        }
        // Throw an error with a fairly generic description, but with more
        // information such that the app can give a better one if so desired.
        const err = new Error("No appropriate authentication flow found");
        err.name = 'NoAuthFlowFoundError';
        err.required_stages = [];
        if (haveEmail) err.required_stages.push(EMAIL_STAGE_TYPE);
        if (haveMsisdn) err.required_stages.push(MSISDN_STAGE_TYPE);
        err.available_flows = flows;
        throw err;
    },

    /**
     * Get the first uncompleted stage in the given flow
     *
     * @private
     * @param {object} flow
     * @return {string} login type
     */
    _firstUncompletedStage: function(flow) {
        const completed = (this._data || {}).completed || [];
        for (let i = 0; i < flow.stages.length; ++i) {
            const stageType = flow.stages[i];
            if (completed.indexOf(stageType) === -1) {
                return stageType;
            }
        }
    },
};

/** */
module.exports = InteractiveAuth;
<|endoftext|>


<commit_before>var commandMap = {
  ALT:'KEY_LEFT_ALT',
  GUI:'KEY_LEFT_GUI',
  WINDOWS:'KEY_LEFT_GUI',
  COMMAND:'KEY_LEFT_GUI',
  CTRL:'KEY_LEFT_CTRL',
  CONTROL:'KEY_LEFT_CTRL',
  SHIFT:'KEY_LEFT_SHIFT',
  ESCAPE:'KEY_ESC',
  MENU:'229',
  ESC:'KEY_LEFT_ESC',
  END:'KEY_END',
  SPACE:'\' \'',
  TAB:'KEY_TAB',
  PRINTSCREEN:'206',
  ENTER:'KEY_RETURN',
  UPARROW:'KEY_UP_ARROW',
  DOWNARROW:'KEY_DOWN_ARROW',
  LEFTARROW:'KEY_LEFT_ARROW',
  RIGHTARROW:'KEY_RIGHT_ARROW',
  CAPSLOCK:'KEY_CAPS_LOCK',
  DELETE:'KEY_DELETE',
  DEL:'KEY_DELETE'
};
var keyMap = {
  a:'97',
  b:'98',
  c:'99',
  d:'100',
  e:'101',
  f:'102',
  g:'103',
  h:'104',
  i:'105',
  j:'106',
  k:'107',
  l:'108',
  m:'109',
  n:'110',
  o:'111',
  p:'112',
  q:'113',
  r:'114',
  s:'115',
  t:'116',
  u:'117',
  v:'118',
  w:'119',
  x:'120',
  y:'121',
  z:'122'
};

class Duckuino{

  constructor(lang) {
    this.keyMap = keyMap;
    this.commandMap = commandMap;
  }

  parser(code){
    var parsed = '';

    // Remove unnecessary empty lines
    code = code.replace(/[\n]{2,}/g, '\n');

    // Split the DuckyScript into lines
    var lines = code.split('\n');

    // Indicate to release all at the of line
    var releaseAll = false;
    var countRepeats = 1;
    for (var i = 0; i < lines.length; i++) {

      var line = lines[i];

      releaseAll = false;
      parsed += '\n';

      // Split line to words
      var words = line.split(' ');

      // Parse special commands
      if(words[0]== "STRING"){
        words.shift();

        if (words[0] != undefined && words[0] != '')
        {
          var string = '';
          while (words.length) {
            string += ' ' + words[0];
            words.shift();
          }

          // Replace all " with \" and all \ with \\
          string = string.replace(/\\/g, '\\\\');
          string = string.replace(/"/g, '\\"');

          parsed += '  Keyboard.print(\'' + string + '\');';
        } else {
          console.error('Error: at line: ' + (i + 1) + ', STRING requires a text')
          return;
        }

      // Command: DELAY
      } else if(words[0] == "DELAY"){
        words.shift();
        if (words[0] != undefined && words[0] != ''){
          parsed += '  delay(' + words[0] + ');\n';
        } else {
          console.error('Error: at line: ' + (i + 1) + ', DELAY requires a number (e.g. DELAY 1000)')
          return;
        }

        continue;

      // Command: GUI/CONTROL/CTRL/COMMAND/WINDOWS/SHIFT/ALT
      } else if(words[0] == "GUI" || words[0] == "WINDOWS" || words[0] == "CTRL" || words[0] == "COMMAND" || words[0] == "ALT" || words[0] == "SHIFT"){
        //var keep = words[0];
        //keep = this.commandMap[keep];
        //words.shift();
        var press = '';
        var release = '';

        while (words.length){
          var key = words[0];
          if(this.keyMap[key] != undefined){
            key = this.keyMap[key];
          } else if(this.commandMap[key] != undefined){
            key = this.commandMap[key];
          }
          if (words.length > 1){
            press +=  '    Keyboard.press(\'' + key + '\');\n';
            release +=  '    Keyboard.release(\'' + key + ');\n';
          }
          words.shift();
        }
        parsed += '  '+press+'delay(50);\n  '+release;

        // Clear other arguments
        continue;

      // Command: TYPE
      } else if(words[0] == "TYPE"){
        words.shift();
        if (words[0] != undefined && words[0] != ''){
          var key = words[0];
          key = this.keyMap[key];
          parsed += '  typeKey(' + key + ');\n';
        } else {
          console.error('Error: at line: ' + (i + 1) + ', TYPE requires a key')
          return;
        }

        continue;

      // Command: REM
      } else if(words[0] == "REM"){
        words.shift();

        if (words[0] != undefined && words[0] != '')
        {
          var remTmp = '  //';

          while (words.length) {
            remTmp += ' ' + words[0];
            words.shift();
          }

          parsed += remTmp;
        } else {
          console.error('Error: at line: ' + (i + 1) + ', REM requires a comment')
          return;
        }

      // Command: MOUSEMOVE
      } else if(words[0] == "MOUSEMOVE"){
        words.shift();

        if (words[0] != undefined && words[0] != ''){
          var mouseParams = words[0].split(',');

          parsed += '  Mouse.move('+mouseParams[0]+', '+mouseParams[1];

          if(mouseParams[2] != undefined && mouseParams[2] != ''){
            parsed += ', '+mouseParams[2];
          }

          parsed += ');';
          words.shift();
        } else {
          console.error('Error: at line: ' + (i + 1) + ', MOUSEMOVE requires at least two parameters')
          return;
        }

      // Command: MOUSECLICK
      } else if(words[0] == "MOUSECLICK"){
        words.shift();
        words[0] = words[0].toUpperCase();

        if (words[0] == 'LEFT' || words[0] == 'RIGHT' || words[0] == 'MIDDLE' && words[0] != undefined && words[0] != ''){
          parsed += '  Mouse.click(\'MOUSE_'+words[0]+'\');'
          words.shift();
        } else {
          console.error('Error: at line: ' + (i + 1) + ', MOUSECLICK requires key (left/middle/right)')
          return;
        }

      // Command: REPEAT / REPLAY
      } else if(words[0] == "REPEAT" || words[0] == "REPLAY" ){
        words.shift();

        if (words[0] != undefined && words[0] != ''){
          // Get the code to repeat/replay
          var lines = code.split('\n');
          var lastLine = lines.length-2;
          lastLine = lines[lastLine];

          // Get rid of last parsed line
          var parsedLines = parsed.split('\n');
          var lastParsed = parsedLines.length-2;
          parsedLines[lastParsed] = '';

          parsed = parsedLines.join('\n');
          var replay = '\n  for (int rID_'+countRepeats+' = 0; rID_'+countRepeats+' < '+words[0]+'; rID_'+countRepeats+'++) {';
          replay += this.parser(lastLine);
          replay += '\n  };\n';
          parsed += replay;

          countRepeats++;
          words.shift();

        } else {
          console.error('Error: at line: ' + (i + 1) + ', REPLAY/REPEAT requires a number')
          return;
        }

      // Everything else
      } else {
        while (words.length){
          var key = words[0];

          if(this.keyMap[key] != undefined){
            key = this.keyMap[key];
            parsed += '  Keyboard.press(\' '+ key +' \');\n    delay(50);\n  Keyboard.release(\'' + key + '\');\n';
          } else if(this.commandMap[key] != undefined){
            if (words.length == 1 && !releaseAll){
              parsed += '  typeKey(' + this.commandMap[key] + ');\n';
            } else {
              parsed += '  Keyboard.press(\'' + this.commandMap[key] + '\');\n  delay(50);\n  Keyboard.release(\'' + this.commandMap[key] + '\');\n';
            }
          }

          words.shift();
        }
      }
    }
    parsed = parsed.replace(/[\n]{2,}/g, '\n\n');
    return parsed;
  }

  compile(code){
    // Build the Arduino code skeleton
    return '// Init function\n'
    + 'void setup()\n'
    + '{\n'
    + '  // Start payload\n'
    + '  Mouse.begin();\n'
    + '  Keyboard.begin();\n\n'
    + '  // Wait 500ms\n'
    + '  delay(500);\n'
    + this.parser(code)
    + '\n'
    + '  // End payload\n'
    + '  Keyboard.end();\n'
    + '  Mouse.end();\n'
    + '}\n'
    + '\n'
    + '// Unused\n'
    + 'void loop() {}';
  }
}
<commit_msg>Update<commit_after>var commandMap = {
  ALT:'KEY_LEFT_ALT',
  GUI:'KEY_LEFT_GUI',
  WINDOWS:'KEY_LEFT_GUI',
  COMMAND:'KEY_LEFT_GUI',
  CTRL:'KEY_LEFT_CTRL',
  CONTROL:'KEY_LEFT_CTRL',
  SHIFT:'KEY_LEFT_SHIFT',
  ESCAPE:'KEY_ESC',
  MENU:'229',
  ESC:'KEY_LEFT_ESC',
  END:'KEY_END',
  SPACE:'\' \'',
  TAB:'KEY_TAB',
  PRINTSCREEN:'206',
  ENTER:'KEY_RETURN',
  UPARROW:'KEY_UP_ARROW',
  DOWNARROW:'KEY_DOWN_ARROW',
  LEFTARROW:'KEY_LEFT_ARROW',
  RIGHTARROW:'KEY_RIGHT_ARROW',
  CAPSLOCK:'KEY_CAPS_LOCK',
  DELETE:'KEY_DELETE',
  DEL:'KEY_DELETE'
};
var keyMap = {
  a:'97',
  b:'98',
  c:'99',
  d:'100',
  e:'101',
  f:'102',
  g:'103',
  h:'104',
  i:'105',
  j:'106',
  k:'107',
  l:'108',
  m:'109',
  n:'110',
  o:'111',
  p:'112',
  q:'113',
  r:'114',
  s:'115',
  t:'116',
  u:'117',
  v:'118',
  w:'119',
  x:'120',
  y:'121',
  z:'122'
};

class Duckuino{

  constructor(lang) {
    this.keyMap = keyMap;
    this.commandMap = commandMap;
  }

  parser(code){
    var parsed = '';

    // Remove unnecessary empty lines
    code = code.replace(/[\n]{2,}/g, '\n');

    // Split the DuckyScript into lines
    var lines = code.split('\n');

    // Indicate to release all at the of line
    var releaseAll = false;
    var countRepeats = 1;
    for (var i = 0; i < lines.length; i++) {

      var line = lines[i];

      releaseAll = false;
      parsed += '\n';

      // Split line to words
      var words = line.split(' ');

      // Parse special commands
      if(words[0]== "STRING"){
        words.shift();

        if (words[0] != undefined && words[0] != '')
        {
          var string = '';
          while (words.length) {
            string += ' ' + words[0];
            words.shift();
          }

          // Replace all " with \" and all \ with \\
          string = string.replace(/\\/g, '\\\\');
          string = string.replace(/"/g, '\\"');

          parsed += '  Keyboard.print(\'' + string + '\');';
        } else {
          console.error('Error: at line: ' + (i + 1) + ', STRING requires a text')
          return;
        }

      // Command: DELAY
      } else if(words[0] == "DELAY"){
        words.shift();
        if (words[0] != undefined && words[0] != ''){
          parsed += '  delay(' + words[0] + ');\n';
        } else {
          console.error('Error: at line: ' + (i + 1) + ', DELAY requires a number (e.g. DELAY 1000)')
          return;
        }

        continue;

      // Command: GUI/CONTROL/CTRL/COMMAND/WINDOWS/SHIFT/ALT
      } else if(words[0] == "GUI" || words[0] == "WINDOWS" || words[0] == "CTRL" || words[0] == "COMMAND" || words[0] == "ALT" || words[0] == "SHIFT"){
        //var keep = words[0];
        //keep = this.commandMap[keep];
        //words.shift();
        var press = '';
        var release = '';

        while (words.length){
          var key = words[0];
          if(this.keyMap[key] != undefined){
            key = this.keyMap[key];
          } else if(this.commandMap[key] != undefined){
            key = this.commandMap[key];
          }
          if (words.length > 1){
            press +=  '    Keyboard.press(\'' + key + '\');\n';
            release +=  '    Keyboard.release(\'' + key + ');\n';
          }
          words.shift();
        }
        parsed += '  '+press+'      delay(50);\n  '+release;

        // Clear other arguments
        continue;

      // Command: TYPE
      } else if(words[0] == "TYPE"){
        words.shift();
        if (words[0] != undefined && words[0] != ''){
          var key = words[0];
          key = this.keyMap[key];
          parsed += '  typeKey(' + key + ');\n';
        } else {
          console.error('Error: at line: ' + (i + 1) + ', TYPE requires a key')
          return;
        }

        continue;

      // Command: REM
      } else if(words[0] == "REM"){
        words.shift();

        if (words[0] != undefined && words[0] != '')
        {
          var remTmp = '  //';

          while (words.length) {
            remTmp += ' ' + words[0];
            words.shift();
          }

          parsed += remTmp;
        } else {
          console.error('Error: at line: ' + (i + 1) + ', REM requires a comment')
          return;
        }

      // Command: MOUSEMOVE
      } else if(words[0] == "MOUSEMOVE"){
        words.shift();

        if (words[0] != undefined && words[0] != ''){
          var mouseParams = words[0].split(',');

          parsed += '  Mouse.move('+mouseParams[0]+', '+mouseParams[1];

          if(mouseParams[2] != undefined && mouseParams[2] != ''){
            parsed += ', '+mouseParams[2];
          }

          parsed += ');';
          words.shift();
        } else {
          console.error('Error: at line: ' + (i + 1) + ', MOUSEMOVE requires at least two parameters')
          return;
        }

      // Command: MOUSECLICK
      } else if(words[0] == "MOUSECLICK"){
        words.shift();
        words[0] = words[0].toUpperCase();

        if (words[0] == 'LEFT' || words[0] == 'RIGHT' || words[0] == 'MIDDLE' && words[0] != undefined && words[0] != ''){
          parsed += '  Mouse.click(\'MOUSE_'+words[0]+'\');'
          words.shift();
        } else {
          console.error('Error: at line: ' + (i + 1) + ', MOUSECLICK requires key (left/middle/right)')
          return;
        }

      // Command: REPEAT / REPLAY
      } else if(words[0] == "REPEAT" || words[0] == "REPLAY" ){
        words.shift();

        if (words[0] != undefined && words[0] != ''){
          // Get the code to repeat/replay
          var lines = code.split('\n');
          var lastLine = lines.length-2;
          lastLine = lines[lastLine];

          // Get rid of last parsed line
          var parsedLines = parsed.split('\n');
          var lastParsed = parsedLines.length-2;
          parsedLines[lastParsed] = '';

          parsed = parsedLines.join('\n');
          var replay = '\n  for (int rID_'+countRepeats+' = 0; rID_'+countRepeats+' < '+words[0]+'; rID_'+countRepeats+'++) {';
          replay += this.parser(lastLine);
          replay += '\n  };\n';
          parsed += replay;

          countRepeats++;
          words.shift();

        } else {
          console.error('Error: at line: ' + (i + 1) + ', REPLAY/REPEAT requires a number')
          return;
        }

      // Everything else
      } else {
        while (words.length){
          var key = words[0];

          if(this.keyMap[key] != undefined){
            key = this.keyMap[key];
            parsed += '  Keyboard.press(\' '+ key +' \');\n    delay(50);\n  Keyboard.release(\'' + key + '\');\n';
          } else if(this.commandMap[key] != undefined){
            if (words.length == 1 && !releaseAll){
              parsed += '  typeKey(' + this.commandMap[key] + ');\n';
            } else {
              parsed += '  Keyboard.press(\'' + this.commandMap[key] + '\');\n  delay(50);\n  Keyboard.release(\'' + this.commandMap[key] + '\');\n';
            }
          }

          words.shift();
        }
      }
    }
    parsed = parsed.replace(/[\n]{2,}/g, '\n\n');
    return parsed;
  }

  compile(code){
    // Build the Arduino code skeleton
    return '// Init function\n'
    + 'void setup()\n'
    + '{\n'
    + '  // Start payload\n'
    + '  Mouse.begin();\n'
    + '  Keyboard.begin();\n\n'
    + '  // Wait 500ms\n'
    + '  delay(500);\n'
    + this.parser(code)
    + '\n'
    + '  // End payload\n'
    + '  Keyboard.end();\n'
    + '  Mouse.end();\n'
    + '}\n'
    + '\n'
    + '// Unused\n'
    + 'void loop() {}';
  }
}
<|endoftext|>


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

var BASE = 'extensions.auto-confirm@myokoym.net.';
var prefs = require('lib/prefs').prefs;
{
  if (prefs.getDefaultPref(BASE + 'debug') === null)
    prefs.setDefaultPref(BASE + 'debug', false);
  // For development
  if (prefs.getPref(BASE + 'debug')) {
    prefs.setDefaultPref(BASE + 'common.debug-confirm-cancel.action', 'cancel');
    prefs.setDefaultPref(BASE + 'common.debug-confirm-cancel.text', 'auto-confirm');
    prefs.setDefaultPref(BASE + 'common.debug-confirm-cancel.type', 'confirm');
    prefs.setDefaultPref(BASE + 'common.debug-confirm-ok.action', 'accept');
    prefs.setDefaultPref(BASE + 'common.debug-confirm-ok.text', 'auto-ok');
    prefs.setDefaultPref(BASE + 'common.debug-confirm-ok.type', 'confirm');
  }
}

function log(message) {
  if (prefs.getPref(BASE + 'debug')) {
    console.log("auto-confirm: " + message);
  }
}

load('lib/WindowManager');

var global = this;
function handleWindow(aWindow)
{
  log("handleWindow");
  var doc = aWindow.document;
  if (doc.documentElement.localName === 'dialog' &&
      doc.documentElement.id === 'commonDialog') {
    handleCommonDialog(aWindow);
    return;
  }

}

function handleCommonDialog(aWindow)
{
  var doc = aWindow.document;
  var args = aWindow.args;
  log("args: " + JSON.stringify(args));
  var configs = prefs.getChildren(BASE + 'common');
  log("commonDialog: " + configs);
  for (let config of configs) {
    let typeMatcher = prefs.getPref(config + '.type');
    if (typeMatcher !== args.promptType)
      continue;
    let textMatcher = prefs.getPref(config + '.text');
    if (textMatcher && !args.text.match(textMatcher))
      continue;
    let titleMatcher = prefs.getPref(config + '.title');
    if (titleMatcher && !args.title.match(titleMatcher))
      continue;

    log("config: " + config);
    let action = prefs.getPref(config + '.action');
    processAction(aWindow, action);
  }
  log("no match");
}

function processAction(aWindow, aAction)
{
    var doc = aWindow.document;
    log("action: " + aAction);
    switch (aAction) {
    case 'accept':
      doc.documentElement.acceptDialog();
      log("accept");
      return;
    case 'cancel':
      doc.documentElement.cancelDialog();
      log("cancel");
      return;
    default:
      log("no action");
      return;
    }
}

WindowManager.addHandler(handleWindow);

function shutdown()
{
  WindowManager = undefined;
  global = undefined;
}
<commit_msg>Log "no match" correctly<commit_after>/*
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

var BASE = 'extensions.auto-confirm@myokoym.net.';
var prefs = require('lib/prefs').prefs;
{
  if (prefs.getDefaultPref(BASE + 'debug') === null)
    prefs.setDefaultPref(BASE + 'debug', false);
  // For development
  if (prefs.getPref(BASE + 'debug')) {
    prefs.setDefaultPref(BASE + 'common.debug-confirm-cancel.action', 'cancel');
    prefs.setDefaultPref(BASE + 'common.debug-confirm-cancel.text', 'auto-confirm');
    prefs.setDefaultPref(BASE + 'common.debug-confirm-cancel.type', 'confirm');
    prefs.setDefaultPref(BASE + 'common.debug-confirm-ok.action', 'accept');
    prefs.setDefaultPref(BASE + 'common.debug-confirm-ok.text', 'auto-ok');
    prefs.setDefaultPref(BASE + 'common.debug-confirm-ok.type', 'confirm');
  }
}

function log(message) {
  if (prefs.getPref(BASE + 'debug')) {
    console.log("auto-confirm: " + message);
  }
}

load('lib/WindowManager');

var global = this;
function handleWindow(aWindow)
{
  log("handleWindow");
  var doc = aWindow.document;
  if (doc.documentElement.localName === 'dialog' &&
      doc.documentElement.id === 'commonDialog') {
    handleCommonDialog(aWindow);
    return;
  }

}

function handleCommonDialog(aWindow)
{
  var doc = aWindow.document;
  var args = aWindow.args;
  log("args: " + JSON.stringify(args));
  var configs = prefs.getChildren(BASE + 'common');
  log("commonDialog: " + configs);
  var matched = false;
  for (let config of configs) {
    let typeMatcher = prefs.getPref(config + '.type');
    if (typeMatcher !== args.promptType)
      continue;
    let textMatcher = prefs.getPref(config + '.text');
    if (textMatcher && !args.text.match(textMatcher))
      continue;
    let titleMatcher = prefs.getPref(config + '.title');
    if (titleMatcher && !args.title.match(titleMatcher))
      continue;

    matched = true;
    log("config: " + config);
    let action = prefs.getPref(config + '.action');
    processAction(aWindow, action);
  }
  if (!matched)
    log("no match");
}

function processAction(aWindow, aAction)
{
    var doc = aWindow.document;
    log("action: " + aAction);
    switch (aAction) {
    case 'accept':
      doc.documentElement.acceptDialog();
      log("accept");
      return;
    case 'cancel':
      doc.documentElement.cancelDialog();
      log("cancel");
      return;
    default:
      log("no action");
      return;
    }
}

WindowManager.addHandler(handleWindow);

function shutdown()
{
  WindowManager = undefined;
  global = undefined;
}
<|endoftext|>


<commit_before>/**
 * jemul8 - JavaScript x86 Emulator v0.0.1
 * http://jemul8.com/
 *
 * Copyright 2013 jemul8.com (http://github.com/asmblah/jemul8)
 * Released under the MIT license
 * http://jemul8.com/MIT-LICENSE.txt
 */

/*global define */
define([
    "js/util",
    "js/EventEmitter",
    "js/Exception",
    "js/Promise"
], function (
    util,
    EventEmitter,
    Exception,
    Promise
) {
    "use strict";

    var hasOwn = {}.hasOwnProperty;

    function Emulator(legacyJemul8) {
        EventEmitter.call(this);

        this.inited = false;
        this.legacyJemul8 = legacyJemul8;
        this.running = false;
    }

    util.inherit(Emulator).from(EventEmitter);

    util.extend(Emulator.prototype, {
        getCPU: function () {
            var legacyCPU = this.legacyJemul8.machine.cpu;

            return {
                getRegisters: function () {
                    return {
                        eax: legacyCPU.EAX,
                        ax: legacyCPU.AX,
                        al: legacyCPU.AL,
                        ah: legacyCPU.AH,

                        ecx: legacyCPU.ECX,
                        cx: legacyCPU.CX,
                        cl: legacyCPU.CL,
                        ch: legacyCPU.CH,

                        ebx: legacyCPU.EBX,
                        bx: legacyCPU.BX,
                        bl: legacyCPU.BL,
                        bh: legacyCPU.BH,

                        edx: legacyCPU.EDX,
                        dx: legacyCPU.DX,
                        dl: legacyCPU.DL,
                        dh: legacyCPU.DH,

                        ebp: legacyCPU.EBP,
                        bp: legacyCPU.BP,

                        edi: legacyCPU.EDI,
                        di: legacyCPU.DI,

                        esi: legacyCPU.ESI,
                        si: legacyCPU.SI,

                        esp: legacyCPU.ESP,
                        sp: legacyCPU.SP,

                        eip: legacyCPU.EIP,
                        ip: legacyCPU.IP,

                        cs: legacyCPU.CS,
                        ds: legacyCPU.DS,
                        es: legacyCPU.ES,
                        fs: legacyCPU.FS,
                        gs: legacyCPU.GS,
                        ss: legacyCPU.SS
                    };
                }
            };
        },

        init: function () {
            var emulator = this,
                legacyJemul8 = emulator.legacyJemul8,
                cpu = legacyJemul8.machine.cpu,
                promise = new Promise();

            legacyJemul8.init(function () {
                // Monkey-patch a trap for interrupts
                cpu.interrupt = (function (interrupt) {
                    return function (vector) {
                        emulator.emit("interrupt", vector);
                        interrupt.apply(this, arguments);
                    };
                }(cpu.interrupt));

                emulator.inited = true;
                promise.resolve();
            });

            return promise;
        },

        pause: function () {
            var emulator = this;

            emulator.running = false;
            emulator.legacyJemul8.machine.cpu.pause();
            emulator.emit("pause");

            return emulator;
        },

        run: function () {
            var emulator = this,
                legacyJemul8 = emulator.legacyJemul8,
                legacyCPU = legacyJemul8.machine.cpu,
                promise = new Promise();

            if (!emulator.inited) {
                throw new Exception("Emulator.run() :: Not yet initialized");
            }

            emulator.running = true;
            legacyCPU.halt = (function (halt) {
                return function haltSpy() {
                    promise.resolve();
                    halt.call(legacyCPU);
                };
            }(legacyCPU.halt));
            legacyJemul8.run();

            return promise;
        },

        write: function (options) {
            var data,
                emulator = this,
                offset,
                size,
                to;

            options = options || {};

            if (!hasOwn.call(options, "data")) {
                throw new Exception("Emulator.write() :: 'data' not specified");
            }

            if (!util.isArray(options.data)) {
                throw new Exception("Emulator.write() :: 'data' must be an array");
            }

            if (!hasOwn.call(options, "to")) {
                throw new Exception("Emulator.write() :: 'to' not specified");
            }

            data = options.data;
            size = data.length;
            to = options.to;

            for (offset = 0; offset < size; offset += 1) {
                emulator.legacyJemul8.machine.mem.writePhysical(to + offset, data[offset], 1);
            }

            return emulator;
        }
    });

    return Emulator;
});
<commit_msg>Added comment for existing monkey-patch<commit_after>/**
 * jemul8 - JavaScript x86 Emulator v0.0.1
 * http://jemul8.com/
 *
 * Copyright 2013 jemul8.com (http://github.com/asmblah/jemul8)
 * Released under the MIT license
 * http://jemul8.com/MIT-LICENSE.txt
 */

/*global define */
define([
    "js/util",
    "js/EventEmitter",
    "js/Exception",
    "js/Promise"
], function (
    util,
    EventEmitter,
    Exception,
    Promise
) {
    "use strict";

    var hasOwn = {}.hasOwnProperty;

    function Emulator(legacyJemul8) {
        EventEmitter.call(this);

        this.inited = false;
        this.legacyJemul8 = legacyJemul8;
        this.running = false;
    }

    util.inherit(Emulator).from(EventEmitter);

    util.extend(Emulator.prototype, {
        getCPU: function () {
            var legacyCPU = this.legacyJemul8.machine.cpu;

            return {
                getRegisters: function () {
                    return {
                        eax: legacyCPU.EAX,
                        ax: legacyCPU.AX,
                        al: legacyCPU.AL,
                        ah: legacyCPU.AH,

                        ecx: legacyCPU.ECX,
                        cx: legacyCPU.CX,
                        cl: legacyCPU.CL,
                        ch: legacyCPU.CH,

                        ebx: legacyCPU.EBX,
                        bx: legacyCPU.BX,
                        bl: legacyCPU.BL,
                        bh: legacyCPU.BH,

                        edx: legacyCPU.EDX,
                        dx: legacyCPU.DX,
                        dl: legacyCPU.DL,
                        dh: legacyCPU.DH,

                        ebp: legacyCPU.EBP,
                        bp: legacyCPU.BP,

                        edi: legacyCPU.EDI,
                        di: legacyCPU.DI,

                        esi: legacyCPU.ESI,
                        si: legacyCPU.SI,

                        esp: legacyCPU.ESP,
                        sp: legacyCPU.SP,

                        eip: legacyCPU.EIP,
                        ip: legacyCPU.IP,

                        cs: legacyCPU.CS,
                        ds: legacyCPU.DS,
                        es: legacyCPU.ES,
                        fs: legacyCPU.FS,
                        gs: legacyCPU.GS,
                        ss: legacyCPU.SS
                    };
                }
            };
        },

        init: function () {
            var emulator = this,
                legacyJemul8 = emulator.legacyJemul8,
                cpu = legacyJemul8.machine.cpu,
                promise = new Promise();

            legacyJemul8.init(function () {
                // Monkey-patch a trap for interrupts
                cpu.interrupt = (function (interrupt) {
                    return function (vector) {
                        emulator.emit("interrupt", vector);
                        interrupt.apply(this, arguments);
                    };
                }(cpu.interrupt));

                emulator.inited = true;
                promise.resolve();
            });

            return promise;
        },

        pause: function () {
            var emulator = this;

            emulator.running = false;
            emulator.legacyJemul8.machine.cpu.pause();
            emulator.emit("pause");

            return emulator;
        },

        run: function () {
            var emulator = this,
                legacyJemul8 = emulator.legacyJemul8,
                legacyCPU = legacyJemul8.machine.cpu,
                promise = new Promise();

            if (!emulator.inited) {
                throw new Exception("Emulator.run() :: Not yet initialized");
            }

            emulator.running = true;
            // Monkey-patch a trap for CPU halt
            legacyCPU.halt = (function (halt) {
                return function haltSpy() {
                    promise.resolve();
                    halt.call(legacyCPU);
                };
            }(legacyCPU.halt));
            legacyJemul8.run();

            return promise;
        },

        write: function (options) {
            var data,
                emulator = this,
                offset,
                size,
                to;

            options = options || {};

            if (!hasOwn.call(options, "data")) {
                throw new Exception("Emulator.write() :: 'data' not specified");
            }

            if (!util.isArray(options.data)) {
                throw new Exception("Emulator.write() :: 'data' must be an array");
            }

            if (!hasOwn.call(options, "to")) {
                throw new Exception("Emulator.write() :: 'to' not specified");
            }

            data = options.data;
            size = data.length;
            to = options.to;

            for (offset = 0; offset < size; offset += 1) {
                emulator.legacyJemul8.machine.mem.writePhysical(to + offset, data[offset], 1);
            }

            return emulator;
        }
    });

    return Emulator;
});
<|endoftext|>


<commit_before>var write = require('fs').writeFile
var read = require('fs').readFileSync
var colors = require('irc').colors
var Bitly = require('bitly')
const owo = require('@zuzak/owo')

const plugin = require('../plugins/news')

var oldnews = {}

module.exports = {
  commands: {
    poll: {
      help: 'poll for news',
      privileged: true,
      command: function () {
        plugin.pollApis(true)
        return 'ok'
      }
    },
    clearnews: {
      help: 'Clears the news cache',
      command: function (bot) {
        oldnews = {}
        return 'News cache cleared. Take cover :)'
      }
    },
    corrections: {
      help: 'Sends link to BBC News corrections',
      command: function () {
        return 'http://www.bbc.co.uk/faqs/bbcnews_editorial'
      }
    }
  },
  onload: function () {
    try {
      oldnews = require(__rootdir + '/data/news.json') || {}
    } catch (e) {
      oldnews = {}
    }
  },
  events: {
    /**
     * The rawnews event is defined in plugins/news.js, and triggers on each poll
     * of the BBC News API. Here, we extract useable data from the rather idiosyncratic API
     * and send it to the news event.
     */
    'rawnews:bbc': function (bot, story) {
      if (story && story.headline) {
        bot.fireEvents('news', {
          color: 'dark_red',
          id: 'BBC' + story.assetId,
          text: story.headline,
          url: 'https://bbc.co.uk' + story.assetUri,
          prompt: 'BBC BREAKING'
        })
      }
    },
    'rawnews:reuters': function (bot, story) {
      if (!story.headline) return
      bot.fireEvents('news', {
        color: 'orange',
        id: story.headline,
        prompt: story.label ? story.label : 'Reuters',
        tail: story.tag ? story.tag : null,
        text: story.headline,
        url: story.url ? story.url : null
      })
    },
    'rawnews:mi5': function (bot, feed) {
      const item = feed.items[0]
      bot.fireEvents('news', {
        color: 'light_cyan',
        id: item.guid,
        prompt: feed.feed.title,
        text: item.content,
        url: item.link
      })
    },
    'rawnews:bloomberg': function (bot, stories) {
      for (var i = 0; i < stories.length; i++) {
        var story = stories[i]
        if (story) {
          bot.fireEvents('news', {
            color: 'purple',
            id: 'bbrg' + story.toString(),
            text: JSON.stringify(story),
            url: null,
            prompt: stories.editorialTitle,
            tail: 'Bloomberg (test)'
          })
        }
      }
    },
    'rawnews:reuwire': function (bot, stories) {
      for (let i = 0; i < stories.length; i++) {
        let story = stories[i]
        bot.fireEvents('news', {
          color: 'yellow',
          id: story.id,
          text: story.headline,
          prompt: 'Reuters',
          url: 'http://www.reuters.com' + story.url
        })
      }
    },
    'rawnews:aljaz': function (bot, story) {
      if (story.Alert) {
        for (var i = 0; i < story.AlertText.length; i++) {
          var curr = story.AlertText[0]
          bot.fireEvents('news', {
            color: 'orange',
            id: curr.GUID,
            prompt: 'Al Jazeera ' + curr.Type,
            text: curr.Text,
            url: curr.Url
          })
        }
      }
    },
    news: function (bot, news) {
      console.log('NEWSNEWSNEWS', news)
      if (!oldnews[news.id]) {
        bot.fireEvents('newNews', news)
      }
    },
    newNews: (bot, news) => {
      var bitly = new Bitly(bot.config.get('bitly.username'), bot.config.get('bitly.password'))
      bitly.shorten(news.url, function (err, res) {
        if (err) res = { data: { url: news.url } }
        var str = ''
        if (news.prompt) {
          str += colors.wrap(news.color, news.prompt + ': ')
        }
        // news transform
        try {
          if (bot.config.get('news.replace')) {
            var substitutions = JSON.parse(read(__rootdir + '/data/substitutions.json', { encoding: 'utf-8' }))
            var stringsToReplace = Object.keys(substitutions)
            var newstr = news.text
            for (var i = 0; i < stringsToReplace.length; i++) {
              newstr = newstr.replace(stringsToReplace[i], '\x1f' + substitutions[stringsToReplace[i]] + '\x0f')
            }
            str += newstr
          } else {
            str += news.text
          }
          if (Math.random() <= bot.config.get('news.owo')) {
            str = owo(str)
          }
        } catch (e) {
          str += news.text + '(err)'
        }
        if (res.data.url) {
          str += ' ' + colors.wrap('gray', res.data.url)
        }
        if (news.tail) {
          str += ' ' + colors.wrap('magenta', '(' + news.tail + ')')
        }

        bot.broadcast(str)
      })
      oldnews[news.id] = news
      write(__rootdir + '/data/news.json', JSON.stringify(oldnews))
    }
  }
}
<commit_msg>Use headline + url as BBC News story id<commit_after>var write = require('fs').writeFile
var read = require('fs').readFileSync
var colors = require('irc').colors
var Bitly = require('bitly')
const owo = require('@zuzak/owo')

const plugin = require('../plugins/news')

var oldnews = {}

module.exports = {
  commands: {
    poll: {
      help: 'poll for news',
      privileged: true,
      command: function () {
        plugin.pollApis(true)
        return 'ok'
      }
    },
    clearnews: {
      help: 'Clears the news cache',
      command: function (bot) {
        oldnews = {}
        return 'News cache cleared. Take cover :)'
      }
    },
    corrections: {
      help: 'Sends link to BBC News corrections',
      command: function () {
        return 'http://www.bbc.co.uk/faqs/bbcnews_editorial'
      }
    }
  },
  onload: function () {
    try {
      oldnews = require(__rootdir + '/data/news.json') || {}
    } catch (e) {
      oldnews = {}
    }
  },
  events: {
    /**
     * The rawnews event is defined in plugins/news.js, and triggers on each poll
     * of the BBC News API. Here, we extract useable data from the rather idiosyncratic API
     * and send it to the news event.
     */
    'rawnews:bbc': function (bot, story) {
      if (story && story.headline) {
        bot.fireEvents('news', {
          color: 'dark_red',
          id: 'BBC' + story.headline + story.assetUri,
          text: story.headline,
          url: 'https://bbc.co.uk' + story.assetUri,
          prompt: 'BBC BREAKING'
        })
      }
    },
    'rawnews:reuters': function (bot, story) {
      if (!story.headline) return
      bot.fireEvents('news', {
        color: 'orange',
        id: story.headline,
        prompt: story.label ? story.label : 'Reuters',
        tail: story.tag ? story.tag : null,
        text: story.headline,
        url: story.url ? story.url : null
      })
    },
    'rawnews:mi5': function (bot, feed) {
      const item = feed.items[0]
      bot.fireEvents('news', {
        color: 'light_cyan',
        id: item.guid,
        prompt: feed.feed.title,
        text: item.content,
        url: item.link
      })
    },
    'rawnews:bloomberg': function (bot, stories) {
      for (var i = 0; i < stories.length; i++) {
        var story = stories[i]
        if (story) {
          bot.fireEvents('news', {
            color: 'purple',
            id: 'bbrg' + story.toString(),
            text: JSON.stringify(story),
            url: null,
            prompt: stories.editorialTitle,
            tail: 'Bloomberg (test)'
          })
        }
      }
    },
    'rawnews:reuwire': function (bot, stories) {
      for (let i = 0; i < stories.length; i++) {
        let story = stories[i]
        bot.fireEvents('news', {
          color: 'yellow',
          id: story.id,
          text: story.headline,
          prompt: 'Reuters',
          url: 'http://www.reuters.com' + story.url
        })
      }
    },
    'rawnews:aljaz': function (bot, story) {
      if (story.Alert) {
        for (var i = 0; i < story.AlertText.length; i++) {
          var curr = story.AlertText[0]
          bot.fireEvents('news', {
            color: 'orange',
            id: curr.GUID,
            prompt: 'Al Jazeera ' + curr.Type,
            text: curr.Text,
            url: curr.Url
          })
        }
      }
    },
    news: function (bot, news) {
      console.log('NEWSNEWSNEWS', news)
      if (!oldnews[news.id]) {
        bot.fireEvents('newNews', news)
      }
    },
    newNews: (bot, news) => {
      var bitly = new Bitly(bot.config.get('bitly.username'), bot.config.get('bitly.password'))
      bitly.shorten(news.url, function (err, res) {
        if (err) res = { data: { url: news.url } }
        var str = ''
        if (news.prompt) {
          str += colors.wrap(news.color, news.prompt + ': ')
        }
        // news transform
        try {
          if (bot.config.get('news.replace')) {
            var substitutions = JSON.parse(read(__rootdir + '/data/substitutions.json', { encoding: 'utf-8' }))
            var stringsToReplace = Object.keys(substitutions)
            var newstr = news.text
            for (var i = 0; i < stringsToReplace.length; i++) {
              newstr = newstr.replace(stringsToReplace[i], '\x1f' + substitutions[stringsToReplace[i]] + '\x0f')
            }
            str += newstr
          } else {
            str += news.text
          }
          if (Math.random() <= bot.config.get('news.owo')) {
            str = owo(str)
          }
        } catch (e) {
          str += news.text + '(err)'
        }
        if (res.data.url) {
          str += ' ' + colors.wrap('gray', res.data.url)
        }
        if (news.tail) {
          str += ' ' + colors.wrap('magenta', '(' + news.tail + ')')
        }

        bot.broadcast(str)
      })
      oldnews[news.id] = news
      write(__rootdir + '/data/news.json', JSON.stringify(oldnews))
    }
  }
}
<|endoftext|>


<commit_before>//Creates special single image webpage that is tinted black with a given image in the center of the webpage
//To exit the display click anywhere not on the image itself
function imgAppearOpen(imgSrc) {

//Create image object from href source
var t = new Image();
t.src = $(imgSrc).attr("href");

//Create Fixed Wrapper Div
	jQuery('<div/>', {
		id: 'imgAppear_wrapper',
		css: {
			width: '100%',
			height: '100%',
			position: 'fixed',
			'z-index' : 2,
			top:0,
			left: 0
		}
	}).appendTo('body');

//Creates Shaded Div that tints whole page black
	jQuery('<div/>', {
		id: 'imgAppear_shade',
		css: {
			background: 'black',
			opacity: 0.8,
			width: '100%',
			height: '100%',
			position: 'fixed',
			top: 0,
			left: 0,
			display: 'none',
			'z-index' : 1
			},
			click: function(){
				imgAppearClose();
			}
	}).appendTo('#imgAppear_wrapper').fadeIn('slow', function() {});

//Get the Width and Height of the Browser
var wrapWidth = $('#imgAppear_wrapper').width();
var wrapHeight = $('#imgAppear_wrapper').height();

//Make sure image loads first
t.onload = function(){

	//Calculate the top and bottom height margins, and check if the image has greather width or height than browser
	//Purpose of + 10 is so the close img does not get cut off
	var marginHeight;
	var maxWidth;
	var maxHeight;

	if (wrapHeight > t.height + 10)
	{
		marginHeight = (wrapHeight - t.height)/2;
		maxHeight = t.height + 10;
	}
	else
	{
		marginHeight = 0;
		maxHeight = wrapHeight
	}

	if (wrapWidth > t.width + 10)
	{
		maxWidth = t.width + 10;
	}
	else
	{
		maxWidth = wrapWidth ;
	}
	//Div that holds the image to be displayed
		jQuery('<div/>', {
			id: 'imgAppear_img',
			css: {
				position: 'relative',
				overflow: 'auto',
				width:maxWidth,
				height: maxHeight,
				margin: '0 auto',
				'margin-top': marginHeight,
				'z-index' : 3
			}
		}).appendTo('#imgAppear_wrapper');

		//Main image to be displayed
//		$('#imgAppear_img').append(t).fadeIn('slow', function() {});

		jQuery(t, {
			id: 'imgAppear_img_img',
			css: {
				position: 'relative',
				top: 5,
				display : 'none',
				'z-index' : 2
			}
		}).appendTo('#imgAppear_img').fadeIn('slow', function() {});

		//Close Button Image
		jQuery('<img/>', {
			id: 'imgAppear_close_img',
			src: 'imgAppear/close.png',
			css: {
				position: 'absolute',
				left: t.width,
				top: 5,
				'margin-left' : '-8px',
				'margin-top' :'-4px',
				display : 'none',
				cursor: 'pointer',
				'z-index' : 2
			},
			click: function(){
				imgAppearClose();
			}
		}).appendTo('#imgAppear_img').fadeIn('slow', function() {});
	};
	return false;
}

//Removes all created divs and images from HTML
function imgAppearClose() {

	$("#imgAppear_wrapper").fadeOut("slow", function () {	$("#imgAppear_wrapper").remove(); });
	return true;
}
<commit_msg>Fixed unloading image problem<commit_after>//Creates special single image webpage that is tinted black with a given image in the center of the webpage
//To exit the display click anywhere not on the image itself
function imgAppearOpen(imgSrc) {

//Create image object from href source
var t = new Image();
t.src = $(imgSrc).attr("href");
t.id = "imgAppear_img";
//Create Fixed Wrapper Div
	jQuery('<div/>', {
		id: 'imgAppear_wrapper',
		css: {
			width: '100%',
			height: '100%',
			position: 'fixed',
			'z-index' : 2,
			top:0,
			left: 0
		}
	}).appendTo('body');

//Creates Shaded Div that tints whole page black
	jQuery('<div/>', {
		id: 'imgAppear_shade',
		css: {
			background: 'black',
			opacity: 0.8,
			width: '100%',
			height: '100%',
			position: 'fixed',
			top: 0,
			left: 0,
			display: 'none',
			'z-index' : 1
			},
			click: function(){
				imgAppearClose();
			}
	}).appendTo('#imgAppear_wrapper').fadeIn('slow', function() {});

//Get the Width and Height of the Browser
var wrapWidth = $('#imgAppear_wrapper').width();
var wrapHeight = $('#imgAppear_wrapper').height();

//Make sure image loads first
t.onload = function(){

	//Calculate the top and bottom height margins, and check if the image has greather width or height than browser
	//Purpose of + 10 is so the close img does not get cut off
	var marginHeight;
	var maxWidth;
	var maxHeight;

	if (wrapHeight > t.height + 10)
	{
		marginHeight = (wrapHeight - t.height)/2;
		maxHeight = t.height + 10;
	}
	else
	{
		marginHeight = 0;
		maxHeight = wrapHeight
	}

	if (wrapWidth > t.width + 10)
	{
		maxWidth = t.width + 10;
	}
	else
	{
		maxWidth = wrapWidth ;
	}
	//Div that holds the image to be displayed
		jQuery('<div/>', {
			id: 'imgAppear_img',
			css: {
				position: 'relative',
				overflow: 'auto',
				width:maxWidth,
				height: maxHeight,
				margin: '0 auto',
				'margin-top': marginHeight,
				'z-index' : 3
			}
		}).appendTo('#imgAppear_wrapper');

		//Main image to be displayed
//		$('#imgAppear_img').append(t).fadeIn('slow', function() {});

		jQuery(t).css({
				position: 'relative',
				top: 5,
				display : 'none',
				'z-index' : 2
			}).appendTo('#imgAppear_img').fadeIn('slow', function() {});

		//Close Button Image
		jQuery('<img/>', {
			id: 'imgAppear_close_img',
			src: 'imgAppear/close.png',
			css: {
				position: 'absolute',
				left: t.width,
				top: 5,
				'margin-left' : '-8px',
				'margin-top' :'-4px',
				display : 'none',
				cursor: 'pointer',
				'z-index' : 2
			},
			click: function(){
				imgAppearClose();
			}
		}).appendTo('#imgAppear_img').fadeIn('slow', function() {});
	};
	return false;
}

//Removes all created divs and images from HTML
function imgAppearClose() {

	$("#imgAppear_wrapper").fadeOut("slow", function () {	$("#imgAppear_wrapper").remove(); });
	return true;
}
<|endoftext|>