<commit_before>
var fs = require('fs');
var exec = require ('child_process').exec;
var async = require ("async");
var app_path, ssh_file, local, email;
var i = 0;
var prompt = require ("prompt");
var config = {};

async.waterfall ([

    function (done){
        // Installs the whole setup
        console.log ("\n\nWELCOME TO THE NODE-AWS-DEPLOY INSTALLER");
        console.log ("This installs your application onto AWS and allows automatic deployment just by pushing to your remote git repository." +
            " Just answer a few questions and everything will be setup");
        prompt.start ();
        done ();
    },

    function (done){
        console.log (++i + ") Is this a 'remote' install? (If this is on a remote server the answer is y)");
        prompt.get (['(y/n)'], function (err, results){
            var answer = (results['(y/n)'] === 'y');
            local = !answer;
            config.sudo = (local) ? "" : "sudo";
            done ();
        });
    },

    function (done){
        console.log (++i + ") Enter your desired application's full path. (no file names. Example  '/home/ec2-user//MyCoolApplication')");
        prompt.get (['folder'], function (err, results){
            var answer = results['folder'];
            config.applicationDirectory = answer;
            try{
                fs.mkdir (answer, function (err){
                    app_path = answer;
                    done ();
                });
            }
            catch (err){
                done ();
            }
        });
    },

    function (done){
        console.log (++i + ") Enter your application's name");
        prompt.get (['name'], function (err, results){
            config.applicationName = results['name'];
            done ();
        });
    },
    function (done){
        console.log (++i + ") Enter your application's entry point (defaults to 'start.js')");
        prompt.get (['entry point'], function(err, results) {
            config.appEntry = results['entry point'];
            done ();
        });
    },
    function (done){
        if (local){
            console.log ("Please take a second ensure you are set up to clone your repository. This might require you to create an ssh key pair or simply use credentials.");
            console.log ("When you have your repository cloned press <enter> to continue.");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Enter your email address to seed the ssh key");
            prompt.get (['email'], function(err, results) {
                email = results['email'];
                done ();
            });
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            // go get the ssh key or create one if it doesn't exist
            try { ssh_file = fs.readFileSync ("/root/.ssh/id_rsa.pub");}
            catch (err) {ssh_file = null; console.log (err);}
            if (!ssh_file){
                console.log ("/tssh key not generated, generating a new one.");
                var child = exec ('sudo ssh-keygen -t rsa -C "' + email + '"', function (err, std, ster){
console.log ("debug here: err:%j, std:%j, ster:%j", err, std, ster);
                    if (err){done (err);}
                    else{
                        ssh_file = fs.readFileSync ("/root/.ssh/id_rsa.pub");
                        done ();
                    }
                });
            }
            else{
                console.log ("/tssh key already generated!");
                done ();
            }
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            console.log(++i + ") Please take a second to copy the ssh key from this server, listed below, and paste into your git repository service (such as github). This will authorize this server AMI to " +
                "clone your repository and perform git pulls. Press <enter> when done.");
            console.log ("\n" + ssh_file + "\n");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Now that your Git repository has been configured, enter the ssh url for remote access so this server can clone it:");
            prompt.get (['Git repository URL'], function (err, results){
                var git_url = results['Git repository URL'];
                if (git_url){
                    console.log ("  Cloning your repository...");
                    var child = exec ('cd ' + config.applicationDirectory + ' ; cd .. ; ' + config.sudo + ' git clone ' + git_url, function (err, std, ster){
                        if (err){
                            done (err);
                        }
                        else{
                            console.log (std);
                            done ();
                        }
                    });
                }
                else{
                    done ();
                }
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Enter the pull information, what triggers it how its configured, etc...");
            console.log ("\t pullPort: <set this to the port for a pull requests> - defaults to 8000");
            console.log ("\t pullKey: <path to a ssh key file for the HTTPS Server>");
            console.log ("\t pullCert: <path to a ssh cert file for the HTTPS Server>");
            console.log ("\t pullCa: <array of paths to the certificate authority files> (optional)");
            console.log ("\t pullPassphrase: <string - phrase that the certificate was generated with> (optional)");
            console.log ("\t pullSecret: <secret phrase that this server uses to identify as a valid pull request> (optional))");
            console.log ("\t pullBranch: <the branch that this server should pull from on pull requests> (defaults to master))");
            prompt.get (["pullPort", "pullKey", "pullCert", "pullCa", "pullPassphrase", "pullSecret", "pullBranch"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    },
    function (done) {
        if (!local){
            console.log (++i + ") Enter AWS SDK Information so that this server can talk to others on a pull request");
            console.log ("\t accessKeyId: <AWS API Access key 'XXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t secretAccessKey: <AWS Secret Access key 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t region: <aws region that the servers are located in. EX 'us-east-1'>");
            prompt.get (["accessKeyId", "secretAccessKey", "region"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    }

], function (err){
    if (!err){
        var data = JSON.stringify (config);
        fs.writeFileSync ("app-config.json", data);
        console.log ("Success installed: " + config.applicationName + ". The Configuration has been written out to app-config.json");
        console.log ("To Launch the application type 'sudo start node-aws-deploy'");
        process.exit (0);
    }
    else{
        console.log ("There were errors. Errors:" + err);
        process.exit (1);
    }
});

<commit_msg>Initial<commit_after>
var fs = require('fs');
var exec = require ('child_process').exec;
var async = require ("async");
var app_path, ssh_file, local, email;
var i = 0;
var prompt = require ("prompt");
var config = {};

async.waterfall ([

    function (done){
        // Installs the whole setup
        console.log ("\n\nWELCOME TO THE NODE-AWS-DEPLOY INSTALLER");
        console.log ("This installs your application onto AWS and allows automatic deployment just by pushing to your remote git repository." +
            " Just answer a few questions and everything will be setup");
        prompt.start ();
        done ();
    },

    function (done){
        console.log (++i + ") Is this a 'remote' install? (If this is on a remote server the answer is y)");
        prompt.get (['(y/n)'], function (err, results){
            var answer = (results['(y/n)'] === 'y');
            local = !answer;
            config.sudo = (local) ? "" : "sudo";
            done ();
        });
    },

    function (done){
        console.log (++i + ") Enter your desired application's full path. (no file names. Example  '/home/ec2-user//MyCoolApplication')");
        prompt.get (['folder'], function (err, results){
            var answer = results['folder'];
            config.applicationDirectory = answer;
            try{
                fs.mkdir (answer, function (err){
                    app_path = answer;
                    done ();
                });
            }
            catch (err){
                done ();
            }
        });
    },

    function (done){
        console.log (++i + ") Enter your application's name");
        prompt.get (['name'], function (err, results){
            config.applicationName = results['name'];
            done ();
        });
    },
    function (done){
        console.log (++i + ") Enter your application's entry point (defaults to 'start.js')");
        prompt.get (['entry point'], function(err, results) {
            config.appEntry = results['entry point'];
            done ();
        });
    },
    function (done){
        if (local){
            console.log ("Please take a second ensure you are set up to clone your repository. This might require you to create an ssh key pair or simply use credentials.");
            console.log ("When you have your repository cloned press <enter> to continue.");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Enter your email address to seed the ssh key");
            prompt.get (['email'], function(err, results) {
                email = results['email'];
                done ();
            });
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            // go get the ssh key or create one if it doesn't exist
            try { ssh_file = fs.readFileSync ("/home/ec2-user/.ssh/id_rsa.pub");}
            catch (err) {ssh_file = null; console.log (err);}
            if (!ssh_file){
                console.log ("/tssh key not generated, generating a new one.");
                var child = exec ('ssh-keygen -t rsa -C "' + email + '"', function (err, std, ster){
console.log ("debug here: err:%j, std:%j, ster:%j", err, std, ster);
                    if (err){done (err);}
                    else{
                        ssh_file = fs.readFileSync ("/home/ec2-user/.ssh/id_rsa.pub");
                        done ();
                    }
                });
            }
            else{
                console.log ("/tssh key already generated!");
                done ();
            }
        }
        else{
            done ();
        }
    },

    function (done){
        if (!local){
            console.log(++i + ") Please take a second to copy the ssh key from this server, listed below, and paste into your git repository service (such as github). This will authorize this server AMI to " +
                "clone your repository and perform git pulls. Press <enter> when done.");
            console.log ("\n" + ssh_file + "\n");
            prompt.get (['<enter>'], function(err, results) {
                done ();
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Now that your Git repository has been configured, enter the ssh url for remote access so this server can clone it:");
            prompt.get (['Git repository URL'], function (err, results){
                var git_url = results['Git repository URL'];
                if (git_url){
                    console.log ("  Cloning your repository...");
                    var child = exec ('cd ' + config.applicationDirectory + ' ; cd .. ; ' + config.sudo + ' git clone ' + git_url, function (err, std, ster){
                        if (err){
                            done (err);
                        }
                        else{
                            console.log (std);
                            done ();
                        }
                    });
                }
                else{
                    done ();
                }
            });
        }
        else{
            done ();
        }
    },
    function (done){
        if (!local){
            console.log (++i + ") Enter the pull information, what triggers it how its configured, etc...");
            console.log ("\t pullPort: <set this to the port for a pull requests> - defaults to 8000");
            console.log ("\t pullKey: <path to a ssh key file for the HTTPS Server>");
            console.log ("\t pullCert: <path to a ssh cert file for the HTTPS Server>");
            console.log ("\t pullCa: <array of paths to the certificate authority files> (optional)");
            console.log ("\t pullPassphrase: <string - phrase that the certificate was generated with> (optional)");
            console.log ("\t pullSecret: <secret phrase that this server uses to identify as a valid pull request> (optional))");
            console.log ("\t pullBranch: <the branch that this server should pull from on pull requests> (defaults to master))");
            prompt.get (["pullPort", "pullKey", "pullCert", "pullCa", "pullPassphrase", "pullSecret", "pullBranch"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    },
    function (done) {
        if (!local){
            console.log (++i + ") Enter AWS SDK Information so that this server can talk to others on a pull request");
            console.log ("\t accessKeyId: <AWS API Access key 'XXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t secretAccessKey: <AWS Secret Access key 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'>");
            console.log ("\t region: <aws region that the servers are located in. EX 'us-east-1'>");
            prompt.get (["accessKeyId", "secretAccessKey", "region"], function (err, results){
                for (var k in results){
                    config[k] = results[k];
                }
                done ();
            });

        }
        else{
            done ();
        }
    }

], function (err){
    if (!err){
        var data = JSON.stringify (config);
        fs.writeFileSync ("app-config.json", data);
        console.log ("Success installed: " + config.applicationName + ". The Configuration has been written out to app-config.json");
        console.log ("To Launch the application type 'sudo start node-aws-deploy'");
        process.exit (0);
    }
    else{
        console.log ("There were errors. Errors:" + err);
        process.exit (1);
    }
});

<|endoftext|>


<commit_before>const $ = require('jquery');
const co = require('co');

const constants = require('../common/constants.js');
const ga = require('../common/ga.js');

const lastVersionKey = 'lastVersion';
const serviceUrl = `https://${constants.hostname}`;

chrome.runtime.onInstalled.addListener(details => {
    const manifest = chrome.runtime.getManifest();
    if (details.reason == 'install') {
        chrome.tabs.create({ url: `${serviceUrl}/${process.env.PRODUCT}/welcome` });
    }
    else if (details.reason == 'update') {
        const lastVersion = localStorage.getItem(lastVersionKey);
        const currentVersion = manifest.version;

        // the following comparison implicitly ignores the C in A.B.C, due to
        // the way that parseFloat works
        if (!lastVersion || parseFloat(currentVersion) > parseFloat(lastVersion)) {
            chrome.tabs.create({ url: chrome.runtime.getURL(`html/changelog.html`) });
        }
    }
    localStorage.setItem(lastVersionKey, manifest.version);
});

function messageListener(handler) {
    chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
        console.log('Handling message:', req);
        co(handler(req, sender))
        .then(data => {
            const response = { data };
            console.log('Success handling message:', req, "response", response);
            sendResponse(response);
        })
        .catch(error => {
            let response = null;
            if (typeof error.status == 'undefined' && error.statusText)
                response = { status: error.status, error: error.statusText };
            else
                response = { status: error.message, error };
            ga.merror(req, error);
            console.log('Error handling message:', req, 'response', response);
            sendResponse(response);
        });

        return true;
    });
}

function* getUser() {
    return yield $.ajax(`${serviceUrl}/api/user`, {
        method: 'GET',
        dataType: 'json'
    });
}

module.exports = {
    serviceUrl,
    messageListener,
    getUser,
};
<commit_msg>added event reporting for background-message handling<commit_after>const $ = require('jquery');
const co = require('co');

const constants = require('../common/constants.js');
const ga = require('../common/ga.js');

const lastVersionKey = 'lastVersion';
const serviceUrl = `https://${constants.hostname}`;

chrome.runtime.onInstalled.addListener(details => {
    const manifest = chrome.runtime.getManifest();
    if (details.reason == 'install') {
        chrome.tabs.create({ url: `${serviceUrl}/${process.env.PRODUCT}/welcome` });
    }
    else if (details.reason == 'update') {
        const lastVersion = localStorage.getItem(lastVersionKey);
        const currentVersion = manifest.version;

        // the following comparison implicitly ignores the C in A.B.C, due to
        // the way that parseFloat works
        if (!lastVersion || parseFloat(currentVersion) > parseFloat(lastVersion)) {
            chrome.tabs.create({ url: chrome.runtime.getURL(`html/changelog.html`) });
        }
    }
    localStorage.setItem(lastVersionKey, manifest.version);
});

function messageListener(handler) {
    chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
        console.log('Handling message:', req);
        ga.mga('event', 'background-message', req.action);

        co(handler(req, sender))
        .then(data => {
            const response = { data };
            console.log('Success handling message:', req, "response", response);
            sendResponse(response);
        })
        .catch(error => {
            let response = null;
            if (typeof error.status == 'undefined' && error.statusText)
                response = { status: error.status, error: error.statusText };
            else
                response = { status: error.message, error };
            ga.merror(req, error);
            console.log('Error handling message:', req, 'response', response);
            sendResponse(response);
        });

        return true;
    });
}

function* getUser() {
    return yield $.ajax(`${serviceUrl}/api/user`, {
        method: 'GET',
        dataType: 'json'
    });
}

module.exports = {
    serviceUrl,
    messageListener,
    getUser,
};
<|endoftext|>


<commit_before>/**
 * Created by quasarchimaere on 29.11.2018.
 */
import { actionTypes } from "../actions/actions.js";
import Immutable from "immutable";
import { get, getIn } from "../utils.js";

const initialState = Immutable.fromJS({
  debugMode: false,
  showRdf: false,
  showClosedAtoms: false,
  showMainMenu: false,
  showMenu: false,
  showAddMessageContent: false,
  selectedAddMessageContent: undefined,
  showModalDialog: false,
  modalDialog: undefined,
  anonymousSlideIn: {
    visible: false,
    showEmailInput: false,

    linkSent: false,
    linkCopied: false,
  },
  showSlideIns: true,
  atoms: new Immutable.Map(),
  locationAccessDenied: false,
  currentLocation: undefined,
});

const initialAtomState = Immutable.fromJS({
  showGeneralInfo: false,
  visibleTab: "DETAIL",
});

export default function(viewState = initialState, action = {}) {
  switch (action.type) {
    case actionTypes.view.locationAccessDenied:
      return viewState.set("locationAccessDenied", true);

    case actionTypes.lostConnection:
      return viewState.set("showSlideIns", true);

    case actionTypes.view.toggleSlideIns:
      return viewState.set("showSlideIns", !viewState.get("showSlideIns"));

    case actionTypes.account.loginFailed:
    case actionTypes.view.showMainMenu:
      return viewState.set("showMainMenu", true);

    case actionTypes.view.showMenu:
      return viewState.set("showMenu", true);

    case actionTypes.view.hideMenu:
      return viewState.set("showMenu", false);

    case actionTypes.view.toggleMenu: {
      return viewState.set("showMenu", !viewState.get("showMenu"));
    }

    case actionTypes.account.reset:
      return initialState;

    case actionTypes.account.store:
    case actionTypes.view.hideMainMenu: {
      if (action.payload) {
        const emailVerified = action.payload.get("emailVerified");
        const acceptedTermsOfService = action.payload.get(
          "acceptedTermsOfService"
        );

        const isAnonymous = action.payload.get("isAnonymous");

        if (isAnonymous || !emailVerified || !acceptedTermsOfService) {
          viewState = viewState.set("showSlideIns", true);
        }
      }

      return viewState.set("showMainMenu", false);
    }

    case actionTypes.view.updateCurrentLocation:
      return viewState.set("currentLocation", action.payload.get("location"));

    case actionTypes.view.toggleRdf:
      return viewState
        .set("showRdf", !viewState.get("showRdf"))
        .set("showMainMenu", false);

    case actionTypes.view.toggleDebugMode:
      return viewState.set("debugMode", action.payload);

    case actionTypes.view.toggleClosedAtoms:
      return viewState.set(
        "showClosedAtoms",
        !viewState.get("showClosedAtoms")
      );

    case actionTypes.view.toggleAddMessageContent:
      return viewState
        .set("showAddMessageContent", !viewState.get("showAddMessageContent"))
        .set("selectedAddMessageContent", undefined);

    case actionTypes.view.selectAddMessageContent: {
      const selectedDetail = getIn(action, ["payload", "selectedDetail"]);
      return viewState
        .set("selectedAddMessageContent", selectedDetail)
        .set("showAddMessageContent", true);
    }

    case actionTypes.view.hideAddMessageContent:
      return viewState
        .set("showAddMessageContent", false)
        .set("selectedAddMessageContent", undefined);

    case actionTypes.view.removeAddMessageContent:
      return viewState.set("selectedAddMessageContent", undefined);

    case actionTypes.view.showTermsDialog: {
      const payload = Immutable.fromJS(action.payload);

      const acceptCallback = get(payload, "acceptCallback");
      const cancelCallback = get(payload, "cancelCallback");

      const termsDialog = Immutable.fromJS({
        showTerms: true,
        buttons: [
          {
            caption: "Yes, I accept ToS",
            callback: acceptCallback,
          },
          {
            caption: "No, cancel",
            callback: cancelCallback,
          },
        ],
      });
      return viewState
        .set("showModalDialog", true)
        .set("modalDialog", termsDialog);
    }

    case actionTypes.view.showModalDialog: {
      const modalDialog = Immutable.fromJS(action.payload);
      return viewState
        .set("showModalDialog", true)
        .set("modalDialog", modalDialog);
    }

    case actionTypes.view.hideModalDialog:
      return viewState
        .set("showModalDialog", false)
        .set("modalDialog", undefined);

    case actionTypes.view.anonymousSlideIn.hide:
      return viewState
        .setIn(["anonymousSlideIn", "visible"], false)
        .setIn(["anonymousSlideIn", "linkSent"], false)
        .setIn(["anonymousSlideIn", "linkCopied"], false)
        .setIn(["anonymousSlideIn", "showEmailInput"], false)
        .set("showSlideIns", false);

    case actionTypes.view.anonymousSlideIn.showEmailInput:
      return viewState.setIn(["anonymousSlideIn", "showEmailInput"], true);

    case actionTypes.account.sendAnonymousLinkEmailSuccess:
      return viewState
        .setIn(["anonymousSlideIn", "linkSent"], true)
        .setIn(["anonymousSlideIn", "linkCopied"], false);

    case actionTypes.account.copiedAnonymousLinkSuccess:
      return viewState
        .setIn(["anonymousSlideIn", "linkCopied"], true)
        .setIn(["anonymousSlideIn", "linkSent"], false);

    case actionTypes.atoms.selectTab: {
      const atomUri = action.payload.get("atomUri");
      const selectTab = action.payload.get("selectTab");

      return viewState.updateIn(
        ["atoms", atomUri],
        initialAtomState,
        atomState => atomState.update("visibleTab", () => selectTab)
      );
    }

    default:
      return viewState;
  }
}
<commit_msg>Fixes atom-menu click issue<commit_after>/**
 * Created by quasarchimaere on 29.11.2018.
 */
import { actionTypes } from "../actions/actions.js";
import Immutable from "immutable";
import { get, getIn } from "../utils.js";

const initialState = Immutable.fromJS({
  debugMode: false,
  showRdf: false,
  showClosedAtoms: false,
  showMainMenu: false,
  showMenu: false,
  showAddMessageContent: false,
  selectedAddMessageContent: undefined,
  showModalDialog: false,
  modalDialog: undefined,
  anonymousSlideIn: {
    visible: false,
    showEmailInput: false,

    linkSent: false,
    linkCopied: false,
  },
  showSlideIns: true,
  atoms: new Immutable.Map(),
  locationAccessDenied: false,
  currentLocation: undefined,
});

const initialAtomState = Immutable.fromJS({
  visibleTab: "DETAIL",
});

export default function(viewState = initialState, action = {}) {
  switch (action.type) {
    case actionTypes.view.locationAccessDenied:
      return viewState.set("locationAccessDenied", true);

    case actionTypes.lostConnection:
      return viewState.set("showSlideIns", true);

    case actionTypes.view.toggleSlideIns:
      return viewState.set("showSlideIns", !viewState.get("showSlideIns"));

    case actionTypes.account.loginFailed:
    case actionTypes.view.showMainMenu:
      return viewState.set("showMainMenu", true);

    case actionTypes.view.showMenu:
      return viewState.set("showMenu", true);

    case actionTypes.view.hideMenu:
      return viewState.set("showMenu", false);

    case actionTypes.view.toggleMenu: {
      return viewState.set("showMenu", !viewState.get("showMenu"));
    }

    case actionTypes.account.reset:
      return initialState;

    case actionTypes.account.store:
    case actionTypes.view.hideMainMenu: {
      if (action.payload) {
        const emailVerified = action.payload.get("emailVerified");
        const acceptedTermsOfService = action.payload.get(
          "acceptedTermsOfService"
        );

        const isAnonymous = action.payload.get("isAnonymous");

        if (isAnonymous || !emailVerified || !acceptedTermsOfService) {
          viewState = viewState.set("showSlideIns", true);
        }
      }

      return viewState.set("showMainMenu", false);
    }

    case actionTypes.view.updateCurrentLocation:
      return viewState.set("currentLocation", action.payload.get("location"));

    case actionTypes.view.toggleRdf:
      return viewState
        .set("showRdf", !viewState.get("showRdf"))
        .set("showMainMenu", false);

    case actionTypes.view.toggleDebugMode:
      return viewState.set("debugMode", action.payload);

    case actionTypes.view.toggleClosedAtoms:
      return viewState.set(
        "showClosedAtoms",
        !viewState.get("showClosedAtoms")
      );

    case actionTypes.view.toggleAddMessageContent:
      return viewState
        .set("showAddMessageContent", !viewState.get("showAddMessageContent"))
        .set("selectedAddMessageContent", undefined);

    case actionTypes.view.selectAddMessageContent: {
      const selectedDetail = getIn(action, ["payload", "selectedDetail"]);
      return viewState
        .set("selectedAddMessageContent", selectedDetail)
        .set("showAddMessageContent", true);
    }

    case actionTypes.view.hideAddMessageContent:
      return viewState
        .set("showAddMessageContent", false)
        .set("selectedAddMessageContent", undefined);

    case actionTypes.view.removeAddMessageContent:
      return viewState.set("selectedAddMessageContent", undefined);

    case actionTypes.view.showTermsDialog: {
      const payload = Immutable.fromJS(action.payload);

      const acceptCallback = get(payload, "acceptCallback");
      const cancelCallback = get(payload, "cancelCallback");

      const termsDialog = Immutable.fromJS({
        showTerms: true,
        buttons: [
          {
            caption: "Yes, I accept ToS",
            callback: acceptCallback,
          },
          {
            caption: "No, cancel",
            callback: cancelCallback,
          },
        ],
      });
      return viewState
        .set("showModalDialog", true)
        .set("modalDialog", termsDialog);
    }

    case actionTypes.view.showModalDialog: {
      const modalDialog = Immutable.fromJS(action.payload);
      return viewState
        .set("showModalDialog", true)
        .set("modalDialog", modalDialog);
    }

    case actionTypes.view.hideModalDialog:
      return viewState
        .set("showModalDialog", false)
        .set("modalDialog", undefined);

    case actionTypes.view.anonymousSlideIn.hide:
      return viewState
        .setIn(["anonymousSlideIn", "visible"], false)
        .setIn(["anonymousSlideIn", "linkSent"], false)
        .setIn(["anonymousSlideIn", "linkCopied"], false)
        .setIn(["anonymousSlideIn", "showEmailInput"], false)
        .set("showSlideIns", false);

    case actionTypes.view.anonymousSlideIn.showEmailInput:
      return viewState.setIn(["anonymousSlideIn", "showEmailInput"], true);

    case actionTypes.account.sendAnonymousLinkEmailSuccess:
      return viewState
        .setIn(["anonymousSlideIn", "linkSent"], true)
        .setIn(["anonymousSlideIn", "linkCopied"], false);

    case actionTypes.account.copiedAnonymousLinkSuccess:
      return viewState
        .setIn(["anonymousSlideIn", "linkCopied"], true)
        .setIn(["anonymousSlideIn", "linkSent"], false);

    case actionTypes.atoms.selectTab: {
      const atomUri = action.payload.get("atomUri");
      const selectTab = action.payload.get("selectTab");

      const atomState = viewState.getIn(["atoms", atomUri]) || initialAtomState;

      return viewState.setIn(
        ["atoms", atomUri],
        atomState.set("visibleTab", selectTab)
      );
    }

    default:
      return viewState;
  }
}
<|endoftext|>


<commit_before>'use strict';

const db = require('../db');
const dbConnectionHandling = require('./dbConnectionHandling');

const createCommitment = function (commitmentId, data) {
    data.title = data.title || `commitment${commitmentId}Title`;
    data.description = data.description || `commitment${commitmentId}Description`;
    data.website = data.website || null;
    data.modified = data.modified || null;
    data.modifiedAddress = data.modifiedAddress || data.created;
    data.importTC = data.importTC ? ':ImportTC' : '';
    data.regions = data.regions || null;
    dbConnectionHandling.getCommands().push(db.cypher().match("(user:User {userId: {adminId}})")
        .create(`(user)-[:IS_ADMIN]->(commitment:Commitment${data.importTC} {title: {title}, language: {language}, description: {description}, modified: {modified}, modifiedAddress: {modifiedAddress},
        created: {created}, commitmentId: {commitmentId}, website: {website}})`)
        .with(`commitment, user`)
        .merge(`(user)-[:IS_CREATOR]->(commitment)`)
        .with(`commitment`)
        .foreach(`(topic IN {topics} | MERGE (:Topic {name: topic}))`)
        .with(`commitment`)
        .match(`(topic:Topic)`)
        .where(`topic.name IN {topics}`)
        .merge(`(topic)-[:TOPIC]->(commitment)`)
        .with(`commitment`)
        .match(`(region:Region)`)
        .where(`region.code IN {regions}`)
        .merge(`(region)<-[:BELONGS_TO_REGION]-(commitment)`)
        .end({
            commitmentId: commitmentId,
            adminId: data.adminId,
            title: data.title,
            description: data.description,
            language: data.language,
            topics: data.topics,
            created: data.created,
            modified: data.modified,
            modifiedAddress: data.modifiedAddress,
            website: data.website,
            regions: data.regions
        }).getCommand());
};

const createEvent = function (data) {
    data.title = data.title || `event${data.eventId}Title`;
    data.description = data.description || `event${data.eventId}Description`;
    data.location = data.location || `event${data.eventId}Location`;
    data.uid = data.description || `${data.eventId}@elyoos.org`;
    data.created = data.created || 500;
    data.modified = data.modified || null;

    dbConnectionHandling.getCommands().push(db.cypher().match(`(commitment:Commitment {commitmentId: {commitmentId}})`)
        .create(`(commitment)-[:EVENT]->(event:Event {eventId: {eventId}, uid: {uid}, title: {title}, description: {description},
                 location: {location}, startDate: {startDate}, endDate: {endDate}, modified: {modified}})`)
        .with(`event`)
        .match(`(region:Region {code: {region}})`)
        .merge(`(event)-[:BELONGS_TO_REGION]->(region)`)
        .end({
            commitmentId: data.commitmentId, eventId: data.eventId, uid: data.uid, title: data.title,
            description: data.description, startDate: data.startDate, endDate: data.endDate, created: data.created,
            modified: data.modified, region: data.region, location: data.location
        }).getCommand());
};

const showQuestionOnCommitment = function (data) {
    dbConnectionHandling.getCommands().push(db.cypher()
        .match(`(c:Commitment {commitmentId: {commitmentId}}), (q:Question {questionId: {questionId}})`)
        .merge(`(q)<-[:SHOW_QUESTION]-(c)`)
        .end({commitmentId: data.commitmentId, questionId: data.questionId}).getCommand());
};

const watchCommitment = function (data) {
    data.created = data.created || 555;
    dbConnectionHandling.getCommands().push(db.cypher()
        .match(`(c:Commitment {commitmentId: {commitmentId}}), (u:User {userId: {userId}})`)
        .merge(`(c)<-[:WATCH {created: {created}}]-(u)`)
        .end({commitmentId: data.commitmentId, userId: data.userId, created: data.created}).getCommand());
};

module.exports = {
    createCommitment,
    createEvent,
    showQuestionOnCommitment,
    watchCommitment
};<commit_msg>Created property added.<commit_after>'use strict';

const db = require('../db');
const dbConnectionHandling = require('./dbConnectionHandling');

const createCommitment = function (commitmentId, data) {
    data.title = data.title || `commitment${commitmentId}Title`;
    data.description = data.description || `commitment${commitmentId}Description`;
    data.website = data.website || null;
    data.modified = data.modified || null;
    data.modifiedAddress = data.modifiedAddress || data.created;
    data.importTC = data.importTC ? ':ImportTC' : '';
    data.regions = data.regions || null;
    dbConnectionHandling.getCommands().push(db.cypher().match("(user:User {userId: {adminId}})")
        .create(`(user)-[:IS_ADMIN]->(commitment:Commitment${data.importTC} {title: {title}, language: {language}, description: {description}, modified: {modified}, modifiedAddress: {modifiedAddress},
        created: {created}, commitmentId: {commitmentId}, website: {website}})`)
        .with(`commitment, user`)
        .merge(`(user)-[:IS_CREATOR]->(commitment)`)
        .with(`commitment`)
        .foreach(`(topic IN {topics} | MERGE (:Topic {name: topic}))`)
        .with(`commitment`)
        .match(`(topic:Topic)`)
        .where(`topic.name IN {topics}`)
        .merge(`(topic)-[:TOPIC]->(commitment)`)
        .with(`commitment`)
        .match(`(region:Region)`)
        .where(`region.code IN {regions}`)
        .merge(`(region)<-[:BELONGS_TO_REGION]-(commitment)`)
        .end({
            commitmentId: commitmentId,
            adminId: data.adminId,
            title: data.title,
            description: data.description,
            language: data.language,
            topics: data.topics,
            created: data.created,
            modified: data.modified,
            modifiedAddress: data.modifiedAddress,
            website: data.website,
            regions: data.regions
        }).getCommand());
};

const createEvent = function (data) {
    data.title = data.title || `event${data.eventId}Title`;
    data.description = data.description || `event${data.eventId}Description`;
    data.location = data.location || `event${data.eventId}Location`;
    data.uid = data.description || `${data.eventId}@elyoos.org`;
    data.created = data.created || 500;
    data.modified = data.modified || null;

    dbConnectionHandling.getCommands().push(db.cypher().match(`(commitment:Commitment {commitmentId: {commitmentId}})`)
        .create(`(commitment)-[:EVENT]->(event:Event {eventId: {eventId}, uid: {uid}, title: {title}, description: {description},
                 location: {location}, startDate: {startDate}, endDate: {endDate}, created: {created}, modified: {modified}})`)
        .with(`event`)
        .match(`(region:Region {code: {region}})`)
        .merge(`(event)-[:BELONGS_TO_REGION]->(region)`)
        .end({
            commitmentId: data.commitmentId, eventId: data.eventId, uid: data.uid, title: data.title,
            description: data.description, startDate: data.startDate, endDate: data.endDate, created: data.created,
            modified: data.modified, region: data.region, location: data.location
        }).getCommand());
};

const showQuestionOnCommitment = function (data) {
    dbConnectionHandling.getCommands().push(db.cypher()
        .match(`(c:Commitment {commitmentId: {commitmentId}}), (q:Question {questionId: {questionId}})`)
        .merge(`(q)<-[:SHOW_QUESTION]-(c)`)
        .end({commitmentId: data.commitmentId, questionId: data.questionId}).getCommand());
};

const watchCommitment = function (data) {
    data.created = data.created || 555;
    dbConnectionHandling.getCommands().push(db.cypher()
        .match(`(c:Commitment {commitmentId: {commitmentId}}), (u:User {userId: {userId}})`)
        .merge(`(c)<-[:WATCH {created: {created}}]-(u)`)
        .end({commitmentId: data.commitmentId, userId: data.userId, created: data.created}).getCommand());
};

module.exports = {
    createCommitment,
    createEvent,
    showQuestionOnCommitment,
    watchCommitment
};<|endoftext|>


<commit_before>var fs = require('fs'),
    jshint = require('jshint'),
    UglifyJS = require('uglify-js'),

    deps = require('./deps.js').deps,
    hintrc = require('./hintrc.js');

function lintFiles(files) {

	var errorsFound = 0,
	    i, j, len, len2, src, errors, e;

	for (i = 0, len = files.length; i < len; i++) {

		jshint.JSHINT(fs.readFileSync(files[i], 'utf8'), hintrc.config, hintrc.globals);
		errors = jshint.JSHINT.errors;

		for (j = 0, len2 = errors.length; j < len2; j++) {
			e = errors[j];
			console.log(files[i] + '\tline ' + e.line + '\tcol ' + e.character + '\t ' + e.reason);
		}

		errorsFound += len2;
	}

	return errorsFound;
}

function getFiles(compsBase32) {
	var memo = {},
	    comps;

	if (compsBase32) {
		comps = parseInt(compsBase32, 32).toString(2).split('');
		console.log('Managing dependencies...');
	}

	function addFiles(srcs) {
		for (var j = 0, len = srcs.length; j < len; j++) {
			memo[srcs[j]] = true;
		}
	}

	for (var i in deps) {
		if (comps) {
			if (parseInt(comps.pop(), 2) === 1) {
				console.log('\t* ' + i);
				addFiles(deps[i].src);
			} else {
				console.log('\t  ' + i);
			}
		} else {
			addFiles(deps[i].src);
		}
	}

	var files = [];

	for (var src in memo) {
		files.push('src/' + src);
	}

	return files;
}

exports.lint = function () {

	var files = getFiles();

	console.log('Checking for JS errors...');

	var errorsFound = lintFiles(files);

	if (errorsFound > 0) {
		console.log(errorsFound + ' error(s) found.\n');
		fail();
	} else {
		console.log('\tCheck passed');
	}
};

function getSizeDelta(newContent, oldContent) {
	if (!oldContent) {
		return 'new';
	}
	var newLen = newContent.replace(/\r\n?/g, '\n').length,
		oldLen = oldContent.replace(/\r\n?/g, '\n').length,
		delta = newLen - oldLen;

	return (delta >= 0 ? '+' : '') + delta;
}

function loadSilently(path) {
	try {
		return fs.readFileSync(path, 'utf8');
	} catch (e) {
		return null;
	}
}

function combineFiles(files) {
	var content = '';
	for (var i = 0, len = files.length; i < len; i++) {
		content += fs.readFileSync(files[i], 'utf8') + '\n\n';
	}
	return content;
}

exports.build = function (compsBase32, buildName) {

	var files = getFiles(compsBase32);

	console.log('Concatenating ' + files.length + ' files...');

	var copy = fs.readFileSync('src/copyright.js', 'utf8'),
	    intro = '(function (window, document, undefined) {\n',
	    outro = '}(this, document));',
	    newSrc = copy + intro + combineFiles(files) + outro,

	    pathPart = 'dist/leaflet.label' + (buildName ? '-' + buildName : ''),
	    srcPath = pathPart + '-src.js',

	    oldSrc = loadSilently(srcPath),
	    srcDelta = getSizeDelta(newSrc, oldSrc);

	console.log('\tUncompressed size: ' + newSrc.length + ' bytes (' + srcDelta + ')');

	if (newSrc === oldSrc) {
		console.log('\tNo changes');
	} else {
		fs.writeFileSync(srcPath, newSrc);
		console.log('\tSaved to ' + srcPath);
	}

	console.log('Compressing...');

	var path = pathPart + '.js',
	    oldCompressed = loadSilently(path),
	    newCompressed = copy + UglifyJS.minify(newSrc, {
	        warnings: true,
	        fromString: true
	    }).code,
	    delta = getSizeDelta(newCompressed, oldCompressed);

	console.log('\tCompressed size: ' + newCompressed.length + ' bytes (' + delta + ')');

	if (newCompressed === oldCompressed) {
		console.log('\tNo changes');
	} else {
		fs.writeFileSync(path, newCompressed);
		console.log('\tSaved to ' + path);
	}
};
<commit_msg>Use the correct name for the build version.<commit_after>var fs = require('fs'),
    jshint = require('jshint'),
    UglifyJS = require('uglify-js'),

    deps = require('./deps.js').deps,
    hintrc = require('./hintrc.js');

function lintFiles(files) {

	var errorsFound = 0,
	    i, j, len, len2, src, errors, e;

	for (i = 0, len = files.length; i < len; i++) {

		jshint.JSHINT(fs.readFileSync(files[i], 'utf8'), hintrc.config, hintrc.globals);
		errors = jshint.JSHINT.errors;

		for (j = 0, len2 = errors.length; j < len2; j++) {
			e = errors[j];
			console.log(files[i] + '\tline ' + e.line + '\tcol ' + e.character + '\t ' + e.reason);
		}

		errorsFound += len2;
	}

	return errorsFound;
}

function getFiles(compsBase32) {
	var memo = {},
	    comps;

	if (compsBase32) {
		comps = parseInt(compsBase32, 32).toString(2).split('');
		console.log('Managing dependencies...');
	}

	function addFiles(srcs) {
		for (var j = 0, len = srcs.length; j < len; j++) {
			memo[srcs[j]] = true;
		}
	}

	for (var i in deps) {
		if (comps) {
			if (parseInt(comps.pop(), 2) === 1) {
				console.log('\t* ' + i);
				addFiles(deps[i].src);
			} else {
				console.log('\t  ' + i);
			}
		} else {
			addFiles(deps[i].src);
		}
	}

	var files = [];

	for (var src in memo) {
		files.push('src/' + src);
	}

	return files;
}

exports.lint = function () {

	var files = getFiles();

	console.log('Checking for JS errors...');

	var errorsFound = lintFiles(files);

	if (errorsFound > 0) {
		console.log(errorsFound + ' error(s) found.\n');
		fail();
	} else {
		console.log('\tCheck passed');
	}
};

function getSizeDelta(newContent, oldContent) {
	if (!oldContent) {
		return 'new';
	}
	var newLen = newContent.replace(/\r\n?/g, '\n').length,
		oldLen = oldContent.replace(/\r\n?/g, '\n').length,
		delta = newLen - oldLen;

	return (delta >= 0 ? '+' : '') + delta;
}

function loadSilently(path) {
	try {
		return fs.readFileSync(path, 'utf8');
	} catch (e) {
		return null;
	}
}

function combineFiles(files) {
	var content = '';
	for (var i = 0, len = files.length; i < len; i++) {
		content += fs.readFileSync(files[i], 'utf8') + '\n\n';
	}
	return content;
}

exports.build = function (compsBase32, buildName) {

	var files = getFiles(compsBase32);

	console.log('Concatenating ' + files.length + ' files...');

	var copy = fs.readFileSync('src/copyright.js', 'utf8'),
	    intro = '(function (window, document, undefined) {\n',
	    outro = '}(this, document));',
	    newSrc = copy + intro + combineFiles(files) + outro,

	    pathPart = 'dist/leaflet.minimaplayerswitcher' + (buildName ? '-' + buildName : ''),
	    srcPath = pathPart + '-src.js',

	    oldSrc = loadSilently(srcPath),
	    srcDelta = getSizeDelta(newSrc, oldSrc);

	console.log('\tUncompressed size: ' + newSrc.length + ' bytes (' + srcDelta + ')');

	if (newSrc === oldSrc) {
		console.log('\tNo changes');
	} else {
		fs.writeFileSync(srcPath, newSrc);
		console.log('\tSaved to ' + srcPath);
	}

	console.log('Compressing...');

	var path = pathPart + '.js',
	    oldCompressed = loadSilently(path),
	    newCompressed = copy + UglifyJS.minify(newSrc, {
	        warnings: true,
	        fromString: true
	    }).code,
	    delta = getSizeDelta(newCompressed, oldCompressed);

	console.log('\tCompressed size: ' + newCompressed.length + ' bytes (' + delta + ')');

	if (newCompressed === oldCompressed) {
		console.log('\tNo changes');
	} else {
		fs.writeFileSync(path, newCompressed);
		console.log('\tSaved to ' + path);
	}
};
<|endoftext|>


<commit_before>/**
 * Modified from https://github.com/jadjoubran/laravel5-angular-material-starter/blob/master/angular/services/API.service.js
 * by anonymous on 04/01/16 1:19.
 */

(function() {
    'use strict';

    angular
        .module('appFoundation')
        .factory('API', API);

    API.$inject = ['Restangular', 'ToastService', '$localStorage'];

    /* @ngInject */
    function API(Restangular, ToastService, $localStorage) {
        //content negotiation
        var
            headers = {
                'Content-Type': 'application/json',
                'Accept'      : 'application/x.laravel.v1+json'
            },
            service = serviceFn();

        return service;

        ////////////////

        function serviceFn() {
            return Restangular.withConfig(function(RestangularConfigurer) {
                RestangularConfigurer
                    .setBaseUrl('/api/')
                    .setDefaultHeaders(headers)
                    .setErrorInterceptor(function(response) {
                        if (response.status === 422) {
                            for (var error in response.data.errors) {
                                return ToastService.error(response.data.errors[error][0]);
                            }
                        }
                    })
                    .addFullRequestInterceptor(function(element, operation, what, url, headers) {
                        if ($localStorage.jwt) {
                            headers.Authorization = 'Bearer ' + $localStorage.jwt;
                        }
                    })
                    .addResponseInterceptor(function(data, operation, what, url, response, deferred) {
                        var extractedData;
                        // look for getList operations
                        if (operation === 'getList') {
                            // handle the data and meta data
                            extractedData = data.data;
                            // extractedData.meta = data.data.meta;
                        } else {
                            extractedData = data;
                        }
                        return extractedData;
                    });
            });
        }
    }

})();

<commit_msg>Modified API.service<commit_after>/**
 * Modified from https://github.com/jadjoubran/laravel5-angular-material-starter/blob/master/angular/services/API.service.js
 * by anonymous on 04/01/16 1:19.
 */

(function() {
    'use strict';

    angular
        .module('appFoundation')
        .factory('API', API);

    API.$inject = ['Restangular', 'ToastService', '$localStorage'];

    /* @ngInject */
    function API(Restangular, ToastService, $localStorage) {
        //content negotiation
        var
            headers = {
                'Content-Type': 'application/json',
                'Accept'      : 'application/x.laravel.v1+json'
            },
            service = serviceFn();

        return service;

        ////////////////

        function serviceFn() {
            return Restangular.withConfig(function(RestangularConfigurer) {
                RestangularConfigurer
                    .setBaseUrl('/api/')
                    .setDefaultHeaders(headers)
                    .setErrorInterceptor(function(response) {
                        if (response.status === 422) {
                            for (var error in response.data.errors) {
                                return ToastService.error(response.data.errors[error][0]);
                            }
                        }
                    })
                    .addFullRequestInterceptor(function(element, operation, what, url, headers) {
                        if ($localStorage.app_token) {
                            headers.Authorization = 'Bearer ' + $localStorage.app_token;
                        }
                    })
                    .addResponseInterceptor(function(data, operation, what, url, response, deferred) {
                        var extractedData;
                        // look for getList operations
                        if (operation === 'getList') {
                            // handle the data and meta data
                            extractedData = data.data;
                            // extractedData.meta = data.data.meta;
                        } else {
                            extractedData = data;
                        }
                        return extractedData;
                    });
            });
        }
    }

})();

<|endoftext|>


<commit_before>var paused = 0;

angular.module("gameApp", [])
//called by ng-controller in receiver.html
//creats instance of cast receiver
    .controller("appController", ["$scope", "keyPressHandlerService", function($scope, keyPressHandlerService) {
      window.onload = function() {
        cast.receiver.logger.setLevelValue(0);
        window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
        console.log('Starting Receiver Manager');

        // handler for the 'ready' event
        castReceiverManager.onReady = function(event) {
          console.log('Received Ready event: ' + JSON.stringify(event.data));
          window.castReceiverManager.setApplicationState('Application status is ready...');
        };

        // handler for 'senderconnected' event
        castReceiverManager.onSenderConnected = function(event) {
          console.log('Received Sender Connected event: ' + event.data);
          console.log(window.castReceiverManager.getSender(event.data).userAgent);
        };

        // handler for 'senderdisconnected' event
        castReceiverManager.onSenderDisconnected = function(event) {
          console.log('Received Sender Disconnected event: ' + event.data);
          if (window.castReceiverManager.getSenders().length == 0) {
            window.close();
          }
        };

        // handler for 'systemvolumechanged' event
        castReceiverManager.onSystemVolumeChanged = function(event) {
          console.log('Received System Volume Changed event: ' + event.data['level'] + ' ' +
              event.data['muted']);
        };

        // create a CastMessageBus to handle messages for a custom namespace
        window.messageBus =
          window.castReceiverManager.getCastMessageBus(
              'urn:x-cast:com.google.cast.sample.helloworld');

        // handler for the CastMessageBus message event
        //called when receiver created above gets data
        window.messageBus.onMessage = function(event) {
          //print received message for debugging
          console.log('Message [' + event.senderId + ']: ' + event.data);
          // display the message from the sender
          displayText(event.data);

          //if pause message received, toggle paused flag
          if(event.data == 80) {
            //if not paused, raise flag and display "play"
            if(paused == 1) {
              paused = 0;
              console.log ("play!")
            }
            //if paused, reset flag and display "pause"
            else {
              console.log("pause!");
              paused = 1;
            }

          }

          //if not pause message, spend data to key press handler
          //simulate a key up AND key down to prevent continuous movement
          keyPressHandlerService.keyPress(event.data);
          keyPressHandlerService.keyRelease(event.data);

          // inform all senders on the CastMessageBus of the incoming message event
          // sender message listener will be invoked
          window.messageBus.send(event.senderId, event.data);
        }

        // initialize the CastReceiverManager with an application status message
        window.castReceiverManager.start({statusText: 'Application is starting'});
        console.log('Receiver Manager started');
      };

      // utility function to display the text message in the input field
      function displayText(text) {
        console.log(text);
        document.getElementById('message').innerText = text;
        window.castReceiverManager.setApplicationState(text);
      };

  //    function triggerKeyDown() {
    //    var e = new KeyboardEvent('keydown', {'key': 'ArrowLeft', 'code': "ArrowLeft", 'keyCode': 38,'which':38});
    //    document.dispatchEvent(e);
    //      console.log(e);
    //  };

/*

        $scope.keydown = function(keyEvent) {
            if (!$scope.instructionsDisplayed) {
                $scope.instructionsDisplayed = true;
                return;
            }
            keyPressHandlerService.keyPress(keyEvent.key);
        };

        $scope.keyup = function(keyEvent) {
            keyPressHandlerService.keyRelease(keyEvent.key);
        };
*/
    }])

//initialize game canvase and start game
    .directive("centipedeGame", ["$interval", "gameService", "renderService", "graphicsEngineService", function($interval, gameService, renderService, graphicsEngineService) {
        return {
            restrict: 'A',
            template: '<canvas id="gameCanvas" width="600" height="640" style="text-align: center; position: absolute; border:1px solid #000000; left:50%; top: 50%; transform: translate(-50%,-50%);"></canvas>',

            link: function(scope, element) {
                var intervalPromise;
                var animation = 0;
                var canvas = element.find('canvas')[0].getContext("2d");

                graphicsEngineService.initialise(canvas, 'App/img/graphics.png');
                gameService.initialise();
                //loop to keep game running
                //cycle through, updating animations
                function gameLoop() {

                    animation++;

                    if (animation == 4) {
                        animation = 0;
                    }
                    //if game is not paused, update the screen
                   if(paused != 1) {
                      gameService.update(animation);
                      renderService.draw(animation);
                  }
                         else{
                         graphicsEngineService.drawText(
                         coordinateSystem.screen,
                         globalSettings.gameOverXPosition,
                         globalSettings.gameOverYPosition,
                         "Paused",
                         globalSettings.gameOverFontColour,
                         globalSettings.gameOverFont);
                 }

                }

                intervalPromise = $interval(gameLoop, 50);

                scope.$on("$destroy", function() {
                    if (intervalPromise) {
                        $interval.cancel(intervalPromise);
                        intervalPromise = undefined;
                    }
                });
            }
        }
    }]);
<commit_msg>Update gameApp.js<commit_after>var paused = 0;

angular.module("gameApp", [])
//called by ng-controller in receiver.html
//creats instance of cast receiver
    .controller("appController", ["$scope", "keyPressHandlerService", function($scope, keyPressHandlerService) {
      window.onload = function() {
        cast.receiver.logger.setLevelValue(0);
        window.castReceiverManager = cast.receiver.CastReceiverManager.getInstance();
        console.log('Starting Receiver Manager');

        // handler for the 'ready' event
        castReceiverManager.onReady = function(event) {
          console.log('Received Ready event: ' + JSON.stringify(event.data));
          window.castReceiverManager.setApplicationState('Application status is ready...');
        };

        // handler for 'senderconnected' event
        castReceiverManager.onSenderConnected = function(event) {
          console.log('Received Sender Connected event: ' + event.data);
          console.log(window.castReceiverManager.getSender(event.data).userAgent);
        };

        // handler for 'senderdisconnected' event
        castReceiverManager.onSenderDisconnected = function(event) {
          console.log('Received Sender Disconnected event: ' + event.data);
          if (window.castReceiverManager.getSenders().length == 0) {
            window.close();
          }
        };

        // handler for 'systemvolumechanged' event
        castReceiverManager.onSystemVolumeChanged = function(event) {
          console.log('Received System Volume Changed event: ' + event.data['level'] + ' ' +
              event.data['muted']);
        };

        // create a CastMessageBus to handle messages for a custom namespace
        window.messageBus =
          window.castReceiverManager.getCastMessageBus(
              'urn:x-cast:com.google.cast.sample.helloworld');

        // handler for the CastMessageBus message event
        //called when receiver created above gets data
        window.messageBus.onMessage = function(event) {
          //print received message for debugging
          console.log('Message [' + event.senderId + ']: ' + event.data);
          // display the message from the sender
          displayText(event.data);

          //if pause message received, toggle paused flag
          if(event.data == 80) {
            //if not paused, raise flag and display "play"
            if(paused == 1) {
              paused = 0;
              console.log ("play!")
            }
            //if paused, reset flag and display "pause"
            else {
              console.log("pause!");
              paused = 1;
            }

          }

          //if not pause message, spend data to key press handler
          //simulate a key up AND key down to prevent continuous movement
          keyPressHandlerService.keyPress(event.data);
          keyPressHandlerService.keyRelease(event.data);

          // inform all senders on the CastMessageBus of the incoming message event
          // sender message listener will be invoked
          window.messageBus.send(event.senderId, event.data);
        }

        // initialize the CastReceiverManager with an application status message
        window.castReceiverManager.start({statusText: 'Application is starting'});
        console.log('Receiver Manager started');
      };

      // utility function to display the text message in the input field
      function displayText(text) {
        console.log(text);
        document.getElementById('message').innerText = text;
        window.castReceiverManager.setApplicationState(text);
      };

  //    function triggerKeyDown() {
    //    var e = new KeyboardEvent('keydown', {'key': 'ArrowLeft', 'code': "ArrowLeft", 'keyCode': 38,'which':38});
    //    document.dispatchEvent(e);
    //      console.log(e);
    //  };

/*

        $scope.keydown = function(keyEvent) {
            if (!$scope.instructionsDisplayed) {
                $scope.instructionsDisplayed = true;
                return;
            }
            keyPressHandlerService.keyPress(keyEvent.key);
        };

        $scope.keyup = function(keyEvent) {
            keyPressHandlerService.keyRelease(keyEvent.key);
        };
*/
    }])

//initialize game canvase and start game
    .directive("centipedeGame", ["$interval", "gameService", "renderService", "graphicsEngineService", function($interval, gameService, renderService, graphicsEngineService) {
        return {
            restrict: 'A',
            template: '<canvas id="gameCanvas" width="600" height="640" style="text-align: center; position: absolute; border:1px solid #000000; left:50%; top: 50%; transform: translate(-50%,-50%);"></canvas>',

            link: function(scope, element) {
                var intervalPromise;
                var animation = 0;
                var canvas = element.find('canvas')[0].getContext("2d");

                graphicsEngineService.initialise(canvas, 'App/img/graphics.png');
                gameService.initialise();
                //loop to keep game running
                //cycle through, updating animations
                function gameLoop() {

                    animation++;

                    if (animation == 4) {
                        animation = 0;
                    }
                    //if game is not paused, update the screen
                   if(paused != 1) {
                      gameService.update(animation);
                      renderService.draw(animation);
                  }

                }

                intervalPromise = $interval(gameLoop, 50);

                scope.$on("$destroy", function() {
                    if (intervalPromise) {
                        $interval.cancel(intervalPromise);
                        intervalPromise = undefined;
                    }
                });
            }
        }
    }]);
<|endoftext|>


<commit_before>"use strict";
const path = require("path");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const HtmlPlugin = require("html-webpack-plugin");
const ScriptExtHtmlPlugin = require("script-ext-html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");

const setdexRegex = /[\\/]dist[\\/]setdex[\\/].*?\.(js|json)$/;
const libRegex = /[\\/]node_modules[\\/](lodash|big-integer|bootstrap|vue|vuex|vue-multiselect)[\\/]/;

module.exports = env => ({
  entry: path.join(__dirname, "../app/index"),
  output: {
    filename: "[name].[chunkhash:8].js",
    path: path.join(__dirname, "../dist/app")
  },
  resolve: {
    alias: {
      sulcalc: path.join(__dirname, "../src"),
      app: path.join(__dirname, "../app")
    },
    extensions: [".js", ".json", ".vue"]
  },
  module: {
    strictExportPresence: true,
    rules: [
      {
        test: /\.js$/,
        type: "javascript/esm",
        loader: "babel-loader",
        exclude: file =>
          /[\\/](node_modules|dist)[\\/]/.test(file) && !/\.vue\.js/.test(file),
        options: { envName: "webpack" }
      },
      {
        test: /\.vue$/,
        loader: "vue-loader"
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"]
      }
    ]
  },
  mode: env.production ? "production" : "development",
  devtool: env.production ? false : "cheap-module-eval-source-map",
  optimization: {
    splitChunks: {
      chunks: "all",
      maxInitialRequests: Infinity,
      maxAsyncRequests: Infinity,
      cacheGroups: {
        sulcalc: {
          test: path.join(__dirname, "../src")
        },
        db: {
          test: path.join(__dirname, "../dist/db")
        },
        usage: {
          test: path.join(__dirname, "../dist/setdex/usage")
        },
        setdex1: {
          test({ resource }) {
            return (
              setdexRegex.test(resource) &&
              (resource.includes("rby") ||
                resource.includes("gsc") ||
                resource.includes("rse") ||
                resource.includes("dpp"))
            );
          }
        },
        setdex2: {
          test({ resource }) {
            return (
              setdexRegex.test(resource) &&
              (resource.includes("bw") ||
                resource.includes("xy") ||
                resource.includes("sm"))
            );
          }
        },
        vendors: {
          test: libRegex,
          priority: -10
        },
        webpack: {
          test: /[\\/]node_modules[\\/]/,
          priority: -15
        }
      }
    },
    minimizer: [
      new TerserPlugin({
        sourceMap: !env.production,
        terserOptions: { ecma: 8 }
      })
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({ filename: "[name].[contenthash:8].css" }),
    new HtmlPlugin({
      template: path.join(__dirname, "../app/index.html"),
      inject: "head"
    }),
    new ScriptExtHtmlPlugin({ defaultAttribute: "defer" }),
    new BundleAnalyzerPlugin({
      analyzerMode: env.production ? "disabled" : "server",
      analyzerHost: "localhost",
      defaultSizes: "gzip",
      openAnalyzer: !env.production
    })
  ]
});
<commit_msg>chore(webpack): switch analyzer to never open automatically<commit_after>"use strict";
const path = require("path");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const HtmlPlugin = require("html-webpack-plugin");
const ScriptExtHtmlPlugin = require("script-ext-html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");

const setdexRegex = /[\\/]dist[\\/]setdex[\\/].*?\.(js|json)$/;
const libRegex = /[\\/]node_modules[\\/](lodash|big-integer|bootstrap|vue|vuex|vue-multiselect)[\\/]/;

module.exports = env => ({
  entry: path.join(__dirname, "../app/index"),
  output: {
    filename: "[name].[chunkhash:8].js",
    path: path.join(__dirname, "../dist/app")
  },
  resolve: {
    alias: {
      sulcalc: path.join(__dirname, "../src"),
      app: path.join(__dirname, "../app")
    },
    extensions: [".js", ".json", ".vue"]
  },
  module: {
    strictExportPresence: true,
    rules: [
      {
        test: /\.js$/,
        type: "javascript/esm",
        loader: "babel-loader",
        exclude: file =>
          /[\\/](node_modules|dist)[\\/]/.test(file) && !/\.vue\.js/.test(file),
        options: { envName: "webpack" }
      },
      {
        test: /\.vue$/,
        loader: "vue-loader"
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"]
      }
    ]
  },
  mode: env.production ? "production" : "development",
  devtool: env.production ? false : "cheap-module-eval-source-map",
  optimization: {
    splitChunks: {
      chunks: "all",
      maxInitialRequests: Infinity,
      maxAsyncRequests: Infinity,
      cacheGroups: {
        sulcalc: {
          test: path.join(__dirname, "../src")
        },
        db: {
          test: path.join(__dirname, "../dist/db")
        },
        usage: {
          test: path.join(__dirname, "../dist/setdex/usage")
        },
        setdex1: {
          test({ resource }) {
            return (
              setdexRegex.test(resource) &&
              (resource.includes("rby") ||
                resource.includes("gsc") ||
                resource.includes("rse") ||
                resource.includes("dpp"))
            );
          }
        },
        setdex2: {
          test({ resource }) {
            return (
              setdexRegex.test(resource) &&
              (resource.includes("bw") ||
                resource.includes("xy") ||
                resource.includes("sm"))
            );
          }
        },
        vendors: {
          test: libRegex,
          priority: -10
        },
        webpack: {
          test: /[\\/]node_modules[\\/]/,
          priority: -15
        }
      }
    },
    minimizer: [
      new TerserPlugin({
        sourceMap: !env.production,
        terserOptions: { ecma: 8 }
      })
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new MiniCssExtractPlugin({ filename: "[name].[contenthash:8].css" }),
    new HtmlPlugin({
      template: path.join(__dirname, "../app/index.html"),
      inject: "head"
    }),
    new ScriptExtHtmlPlugin({ defaultAttribute: "defer" }),
    new BundleAnalyzerPlugin({
      analyzerMode: env.production ? "disabled" : "server",
      analyzerHost: "localhost",
      defaultSizes: "gzip",
      openAnalyzer: false
    })
  ]
});
<|endoftext|>


<commit_before>var program = require('commander');

program
  .version('0.5.0');

program
  .command('server')
  .action( function() {
    require("./src/server")();
  });

program
  .command('client')
  .option('-i, --ip <ip>', 'Specify the IP where the StreamKey Server is located')
  .action( function(options) {
    var ip = options.ip || "localhost";
    console.log('Connecting to ' + ip);
    require("./src/client")(ip);
  });

program.parse(process.argv);
<commit_msg>Changed version for commander<commit_after>var program = require('commander');

program
  .version('0.6.5');

program
  .command('server')
  .action( function() {
    require("./src/server")();
  });

program
  .command('client')
  .option('-i, --ip <ip>', 'Specify the IP where the StreamKey Server is located')
  .action( function(options) {
    var ip = options.ip || "localhost";
    console.log('Connecting to ' + ip);
    require("./src/client")(ip);
  });

program.parse(process.argv);
<|endoftext|>


<commit_before>'use strict';

var find = require('find-file');
var path = require('path');
var url = require('url');
var logSymbols = require('log-symbols');
var pkg = require('./package.json');
var spawn  = require("child_process").spawn;

require('string.prototype.endswith');

var moduleCheck = function(rpath, cb, thisArg) {
	try {
		require(rpath);
	} catch(e) {
		cb.call(thisArg, e, false);
		return;
	}

	cb.call(thisArg, null, true);
};

var moduleBuilder = function(cb) {
	var nodeGypPath = find("node-gyp");

	if (!nodeGypPath) {
		return cb(new Error("Couldn\'t find the `node-gyp` binary. Make sure it\'s installed and in your $PATH."));
	}

	var cmd = process.platform === "win32" ? nodeGypPath[0] + ".cmd" : nodeGypPath[0];
	var nodeGyp = spawn(cmd, ['rebuild'], {stdio: [ 'ignore', process.stdout, process.stderr ]});

	nodeGyp.on("error", function(err){
		console.error(logSymbols.error, err.message);
	});

	nodeGyp.on("close", function(code){
		cb(code ? new Error("Build failed!") : null);
	});
};

/**
 * Initialize a new `BinWrapper`
 *
 * @api public
 */

function BinWrapper() {
    if (!(this instanceof BinWrapper)) {
        return new BinWrapper();
    }

    this._src = [];
}

/**
 * Add a file to download
 *
 * @param {String} src
 * @param {String} os
 * @param {String} arch
 * @api public
 */

BinWrapper.prototype.src = function (src, os, arch) {
    if (!arguments.length) {
        return this._src;
    }

    var obj = { url: src, name: path.basename(src) };

    if (os) {
        obj.os = os;
    }

    if (arch) {
        obj.arch = arch;
    }

    this._src = this._src.concat(obj);
    return this;
};

/**
 * Define where to download the file to
 *
 * @param {String} dest
 * @api public
 */

BinWrapper.prototype.dest = function (dest) {
    if (!arguments.length) {
        return this._dest;
    }

    this._dest = dest;
    return this;
};

/**
 * Define which file to use as a binary
 *
 * @param {String} bin
 * @api public
 */

BinWrapper.prototype.use = function (bin) {
    if (!arguments.length) {
        return this._use;
    }

    if (!bin.endsWith(".node")) {
    	bin += ".node";
    }

    this._use = bin;
    return this;
};

/**
 * Get the bin path
 *
 * @api public
 */

BinWrapper.prototype.path = function () {
    var opts = { path: this.dest(), global: this.global, exclude: 'node_modules/.bin' };
    var bin = find(this.use(), opts);
    var dir;

    if (bin && bin.length > 0) {
        dir = bin[0];
    } else {
        dir = path.join(this.dest(), this.use());
    }

    return dir;
};

/**
 * Run bin-wrapper
 *
 * @param {Array} cmd
 * @param {Function} cb
 * @api public
 */

BinWrapper.prototype.install = function (cb, thisArg) {
    var Download = require('download');
    var files = this._parse(this.src());

    this._test(function (err) {
        if (err) {
            var download = new Download({ mode: 777 });

            files.forEach(function (file) {
                download.get(file, this.dest());
            }, this);

            return download.run(function (err) {
                if (err) {
                    cb.call(thisArg, err);
                    return;
                }

                this._test(function (err) {
                    if (err) {
                        cb.call(thisArg, err);
                        return;
                    }

                    cb.call(thisArg);
                });
            }.bind(this));
        }

        cb.call(thisArg);
    },  this);
};

BinWrapper.prototype._require = function() {
	var $path = this.path();

	if ($path.endsWith(".node")) {
		$path = $path.substring(0, $path.length - 5);
	}

	return $path;
}

/**
 * Test binary
 *
 * @param {Array} cmd
 * @param {Function} cb
 * @api private
 */

BinWrapper.prototype._test = function (cb, thisArg) {
    if (this.path()) {
        return moduleCheck(this._require(), function (err, works) {
            if (err) {
                cb.call(thisArg, err);
                return;
            }

            if (!works) {
                cb.call(thisArg, new Error('The `' + this.use() + '` binary doesn\'t seem to work correctly.'));
                return;
            }

            cb.call(thisArg);
        }.bind(this));
    }

    cb.call(thisArg, new Error('Couldn\'t find the `' + this.use() + '` binary. Make sure it\'s installed and in your $PATH.'));
};

/**
 * Parse
 *
 * @param {Object} obj
 * @api private
 */

BinWrapper.prototype._parse = function (obj) {
    var arch = process.arch === 'x64' ? 'x64' : process.arch === 'arm' ? 'arm' : 'x86';
    var ret = [];

    obj.filter(function (o) {
        if (o.os && o.os === process.platform && o.arch && o.arch === arch) {
            return ret.push(o);
        } else if (o.os && o.os === process.platform && !o.arch) {
            return ret.push(o);
        } else if (!o.os && !o.arch) {
            return ret.push(o);
        }
    });

    return ret;
};

var BASE_URL = 'https://raw.githubusercontent.com/reklatsmasters/node-process-list/master/dist/';

var bin = new BinWrapper()
        .src(url.resolve(BASE_URL, "linux/x86/" + pkg.name + ".node"), 'linux')
        .src(url.resolve(BASE_URL, "win/x86/" + pkg.name + ".node"), 'win32')
        .dest(path.join(__dirname, './lib'))
        .use(pkg.name + ".node")
;

bin.install(function(err) {
	if (err) {
		console.warn(logSymbols.warning , "pre-build test failed, compiling from source...");

		return moduleBuilder(function(err){
			if (err) {
				console.error(logSymbols.error, err.message);
				return;
			}

			console.log(logSymbols.success, pkg.name,'built successfully!');
		});
	}

	console.log(logSymbols.success, "pre-build test passed successfully!");
});<commit_msg>[=] fix install<commit_after>'use strict';

var find = require('find-file');
var path = require('path');
var url = require('url');
var logSymbols = require('log-symbols');
var pkg = require('./package.json');
var spawn  = require("child_process").spawn;

require('string.prototype.endswith');

var moduleCheck = function(rpath, cb, thisArg) {
	try {
		require(rpath);
	} catch(e) {
		cb.call(thisArg, e, false);
		return;
	}

	cb.call(thisArg, null, true);
};

var moduleBuilder = function(cb) {
	var nodeGypPath = find("node-gyp");

	if (!nodeGypPath) {
		return cb(new Error("Couldn\'t find the `node-gyp` binary. Make sure it\'s installed and in your $PATH."));
	}

	var cmd = process.platform === "win32" ? nodeGypPath[0] + ".cmd" : nodeGypPath[0];
	var nodeGyp = spawn(cmd, ['rebuild'], {stdio: [ 'ignore', process.stdout, process.stderr ]});

	nodeGyp.on("error", function(err){
		console.error(logSymbols.error, err.message);
	});

	nodeGyp.on("close", function(code){
		cb(code ? new Error("Build failed!") : null);
	});
};

/**
 * Initialize a new `BinWrapper`
 *
 * @api public
 */

function BinWrapper() {
    if (!(this instanceof BinWrapper)) {
        return new BinWrapper();
    }

    this._src = [];
}

/**
 * Add a file to download
 *
 * @param {String} src
 * @param {String} os
 * @param {String} arch
 * @api public
 */

BinWrapper.prototype.src = function (src, os, arch) {
    if (!arguments.length) {
        return this._src;
    }

    var obj = { url: src, name: path.basename(src) };

    if (os) {
        obj.os = os;
    }

    if (arch) {
        obj.arch = arch;
    }

    this._src = this._src.concat(obj);
    return this;
};

/**
 * Define where to download the file to
 *
 * @param {String} dest
 * @api public
 */

BinWrapper.prototype.dest = function (dest) {
    if (!arguments.length) {
        return this._dest;
    }

    this._dest = dest;
    return this;
};

/**
 * Define which file to use as a binary
 *
 * @param {String} bin
 * @api public
 */

BinWrapper.prototype.use = function (bin) {
    if (!arguments.length) {
        return this._use;
    }

    if (!bin.endsWith(".node")) {
    	bin += ".node";
    }

    this._use = bin;
    return this;
};

/**
 * Get the bin path
 *
 * @api public
 */

BinWrapper.prototype.path = function () {
    var opts = { path: this.dest(), global: this.global, exclude: 'node_modules/.bin' };
    var bin = find(this.use(), opts);
    var dir;

    if (bin && bin.length > 0) {
        dir = bin[0];
    } else {
        dir = path.join(this.dest(), this.use());
    }

    return dir;
};

/**
 * Run bin-wrapper
 *
 * @param {Array} cmd
 * @param {Function} cb
 * @api public
 */

BinWrapper.prototype.install = function (cb, thisArg) {
    var Download = require('download');
    var files = this._parse(this.src());

    this._test(function (err) {
        if (err) {
            var download = new Download({ mode: 777 });

            files.forEach(function (file) {
                download.get(file, this.dest());
            }, this);

            return download.run(function (err) {
                if (err) {
                    cb.call(thisArg, err);
                    return;
                }

                this._test(function (err) {
                    if (err) {
                        cb.call(thisArg, err);
                        return;
                    }

                    cb.call(thisArg);
                });
            }.bind(this));
        }

        cb.call(thisArg);
    },  this);
};

BinWrapper.prototype._require = function() {
	var $path = this.path();

	if ($path.endsWith(".node")) {
		$path = $path.substring(0, $path.length - 5);
	}

	return $path;
}

/**
 * Test binary
 *
 * @param {Array} cmd
 * @param {Function} cb
 * @api private
 */

BinWrapper.prototype._test = function (cb, thisArg) {
    if (this.path()) {
        return moduleCheck(this._require(), function (err, works) {
            if (err) {
                cb.call(thisArg, err);
                return;
            }

            if (!works) {
                cb.call(thisArg, new Error('The `' + this.use() + '` binary doesn\'t seem to work correctly.'));
                return;
            }

            cb.call(thisArg);
        }.bind(this));
    }

    cb.call(thisArg, new Error('Couldn\'t find the `' + this.use() + '` binary. Make sure it\'s installed and in your $PATH.'));
};

/**
 * Parse
 *
 * @param {Object} obj
 * @api private
 */

BinWrapper.prototype._parse = function (obj) {
    var arch = process.arch === 'x64' ? 'x64' : process.arch === 'arm' ? 'arm' : 'x86';
    var ret = [];

    obj.filter(function (o) {
        if (o.os && o.os === process.platform && o.arch && o.arch === arch) {
            return ret.push(o);
        } else if (o.os && o.os === process.platform && !o.arch) {
            return ret.push(o);
        } else if (!o.os && !o.arch) {
            return ret.push(o);
        }
    });

    return ret;
};

var BASE_URL = 'https://raw.githubusercontent.com/reklatsmasters/node-process-list/v' + pkg.version + '/dist/';

var bin = new BinWrapper()
        .src(url.resolve(BASE_URL, "linux/x86/" + pkg.name + ".node"), 'linux')
        .src(url.resolve(BASE_URL, "win/x86/" + pkg.name + ".node"), 'win32')
        .dest(path.join(__dirname, './lib'))
        .use(pkg.name + ".node")
;

bin.install(function(err) {
	if (err) {
		console.warn(logSymbols.warning , "pre-build test failed, compiling from source...");

		return moduleBuilder(function(err){
			if (err) {
				console.error(logSymbols.error, err.message);
				return;
			}

			console.log(logSymbols.success, pkg.name,'built successfully!');
		});
	}

	console.log(logSymbols.success, "pre-build test passed successfully!");
});<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is infoRSS.
 *
 * The Initial Developer of the Original Code is
 *   Didier Ernotte <didier@ernotte.com>.
 * Portions created by the Initial Developer are Copyright (C) 2004
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Didier Ernotte <didier@ernotte.com>.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
//------------------------------------------------------------------------------
// inforss_timeout
// Author : Tom Tanner 2018
// Inforss extension
//------------------------------------------------------------------------------

//This provides timeouts without referencing any global window object

/* jshint worker: true */
/* eslint-env worker */

/* jshint globalstrict: true */
/* eslint-disable strict */
"use strict";

const timers = {};

/** called when the timeout fires
 *
 * Just posts a message to the caller
 *
 * @param {Timer} id - time id from setTimeout
 */
function fireTimeout(id)
{
  postMessage(id);
  delete timers[id];
}

addEventListener(
  "message",
  event =>
  {
    const data = event.data;
    const id = data.id;
    switch (data.command)
    {
      case "setTimeout":
        timers[id] = setTimeout(fireTimeout, data.delay, id);
        break;

      case "clearTimeout":
        if (id in timers)
        {
          clearTimeout(timers[id]);
          delete timers[id];
        }
        break;

      default:
        break;
    }
  }
);
<commit_msg>work round jshint bug<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is infoRSS.
 *
 * The Initial Developer of the Original Code is
 *   Didier Ernotte <didier@ernotte.com>.
 * Portions created by the Initial Developer are Copyright (C) 2004
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Didier Ernotte <didier@ernotte.com>.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
//------------------------------------------------------------------------------
// inforss_timeout
// Author : Tom Tanner 2018
// Inforss extension
//------------------------------------------------------------------------------

//This provides timeouts without referencing any global window object

//JSHint bug. Shouldn't need browser: true here
/* jshint worker: true, browser: true */
/* eslint-env worker */

/* jshint globalstrict: true */
/* eslint-disable strict */
"use strict";

const timers = {};

/** called when the timeout fires
 *
 * Just posts a message to the caller
 *
 * @param {Timer} id - time id from setTimeout
 */
function fireTimeout(id)
{
  postMessage(id);
  delete timers[id];
}

addEventListener(
  "message",
  event =>
  {
    const data = event.data;
    const id = data.id;
    switch (data.command)
    {
      case "setTimeout":
        timers[id] = setTimeout(fireTimeout, data.delay, id);
        break;

      case "clearTimeout":
        if (id in timers)
        {
          clearTimeout(timers[id]);
          delete timers[id];
        }
        break;

      default:
        break;
    }
  }
);
<|endoftext|>


<commit_before>import { delay } from 'redux-saga';
import { take, call, apply, put, race, select } from 'redux-saga/effects';
import * as Keychain from 'react-native-keychain';
import { REHYDRATE } from 'redux-persist/constants';
import {
  LOGIN_REQUEST,
  LOGIN_SUCCESS,
  LOGIN_ERROR,
  LOGOUT,
  login,
  successLogin,
  failedLogin,
  logout,
  doneRehydrate,
} from '../actions/auth';
import { addError } from '../actions/error';
import pixiv from '../helpers/apiClient';
import { getAuthUser } from '../selectors';

export function* authorize(email, password) {
  // use apply instead of call to pass this to function
  const loginResponse = yield apply(pixiv, pixiv.login, [email, password]);
  yield call(Keychain.setGenericPassword, email, password);
  yield put(successLogin(loginResponse));
  return loginResponse;
}

export function* authAndRefreshTokenOnExpiry(email, password) {
  const loginResponse = yield call(authorize, email, password);
  while (true) {
    const credentials = yield call(Keychain.getGenericPassword);
    if (credentials.username && credentials.password) {
      // refresh token 5 min before expire
      // convert expires in to milisecond
      const delayMilisecond = (loginResponse.expires_in - 300) * 1000;
      yield call(delay, delayMilisecond);
      try {
        yield call(authorize, credentials.username, credentials.password);
      } catch (err) {
        yield put(logout());
      }
    }
  }
}

export function* handleLogout() {
  yield [call(Keychain.resetGenericPassword), apply(pixiv, pixiv.logout)];
}

export function* watchLoginRequest() {
  // yield takeEvery(LOGIN_REQUEST, loginFlow)
  while (true) {
    try {
      const action = yield take(LOGIN_REQUEST);
      const { email, password } = action.payload;
      yield race([
        take(LOGOUT),
        call(authAndRefreshTokenOnExpiry, email, password),
      ]);
      yield call(handleLogout);
      // user logged out, next while iteration will wait for the
      // next LOGIN_REQUEST action
    } catch (err) {
      const errMessage = err.errors &&
        err.errors.system &&
        err.errors.system.message
        ? err.errors.system.message
        : '';
      yield put(failedLogin());
      yield put(addError(errMessage));
    }
  }
}

// wait rehydrate complete, login if authUser exist, then run other api
export function* watchRehydrate() {
  while (true) {
    try {
      yield take(REHYDRATE);
      const user = yield select(getAuthUser);
      if (user) {
        console.log('watchRehydrate login');
        const credentials = yield call(Keychain.getGenericPassword);
        yield put(login(credentials.username, credentials.password));
        yield take([LOGIN_SUCCESS, LOGIN_ERROR]);
      }
      // todo put sync complete
      yield put(doneRehydrate());
    } catch (err) {
      // todo logout user
      console.log('err in watchRehydrate ', err);
    }
  }
}
<commit_msg>better auth watchRehydrate saga handling<commit_after>import { delay } from 'redux-saga';
import { take, call, apply, put, race, select } from 'redux-saga/effects';
import * as Keychain from 'react-native-keychain';
import { REHYDRATE } from 'redux-persist/constants';
import {
  LOGIN_REQUEST,
  LOGIN_SUCCESS,
  LOGIN_ERROR,
  LOGOUT,
  login,
  successLogin,
  failedLogin,
  logout,
  doneRehydrate,
} from '../actions/auth';
import { addError } from '../actions/error';
import pixiv from '../helpers/apiClient';
import { getAuthUser } from '../selectors';

export function* authorize(email, password) {
  // use apply instead of call to pass this to function
  const loginResponse = yield apply(pixiv, pixiv.login, [email, password]);
  yield call(Keychain.setGenericPassword, email, password);
  yield put(successLogin(loginResponse));
  return loginResponse;
}

export function* authAndRefreshTokenOnExpiry(email, password) {
  const loginResponse = yield call(authorize, email, password);
  while (true) {
    const credentials = yield call(Keychain.getGenericPassword);
    if (credentials.username && credentials.password) {
      // refresh token 5 min before expire
      // convert expires in to milisecond
      const delayMilisecond = (loginResponse.expires_in - 300) * 1000;
      yield call(delay, delayMilisecond);
      try {
        yield call(authorize, credentials.username, credentials.password);
      } catch (err) {
        yield put(logout());
      }
    }
  }
}

export function* handleLogout() {
  yield [call(Keychain.resetGenericPassword), apply(pixiv, pixiv.logout)];
}

export function* watchLoginRequest() {
  // yield takeEvery(LOGIN_REQUEST, loginFlow)
  while (true) {
    try {
      const action = yield take(LOGIN_REQUEST);
      const { email, password } = action.payload;
      yield race([
        take(LOGOUT),
        call(authAndRefreshTokenOnExpiry, email, password),
      ]);
      yield call(handleLogout);
      // user logged out, next while iteration will wait for the
      // next LOGIN_REQUEST action
    } catch (err) {
      const errMessage = err.errors &&
        err.errors.system &&
        err.errors.system.message
        ? err.errors.system.message
        : '';
      yield put(failedLogin());
      yield put(addError(errMessage));
    }
  }
}

// wait rehydrate complete, login if authUser exist, then run other api
export function* watchRehydrate() {
  while (true) {
    try {
      yield take(REHYDRATE);
      const user = yield select(getAuthUser);
      if (user) {
        console.log('watchRehydrate login');
        const credentials = yield call(Keychain.getGenericPassword);
        if (credentials) {
          yield put(login(credentials.username, credentials.password));
        } else {
          yield put(logout());
        }
        yield take([LOGIN_SUCCESS, LOGIN_ERROR, LOGOUT]);
      }
      // todo put sync complete
      yield put(doneRehydrate());
    } catch (err) {
      // todo logout user
      console.log('err in watchRehydrate ', err);
    }
  }
}
<|endoftext|>