<commit_before>var Botkit = require(__dirname + '/CoreBot.js');
var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');
var JSONbig = require('json-bigint');

function Facebookbot(configuration) {

    // Create a core botkit bot
    var facebook_botkit = Botkit(configuration || {});

    // customize the bot definition, which will be used when new connections
    // spawn!
    facebook_botkit.defineBot(function(botkit, config) {

        var bot = {
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances,
        };

        bot.startConversation = function(message, cb) {
            botkit.startConversation(this, message, cb);
        };

        bot.send = function(message, cb) {

            var facebook_message = {
                recipient: {},
                message: {}
            };

            if (typeof(message.channel) == 'string' && message.channel.match(/\+\d+\(\d\d\d\)\d\d\d\-\d\d\d\d/)) {
                facebook_message.recipient.phone_number = message.channel;
            } else {
                facebook_message.recipient.id = message.channel;
            }

            if (message.text) {
                facebook_message.message.text = message.text;
            }

            if (message.attachment) {
                facebook_message.message.attachment = message.attachment;
            }

            request.post('https://graph.facebook.com/me/messages?access_token=' + configuration.access_token,
                function(err, res, body) {
                    if (err) {
                        botkit.debug('WEBHOOK ERROR', err);
                        return cb && cb(err);
                    }

                    try {

                        var json = JSON.parse(body);

                    } catch (err) {

                        botkit.debug('JSON Parse error: ', err);
                        return cb && cb(err);

                    }

                    if (json.error) {
                        botkit.debug('API ERROR', json.error);
                        return cb && cb(json.error.message);
                    }

                    botkit.debug('WEBHOOK SUCCESS', body);
                    cb && cb(null, body);
                }).form(facebook_message);
        };

        bot.reply = function(src, resp, cb) {
            var msg = {};

            if (typeof(resp) == 'string') {
                msg.text = resp;
            } else {
                msg = resp;
            }

            msg.channel = src.channel;

            bot.say(msg, cb);
        };

        bot.findConversation = function(message, cb) {
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
                    if (
                        botkit.tasks[t].convos[c].isActive() &&
                        botkit.tasks[t].convos[c].source_message.user == message.user
                    ) {
                        botkit.debug('FOUND EXISTING CONVO!');
                        cb(botkit.tasks[t].convos[c]);
                        return;
                    }
                }
            }

            cb();
        };

        return bot;

    });

    // set up a web route for receiving outgoing webhooks and/or slash commands
    facebook_botkit.createWebhookEndpoints = function(webserver, bot) {

        facebook_botkit.log(
            '** Serving webhook endpoints for Slash commands and outgoing ' +
            'webhooks at: http://MY_HOST:' + facebook_botkit.config.port + '/facebook/receive');
        webserver.post('/facebook/receive', function(req, res) {
            facebook_botkit.debug('GOT A MESSAGE HOOK');
            var obj = JSONbig.parse(req.body);
            if (obj.entry) {
                for (var e = 0; e < obj.entry.length; e++) {
                    for (var m = 0; m < obj.entry[e].messaging.length; m++) {
                        var facebook_message = obj.entry[e].messaging[m];
                        var fbSenderId = facebook_message.sender.id.toString();
                        if (facebook_message.message) {

                            var message = {
                                text: facebook_message.message.text,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                                seq: facebook_message.message.seq,
                                mid: facebook_message.message.mid,
                            };

                            facebook_botkit.receiveMessage(bot, message);

                        } else if (facebook_message.message.attachments) {
                            var message = {
                                text: facebook_message.message.text,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                                seq: facebook_message.message.seq,
                                mid: facebook_message.message.mid,
                                attachments: facebook_message.message.attachments,
                            };

                            facebook_botkit.receiveMessage(bot, message);

                        } else if (facebook_message.postback) {

                            var message = {
                                payload: facebook_message.postback.payload,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_postback', [bot, message]);
                        } else if (facebook_message.optin) {

                            var message = {
                                optin: facebook_message.optin,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_optin', [bot, message]);
                        } else if (facebook_message.delivery) {

                            var message = {
                                optin: facebook_message.delivery,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('message_delivered', [bot, message]);

                        } else {
                            botkit.log('Got an unexpected message from Facebook: ', facebook_message);
                        }
                    }
                }
            }
            res.send('ok');
        });

        webserver.get('/facebook/receive', function(req, res) {
            console.log(req.query);
            if (req.query['hub.mode'] == 'subscribe') {
                if (req.query['hub.verify_token'] == configuration.verify_token) {
                    res.send(req.query['hub.challenge']);
                } else {
                    res.send('OK');
                }
            }
        });

        return facebook_botkit;
    };

    facebook_botkit.setupWebserver = function(port, cb) {

        if (!port) {
            throw new Error('Cannot start webserver without a port');
        }
        if (isNaN(port)) {
            throw new Error('Specified port is not a valid number');
        }

        facebook_botkit.config.port = port;

        facebook_botkit.webserver = express();
        facebook_botkit.webserver.use(bodyParser.text({ type: 'application/json' }));
        facebook_botkit.webserver.use(bodyParser.urlencoded({ extended: true }));
        facebook_botkit.webserver.use(express.static(__dirname + '/public'));

        var server = facebook_botkit.webserver.listen(
            facebook_botkit.config.port,
            function() {
                facebook_botkit.log('** Starting webserver on port ' +
                    facebook_botkit.config.port);
                if (cb) { cb(null, facebook_botkit.webserver); }
            });

        request.post('https://graph.facebook.com/me/subscribed_apps?access_token=' + configuration.access_token,
            function(err, res, body) {
                if (err) {
                    facebook_botkit.log('Could not subscribe to page messages');
                } else {
                    facebook_botkit.debug('Successfully subscribed to Facebook events:', body);
                    // facebook_botkit.startTicking();
                }
            });

        return facebook_botkit;

    };

    return facebook_botkit;
};

module.exports = Facebookbot;
<commit_msg>added messages<commit_after>var Botkit = require(__dirname + '/CoreBot.js');
var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');
var JSONbig = require('json-bigint');

function Facebookbot(configuration) {

    // Create a core botkit bot
    var facebook_botkit = Botkit(configuration || {});

    // customize the bot definition, which will be used when new connections
    // spawn!
    facebook_botkit.defineBot(function(botkit, config) {

        var bot = {
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances,
        };

        bot.startConversation = function(message, cb) {
            botkit.startConversation(this, message, cb);
        };

        bot.send = function(message, cb) {

            var facebook_message = {
                recipient: {},
                message: {}
            };

            if (typeof(message.channel) == 'string' && message.channel.match(/\+\d+\(\d\d\d\)\d\d\d\-\d\d\d\d/)) {
                facebook_message.recipient.phone_number = message.channel;
            } else {
                facebook_message.recipient.id = message.channel;
            }

            if (message.text) {
                facebook_message.message.text = message.text;
            }

            if (message.attachment) {
                facebook_message.message.attachment = message.attachment;
            }

            request.post('https://graph.facebook.com/me/messages?access_token=' + configuration.access_token,
                function(err, res, body) {
                    if (err) {
                        botkit.debug('WEBHOOK ERROR', err);
                        return cb && cb(err);
                    }

                    try {

                        var json = JSON.parse(body);

                    } catch (err) {

                        botkit.debug('JSON Parse error: ', err);
                        return cb && cb(err);

                    }

                    if (json.error) {
                        botkit.debug('API ERROR', json.error);
                        return cb && cb(json.error.message);
                    }

                    botkit.debug('WEBHOOK SUCCESS', body);
                    cb && cb(null, body);
                }).form(facebook_message);
        };

        bot.reply = function(src, resp, cb) {
            var msg = {};

            if (typeof(resp) == 'string') {
                msg.text = resp;
            } else {
                msg = resp;
            }

            msg.channel = src.channel;

            bot.say(msg, cb);
        };

        bot.findConversation = function(message, cb) {
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
                    if (
                        botkit.tasks[t].convos[c].isActive() &&
                        botkit.tasks[t].convos[c].source_message.user == message.user
                    ) {
                        botkit.debug('FOUND EXISTING CONVO!');
                        cb(botkit.tasks[t].convos[c]);
                        return;
                    }
                }
            }

            cb();
        };

        return bot;

    });

    // set up a web route for receiving outgoing webhooks and/or slash commands
    facebook_botkit.createWebhookEndpoints = function(webserver, bot) {

        facebook_botkit.log(
            '** Serving webhook endpoints for Slash commands and outgoing ' +
            'webhooks at: http://MY_HOST:' + facebook_botkit.config.port + '/facebook/receive');
        webserver.post('/facebook/receive', function(req, res) {
            facebook_botkit.debug('GOT A MESSAGE HOOK');
            var obj = JSONbig.parse(req.body);
            if (obj.entry) {
                for (var e = 0; e < obj.entry.length; e++) {
                    for (var m = 0; m < obj.entry[e].messaging.length; m++) {
                        var facebook_message = obj.entry[e].messaging[m];
                        var fbSenderId = facebook_message.sender.id.toString();
                        if (facebook_message.message) {
                            if (facebook_message.message.attachments == undefined) {
                                var message = {
                                    text: facebook_message.message.text,
                                    user: fbSenderId,
                                    channel: fbSenderId,
                                    timestamp: facebook_message.timestamp,
                                    seq: facebook_message.message.seq,
                                    mid: facebook_message.message.mid,
                                };

                                facebook_botkit.receiveMessage(bot, message);
                            } else {
                                var message = {
                                    text: facebook_message.message.text,
                                    user: fbSenderId,
                                    channel: fbSenderId,
                                    timestamp: facebook_message.timestamp,
                                    seq: facebook_message.message.seq,
                                    mid: facebook_message.message.mid,
                                    attachments: facebook_message.message.attachments,
                                };

                                facebook_botkit.receiveMessage(bot, message);
                            }

                        } else if (facebook_message.postback) {

                            var message = {
                                payload: facebook_message.postback.payload,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_postback', [bot, message]);
                        } else if (facebook_message.optin) {

                            var message = {
                                optin: facebook_message.optin,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_optin', [bot, message]);
                        } else if (facebook_message.delivery) {

                            var message = {
                                optin: facebook_message.delivery,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('message_delivered', [bot, message]);

                        } else {
                            botkit.log('Got an unexpected message from Facebook: ', facebook_message);
                        }
                    }
                }
            }
            res.send('ok');
        });

        webserver.get('/facebook/receive', function(req, res) {
            console.log(req.query);
            if (req.query['hub.mode'] == 'subscribe') {
                if (req.query['hub.verify_token'] == configuration.verify_token) {
                    res.send(req.query['hub.challenge']);
                } else {
                    res.send('OK');
                }
            }
        });

        return facebook_botkit;
    };

    facebook_botkit.setupWebserver = function(port, cb) {

        if (!port) {
            throw new Error('Cannot start webserver without a port');
        }
        if (isNaN(port)) {
            throw new Error('Specified port is not a valid number');
        }

        facebook_botkit.config.port = port;

        facebook_botkit.webserver = express();
        facebook_botkit.webserver.use(bodyParser.text({ type: 'application/json' }));
        facebook_botkit.webserver.use(bodyParser.urlencoded({ extended: true }));
        facebook_botkit.webserver.use(express.static(__dirname + '/public'));

        var server = facebook_botkit.webserver.listen(
            facebook_botkit.config.port,
            function() {
                facebook_botkit.log('** Starting webserver on port ' +
                    facebook_botkit.config.port);
                if (cb) { cb(null, facebook_botkit.webserver); }
            });

        request.post('https://graph.facebook.com/me/subscribed_apps?access_token=' + configuration.access_token,
            function(err, res, body) {
                if (err) {
                    facebook_botkit.log('Could not subscribe to page messages');
                } else {
                    facebook_botkit.debug('Successfully subscribed to Facebook events:', body);
                    // facebook_botkit.startTicking();
                }
            });

        return facebook_botkit;

    };

    return facebook_botkit;
};

module.exports = Facebookbot;
<|endoftext|>


<commit_before>// Copyright (c) 2015 Analog.IO group. All rights reserved.
// Use of this source code is governed by a Apache-style license that can be
// found in the LICENSE file.
var dayStringRegex = /[A-Z][a-z]{2}/;
var dateStringRegex = /(\d{1,2})[a-z]{2}/;
var nameRegex = /On shift right now: ([a-zæøå,&\s]+)\n/gi;

function isToday(dateString) {
  var day = dayToInt(dayStringRegex.exec(dateString)[0]);
  console.log(day);
  var today = new Date();
  if (day == today.getDay()) {
    // Check if the date is the same
    var date = parseInt(dateStringRegex.exec(dateString)[1]);
    console.log(date);
    if (date == today.getDate()) {
      return true;
    }
  }
  return false;
}

function dayToInt(dayString) {
  switch (dayString) {
    case 'Sun': return 0;
    case 'Mon': return 1;
    case 'Tue': return 2;
    case 'Wed': return 3;
    case 'Thu': return 4;
    case 'Fri': return 5;
    case 'Sat': return 6;
  }
}

function getIsAnalogOpen(callback, errorCallback) {
  var x = new XMLHttpRequest();
  x.open('GET', "http://cafeanalog.dk/REST/");
  x.responseType = 'json';
  x.onload = function() {
    var response = x.response;
    if (!response ) {
        errorCallback('No response from CafeAnalog.dk!');
    }
    else
    {
      var isOpen = response.open;
      callback(isOpen);
    }
  };
  x.onerror = function(){}; // errorCallback('Network error.');
  x.send();
}

var cafeanalog;
var downloading;

function downloadHomePage(callback, errorCallback) {
  if (downloading) {
    // If currently downloading, don't redownload, just wait to see if the download finishes soon.
    setTimeout( function() {
      downloadHomePage(callback, errorCallback);
      }, 50);
    return;
  }
  if (cafeanalog) { // If the content is already available
    callback(cafeanalog); // just callback with content
    return;
  }
  downloading = true; // Download now in progress
  var x = new XMLHttpRequest();
  x.open('GET', 'http://cafeanalog.dk/');
  x.responseType = 'document';
  x.onload = function() {
    cafeanalog = x.response;
    downloading = false; // Download now done, and content is available if found
    if (!cafeanalog) {
      errorCallback();
    }
    else
    {
      callback(cafeanalog);
    }
  }
  x.onerror = function(){}; // errorCallback
  x.send();
}

function getOpening(callback, errorCallback) {
  getShowOpening( function (showOpening) { // Check the settings to see if the opening should be downloaded or not.
    if (!showOpening) return;

    downloadHomePage( function(response) {
      var opening = response.getElementById("openingHours").getElementsByTagName("li")[0].textContent;
      if (!opening) {
        errorCallback('No openings found');
      }
      else
      {
        if (isToday(opening)) {
          var nextOpening = response.getElementById("openingHours").getElementsByTagName("li")[1].textContent;
          var openingString = 'Today: ' + opening.substring(9).trim();
          if (nextOpening && isToday(nextOpening)) {
            callback(openingString + " and again " + nextOpening.substring(9));
          } else {
            callback(openingString); // Check that this works for all dates.
          }
        } else {
          callback(opening);
        }
      }
    }, function() {
      errorCallback('No openings found');
      });
  });
}

function getNames(callback, errorCallback) {
  getShowNames( function (showNames) {
    if (!showNames) return;
    downloadHomePage( function(response) {
      var names = nameRegex.exec(response.getElementById("openingHours").textContent);
      if (!names) {
        errorCallback('No names found');
      }
      else {
        if(names[1].indexOf("&") == -1) // only 1 name
        {
          callback(names[1])
        }
        else
        {
          var commaSeparated = names[1].replace(/ &/g,','); // All comma separated.
          var lastComma = commaSeparated.lastIndexOf(","); // Find the last comma
          var result = commaSeparated.substring(0, lastComma) + " and" + commaSeparated.substring(lastComma + 1); // Remove that comma and insert ' and' instead.

          callback(result);
        }
      }
    }, function() {
      errorCallback('No names found');
      }
    );
  });
}

function renderOpening(openingText) {
  document.getElementById('opening').textContent = openingText;
}

function renderNames(namesText) {
  document.getElementById('onshift').innerHTML = namesText;
}

function renderStatus(statusText) {
  document.getElementById('status').textContent = statusText;
}

function boolToText(isOpenBool) {
  if (isOpenBool)
  {
    setIcon("Open");
    return "ÅPEN";
  }
  else
  {
    setIcon("");
    return "CLØSED";
  }
}

function setIcon(openString) {
  chrome.browserAction.setIcon({path:"Assets/icon"+openString+"38.png"});
}

function getShowNames(callback) {
  chrome.storage.sync.get({
    showshiftsetting: true
  }, function(items) {
    callback(items.showshiftsetting);
  })
}

function getShowOpening(callback) {
  chrome.storage.sync.get({
    showopeningsetting: true
  }, function(items) {
    callback(items.showopeningsetting);
  })
}

document.addEventListener('DOMContentLoaded', function() {
  renderStatus('Cafe Analog is ...');

  getIsAnalogOpen( function (boolValue) {
    renderStatus('Cafe Analog is ' + boolToText(boolValue));
    // names
    if (boolValue) {
      getNames( function (names) {
        renderNames(names); // put special handeling if necesarry
      }, renderNames);
    }
    // opening
    getOpening( function(openingText) {
      if (boolValue)
      {
        renderOpening(openingText);
      }
      else
      {
        renderOpening("We open again " + openingText);
      }
    }, renderOpening);
  }, renderStatus);
});
<commit_msg>removed an "again" when there is two shift in one day<commit_after>// Copyright (c) 2015 Analog.IO group. All rights reserved.
// Use of this source code is governed by a Apache-style license that can be
// found in the LICENSE file.
var dayStringRegex = /[A-Z][a-z]{2}/;
var dateStringRegex = /(\d{1,2})[a-z]{2}/;
var nameRegex = /On shift right now: ([a-zæøå,&\s]+)\n/gi;

function isToday(dateString) {
  var day = dayToInt(dayStringRegex.exec(dateString)[0]);
  console.log(day);
  var today = new Date();
  if (day == today.getDay()) {
    // Check if the date is the same
    var date = parseInt(dateStringRegex.exec(dateString)[1]);
    console.log(date);
    if (date == today.getDate()) {
      return true;
    }
  }
  return false;
}

function dayToInt(dayString) {
  switch (dayString) {
    case 'Sun': return 0;
    case 'Mon': return 1;
    case 'Tue': return 2;
    case 'Wed': return 3;
    case 'Thu': return 4;
    case 'Fri': return 5;
    case 'Sat': return 6;
  }
}

function getIsAnalogOpen(callback, errorCallback) {
  var x = new XMLHttpRequest();
  x.open('GET', "http://cafeanalog.dk/REST/");
  x.responseType = 'json';
  x.onload = function() {
    var response = x.response;
    if (!response ) {
        errorCallback('No response from CafeAnalog.dk!');
    }
    else
    {
      var isOpen = response.open;
      callback(isOpen);
    }
  };
  x.onerror = function(){}; // errorCallback('Network error.');
  x.send();
}

var cafeanalog;
var downloading;

function downloadHomePage(callback, errorCallback) {
  if (downloading) {
    // If currently downloading, don't redownload, just wait to see if the download finishes soon.
    setTimeout( function() {
      downloadHomePage(callback, errorCallback);
      }, 50);
    return;
  }
  if (cafeanalog) { // If the content is already available
    callback(cafeanalog); // just callback with content
    return;
  }
  downloading = true; // Download now in progress
  var x = new XMLHttpRequest();
  x.open('GET', 'http://cafeanalog.dk/');
  x.responseType = 'document';
  x.onload = function() {
    cafeanalog = x.response;
    downloading = false; // Download now done, and content is available if found
    if (!cafeanalog) {
      errorCallback();
    }
    else
    {
      callback(cafeanalog);
    }
  }
  x.onerror = function(){}; // errorCallback
  x.send();
}

function getOpening(callback, errorCallback) {
  getShowOpening( function (showOpening) { // Check the settings to see if the opening should be downloaded or not.
    if (!showOpening) return;

    downloadHomePage( function(response) {
      var opening = response.getElementById("openingHours").getElementsByTagName("li")[0].textContent;
      if (!opening) {
        errorCallback('No openings found');
      }
      else
      {
        if (isToday(opening)) {
          var nextOpening = response.getElementById("openingHours").getElementsByTagName("li")[1].textContent;
          var openingString = 'Today: ' + opening.substring(9).trim();
          if (nextOpening && isToday(nextOpening)) {
            callback(openingString + " and " + nextOpening.substring(9));
          } else {
            callback(openingString); // Check that this works for all dates.
          }
        } else {
          callback(opening);
        }
      }
    }, function() {
      errorCallback('No openings found');
      });
  });
}

function getNames(callback, errorCallback) {
  getShowNames( function (showNames) {
    if (!showNames) return;
    downloadHomePage( function(response) {
      var names = nameRegex.exec(response.getElementById("openingHours").textContent);
      if (!names) {
        errorCallback('No names found');
      }
      else {
        if(names[1].indexOf("&") == -1) // only 1 name
        {
          callback(names[1])
        }
        else
        {
          var commaSeparated = names[1].replace(/ &/g,','); // All comma separated.
          var lastComma = commaSeparated.lastIndexOf(","); // Find the last comma
          var result = commaSeparated.substring(0, lastComma) + " and" + commaSeparated.substring(lastComma + 1); // Remove that comma and insert ' and' instead.

          callback(result);
        }
      }
    }, function() {
      errorCallback('No names found');
      }
    );
  });
}

function renderOpening(openingText) {
  document.getElementById('opening').textContent = openingText;
}

function renderNames(namesText) {
  document.getElementById('onshift').innerHTML = namesText;
}

function renderStatus(statusText) {
  document.getElementById('status').textContent = statusText;
}

function boolToText(isOpenBool) {
  if (isOpenBool)
  {
    setIcon("Open");
    return "ÅPEN";
  }
  else
  {
    setIcon("");
    return "CLØSED";
  }
}

function setIcon(openString) {
  chrome.browserAction.setIcon({path:"Assets/icon"+openString+"38.png"});
}

function getShowNames(callback) {
  chrome.storage.sync.get({
    showshiftsetting: true
  }, function(items) {
    callback(items.showshiftsetting);
  })
}

function getShowOpening(callback) {
  chrome.storage.sync.get({
    showopeningsetting: true
  }, function(items) {
    callback(items.showopeningsetting);
  })
}

document.addEventListener('DOMContentLoaded', function() {
  renderStatus('Cafe Analog is ...');

  getIsAnalogOpen( function (boolValue) {
    renderStatus('Cafe Analog is ' + boolToText(boolValue));
    // names
    if (boolValue) {
      getNames( function (names) {
        renderNames(names); // put special handeling if necesarry
      }, renderNames);
    }
    // opening
    getOpening( function(openingText) {
      if (boolValue)
      {
        renderOpening(openingText);
      }
      else
      {
        renderOpening("We open again " + openingText);
      }
    }, renderOpening);
  }, renderStatus);
});
<|endoftext|>


<commit_before>(function () {
  "use strict";
  var defaultSE = "Google.com";
  var advanced_settings = document.getElementsByClassName('chrometana_advanced_setting');
  var useCustomSearch = document.getElementById('useCustomSearch');
  var custom_engine_settings = document.getElementById('custom_engine_settings');
  var selectorList = document.getElementsByClassName('selector');

  if (getURLVariable("newinstall") === "yes"){
    var installadvice = document.getElementById('installadvice');
    addClass(installadvice, 'visible');
  }

  if (getURLVariable("update") === "yes"){
    // var installadvice = document.getElementById('installadvice');
    // addClass(installadvice, 'visible');
      chrome.storage.sync.get(['search_engine','custom_engine','enable_open_website','all_bing_searches','exclude_settings_app'], function (obj) {
        console.log(obj);
      });
      save_options("all_bing_searches", true);
  }

  var optionCaller = function() {
    save_options('search_engine', this.getAttribute('value'));
  };

  var handleMouseover = function() {
    var selectedElements = document.getElementsByClassName('hovering');
    for (var i = 0; i < selectedElements.length; i++) {
      removeClass(selectedElements[i], 'hovering');
    }
    var selected = document.getElementsByClassName('selected')[0];
    removeClass(selected, 'hovering');
    addClass(this, 'hovering');

  };

  var handleMouseout = function() {
    var selected = document.getElementsByClassName('selected')[0];
    removeClass(this, 'hovering');
    addClass(selected, 'hovering');
  };

  var advancedSettingsCaller = function() {
    var value;
    if(this.getAttribute("type") === "checkbox" || this.getAttribute("type") === "radio"){
      if(this.checked){
        value = true;
      }
      else{
        value = false;
      }
    }
    save_options(this.id, value);
  };

  function save_options(key, value){
    var options = {};
    options[key] = value;
    if(key === "custom_engine"){
      if(value !== ""){
        options.search_engine = "Custom";
      }
      else{
        options.search_engine = defaultSE;
      }
    }
    chrome.storage.sync.set(options, function() {
      restore_options();
    });
  }

  // Restores select box and checkbox state using the preferences
  // stored in chrome.storage.
  function restore_options() {
    chrome.storage.sync.get({
      search_engine: defaultSE,
      custom_engine: '',
      enable_open_website: false,
      all_bing_searches: true,
      exclude_settings_app: true
    }, function(items) {
      updateDisplay(items);
    });
  }

  function updateDisplay(items){
    for (var i = 0; i <  selectorList.length; i++) {
      if (selectorList[i].getAttribute('value') === items.search_engine) {
        addClass(selectorList[i], 'selected');
        addClass(selectorList[i], 'hovering');
      }
      else {
        removeClass(selectorList[i], 'selected');
      }
    }
    if(items.search_engine === "Custom"){
      useCustomSearch.checked = true;
    }
    else{
      useCustomSearch.checked = false;
    }
    document.getElementById("custom_engine").value = items.custom_engine;
    updateCustomSearchView();
    updateCheckBoxes(items);
    var status = document.getElementById('status');
    addClass(status, 'updated');
      status.textContent = 'New search engine preferences saved.';
      setTimeout(function() {
        status.textContent = '';
        removeClass(status, 'updated');
      }, 1050);
  }

  function updateCheckBoxes(items){
    for (var i = 0; i <  advanced_settings.length; i++) {
      var id = advanced_settings[i].getAttribute("id");
      if(id in items){
        if(items[id] === true){
          document.getElementById(id).checked = true;
        }
        else{
          document.getElementById(id).checked = false;
        }
      }
      else if (id !== null){
        document.getElementById(id).checked = false;
      }
    }
  }

  function updateCustomSearchView(){
    if(useCustomSearch.checked){
      addClass(custom_engine_settings, 'visible');
    }
    else{
      removeClass(custom_engine_settings, 'visible');
    }
  }

  //Parses arguments from URL
  function getURLVariable(variable){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      if(pair[0] === variable){
        return pair[1];
      }
    }
    return(false);
  }

  function addClass(element, classNameToAdd) {
    if(typeof element!=="undefined"){
      element.classList.add(classNameToAdd);
    }
  }

  function removeClass(element, classNameToRemove) {
    if(typeof element!=="undefined"){
      element.classList.remove(classNameToRemove);
    }
  }

  // Add Event Listeners
  document.addEventListener('DOMContentLoaded', restore_options);

  for (var s = 0; s <  selectorList.length; s++) {
    selectorList[s].addEventListener('click', optionCaller,false);
    selectorList[s].addEventListener('mouseover', handleMouseover, false);
    selectorList[s].addEventListener('mouseleave', handleMouseout, false);
  }

  useCustomSearch.addEventListener('click', function() {
    updateCustomSearchView();
    if(!this.checked){
      document.getElementById('custom_engine_update').click();
    }
  });

  for (var i = 0; i <  advanced_settings.length; i++) {
    advanced_settings[i].addEventListener('click', advancedSettingsCaller, false);
  }

  document.getElementById('custom_engine_update').addEventListener('click', function() {
    var element = document.getElementById('custom_engine');
    if(useCustomSearch.checked){
      if(element.value.toLowerCase().indexOf("http") !== -1){
        save_options('custom_engine', element, element.value);
      }
      else{
        alert("Custom search engine must start with http");
      }
    }
    else{
      save_options('custom_engine', element, "");
    }
  });

  document.getElementById('additional-settings-toggle').addEventListener('click', function() {
    var settingsPane = document.getElementById('expandable_settings_pane');
    var engines = document.getElementById('custom-engine-select');

    if (settingsPane.className.search('open') >= 0) {
      removeClass(settingsPane, 'open');
      removeClass(engines, 'hidden');
    }
    else {
      addClass(settingsPane, 'open');
      addClass(engines, 'hidden');
    }
  });
}());<commit_msg>only update all_bing_searches if not already set<commit_after>(function () {
  "use strict";
  var defaultSE = "Google.com";
  var advanced_settings = document.getElementsByClassName('chrometana_advanced_setting');
  var useCustomSearch = document.getElementById('useCustomSearch');
  var custom_engine_settings = document.getElementById('custom_engine_settings');
  var selectorList = document.getElementsByClassName('selector');

  if (getURLVariable("newinstall") === "yes"){
    var installadvice = document.getElementById('installadvice');
    addClass(installadvice, 'visible');
    // Set all bing searches to redirect by default (Google policy "works by default" workaround)
    save_options('all_bing_searches', true);
  }

  if (getURLVariable("update") === "yes"){
      chrome.storage.sync.get(['all_bing_searches'], function (all_bing_searches){
        console.log(all_bing_searches);
        if(all_bing_searches['all_bing_searches'] != null) {
          console.log("already set");
        } else {
          // Set all bing searches to redirect by default (Google policy "works by default" workaround)
          save_options('all_bing_searches', true);
          console.log("just set");
        }
      });
  }

  var optionCaller = function() {
    save_options('search_engine', this.getAttribute('value'));
  };

  var handleMouseover = function() {
    var selectedElements = document.getElementsByClassName('hovering');
    for (var i = 0; i < selectedElements.length; i++) {
      removeClass(selectedElements[i], 'hovering');
    }
    var selected = document.getElementsByClassName('selected')[0];
    removeClass(selected, 'hovering');
    addClass(this, 'hovering');

  };

  var handleMouseout = function() {
    var selected = document.getElementsByClassName('selected')[0];
    removeClass(this, 'hovering');
    addClass(selected, 'hovering');
  };

  var advancedSettingsCaller = function() {
    var value;
    if(this.getAttribute("type") === "checkbox" || this.getAttribute("type") === "radio"){
      if(this.checked){
        value = true;
      }
      else{
        value = false;
      }
    }
    save_options(this.id, value);
  };

  function save_options(key, value){
    var options = {};
    options[key] = value;
    if(key === "custom_engine"){
      if(value !== ""){
        options.search_engine = "Custom";
      }
      else{
        options.search_engine = defaultSE;
      }
    }
    chrome.storage.sync.set(options, function() {
      restore_options();
    });
  }

  // Restores select box and checkbox state using the preferences
  // stored in chrome.storage.
  function restore_options() {
    chrome.storage.sync.get({
      search_engine: defaultSE,
      custom_engine: '',
      enable_open_website: false,
      all_bing_searches: true,
      exclude_settings_app: true
    }, function(items) {
      updateDisplay(items);
    });
  }

  function updateDisplay(items){
    for (var i = 0; i <  selectorList.length; i++) {
      if (selectorList[i].getAttribute('value') === items.search_engine) {
        addClass(selectorList[i], 'selected');
        addClass(selectorList[i], 'hovering');
      }
      else {
        removeClass(selectorList[i], 'selected');
      }
    }
    if(items.search_engine === "Custom"){
      useCustomSearch.checked = true;
    }
    else{
      useCustomSearch.checked = false;
    }
    document.getElementById("custom_engine").value = items.custom_engine;
    updateCustomSearchView();
    updateCheckBoxes(items);
    var status = document.getElementById('status');
    addClass(status, 'updated');
      status.textContent = 'New search engine preferences saved.';
      setTimeout(function() {
        status.textContent = '';
        removeClass(status, 'updated');
      }, 1050);
  }

  function updateCheckBoxes(items){
    for (var i = 0; i <  advanced_settings.length; i++) {
      var id = advanced_settings[i].getAttribute("id");
      if(id in items){
        if(items[id] === true){
          document.getElementById(id).checked = true;
        }
        else{
          document.getElementById(id).checked = false;
        }
      }
      else if (id !== null){
        document.getElementById(id).checked = false;
      }
    }
  }

  function updateCustomSearchView(){
    if(useCustomSearch.checked){
      addClass(custom_engine_settings, 'visible');
    }
    else{
      removeClass(custom_engine_settings, 'visible');
    }
  }

  //Parses arguments from URL
  function getURLVariable(variable){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split("=");
      if(pair[0] === variable){
        return pair[1];
      }
    }
    return(false);
  }

  function addClass(element, classNameToAdd) {
    if(typeof element!=="undefined"){
      element.classList.add(classNameToAdd);
    }
  }

  function removeClass(element, classNameToRemove) {
    if(typeof element!=="undefined"){
      element.classList.remove(classNameToRemove);
    }
  }

  // Add Event Listeners
  document.addEventListener('DOMContentLoaded', restore_options);

  for (var s = 0; s <  selectorList.length; s++) {
    selectorList[s].addEventListener('click', optionCaller,false);
    selectorList[s].addEventListener('mouseover', handleMouseover, false);
    selectorList[s].addEventListener('mouseleave', handleMouseout, false);
  }

  useCustomSearch.addEventListener('click', function() {
    updateCustomSearchView();
    if(!this.checked){
      document.getElementById('custom_engine_update').click();
    }
  });

  for (var i = 0; i <  advanced_settings.length; i++) {
    advanced_settings[i].addEventListener('click', advancedSettingsCaller, false);
  }

  document.getElementById('custom_engine_update').addEventListener('click', function() {
    var element = document.getElementById('custom_engine');
    if(useCustomSearch.checked){
      if(element.value.toLowerCase().indexOf("http") !== -1){
        save_options('custom_engine', element, element.value);
      }
      else{
        alert("Custom search engine must start with http");
      }
    }
    else{
      save_options('custom_engine', element, "");
    }
  });

  document.getElementById('additional-settings-toggle').addEventListener('click', function() {
    var settingsPane = document.getElementById('expandable_settings_pane');
    var engines = document.getElementById('custom-engine-select');

    if (settingsPane.className.search('open') >= 0) {
      removeClass(settingsPane, 'open');
      removeClass(engines, 'hidden');
    }
    else {
      addClass(settingsPane, 'open');
      addClass(engines, 'hidden');
    }
  });
}());<|endoftext|>


<commit_before>const { assign } = require('lodash')
const { globalFields } = require('../../macros')

const eventFormConfig = ({
  eventId,
  advisers,
  eventTypes,
  locationTypes,
  countries,
  teams,
  services,
  programmes,
  ukRegions,
}) => {
  return {
    class: 'js-vue-wrapper',
    method: 'post',
    buttonText: eventId ? 'Save and return' : 'Add event',
    returnText: eventId ? 'Return without saving' : 'Cancel',
    returnLink: eventId ? `/events/${eventId}` : '/events',
    hiddenFields: {
      id: eventId,
    },
    children: [
      {
        macroName: 'TextField',
        name: 'name',
        label: 'Event name',
      },
      assign({}, globalFields.eventTypes, {
        options: eventTypes,
      }),
      {
        macroName: 'DateFieldset',
        name: 'start_date',
        label: 'Event start date',
      },
      {
        macroName: 'DateFieldset',
        name: 'end_date',
        label: 'Event end date',
      },
      assign({}, globalFields.locationTypes, {
        label: 'Event location type',
        optional: true,
        options: locationTypes,
      }),
      {
        macroName: 'TextField',
        name: 'address_1',
        label: 'Business and street',
      },
      {
        macroName: 'TextField',
        name: 'address_2',
        label: 'Second line of address',
        isLabelHidden: true,
        optional: true,
      },
      {
        macroName: 'TextField',
        name: 'address_town',
        label: 'Town or city',
      },
      {
        macroName: 'TextField',
        name: 'address_county',
        label: 'County',
      },
      {
        macroName: 'TextField',
        name: 'postcode',
        label: 'Postcode',
        class: 'u-js-hidden',
      },
      assign({}, globalFields.countries, {
        name: 'address_country',
        options: countries,
      }),
      assign({}, globalFields.ukRegions, {
        condition: {
          name: 'address_country',
          value: '80756b9a-5d95-e211-a939-e4115bead28a',
        },
        options: ukRegions,
      }),
      {
        macroName: 'TextField',
        type: 'textarea',
        name: 'notes',
        label: 'Event notes',
        optional: true,
      },
      assign({}, globalFields.teams, {
        name: 'lead_team',
        label: 'Team hosting the event',
        optional: false,
        options: teams,
      }),
      assign({}, globalFields.serviceDeliveryServices, {
        options: services,
      }),
      {
        macroName: 'Typeahead',
        name: 'dit_adviser',
        entity: 'adviser',
        label: 'Organiser',
        classes: 'c-form-group c-form-group--no-filter',
        placeholder: 'Search organiser',
        multipleSelect: false,
        options: advisers,
      },
      {
        macroName: 'MultipleChoiceField',
        type: 'radio',
        name: 'event_shared',
        label: 'Is this a shared event',
        optional: true,
        modifier: 'inline',
        options: [
          {
            label: 'Yes',
            value: 'true',
          },
          {
            label: 'No',
            value: 'false',
          },
        ],
      },
      {
        macroName: 'AddAnother',
        buttonName: 'add_team',
        name: 'teams',
        label: 'Teams',
        children: [
          assign({}, globalFields.teams, {
            name: 'teams',
            label: 'Team',
            isLabelHidden: true,
            persistsConditionalValue: true,
            optional: true,
            options: teams,
          }),
        ],
        modifier: 'subfield',
        condition: {
          name: 'event_shared',
          value: 'true',
        },
      },
      {
        macroName: 'AddAnother',
        buttonName: 'add_related_programme',
        name: 'related_programmes',
        label: 'Related programmes',
        children: [
          assign({}, globalFields.programmes, {
            name: 'related_programmes',
            label: 'Related programmes',
            isLabelHidden: true,
            optional: true,
            options: programmes,
          }),
        ],
      },
    ],
  }
}

module.exports = eventFormConfig
<commit_msg>Remove class as it swallows click events<commit_after>const { assign } = require('lodash')
const { globalFields } = require('../../macros')

const eventFormConfig = ({
  eventId,
  advisers,
  eventTypes,
  locationTypes,
  countries,
  teams,
  services,
  programmes,
  ukRegions,
}) => {
  return {
    method: 'post',
    buttonText: eventId ? 'Save and return' : 'Add event',
    returnText: eventId ? 'Return without saving' : 'Cancel',
    returnLink: eventId ? `/events/${eventId}` : '/events',
    hiddenFields: {
      id: eventId,
    },
    children: [
      {
        macroName: 'TextField',
        name: 'name',
        label: 'Event name',
      },
      assign({}, globalFields.eventTypes, {
        options: eventTypes,
      }),
      {
        macroName: 'DateFieldset',
        name: 'start_date',
        label: 'Event start date',
      },
      {
        macroName: 'DateFieldset',
        name: 'end_date',
        label: 'Event end date',
      },
      assign({}, globalFields.locationTypes, {
        label: 'Event location type',
        optional: true,
        options: locationTypes,
      }),
      {
        macroName: 'TextField',
        name: 'address_1',
        label: 'Business and street',
      },
      {
        macroName: 'TextField',
        name: 'address_2',
        label: 'Second line of address',
        isLabelHidden: true,
        optional: true,
      },
      {
        macroName: 'TextField',
        name: 'address_town',
        label: 'Town or city',
      },
      {
        macroName: 'TextField',
        name: 'address_county',
        label: 'County',
      },
      {
        macroName: 'TextField',
        name: 'postcode',
        label: 'Postcode',
        class: 'u-js-hidden',
      },
      assign({}, globalFields.countries, {
        name: 'address_country',
        options: countries,
      }),
      assign({}, globalFields.ukRegions, {
        condition: {
          name: 'address_country',
          value: '80756b9a-5d95-e211-a939-e4115bead28a',
        },
        options: ukRegions,
      }),
      {
        macroName: 'TextField',
        type: 'textarea',
        name: 'notes',
        label: 'Event notes',
        optional: true,
      },
      assign({}, globalFields.teams, {
        name: 'lead_team',
        label: 'Team hosting the event',
        optional: false,
        options: teams,
      }),
      assign({}, globalFields.serviceDeliveryServices, {
        options: services,
      }),
      {
        macroName: 'Typeahead',
        name: 'dit_adviser',
        entity: 'adviser',
        label: 'Organiser',
        classes: 'c-form-group c-form-group--no-filter',
        placeholder: 'Search organiser',
        multipleSelect: false,
        options: advisers,
      },
      {
        macroName: 'MultipleChoiceField',
        type: 'radio',
        name: 'event_shared',
        label: 'Is this a shared event',
        optional: true,
        modifier: 'inline',
        options: [
          {
            label: 'Yes',
            value: 'true',
          },
          {
            label: 'No',
            value: 'false',
          },
        ],
      },
      {
        macroName: 'AddAnother',
        buttonName: 'add_team',
        name: 'teams',
        label: 'Teams',
        children: [
          assign({}, globalFields.teams, {
            name: 'teams',
            label: 'Team',
            isLabelHidden: true,
            persistsConditionalValue: true,
            optional: true,
            options: teams,
          }),
        ],
        modifier: 'subfield',
        condition: {
          name: 'event_shared',
          value: 'true',
        },
      },
      {
        macroName: 'AddAnother',
        buttonName: 'add_related_programme',
        name: 'related_programmes',
        label: 'Related programmes',
        children: [
          assign({}, globalFields.programmes, {
            name: 'related_programmes',
            label: 'Related programmes',
            isLabelHidden: true,
            optional: true,
            options: programmes,
          }),
        ],
      },
    ],
  }
}

module.exports = eventFormConfig
<|endoftext|>


<commit_before>
var Base = require('./Base.js');
var Graph = require('./Graph.js');
var Http = require('http');
var Https = require('https');
var Neo4jUtils = require('./Neo4jUtils.js');
var Node = require('./Node.js');
var Path = require('./Path.js');
var Relationship = require('./Relationship.js');
var Url = require('url');

/* ========================================================================================================
 *
 * Private Members Declaration (no methods)
 *
 * ===================================================================================================== */

// code

/* ========================================================================================================
 *
 * Public Members Declaration (no methods)
 *
 * ===================================================================================================== */

// code

module.exports.connect = function (initUrl, callback)
{
	var _basePath;
	var _endpoints = {};

	/* ========================================================================================================
	 *
	 * Initialization
	 *
	 * ===================================================================================================== */

	// setup internal namespace
	var neo4j = {};

	neo4j.Api =
	{
		Batch: Batch,
		PreProcessedContent: PreProcessedContent,
		Request: Request,
		getEndpoint: getEndpoint,
		reconnect: reconnect
	};

	neo4j.Utils = new Neo4jUtils(neo4j);

	neo4j.Base = Base(neo4j);
	neo4j.Node = Node(neo4j);
	neo4j.Relationship = Relationship(neo4j);
	neo4j.Path = Path(neo4j);

	neo4j._graph = new Graph(neo4j);

	process.nextTick(reconnect.bind(null, initUrl, callback)); // let the Request class get setup before calling anything.

	/* ========================================================================================================
	 *
	 * Internal Methods - Keep in alphabetical order
	 *
	 * ===================================================================================================== */

	function createEndpoint (base, name, replacer)
	{
		_endpoints[name] = {};

		for (var i in _endpoints[base])
		{
			switch (i)
			{
				case 'path':
				case 'pathname':
				case 'href':
					_endpoints[name][i] = replacer(_endpoints[base][i]);
					break;
				default:
					_endpoints[name][i] = _endpoints[base][i];
					break;
			}
		}
	}

	function getEndpoint (endpoint, path)
	{
		var result = {};

		if (typeof endpoint === 'string')
			endpoint = _endpoints[endpoint];

		if (!path)
			return endpoint;

		for (var i in endpoint)
		{
			result[i] = endpoint[i];
		}

		// this always discards any query which existed in the original endpoint. This should not be a problem unless neo4j starts using query strings in their base url's
		result.path = neo4j.Utils.pathJoin(result.pathname, path + '');
		result.href = result.protocol + '//' + result.hostname + ':' + result.port + result.path;

		return result;
	}

	function reconnect (initUrl, callback)
	{
		var endpoint = Url.parse(initUrl);
		_endpoints.root = endpoint;

		_basePath = endpoint.pathname;
		if (_basePath[_basePath.length - 1] === '/') // this should always be true, but just in case it changes in the future
			_basePath = _basePath.substr(0, _basePath.length - 1);

		new Request(null, endpoint, 'GET', null, function (error, obj)
		{
			if (error)
			{
				callback(error);
				return;
			}

			for (var i in obj)
			{
				if (i === 'neo4j_version')
					neo4j._graph.version = obj[i];
				else if (i !== 'extensions')
					_endpoints[i] = Url.parse(obj[i]);
			}

			if (!_endpoints.relationship) // for some reason, the api doesn't directly provide the endpoint for relationships, so we'll create it
			{
				createEndpoint('node', 'relationship', function (str) { return str.replace(/node$/, 'relationship'); });
			}

			createEndpoint('node_index', 'node_auto', function (str) { return str.replace(/node$/, 'auto/node'); });
			createEndpoint('relationship_index', 'relationship_auto', function (str) { return str.replace(/relationship$/, 'auto/relationship'); });

			callback(null, neo4j._graph);
		});
	}

	/* ========================================================================================================
	 *
	 * Batch Class
	 *
	 * ===================================================================================================== */

	function Batch ()
	{
		this.requests = [];
		this.run = runBatch.bind(null, this.requests);
	}

	/* ========================================================================================================
	 *
	 * PreProcessedContent Class
	 *
	 * ===================================================================================================== */

	function PreProcessedContent (content)
	{
		this.content = content + '';
	}

	PreProcessedContent.prototype.toJSON = function () { return this.content; };

	/* ========================================================================================================
	 *
	 * Request Class
	 *
	 * ===================================================================================================== */

	function Request (batch, endpoint, method, data, callback)
	{
		this.endpoint = typeof endpoint === 'string' ? _endpoints[endpoint] : endpoint;
		this.method = method;
		this.data = data;
		this.callback = callback;

		if (batch)
			batch.requests.push(this);
		else
			this.send(); // if no batch, send immediately
	}

	Request.prototype.send = function ()
	{
		var options =
		{
			hostname: this.endpoint.hostname,
			port: this.endpoint.port,
			path: this.endpoint.path,
			method: this.method,
			headers: { Accept: 'application/json'/*, 'X-Stream': 'true' */}
		};

		if (this.data !== undefined && this.data !== null)
			options.headers['Content-Type'] = 'application/json'; // this doesn't appear to be necessary, but perhaps it is for backwards compatibility.

		var http = this.endpoint.protocol === 'https:' ? Https : Http;

		var request = http.request(options, Request.createCallback(this.callback));
		request.on('error', this.callback);

		if (this.data instanceof PreProcessedContent)
			request.write(this.data.toJSON());
		else if (this.data !== undefined && this.data !== null)
			request.write(JSON.stringify(this.data));

		request.end();
	};

	Request.createCallback = function (callback)
	{
		return function (response)
		{
			var result = [];
			var error = null;
			if (response.statusCode > 204)
			{
				error = new Error('Unspecified neo4j API Error.');
				error.code = response.statusCode;
			}

			response.setEncoding('utf8');
			response.on('data', function (data) { result.push(data); });

			response.on('end', function ()
			{
				var obj = null;

				try
				{
					if (result.length)
						obj = JSON.parse(result.join(''));
				}
				catch (e)
				{
					callback(e);
					return;
				}

				if (error)
				{
					if (obj)
					{
						error.innerError = obj;
						error.message = obj.message;
						error.exception = obj.exception;
						error.fullname = obj.fullname;
					}
					callback (error);
				}
				else
				{
					callback(null, obj);
				}
			});
		};
	};

	function runBatch (requests, errorCallback)
	{
		if (requests.length === 0)
			return;

		if (requests.length === 1)
		{
			requests[0].send();
			return;
		}

		var req = [];

		for (var i = 0; i < requests.length; i++)
		{
			req.push(
			{
				id: i,
				method: requests[i].method,
				to: requests[i].endpoint.path.substr(_basePath.length),
				body: requests[i].data !== null ? requests[i].data : undefined
			});
		}

		new Request(null, 'batch', 'POST', req, function (error, obj)
		{
			if (error || obj.length < req.length || (obj[obj.length - 1].status && obj[obj.length - 1].status > 204))
			{
				if (!error)
				{
					error = new Error(obj[obj.length - 1].body ? obj[obj.length - 1].body.message : 'Unknown neo4j REST API Error');
					error.code = obj[obj.length - 1].status;
					if (obj[obj.length - 1].body)
						error.exception = obj[obj.length - 1].body.exception;
					error.innerError = obj[obj.length - 1].body;
				}

				if (errorCallback)
				{
					errorCallback(error);
				}
				else
				{
					for (var i in requests)
						requests[i].callback(error);
				}
			}
			else
			{
				for (var i in requests)
				{
					requests[obj[i].id].callback(null, obj[i].body);
				}
			}
		});
	}
};
<commit_msg>Fix for the authentication problem.<commit_after>
var Base = require('./Base.js');
var Graph = require('./Graph.js');
var Http = require('http');
var Https = require('https');
var Neo4jUtils = require('./Neo4jUtils.js');
var Node = require('./Node.js');
var Path = require('./Path.js');
var Relationship = require('./Relationship.js');
var Url = require('url');

/* ========================================================================================================
 *
 * Private Members Declaration (no methods)
 *
 * ===================================================================================================== */

// code

/* ========================================================================================================
 *
 * Public Members Declaration (no methods)
 *
 * ===================================================================================================== */

// code

module.exports.connect = function (initUrl, callback)
{
	var _basePath;
	var _endpoints = {};

	/* ========================================================================================================
	 *
	 * Initialization
	 *
	 * ===================================================================================================== */

	// setup internal namespace
	var neo4j = {};

	neo4j.Api =
	{
		Batch: Batch,
		PreProcessedContent: PreProcessedContent,
		Request: Request,
		getEndpoint: getEndpoint,
		reconnect: reconnect
	};

	neo4j.Utils = new Neo4jUtils(neo4j);

	neo4j.Base = Base(neo4j);
	neo4j.Node = Node(neo4j);
	neo4j.Relationship = Relationship(neo4j);
	neo4j.Path = Path(neo4j);

	neo4j._graph = new Graph(neo4j);

	process.nextTick(reconnect.bind(null, initUrl, callback)); // let the Request class get setup before calling anything.

	/* ========================================================================================================
	 *
	 * Internal Methods - Keep in alphabetical order
	 *
	 * ===================================================================================================== */

	function createEndpoint (base, name, replacer)
	{
		_endpoints[name] = {};

		for (var i in _endpoints[base])
		{
			switch (i)
			{
				case 'path':
				case 'pathname':
				case 'href':
					_endpoints[name][i] = replacer(_endpoints[base][i]);
					break;
				default:
					_endpoints[name][i] = _endpoints[base][i];
					break;
			}
		}
	}

	function getEndpoint (endpoint, path)
	{
		var result = {};

		if (typeof endpoint === 'string')
			endpoint = _endpoints[endpoint];

		if (!path)
			return endpoint;

		for (var i in endpoint)
		{
			result[i] = endpoint[i];
		}

		// this always discards any query which existed in the original endpoint. This should not be a problem unless neo4j starts using query strings in their base url's
		result.path = neo4j.Utils.pathJoin(result.pathname, path + '');
		result.href = result.protocol + '//' + result.hostname + ':' + result.port + result.path;

		return result;
	}

	function reconnect (initUrl, callback)
	{
		var endpoint = Url.parse(initUrl);
		_endpoints.root = endpoint;

		_basePath = endpoint.pathname;
		if (_basePath[_basePath.length - 1] === '/') // this should always be true, but just in case it changes in the future
			_basePath = _basePath.substr(0, _basePath.length - 1);

		new Request(null, endpoint, 'GET', null, function (error, obj)
		{
			if (error)
			{
				callback(error);
				return;
			}

			for (var i in obj)
			{
				if (i === 'neo4j_version')
					neo4j._graph.version = obj[i];
				else if (i !== 'extensions')
					_endpoints[i] = Url.parse(obj[i]);
			}

			if (!_endpoints.relationship) // for some reason, the api doesn't directly provide the endpoint for relationships, so we'll create it
			{
				createEndpoint('node', 'relationship', function (str) { return str.replace(/node$/, 'relationship'); });
			}

			createEndpoint('node_index', 'node_auto', function (str) { return str.replace(/node$/, 'auto/node'); });
			createEndpoint('relationship_index', 'relationship_auto', function (str) { return str.replace(/relationship$/, 'auto/relationship'); });

			callback(null, neo4j._graph);
		});
	}

	/* ========================================================================================================
	 *
	 * Batch Class
	 *
	 * ===================================================================================================== */

	function Batch ()
	{
		this.requests = [];
		this.run = runBatch.bind(null, this.requests);
	}

	/* ========================================================================================================
	 *
	 * PreProcessedContent Class
	 *
	 * ===================================================================================================== */

	function PreProcessedContent (content)
	{
		this.content = content + '';
	}

	PreProcessedContent.prototype.toJSON = function () { return this.content; };

	/* ========================================================================================================
	 *
	 * Request Class
	 *
	 * ===================================================================================================== */

	function Request (batch, endpoint, method, data, callback)
	{
		this.endpoint = typeof endpoint === 'string' ? _endpoints[endpoint] : endpoint;
		this.method = method;
		this.data = data;
		this.callback = callback;

		if (batch)
			batch.requests.push(this);
		else
			this.send(); // if no batch, send immediately
	}

	Request.prototype.send = function ()
	{
		var options =
		{
			hostname: this.endpoint.hostname,
			port: this.endpoint.port,
			path: this.endpoint.path,
			auth: _endpoints.root.auth,
			method: this.method,
			headers: { Accept: 'application/json'/*, 'X-Stream': 'true' */}
		};

		if (this.data !== undefined && this.data !== null)
			options.headers['Content-Type'] = 'application/json'; // this doesn't appear to be necessary, but perhaps it is for backwards compatibility.

		var http = this.endpoint.protocol === 'https:' ? Https : Http;

		var request = http.request(options, Request.createCallback(this.callback));
		request.on('error', this.callback);

		if (this.data instanceof PreProcessedContent)
			request.write(this.data.toJSON());
		else if (this.data !== undefined && this.data !== null)
			request.write(JSON.stringify(this.data));

		request.end();
	};

	Request.createCallback = function (callback)
	{
		return function (response)
		{
			var result = [];
			var error = null;
			if (response.statusCode > 204)
			{
				error = new Error('Unspecified neo4j API Error.');
				error.code = response.statusCode;
			}

			response.setEncoding('utf8');
			response.on('data', function (data) { result.push(data); });

			response.on('end', function ()
			{
				var obj = null;

				try
				{
					if (result.length)
						obj = JSON.parse(result.join(''));
				}
				catch (e)
				{
					callback(e);
					return;
				}

				if (error)
				{
					if (obj)
					{
						error.innerError = obj;
						error.message = obj.message;
						error.exception = obj.exception;
						error.fullname = obj.fullname;
					}
					callback (error);
				}
				else
				{
					callback(null, obj);
				}
			});
		};
	};

	function runBatch (requests, errorCallback)
	{
		if (requests.length === 0)
			return;

		if (requests.length === 1)
		{
			requests[0].send();
			return;
		}

		var req = [];

		for (var i = 0; i < requests.length; i++)
		{
			req.push(
			{
				id: i,
				method: requests[i].method,
				to: requests[i].endpoint.path.substr(_basePath.length),
				body: requests[i].data !== null ? requests[i].data : undefined
			});
		}

		new Request(null, 'batch', 'POST', req, function (error, obj)
		{
			if (error || obj.length < req.length || (obj[obj.length - 1].status && obj[obj.length - 1].status > 204))
			{
				if (!error)
				{
					error = new Error(obj[obj.length - 1].body ? obj[obj.length - 1].body.message : 'Unknown neo4j REST API Error');
					error.code = obj[obj.length - 1].status;
					if (obj[obj.length - 1].body)
						error.exception = obj[obj.length - 1].body.exception;
					error.innerError = obj[obj.length - 1].body;
				}

				if (errorCallback)
				{
					errorCallback(error);
				}
				else
				{
					for (var i in requests)
						requests[i].callback(error);
				}
			}
			else
			{
				for (var i in requests)
				{
					requests[obj[i].id].callback(null, obj[i].body);
				}
			}
		});
	}
};
<|endoftext|>


<commit_before>var L = A.Lang,
	isNumber = L.isNumber,
	isString = L.isString,

	BLANK = '',
	DOT = '.',
	SPACE = ' ',

	AUTO = 'auto',
	BOUNDING_BOX = 'boundingBox',
	COMPLETE = 'complete',
	CONTENT_BOX = 'contentBox',
	HEIGHT = 'height',
	HORIZONTAL = 'horizontal',
	LABEL = 'label',
	LINE_HEIGHT = 'lineHeight',
	MAX = 'max',
	MIN = 'min',
	ORIENTATION = 'orientation',
	PROGRESS_BAR = 'progress-bar',
	PX = 'px',
	RATIO = 'ratio',
	STATUS = 'status',
	STATUS_NODE = 'statusNode',
	STEP = 'step',
	TEXT = 'text',
	TEXT_NODE = 'textNode',
	VALUE = 'value',
	VERTICAL = 'vertical',
	WIDTH = 'width',

	toNumber = function(v) {
		return parseInt(v, 10) || 0;
	},

	getCN = A.ClassNameManager.getClassName,

	CSS_HORIZONTAL = getCN(PROGRESS_BAR, HORIZONTAL),
	CSS_STATUS = getCN(PROGRESS_BAR, STATUS),
	CSS_TEXT = getCN(PROGRESS_BAR, TEXT),
	CSS_VERTICAL = getCN(PROGRESS_BAR, VERTICAL),

	TPL_STATUS = '

',
	TPL_TEXT = '

',

	WP = A.Widget.prototype,

	UI_ATTRS = [ LABEL, ORIENTATION, VALUE ],

	_BIND_UI_ATTRS = WP._BIND_UI_ATTRS,
	_SYNC_UI_ATTRS = WP._SYNC_UI_ATTRS,

	BIND_UI_ATTRS = _BIND_UI_ATTRS.concat(UI_ATTRS),
	SYNC_UI_ATTRS = _SYNC_UI_ATTRS.concat(UI_ATTRS);

function ProgressBar(config) {
	ProgressBar.superclass.constructor.apply(this, arguments);
}

A.mix(ProgressBar, {
	NAME: PROGRESS_BAR,

	ATTRS: {
		height: {
			value: 25
		},

		label: {
			value: BLANK
		},

		max: {
			validator: isNumber,
			value: 100
		},

		min: {
			validator: isNumber,
			value: 0
		},

		orientation: {
			value: HORIZONTAL,
			validator: function(val) {
				return isString(val) && (val === HORIZONTAL || val === VERTICAL);
			}
		},

		ratio: {
			getter: '_getRatio',
			readOnly: true
		},

		step: {
			getter: '_getStep',
			readOnly: true
		},

		statusNode: {
			valueFn: function() {
				return A.Node.create(TPL_STATUS);
			}
		},

		textNode: {
			valueFn: function() {
				return A.Node.create(TPL_TEXT);
			}
		},

		value: {
			setter: toNumber,
			validator: function(val) {
				return isNumber(toNumber(val)) && ((val >= this.get(MIN)) && (val <= this.get(MAX)));
			},
			value: 0
		},

		width: {
			value: 250
		}
	},

	HTML_PARSER: {
		label: function(boundingBox) {
			var textNode = boundingBox.one(DOT+CSS_TEXT);

			if (textNode) {
				return textNode.html();
			}
		},
		statusNode: DOT+CSS_STATUS,
		textNode: DOT+CSS_TEXT
	}
});

A.extend(ProgressBar, A.Widget, {
	_BIND_UI_ATTRS: BIND_UI_ATTRS,
	_SYNC_UI_ATTRS: SYNC_UI_ATTRS,

	/*
	* Lifecycle
	*/
	renderUI: function() {
		var instance = this;

		instance._renderStatusNode();
		instance._renderTextNode();
	},

	bindUI: function() {
		var instance = this;

		instance.after('valueChange', A.bind(instance._afterValueChange, instance));
	},

	_afterValueChange: function(event) {
		var instance = this;
		var step = instance.get(STEP);

		if (step >= 100) {
			instance.fire(COMPLETE, {
				progressbar: {
					ratio: instance.get(RATIO),
					step: step,
					value: instance.get(VALUE)
				}
			});
		}
	},

	_getContentBoxSize: function() {
		var instance = this;
		var contentBox = instance.get(CONTENT_BOX);

		return toNumber(
			contentBox.getStyle(
				(this.get(ORIENTATION) === HORIZONTAL) ? WIDTH : HEIGHT
			)
		);
	},

	_getPixelStep: function() {
		var instance = this;

		return instance._getContentBoxSize() * instance.get(RATIO);
	},

	_getRatio: function() {
		var instance = this;
		var min = instance.get(MIN);
		var ratio = (instance.get(VALUE) - min) / (instance.get(MAX) - min);

		return Math.max(ratio, 0);
	},

	_getStep: function() {
		return this.get(RATIO) * 100;
	},

	_renderStatusNode: function() {
		var instance = this;

		instance.get(CONTENT_BOX).append(
			instance.get(STATUS_NODE)
		);
	},

	_renderTextNode: function() {
		var instance = this;

		instance.get(CONTENT_BOX).append(
			instance.get(TEXT_NODE)
		);
	},

	_uiSetLabel: function(val) {
		this.get(TEXT_NODE).html(val);
	},

	_uiSetOrientation: function(val) {
		var instance = this;
		var boundingBox = instance.get(BOUNDING_BOX);
		var horizontal = (val === HORIZONTAL);

		boundingBox.toggleClass(CSS_HORIZONTAL, horizontal);
		boundingBox.toggleClass(CSS_VERTICAL, !horizontal);

		instance._uiSizeTextNode();
	},

	_uiSetValue: function(val) {
		var instance = this;
		var statusNode = instance.get(STATUS_NODE);
		var pixelStep = instance._getPixelStep();

		var styles = {};

		if (instance.get(ORIENTATION) === HORIZONTAL) {
			styles = {
				height: '100%',
				top: AUTO,
				width: pixelStep+PX
			};
		}
		else {
			 styles = {
				height: pixelStep+PX,
				top: toNumber(instance._getContentBoxSize() - pixelStep)+PX,
				width: '100%'
			};
		}

		statusNode.setStyles(styles);
	},

	_uiSizeTextNode: function() {
		var instance = this;
		var contentBox = instance.get(CONTENT_BOX);
		var textNode = instance.get(TEXT_NODE);

		textNode.setStyle(
			LINE_HEIGHT,
			contentBox.getStyle(HEIGHT)
		);
	}
});

A.ProgressBar = ProgressBar;<commit_msg>ProgressBar use parseFloat for better alignment of the aui-progressbar-status<commit_after>var L = A.Lang,
	isNumber = L.isNumber,
	isString = L.isString,

	BLANK = '',
	DOT = '.',
	SPACE = ' ',

	AUTO = 'auto',
	BOUNDING_BOX = 'boundingBox',
	COMPLETE = 'complete',
	CONTENT_BOX = 'contentBox',
	HEIGHT = 'height',
	HORIZONTAL = 'horizontal',
	LABEL = 'label',
	LINE_HEIGHT = 'lineHeight',
	MAX = 'max',
	MIN = 'min',
	ORIENTATION = 'orientation',
	PROGRESS_BAR = 'progress-bar',
	PX = 'px',
	RATIO = 'ratio',
	STATUS = 'status',
	STATUS_NODE = 'statusNode',
	STEP = 'step',
	TEXT = 'text',
	TEXT_NODE = 'textNode',
	VALUE = 'value',
	VERTICAL = 'vertical',
	WIDTH = 'width',

	toNumber = function(v) {
		return parseFloat(v) || 0;
	},

	getCN = A.ClassNameManager.getClassName,

	CSS_HORIZONTAL = getCN(PROGRESS_BAR, HORIZONTAL),
	CSS_STATUS = getCN(PROGRESS_BAR, STATUS),
	CSS_TEXT = getCN(PROGRESS_BAR, TEXT),
	CSS_VERTICAL = getCN(PROGRESS_BAR, VERTICAL),

	TPL_STATUS = '

',
	TPL_TEXT = '

',

	WP = A.Widget.prototype,

	UI_ATTRS = [ LABEL, ORIENTATION, VALUE ],

	_BIND_UI_ATTRS = WP._BIND_UI_ATTRS,
	_SYNC_UI_ATTRS = WP._SYNC_UI_ATTRS,

	BIND_UI_ATTRS = _BIND_UI_ATTRS.concat(UI_ATTRS),
	SYNC_UI_ATTRS = _SYNC_UI_ATTRS.concat(UI_ATTRS);

function ProgressBar(config) {
	ProgressBar.superclass.constructor.apply(this, arguments);
}

A.mix(ProgressBar, {
	NAME: PROGRESS_BAR,

	ATTRS: {
		height: {
			value: 25
		},

		label: {
			value: BLANK
		},

		max: {
			validator: isNumber,
			value: 100
		},

		min: {
			validator: isNumber,
			value: 0
		},

		orientation: {
			value: HORIZONTAL,
			validator: function(val) {
				return isString(val) && (val === HORIZONTAL || val === VERTICAL);
			}
		},

		ratio: {
			getter: '_getRatio',
			readOnly: true
		},

		step: {
			getter: '_getStep',
			readOnly: true
		},

		statusNode: {
			valueFn: function() {
				return A.Node.create(TPL_STATUS);
			}
		},

		textNode: {
			valueFn: function() {
				return A.Node.create(TPL_TEXT);
			}
		},

		value: {
			setter: toNumber,
			validator: function(val) {
				return isNumber(toNumber(val)) && ((val >= this.get(MIN)) && (val <= this.get(MAX)));
			},
			value: 0
		},

		width: {
			value: 250
		}
	},

	HTML_PARSER: {
		label: function(boundingBox) {
			var textNode = boundingBox.one(DOT+CSS_TEXT);

			if (textNode) {
				return textNode.html();
			}
		},
		statusNode: DOT+CSS_STATUS,
		textNode: DOT+CSS_TEXT
	}
});

A.extend(ProgressBar, A.Widget, {
	_BIND_UI_ATTRS: BIND_UI_ATTRS,
	_SYNC_UI_ATTRS: SYNC_UI_ATTRS,

	/*
	* Lifecycle
	*/
	renderUI: function() {
		var instance = this;

		instance._renderStatusNode();
		instance._renderTextNode();
	},

	bindUI: function() {
		var instance = this;

		instance.after('valueChange', A.bind(instance._afterValueChange, instance));
	},

	_afterValueChange: function(event) {
		var instance = this;
		var step = instance.get(STEP);

		if (step >= 100) {
			instance.fire(COMPLETE, {
				progressbar: {
					ratio: instance.get(RATIO),
					step: step,
					value: instance.get(VALUE)
				}
			});
		}
	},

	_getContentBoxSize: function() {
		var instance = this;
		var contentBox = instance.get(CONTENT_BOX);

		return toNumber(
			contentBox.getStyle(
				(this.get(ORIENTATION) === HORIZONTAL) ? WIDTH : HEIGHT
			)
		);
	},

	_getPixelStep: function() {
		var instance = this;

		return instance._getContentBoxSize() * instance.get(RATIO);
	},

	_getRatio: function() {
		var instance = this;
		var min = instance.get(MIN);
		var ratio = (instance.get(VALUE) - min) / (instance.get(MAX) - min);

		return Math.max(ratio, 0);
	},

	_getStep: function() {
		return this.get(RATIO) * 100;
	},

	_renderStatusNode: function() {
		var instance = this;

		instance.get(CONTENT_BOX).append(
			instance.get(STATUS_NODE)
		);
	},

	_renderTextNode: function() {
		var instance = this;

		instance.get(CONTENT_BOX).append(
			instance.get(TEXT_NODE)
		);
	},

	_uiSetLabel: function(val) {
		this.get(TEXT_NODE).html(val);
	},

	_uiSetOrientation: function(val) {
		var instance = this;
		var boundingBox = instance.get(BOUNDING_BOX);
		var horizontal = (val === HORIZONTAL);

		boundingBox.toggleClass(CSS_HORIZONTAL, horizontal);
		boundingBox.toggleClass(CSS_VERTICAL, !horizontal);

		instance._uiSizeTextNode();
	},

	_uiSetValue: function(val) {
		var instance = this;
		var statusNode = instance.get(STATUS_NODE);
		var pixelStep = instance._getPixelStep();

		var styles = {};

		if (instance.get(ORIENTATION) === HORIZONTAL) {
			styles = {
				height: '100%',
				top: AUTO,
				width: pixelStep+PX
			};
		}
		else {
			 styles = {
				height: pixelStep+PX,
				top: toNumber(instance._getContentBoxSize() - pixelStep)+PX,
				width: '100%'
			};
		}

		statusNode.setStyles(styles);
	},

	_uiSizeTextNode: function() {
		var instance = this;
		var contentBox = instance.get(CONTENT_BOX);
		var textNode = instance.get(TEXT_NODE);

		textNode.setStyle(
			LINE_HEIGHT,
			contentBox.getStyle(HEIGHT)
		);
	}
});

A.ProgressBar = ProgressBar;<|endoftext|>


<commit_before>var _ = require('underscore');
var utils = require('./controllerUtils.js');
var events = require('../../events');
var msg = require('./msg');
var model = require('./model');

function passback(id, result, nextFunction){
  // filter out results here
  events.Emitter.emit(id, result);
}

function subRegister(dataModel, method, params, data, ip, id) {
  // Provide some basic sanity checks
  if(!data.email) return passback(id, msg.missingEmail());
  if(utils.invalidEmail(data.email)) return passback(id, msg.badEmail(data.email));
  if(!data.password) return passback(id, msg.missingPwd());
  if(utils.invalidPassword(data.password) ) return passback(id, msg.badPwd());

  dataModel.subscriber.create(data.email, data.password, ip, function(result){
      passback(id, result);
  });
}

function subVerify(dataModel, method, params, data, ip, id) {

  var token = params[1];
  // Ensure a verification token is present and valid
  if(!token) return passback(id, msg.missingVerificationToken());
  if(invalidToken(token)) return passback(id, msg.missingToken());

  dataModel.subscriber.verify(token, function(result){
      passback(id, result);
  });

}

function subReset(dataModel, method, params, data, ip, id) {
  // Ensure email is present and valid
  if(!data.email) return msg.missingEmail();
  //if(badEmail(data.email)) return msg.badEmail(data.email);
  // Return the result of password reset
  dataModel.subscriber.reset(data.email, function(result){
    passback(id, result);
  })
}

function subLogin(dataModel, method, params, data, ip, id) {
  if(!data.email) return msg.missingEmail();
 // if(badEmail(data.email)) return msg.badEmail(data.email);
  dataModel.session.authenticate(data.email, data.password,
  function(result){
    passback(id, result);
  });
}

function subLogout(dataModel, method, params, data, ip, id) {
  return msg.success(); // TODO: implement this..
}

function sessAuthenticate(dataModel, headers, cb) {
  if(headers['x-access-token']) {
    dataModel.session.getByAccessToken(headers['x-access-token'],
    function(result){ cb(result); });
  } else cb(null);
}

module.exports = function(testAdapter) {
  var dataModel;
	if(testAdapter){
		dataModel = model(testAdapter);
  } else {
		dataModel = model();
	}
  return {
    authenticate: _.bind(sessAuthenticate, null, dataModel),
    module: {
      noauth: {
        register: _.bind(subRegister, null, dataModel),
        verify: _.bind(subVerify, null, dataModel),
        reset: _.bind(subRegister, null, dataModel),
        login: _.bind(subLogin, null, dataModel)
      },
      auth: {
        logout: _.bind(subLogout, null, dataModel)
      }
    }
  }
}

<commit_msg>Update controller.js<commit_after>var _ = require('underscore');
var utils = require('./controllerUtils.js');
var events = require('../../events');
var msg = require('./msg');
var model = require('./model');

function passback(id, result, nextFunction){
  // filter out results here
  events.Emitter.emit(id, result);
}

function subRegister(dataModel, method, params, data, ip, id) {
  // Provide some basic sanity checks
  if(!data.email) return passback(id, msg.missingEmail());
  if(utils.invalidEmail(data.email)) return passback(id, msg.badEmail(data.email));
  if(!data.password) return passback(id, msg.missingPwd());
  if(utils.invalidPassword(data.password) ) return passback(id, msg.badPwd());

  dataModel.subscriber.create(data.email, data.password, ip, function(result){
      passback(id, result);
  });
}

function subVerify(dataModel, method, params, data, ip, id) {

  var token = params[1];
  // Ensure a verification token is present and valid
  if(!token) return passback(id, msg.missingVerificationToken());
  if(invalidToken(token)) return passback(id, msg.badVerificationToken());

  dataModel.subscriber.verify(token, function(result){
      passback(id, result);
  });

}

function subReset(dataModel, method, params, data, ip, id) {
  // Ensure email is present and valid
  if(!data.email) return msg.missingEmail();
  //if(badEmail(data.email)) return msg.badEmail(data.email);
  // Return the result of password reset
  dataModel.subscriber.reset(data.email, function(result){
    passback(id, result);
  })
}

function subLogin(dataModel, method, params, data, ip, id) {
  if(!data.email) return msg.missingEmail();
 // if(badEmail(data.email)) return msg.badEmail(data.email);
  dataModel.session.authenticate(data.email, data.password,
  function(result){
    passback(id, result);
  });
}

function subLogout(dataModel, method, params, data, ip, id) {
  return msg.success(); // TODO: implement this..
}

function sessAuthenticate(dataModel, headers, cb) {
  if(headers['x-access-token']) {
    dataModel.session.getByAccessToken(headers['x-access-token'],
    function(result){ cb(result); });
  } else cb(null);
}

module.exports = function(testAdapter) {
  var dataModel;
	if(testAdapter){
		dataModel = model(testAdapter);
  } else {
		dataModel = model();
	}
  return {
    authenticate: _.bind(sessAuthenticate, null, dataModel),
    module: {
      noauth: {
        register: _.bind(subRegister, null, dataModel),
        verify: _.bind(subVerify, null, dataModel),
        reset: _.bind(subRegister, null, dataModel),
        login: _.bind(subLogin, null, dataModel)
      },
      auth: {
        logout: _.bind(subLogout, null, dataModel)
      }
    }
  }
}

<|endoftext|>


<commit_before>/// <binding />
'use strict';

var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var del = require('del');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');

require('require-dir')('./gulp-tasks');

gulp.paths = {
    webroot: './wwwroot/',
    temp: './wwwroot/temp/',
    css: 'css/',
    js: 'js/',
    fonts: 'fonts/',
    vendors: 'vendors/'
};

//gulp.paths.js = gulp.paths.webroot + 'js/**/*.js';
//gulp.paths.css = gulp.paths.webroot + 'css/**/*.css';

//gulp.paths.minJs = gulp.paths.webroot + 'js/**/*.min.js';
//gulp.paths.minCss = gulp.paths.webroot + 'css/**/*.min.css';

//gulp.paths.jsDest = gulp.paths.webroot + 'js/';
//gulp.paths.cssDest = gulp.paths.webroot + 'css/';

//gulp.paths.jsVendorDest = gulp.paths.webroot + 'js/vendor/';
//gulp.paths.cssVendorDest = gulp.paths.webroot + 'css/vendor/';

gulp.paths.concatJsDest = gulp.paths.webroot + 'js/site.min.js';
gulp.paths.concatCssDest = gulp.paths.webroot + 'css/site.min.css';

gulp.task('build:admin', function () {
    return gulp.src('./assets/scss/admin/admin.scss')
        .pipe(sass())
        .pipe(autoprefixer())
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.css))
        .pipe(cssmin())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.css));
    //.pipe(browserSync.stream());
});

gulp.task('build:admin-scripts', function () {
    return gulp.src('./assets/js/admin/*.js')
        .pipe(gulp.dest(gulp.paths.temp + gulp.paths.js))
        .pipe(concat('admin.js'))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.js))
        .pipe(uglify())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.js));
});

gulp.task('build:site', function () {
    return gulp.src('./assets/scss/site/site.scss')
        .pipe(sass())
        .pipe(autoprefixer())
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.css))
        .pipe(cssmin())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.css));
    //.pipe(browserSync.stream());
});

gulp.task('build:site-scripts', function () {
    return gulp.src('./assets/js/site/*.js')
        .pipe(gulp.dest(gulp.paths.temp + gulp.paths.js))
        .pipe(concat('site.js'))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.js))
        .pipe(uglify())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.js));
});

gulp.task('copy:images', function () {
    return gulp.src('./assets/img/**/*')
        .pipe(gulp.dest(gulp.paths.webroot + '/img'));
});

gulp.task('clean:dist', function () {
    return del(gulp.paths.webroot + './*');
});

gulp.task('default', function (callback) {
    runSequence(
        'clean:dist', 'copy:images',
        'build:admin', 'build:admin-scripts',
        'build:site', 'build:site-scripts',
        'build:vendors',
        'clean:min-min',
        callback);
});
<commit_msg>Added exclusion of UploadedFiles folder to gulpfile<commit_after>/// <binding />
'use strict';

var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var del = require('del');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');

require('require-dir')('./gulp-tasks');

gulp.paths = {
    webroot: './wwwroot/',
    temp: './wwwroot/temp/',
    css: 'css/',
    js: 'js/',
    img: 'img/',
    uploadedFiles: 'UploadedFiles/',
    fonts: 'fonts/',
    vendors: 'vendors/'
};

//gulp.paths.js = gulp.paths.webroot + 'js/**/*.js';
//gulp.paths.css = gulp.paths.webroot + 'css/**/*.css';

//gulp.paths.minJs = gulp.paths.webroot + 'js/**/*.min.js';
//gulp.paths.minCss = gulp.paths.webroot + 'css/**/*.min.css';

//gulp.paths.jsDest = gulp.paths.webroot + 'js/';
//gulp.paths.cssDest = gulp.paths.webroot + 'css/';

//gulp.paths.jsVendorDest = gulp.paths.webroot + 'js/vendor/';
//gulp.paths.cssVendorDest = gulp.paths.webroot + 'css/vendor/';

gulp.paths.concatJsDest = gulp.paths.webroot + 'js/site.min.js';
gulp.paths.concatCssDest = gulp.paths.webroot + 'css/site.min.css';

gulp.task('build:admin', function () {
    return gulp.src('./assets/scss/admin/admin.scss')
        .pipe(sass())
        .pipe(autoprefixer())
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.css))
        .pipe(cssmin())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.css));
    //.pipe(browserSync.stream());
});

gulp.task('build:admin-scripts', function () {
    return gulp.src('./assets/js/admin/*.js')
        .pipe(gulp.dest(gulp.paths.temp + gulp.paths.js))
        .pipe(concat('admin.js'))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.js))
        .pipe(uglify())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.js));
});

gulp.task('build:site', function () {
    return gulp.src('./assets/scss/site/site.scss')
        .pipe(sass())
        .pipe(autoprefixer())
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.css))
        .pipe(cssmin())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.css));
    //.pipe(browserSync.stream());
});

gulp.task('build:site-scripts', function () {
    return gulp.src('./assets/js/site/*.js')
        .pipe(gulp.dest(gulp.paths.temp + gulp.paths.js))
        .pipe(concat('site.js'))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.js))
        .pipe(uglify())
        .pipe(rename({ suffix: '.min' }))
        .pipe(gulp.dest(gulp.paths.webroot + gulp.paths.js));
});

gulp.task('copy:images', function () {
    return gulp.src('./assets/img/**/*')
        .pipe(gulp.dest(gulp.paths.webroot + '/img'));
});

gulp.task('clean:dist', function () {
    return del([
        gulp.paths.webroot + gulp.paths.css + '**',
        gulp.paths.webroot + gulp.paths.img + '**',
        gulp.paths.webroot + gulp.paths.js + '**',
        '!' + gulp.paths.webroot + gulp.paths.uploadedFiles
    ]);
});

gulp.task('default', function (callback) {
    runSequence(
        'clean:dist', 'copy:images',
        'build:admin', 'build:admin-scripts',
        'build:site', 'build:site-scripts',
        'build:vendors',
        'clean:min-min',
        callback);
});
<|endoftext|>


<commit_before>var inherits = require('inherits');
var EventEmitter = require('wolfy87-eventemitter');

/**
 * The Response is used as the `this` value for route functions. It hosts
 * methods for manipulating the server response and application state.
 */
function Response(request, router) {
  this.request = request;
  this.router = router;
  this.state = router.state;

  // FIXME: We shouldn't have to do this. Should `unhandled()` be on the response? Or should we have some other way to catch it?
  request.on('error', function(err) {
    this.emit('error', err);
  }.bind(this));
}

inherits(Response, EventEmitter);

//
//
// The main methods for manipulating the application state.
//
//

Response.prototype.setState = function(state) {
  this.router.setState(state);
  this.state = this.router.state;
  return this;
};

Response.prototype.setView = function(view) {
  this.router.setView(view);
  this.view = this.router.view;
  return this;
};

//
//
// Ending
//
//

/**
 * Indicates that a response was ended.
 */
Response.prototype.ended = false;
Response.prototype.initialEnded = false;

/**
 * Call to indicate that router is in the "initial" state—the state that the
 * server will send and the browser app will begin in.
 */
Response.prototype.endInitial = function() {
  if (this.initialEnded) {
    return;
  }
  this.initialEnded = true;
  this.emit('initialReady');
  if (this.request.initialOnly) {
    this.end();
  }
  return this.ended;
};

Response.prototype.end = function() {
  if (!this.ended) {
    this.endInitial();
    this.ended = true;
    this.emit('end');
  }
};

//
//
// Metadata methods.
//
//

/**
 * Indicate that no view was found for the corresponding request. This has no
 * effect in the browser, but causes a 404 response to be sent on the server.
 * Note that this is different from `unhandled` as it indicates that the UI has
 * been updated.
 */
Response.prototype.notFound = function() {
  // TODO: Should this work as a getter too? Or should we make it chainable?
  this._notFound = true;
};

Response.prototype.doctype = function() {
  return ''; // TODO: THIS!
};

Response.prototype.contentType = function() {
  return ''; // TODO: THIS, ALSO!
};

//
//
// Rendering shortcuts.
//
//

/**
 * A function decorator that creates a new view from the provided one and the
 * (optional) remaining arguments.
 *
 * @param {function} fn The function whose arguments to transform.
 */
function renderer(fn) {
  return function(view) {
    if (arguments.length > 1) {
      var oldView = view;
      var args = Array.prototype.slice.call(arguments, 1);
      view = function() {
        return oldView.apply(this, args);
      };
    }
    return fn.call(this, view);
  };
}

//
// Shortcut methods for rendering a view with props and (optionally) ending the
// request.
//

/**
 * Render the provided view and end the request.
 */
Response.prototype.render = renderer(function(view) {
  this.setView(view);
  this.end();
});

/**
 * Render the provided view and mark the current state as the initial one.
 */
Response.prototype.renderInitial = renderer(function(view) {
  this.setView(view);
  this.request.endInitial();
  return this.ended;
});

/**
 * Render the provided view.
 */
Response.prototype.renderIntermediate = renderer(function(view) {
  this.setView(view);
});

Response.prototype.renderDocumentToString = function() {
  var engine = this.router.constructor.engine;
  var markup = engine.renderToString(router);
  var doctype = this.doctype(); // Guess from contentType if not present.
  return (doctype || '') + markup;
};

module.exports = Response;
<commit_msg>Fix variable reference<commit_after>var inherits = require('inherits');
var EventEmitter = require('wolfy87-eventemitter');

/**
 * The Response is used as the `this` value for route functions. It hosts
 * methods for manipulating the server response and application state.
 */
function Response(request, router) {
  this.request = request;
  this.router = router;
  this.state = router.state;

  // FIXME: We shouldn't have to do this. Should `unhandled()` be on the response? Or should we have some other way to catch it?
  request.on('error', function(err) {
    this.emit('error', err);
  }.bind(this));
}

inherits(Response, EventEmitter);

//
//
// The main methods for manipulating the application state.
//
//

Response.prototype.setState = function(state) {
  this.router.setState(state);
  this.state = this.router.state;
  return this;
};

Response.prototype.setView = function(view) {
  this.router.setView(view);
  this.view = this.router.view;
  return this;
};

//
//
// Ending
//
//

/**
 * Indicates that a response was ended.
 */
Response.prototype.ended = false;
Response.prototype.initialEnded = false;

/**
 * Call to indicate that router is in the "initial" state—the state that the
 * server will send and the browser app will begin in.
 */
Response.prototype.endInitial = function() {
  if (this.initialEnded) {
    return;
  }
  this.initialEnded = true;
  this.emit('initialReady');
  if (this.request.initialOnly) {
    this.end();
  }
  return this.ended;
};

Response.prototype.end = function() {
  if (!this.ended) {
    this.endInitial();
    this.ended = true;
    this.emit('end');
  }
};

//
//
// Metadata methods.
//
//

/**
 * Indicate that no view was found for the corresponding request. This has no
 * effect in the browser, but causes a 404 response to be sent on the server.
 * Note that this is different from `unhandled` as it indicates that the UI has
 * been updated.
 */
Response.prototype.notFound = function() {
  // TODO: Should this work as a getter too? Or should we make it chainable?
  this._notFound = true;
};

Response.prototype.doctype = function() {
  return ''; // TODO: THIS!
};

Response.prototype.contentType = function() {
  return ''; // TODO: THIS, ALSO!
};

//
//
// Rendering shortcuts.
//
//

/**
 * A function decorator that creates a new view from the provided one and the
 * (optional) remaining arguments.
 *
 * @param {function} fn The function whose arguments to transform.
 */
function renderer(fn) {
  return function(view) {
    if (arguments.length > 1) {
      var oldView = view;
      var args = Array.prototype.slice.call(arguments, 1);
      view = function() {
        return oldView.apply(this, args);
      };
    }
    return fn.call(this, view);
  };
}

//
// Shortcut methods for rendering a view with props and (optionally) ending the
// request.
//

/**
 * Render the provided view and end the request.
 */
Response.prototype.render = renderer(function(view) {
  this.setView(view);
  this.end();
});

/**
 * Render the provided view and mark the current state as the initial one.
 */
Response.prototype.renderInitial = renderer(function(view) {
  this.setView(view);
  this.request.endInitial();
  return this.ended;
});

/**
 * Render the provided view.
 */
Response.prototype.renderIntermediate = renderer(function(view) {
  this.setView(view);
});

Response.prototype.renderDocumentToString = function() {
  var engine = this.router.constructor.engine;
  var markup = engine.renderToString(this.router);
  var doctype = this.doctype(); // Guess from contentType if not present.
  return (doctype || '') + markup;
};

module.exports = Response;
<|endoftext|>