<commit_before>// TODO: Refactor... switch from jQuery to Vue.js
// public methods
function resetTabsSlider() {
    $("#tabsSlider").removeClass("slide-copy");
    $("#tabsSlider").removeClass("slide-altcoins");

    $("#scan-tab").removeClass("active");
    $("#copy-tab").removeClass("active");
    $("#altcoins-tab").removeClass("active");

    $("#copy").hide();
    $("#copy").removeClass("active");

    $("#scan").hide();
    $("#scan").removeClass("active");

    $("#altcoins").hide();
    $("#altcoins").removeClass("active");
}

function onDataCallback(jsonData) {
    // extender properties used
    jsonData.shapeshiftUrl = "https://shapeshift.io/shifty.html?destination=" + jsonData.btcAddress + "&output=" + jsonData.paymentMethodId + "&amount=" + jsonData.btcDue;
    //

    var newStatus = jsonData.status;

    if (newStatus === "complete" ||
        newStatus === "confirmed" ||
        newStatus === "paid") {
        if ($(".modal-dialog").hasClass("expired")) {
            $(".modal-dialog").removeClass("expired");
        }

        if (srvModel.merchantRefLink !== "") {
            $(".action-button").click(function () {
                window.location.href = srvModel.merchantRefLink;
            });
        }
        else {
            $(".action-button").hide();
        }

        $(".modal-dialog").addClass("paid");

        resetTabsSlider();
        $("#paid").addClass("active");
    }

    if (newStatus === "expired" || newStatus === "invalid") { //TODO: different state if the invoice is invalid (failed to confirm after timeout)
        $(".timer-row").removeClass("expiring-soon");
        $(".timer-row__spinner").html("");
        $("#emailAddressView").removeClass("active");
        $(".modal-dialog").addClass("expired");
        $("#expired").addClass("active");

        resetTabsSlider();
    }

    if (checkoutCtrl.srvModel.status !== newStatus) {
        window.parent.postMessage({ "invoiceId": srvModel.invoiceId, "status": newStatus }, "*");
    }

    // restoring qr code view only when currency is switched
    if (jsonData.paymentMethodId == srvModel.paymentMethodId) {
        $(".payment__currencies").show();
        $(".payment__spinner").hide();
    }

    // updating ui
    checkoutCtrl.srvModel = jsonData;
}

function changeCurrency(currency) {
    if (srvModel.paymentMethodId != currency) {
        $(".payment__currencies").hide();
        $(".payment__spinner").show();
        srvModel.paymentMethodId = currency;
        fetchStatus();
    }
    return false;
}

function fetchStatus() {
    var path = srvModel.serverUrl + "/i/" + srvModel.invoiceId + "/" + srvModel.paymentMethodId + "/status";
    $.ajax({
        url: path,
        type: "GET",
        cache: false
    }).done(function (data) {
        onDataCallback(data);
    }).fail(function (jqXHR, textStatus, errorThrown) {

    });
}

// private methods
$(document).ready(function () {
    // initialize
    onDataCallback(srvModel);

    /* TAF

    - Version mobile

    - Réparer le décallage par timer

    - Preparer les variables de l'API

    - Gestion des differents evenements en fonction du status de l'invoice

    - sécuriser les CDN

    */

    var display = $(".timer-row__time-left"); // Timer container

    // check if the Document expired
    if (srvModel.expirationSeconds > 0) {
        progressStart(srvModel.maxTimeSeconds); // Progress bar
        startTimer(srvModel.expirationSeconds, display); // Timer

        if (!validateEmail(srvModel.customerEmail))
            emailForm(); // Email form Display
        else
            hideEmailForm();
    }

    function hideEmailForm() {
        $("#emailAddressView").removeClass("active");
        $("placeholder-refundEmail").html(srvModel.customerEmail);

        // Remove Email mode
        $(".modal-dialog").removeClass("enter-purchaser-email");
        $("#scan").addClass("active");
    }
    // Email Form
    // Setup Email mode
    function emailForm() {
        $(".modal-dialog").addClass("enter-purchaser-email");

        $("#emailAddressForm .action-button").click(function () {
            var emailAddress = $("#emailAddressFormInput").val();
            if (validateEmail(emailAddress)) {
                $("#emailAddressForm .input-wrapper bp-loading-button .action-button").addClass("loading");
                // Push the email to a server, once the reception is confirmed move on
                srvModel.customerEmail = emailAddress;

                var path = srvModel.serverUrl + "/i/" + srvModel.invoiceId + "/UpdateCustomer";

                $.ajax({
                    url: path,
                    type: "POST",
                    data: JSON.stringify({ Email: srvModel.customerEmail }),
                    contentType: "application/json; charset=utf-8"
                }).done(function () {
                    hideEmailForm();
                }).fail(function (jqXHR, textStatus, errorThrown) {

                })
                    .always(function () {
                        $("#emailAddressForm .input-wrapper bp-loading-button .action-button").removeClass("loading");
                    });
            } else {
                $("#emailAddressForm").addClass("ng-touched ng-dirty ng-submitted ng-invalid");
            }

            return false;
        });
    }

    // Validate Email address
    function validateEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }

    /* =============== Even listeners =============== */

    // Email
    $("#emailAddressFormInput").change(function () {
        if ($("#emailAddressForm").hasClass("ng-submitted")) {
            $("#emailAddressForm").removeClass("ng-submitted");
        }
    });

    // Scan/Copy Transitions
    // Scan Tab
    $("#scan-tab").click(function () {
        resetTabsSlider();
        activateTab("#scan");
    });

    // Copy tab
    $("#copy-tab").click(function () {
        resetTabsSlider();
        activateTab("#copy");

        $("#tabsSlider").addClass("slide-copy");
    });

    // Altcoins tab
    $("#altcoins-tab").click(function () {
        resetTabsSlider();
        activateTab("#altcoins");

        $("#tabsSlider").addClass("slide-altcoins");
    });

    function activateTab(senderName) {
        $(senderName + "-tab").addClass("active");

        $(senderName).show();
        $(senderName).addClass("active");
    }

    // Payment received
    // Should connect using webhook ?
    // If notification received

    var supportsWebSockets = 'WebSocket' in window && window.WebSocket.CLOSING === 2;
    if (supportsWebSockets) {
        var path = srvModel.serverUrl + "/i/" + srvModel.invoiceId + "/status/ws";
        path = path.replace("https://", "wss://");
        path = path.replace("http://", "ws://");
        try {
            var socket = new WebSocket(path);
            socket.onmessage = function (e) {
                fetchStatus();
            };
        }
        catch (e) {
            console.error("Error while connecting to websocket for invoice notifications");
        }
    }

    var watcher = setInterval(function () {
        fetchStatus();
    }, 2000);

    $(".menu__item").click(function () {
        $(".menu__scroll .menu__item").removeClass("selected");
        $(this).addClass("selected");
        language();
        $(".selector span").text($(".selected").text());
        // function to load contents in different language should go there
    });

    // Expand Line-Items
    $(".buyerTotalLine").click(function () {
        $("line-items").toggleClass("expanded");
        $(".buyerTotalLine").toggleClass("expanded");
        $(".single-item-order__right__btc-price__chevron").toggleClass("expanded");
    });

    // Timer Countdown
    function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
        var timeout = setInterval(function () {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.text(minutes + ":" + seconds);

            if (--timer < 0) {
                clearInterval(timeout);
            }
        }, 1000);
    }

    // Progress bar
    function progressStart(timerMax) {
        var end = new Date(); // Setup Time Variable, should come from server
        end.setSeconds(end.getSeconds() + srvModel.expirationSeconds);
        timerMax *= 1000; // Usually 15 minutes = 9000 second= 900000 ms
        var timeoutVal = Math.floor(timerMax / 100); // Timeout calc
        animateUpdate(); //Launch it

        function updateProgress(percentage) {
            $('.timer-row__progress-bar').css("width", percentage + "%");
        }

        function animateUpdate() {
            var now = new Date();
            var timeDiff = end.getTime() - now.getTime();
            var perc = 100 - Math.round(timeDiff / timerMax * 100);
            var status = checkoutCtrl.srvModel.status;

            if (perc === 75 && (status === "paidPartial" || status === "new")) {
                $(".timer-row").addClass("expiring-soon");
                checkoutCtrl.expiringSoon = true;
                updateProgress(perc);
            }
            if (perc <= 100) {
                updateProgress(perc);
                setTimeout(animateUpdate, timeoutVal);
            }
            //if (perc >= 100 && status === "expired") {
            //    onDataCallback(status);
            //}
        }
    }

    // Manual Copy
    // Amount
    var copyAmount = new Clipboard('.manual-box__amount__value', {
        target: function () {
            var $el = $(".manual-box__amount__value");
            $el.removeClass("copy-cursor").addClass("copied");
            setTimeout(function () { $el.removeClass("copied").addClass("copy-cursor"); }, 500);
            return document.querySelector('.manual-box__amount__value span');
        }
    });
    // Address
    var copyAddress = new Clipboard('.manual-box__address__value', {
        target: function () {
            var $elm = $(".manual-box__address__value");
            $elm.removeClass("copy-cursor").addClass("copied");
            setTimeout(function () { $elm.removeClass("copied").addClass("copy-cursor"); }, 500);
            return document.querySelector('.manual-box__address__value .manual-box__address__wrapper .manual-box__address__wrapper__value');
        }
    });

    // Disable enter key
    $(document).keypress(
        function (event) {
            if (event.which === '13') {
                event.preventDefault();
            }
        }
    );

});
<commit_msg>Remove ESSLint errors<commit_after>// TODO: Refactor... switch from jQuery to Vue.js
// public methods
function resetTabsSlider() {
    $("#tabsSlider").removeClass("slide-copy");
    $("#tabsSlider").removeClass("slide-altcoins");

    $("#scan-tab").removeClass("active");
    $("#copy-tab").removeClass("active");
    $("#altcoins-tab").removeClass("active");

    $("#copy").hide();
    $("#copy").removeClass("active");

    $("#scan").hide();
    $("#scan").removeClass("active");

    $("#altcoins").hide();
    $("#altcoins").removeClass("active");
}

function onDataCallback(jsonData) {
    // extender properties used
    jsonData.shapeshiftUrl = "https://shapeshift.io/shifty.html?destination=" + jsonData.btcAddress + "&output=" + jsonData.paymentMethodId + "&amount=" + jsonData.btcDue;
    //

    var newStatus = jsonData.status;

    if (newStatus === "complete" ||
        newStatus === "confirmed" ||
        newStatus === "paid") {
        if ($(".modal-dialog").hasClass("expired")) {
            $(".modal-dialog").removeClass("expired");
        }

        if (srvModel.merchantRefLink !== "") {
            $(".action-button").click(function () {
                window.location.href = srvModel.merchantRefLink;
            });
        }
        else {
            $(".action-button").hide();
        }

        $(".modal-dialog").addClass("paid");

        resetTabsSlider();
        $("#paid").addClass("active");
    }

    if (newStatus === "expired" || newStatus === "invalid") { //TODO: different state if the invoice is invalid (failed to confirm after timeout)
        $(".timer-row").removeClass("expiring-soon");
        $(".timer-row__spinner").html("");
        $("#emailAddressView").removeClass("active");
        $(".modal-dialog").addClass("expired");
        $("#expired").addClass("active");

        resetTabsSlider();
    }

    if (checkoutCtrl.srvModel.status !== newStatus) {
        window.parent.postMessage({ "invoiceId": srvModel.invoiceId, "status": newStatus }, "*");
    }

    // restoring qr code view only when currency is switched
    if (jsonData.paymentMethodId === srvModel.paymentMethodId) {
        $(".payment__currencies").show();
        $(".payment__spinner").hide();
    }

    // updating ui
    checkoutCtrl.srvModel = jsonData;
}

function changeCurrency(currency) {
    if (srvModel.paymentMethodId !== currency) {
        $(".payment__currencies").hide();
        $(".payment__spinner").show();
        srvModel.paymentMethodId = currency;
        fetchStatus();
    }
    return false;
}

function fetchStatus() {
    var path = srvModel.serverUrl + "/i/" + srvModel.invoiceId + "/" + srvModel.paymentMethodId + "/status";
    $.ajax({
        url: path,
        type: "GET",
        cache: false
    }).done(function (data) {
        onDataCallback(data);
    }).fail(function (jqXHR, textStatus, errorThrown) {

    });
}

// private methods
$(document).ready(function () {
    // initialize
    onDataCallback(srvModel);

    /* TAF

    - Version mobile

    - Réparer le décallage par timer

    - Preparer les variables de l'API

    - Gestion des differents evenements en fonction du status de l'invoice

    - sécuriser les CDN

    */

    var display = $(".timer-row__time-left"); // Timer container

    // check if the Document expired
    if (srvModel.expirationSeconds > 0) {
        progressStart(srvModel.maxTimeSeconds); // Progress bar
        startTimer(srvModel.expirationSeconds, display); // Timer

        if (!validateEmail(srvModel.customerEmail))
            emailForm(); // Email form Display
        else
            hideEmailForm();
    }

    function hideEmailForm() {
        $("#emailAddressView").removeClass("active");
        $("placeholder-refundEmail").html(srvModel.customerEmail);

        // Remove Email mode
        $(".modal-dialog").removeClass("enter-purchaser-email");
        $("#scan").addClass("active");
    }
    // Email Form
    // Setup Email mode
    function emailForm() {
        $(".modal-dialog").addClass("enter-purchaser-email");

        $("#emailAddressForm .action-button").click(function () {
            var emailAddress = $("#emailAddressFormInput").val();
            if (validateEmail(emailAddress)) {
                $("#emailAddressForm .input-wrapper bp-loading-button .action-button").addClass("loading");
                // Push the email to a server, once the reception is confirmed move on
                srvModel.customerEmail = emailAddress;

                var path = srvModel.serverUrl + "/i/" + srvModel.invoiceId + "/UpdateCustomer";

                $.ajax({
                    url: path,
                    type: "POST",
                    data: JSON.stringify({ Email: srvModel.customerEmail }),
                    contentType: "application/json; charset=utf-8"
                }).done(function () {
                    hideEmailForm();
                }).fail(function (jqXHR, textStatus, errorThrown) {

                })
                    .always(function () {
                        $("#emailAddressForm .input-wrapper bp-loading-button .action-button").removeClass("loading");
                    });
            } else {
                $("#emailAddressForm").addClass("ng-touched ng-dirty ng-submitted ng-invalid");
            }

            return false;
        });
    }

    // Validate Email address
    function validateEmail(email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }

    /* =============== Even listeners =============== */

    // Email
    $("#emailAddressFormInput").change(function () {
        if ($("#emailAddressForm").hasClass("ng-submitted")) {
            $("#emailAddressForm").removeClass("ng-submitted");
        }
    });

    // Scan/Copy Transitions
    // Scan Tab
    $("#scan-tab").click(function () {
        resetTabsSlider();
        activateTab("#scan");
    });

    // Copy tab
    $("#copy-tab").click(function () {
        resetTabsSlider();
        activateTab("#copy");

        $("#tabsSlider").addClass("slide-copy");
    });

    // Altcoins tab
    $("#altcoins-tab").click(function () {
        resetTabsSlider();
        activateTab("#altcoins");

        $("#tabsSlider").addClass("slide-altcoins");
    });

    function activateTab(senderName) {
        $(senderName + "-tab").addClass("active");

        $(senderName).show();
        $(senderName).addClass("active");
    }

    // Payment received
    // Should connect using webhook ?
    // If notification received

    var supportsWebSockets = 'WebSocket' in window && window.WebSocket.CLOSING === 2;
    if (supportsWebSockets) {
        var path = srvModel.serverUrl + "/i/" + srvModel.invoiceId + "/status/ws";
        path = path.replace("https://", "wss://");
        path = path.replace("http://", "ws://");
        try {
            var socket = new WebSocket(path);
            socket.onmessage = function (e) {
                fetchStatus();
            };
        }
        catch (e) {
            console.error("Error while connecting to websocket for invoice notifications");
        }
    }

    var watcher = setInterval(function () {
        fetchStatus();
    }, 2000);

    $(".menu__item").click(function () {
        $(".menu__scroll .menu__item").removeClass("selected");
        $(this).addClass("selected");
        language();
        $(".selector span").text($(".selected").text());
        // function to load contents in different language should go there
    });

    // Expand Line-Items
    $(".buyerTotalLine").click(function () {
        $("line-items").toggleClass("expanded");
        $(".buyerTotalLine").toggleClass("expanded");
        $(".single-item-order__right__btc-price__chevron").toggleClass("expanded");
    });

    // Timer Countdown
    function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
        var timeout = setInterval(function () {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.text(minutes + ":" + seconds);

            if (--timer < 0) {
                clearInterval(timeout);
            }
        }, 1000);
    }

    // Progress bar
    function progressStart(timerMax) {
        var end = new Date(); // Setup Time Variable, should come from server
        end.setSeconds(end.getSeconds() + srvModel.expirationSeconds);
        timerMax *= 1000; // Usually 15 minutes = 9000 second= 900000 ms
        var timeoutVal = Math.floor(timerMax / 100); // Timeout calc
        animateUpdate(); //Launch it

        function updateProgress(percentage) {
            $('.timer-row__progress-bar').css("width", percentage + "%");
        }

        function animateUpdate() {
            var now = new Date();
            var timeDiff = end.getTime() - now.getTime();
            var perc = 100 - Math.round(timeDiff / timerMax * 100);
            var status = checkoutCtrl.srvModel.status;

            if (perc === 75 && (status === "paidPartial" || status === "new")) {
                $(".timer-row").addClass("expiring-soon");
                checkoutCtrl.expiringSoon = true;
                updateProgress(perc);
            }
            if (perc <= 100) {
                updateProgress(perc);
                setTimeout(animateUpdate, timeoutVal);
            }
            //if (perc >= 100 && status === "expired") {
            //    onDataCallback(status);
            //}
        }
    }

    // Manual Copy
    // Amount
    var copyAmount = new Clipboard('.manual-box__amount__value', {
        target: function () {
            var $el = $(".manual-box__amount__value");
            $el.removeClass("copy-cursor").addClass("copied");
            setTimeout(function () { $el.removeClass("copied").addClass("copy-cursor"); }, 500);
            return document.querySelector('.manual-box__amount__value span');
        }
    });
    // Address
    var copyAddress = new Clipboard('.manual-box__address__value', {
        target: function () {
            var $elm = $(".manual-box__address__value");
            $elm.removeClass("copy-cursor").addClass("copied");
            setTimeout(function () { $elm.removeClass("copied").addClass("copy-cursor"); }, 500);
            return document.querySelector('.manual-box__address__value .manual-box__address__wrapper .manual-box__address__wrapper__value');
        }
    });

    // Disable enter key
    $(document).keypress(
        function (event) {
            if (event.which === '13') {
                event.preventDefault();
            }
        }
    );

});
<|endoftext|>


<commit_before>/**
 * Copyright 2015, Yahoo! Inc.
 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */

 var VersionChecker = require('ember-cli-version-checker');

function isModern(instance) {
    var checker = new VersionChecker(instance);
    var dep     = checker.for('ember', 'bower');
    return dep.satisfies('>= 1.13.0 || >= 2.0.0-0 || >= 2.1.0-0 || >= 2.2.0-0');
}

module.exports = isModern;
<commit_msg>Update is-modern.js<commit_after>/**
 * Copyright 2015, Yahoo! Inc.
 * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
 */

 var VersionChecker = require('ember-cli-version-checker');

function isModern(instance) {
    var checker = new VersionChecker(instance);
    var dep     = checker.for('ember', 'bower');
    return dep.gt('1.13.0');
}

module.exports = isModern;
<|endoftext|>


<commit_before>
exports = module.exports = lifecycle
exports.cmd = cmd

var log = require("./log")
  , exec = require("./exec")
  , npm = require("../../npm")
  , path = require("path")
  , readJson = require("./read-json")
  , fs = require("./graceful-fs")

function lifecycle (pkg, stage, cb) {
  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error("Invalid package data"))
  if (!pkg.scripts || !(stage in pkg.scripts)) return cb()

  // run package lifecycle scripts in the package root, or the nearest parent.
  var d = path.join(npm.dir, pkg.name, pkg.version, "package")
  while (d) {
    try {
      process.chdir(d)
      break
    } catch (ex) {
      d = path.dirname(d)
    }
  }
  log(pkg._id, stage)

  // set the env variables, then run the script as a child process.
  // NOTE: The env vars won't work until node supports env hashes for child procs
  var env = makeEnv(pkg)
  env.npm_lifecycle_event = stage
  env.npm_lifecycle_script = pkg.scripts[stage]
  log.silly(env, "lifecycle env")
  exec("sh", ["-c", env.npm_lifecycle_script], env, function (er) {
    if (er && !npm.ROLLBACK) {
      log("Failed to exec "+stage+" script", pkg._id)
      er.message = pkg._id + " " + stage + ": `" + env.npm_lifecycle_script+"`\n"
                 + er.message
      return cb(er)
    }
    // check for a hook script
    var hook = path.join(npm.dir, ".hooks", stage)
    fs.stat(hook, function (er) {
      if (er) return cb()
      exec(hook, env, function (er) {
        if (er) log("Failed to exec "+stage+" hook script", pkg._id)
        if (npm.ROLLBACK) return cb()
        cb(er)
      })
    })
  })
}

function makeEnv (data, prefix, env) {
  if (data._lifecycleEnv) return data._lifecycleEnv
  prefix = prefix || "npm_package_"
  if (!env) {
    env = {}
    for (var i in process.env) env[i] = process.env[i]
  } else {
    Object.defineProperty(data, "_lifecycleEnv",
      { value : env
      , enumerable : false
      })
  }

  for (var i in data) if (i.charAt(0) !== "_") {
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
    if (data[i] && typeof(data[i]) === "object") {
      env[envKey] = JSON.stringify(data[i])
      makeEnv(data[i], envKey+"_", env)
    } else {
      env[envKey] = String(data[i])
    }
  }
  if (prefix !== "npm_package_") return env
  prefix = "npm_config_"
  var conf = npm.config.get()
  for (var i in conf) if (i.charAt(0) !== "_") {
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
    env[envKey] = String(conf[i])
  }
  return env
}

function cmd (stage, req) { return function (args, cb_) {
  var d = args.length
  function cb (er) {
    if (er) return cb_(er)
    if (-- d === 0) return cb_()
  }
  args.forEach(function (arg) {
    var pkg = arg.split("@")
      , name = pkg.shift()
      , ver = pkg.join("@")
      , json = path.join(npm.dir, name, ver || "active", "package/package.json")
    readJson(json, function (er, data) {
      if (er) return log.er(cb, "Couldn't find "+name + "@" + ver)(er)
      if (ver && ver !== data.version) {
        data.version = ver
        data._id = data.name+"-"+ver
      }
      if ( !data.scripts
          || !(stage in data.scripts)
          && !("pre"+stage in data.scripts)) {
        log("Nothing to do", stage)
        return cb(req ? new Error("Nothing to do") : null)
      }
      lifecycle(data, "pre"+stage, function (er) {
        if (er) return log.er(cb, "Failed pre"+stage)(er)
        lifecycle(data, stage, cb)
      })
    })
  })
}}
<commit_msg>log verbosely the lifecycle event<commit_after>
exports = module.exports = lifecycle
exports.cmd = cmd

var log = require("./log")
  , exec = require("./exec")
  , npm = require("../../npm")
  , path = require("path")
  , readJson = require("./read-json")
  , fs = require("./graceful-fs")

function lifecycle (pkg, stage, cb) {
  while (pkg && pkg._data) pkg = pkg._data
  if (!pkg) return cb(new Error("Invalid package data"))
  log.verbose(pkg._id, "lifecycle "+stage)
  if (!pkg.scripts || !(stage in pkg.scripts)) return cb()

  // run package lifecycle scripts in the package root, or the nearest parent.
  var d = path.join(npm.dir, pkg.name, pkg.version, "package")
  while (d) {
    try {
      process.chdir(d)
      break
    } catch (ex) {
      d = path.dirname(d)
    }
  }
  log(pkg._id, stage)

  // set the env variables, then run the script as a child process.
  // NOTE: The env vars won't work until node supports env hashes for child procs
  var env = makeEnv(pkg)
  env.npm_lifecycle_event = stage
  env.npm_lifecycle_script = pkg.scripts[stage]
  log.silly(env, "lifecycle env")
  exec("sh", ["-c", env.npm_lifecycle_script], env, function (er) {
    if (er && !npm.ROLLBACK) {
      log("Failed to exec "+stage+" script", pkg._id)
      er.message = pkg._id + " " + stage + ": `" + env.npm_lifecycle_script+"`\n"
                 + er.message
      return cb(er)
    }
    // check for a hook script
    var hook = path.join(npm.dir, ".hooks", stage)
    fs.stat(hook, function (er) {
      if (er) return cb()
      exec(hook, env, function (er) {
        if (er) log("Failed to exec "+stage+" hook script", pkg._id)
        if (npm.ROLLBACK) return cb()
        cb(er)
      })
    })
  })
}

function makeEnv (data, prefix, env) {
  if (data._lifecycleEnv) return data._lifecycleEnv
  prefix = prefix || "npm_package_"
  if (!env) {
    env = {}
    for (var i in process.env) env[i] = process.env[i]
  } else {
    Object.defineProperty(data, "_lifecycleEnv",
      { value : env
      , enumerable : false
      })
  }

  for (var i in data) if (i.charAt(0) !== "_") {
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
    if (data[i] && typeof(data[i]) === "object") {
      env[envKey] = JSON.stringify(data[i])
      makeEnv(data[i], envKey+"_", env)
    } else {
      env[envKey] = String(data[i])
    }
  }
  if (prefix !== "npm_package_") return env
  prefix = "npm_config_"
  var conf = npm.config.get()
  for (var i in conf) if (i.charAt(0) !== "_") {
    var envKey = (prefix+i).replace(/[^a-zA-Z0-9_]/g, '_')
    env[envKey] = String(conf[i])
  }
  return env
}

function cmd (stage, req) { return function (args, cb_) {
  var d = args.length
  function cb (er) {
    if (er) return cb_(er)
    if (-- d === 0) return cb_()
  }
  args.forEach(function (arg) {
    var pkg = arg.split("@")
      , name = pkg.shift()
      , ver = pkg.join("@")
      , json = path.join(npm.dir, name, ver || "active", "package/package.json")
    readJson(json, function (er, data) {
      if (er) return log.er(cb, "Couldn't find "+name + "@" + ver)(er)
      if (ver && ver !== data.version) {
        data.version = ver
        data._id = data.name+"-"+ver
      }
      if ( !data.scripts
          || !(stage in data.scripts)
          && !("pre"+stage in data.scripts)) {
        log("Nothing to do", stage)
        return cb(req ? new Error("Nothing to do") : null)
      }
      lifecycle(data, "pre"+stage, function (er) {
        if (er) return log.er(cb, "Failed pre"+stage)(er)
        lifecycle(data, stage, cb)
      })
    })
  })
}}
<|endoftext|>


<commit_before>"use strict";

(
	/**
	 * @param {Window} window
	 * @param {undefined} undefined
	 */
	function ( window, undefined) {

		if (!window["Asc"]) {window["Asc"] = {};}
		var prot;

		/** @constructor */
		function asc_CCellFlag(m, s, w, t, l) {
			this.merge = !!m;
			this.shrinkToFit = !!s;
			this.wrapText = !!w;
			this.selectionType = t;
			this.lockText = !!l;
		}

		asc_CCellFlag.prototype = {
			asc_getMerge: function() { return this.merge; },
			asc_getShrinkToFit: function() { return this.shrinkToFit; },
			asc_getWrapText: function() { return this.wrapText; },
			asc_getSelectionType: function() { return this.selectionType; },
			asc_getLockText: function() { return this.lockText; }
		};

		window["Asc"].asc_CCellFlag = window["Asc"]["asc_CCellFlag"] = asc_CCellFlag;
		prot = asc_CCellFlag.prototype;

		prot["asc_getMerge"] = prot.asc_getMerge;
		prot["asc_getShrinkToFit"] = prot.asc_getShrinkToFit;
		prot["asc_getWrapText"] = prot.asc_getWrapText;
		prot["asc_getSelectionType"] = prot.asc_getSelectionType;
		prot["asc_getLockText"] = prot.asc_getLockText;

		/** @constructor */
		function asc_CFont(name, size, color, b, i, u, s, sub, sup) {
			this.name = name !== undefined ? name : "Arial";
			this.size = size !== undefined ? size : 10;
			this.color = color !== undefined ? color : null;
			this.bold = !!b;
			this.italic = !!i;
			this.underline = !!u;
			this.strikeout = !!s;
			this.subscript = !!sub;
			this.superscript = !!sup;
		}

		asc_CFont.prototype = {
			asc_getName: function () { return this.name; },
			asc_getSize: function () { return this.size; },
			asc_getBold: function () { return this.bold; },
			asc_getItalic: function () { return this.italic; },
			asc_getUnderline: function () { return this.underline; },
			asc_getStrikeout: function () { return this.strikeout; },
			asc_getSubscript: function () { return this.subscript; },
			asc_getSuperscript: function () { return this.superscript; },
			asc_getColor: function () { return this.color; }
		};

		window["Asc"].asc_CFont = window["Asc"]["asc_CFont"] = asc_CFont;
		prot = asc_CFont.prototype;

		prot["asc_getName"]			= prot.asc_getName;
		prot["asc_getSize"]			= prot.asc_getSize;
		prot["asc_getBold"]			= prot.asc_getBold;
		prot["asc_getItalic"]		= prot.asc_getItalic;
		prot["asc_getUnderline"]	= prot.asc_getUnderline;
		prot["asc_getStrikeout"]	= prot.asc_getStrikeout;
		prot["asc_getSubscript"]	= prot.asc_getSubscript;
		prot["asc_getSuperscript"]	= prot.asc_getSuperscript;
		prot["asc_getColor"]		= prot.asc_getColor;

		/** @constructor */
		function asc_CFill(color) {
			this.color = color !== undefined ? color : null;
		}

		asc_CFill.prototype = {
			asc_getColor: function() { return this.color; }
		};

		window["Asc"].asc_CFill = window["Asc"]["asc_CFill"] = asc_CFill;
		prot = asc_CFill.prototype;

		prot["asc_getColor"] = prot.asc_getColor;

		/** @constructor */
		function asc_CBorder(style, color) {
			// ToDo заглушка для создания border-а
			if (typeof style === "string") {
				switch (style) {
					case "thin"		: this.style = c_oAscBorderStyles.Thin; break;
					case "medium"	: this.style = c_oAscBorderStyles.Medium; break;
					case "thick"	: this.style = c_oAscBorderStyles.Thick; break;
					default			: this.style = c_oAscBorderStyles.None; break;
				}
			} else {
				this.style = style !== undefined ? style : c_oAscBorderStyles.None;
			}
			this.color = color !== undefined ? color : null;
		}

		asc_CBorder.prototype = {
			asc_getStyle: function() { return this.style; },
			asc_getColor: function() { return this.color; }
		};

		window["Asc"].asc_CBorder = window["Asc"]["asc_CBorder"] = asc_CBorder;
		prot = asc_CBorder.prototype;

		prot["asc_getStyle"] = prot.asc_getStyle;
		prot["asc_getColor"] = prot.asc_getColor;

		/** @constructor */
		function asc_CBorders() {
			this.left = null;
			this.top = null;
			this.right = null;
			this.bottom = null;
			this.diagDown = null;
			this.diagUp = null;
		}

		asc_CBorders.prototype = {
			asc_getLeft: function() { return this.left; },
			asc_getTop: function() { return this.top; },
			asc_getRight: function() { return this.right; },
			asc_getBottom: function() { return this.bottom; },
			asc_getDiagDown: function() { return this.diagDown; },
			asc_getDiagUp: function() { return this.diagUp; }
		};

		window["Asc"].asc_CBorders = window["Asc"]["asc_CBorders"] = asc_CBorders;
		prot = asc_CBorders.prototype;

		prot["asc_getLeft"]		= prot.asc_getLeft;
		prot["asc_getTop"]		= prot.asc_getTop;
		prot["asc_getRight"]	= prot.asc_getRight;
		prot["asc_getBottom"]	= prot.asc_getBottom;
		prot["asc_getDiagDown"]	= prot.asc_getDiagDown;
		prot["asc_getDiagUp"]	= prot.asc_getDiagUp;

		/** @constructor */
		function asc_CCellInfo() {
			this.name = null;
			this.formula = "";
			this.text = "";
			this.halign = "left";
			this.valign = "top";
			this.flags = null;
			this.font = null;
			this.fill = null;
			this.border = null;
			this.innertext = null;
			this.numFormat = null;
			this.hyperlink = null;
			this.comments = [];
			this.isLocked = false;
			this.isFormatTable = false;
			this.styleName = null;
			this.numFormatType = null;
			this.angle = null;
			this.clearFilter = null;
		}

		asc_CCellInfo.prototype = {
			asc_getName: function(){ return this.name; },
			asc_getFormula: function() { return this.formula; },
			asc_getText: function(){ return this.text; },
			asc_getHorAlign: function(){ return this.halign; },
			asc_getVertAlign: function(){ return this.valign; },
			asc_getFlags: function(){ return this.flags; },
			asc_getFont: function(){ return this.font; },
			asc_getFill: function(){ return this.fill; },
			asc_getBorders: function(){ return this.border; },
			asc_getInnerText: function(){ return this.innertext; },
			asc_getNumFormat: function(){ return this.numFormat; },
			asc_getHyperlink: function(){ return this.hyperlink; },
			asc_getComments: function(){ return this.comments; },
			asc_getLocked: function(){ return this.isLocked; },
			asc_getIsFormatTable: function () { return this.isFormatTable; },
			asc_getStyleName: function () { return this.styleName; },
			asc_getNumFormatType: function(){ return this.numFormatType; },
			asc_getAngle: function () { return this.angle; },
			asc_getClearFilter: function () { return this.clearFilter; }
		};

		window["Asc"].asc_CCellInfo = window["Asc"]["asc_CCellInfo"] = asc_CCellInfo;
		prot = asc_CCellInfo.prototype;

		prot["asc_getName"]				= prot.asc_getName;
		prot["asc_getFormula"]			= prot.asc_getFormula;
		prot["asc_getText"]				= prot.asc_getText;
		prot["asc_getHorAlign"]			= prot.asc_getHorAlign;
		prot["asc_getVertAlign"]		= prot.asc_getVertAlign;
		prot["asc_getFlags"]			= prot.asc_getFlags;
		prot["asc_getFont"]				= prot.asc_getFont;
		prot["asc_getFill"]				= prot.asc_getFill;
		prot["asc_getBorders"]			= prot.asc_getBorders;
		prot["asc_getInnerText"]		= prot.asc_getInnerText;
		prot["asc_getNumFormat"]		= prot.asc_getNumFormat;
		prot["asc_getHyperlink"]		= prot.asc_getHyperlink;
		prot["asc_getComments"]			= prot.asc_getComments;
		prot["asc_getLocked"]			= prot.asc_getLocked;
		prot["asc_getIsFormatTable"]	= prot.asc_getIsFormatTable;
		prot["asc_getStyleName"]		= prot.asc_getStyleName;
		prot["asc_getNumFormatType"]	= prot.asc_getNumFormatType;
		prot["asc_getAngle"]			= prot.asc_getAngle;
		prot["asc_getAutoFilter"]	    = prot.asc_getAutoFilter;
	}
)(window);<commit_msg>+ к предыдущей заливке<commit_after>"use strict";

(
	/**
	 * @param {Window} window
	 * @param {undefined} undefined
	 */
	function ( window, undefined) {

		if (!window["Asc"]) {window["Asc"] = {};}
		var prot;

		/** @constructor */
		function asc_CCellFlag(m, s, w, t, l) {
			this.merge = !!m;
			this.shrinkToFit = !!s;
			this.wrapText = !!w;
			this.selectionType = t;
			this.lockText = !!l;
		}

		asc_CCellFlag.prototype = {
			asc_getMerge: function() { return this.merge; },
			asc_getShrinkToFit: function() { return this.shrinkToFit; },
			asc_getWrapText: function() { return this.wrapText; },
			asc_getSelectionType: function() { return this.selectionType; },
			asc_getLockText: function() { return this.lockText; }
		};

		window["Asc"].asc_CCellFlag = window["Asc"]["asc_CCellFlag"] = asc_CCellFlag;
		prot = asc_CCellFlag.prototype;

		prot["asc_getMerge"] = prot.asc_getMerge;
		prot["asc_getShrinkToFit"] = prot.asc_getShrinkToFit;
		prot["asc_getWrapText"] = prot.asc_getWrapText;
		prot["asc_getSelectionType"] = prot.asc_getSelectionType;
		prot["asc_getLockText"] = prot.asc_getLockText;

		/** @constructor */
		function asc_CFont(name, size, color, b, i, u, s, sub, sup) {
			this.name = name !== undefined ? name : "Arial";
			this.size = size !== undefined ? size : 10;
			this.color = color !== undefined ? color : null;
			this.bold = !!b;
			this.italic = !!i;
			this.underline = !!u;
			this.strikeout = !!s;
			this.subscript = !!sub;
			this.superscript = !!sup;
		}

		asc_CFont.prototype = {
			asc_getName: function () { return this.name; },
			asc_getSize: function () { return this.size; },
			asc_getBold: function () { return this.bold; },
			asc_getItalic: function () { return this.italic; },
			asc_getUnderline: function () { return this.underline; },
			asc_getStrikeout: function () { return this.strikeout; },
			asc_getSubscript: function () { return this.subscript; },
			asc_getSuperscript: function () { return this.superscript; },
			asc_getColor: function () { return this.color; }
		};

		window["Asc"].asc_CFont = window["Asc"]["asc_CFont"] = asc_CFont;
		prot = asc_CFont.prototype;

		prot["asc_getName"]			= prot.asc_getName;
		prot["asc_getSize"]			= prot.asc_getSize;
		prot["asc_getBold"]			= prot.asc_getBold;
		prot["asc_getItalic"]		= prot.asc_getItalic;
		prot["asc_getUnderline"]	= prot.asc_getUnderline;
		prot["asc_getStrikeout"]	= prot.asc_getStrikeout;
		prot["asc_getSubscript"]	= prot.asc_getSubscript;
		prot["asc_getSuperscript"]	= prot.asc_getSuperscript;
		prot["asc_getColor"]		= prot.asc_getColor;

		/** @constructor */
		function asc_CFill(color) {
			this.color = color !== undefined ? color : null;
		}

		asc_CFill.prototype = {
			asc_getColor: function() { return this.color; }
		};

		window["Asc"].asc_CFill = window["Asc"]["asc_CFill"] = asc_CFill;
		prot = asc_CFill.prototype;

		prot["asc_getColor"] = prot.asc_getColor;

		/** @constructor */
		function asc_CBorder(style, color) {
			// ToDo заглушка для создания border-а
			if (typeof style === "string") {
				switch (style) {
					case "thin"		: this.style = c_oAscBorderStyles.Thin; break;
					case "medium"	: this.style = c_oAscBorderStyles.Medium; break;
					case "thick"	: this.style = c_oAscBorderStyles.Thick; break;
					default			: this.style = c_oAscBorderStyles.None; break;
				}
			} else {
				this.style = style !== undefined ? style : c_oAscBorderStyles.None;
			}
			this.color = color !== undefined ? color : null;
		}

		asc_CBorder.prototype = {
			asc_getStyle: function() { return this.style; },
			asc_getColor: function() { return this.color; }
		};

		window["Asc"].asc_CBorder = window["Asc"]["asc_CBorder"] = asc_CBorder;
		prot = asc_CBorder.prototype;

		prot["asc_getStyle"] = prot.asc_getStyle;
		prot["asc_getColor"] = prot.asc_getColor;

		/** @constructor */
		function asc_CBorders() {
			this.left = null;
			this.top = null;
			this.right = null;
			this.bottom = null;
			this.diagDown = null;
			this.diagUp = null;
		}

		asc_CBorders.prototype = {
			asc_getLeft: function() { return this.left; },
			asc_getTop: function() { return this.top; },
			asc_getRight: function() { return this.right; },
			asc_getBottom: function() { return this.bottom; },
			asc_getDiagDown: function() { return this.diagDown; },
			asc_getDiagUp: function() { return this.diagUp; }
		};

		window["Asc"].asc_CBorders = window["Asc"]["asc_CBorders"] = asc_CBorders;
		prot = asc_CBorders.prototype;

		prot["asc_getLeft"]		= prot.asc_getLeft;
		prot["asc_getTop"]		= prot.asc_getTop;
		prot["asc_getRight"]	= prot.asc_getRight;
		prot["asc_getBottom"]	= prot.asc_getBottom;
		prot["asc_getDiagDown"]	= prot.asc_getDiagDown;
		prot["asc_getDiagUp"]	= prot.asc_getDiagUp;

		/** @constructor */
		function asc_CCellInfo() {
			this.name = null;
			this.formula = "";
			this.text = "";
			this.halign = "left";
			this.valign = "top";
			this.flags = null;
			this.font = null;
			this.fill = null;
			this.border = null;
			this.innertext = null;
			this.numFormat = null;
			this.hyperlink = null;
			this.comments = [];
			this.isLocked = false;
			this.isFormatTable = false;
			this.styleName = null;
			this.numFormatType = null;
			this.angle = null;
			this.clearFilter = null;
		}

		asc_CCellInfo.prototype = {
			asc_getName: function(){ return this.name; },
			asc_getFormula: function() { return this.formula; },
			asc_getText: function(){ return this.text; },
			asc_getHorAlign: function(){ return this.halign; },
			asc_getVertAlign: function(){ return this.valign; },
			asc_getFlags: function(){ return this.flags; },
			asc_getFont: function(){ return this.font; },
			asc_getFill: function(){ return this.fill; },
			asc_getBorders: function(){ return this.border; },
			asc_getInnerText: function(){ return this.innertext; },
			asc_getNumFormat: function(){ return this.numFormat; },
			asc_getHyperlink: function(){ return this.hyperlink; },
			asc_getComments: function(){ return this.comments; },
			asc_getLocked: function(){ return this.isLocked; },
			asc_getIsFormatTable: function () { return this.isFormatTable; },
			asc_getStyleName: function () { return this.styleName; },
			asc_getNumFormatType: function(){ return this.numFormatType; },
			asc_getAngle: function () { return this.angle; },
			asc_getClearFilter: function () { return this.clearFilter; }
		};

		window["Asc"].asc_CCellInfo = window["Asc"]["asc_CCellInfo"] = asc_CCellInfo;
		prot = asc_CCellInfo.prototype;

		prot["asc_getName"]				= prot.asc_getName;
		prot["asc_getFormula"]			= prot.asc_getFormula;
		prot["asc_getText"]				= prot.asc_getText;
		prot["asc_getHorAlign"]			= prot.asc_getHorAlign;
		prot["asc_getVertAlign"]		= prot.asc_getVertAlign;
		prot["asc_getFlags"]			= prot.asc_getFlags;
		prot["asc_getFont"]				= prot.asc_getFont;
		prot["asc_getFill"]				= prot.asc_getFill;
		prot["asc_getBorders"]			= prot.asc_getBorders;
		prot["asc_getInnerText"]		= prot.asc_getInnerText;
		prot["asc_getNumFormat"]		= prot.asc_getNumFormat;
		prot["asc_getHyperlink"]		= prot.asc_getHyperlink;
		prot["asc_getComments"]			= prot.asc_getComments;
		prot["asc_getLocked"]			= prot.asc_getLocked;
		prot["asc_getIsFormatTable"]	= prot.asc_getIsFormatTable;
		prot["asc_getStyleName"]		= prot.asc_getStyleName;
		prot["asc_getNumFormatType"]	= prot.asc_getNumFormatType;
		prot["asc_getAngle"]			= prot.asc_getAngle;
		prot["asc_getClearFilter"]	    = prot.asc_getClearFilter;
	}
)(window);<|endoftext|>


<commit_before>var net = require('net');
var EventEmitter = require('events').EventEmitter;
var sys = require('sys');
var ltx = require('ltx');
var StreamParser = require('./stream_parser');

var NS_XMPP_TLS = exports.NS_XMPP_TLS = 'urn:ietf:params:xml:ns:xmpp-tls';
var NS_STREAM = exports.NS_STREAM = 'http://etherx.jabber.org/streams';
var NS_XMPP_STREAMS = 'urn:ietf:params:xml:ns:xmpp-streams';

/** A note on events: this base class will emit 'rawStanza' and leaves
    'stanza' to Client & Component. Therefore we won't confuse the
    user with stanzas before authentication has finished.
*/
function Connection(socket) {
    var self = this;
    EventEmitter.call(this);

    this.charset = 'UTF-8';
    this.xmlns = { stream: NS_STREAM };

    this.socket = socket || new net.Stream();
    this.socket.addListener('data', function(data) {
        self.onData(data);
    });
    this.socket.addListener('end', function() {
        self.onEnd();
    });
    var proxyEvent = function(event) {
        self.socket.addListener(event, function() {
	    var args = Array.prototype.slice.call(arguments);
	    args.unshift(event);
	    self.emit.apply(self, args);
        });
    };
    proxyEvent('data');  // let them sniff
    proxyEvent('drain');
    proxyEvent('close');
}

sys.inherits(Connection, EventEmitter);
exports.Connection = Connection;

// Defaults
Connection.prototype.charset = 'UTF-8';
Connection.prototype.allowTLS = true;

/** Climbs the stanza up if a child was passed,
    but you can send strings and buffers too.
*/
Connection.prototype.send = function(stanza) {
    if (!this.socket.writable) {
        this.socket.end();
        return;
    }

    if (stanza.root) {
        var el = this.rmStreamNs(stanza.root());
        var socket = this.socket;
        el.write(function(s) { socket.write(s); });
        return el;
    } else {
        this.socket.write(stanza);
        return stanza;
    }
};

Connection.prototype.startParser = function() {
    var self = this;
    this.parser = new StreamParser.StreamParser(this.charset, this.maxStanzaSize);

    this.parser.addListener('start', function(attrs) {
        self.streamAttrs = attrs;
        /* We need those xmlns often, store them extra */
        self.streamNsAttrs = {};
        for(var k in attrs) {
        if (k == 'xmlns' ||
            k.substr(0, 6) == 'xmlns:')
                self.streamNsAttrs[k] = attrs[k];
        }

        /* Notify in case we don't wait for <stream:features/>
           (Component or non-1.0 streams)
         */
        self.emit('streamStart', attrs);
    });
    this.parser.addListener('stanza', function(stanza) {
        self.onStanza(self.addStreamNs(stanza));
    });
    this.parser.addListener('error', function(e) {
        self.error(e.condition || 'internal-server-error', e.message);
    });
    this.parser.addListener('end', function() {
        self.stopParser();
        self.end();
    });
};

Connection.prototype.stopParser = function() {
    delete this.parser;
};

Connection.prototype.startStream = function() {
    var attrs = {};
    for(var k in this.xmlns) {
        if (this.xmlns.hasOwnProperty(k)) {
            if (!k)
                attrs.xmlns = this.xmlns[k];
            else
                attrs['xmlns:' + k] = this.xmlns[k];
        }
    }
    if (this.xmppVersion)
        attrs.version = this.xmppVersion;
    if (this.streamTo)
        attrs.to = this.streamTo;
    if (this.streamId)
        attrs.id = this.streamId;

    var el = new ltx.Element('stream:stream', attrs);
    // make it non-empty to cut the closing tag
    el.t(' ');
    var s = el.toString();
    this.send(s.substr(0, s.indexOf(' </stream:stream>')));

    this.streamOpened = true;
};

Connection.prototype.onData = function(data) {
    if (this.parser)
        this.parser.write(data);
};

Connection.prototype.setSecure = function(credentials) {
    var self = this;
    this.stopParser();
    this.socket.setSecure(credentials || this.credentials);
    this.socket.addListener('secure', function() {
        self.startParser();
    });
};

/**
 * This is not an event listener, but takes care of the TLS handshake
 * before 'rawStanza' events are emitted to the derived classes.
 */
Connection.prototype.onStanza = function(stanza) {
    if (stanza.is('error', NS_STREAM)) {
        /* TODO: extract error text */
        this.emit('error', stanza);
    } else if (stanza.is('features', NS_STREAM) &&
               this.allowTLS &&
               stanza.getChild('starttls', NS_XMPP_TLS)) {
        /* Signal willingness to perform TLS handshake */
        this.send(new ltx.Element('starttls', { xmlns: NS_XMPP_TLS }));
    } else if (this.allowTLS &&
               stanza.is('proceed', NS_XMPP_TLS)) {
        /* Server is waiting for TLS handshake */
        this.setSecure();
    } else {
        this.emit('rawStanza', stanza);
    }
};

/**
 *  Add stream xmlns to a stanza, so the user can check for
 * 'jabber:client' etc.
 */
Connection.prototype.addStreamNs = function(stanza) {
    for(var k in this.streamNsAttrs) {
        if (!stanza.attrs[k])
            stanza.attrs[k] = this.streamNsAttrs[k];
    }
    return stanza;
};

/**
 * Remove superfluous xmlns that were aleady declared in
 * our <stream:stream>
 */
Connection.prototype.rmStreamNs = function(stanza) {
    for(var k in this.xmlns) {
        var attr = k ? 'xmlns:' + k : 'xmlns';
        if (stanza.attrs[attr] == this.xmlns[k])
            delete stanza.attrs[attr];
    }
    return stanza;
};

/**
 * Connection has been ended by remote, we will not get any incoming
 * 'data' events. Alternatively, used for 'error' event.
 */
Connection.prototype.onEnd = function() {
    this.stopParser();
    this.socket.end();
};

/**
 * XMPP-style end connection for user
 */
Connection.prototype.end = function() {
    if (this.socket.writable) {
        if (this.streamOpened) {
            this.socket.write('</stream:stream>');
            delete this.streamOpened;
        } else {
            this.socket.end();
        }
    }
};

/**
 * End connection with stream error.
 * Emits 'error' event too.
 *
 * @param {String} condition XMPP error condition, see RFC3920 4.7.3. Defined Conditions
 * @param {String} text Optional error message
 */
Connection.prototype.error = function(condition, message) {
    this.emit('error', new Error(message));

    if (!this.socket.writable)
        return;

    var e = new ltx.Element('stream:error');
    e.c(condition, { xmlns: NS_XMPP_STREAMS });
    if (message)
        e.c('text', { xmlns: NS_XMPP_STREAMS,
                      'xml:lang': 'en' }).
        t(message);

    this.send(e);
    this.end();
};
<commit_msg>connection: documentation<commit_after>var net = require('net');
var EventEmitter = require('events').EventEmitter;
var sys = require('sys');
var ltx = require('ltx');
var StreamParser = require('./stream_parser');

var NS_XMPP_TLS = exports.NS_XMPP_TLS = 'urn:ietf:params:xml:ns:xmpp-tls';
var NS_STREAM = exports.NS_STREAM = 'http://etherx.jabber.org/streams';
var NS_XMPP_STREAMS = 'urn:ietf:params:xml:ns:xmpp-streams';

/**
 Base class for connection-based streams.

 The socket parameter is optional for incoming connections.

 A note on events: this base class will emit 'rawStanza' and leaves
 'stanza' to Client & Component. Therefore we won't confuse the
 user with stanzas before authentication has finished.
*/
function Connection(socket) {
    var self = this;
    EventEmitter.call(this);

    this.charset = 'UTF-8';
    this.xmlns = { stream: NS_STREAM };

    this.socket = socket || new net.Stream();
    this.socket.addListener('data', function(data) {
        self.onData(data);
    });
    this.socket.addListener('end', function() {
        self.onEnd();
    });
    var proxyEvent = function(event) {
        self.socket.addListener(event, function() {
	    var args = Array.prototype.slice.call(arguments);
	    args.unshift(event);
	    self.emit.apply(self, args);
        });
    };
    proxyEvent('data');  // let them sniff
    proxyEvent('drain');
    proxyEvent('close');
}

sys.inherits(Connection, EventEmitter);
exports.Connection = Connection;

// Defaults
Connection.prototype.charset = 'UTF-8';
Connection.prototype.allowTLS = true;

/** Climbs the stanza up if a child was passed,
    but you can send strings and buffers too.
*/
Connection.prototype.send = function(stanza) {
    if (!this.socket.writable) {
        this.socket.end();
        return;
    }

    if (stanza.root) {
        var el = this.rmStreamNs(stanza.root());
        var socket = this.socket;
        el.write(function(s) { socket.write(s); });
        return el;
    } else {
        this.socket.write(stanza);
        return stanza;
    }
};

Connection.prototype.startParser = function() {
    var self = this;
    this.parser = new StreamParser.StreamParser(this.charset, this.maxStanzaSize);

    this.parser.addListener('start', function(attrs) {
        self.streamAttrs = attrs;
        /* We need those xmlns often, store them extra */
        self.streamNsAttrs = {};
        for(var k in attrs) {
        if (k == 'xmlns' ||
            k.substr(0, 6) == 'xmlns:')
                self.streamNsAttrs[k] = attrs[k];
        }

        /* Notify in case we don't wait for <stream:features/>
           (Component or non-1.0 streams)
         */
        self.emit('streamStart', attrs);
    });
    this.parser.addListener('stanza', function(stanza) {
        self.onStanza(self.addStreamNs(stanza));
    });
    this.parser.addListener('error', function(e) {
        self.error(e.condition || 'internal-server-error', e.message);
    });
    this.parser.addListener('end', function() {
        self.stopParser();
        self.end();
    });
};

Connection.prototype.stopParser = function() {
    delete this.parser;
};

Connection.prototype.startStream = function() {
    var attrs = {};
    for(var k in this.xmlns) {
        if (this.xmlns.hasOwnProperty(k)) {
            if (!k)
                attrs.xmlns = this.xmlns[k];
            else
                attrs['xmlns:' + k] = this.xmlns[k];
        }
    }
    if (this.xmppVersion)
        attrs.version = this.xmppVersion;
    if (this.streamTo)
        attrs.to = this.streamTo;
    if (this.streamId)
        attrs.id = this.streamId;

    var el = new ltx.Element('stream:stream', attrs);
    // make it non-empty to cut the closing tag
    el.t(' ');
    var s = el.toString();
    this.send(s.substr(0, s.indexOf(' </stream:stream>')));

    this.streamOpened = true;
};

Connection.prototype.onData = function(data) {
    if (this.parser)
        this.parser.write(data);
};

Connection.prototype.setSecure = function(credentials) {
    var self = this;
    this.stopParser();
    this.socket.setSecure(credentials || this.credentials);
    this.socket.addListener('secure', function() {
        self.startParser();
    });
};

/**
 * This is not an event listener, but takes care of the TLS handshake
 * before 'rawStanza' events are emitted to the derived classes.
 */
Connection.prototype.onStanza = function(stanza) {
    if (stanza.is('error', NS_STREAM)) {
        /* TODO: extract error text */
        this.emit('error', stanza);
    } else if (stanza.is('features', NS_STREAM) &&
               this.allowTLS &&
               stanza.getChild('starttls', NS_XMPP_TLS)) {
        /* Signal willingness to perform TLS handshake */
        this.send(new ltx.Element('starttls', { xmlns: NS_XMPP_TLS }));
    } else if (this.allowTLS &&
               stanza.is('proceed', NS_XMPP_TLS)) {
        /* Server is waiting for TLS handshake */
        this.setSecure();
    } else {
        this.emit('rawStanza', stanza);
    }
};

/**
 *  Add stream xmlns to a stanza, so the user can check for
 * 'jabber:client' etc.
 */
Connection.prototype.addStreamNs = function(stanza) {
    for(var k in this.streamNsAttrs) {
        if (!stanza.attrs[k])
            stanza.attrs[k] = this.streamNsAttrs[k];
    }
    return stanza;
};

/**
 * Remove superfluous xmlns that were aleady declared in
 * our <stream:stream>
 */
Connection.prototype.rmStreamNs = function(stanza) {
    for(var k in this.xmlns) {
        var attr = k ? 'xmlns:' + k : 'xmlns';
        if (stanza.attrs[attr] == this.xmlns[k])
            delete stanza.attrs[attr];
    }
    return stanza;
};

/**
 * Connection has been ended by remote, we will not get any incoming
 * 'data' events. Alternatively, used for 'error' event.
 */
Connection.prototype.onEnd = function() {
    this.stopParser();
    this.socket.end();
};

/**
 * XMPP-style end connection for user
 */
Connection.prototype.end = function() {
    if (this.socket.writable) {
        if (this.streamOpened) {
            this.socket.write('</stream:stream>');
            delete this.streamOpened;
        } else {
            this.socket.end();
        }
    }
};

/**
 * End connection with stream error.
 * Emits 'error' event too.
 *
 * @param {String} condition XMPP error condition, see RFC3920 4.7.3. Defined Conditions
 * @param {String} text Optional error message
 */
Connection.prototype.error = function(condition, message) {
    this.emit('error', new Error(message));

    if (!this.socket.writable)
        return;

    var e = new ltx.Element('stream:error');
    e.c(condition, { xmlns: NS_XMPP_STREAMS });
    if (message)
        e.c('text', { xmlns: NS_XMPP_STREAMS,
                      'xml:lang': 'en' }).
        t(message);

    this.send(e);
    this.end();
};
<|endoftext|>


<commit_before>//two menu implementations -- one native and one in html
'use strict'
D.installMenu=function(x){
  if(D.el){
    var render=function(x){
      if(x['']==='-')return new D.el.MenuItem({type:'separator'})
      var h={label:x[''],click:x.action}
      if(x.group){
        h.type='radio';h.checked=!!x.checked
      }else if(x.checkBoxPref){
        h.type='checkbox';h.checked=!!x.checkBoxPref()
        if(x.action)h.click=function(){x.action(mi.checked)}
        x.checkBoxPref(function(v){mi.checked=!!v})
      }
      if(x.items){h.submenu=new D.el.Menu;x.items.forEach(function(y){h.submenu.append(render(y))})}
      var mi=new D.el.MenuItem(h);return mi
    }
    var m=new D.el.Menu;x.forEach(function(y){m.append(render(y))});D.elw.setMenu(m)
  }else{
    var arg=x
    // DOM structure:
    // ┌.menu───────────────────────────────────────────┐
    // │┌div.m-sub────────────────────────────────┐     │
    // ││            ┌div.m-box──────────────────┐│     │
    // ││┌a.m-opener┐│┌a─────┐┌a─────┐┌div.m-sub┐││     │
    // │││┌span┐    │││┌span┐││┌span┐││         │││     │
    // ││││File│    ││││Open││││Save│││   ...   │││ ... │
    // │││└────┘    │││└────┘││└────┘││         │││     │
    // ││└──────────┘│└──────┘└──────┘└─────────┘││     │
    // ││            └───────────────────────────┘│     │
    // │└─────────────────────────────────────────┘     │
    // └────────────────────────────────────────────────┘
    // Top-level ".m-opener"-s also have class ".m-top"
    function render(x){
      if(!x)return
      if(x['']==='-')return $('
')
      var acc,name=x[''].replace(/_(.)/g,function(_,k){return acc||k==='_'?k:''+(acc=k)+''}) // acc:access key
      var $a=$(''+name+'')
      x.cmd&&$a.append('')
      if(x.group){
        $a.addClass('m-group-'+x.group).toggleClass('m-checked',!!x.checked).on('mousedown mouseup click',function(e){
          $(this).closest('.menu').find('.m-group-'+x.group).removeClass('m-checked');$(this).addClass('m-checked')
          mFocus(null);x.action&&x.action();return!1
        })
      }else if(x.checkBoxPref){
        x.checkBoxPref(function(v){$a.toggleClass('m-checked',!!v)})
        $a.toggleClass('m-checked',!!x.checkBoxPref()).on('mousedown mouseup click',function(e){
          mFocus(null);x.action&&x.action($(this).hasClass('m-checked'));return!1
        })
      }else{
        x.action&&$a.on('mousedown mouseup click',function(e){mFocus(null);x.action();return!1})
      }
      if(!x.items)return $a
      var $b=$('
')
      return $('
').append($a.addClass('m-opener'),$b.append.apply($b,x.items.map(render)))
    }
    var $o // original focused element
    function mFocus(anchor){
      $m.find('.m-open').removeClass('m-open');if(!anchor){$o&&$o.focus();$o=null;return}
      $o||($o=$(':focus'));var $a=$(anchor);$a.parentsUntil('.menu').addClass('m-open')
      $a.is('.m-top')?$a.closest('.m-sub').find('a').eq(1).focus():$a.focus()
    }
    function leftRight(d,$e){ // d: +1 or -1, $e: target element
      if(d>0&&$e.is('.m-opener')){
        mFocus($e.next('.m-box').find('a').first())
      }else if(d<0&&!$e.is('.m-opener')&&$e.parents('.m-sub').length>1){
        mFocus($e.closest('.m-sub').find('.m-opener').first())
      }else{
        var $t=$m.children(),n=$t.length,i=$e.parentsUntil('.menu').last().index();mFocus($t.eq((i+d+n)%n).find('a').eq(1))
      }
      return!1
    }
    function upDown(d,$e){ // d: +1 or -1, $e: target element
      if($e.is('.m-top')){
        mFocus($e.parent().find(':not(hr)').eq(1))
      }else{
        var $s=$e.closest('.m-box').children(':not(hr)'),i=$s.index($e),n=$s.length,$f=$s.eq((i+d+n)%n)
        mFocus($f.is('a')?$f:$f.find('a').first())
      }
      return!1
    }
    var $m=$('
').prependTo('body').empty().addClass('menu').append(arg.map(render))
    $m.find('>.m-sub>.m-opener').addClass('m-top')
    $m.on('mouseover','a',function(){$(this).closest('.menu').children().is('.m-open')&&mFocus(this)})
      .on('mousedown click','a',function(e){
        mFocus($(this).parentsUntil('.menu').last().is('.m-open')&&e.type==='mousedown'?null:this);return!1
      })
      .keydown(function(e){
        switch(CodeMirror.keyNames[e.which]){
          case'Left' :leftRight(-1,$(e.target));break
          case'Right':leftRight( 1,$(e.target));break
          case'Up'   :upDown   (-1,$(e.target));break
          case'Down' :upDown   ( 1,$(e.target));break
          case'Esc':case'F10':mFocus(null);return!1
        }
      })
    $(document).mousedown(function(e){$(e.target).closest('.menu').length||mFocus(null)})
    updMenuShcs(D.prf.keys())
    function updMenuShcs(h){
      var k={};for(var i=0;i<D.cmds.length;i++){var c=D.cmds[i][0],d=D.cmds[i][2];k[c]=(h[c]||d)[0]} // c:code, d:defaults
      $('.m-shc').each(function(){$(this).text(k[$(this).data('cmd')]||'')})
    }
    D.prf.keys(updMenuShcs)
  }
}
<commit_msg>some fixes in html menu<commit_after>//two menu implementations -- one native and one in html
'use strict'
D.installMenu=function(x){
  if(D.el){
    var render=function(x){
      if(x['']==='-')return new D.el.MenuItem({type:'separator'})
      var h={label:x[''],click:x.action}
      if(x.group){
        h.type='radio';h.checked=!!x.checked
      }else if(x.checkBoxPref){
        h.type='checkbox';h.checked=!!x.checkBoxPref()
        if(x.action)h.click=function(){x.action(mi.checked)}
        x.checkBoxPref(function(v){mi.checked=!!v})
      }
      if(x.items){h.submenu=new D.el.Menu;x.items.forEach(function(y){h.submenu.append(render(y))})}
      var mi=new D.el.MenuItem(h);return mi
    }
    var m=new D.el.Menu;x.forEach(function(y){m.append(render(y))});D.elw.setMenu(m)
  }else{
    var arg=x
    // DOM structure:
    // ┌.menu───────────────────────────────────────────┐
    // │┌div.m-sub────────────────────────────────┐     │
    // ││            ┌div.m-box──────────────────┐│     │
    // ││┌a.m-opener┐│┌a─────┐┌a─────┐┌div.m-sub┐││     │
    // │││┌span┐    │││┌span┐││┌span┐││         │││     │
    // ││││File│    ││││Open││││Save│││   ...   │││ ... │
    // │││└────┘    │││└────┘││└────┘││         │││     │
    // ││└──────────┘│└──────┘└──────┘└─────────┘││     │
    // ││            └───────────────────────────┘│     │
    // │└─────────────────────────────────────────┘     │
    // └────────────────────────────────────────────────┘
    // Top-level ".m-opener"-s also have class ".m-top"
    var render=function(x){
      if(!x)return
      if(x['']==='-')return $('
')
      var acc,name=x[''].replace(/&(.)/g,function(_,k){return acc||k==='&'?k:''+(acc=k)+''}) // acc:access key
      var $a=$(''+name+'')
      x.cmd&&$a.append('')
      if(x.group){
        $a.addClass('m-group-'+x.group).toggleClass('m-checked',!!x.checked).on('mousedown mouseup click',function(e){
          $(this).closest('.menu').find('.m-group-'+x.group).removeClass('m-checked');$(this).addClass('m-checked')
          mFocus(null);x.action&&x.action();return!1
        })
      }else if(x.checkBoxPref){
        x.checkBoxPref(function(v){$a.toggleClass('m-checked',!!v)})
        $a.toggleClass('m-checked',!!x.checkBoxPref()).on('mousedown mouseup click',function(e){
          mFocus(null);x.action&&x.action($(this).hasClass('m-checked'));return!1
        })
      }else{
        x.action&&$a.on('mousedown mouseup click',function(e){mFocus(null);x.action();return!1})
      }
      if(!x.items)return $a
      var $b=$('
')
      return $('
').append($a.addClass('m-opener'),$b.append.apply($b,x.items.map(render)))
    }
    var $o // original focused element
    var mFocus=function(anchor){
      $m.find('.m-open').removeClass('m-open');if(!anchor){$o&&$o.focus();$o=null;return}
      $o||($o=$(':focus'));var $a=$(anchor);$a.parentsUntil('.menu').addClass('m-open')
      $a.is('.m-top')?$a.closest('.m-sub').find('a').eq(1).focus():$a.focus()
    }
    var leftRight=function(d,$e){ // d: +1 or -1, $e: target element
      if(d>0&&$e.is('.m-opener')){
        mFocus($e.next('.m-box').find('a').first())
      }else if(d<0&&!$e.is('.m-opener')&&$e.parents('.m-sub').length>1){
        mFocus($e.closest('.m-sub').find('.m-opener').first())
      }else{
        var $t=$m.children(),n=$t.length,i=$e.parentsUntil('.menu').last().index();mFocus($t.eq((i+d+n)%n).find('a').eq(1))
      }
      return!1
    }
    var upDown=function(d,$e){ // d: +1 or -1, $e: target element
      if($e.is('.m-top')){
        mFocus($e.parent().find(':not(hr)').eq(1))
      }else{
        var $s=$e.closest('.m-box').children(':not(hr)'),i=$s.index($e),n=$s.length,$f=$s.eq((i+d+n)%n)
        mFocus($f.is('a')?$f:$f.find('a').first())
      }
      return!1
    }
    var $m=$('
').prependTo('body').empty().addClass('menu').append(arg.map(render))
    $m.find('>.m-sub>.m-opener').addClass('m-top')
    $m.on('mouseover','a',function(){$(this).closest('.menu').children().is('.m-open')&&mFocus(this)})
      .on('mousedown click','a',function(e){
        mFocus($(this).parentsUntil('.menu').last().is('.m-open')&&e.type==='mousedown'?null:this);return!1
      })
      .keydown(function(e){
        switch(CodeMirror.keyNames[e.which]){
          case'Left' :leftRight(-1,$(e.target));break
          case'Right':leftRight( 1,$(e.target));break
          case'Up'   :upDown   (-1,$(e.target));break
          case'Down' :upDown   ( 1,$(e.target));break
          case'Esc':case'F10':mFocus(null);return!1
        }
      })
    $(document).mousedown(function(e){$(e.target).closest('.menu').length||mFocus(null)})
    var updShcs=function(h){
      var k={};for(var i=0;i<D.cmds.length;i++){var c=D.cmds[i][0],d=D.cmds[i][2];k[c]=(h[c]||d)[0]} // c:code, d:defaults
      $('.m-shc').each(function(){$(this).text(k[$(this).data('cmd')]||'')})
    }
    updShcs(D.prf.keys());D.prf.keys(updShcs)
  }
}
<|endoftext|>


<commit_before>
import axios from 'axios'

exports.uploadBlobToDrive = function(blob, info) { //info = object with properties:interviewee_name, folder_id both accessed from interviewService
  LoggedIn(uploadBlob, blob, info)

}

var LoggedIn = function(callback, callbackInput1, callbackInput2) {
     axios.get('/logged-in')
    .then(function(response) {
      //console.log('g usertown', response.data)
      if (response.data.user) {
        localStorage.setItem('googleUser', JSON.stringify(response.data.user))
        //console.log('g usertown', response.data.user)
        console.log('is logged in, now running callback')
        callback(callbackInput1, callbackInput2)
        //return true
      } else {
        localStorage.setItem('googleUser', JSON.stringify(response.data.user))
        console.log('notlodgedin')
      }
      //callback(false)
      //return false
    })
    .catch(function (error) {
        console.log(error);
      });
  };

  // logmit(islogged) {
  //   this.emit('log_result', islogged)
  // }

var uploadBlob = function(blob, info) {
//     //include Authorization: Bearer AbCdEf123456 header if accesstoken in url doesn't work const AuthStr = 'Bearer '.concat(USER_TOKEN);
// axios.get(URL, { headers: { Authorization: AuthStr } })
//  .then(response => {

  var accessToken = JSON.parse(localStorage.getItem('googleUser')).token.token

  var url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable" +'&access_token='+ accessToken;

  var headers = {'X-Upload-Content-Type': blob.type , 'X-Upload-Content-Length': blob.size, 'Content-Type': 'application/json; charset=UTF-8'
}
  var name = info.interviewee_name + '_interviewRecording';
  var parents = [info.folder_id];

  axios({
    method: 'post',
    url: url,
    headers: headers,
    data:{
      name: name,
      parents: parents
    }
  })
  .then(function(response) {
    if (response.status === 200) {
      console.log('success! resumable session URI for upload:', response.headers.location)//should save this url somewhere
      var url = response.headers.location;
      var headers = {'Content-Type': blob.type , 'Content-Length': blob.size }
      axios({
        method: 'put',
        url: url,
        headers: headers,
        data: blob
      })
      .then(function(response) {
        console.log('upload response', response)
      })
      .catch(function (error) {
        console.log(error);
      });

    } else {
      console.log('Error:', response.statusText)
    }
  })
  .catch(function (error) {
    console.log(error);
  });
};

exports.makeFolder = function(name, parents) { //parents passed as an array of parent folder ID's
  var accessToken = JSON.parse(localStorage.getItem('googleUser')).token.token
  var url = "https://www.googleapis.com/drive/v3/files" +"?access_token="+ accessToken;
  var headers = {'Content-Type': 'application/json; charset=UTF-8'};
  var data = {
    'name': 'name',
    'mimeType': 'application/vnd.google-apps.folder'
  }
  if (parents) {
    data.parents = parents;
  }
  axios({
    method: 'post',
    url: url,
    headers: headers,
    data: data
  })
  .then(function(response) {
    console.log('makefolder response:', response);
  })
  .catch(function (error) {
    console.log(error);
  });

}
  // req.body.interviewee
  // req.body.room_folder_id
  // req.body.interview_id
  // req.body.owner_id

  exports.makeInterviewFolder = function(input) {//not in action
    axios.post('/api/addInterviewFolder', input)
    .then(function(response) {
      console.log('interview folder made ', response)
    })
    .catch(function (error) {
      console.log('makefoldererror', error);
    });

  }

// var fileMetadata = {
//   'name' : 'Invoices',
//   'mimeType' : 'application/vnd.google-apps.folder'
// };
// drive.files.create({
//    resource: fileMetadata,
//    fields: 'id'
// }, function(err, file) {
//   if(err) {
//     // Handle error
//     console.log(err);
//   } else {
//     console.log('Folder Id: ', file.id);
//   }
// });
// POST
// https://www.googleapis.com/upload/drive/v3/files
// POST https://www.googleapis.com/drive/v3/files

// PUT https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&upload_id=xa298sd_sdlkj2 HTTP/1.1
// Content-Length: 2000000
// Content-Type: image/jpeg
// [BYTES 0-1999999]

// POST https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable
// X-Upload-Content-Type
// Content-Type//required if have metadata
// Content-Length

// POST https://www.googleapis.com/drive/v3/files?uploadType=resumable HTTP/1.1
// Authorization: Bearer [YOUR_AUTH_TOKEN]
// Content-Length: 38
// Content-Type: application/json; charset=UTF-8
// X-Upload-Content-Type: image/jpeg
// X-Upload-Content-Length: 2000000

// {
//   "name": "myObject"
// }<commit_msg>REMOVE OLD COMMENTS/CODES FROM UploadService.js<commit_after>import axios from 'axios';

exports.uploadBlobToDrive = function(blob, info) { //info = object with properties:interviewee_name, folder_id both accessed from interviewService
  LoggedIn(uploadBlob, blob, info);
};

var LoggedIn = function(callback, callbackInput1, callbackInput2) {
  axios.get('/logged-in')
  .then(function(response) {
    if (response.data.user) {
      localStorage.setItem('googleUser', JSON.stringify(response.data.user));
    } else {
      localStorage.setItem('googleUser', JSON.stringify(response.data.user));
    }
  })
  .catch(function (error) {
    // console.log(error);
  });
};

var uploadBlob = function(blob, info) {
  var accessToken = JSON.parse(localStorage.getItem('googleUser')).token.token;
  var url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable" +'&access_token='+ accessToken;
  var headers = {'X-Upload-Content-Type': blob.type , 'X-Upload-Content-Length': blob.size, 'Content-Type': 'application/json; charset=UTF-8'
};
  var name = info.interviewee_name + '_interviewRecording';
  var parents = [info.folder_id];

  axios({
    method: 'post',
    url: url,
    headers: headers,
    data: {
      name: name,
      parents: parents
    }
  })
  .then(function(response) {
    if (response.status === 200) {
      var url = response.headers.location;
      var headers = {'Content-Type': blob.type , 'Content-Length': blob.size };
      axios({
        method: 'put',
        url: url,
        headers: headers,
        data: blob
      })
      .then(function(response) {
        // console.log('upload response', response);
      })
      .catch(function (error) {
        // console.log(error);
      });

    } else {
      // console.log('Error:', response.statusText);
    }
  })
  .catch(function (error) {
    // console.log(error);
  });
};

exports.makeFolder = function(name, parents) { //parents passed as an array of parent folder ID's
  var accessToken = JSON.parse(localStorage.getItem('googleUser')).token.token;
  var url = "https://www.googleapis.com/drive/v3/files" + "?access_token=" + accessToken;
  var headers = {'Content-Type': 'application/json; charset=UTF-8'};
  var data = {
    'name': 'name',
    'mimeType': 'application/vnd.google-apps.folder'
  };
  if (parents) {
    data.parents = parents;
  }
  axios({
    method: 'post',
    url: url,
    headers: headers,
    data: data
  })
  .then(function(response) {
    // console.log('makefolder response:', response);
  })
  .catch(function (error) {
    // console.log(error);
  });
};

exports.makeInterviewFolder = function(input) {//not in action
  axios.post('/api/addInterviewFolder', input)
  .then(function(response) {
    // console.log('interview folder made ', response)
  })
  .catch(function (error) {
    // console.log('makefoldererror', error);
  });
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import LandingPageInfoBox from './LandingPageInfoBox';

class LandingPage extends Component {

  componentWillMount() {
    this.content  = {
      boxOneTitle: 'Learning By Typing',
      boxOneText: 'Being a faster, more efficient coder is a goal of software engineers everywhere, whether they are beginning or expereienced.  An easy way to improve on that skill is to simply write lines of code.  So why not learn and have competitive fun at the same time?',
      boxTwoTitle: 'Race Against Your Friends',
      boxTwoText: 'Everyone loves some occasionl friendly competition.  At nimblecode, we provide an easy to use platform to display your coding prowess by competing against your friends in real time.  Stretch those fingers and try multiplayer mode with friends!',
      boxThreeTitle: 'About',
      boxThreeText: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu placerat libero, a commodo ligula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus maximus ultrices rutrum. Donec eu nunc a elit sagittis interdum. Nunc sed turpis mi.',
      boxFourTitle: 'JS, Python, and More!',
      boxFourText: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu placerat libero, a commodo ligula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus maximus ultrices rutrum. Donec eu nunc a elit sagittis interdum. Nunc sed turpis mi.'
    };
  }

  render() {
    return (

How fast can you code?

Cool video here

                Start Now!
                Challenge a Friend

              <LandingPageInfoBox title={this.content.boxOneTitle} text={this.content.boxOneText} />

              <LandingPageInfoBox title={this.content.boxTwoTitle} text={this.content.boxTwoText} />

              <LandingPageInfoBox title={this.content.boxThreeTitle} text={this.content.boxThreeText} />

              <LandingPageInfoBox title={this.content.boxFourTitle} text={this.content.boxFourText} />

    );
  }
}

export default LandingPage;
<commit_msg>[content] revised text content on front landing page<commit_after>import React, { Component } from 'react';
import LandingPageInfoBox from './LandingPageInfoBox';

class LandingPage extends Component {

  componentWillMount() {
    this.content  = {
      boxOneTitle: 'Learn By Typing',
      boxOneText: 'Become a faster and more efficient coder, whether you are an experienced or beginner software engineer. One way to improve is to practice writing more lines of code. Why not learn and have competitive fun at the same time?',
      boxTwoTitle: 'Race Against Your Friends',
      boxTwoText: 'Everyone loves friendly competition. We help you display your coding prowess by competing against your friends in real time. Stretch those fingers and challenge your friends!',
      boxThreeTitle: 'About',
      boxThreeText: 'Nimblecode was created by four software engineers at Makersquare, an immersive software engineering program in Los Angeles, CA.  Are you looking to hire? Check out our Github pages in our Contact page above!',
      boxFourTitle: 'JS, Python, and More!',
      boxFourText: 'We are four full stack JavaScript developers, but we understand that you may have a different favorite language.  Currently we only have lessons in JS, with Python under development.  If you would like to see nimblecode support more languages, let us know!'
    };
  }

  render() {
    return (

How fast can you code?

Cool video here

                Start Now!
                Challenge a Friend

              <LandingPageInfoBox title={this.content.boxOneTitle} text={this.content.boxOneText} />

              <LandingPageInfoBox title={this.content.boxTwoTitle} text={this.content.boxTwoText} />

              <LandingPageInfoBox title={this.content.boxThreeTitle} text={this.content.boxThreeText} />

              <LandingPageInfoBox title={this.content.boxFourTitle} text={this.content.boxFourText} />

    );
  }
}

export default LandingPage;
<|endoftext|>


<commit_before>import React from 'react';
import { mount, shallow } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';

import { Links } from './Links';

describe('Links Component - List Items', function () {
  let git;
  let stack;
  let error;
  let wrapper;
  let spy;

  function mockGit() {
    return [
      {
        vendor_id: 172123914,
        title: `and i'm sittin' here on capitol hill`,
        modified: '2017-06-22T18:54:57Z',
        status: 'closed',
        comments: 2,
      }
    ]
  }

  function mockStack() {
    return [
      {
        vendor_id: 1,
        title: 'i\'m just a link',
        modified: 'Sun Feb 22 2015',
        views: 47,
      }
    ]
  }

  beforeEach('render the component', () => {
    git = mockGit()
    stack = mockStack()
    error = 'THIS IS ALL WRONG!!!'
    spy = sinon.spy();
    wrapper = shallow(<Links git={git} stack={stack} error={error} dispatchUpvote={spy} />);
  });

  describe('Contents', () => {
    it('renders the original error message', () => {
      console.log(wrapper.debug())
      expect(wrapper.text()).to.contain(`THIS IS ALL WRONG!!!`)
    })

    it('renders the title of each git and stack search result', () => {
      expect(wrapper.text()).to.contain(`i\'m just a link`);
      expect(wrapper.text()).to.contain(`and i\'m sittin\' here on capitol hill`);
    });

    it('renders the last activity date of each git and stack search result', () => {
      expect(wrapper.text()).to.contain('2017-06-22T18:54:57Z');
      expect(wrapper.text()).to.contain('Sun Feb 22 2015');
    });

    it('renders the status of each git search result', () => {
      expect(wrapper.text()).to.contain('closed');
    });

    it('renders the number of comments for each git search result', () => {
      expect(wrapper.text()).to.contain('2');
    });

    it('renders the number of views for each stack search result', () => {
      expect(wrapper.text()).to.contain('47');
    });
  })

  describe('Voting Buttons', () => {
    it('calls dispatchUpvote when clicked for git result', () => {
      wrapper = shallow(<Links git={git} dispatchUpvote={spy} />);
      wrapper.find('.upvote').simulate('click');
      expect(spy).to.have.property('callCount', 1);
    })

    it('calls dispatchDownvote when clicked for git result', () => {
      wrapper = shallow(<Links git={git} dispatchDownvote={spy} />);
      wrapper.find('.downvote').simulate('click');
      expect(spy).to.have.property('callCount', 1);
    })

    it('calls dispatchUpvote when clicked for Stack Overflow result', () => {
      wrapper = shallow(<Links stack={stack} dispatchUpvote={spy} />);
      wrapper.find('.upvote').simulate('click');
      expect(spy).to.have.property('callCount', 1);
    })

    it('calls dispatchDownvote when clicked for Stack Overflow result', () => {
      wrapper = shallow(<Links stack={stack} dispatchDownvote={spy} />);
      wrapper.find('.downvote').simulate('click');
      expect(spy).to.have.property('callCount', 1);
    })
  })
});
<commit_msg>Chore(Links_Specs): remove console.log<commit_after>import React from 'react';
import { mount, shallow } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';

import { Links } from './Links';

describe('Links Component - List Items', function () {
  let git;
  let stack;
  let error;
  let wrapper;
  let spy;

  function mockGit() {
    return [
      {
        vendor_id: 172123914,
        title: `and i'm sittin' here on capitol hill`,
        modified: '2017-06-22T18:54:57Z',
        status: 'closed',
        comments: 2,
      }
    ]
  }

  function mockStack() {
    return [
      {
        vendor_id: 1,
        title: 'i\'m just a link',
        modified: 'Sun Feb 22 2015',
        views: 47,
      }
    ]
  }

  beforeEach('render the component', () => {
    git = mockGit()
    stack = mockStack()
    error = 'THIS IS ALL WRONG!!!'
    spy = sinon.spy();
    wrapper = shallow(<Links git={git} stack={stack} error={error} dispatchUpvote={spy} />);
  });

  describe('Contents', () => {
    it('renders the original error message', () => {
      expect(wrapper.text()).to.contain(`THIS IS ALL WRONG!!!`)
    })

    it('renders the title of each git and stack search result', () => {
      expect(wrapper.text()).to.contain(`i\'m just a link`);
      expect(wrapper.text()).to.contain(`and i\'m sittin\' here on capitol hill`);
    });

    it('renders the last activity date of each git and stack search result', () => {
      expect(wrapper.text()).to.contain('2017-06-22T18:54:57Z');
      expect(wrapper.text()).to.contain('Sun Feb 22 2015');
    });

    it('renders the status of each git search result', () => {
      expect(wrapper.text()).to.contain('closed');
    });

    it('renders the number of comments for each git search result', () => {
      expect(wrapper.text()).to.contain('2');
    });

    it('renders the number of views for each stack search result', () => {
      expect(wrapper.text()).to.contain('47');
    });
  })

  describe('Voting Buttons', () => {
    it('calls dispatchUpvote when clicked for git result', () => {
      wrapper = shallow(<Links git={git} dispatchUpvote={spy} />);
      wrapper.find('.upvote').simulate('click');
      expect(spy).to.have.property('callCount', 1);
    })

    it('calls dispatchDownvote when clicked for git result', () => {
      wrapper = shallow(<Links git={git} dispatchDownvote={spy} />);
      wrapper.find('.downvote').simulate('click');
      expect(spy).to.have.property('callCount', 1);
    })

    it('calls dispatchUpvote when clicked for Stack Overflow result', () => {
      wrapper = shallow(<Links stack={stack} dispatchUpvote={spy} />);
      wrapper.find('.upvote').simulate('click');
      expect(spy).to.have.property('callCount', 1);
    })

    it('calls dispatchDownvote when clicked for Stack Overflow result', () => {
      wrapper = shallow(<Links stack={stack} dispatchDownvote={spy} />);
      wrapper.find('.downvote').simulate('click');
      expect(spy).to.have.property('callCount', 1);
    })
  })
});
<|endoftext|>


<commit_before>var dummyUsers = {
  0: 'John',
  1: 'Josh',
  2: 'Terry',
  3: 'Justin',
  4: 'Mark',
  5: 'Daniel',
  6: 'Nathan'
};

var arrUsers = [];
for (var key in dummyUsers) {
  arrUsers.push(dummyUsers[key]);
}

var Users = React.createClass({
  render: function() {
    var style = {
      cursor: 'pointer',
      marginBottom: '5px',
      padding: '0',
      margin: '0',
      color: 'grey',
      listStyleType: 'none'
    }
    var listItems = arrUsers.map((function(item, i) {
      return (

          {item}

      );
    }).bind(this));
    return (

{listItems}

    );
  }
});

var UsersTitle = React.createClass({
  render: function() {
    var style = {
      textAlign: 'center',
      color: 'grey'
    };
    return (

Online Users

    );
  }
});

var OnlineUsers = React.createClass({
  render: function() {
    var style = {
      background: '#222222',
      border: '2px solid #444444',
      position: 'absolute',
      width: '100%',
      height: '50%',
      overflow: 'auto',
      resize: 'vertical',
      bottom: '0'
    };
    return (

        <UsersTitle />
        <Users />

    );
  }
});<commit_msg>(fix) Removed unnecessary code in users.js<commit_after>var dummyUsers = {
  0: 'John',
  1: 'Josh',
  2: 'Terry',
  3: 'Justin',
  4: 'Mark',
  5: 'Daniel',
  6: 'Nathan'
};

var arrUsers = [];
for (var key in dummyUsers) {
  arrUsers.push(dummyUsers[key]);
}

var Users = React.createClass({
  render: function() {
    var style = {
      cursor: 'pointer',
      marginBottom: '5px',
      padding: '0',
      margin: '0',
      color: 'grey',
      listStyleType: 'none'
    }
    var listItems = arrUsers.map((function(item, i) {
      return (

          {item}

      );
    }).bind(this));
    return (

{listItems}

    );
  }
});

var UsersTitle = React.createClass({
  render: function() {
    var style = {
      textAlign: 'center',
      color: 'grey'
    };
    return (

Online Users

    );
  }
});

var OnlineUsers = React.createClass({
  render: function() {
    var style = {
      background: '#222222',
      border: '2px solid #444444',
      position: 'absolute',
      width: '100%',
      height: '50%',
      overflow: 'auto',
      resize: 'vertical',
      bottom: '0'
    };
    return (

        <UsersTitle />
        <Users />

    );
  }
});<|endoftext|>