<commit_before>const { interfaces: Ci, utils: Cu, classes: Cc } = Components;

Cu.import("resource:///modules/imServices.jsm");
Cu.import("resource:///modules/imWindows.jsm");

const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

let csl = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
function log(msg) csl.logStringMessage(msg);

let pre = "extensions.otr.";

let ui = {

  otr: null,
  prefs: null,
  origAddConv: null,

  init: function() {
    log("init")
    ui.prefs = Services.prefs.getBranch(pre);
    let opts = {
      requireEncryption: Services.prefs.getBoolPref(pre + "requireEncryption")
    };
    ui.otr = new OTR(opts);
    ui.otr.addObserver(ui);
    ui.otr.loadFiles().then(function() {
      log("attach handlers")
      Services.obs.addObserver(ui.otr, "new-ui-conversation", false);
      Services.obs.addObserver(ui, "conversation-loaded", false);
      Services.obs.addObserver(ui, "account-disconnecting", false);
      ui.prefs.addObserver("", ui, false);
    }, function(reason) { throw new Error(reason); });
  },

  disconnect: function(aAccount) {
    Conversations._conversations.forEach(function(binding) {
      let conv = binding._conv;
      if (conv.isChat || conv.account.id !== aAccount.id)
        return;
      ui.otr.disconnect(conv.target);
    });
  },

  changePref: function(aMsg) {
    switch(aMsg) {
    case "requireEncryption":
      ui.otr.setPolicy(Services.prefs.getBoolPref(pre + "requireEncryption"));
      break;
    default:
      log(aMsg);
    }
  },

  resize: function(aEvent) {
    let convElt = aEvent.originalTarget.document.getElementById("conversations");
    if (!convElt)
      return;

    let conversations = convElt.conversations;
    for each (let binding in conversations) {
      if (binding.conv.isChat)
        continue;
      ui.addButton(binding, false);
    }
  },

  tabListener: function(aObject) {
    let binding = aObject.ownerDocument.getBindingParent(aObject);
    ui.addButton(binding, true);
  },

  addButton: function(binding, attachResize) {
    let convTop = binding.getElt("conv-top-info");
    let doc = convTop.ownerDocument;
    let window = doc.defaultView;

    if (attachResize)
      window.addEventListener("resize", ui.resize, false);

    // only add to large view
    if (window.getComputedStyle(convTop).MozBinding.indexOf("conv-info-large") < 0)
      return;

    // handle timing issue
    if (doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:hbox") != null)
      return;

    let smElt = doc.getAnonymousElementByAttribute(convTop, "anonid", "statusMessage");

    // workaround so status message still gets its attributes updated
    let broadcaster = doc.createElementNS(XULNS, "xul:broadcaster")
    let broadcastID = "brID_" + uniqueId.next();
    broadcaster.setAttribute("id", broadcastID);
    broadcaster.setAttribute("isBroadcaster", "true");
    smElt.parentNode.appendChild(broadcaster);
    smElt.setAttribute("observes", broadcastID);

    let hboxElt = doc.createElementNS(XULNS, "xul:hbox");
    hboxElt.setAttribute("flex", "1");
    hboxElt.setAttribute("anonid", "otr:hbox");
    smElt.parentNode.appendChild(hboxElt);
    hboxElt.appendChild(smElt);

    let tbb = doc.createElementNS(XULNS, "xul:toolbarbutton");
    tbb.setAttribute("anonid", "otr:button");
    tbb.setAttribute("tooltiptext", "OTR");
    tbb.setAttribute("type", "button");
    tbb.addEventListener("command", function(e) {
      e.preventDefault();
      menupopup.openPopup(tbb, "after_start");
    }, false);

    tbb.style.margin = "29px 0px 0px 0px";
    tbb.style.setProperty("padding", "0", "important");

    let menupopup = doc.createElementNS(XULNS, "xul:menupopup");

    let start = doc.createElementNS(XULNS, "xul:menuitem");
    start.setAttribute("label", "Start OTR session");
    start.setAttribute("anonid", "otr:start");
    start.addEventListener("click", function(e) {
      e.preventDefault();
      if (!e.target.disabled)
        ui.otr.sendQueryMsg(binding._conv.target);
    });
    menupopup.appendChild(start);

    let end = doc.createElementNS(XULNS, "xul:menuitem");
    end.setAttribute("label", "End OTR session");
    end.setAttribute("anonid", "otr:end");
    end.addEventListener("click", function(e) {
      e.preventDefault();
      if (!e.target.disabled)
        ui.otr.disconnect(binding._conv.target);
    });
    menupopup.appendChild(end);

    tbb.appendChild(menupopup);

    // get otr msg state
    let context = ui.otr.getContext(binding._conv.target);
    ui.setMsgState(context.msgState, tbb, start, end);

    hboxElt.appendChild(tbb);
  },

  updateButton: function(context) {
    let conv = ui.otr.convos.get(context.id);
    Conversations._conversations.forEach(function(binding) {
      if (binding._conv.id !== conv.conv.id)
        return;

      let convTop = binding.getElt("conv-top-info");
      let doc = convTop.ownerDocument;
      let window = doc.defaultView;

      if (window.getComputedStyle(convTop).MozBinding.indexOf("conv-info-large") < 0)
        return;

      let tbb = doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:button");
      let start = doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:start");
      let end = doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:end");
      ui.setMsgState(context.msgState, tbb, start, end);
    });
  },

  // set msg state on toolbar button
  setMsgState: function(msgState, tbb, start, end) {
    let label, color, disableStart, disableEnd;
    switch(msgState) {
    case ui.otr.messageState.OTRL_MSGSTATE_ENCRYPTED:
    case ui.otr.messageState.OTRL_MSGSTATE_FINISHED:
      label = "Private";
      color = "black";
      disableStart = true;
      disableEnd = false;
      break;
    case ui.otr.messageState.OTRL_MSGSTATE_PLAINTEXT:
      label = "Not private";
      color = "red";
      disableStart = false;
      disableEnd = true;
      break;
    default:
      throw new Error("Shouldn't be here.");
    }
    tbb.setAttribute("label", label);
    tbb.style.color = color;
    start.setAttribute("disabled", disableStart);
    end.setAttribute("disabled", disableEnd);
  },

  observe: function(aObject, aTopic, aMsg) {
    switch(aTopic) {
    case "nsPref:changed":
      this.changePref(aMsg);
      break;
    case "conversation-loaded":
      this.tabListener(aObject);
      break;
    case "msg-state":
      this.updateButton(aObject);
      break;
    case "account-disconnecting":
      ui.disconnect(aObject);
      break;
    default:
      log(aTopic)
    }
  },

  resetConv: function(binding) {
    ui.otr.removeConversation(binding._conv);

    let convTop = binding.getElt("conv-top-info");
    let doc = convTop.ownerDocument;
    let window = doc.defaultView;
    window.removeEventListener("resize", ui.resize, false);

    if (window.getComputedStyle(convTop).MozBinding.indexOf("conv-info-large") < 0)
      return;

    if (!doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:button"))
      return;

    let smElt = doc.getAnonymousElementByAttribute(convTop, "anonid", "statusMessage");
    smElt.parentNode.appendChild(smElt);
    stackElt.removeChild(doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:hbox"));
    stackElt.removeChild(doc.getAnonymousElementByAttribute(convTop, "isBroadcaster", "true"));
    smElt.removeAttribute("observes");
  },

  destroy: function() {
    Services.obs.removeObserver(ui.otr, "new-ui-conversation");
    Services.obs.removeObserver(ui, "conversation-loaded");
    Services.obs.removeObserver(ui, "account-disconnecting");
    Conversations._conversations.forEach(ui.resetConv);
    ui.prefs.removeObserver("", ui);
    ui.otr.removeObserver(ui);
    // ui.otr.close();
  }

};

function startup(data, reason) {
  Cu.import("chrome://otr/content/otr.js");
  ui.init()
}

function shutdown(data, reason) {
  if (reason === APP_SHUTDOWN)
    return;

  ui.destroy();
  Cu.unload("chrome://otr/content/otr.js");
}

function install(data, reason) {}
function uninstall(data, reason) {}<commit_msg>Nevermind, it was fine as is<commit_after>const { interfaces: Ci, utils: Cu, classes: Cc } = Components;

Cu.import("resource:///modules/imServices.jsm");
Cu.import("resource:///modules/imWindows.jsm");

const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";

let csl = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
function log(msg) csl.logStringMessage(msg);

let ui = {

  otr: null,
  prefs: null,
  origAddConv: null,

  init: function() {
    log("init")
    ui.prefs = Services.prefs.getBranch("extensions.otr.");
    let opts = {
      requireEncryption: ui.prefs.getBoolPref("requireEncryption")
    };
    ui.otr = new OTR(opts);
    ui.otr.addObserver(ui);
    ui.otr.loadFiles().then(function() {
      log("attach handlers")
      Services.obs.addObserver(ui.otr, "new-ui-conversation", false);
      Services.obs.addObserver(ui, "conversation-loaded", false);
      Services.obs.addObserver(ui, "account-disconnecting", false);
      ui.prefs.addObserver("", ui, false);
    }, function(reason) { throw new Error(reason); });
  },

  disconnect: function(aAccount) {
    Conversations._conversations.forEach(function(binding) {
      let conv = binding._conv;
      if (conv.isChat || conv.account.id !== aAccount.id)
        return;
      ui.otr.disconnect(conv.target);
    });
  },

  changePref: function(aMsg) {
    switch(aMsg) {
    case "requireEncryption":
      ui.otr.setPolicy(ui.prefs.getBoolPref("requireEncryption"));
      break;
    default:
      log(aMsg);
    }
  },

  resize: function(aEvent) {
    let convElt = aEvent.originalTarget.document.getElementById("conversations");
    if (!convElt)
      return;

    let conversations = convElt.conversations;
    for each (let binding in conversations) {
      if (binding.conv.isChat)
        continue;
      ui.addButton(binding, false);
    }
  },

  tabListener: function(aObject) {
    let binding = aObject.ownerDocument.getBindingParent(aObject);
    ui.addButton(binding, true);
  },

  addButton: function(binding, attachResize) {
    let convTop = binding.getElt("conv-top-info");
    let doc = convTop.ownerDocument;
    let window = doc.defaultView;

    if (attachResize)
      window.addEventListener("resize", ui.resize, false);

    // only add to large view
    if (window.getComputedStyle(convTop).MozBinding.indexOf("conv-info-large") < 0)
      return;

    // handle timing issue
    if (doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:hbox") != null)
      return;

    let smElt = doc.getAnonymousElementByAttribute(convTop, "anonid", "statusMessage");

    // workaround so status message still gets its attributes updated
    let broadcaster = doc.createElementNS(XULNS, "xul:broadcaster")
    let broadcastID = "brID_" + uniqueId.next();
    broadcaster.setAttribute("id", broadcastID);
    broadcaster.setAttribute("isBroadcaster", "true");
    smElt.parentNode.appendChild(broadcaster);
    smElt.setAttribute("observes", broadcastID);

    let hboxElt = doc.createElementNS(XULNS, "xul:hbox");
    hboxElt.setAttribute("flex", "1");
    hboxElt.setAttribute("anonid", "otr:hbox");
    smElt.parentNode.appendChild(hboxElt);
    hboxElt.appendChild(smElt);

    let tbb = doc.createElementNS(XULNS, "xul:toolbarbutton");
    tbb.setAttribute("anonid", "otr:button");
    tbb.setAttribute("tooltiptext", "OTR");
    tbb.setAttribute("type", "button");
    tbb.addEventListener("command", function(e) {
      e.preventDefault();
      menupopup.openPopup(tbb, "after_start");
    }, false);

    tbb.style.margin = "29px 0px 0px 0px";
    tbb.style.setProperty("padding", "0", "important");

    let menupopup = doc.createElementNS(XULNS, "xul:menupopup");

    let start = doc.createElementNS(XULNS, "xul:menuitem");
    start.setAttribute("label", "Start OTR session");
    start.setAttribute("anonid", "otr:start");
    start.addEventListener("click", function(e) {
      e.preventDefault();
      if (!e.target.disabled)
        ui.otr.sendQueryMsg(binding._conv.target);
    });
    menupopup.appendChild(start);

    let end = doc.createElementNS(XULNS, "xul:menuitem");
    end.setAttribute("label", "End OTR session");
    end.setAttribute("anonid", "otr:end");
    end.addEventListener("click", function(e) {
      e.preventDefault();
      if (!e.target.disabled)
        ui.otr.disconnect(binding._conv.target);
    });
    menupopup.appendChild(end);

    tbb.appendChild(menupopup);

    // get otr msg state
    let context = ui.otr.getContext(binding._conv.target);
    ui.setMsgState(context.msgState, tbb, start, end);

    hboxElt.appendChild(tbb);
  },

  updateButton: function(context) {
    let conv = ui.otr.convos.get(context.id);
    Conversations._conversations.forEach(function(binding) {
      if (binding._conv.id !== conv.conv.id)
        return;

      let convTop = binding.getElt("conv-top-info");
      let doc = convTop.ownerDocument;
      let window = doc.defaultView;

      if (window.getComputedStyle(convTop).MozBinding.indexOf("conv-info-large") < 0)
        return;

      let tbb = doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:button");
      let start = doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:start");
      let end = doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:end");
      ui.setMsgState(context.msgState, tbb, start, end);
    });
  },

  // set msg state on toolbar button
  setMsgState: function(msgState, tbb, start, end) {
    let label, color, disableStart, disableEnd;
    switch(msgState) {
    case ui.otr.messageState.OTRL_MSGSTATE_ENCRYPTED:
    case ui.otr.messageState.OTRL_MSGSTATE_FINISHED:
      label = "Private";
      color = "black";
      disableStart = true;
      disableEnd = false;
      break;
    case ui.otr.messageState.OTRL_MSGSTATE_PLAINTEXT:
      label = "Not private";
      color = "red";
      disableStart = false;
      disableEnd = true;
      break;
    default:
      throw new Error("Shouldn't be here.");
    }
    tbb.setAttribute("label", label);
    tbb.style.color = color;
    start.setAttribute("disabled", disableStart);
    end.setAttribute("disabled", disableEnd);
  },

  observe: function(aObject, aTopic, aMsg) {
    switch(aTopic) {
    case "nsPref:changed":
      this.changePref(aMsg);
      break;
    case "conversation-loaded":
      this.tabListener(aObject);
      break;
    case "msg-state":
      this.updateButton(aObject);
      break;
    case "account-disconnecting":
      ui.disconnect(aObject);
      break;
    default:
      log(aTopic)
    }
  },

  resetConv: function(binding) {
    ui.otr.removeConversation(binding._conv);

    let convTop = binding.getElt("conv-top-info");
    let doc = convTop.ownerDocument;
    let window = doc.defaultView;
    window.removeEventListener("resize", ui.resize, false);

    if (window.getComputedStyle(convTop).MozBinding.indexOf("conv-info-large") < 0)
      return;

    if (!doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:button"))
      return;

    let smElt = doc.getAnonymousElementByAttribute(convTop, "anonid", "statusMessage");
    smElt.parentNode.appendChild(smElt);
    stackElt.removeChild(doc.getAnonymousElementByAttribute(convTop, "anonid", "otr:hbox"));
    stackElt.removeChild(doc.getAnonymousElementByAttribute(convTop, "isBroadcaster", "true"));
    smElt.removeAttribute("observes");
  },

  destroy: function() {
    Services.obs.removeObserver(ui.otr, "new-ui-conversation");
    Services.obs.removeObserver(ui, "conversation-loaded");
    Services.obs.removeObserver(ui, "account-disconnecting");
    Conversations._conversations.forEach(ui.resetConv);
    ui.prefs.removeObserver("", ui);
    ui.otr.removeObserver(ui);
    // ui.otr.close();
  }

};

function startup(data, reason) {
  Cu.import("chrome://otr/content/otr.js");
  ui.init()
}

function shutdown(data, reason) {
  if (reason === APP_SHUTDOWN)
    return;

  ui.destroy();
  Cu.unload("chrome://otr/content/otr.js");
}

function install(data, reason) {}
function uninstall(data, reason) {}<|endoftext|>


<commit_before>var AudioDataAnalyzer = require('./library/audioDataAnalyzer').analyzer;

var TrackDownloader = require('./library/trackDownloader').downloader;

var http = require('http');

var fs = require('fs');

var url = require('url');

var querystring = require('querystring');

var serverPort = 35000;
var serverIp = '127.0.0.1';

/**
 *
 * create a new nodejs server handle incoming requests
 *
 * @param {type} request
 * @param {type} response
 */
http.createServer(function (request, response) {

    // parse the url
    var urlParts = url.parse(request.url);

    //console.log(urlParts);

    // check if its is the url of a javascript file
    if (urlParts.pathname.split('.').pop() === 'js') {

        // if the file exists send it to the client
        // not really secure but this is a prototype
        fs.readFile('client' + urlParts.pathname, function(error, fileContent) {

            if (!error) {

                // send the static file to the client
                response.writeHead(200, { 'Content-Type': 'application/javascript' });
                response.write(fileContent);
                response.end();

            } else {

                // the file was not on the server send a 404 page to the client
                response.writeHead(404, { 'Content-Type': 'text/html' });
                response.write('page not found');
                response.end();

            }

        });

    } else {

        // handle the "routes"
        switch(urlParts.pathname) {
            case '/':
                fs.readFile('client/index.html', function(error, html) {

                    if (!error) {

                        // send the main html page to the client
                        response.writeHead(200, { 'Content-Type': 'text/html' });
                        response.write(html);
                        response.end();

                    } else {

                        // the main page could not be found return a page not
                        // found message
                        response.writeHead(404, { 'Content-Type': 'text/html' });
                        response.write('page not found');
                        response.end();

                    }

                });
                break;
            case '/getwavedata':

                var queryObject = querystring.parse(urlParts.query);

                if (typeof queryObject !== 'undefined' && queryObject.trackId !== 'undefined' && queryObject.trackFormat !== 'undefined' && queryObject.peaksAmount !== 'undefined') {

                    getWaveData(queryObject.trackId, queryObject.trackFormat, queryObject.peaksAmount, function(error, peaks) {

                        if (!error) {

                            // success, send the track peaks to the client
                            response.writeHead(200, { 'Content-Type': 'application/json' });
                            response.write('{ "peaks": ' + JSON.stringify(peaks) + ' }');
                            response.end();

                        } else {

                            // fail, send the error to the client
                            response.writeHead(500, { 'Content-Type': 'application/json' });
                            response.write('{ error: ' + error + ' }');
                            response.end();

                        }

                    });

                }

                break;
            case '/getTrack':

                var queryObject = querystring.parse(urlParts.query);

                if (typeof queryObject !== 'undefined' && queryObject.trackId !== 'undefined' && queryObject.trackFormat !== 'undefined') {

                    var trackName = queryObject.trackId + '.' + queryObject.trackFormat;

                    fs.readFile('downloaded_tracks/' + trackName, function(error, track) {

                        var mimeType;

                        switch(queryObject.trackFormat) {
                            case 'ogg':
                                mimeType = 'audio/ogg';
                                break;
                            case 'mp3':
                                mimeType = 'audio/mpeg';
                                break;
                        }

                        if (!error) {

                            response.writeHead(200, { 'Content-Type': mimeType });
                            response.write(track);
                            response.end();

                        } else {

                            response.writeHead(404, { 'Content-Type': 'text/html' });
                            response.write('page not found');
                            response.end();

                        }

                    });

                }

            default:
                response.writeHead(404, { 'Content-Type': 'text/html' });
                response.write('page not found');
                response.end();

        }
    }

}).listen(serverPort, serverIp);

console.log('server is listening, ip: ' + serverIp + ', port: ' + serverPort);

/**
 *
 * get the wave data for a given trackId
 *
 * @param {type} trackId
 * @param {type} trackFormat
 * @param {type} peaksAmount
 * @param {type} callback
 * @returns {undefined}
 */
var getWaveData = function getWaveDataFunction(trackId, trackFormat, peaksAmount, callback) {

    // initialize the audioAnalyzer
    var audioDataAnalyzer = new AudioDataAnalyzer();

    // initialize the track downloader
    var trackDownloader = new TrackDownloader();

    var temporaryTracksDirecotry = './downloaded_tracks';

    // download the track and write it on the disc of it does not already exist
    trackDownloader.writeTrackToDisc(trackId, function writeTrackCallback(error, trackPath) {

        // if there was no error downloading and writing the track
        if (!error) {

            // analyze the track using ffmpeg
            audioDataAnalyzer.getPeaks(trackPath, peaksAmount, function getValuesCallback(error, peaks) {

                // if there was no error analyzing the track
                if (!error) {

                    callback(false, peaks);

                } else {

                    callback(error);

                }

            });

        } else {

            callback(error);

        }

    }, temporaryTracksDirecotry, trackFormat);

};<commit_msg>web audio api buffer<commit_after>var AudioDataAnalyzer = require('./library/audioDataAnalyzer').analyzer;

var TrackDownloader = require('./library/trackDownloader').downloader;

var http = require('http');

var fs = require('fs');

var url = require('url');

var querystring = require('querystring');

var serverPort = 35000;
var serverIp = '127.0.0.1';

/**
 *
 * create a new nodejs server handle incoming requests
 *
 * @param {type} request
 * @param {type} response
 */
http.createServer(function (request, response) {

    // parse the url
    var urlParts = url.parse(request.url);

    //console.log(urlParts);

    // check if its is the url of a javascript file
    if (urlParts.pathname.split('.').pop() === 'js') {

        // if the file exists send it to the client
        // not really secure but this is a prototype
        // TODO: filter the file request
        fs.readFile('client' + urlParts.pathname, function(error, fileContent) {

            if (!error) {

                // send the static file to the client
                response.writeHead(200, { 'Content-Type': 'application/javascript' });
                response.write(fileContent);
                response.end();

            } else {

                // the file was not on the server send a 404 page to the client
                response.writeHead(404, { 'Content-Type': 'text/html' });
                response.write('page not found');
                response.end();

            }

        });

    } else {

        // handle the "routes"
        switch(urlParts.pathname) {
            case '/':
                fs.readFile('client/index.html', function(error, html) {

                    if (!error) {

                        // send the main html page to the client
                        response.writeHead(200, { 'Content-Type': 'text/html' });
                        response.write(html);
                        response.end();

                    } else {

                        // the main page could not be found return a page not
                        // found message
                        response.writeHead(404, { 'Content-Type': 'text/html' });
                        response.write('page not found');
                        response.end();

                    }

                });
                break;
            case '/getwavedata':

                var queryObject = querystring.parse(urlParts.query);

                if (typeof queryObject !== 'undefined' && queryObject.trackId !== 'undefined' && queryObject.trackFormat !== 'undefined' && queryObject.peaksAmount !== 'undefined') {

                    getWaveData(queryObject.trackId, queryObject.trackFormat, queryObject.peaksAmount, function(error, peaks) {

                        if (!error) {

                            // success, send the track peaks to the client
                            response.writeHead(200, { 'Content-Type': 'application/json' });
                            response.write('{ "peaks": ' + JSON.stringify(peaks) + ' }');
                            response.end();

                        } else {

                            // fail, send the error to the client
                            response.writeHead(500, { 'Content-Type': 'application/json' });
                            response.write('{ error: ' + error + ' }');
                            response.end();

                        }

                    });

                }

                break;
            case '/getTrack':

                var queryObject = querystring.parse(urlParts.query);

                console.log(queryObject);

                if (typeof queryObject !== 'undefined' && queryObject.trackId !== 'undefined' && queryObject.trackFormat !== 'undefined') {

                    var trackName = queryObject.trackId + '.' + queryObject.trackFormat;
                    var trackPath = 'downloaded_tracks/' + trackName;

                    var fileStat = fs.statSync(trackPath);

                    var mimeType;

                    switch(queryObject.trackFormat) {
                        case 'ogg':
                            mimeType = 'audio/ogg';
                            break;
                        case 'mp3':
                            mimeType = 'audio/mpeg';
                            break;
                    }

                    response.writeHead(200, { 'Content-Type': mimeType, 'Content-Length': fileStat.size });

                    var readStream = fs.createReadStream(trackPath);

                    readStream.pipe(response);

                }

                break;
            default:
                response.writeHead(404, { 'Content-Type': 'text/html' });
                response.write('page not found');
                response.end();

        }
    }

}).listen(serverPort, serverIp);

console.log('server is listening, ip: ' + serverIp + ', port: ' + serverPort);

/**
 *
 * get the wave data for a given trackId
 *
 * @param {type} trackId
 * @param {type} trackFormat
 * @param {type} peaksAmount
 * @param {type} callback
 * @returns {undefined}
 */
var getWaveData = function getWaveDataFunction(trackId, trackFormat, peaksAmount, callback) {

    // initialize the audioAnalyzer
    var audioDataAnalyzer = new AudioDataAnalyzer();

    // initialize the track downloader
    var trackDownloader = new TrackDownloader();

    var temporaryTracksDirecotry = './downloaded_tracks';

    // download the track and write it on the disc of it does not already exist
    trackDownloader.writeTrackToDisc(trackId, function writeTrackCallback(error, trackPath) {

        // if there was no error downloading and writing the track
        if (!error) {

            // analyze the track using ffmpeg
            audioDataAnalyzer.getPeaks(trackPath, peaksAmount, function getValuesCallback(error, peaks) {

                // if there was no error analyzing the track
                if (!error) {

                    callback(false, peaks);

                } else {

                    callback(error);

                }

            });

        } else {

            callback(error);

        }

    }, temporaryTracksDirecotry, trackFormat);

};<|endoftext|>


<commit_before>/*global app, chai, sinon */
"use strict";

var expect = chai.expect;

describe("UsersView", function() {
  var sandbox, user, collection;

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

    user = new app.models.CurrentUser();

    collection = new app.models.UserSet([
      {email: "a@a.com"},
      {email: "b@b.com"}
    ]);
  });

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

  describe("Unit tests", function() {
    var usersView;

    beforeEach(function() {
      sandbox.stub(app.views.UsersView.prototype, "render");

      usersView = new app.views.UsersView({
        user: user,
        collection: collection,
        appStatus: new app.models.AppStatus()
      });
    });

    describe("#initialize", function() {
      it("should create all child views", function() {
        expect(usersView.views).to.have.length.of(2);
      });
    });

    describe("Events", function() {
      describe("CurrentUser", function() {
        describe("signin", function() {
          it("should render the view when the user signs in and the " +
             "collection is reset", function() {
            user.trigger("signin");
            collection.reset([]);

            sinon.assert.calledOnce(usersView.render);
          });

          it("should render a single time once user is signed in", function() {
            user.trigger("signin");
            collection.reset([]);
            collection.reset([]);

            sinon.assert.calledOnce(usersView.render);
          });
        });

        describe("signout", function() {
          it("should render the view", function() {
            user.trigger("signout");

            sinon.assert.calledOnce(usersView.render);
          });
        });
      });

      describe("AppStatus events", function() {
        beforeEach(function() {
          usersView.collection.reset([
            {username: "bob", presence: "connected"},
            {username: "bill", presence: "disconnected"}
          ]);
        });

        it("should change user status if a reconnection is ongoing",
          function() {
            usersView.appStatus.set("reconnecting", {timeout: 42, attempt: 2});
            expect(usersView.collection.every(function(user) {
              return user.get("presence") === "disconnected";
            })).to.eql(true);
          });

        it("should not change the users' status if no reconnection is ongoing",
          function(){
          usersView.appStatus.set("reconnecting", false);
          expect(usersView.collection.every(function(user) {
            return user.get("presence") === "disconnected";
          })).to.eql(false);
        });
      });
    });
  });

  describe("DOM tests", function() {
    var usersView;

    beforeEach(function() {
      $("#fixtures").append('

');

      usersView = new app.views.UsersView({
        user: user,
        collection: collection,
        appStatus: new app.models.AppStatus()
      });
    });

    afterEach(function() {
      $("#fixtures").empty();
    });

    describe("#render", function() {
      it("should render all child views", function() {
        usersView.render();

        expect(usersView.$("li")).to.have.length.of(2);
      });
    });
  });
});
<commit_msg>added test for UserView#render on user presence changed<commit_after>/*global app, chai, sinon */
"use strict";

var expect = chai.expect;

describe("UsersView", function() {
  var sandbox, user, collection;

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

    user = new app.models.CurrentUser();

    collection = new app.models.UserSet([
      {email: "a@a.com", presence: "disconnected"},
      {email: "b@b.com", presence: "disconnected"}
    ]);
  });

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

  describe("Unit tests", function() {
    var usersView;

    beforeEach(function() {
      sandbox.stub(app.views.UsersView.prototype, "render");

      usersView = new app.views.UsersView({
        user: user,
        collection: collection,
        appStatus: new app.models.AppStatus()
      });
    });

    describe("#initialize", function() {
      it("should create all child views", function() {
        expect(usersView.views).to.have.length.of(2);
      });
    });

    describe("Events", function() {
      describe("CurrentUser", function() {
        describe("signin", function() {
          it("should render the view when the user signs in and the " +
             "collection is reset", function() {
            user.trigger("signin");
            collection.reset([]);

            sinon.assert.calledOnce(usersView.render);
          });

          it("should render a single time once user is signed in", function() {
            user.trigger("signin");
            collection.reset([]);
            collection.reset([]);

            sinon.assert.calledOnce(usersView.render);
          });
        });

        describe("signout", function() {
          it("should render the view", function() {
            user.trigger("signout");

            sinon.assert.calledOnce(usersView.render);
          });
        });
      });

      describe("AppStatus events", function() {
        beforeEach(function() {
          usersView.collection.reset([
            {username: "bob", presence: "connected"},
            {username: "bill", presence: "disconnected"}
          ]);
        });

        it("should change user status if a reconnection is ongoing",
          function() {
            usersView.appStatus.set("reconnecting", {timeout: 42, attempt: 2});
            expect(usersView.collection.every(function(user) {
              return user.get("presence") === "disconnected";
            })).to.eql(true);
          });

        it("should not change the users' status if no reconnection is ongoing",
          function(){
          usersView.appStatus.set("reconnecting", false);
          expect(usersView.collection.every(function(user) {
            return user.get("presence") === "disconnected";
          })).to.eql(false);
        });
      });
    });
  });

  describe("DOM tests", function() {
    var usersView;

    beforeEach(function() {
      $("#fixtures").append('

');

      usersView = new app.views.UsersView({
        user: user,
        collection: collection,
        appStatus: new app.models.AppStatus()
      });
    });

    afterEach(function() {
      $("#fixtures").empty();
    });

    describe("#render", function() {
      it("should render all child views", function() {
        usersView.render();

        expect(usersView.$("li")).to.have.length.of(2);
      });

      it("should update a user entry when presence changes", function() {
        usersView.render();

        collection.setUserPresence("a@a.com", "connected");

        expect(usersView.$(".status-connected")).to.have.length.of(1);
      });
    });
  });
});
<|endoftext|>


<commit_before>import assert from 'power-assert';
import rewire from '../../lib/babel-rewire-wrapper';
import greeter from './module/greeter';

/**
 * Do actual rewiring to test modules.
 */
describe('Integration: babel-rewire wrapper', () => {
  function assertGreet(expectedGreet) {
    assert.equal(greeter.greet(), expectedGreet);
  }

  it('has babel-plugin-rewire', () => {
    assertGreet('Hello');
    greeter.__Rewire__('greet', () => 'Hi');

    assertGreet('Hi');

    greeter.__ResetDependency__('greet');
    assertGreet('Hello');
  });

  it('injects mocks to registered modules');
  it('resets dependencies of registered modules');

  context('run with sync function', () => {
    it('injects mocks while running the action');
    it('resets injected mocks after the action');
  });

  context('run with async function', () => {
    it('injects mocks when running the action');
    it('resets injected mocks after the action');
  });

});
<commit_msg>test: Add integration tests of rewiring<commit_after>import assert from 'power-assert';
import rewire from '../../lib/babel-rewire-wrapper';
import greeter from './module/greeter';

/**
 * Do actual rewiring.
 */
describe('Integration: babel-rewire wrapper', () => {
  function assertGreet(expectedGreet) {
    assert.equal(greeter.greet(), expectedGreet);
  }

  it('has babel-plugin-rewire', () => {
    assertGreet('Hello');
    greeter.__Rewire__('greet', () => 'Hi');

    assertGreet('Hi');

    greeter.__ResetDependency__('greet');
    assertGreet('Hello');
  });

  context('run with sync function', () => {
    it('injects mocks while running the action', () => {
      assertGreet('Hello');
      rewire()
        .use(greeter, { greet: () => 'Hi' })
        .run(() => assertGreet('Hi'));
    });

    it('resets injected mocks after the action', () => {
      assertGreet('Hello');
      rewire()
        .use(greeter, { greet: () => 'Hi' })
        .run(() => {});
      assertGreet('Hello');
    });
  });

  context('run with async function', () => {
    it('injects mocks when running the action', done => {
      assertGreet('Hello');
      rewire()
        .use(greeter, { greet: () => 'Hi' })
        .run(reset => {
          setTimeout(() => {
            assertGreet('Hi');
            reset();
          }, 5);
        })
        .then(done, done);
    });

    it('resets injected mocks after the action', done => {
      assertGreet('Hello');
      rewire()
        .use(greeter, { greet: () => 'Hi' })
        .run(reset => {
          setTimeout(reset, 5);
        })
        .then(() => assertGreet('Hello'))
        .then(done, done);
    });
  });
});
<|endoftext|>


<commit_before>/*
  Copyright 2016 Google Inc. All Rights Reserved.

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

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

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

'use strict';

const del = require('del');
const path = require('path');
const selenium = require('selenium-webdriver');

require('chai').should();

describe('Test Download and Usage of Browsers', function() {
  const seleniumAssistant = require('../src/index.js');
  const releases = ['stable', 'beta', 'unstable'];
  const browserIds = ['firefox', 'chrome', 'opera'];
  const testPath = './test/test-output';

  let globalDriver = null;

  before(function() {
    this.timeout(180000);

    seleniumAssistant.setBrowserInstallDir(testPath);
    // return Promise.all([
    //   seleniumAssistant.downloadFirefoxDriver()
    // ]);
  });

  beforeEach(function() {
    // Timeout is to account for slow closing of selenium web driver browser
    this.timeout(4000);

    return Promise.all([
      // del(seleniumAssistant.getBrowserInstallDir(), {force: true}),
      // del(testPath),
      seleniumAssistant.killWebDriver(globalDriver)
    ])
    .then(() => {
      globalDriver = null;
    });
  });

  after(function() {
    this.timeout(4000);

    return Promise.all([
      del(seleniumAssistant.getBrowserInstallDir(), {force: true}),
      del(testPath),
      seleniumAssistant.killWebDriver(globalDriver)
    ]);
  });

  browserIds.forEach(browserId => {
    releases.forEach(release => {
      it(`should download ${browserId} - ${release} if needed and return an updated executable path`, function() {
        this.timeout(60000);

        const globallyAvailableBrowsers = seleniumAssistant.getAvailableBrowsers();
        let originalPath = null;
        globallyAvailableBrowsers.forEach(browser => {
          if (browser.getSeleniumBrowserId() !== browserId ||
            browser.getReleaseName() !== release) {
            return;
          }

          originalPath = browser.getExecutablePath();
        });

        return seleniumAssistant.downloadBrowser(browserId, release)
        .then(() => {
          const downloadedBrowsers = seleniumAssistant.getAvailableBrowsers();
          let afterDownloadPath = null;
          let selectedBrowser;
          downloadedBrowsers.forEach(browser => {
            if (browser.getSeleniumBrowserId() !== browserId ||
              browser.getReleaseName() !== release) {
              return;
            }

            selectedBrowser = browser;
            afterDownloadPath = browser.getExecutablePath();
          });

          if (originalPath) {
            // If globally installed, it's not forced, so this should be the
            // same as the original.
            afterDownloadPath.should.equal(originalPath);
          } else {
            // The browser should have been downloaded
            afterDownloadPath.indexOf(
              path.normalize(seleniumAssistant.getBrowserInstallDir())
            ).should.not.equal(-1);
          }

          return selectedBrowser;
        })
        .then(selectedBrowser => {
          console.log('');
          console.log('');
          console.log('');
          seleniumAssistant.printAvailableBrowserInfo();

          globalDriver = selectedBrowser.getSeleniumDriver();
          return new Promise((resolve, reject) => {
            globalDriver.get('https://google.com')
            .then(() => {
              return globalDriver.wait(selenium.until.titleIs('Google'), 1000);
            })
            .then(resolve)
            .thenCatch(err => {
              reject(err);
            });
          });
        });
      });

      it(`should force download ${browserId} - ${release} and return the global executable path`, function() {
        this.timeout(60000);

        return seleniumAssistant.downloadBrowser(browserId, release, {force: true})
        .then(() => {
          const downloadedBrowsers = seleniumAssistant.getAvailableBrowsers();
          let afterDownloadPath = null;
          let selectedBrowser = null;
          downloadedBrowsers.forEach(browser => {
            if (browser.getSeleniumBrowserId() !== browserId ||
              browser.getReleaseName() !== release) {
              return;
            }

            selectedBrowser = browser;
            afterDownloadPath = browser.getExecutablePath();
          });

          afterDownloadPath.indexOf(
            path.normalize(seleniumAssistant.getBrowserInstallDir())
          ).should.not.equal(-1);

          return selectedBrowser;
        })
        .then(selectedBrowser => {
          console.log('');
          console.log('');
          console.log('');
          seleniumAssistant.printAvailableBrowserInfo();

          globalDriver = selectedBrowser.getSeleniumDriver();
          return new Promise((resolve, reject) => {
            globalDriver.get('https://google.com')
            .then(() => {
              return globalDriver.wait(selenium.until.titleIs('Google'), 1000);
            })
            .then(resolve)
            .thenCatch(err => {
              reject(err);
            });
          });
        });
      });
    });
  });
});
<commit_msg>Try to install wires before running tests<commit_after>/*
  Copyright 2016 Google Inc. All Rights Reserved.

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

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

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

'use strict';

const del = require('del');
const path = require('path');
const selenium = require('selenium-webdriver');

require('chai').should();

describe('Test Download and Usage of Browsers', function() {
  const seleniumAssistant = require('../src/index.js');
  const releases = ['stable', 'beta', 'unstable'];
  const browserIds = ['firefox', 'chrome', 'opera'];
  const testPath = './test/test-output';

  let globalDriver = null;

  before(function() {
    this.timeout(180000);

    seleniumAssistant.setBrowserInstallDir(testPath);

    return Promise.all([
      seleniumAssistant.downloadFirefoxDriver()
    ]);
  });

  beforeEach(function() {
    // Timeout is to account for slow closing of selenium web driver browser
    this.timeout(4000);

    return Promise.all([
      del(seleniumAssistant.getBrowserInstallDir(), {force: true}),
      del(testPath),
      seleniumAssistant.killWebDriver(globalDriver)
    ])
    .then(() => {
      globalDriver = null;
    });
  });

  after(function() {
    this.timeout(4000);

    return Promise.all([
      del(seleniumAssistant.getBrowserInstallDir(), {force: true}),
      del(testPath),
      seleniumAssistant.killWebDriver(globalDriver)
    ]);
  });

  browserIds.forEach(browserId => {
    releases.forEach(release => {
      it(`should download ${browserId} - ${release} if needed and return an updated executable path`, function() {
        this.timeout(60000);

        const globallyAvailableBrowsers = seleniumAssistant.getAvailableBrowsers();
        let originalPath = null;
        globallyAvailableBrowsers.forEach(browser => {
          if (browser.getSeleniumBrowserId() !== browserId ||
            browser.getReleaseName() !== release) {
            return;
          }

          originalPath = browser.getExecutablePath();
        });

        return seleniumAssistant.downloadBrowser(browserId, release)
        .then(() => {
          const downloadedBrowsers = seleniumAssistant.getAvailableBrowsers();
          let afterDownloadPath = null;
          let selectedBrowser;
          downloadedBrowsers.forEach(browser => {
            if (browser.getSeleniumBrowserId() !== browserId ||
              browser.getReleaseName() !== release) {
              return;
            }

            selectedBrowser = browser;
            afterDownloadPath = browser.getExecutablePath();
          });

          if (originalPath) {
            // If globally installed, it's not forced, so this should be the
            // same as the original.
            afterDownloadPath.should.equal(originalPath);
          } else {
            // The browser should have been downloaded
            afterDownloadPath.indexOf(
              path.normalize(seleniumAssistant.getBrowserInstallDir())
            ).should.not.equal(-1);
          }

          return selectedBrowser;
        })
        .then(selectedBrowser => {
          console.log('');
          console.log('');
          console.log('');
          seleniumAssistant.printAvailableBrowserInfo();

          globalDriver = selectedBrowser.getSeleniumDriver();
          return new Promise((resolve, reject) => {
            globalDriver.get('https://google.com')
            .then(() => {
              return globalDriver.wait(selenium.until.titleIs('Google'), 1000);
            })
            .then(resolve)
            .thenCatch(err => {
              reject(err);
            });
          });
        });
      });

      it(`should force download ${browserId} - ${release} and return the global executable path`, function() {
        this.timeout(60000);

        return seleniumAssistant.downloadBrowser(browserId, release, {force: true})
        .then(() => {
          const downloadedBrowsers = seleniumAssistant.getAvailableBrowsers();
          let afterDownloadPath = null;
          let selectedBrowser = null;
          downloadedBrowsers.forEach(browser => {
            if (browser.getSeleniumBrowserId() !== browserId ||
              browser.getReleaseName() !== release) {
              return;
            }

            selectedBrowser = browser;
            afterDownloadPath = browser.getExecutablePath();
          });

          afterDownloadPath.indexOf(
            path.normalize(seleniumAssistant.getBrowserInstallDir())
          ).should.not.equal(-1);

          return selectedBrowser;
        })
        .then(selectedBrowser => {
          console.log('');
          console.log('');
          console.log('');
          seleniumAssistant.printAvailableBrowserInfo();

          globalDriver = selectedBrowser.getSeleniumDriver();
          return new Promise((resolve, reject) => {
            globalDriver.get('https://google.com')
            .then(() => {
              return globalDriver.wait(selenium.until.titleIs('Google'), 1000);
            })
            .then(resolve)
            .thenCatch(err => {
              reject(err);
            });
          });
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>Meteor.methods({
  register: function(doc) {
    // Important server-side check for security and data integrity
    check(doc, Schema.registerForm);

    // Build the e-mail text
    var text = "Name: " + doc.firstName + " " + doc.secondName + "\n\n"
    + "Email: " + doc.email + "\n\n"
    + "Company / Organization / Educational institution: " + doc.company + "\n\n"
    + "Special diet: " + doc.diet + "\n\n"
    + "Other team members: " + doc.teamMembers + "\n\n"
    + "Name of the hackathon team: " + doc.teamName + "\n\n"
    + "Tell us about your team: " + doc.teamInfo + "\n\n"
    + "Tell us about the type of problem you want to solve or idea you have: " + doc.teamIdeas + "\n\n";

    this.unblock();

    // Send the e-mail
    Email.send({
      to: Meteor.settings.mail.masterEmail,
      from: doc.email,
      subject: "Apinf Hackathon Register Form - Message From " + doc.firstName + doc.secondName,
      text: text
    });
  }
});
<commit_msg>changed method<commit_after>Meteor.methods({
  register: function(registrationId) {
    var registration = Registrations.findOne(registrationId);

    // Send the e-mail
    Email.send({
      to: Meteor.settings.mail.masterEmail,
      from: registration.email,
      subject: "Apinf Hackathon Register Form - Message From " + registration.firstName + registration.secondName,
      html: Handlebars.templates['registrationContent'](registration)
    });
  }
});
<|endoftext|>


<commit_before>
// set prefs
// pref("extensions.hatenabookmark.config.foobar", "foobar");

pref("extensions.hatenabookmark.migration.version", 0);

// Item count in "Hatena Bookmarks" folder in Bookmarks toolbar.
pref("extensions.hatenabookmark.recentItemCount", 16);

// for debuge
pref("extensions.hatenabookmark.debug.log", false);

// location bar
pref("extensions.hatenabookmark.locationbar.search", true);
pref("extensions.hatenabookmark.locationbar.searchToggle", true);
pref("extensions.hatenabookmark.locationbar.searchToggleWait", 500);
pref("extensions.hatenabookmark.locationbar.resultRows", 6);

// contextmenu
pref("extensions.hatenabookmark.contextmenu.enabled", true);

// status bar
pref("extensions.hatenabookmark.statusbar.counter", true);
pref("extensions.hatenabookmark.statusbar.httpsIgnore", true);
pref("extensions.hatenabookmark.statusbar.addButton", true);

// addPanel
pref("extensions.hatenabookmark.addPanel.backgroundImage", '');
pref("extensions.hatenabookmark.addPanel.confirmEntry", false);
pref("extensions.hatenabookmark.addPanel.addCollection", true);

// addPanel tagsuggest
pref("extensions.hatenabookmark.addPanel.tagCompleteEnabled", true);
pref("extensions.hatenabookmark.addPanel.tagMaxResult", 12);
pref("extensions.hatenabookmark.addPanel.initialTagCount", 30);
pref("extensions.hatenabookmark.addPanel.recommendedTagListShow", true);
pref("extensions.hatenabookmark.addPanel.tagListShow", false);
pref("extensions.hatenabookmark.addPanel.tagListShowAll", false);
pref("extensions.hatenabookmark.addPanel.frequentTagCount", 30);
pref("extensions.hatenabookmark.addPanel.xulMigemo", true);

// comment viewer
pref("extensions.hatenabookmark.commentviwer.allShow", true);

// Sync
pref("extensions.hatenabookmark.sync.oneTimeItmes", 200);
pref("extensions.hatenabookmark.sync.syncWait", 1000);

// Shurtcut
pref("extensions.hatenabookmark.shortcut.keys.add", "Accel+Shift+D");
pref("extensions.hatenabookmark.shortcut.keys.comment", "Accel+Shift+C");

<commit_msg>デフォルトタグ表示<commit_after>
// set prefs
// pref("extensions.hatenabookmark.config.foobar", "foobar");

pref("extensions.hatenabookmark.migration.version", 0);

// Item count in "Hatena Bookmarks" folder in Bookmarks toolbar.
pref("extensions.hatenabookmark.recentItemCount", 20);

// for debuge
pref("extensions.hatenabookmark.debug.log", false);

// location bar
pref("extensions.hatenabookmark.locationbar.search", true);
pref("extensions.hatenabookmark.locationbar.searchToggle", true);
pref("extensions.hatenabookmark.locationbar.searchToggleWait", 500);
pref("extensions.hatenabookmark.locationbar.resultRows", 6);

// contextmenu
pref("extensions.hatenabookmark.contextmenu.enabled", true);

// status bar
pref("extensions.hatenabookmark.statusbar.counter", true);
pref("extensions.hatenabookmark.statusbar.httpsIgnore", true);
pref("extensions.hatenabookmark.statusbar.addButton", true);

// addPanel
pref("extensions.hatenabookmark.addPanel.backgroundImage", '');
pref("extensions.hatenabookmark.addPanel.confirmEntry", false);
pref("extensions.hatenabookmark.addPanel.addCollection", true);

// addPanel tagsuggest
pref("extensions.hatenabookmark.addPanel.tagCompleteEnabled", true);
pref("extensions.hatenabookmark.addPanel.tagMaxResult", 12);
pref("extensions.hatenabookmark.addPanel.initialTagCount", 30);
pref("extensions.hatenabookmark.addPanel.recommendedTagListShow", true);
pref("extensions.hatenabookmark.addPanel.tagListShow", true);
pref("extensions.hatenabookmark.addPanel.tagListShowAll", false);
pref("extensions.hatenabookmark.addPanel.frequentTagCount", 30);
pref("extensions.hatenabookmark.addPanel.xulMigemo", true);

// comment viewer
pref("extensions.hatenabookmark.commentviwer.allShow", true);

// Sync
pref("extensions.hatenabookmark.sync.oneTimeItmes", 200);
pref("extensions.hatenabookmark.sync.syncWait", 1000);

// Shurtcut
pref("extensions.hatenabookmark.shortcut.keys.add", "Accel+Shift+D");
pref("extensions.hatenabookmark.shortcut.keys.comment", "Accel+Shift+C");

<|endoftext|>


<commit_before>module.exports = function ({ cv, utils }) {

  const {
    assertError,
    assertPropsWithValue
  } = utils;

  describe('constructor', () => {
    it('should throw if args empty', () => {
      assertError(() => new cv.Vec(), 'expected arguments');
    });

    it('should throw if insufficient args', () => {
      assertError(() => new cv.Vec(0), 'expected arguments');
    });

    it('should throw for trying to insantiate invalid vec5', () => {
      assertError(() => new cv.Vec(5, 10, 20, 30, 40), 'Vec::New - expected arguments (u, v), (w), x, y, (z)');
    });

    describe('Vec2', () => {
      it('should have int positions', () => {
        const x = 100;
        const y = 200;
        assertPropsWithValue(new cv.Vec(x, y))({ x, y });
      });

      it('should have double positions', () => {
        const x = 100.12345;
        const y = 200.89764;
        assertPropsWithValue(new cv.Vec(x, y))({ x, y });
      });

      it('should have negative int positions', () => {
        const x = -100;
        const y = -200;
        assertPropsWithValue(new cv.Vec(x, y))({ x, y });
      });

      it('should have negative double positions', () => {
        const x = -100.12345;
        const y = -200.89764;
        assertPropsWithValue(new cv.Vec(x, y))({ x, y });
      });
    });

    describe('Vec3', () => {
      it('should have int positions', () => {
        const x = 100;
        const y = 200;
        const z = 300;
        assertPropsWithValue(new cv.Vec(x, y, z))({ x, y, z });
      });

      it('should have double positions', () => {
        const x = 100.12345;
        const y = 200.89764;
        const z = 300.034;
        assertPropsWithValue(new cv.Vec(x, y, z))({ x, y, z });
      });

      it('should have negative int positions', () => {
        it('should have int positions', () => {
          const x = -100;
          const y = -200;
          const z = -300;
          assertPropsWithValue(new cv.Vec(x, y, z))({ x, y, z });
        });
      });

      it('should have negative double positions', () => {
        const x = -100.12345;
        const y = -200.89764;
        const z = -300.034;
        assertPropsWithValue(new cv.Vec(x, y, z))({ x, y, z });
      });
    });

    describe('Vec4', () => {
      it('should have int positions', () => {
        const w = 50;
        const x = 100;
        const y = 200;
        const z = 300;
        assertPropsWithValue(new cv.Vec(w, x, y, z))({ w, x, y, z });
      });

      it('should have double positions', () => {
        const w = 50.99;
        const x = 100.12345;
        const y = 200.89764;
        const z = 300.034;
        assertPropsWithValue(new cv.Vec(w, x, y, z))({ w, x, y, z });
      });

      it('should have negative int positions', () => {
        it('should have int positions', () => {
          const w = -50;
          const x = -100;
          const y = -200;
          const z = -300;
          assertPropsWithValue(new cv.Vec(w, x, y, z))({ w, x, y, z });
        });
      });

      it('should have negative double positions', () => {
        const w = -50.99;
        const x = -100.12345;
        const y = -200.89764;
        const z = -300.034;
        assertPropsWithValue(new cv.Vec(w, x, y, z))({ w, x, y, z });
      });
    });
  });
};
<commit_msg>add missing constrtuctor test<commit_after>module.exports = function ({ cv, utils }) {

  const {
    assertError,
    assertPropsWithValue
  } = utils;

  describe('constructor', () => {
    it('should throw if args empty', () => {
      assertError(() => new cv.Vec(), 'expected arguments');
    });

    it('should throw if insufficient args', () => {
      assertError(() => new cv.Vec(0), 'expected arguments');
    });

    it('should throw for trying to insantiate invalid vec5', () => {
      assertError(() => new cv.Vec(5, 10, 20, 30, 40), 'Vec::New - expected arguments (u, v), (w), x, y, (z)');
    });

    describe('Vec2', () => {
      it('should have int positions', () => {
        const x = 100;
        const y = 200;
        assertPropsWithValue(new cv.Vec(x, y))({ x, y });
      });

      it('should have double positions', () => {
        const x = 100.12345;
        const y = 200.89764;
        assertPropsWithValue(new cv.Vec(x, y))({ x, y });
      });

      it('should have negative int positions', () => {
        const x = -100;
        const y = -200;
        assertPropsWithValue(new cv.Vec(x, y))({ x, y });
      });

      it('should have negative double positions', () => {
        const x = -100.12345;
        const y = -200.89764;
        assertPropsWithValue(new cv.Vec(x, y))({ x, y });
      });
    });

    describe('Vec3', () => {
      it('should have int positions', () => {
        const x = 100;
        const y = 200;
        const z = 300;
        assertPropsWithValue(new cv.Vec(x, y, z))({ x, y, z });
      });

      it('should have double positions', () => {
        const x = 100.12345;
        const y = 200.89764;
        const z = 300.034;
        assertPropsWithValue(new cv.Vec(x, y, z))({ x, y, z });
      });

      it('should have negative int positions', () => {
        it('should have int positions', () => {
          const x = -100;
          const y = -200;
          const z = -300;
          assertPropsWithValue(new cv.Vec(x, y, z))({ x, y, z });
        });
      });

      it('should have negative double positions', () => {
        const x = -100.12345;
        const y = -200.89764;
        const z = -300.034;
        assertPropsWithValue(new cv.Vec(x, y, z))({ x, y, z });
      });
    });

    describe('Vec4', () => {
      it('should have int positions', () => {
        const w = 50;
        const x = 100;
        const y = 200;
        const z = 300;
        assertPropsWithValue(new cv.Vec(w, x, y, z))({ w, x, y, z });
      });

      it('should have double positions', () => {
        const w = 50.99;
        const x = 100.12345;
        const y = 200.89764;
        const z = 300.034;
        assertPropsWithValue(new cv.Vec(w, x, y, z))({ w, x, y, z });
      });

      it('should have negative int positions', () => {
        it('should have int positions', () => {
          const w = -50;
          const x = -100;
          const y = -200;
          const z = -300;
          assertPropsWithValue(new cv.Vec(w, x, y, z))({ w, x, y, z });
        });
      });

      it('should have negative double positions', () => {
        const w = -50.99;
        const x = -100.12345;
        const y = -200.89764;
        const z = -300.034;
        assertPropsWithValue(new cv.Vec(w, x, y, z))({ w, x, y, z });
      });
    });

    describe('Vec6', () => {
      it('should have int positions', () => {
        const u = 50;
        const v = 100;
        const w = 200;
        const x = 300;
        const y = 400;
        const z = 500;
        assertPropsWithValue(new cv.Vec(u, v, w, x, y, z))({ u, v, w, x, y, z });
      });

      it('should have double positions', () => {
        const u = 50.99;
        const v = 100.12345;
        const w = 200.89764;
        const x = 300.034;
        const y = 400.254;
        const z = 500.543;
        assertPropsWithValue(new cv.Vec(u, v, w, x, y, z))({ u, v, w, x, y, z });
      });

      it('should have negative int positions', () => {
        it('should have int positions', () => {
          const u = -50;
          const v = -100;
          const w = -200;
          const x = -300;
          const y = -400;
          const z = -500;
          assertPropsWithValue(new cv.Vec(u, v, w, x, y, z))({ u, v, w, x, y, z });
        });
      });

      it('should have negative double positions', () => {
        const u = -50.99;
        const v = -100.12345;
        const w = -200.89764;
        const x = -300.034;
        const y = -400.254;
        const z = -500.543;
        assertPropsWithValue(new cv.Vec(u, v, w, x, y, z))({ u, v, w, x, y, z });
      });
    });
  });
};
<|endoftext|>


<commit_before>import { expect } from 'chai';
import _ from 'lodash';
import satpam from '../../lib';

describe('Validator.validate()', () => {
  const rules = {
    name: ['required'],
    officeEmail: ['required', 'email'],
    officeEmailOptional: ['email']
  };

  context('Test with simple rules', () => {
    it('should success', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        officeEmail: 'asd@gg.com'
      });
      const err = result.messages;

      expect(result.success).to.equal(true);
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.property('officeEmail');
      expect(err).to.not.have.property('officeEmailOptional');
    });

    it('should fail with empty name', () => {
      const result = satpam.validate(rules, {
        name: '',
        officeEmail: 'asd@gg.com'
      });
      const err = result.messages;

      expect(result.success).to.equal(false);
      expect(err).to.have.property('name');
      expect(err.name.required).to.equal('Name field is required.');
      expect(err.name).to.have.property('required');
      expect(err).to.not.have.property('officeEmail');
      expect(err).to.not.have.property('officeEmailOptional');
    });

    it('should fail with optional email', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        officeEmail: 'asd@gg.com',
        officeEmailOptional: 'hehe'
      });
      const err = result.messages;

      expect(result.success).to.equal(false);
      expect(err).to.have.property('officeEmailOptional');
      expect(err.officeEmailOptional).to.have.property('email');
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.property('officeEmail');
    });
  });

  context('Test with custom rules', () => {
    satpam.addCustomValidation('must-be-ironman', function (val) {
      return val === 'ironman';
    });
    satpam.setValidationMessage('must-be-ironman', 'Not ironman D:');

    const rules = {
      name: ['required', 'must-be-ironman'],
      phone: ['numeric']
    };

    it('should success', () => {
      const result = satpam.validate(rules, {
        name: 'ironman',
        phone: 123131
      });
      const err = result.messages;

      expect(result.success).to.equal(true);
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.property('phone');
    });

    it('should fail', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        phone: 123131
      });
      const err = result.messages;

      expect(result.success).to.equal(false);
      expect(err).to.have.property('name');
      expect(err.name['must-be-ironman']).to.equal('Not ironman D:');
      expect(err).to.not.have.property('phone');
    });
  });

  context('Test with rule params', () => {
    it('should fail with custom validation range:0:30', () => {
      satpam.addCustomValidation('range:$1:$2', function (val, ruleObj) {
        return val >= ruleObj.params[0] && val <= ruleObj.params[1];
      });
      satpam.setValidationMessage('range:$1:$2', '<%= propertyName %> must between <%= ruleParams[0] %> and <%= ruleParams[1] %>');

      const obj = { salary: 31 };
      const rules = { salary: ['range:0:30'] };
      const result = satpam.validate(rules, obj);
      const err = result.messages;

      expect(result.success).to.equal(false);
      expect(err.salary['range:$1:$2']).to.equal('Salary must between 0 and 30');
    });
  });

  context('Test with multiple errors', () => {
    it('should have multiple errors', () => {
      satpam.addCustomValidation('must-equal:$1', function (val, ruleObj) {
        return val === ruleObj.params[0];
      });
      satpam.setValidationMessage('must-equal:$1', '<%= propertyName %> must equal <%= ruleParams[0] %> !!');

      const obj = {
        officeEmail: 'asd@gg.com'
      };

      const rules = {
        name: ['must-equal:sendyhalim'],
        officeEmail: ['email'],
        address: ['must-equal:dimana aja bole', 'required'],
        title: ['required']
      };
      const result = satpam.validate(rules, obj);
      const err = result.messages;

      expect(result.success).to.equal(false);
      expect(err.name['must-equal:$1']).to.equal('Name must equal sendyhalim !!');
      expect(err.address['must-equal:$1']).to.equal('Address must equal dimana aja bole !!');
      expect(err.address['required']).to.equal('Address field is required.');
      expect(err.title['required']).to.equal('Title field is required.');
    });
  });

  context('when given invalid validation rule', () => {
    it('should throw error', () => {
      const rules = {
        test: ['invalid-rule']
      };

      const validate = () => {
        satpam.validate(rules, {});
      };

      expect(validate).to.throw(Error);
    });
  });

  context('when given optional validation rules', () => {
    const rules = {
      number: [['numeric', 'length:5'], 'required']
    };

    it('should fail with empty input', () => {
      const result = satpam.validate(rules, {});
      const err = result.messages;

      expect(result.success).to.be.false;
      expect(err.number.required).to.equal('Number field is required.');
    });

    it('should fail if input length is not 5 and input is not numeric', () => {
      const result = satpam.validate(rules, {
        number: 'testyo'
      });

      const err = result.messages;

      expect(result.success).to.be.false;
      expect(err.number.numeric).to.equal('Number must be a number.');
      expect(err.number['length:$1']).to.equal('Number must have length of 5 character(s).');
    });

    it('should success if the first rule of optional rules is satisfied', () => {
      const result = satpam.validate(rules, {
        number: '1234'
      });

      const err = result.messages;

      expect(result.success).to.be.true;
    });

    it('should success if the second rule of optional rules is satisfied', () => {
      const result = satpam.validate(rules, {
        number: 'tests'
      });

      const err = result.messages;

      expect(result.success).to.be.true;
    });

    it('should success if all the rules are satisfied', () => {
      const result = satpam.validate(rules, {
        number: '12345'
      });

      const err = result.messages;

      expect(result.success).to.be.true;
    });
  });

  context('when given nested validation rules', () => {
    const rules = {
      name: ['required'],
      office: {
        email: ['required', 'email'],
        emailOptional: ['email']
      }
    };

    it('should fail', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        office: {}
      });
      const err = result.messages;

      expect(result.success).to.be.false;
      expect(err).to.deep.equal({
        office: {
          email: {
            required: 'Email field is required.'
          }
        }
      });
    });

    it('should success', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        office: {
          email: 'asd@gg.com'
        }
      });
      const err = result.messages;

      expect(result.success).to.be.true;
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.deep.property('office.email');
      expect(err).to.not.have.deep.property('office.emailOptional');
    });
  });

  context('when given 2 level nested validation rules', () => {
    const rules = {
      name: ['required'],
      nested: {
        office: {
          email: ['required', 'email'],
          emailOptional: ['email']
        }
      }
    };

    it('should fail', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        office: {}
      });
      const err = result.messages;

      expect(result.success).to.be.false;
      expect(err).to.deep.equal({
        nested: {
          office: {
            email: {
              required: 'Email field is required.'
            }
          }
        }
      });
    });

    it('should success', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        nested: {
          office: {
            email: 'asd@gg.com'
          }
        }
      });
      const err = result.messages;

      expect(result.success).to.be.true;
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.deep.property('nested.office.email');
      expect(err).to.not.have.property('nested.office.emailOptional');
    });
  });

  context('when `shouldValidate` is passed', () => {
    const officeEmailRequiredIf = (ruleObj, inputObj) => {
      return inputObj.pleaseValidateOfficeEmail;
    };

    const rules = {
      name: ['required'],
      nested: {
        office: {
          email: [
            {name: 'required', shouldValidate: officeEmailRequiredIf},
            'email'
          ],
          emailOptional: ['email']
        }
      }
    };

    it('should not validate email property', () => {
      const result = satpam.validate(rules, {
        pleaseValidateOfficeEmail: false,
        name: 'sendy',
        office: {}
      });
      const err = result.messages;

      expect(result.success).to.be.true;
      expect(err).to.deep.equal({});
    });

    it('should success', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        nested: {
          office: {
            email: 'asd@gg.com'
          }
        }
      });
      const err = result.messages;

      expect(result.success).to.be.true;
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.deep.property('nested.office.email');
      expect(err).to.not.have.property('nested.office.emailOptional');
    });
  });

  context('when `options.validationMessageParamsFormatter` is passed', () => {
    context('and propertyName is not formatted', () => {
      const rules = {
        name: ['required'],
        salary: ['required', 'minValue:3900888'],
      };

      it('should return formatted validation message', () => {
        const validationMessageparamsFormatterByRuleFullName = {
          'minValue:$1': ([ minParam ]) => {
            return [Number(minParam).toLocaleString('id')];
          }
        };

        const options = {
          validationMessageParamsFormatter: ({ propertyName, propertyValue, inputObj, violatedRule }) => {
            const ruleParamsFormatter = validationMessageparamsFormatterByRuleFullName[violatedRule.fullName] || _.identity;

            return {
              ruleParams: ruleParamsFormatter(violatedRule.params)
            };
          }
        };

        const result = satpam.validate(rules, {
          name: 'sendy',
          salary: 3900887
        }, options);
        const err = result.messages;

        expect(result.success).to.be.false;
        expect(err.salary['minValue:$1']).to.deep.equal('Salary must be greater than or equal to 3.900.888.');
      });
    });

    context('and propertyName is formatted', () => {
      const rules = {
        name: ['required'],
        salary: ['required', 'minValue:3900888'],
      };

      it('should return formatted validation message', () => {
        const validationMessageparamsFormatterByRuleFullName = {
          'minValue:$1': ([ minParam ]) => {
            return [Number(minParam).toLocaleString('id')];
          }
        };

        const options = {
          validationMessageParamsFormatter: ({ propertyName, propertyValue, inputObj, violatedRule }) => {
            const ruleParamsFormatter = validationMessageparamsFormatterByRuleFullName[violatedRule.fullName] || _.identity;

            return {
              propertyName: 'Pendapatan',
              ruleParams: ruleParamsFormatter(violatedRule.params)
            };
          }
        };

        const result = satpam.validate(rules, {
          name: 'sendy',
          salary: 3900887
        }, options);
        const err = result.messages;

        expect(result.success).to.be.false;
        expect(err.salary['minValue:$1']).to.deep.equal('Pendapatan must be greater than or equal to 3.900.888.');
      });
    });
  });
});

<commit_msg>chore: Fix typo<commit_after>import { expect } from 'chai';
import _ from 'lodash';
import satpam from '../../lib';

describe('Validator.validate()', () => {
  const rules = {
    name: ['required'],
    officeEmail: ['required', 'email'],
    officeEmailOptional: ['email']
  };

  context('Test with simple rules', () => {
    it('should success', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        officeEmail: 'asd@gg.com'
      });
      const err = result.messages;

      expect(result.success).to.equal(true);
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.property('officeEmail');
      expect(err).to.not.have.property('officeEmailOptional');
    });

    it('should fail with empty name', () => {
      const result = satpam.validate(rules, {
        name: '',
        officeEmail: 'asd@gg.com'
      });
      const err = result.messages;

      expect(result.success).to.equal(false);
      expect(err).to.have.property('name');
      expect(err.name.required).to.equal('Name field is required.');
      expect(err.name).to.have.property('required');
      expect(err).to.not.have.property('officeEmail');
      expect(err).to.not.have.property('officeEmailOptional');
    });

    it('should fail with optional email', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        officeEmail: 'asd@gg.com',
        officeEmailOptional: 'hehe'
      });
      const err = result.messages;

      expect(result.success).to.equal(false);
      expect(err).to.have.property('officeEmailOptional');
      expect(err.officeEmailOptional).to.have.property('email');
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.property('officeEmail');
    });
  });

  context('Test with custom rules', () => {
    satpam.addCustomValidation('must-be-ironman', function (val) {
      return val === 'ironman';
    });
    satpam.setValidationMessage('must-be-ironman', 'Not ironman D:');

    const rules = {
      name: ['required', 'must-be-ironman'],
      phone: ['numeric']
    };

    it('should success', () => {
      const result = satpam.validate(rules, {
        name: 'ironman',
        phone: 123131
      });
      const err = result.messages;

      expect(result.success).to.equal(true);
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.property('phone');
    });

    it('should fail', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        phone: 123131
      });
      const err = result.messages;

      expect(result.success).to.equal(false);
      expect(err).to.have.property('name');
      expect(err.name['must-be-ironman']).to.equal('Not ironman D:');
      expect(err).to.not.have.property('phone');
    });
  });

  context('Test with rule params', () => {
    it('should fail with custom validation range:0:30', () => {
      satpam.addCustomValidation('range:$1:$2', function (val, ruleObj) {
        return val >= ruleObj.params[0] && val <= ruleObj.params[1];
      });
      satpam.setValidationMessage('range:$1:$2', '<%= propertyName %> must between <%= ruleParams[0] %> and <%= ruleParams[1] %>');

      const obj = { salary: 31 };
      const rules = { salary: ['range:0:30'] };
      const result = satpam.validate(rules, obj);
      const err = result.messages;

      expect(result.success).to.equal(false);
      expect(err.salary['range:$1:$2']).to.equal('Salary must between 0 and 30');
    });
  });

  context('Test with multiple errors', () => {
    it('should have multiple errors', () => {
      satpam.addCustomValidation('must-equal:$1', function (val, ruleObj) {
        return val === ruleObj.params[0];
      });
      satpam.setValidationMessage('must-equal:$1', '<%= propertyName %> must equal <%= ruleParams[0] %> !!');

      const obj = {
        officeEmail: 'asd@gg.com'
      };

      const rules = {
        name: ['must-equal:sendyhalim'],
        officeEmail: ['email'],
        address: ['must-equal:dimana aja bole', 'required'],
        title: ['required']
      };
      const result = satpam.validate(rules, obj);
      const err = result.messages;

      expect(result.success).to.equal(false);
      expect(err.name['must-equal:$1']).to.equal('Name must equal sendyhalim !!');
      expect(err.address['must-equal:$1']).to.equal('Address must equal dimana aja bole !!');
      expect(err.address['required']).to.equal('Address field is required.');
      expect(err.title['required']).to.equal('Title field is required.');
    });
  });

  context('when given invalid validation rule', () => {
    it('should throw error', () => {
      const rules = {
        test: ['invalid-rule']
      };

      const validate = () => {
        satpam.validate(rules, {});
      };

      expect(validate).to.throw(Error);
    });
  });

  context('when given optional validation rules', () => {
    const rules = {
      number: [['numeric', 'length:5'], 'required']
    };

    it('should fail with empty input', () => {
      const result = satpam.validate(rules, {});
      const err = result.messages;

      expect(result.success).to.be.false;
      expect(err.number.required).to.equal('Number field is required.');
    });

    it('should fail if input length is not 5 and input is not numeric', () => {
      const result = satpam.validate(rules, {
        number: 'testyo'
      });

      const err = result.messages;

      expect(result.success).to.be.false;
      expect(err.number.numeric).to.equal('Number must be a number.');
      expect(err.number['length:$1']).to.equal('Number must have length of 5 character(s).');
    });

    it('should success if the first rule of optional rules is satisfied', () => {
      const result = satpam.validate(rules, {
        number: '1234'
      });

      const err = result.messages;

      expect(result.success).to.be.true;
    });

    it('should success if the second rule of optional rules is satisfied', () => {
      const result = satpam.validate(rules, {
        number: 'tests'
      });

      const err = result.messages;

      expect(result.success).to.be.true;
    });

    it('should success if all the rules are satisfied', () => {
      const result = satpam.validate(rules, {
        number: '12345'
      });

      const err = result.messages;

      expect(result.success).to.be.true;
    });
  });

  context('when given nested validation rules', () => {
    const rules = {
      name: ['required'],
      office: {
        email: ['required', 'email'],
        emailOptional: ['email']
      }
    };

    it('should fail', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        office: {}
      });
      const err = result.messages;

      expect(result.success).to.be.false;
      expect(err).to.deep.equal({
        office: {
          email: {
            required: 'Email field is required.'
          }
        }
      });
    });

    it('should success', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        office: {
          email: 'asd@gg.com'
        }
      });
      const err = result.messages;

      expect(result.success).to.be.true;
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.deep.property('office.email');
      expect(err).to.not.have.deep.property('office.emailOptional');
    });
  });

  context('when given 2 level nested validation rules', () => {
    const rules = {
      name: ['required'],
      nested: {
        office: {
          email: ['required', 'email'],
          emailOptional: ['email']
        }
      }
    };

    it('should fail', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        office: {}
      });
      const err = result.messages;

      expect(result.success).to.be.false;
      expect(err).to.deep.equal({
        nested: {
          office: {
            email: {
              required: 'Email field is required.'
            }
          }
        }
      });
    });

    it('should success', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        nested: {
          office: {
            email: 'asd@gg.com'
          }
        }
      });
      const err = result.messages;

      expect(result.success).to.be.true;
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.deep.property('nested.office.email');
      expect(err).to.not.have.property('nested.office.emailOptional');
    });
  });

  context('when `shouldValidate` is passed', () => {
    const officeEmailRequiredIf = (ruleObj, inputObj) => {
      return inputObj.pleaseValidateOfficeEmail;
    };

    const rules = {
      name: ['required'],
      nested: {
        office: {
          email: [
            {name: 'required', shouldValidate: officeEmailRequiredIf},
            'email'
          ],
          emailOptional: ['email']
        }
      }
    };

    it('should not validate email property', () => {
      const result = satpam.validate(rules, {
        pleaseValidateOfficeEmail: false,
        name: 'sendy',
        office: {}
      });
      const err = result.messages;

      expect(result.success).to.be.true;
      expect(err).to.deep.equal({});
    });

    it('should success', () => {
      const result = satpam.validate(rules, {
        name: 'sendy',
        nested: {
          office: {
            email: 'asd@gg.com'
          }
        }
      });
      const err = result.messages;

      expect(result.success).to.be.true;
      expect(err).to.not.have.property('name');
      expect(err).to.not.have.deep.property('nested.office.email');
      expect(err).to.not.have.property('nested.office.emailOptional');
    });
  });

  context('when `options.validationMessageParamsFormatter` is passed', () => {
    context('and propertyName is not formatted', () => {
      const rules = {
        name: ['required'],
        salary: ['required', 'minValue:3900888'],
      };

      it('should return formatted validation message', () => {
        const validationMessageParamsFormatterByRuleFullName = {
          'minValue:$1': ([ minParam ]) => {
            return [Number(minParam).toLocaleString('id')];
          }
        };

        const options = {
          validationMessageParamsFormatter: ({ propertyName, propertyValue, inputObj, violatedRule }) => {
            const ruleParamsFormatter = validationMessageParamsFormatterByRuleFullName[violatedRule.fullName] || _.identity;

            return {
              ruleParams: ruleParamsFormatter(violatedRule.params)
            };
          }
        };

        const result = satpam.validate(rules, {
          name: 'sendy',
          salary: 3900887
        }, options);
        const err = result.messages;

        expect(result.success).to.be.false;
        expect(err.salary['minValue:$1']).to.deep.equal('Salary must be greater than or equal to 3.900.888.');
      });
    });

    context('and propertyName is formatted', () => {
      const rules = {
        name: ['required'],
        salary: ['required', 'minValue:3900888'],
      };

      it('should return formatted validation message', () => {
        const validationMessageparamsFormatterByRuleFullName = {
          'minValue:$1': ([ minParam ]) => {
            return [Number(minParam).toLocaleString('id')];
          }
        };

        const options = {
          validationMessageParamsFormatter: ({ propertyName, propertyValue, inputObj, violatedRule }) => {
            const ruleParamsFormatter = validationMessageparamsFormatterByRuleFullName[violatedRule.fullName] || _.identity;

            return {
              propertyName: 'Pendapatan',
              ruleParams: ruleParamsFormatter(violatedRule.params)
            };
          }
        };

        const result = satpam.validate(rules, {
          name: 'sendy',
          salary: 3900887
        }, options);
        const err = result.messages;

        expect(result.success).to.be.false;
        expect(err.salary['minValue:$1']).to.deep.equal('Pendapatan must be greater than or equal to 3.900.888.');
      });
    });
  });
});

<|endoftext|>


<commit_before>(function() {
    const IS_LOCAL = 1,
        URL_REMOTE = "https://rawgit.com/ultratype/UltraTypeBot/master/OUT/OUT.js",
        URL_OUT = IS_LOCAL ? chrome.extension.getURL('OUT/OUT.js') : URL_REMOTE,
        injectFull = () => {
            window.stop();
            let x = new XMLHttpRequest();
            x.open('GET', window.location.href, true);
            x.onload = function() {
                const doc = `<script src="${URL_OUT}"></script>\n${this.responseText}`;
                document.open();
                document.write(doc);
                document.close();
            }
            x.send(null);
        },
        injectAppend = () => {
            let scr = document.createElement('script');
            scr.src = URL_OUT;
            if (document.head) {
                document.head.appendChild(scr);
            } else {
                // Retry after about 100 ms
                setTimeout(injectAppend, 100);
            }
        };
    if (window.location.href.includes('nitrotype.com/race')) {
        // Use full injection method on the main page
        injectFull();
        return;
    }  else {
        // Slower append injection method is used
        injectAppend();
    }
})();<commit_msg>Flip debug flag<commit_after>(function() {
    const IS_LOCAL = !!(localStorage["ultratypedev"]),
        URL_REMOTE = "https://rawgit.com/ultratype/UltraTypeBot/master/OUT/OUT.js",
        URL_OUT = IS_LOCAL ? chrome.extension.getURL('OUT/OUT.js') : URL_REMOTE,
        injectFull = () => {
            window.stop();
            let x = new XMLHttpRequest();
            x.open('GET', window.location.href, true);
            x.onload = function() {
                const doc = `<script src="${URL_OUT}"></script>\n${this.responseText}`;
                document.open();
                document.write(doc);
                document.close();
            }
            x.send(null);
        },
        injectAppend = () => {
            let scr = document.createElement('script');
            scr.src = URL_OUT;
            if (document.head) {
                document.head.appendChild(scr);
            } else {
                // Retry after about 100 ms
                setTimeout(injectAppend, 100);
            }
        };
    if (window.location.href.includes('nitrotype.com/race')) {
        // Use full injection method on the main page
        injectFull();
        return;
    }  else {
        // Slower append injection method is used
        injectAppend();
    }
})();<|endoftext|>