<commit_before>var timesViewed = 0;
var timesSelected = 0;
var totalClicks = 0;
var selectedProduct = 0;
var itemsForSale = [];
var previouslyDisplayed = [];
var chartSelected = [];
var chartViewed = [];
var myStorage = [];
var leftRandom = 0;
var centerRandom = 0;
var rightRandom = 0;
var resultsToggle = 2;
var chartToggle = 2;
var left = document.getElementById('left');
var right = document.getElementById('right');
var center = document.getElementById('center');
var selection = document.getElementById('selection');
var results = document.getElementById('results');
var productNames = ['bag', 'banana', 'bathroom', 'boots', 'breakfast', 'bubblegum', 'chair', 'cthulhu', 'dog-duck', 'dragon', 'pen', 'pet-sweep', 'scissors', 'shark', 'sweep', 'tauntaun', 'usb', 'unicorn', 'water-can', 'wine-glass'];

// ******************************* constructor ***********************************************
function Product(productName) {
  this.productName = productName;
  this.path = 'img/' + productName + '.jpg';
  this.timesViewed = 0;
  this.timesSelected = 0;
  itemsForSale.push(this);
}
// **************************** create 3 random numbers that don't repeat each other or previous groups *****
function randomizeNumber() {
  leftRandom = Math.floor(Math.random() * 20);
  while (previouslyDisplayed.indexOf(leftRandom) > -1) {
    leftRandom = Math.floor(Math.random() * 20);
  }
  previouslyDisplayed.push(leftRandom);
  centerRandom = Math.floor(Math.random() * 20);
  while (previouslyDisplayed.indexOf(centerRandom) > -1) {
    centerRandom = Math.floor(Math.random() * 20);
  }
  previouslyDisplayed.push(centerRandom);
  rightRandom = Math.floor(Math.random() * 20);
  while (previouslyDisplayed.indexOf(rightRandom) > -1) {
    rightRandom = Math.floor(Math.random() * 20);
  }
  previouslyDisplayed.push(rightRandom);
}
// ***************************clear first 12 items in previouslyDisplayed array *************
function cleanUpArray() {
  if (previouslyDisplayed.length > 15) {
    for (var i= 0; i < 12; i++) {
      previouslyDisplayed.shift();
    }
  }
}
// ************************ three  random images onto screen **************
function putImageOnPage() {

  left.src = itemsForSale[leftRandom].path;
  itemsForSale[leftRandom].timesViewed += 1;
  center.src = itemsForSale[centerRandom].path;
  itemsForSale[centerRandom].timesViewed += 1;
  right.src = itemsForSale[rightRandom].path;
  itemsForSale[rightRandom].timesViewed += 1;
}
// ***************************** tally selected pics ***********************
function tallySelectedPic() {
  if (selectedProduct === 'left') {
    itemsForSale[leftRandom].timesSelected += 1;
  }
  if (selectedProduct === 'center') {
    itemsForSale[centerRandom].timesSelected += 1;
  }
  if (selectedProduct === 'right') {
    itemsForSale[rightRandom].timesSelected += 1;
  }
}
//********************************** Hide the list **********************
function hideList() {
  document.getElementById('results').hidden = true;
  document.getElementById('chart').hidden = true;
}
// ************************* Make a finished list ************************
function makeFinalList() {
  for (var i = 0; i < itemsForSale.length; i++) {
    var finalList = document.getElementById('piclist');
    var liEl = document.createElement('li');
    liEl.textContent = 'The ' + itemsForSale[i].productName + ' was selected: ' + itemsForSale[i].timesSelected + ' out of ' + itemsForSale[i].timesViewed + ' times being viewed.'
    finalList.appendChild(liEl);
  }

}
// ****************************** build data arrays for chart **********
function insertChartData() {
  for (var i = 0; i < itemsForSale.length; i++) {
    chartSelected[i] = itemsForSale[i].timesSelected;
    chartViewed[i] = itemsForSale[i].timesViewed;
  }
}
 // ******************** Event Handler ********************************
function handleSelectionSubmit(event) {
  event.preventDefault();
  totalClicks += 1;
  selectedProduct = event.target.id;
  if (selectedProduct === 'selection') {
    return alert('Sorry, that was not a valid selection.')
  }
  tallySelectedPic();
  localStorage.myStorage = JSON.stringify(itemsForSale);
  checkTotalClicks();
  cleanUpArray();
  randomizeNumber();
  putImageOnPage();
}
 // ************************** Show Hide Handler **************************
function showHideHandler(event) {
  event.preventDefault();
  var hideOrShow = event.target.id;
  if (hideOrShow === 'choicebar') {
    return alert('Sorry, that was not a valid choice.')
  }
  if (hideOrShow === 'results') {
    resultsToggle +=1;
    toggleResults();
  }
  if (hideOrShow === 'chart') {
    chartToggle += 1;
    toggleChart();
  }
}
// ******************** toggle the list and chart ***********************
function toggleResults() {
  var checkup = resultsToggle % 2;
  document.getElementById('piclist').hidden = true;
  if (checkup === 0) {
    document.getElementById('piclist').hidden = false;
  }
}
function toggleChart() {
  var checkdown = chartToggle % 2;
  console.log(checkdown);

  document.getElementById('chartcontainer').hidden = true;
  if (checkdown === 0) {
    document.getElementById('chartcontainer').hidden = false;
  }
}
// *********************** check the total clicks and do stop actions ****
function checkTotalClicks() {
  if (totalClicks > 24) {
    selection.removeEventListener("click", handleSelectionSubmit);
    document.getElementById('results').hidden = false;
    document.getElementById('chart').hidden = false;
    choicebar.addEventListener("click", showHideHandler);
    insertChartData();
    makeFinalList();
    makeChart();

  }
}
//********************* instances **************************************
function createArray () {
  for (var i = 0; i < productNames.length; i++) {
    new Product(productNames[i])
    if (itemsForSale[i].productName === 'sweep') {
      itemsForSale[i].path = 'img/sweep.png';
    }
    if (itemsForSale[i].productName === 'usb') {
      itemsForSale[i].path = 'img/usb.gif';
    }
  }
}
// ********************************** starting chart trial ********************
function makeChart() {
  var ctx = document.getElementById("myChart").getContext("2d");
  var myChart = new Chart(ctx, {
    type: 'polarArea',
    data: {
      labels: productNames,
      datasets: [{
        label: 'Times Viewed',
        data: chartViewed,
        backgroundColor: 'rgba(11, 54, 124, 0.6)'
      }, {
        label: 'Times Selected',
        data: chartSelected,
        backgroundColor: 'rgba(29, 147, 13, 0.6)'
      }]
    }
  });
}

//**************************Local Storage***********************
if (!localStorage.myStorage) {
  createArray();
  console.log('no local');
} else {
  var tempDataHolder = localStorage.getItem('myStorage');
  var parseData = JSON.parse(tempDataHolder);
  itemsForSale = parseData;
}

//***************************************************************
// ************************** page load functions ***************************
hideList();
randomizeNumber();
putImageOnPage();
// ********************* Event Listener *********************************
selection.addEventListener("click", handleSelectionSubmit);
<commit_msg>added percentage<commit_after>var timesViewed = 0;
var timesSelected = 0;
var totalClicks = 0;
var selectedProduct = 0;
var itemsForSale = [];
var previouslyDisplayed = [];
var chartSelected = [];
var chartViewed = [];
var percentageSelected = [];
var myStorage = [];
var leftRandom = 0;
var centerRandom = 0;
var rightRandom = 0;
var resultsToggle = 2;
var chartToggle = 2;
var left = document.getElementById('left');
var right = document.getElementById('right');
var center = document.getElementById('center');
var selection = document.getElementById('selection');
var results = document.getElementById('results');
var productNames = ['bag', 'banana', 'bathroom', 'boots', 'breakfast', 'bubblegum', 'chair', 'cthulhu', 'dog-duck', 'dragon', 'pen', 'pet-sweep', 'scissors', 'shark', 'sweep', 'tauntaun', 'usb', 'unicorn', 'water-can', 'wine-glass'];

// ******************************* constructor ***********************************************
function Product(productName) {
  this.productName = productName;
  this.path = 'img/' + productName + '.jpg';
  this.timesViewed = 0;
  this.timesSelected = 0;
  itemsForSale.push(this);
}
// **************************** create 3 random numbers that don't repeat each other or previous groups *****
function randomizeNumber() {
  leftRandom = Math.floor(Math.random() * 20);
  while (previouslyDisplayed.indexOf(leftRandom) > -1) {
    leftRandom = Math.floor(Math.random() * 20);
  }
  previouslyDisplayed.push(leftRandom);
  centerRandom = Math.floor(Math.random() * 20);
  while (previouslyDisplayed.indexOf(centerRandom) > -1) {
    centerRandom = Math.floor(Math.random() * 20);
  }
  previouslyDisplayed.push(centerRandom);
  rightRandom = Math.floor(Math.random() * 20);
  while (previouslyDisplayed.indexOf(rightRandom) > -1) {
    rightRandom = Math.floor(Math.random() * 20);
  }
  previouslyDisplayed.push(rightRandom);
}
// ***************************clear first 12 items in previouslyDisplayed array *************
function cleanUpArray() {
  if (previouslyDisplayed.length > 15) {
    for (var i= 0; i < 12; i++) {
      previouslyDisplayed.shift();
    }
  }
}
// ************************ three  random images onto screen **************
function putImageOnPage() {

  left.src = itemsForSale[leftRandom].path;
  itemsForSale[leftRandom].timesViewed += 1;
  center.src = itemsForSale[centerRandom].path;
  itemsForSale[centerRandom].timesViewed += 1;
  right.src = itemsForSale[rightRandom].path;
  itemsForSale[rightRandom].timesViewed += 1;
}
// ***************************** tally selected pics ***********************
function tallySelectedPic() {
  if (selectedProduct === 'left') {
    itemsForSale[leftRandom].timesSelected += 1;
  }
  if (selectedProduct === 'center') {
    itemsForSale[centerRandom].timesSelected += 1;
  }
  if (selectedProduct === 'right') {
    itemsForSale[rightRandom].timesSelected += 1;
  }
}
//********************************** Hide the list **********************
function hideList() {
  document.getElementById('results').hidden = true;
  document.getElementById('chart').hidden = true;
}
// ************************* Make a finished list ************************
function makeFinalList() {
  for (var i = 0; i < itemsForSale.length; i++) {
    var finalList = document.getElementById('piclist');
    var liEl = document.createElement('li');
    liEl.textContent = 'The ' + itemsForSale[i].productName + ' was selected: ' + itemsForSale[i].timesSelected + ' out of ' + itemsForSale[i].timesViewed + ' times being viewed. It was picked ' + percentageSelected[i] + '% of the time.'
    finalList.appendChild(liEl);
  }

}
// ****************************** build data arrays for chart **********
function insertChartData() {
  for (var i = 0; i < itemsForSale.length; i++) {
    chartSelected[i] = itemsForSale[i].timesSelected;
    chartViewed[i] = itemsForSale[i].timesViewed;
    percentageSelected[i] = Math.round(itemsForSale[i].timesSelected/itemsForSale[i].timesViewed * 100) / 100;
  }
}
 // ******************** Event Handler ********************************
function handleSelectionSubmit(event) {
  event.preventDefault();
  totalClicks += 1;
  selectedProduct = event.target.id;
  if (selectedProduct === 'selection') {
    return alert('Sorry, that was not a valid selection.')
  }
  tallySelectedPic();
  localStorage.myStorage = JSON.stringify(itemsForSale);
  checkTotalClicks();
  cleanUpArray();
  randomizeNumber();
  putImageOnPage();
}
 // ************************** Show Hide Handler **************************
function showHideHandler(event) {
  event.preventDefault();
  var hideOrShow = event.target.id;
  if (hideOrShow === 'choicebar') {
    return alert('Sorry, that was not a valid choice.')
  }
  if (hideOrShow === 'results') {
    resultsToggle +=1;
    toggleResults();
  }
  if (hideOrShow === 'chart') {
    chartToggle += 1;
    toggleChart();
  }
}
// ******************** toggle the list and chart ***********************
function toggleResults() {
  var checkup = resultsToggle % 2;
  document.getElementById('piclist').hidden = true;
  if (checkup === 0) {
    document.getElementById('piclist').hidden = false;
  }
}
function toggleChart() {
  var checkdown = chartToggle % 2;
  console.log(checkdown);

  document.getElementById('chartcontainer').hidden = true;
  if (checkdown === 0) {
    document.getElementById('chartcontainer').hidden = false;
  }
}
// *********************** check the total clicks and do stop actions ****
function checkTotalClicks() {
  if (totalClicks > 24) {
    selection.removeEventListener("click", handleSelectionSubmit);
    document.getElementById('results').hidden = false;
    document.getElementById('chart').hidden = false;
    choicebar.addEventListener("click", showHideHandler);
    insertChartData();
    makeFinalList();
    makeChart();

  }
}
//********************* instances **************************************
function createArray () {
  for (var i = 0; i < productNames.length; i++) {
    new Product(productNames[i])
    if (itemsForSale[i].productName === 'sweep') {
      itemsForSale[i].path = 'img/sweep.png';
    }
    if (itemsForSale[i].productName === 'usb') {
      itemsForSale[i].path = 'img/usb.gif';
    }
  }
}
// ********************************** starting chart trial ********************
function makeChart() {
  var ctx = document.getElementById("myChart").getContext("2d");
  var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: productNames,
      datasets: [{
        label: 'Times Viewed',
        data: chartViewed,
        backgroundColor: 'rgba(11, 54, 124, 0.6)'
      }, {
        label: 'Times Selected',
        data: chartSelected,
        backgroundColor: 'rgba(29, 147, 13, 0.6)'
      }, {
        label: 'Percent Picked',
        data: percentageSelected,
        backgroundColor: 'rgba(66, 241, 244, 0.6)'
      }]
    }
  });
}

//**************************Local Storage***********************
if (!localStorage.myStorage) {
  createArray();
  console.log('no local');
} else {
  var tempDataHolder = localStorage.getItem('myStorage');
  var parseData = JSON.parse(tempDataHolder);
  itemsForSale = parseData;
}

//***************************************************************
// ************************** page load functions ***************************
hideList();
randomizeNumber();
putImageOnPage();
// ********************* Event Listener *********************************
selection.addEventListener("click", handleSelectionSubmit);
<|endoftext|>


<commit_before>var combo   = require('combohandler'),
    express = require('express'),
    exphbs  = require('express3-handlebars'),
    state   = require('express-state'),
	ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn,
	ConnectRoles = require('connect-roles'),

    config     = require('./config'),
    helpers    = require('./lib/helpers'),
    middleware = require('./middleware'),
    routes     = require('./routes'),
    userModel  = require('./models/userModel.js'),
    AuthController = require('./models/authController.js'),

    app = express();
// Required Config additions of passport and flash
    var flash = require("connect-flash");
    var passport = require("passport");
	var Sequelize = require('sequelize');
	var PassportLocalStrategy = require('passport-local').Strategy;

// -- Configure ----------------------------------------------------------------

app.set('name', 'Charles-Fiona Wedding');
app.set('env', config.env);
app.set('port', config.port);
app.set('views', config.dirs.views);
app.set('view engine', 'hbs');
app.set('state namespace', 'YUI.Env.LE');
app.enable('strict routing');

app.engine('hbs', exphbs({
    defaultLayout: 'main',
    extname      : '.hbs',
    helpers      : helpers,
    layoutsDir   : config.dirs.layouts,
    partialsDir  : config.dirs.partials
}));

// -- Roles middleware -------------------------------------------------------------------
var user = new ConnectRoles({
  failureHandler: function (req, res, action) {
    // optional function to customise code that runs when
    // user fails authorisation
    var accept = req.headers.accept || '';
    res.status(403);
    if (~accept.indexOf('html')) {
      res.render('access-denied', {action: action});
    } else {
      res.send('Access Denied - You don\'t have permission to: ' + action);
    }
  }
});

//anonymous users can only access the home page
////returning false stops any more rules from being
////considered
user.use(function (req, action) {
  if (!req.isAuthenticated()) return action === 'access home page';
})

//moderator users can access private page, but
////they might not be the only ones so we don't return
////false if the user isn't a moderator
user.use('access private page', function (req) {
  if (req.user.role === 'moderator') {
    return true;
  }
})

//admin users can access all pages
user.use(function (req) {
  if (req.user.role === 'admin') {
    return true;
  }
});

// -- Locals -------------------------------------------------------------------

app.expose(config.yui.config, 'window.YUI_config');

app.locals({
    title   : 'Charles & Fiona',
    appTitle: 'C&L Wedding',

    version    : config.version,
    yui_version: config.yui.version,

    nav: [
        {id: 'wedding',   url: '/wedding/',   label: 'Wedding'},
        {id: 'logistics', url: '/logistics/', label: 'Logistics'},
        {id: 'registry',  url: '/registry/',  label: 'Registry'},
        {id: 'rsvp',      url: '/rsvp/',      label: 'RSVP'},
        {id: 'party_itinerary',      url: '/party_itinerary/',      label: 'Itinerary'},
        {id: 'logout',      url: '/logout/',      label: 'Logout'}

    ],

    subnav: {
        logistics: [
            {id: 'logistics', url: '/logistics/',         label: 'Logistics'},
            {id: 'hotels',    url: '/logistics/hotels/',  label: 'Hotels'},
            {id: 'outings',   url: '/logistics/outings/', label: 'Outings'},
            {id: 'ride_share',   url: '/logistics/ride_share/', label: 'Ride Share'}
        ]
    },

    yui_module: 'le-main',

    pictos : config.pictos,
    typekit: config.typekit,

    isDevelopment: config.isDevelopment,
    isProduction : config.isProduction,

    min: config.isProduction ? '-min' : ''
});

// -- Middleware ---------------------------------------------------------------

if (config.isDevelopment) {
    app.use(express.logger('tiny'));
}

app.use(express.compress());
app.use(express.favicon(config.dirs.pub + '/favicon.ico'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(flash());
app.use(express.cookieSession(config.session));
app.use(express.session({ secret: 'super secret', cookie: { maxAge: 60000 }}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.csrf());
app.use(middleware.csrfToken);
app.use(middleware.invitation);
app.use(middleware.pjax('bare'));
app.use(middleware.checkDate);
app.use(app.router);
app.use(middleware.slash());
app.use(express.static(config.dirs.pub));
app.use(middleware.notfound);
//app.use(authentication);
//app.use(user.middleware());

if (config.isDevelopment) {
    app.use(express.errorHandler({
        dumpExceptions: true,
        showStack     : true
    }));
} else {
    app.use(middleware.error);
}

// -- Routes -------------------------------------------------------------------

//app.get('/', routes.render('home'));
app.get('/', routes.render('landing_page'));

//new landing page for login.
app.get('/welcome/', routes.render('landing_page'));

app.get('/auth/login/failure', routes.render('/login'));
app.get('/auth/login/success', routes.render('/wedding/'));

app.get('/admin/',
  ensureLoggedIn('/login'),
  user.can('access admin page'),
  function(req, res) {
    res.render('views/pages/admin/admin_main', { user: req.user });
    console.log(req.user);
  });

app.get('/home/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('home', { user: req.user });
    console.log(req.user);
  });

app.get('/registry/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('registry', { user: req.user });
    console.log(req.user);
  });

  app.get('/logistics/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('logistics', { user: req.user });
    console.log(req.user);
  });

app.get('/logistics/hotels/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('logistics/hotels', { user: req.user });
    console.log(req.user);
  });

app.get('/logistics/outings/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('logistics/outings', { user: req.user });
    console.log(req.user);
  });

app.get('/logistics/ride_share/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('logistics/ride_share', { user: req.user });
    console.log(req.user);
  });

app.get('/wedding/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('wedding', { user: req.user });
    console.log(req.user);
  });

app.get('/party_itinerary/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('party_itinerary', { user: req.user });
    console.log(req.user);
  });

//basic login page.
app.get('/login',
  function(req, res) {
    res.redirect('/welcome/');
  });

app.get('/logout',
  function(req, res) {
    req.logout();
    res.redirect('/');
  });

// route to authenticate the user
app.post('/login', passport.authenticate('local', {
  successRedirect: '/wedding/',
  failureRedirect: '/login/'
}));

app.get('/rsvp/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('rsvp.pub', { user: req.user });
    console.log(req.user);
  });

app.get('/rsvp/brunch/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('rsvp.brunch', { user: req.user });
    console.log(req.user);
  });

//app.get( '/rsvp/',                       routes.rsvp.pub, routes.rsvp.edit);
app.post('/rsvp/',                       routes.rsvp.resend);
//app.get( '/rsvp/brunch/',                routes.rsvp.brunch);
app.post('/rsvp/brunch/',                routes.rsvp.brunch);
app.get( '/rsvp/brunch/:invitation_key', routes.rsvp.login);
app.get( '/rsvp/:invitation_key',        routes.rsvp.login);

app.all( '/invitations/:invitation/*',       middleware.auth.ensureInvitation);
app.get( '/invitations/:invitation/',        routes.invitations.read);
app.put( '/invitations/:invitation/',        routes.invitations.update);
app.get( '/invitations/:invitation/guests',  routes.invitations.readGuests);
app.post('/invitations/:invitation/confirm', routes.invitations.confirm);

app.all('/guests/:guest/', middleware.auth.ensureGuest);
app.get('/guests/:guest/', routes.guests.read);
app.put('/guests/:guest/', routes.guests.update);

app.get('/combo/:version', [
    combo.combine({rootPath: config.dirs.pub}),
    combo.respond
]);

module.exports = app;
<commit_msg>working<commit_after>var combo   = require('combohandler'),
    express = require('express'),
    exphbs  = require('express3-handlebars'),
    state   = require('express-state'),
	ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn,
	ConnectRoles = require('connect-roles'),

    config     = require('./config'),
    helpers    = require('./lib/helpers'),
    middleware = require('./middleware'),
    routes     = require('./routes'),
    userModel  = require('./models/userModel.js'),
    AuthController = require('./models/authController.js'),

    app = express();
// Required Config additions of passport and flash
    var flash = require("connect-flash");
    var passport = require("passport");
	var Sequelize = require('sequelize');
	var PassportLocalStrategy = require('passport-local').Strategy;

// -- Configure ----------------------------------------------------------------

app.set('name', 'Charles-Fiona Wedding');
app.set('env', config.env);
app.set('port', config.port);
app.set('views', config.dirs.views);
app.set('view engine', 'hbs');
app.set('state namespace', 'YUI.Env.LE');
app.enable('strict routing');

app.engine('hbs', exphbs({
    defaultLayout: 'main',
    extname      : '.hbs',
    helpers      : helpers,
    layoutsDir   : config.dirs.layouts,
    partialsDir  : config.dirs.partials
}));

// -- Roles middleware -------------------------------------------------------------------
var user = new ConnectRoles({
  failureHandler: function (req, res, action) {
    // optional function to customise code that runs when
    // user fails authorisation
    var accept = req.headers.accept || '';
    res.status(403);
    if (~accept.indexOf('html')) {
      res.render('access-denied', {action: action});
    } else {
      res.send('Access Denied - You don\'t have permission to: ' + action);
    }
  }
});

//anonymous users can only access the home page
////returning false stops any more rules from being
////considered
user.use(function (req, action) {
  if (!req.isAuthenticated()) return action === 'access home page';
})

//moderator users can access private page, but
////they might not be the only ones so we don't return
////false if the user isn't a moderator
user.use('access private page', function (req) {
  if (req.user.role === 'moderator') {
    return true;
  }
})

//admin users can access all pages
user.use(function (req) {
  if (user.groups === 'admin') {
    return true;
  }
});

// -- Locals -------------------------------------------------------------------

app.expose(config.yui.config, 'window.YUI_config');

app.locals({
    title   : 'Charles & Fiona',
    appTitle: 'C&L Wedding',

    version    : config.version,
    yui_version: config.yui.version,

    nav: [
        {id: 'wedding',   url: '/wedding/',   label: 'Wedding'},
        {id: 'logistics', url: '/logistics/', label: 'Logistics'},
        {id: 'registry',  url: '/registry/',  label: 'Registry'},
        {id: 'rsvp',      url: '/rsvp/',      label: 'RSVP'},
        {id: 'party_itinerary',      url: '/party_itinerary/',      label: 'Itinerary'},
        {id: 'logout',      url: '/logout/',      label: 'Logout'}

    ],

    subnav: {
        logistics: [
            {id: 'logistics', url: '/logistics/',         label: 'Logistics'},
            {id: 'hotels',    url: '/logistics/hotels/',  label: 'Hotels'},
            {id: 'outings',   url: '/logistics/outings/', label: 'Outings'},
            {id: 'ride_share',   url: '/logistics/ride_share/', label: 'Ride Share'}
        ]
    },

    yui_module: 'le-main',

    pictos : config.pictos,
    typekit: config.typekit,

    isDevelopment: config.isDevelopment,
    isProduction : config.isProduction,

    min: config.isProduction ? '-min' : ''
});

// -- Middleware ---------------------------------------------------------------

if (config.isDevelopment) {
    app.use(express.logger('tiny'));
}

app.use(express.compress());
app.use(express.favicon(config.dirs.pub + '/favicon.ico'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(flash());
app.use(express.cookieSession(config.session));
app.use(express.session({ secret: 'super secret', cookie: { maxAge: 60000 }}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.csrf());
app.use(middleware.csrfToken);
app.use(middleware.invitation);
app.use(middleware.pjax('bare'));
app.use(middleware.checkDate);
app.use(app.router);
app.use(middleware.slash());
app.use(express.static(config.dirs.pub));
app.use(middleware.notfound);
//app.use(authentication);
//app.use(user.middleware());

if (config.isDevelopment) {
    app.use(express.errorHandler({
        dumpExceptions: true,
        showStack     : true
    }));
} else {
    app.use(middleware.error);
}

// -- Routes -------------------------------------------------------------------

//app.get('/', routes.render('home'));
app.get('/', routes.render('landing_page'));

//new landing page for login.
app.get('/welcome/', routes.render('landing_page'));

app.get('/auth/login/failure', routes.render('/login'));
app.get('/auth/login/success', routes.render('/wedding/'));

app.get('/admin/',
  ensureLoggedIn('/login'),
  user.can('access admin page'),
  function(req, res) {
    res.render('views/pages/admin/admin_main', { user: req.user });
    console.log(req.user);
  });

app.get('/home/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('home', { user: req.user });
    console.log(req.user);
  });

app.get('/registry/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('registry', { user: req.user });
    console.log(req.user);
  });

  app.get('/logistics/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('logistics', { user: req.user });
    console.log(req.user);
  });

app.get('/logistics/hotels/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('logistics/hotels', { user: req.user });
    console.log(req.user);
  });

app.get('/logistics/outings/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('logistics/outings', { user: req.user });
    console.log(req.user);
  });

app.get('/logistics/ride_share/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('logistics/ride_share', { user: req.user });
    console.log(req.user);
  });

app.get('/wedding/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('wedding', { user: req.user });
    console.log(req.user);
  });

app.get('/party_itinerary/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('party_itinerary', { user: req.user });
    console.log(req.user);
  });

//basic login page.
app.get('/login',
  function(req, res) {
    res.redirect('/welcome/');
  });

app.get('/logout',
  function(req, res) {
    req.logout();
    res.redirect('/');
  });

// route to authenticate the user
app.post('/login', passport.authenticate('local', {
  successRedirect: '/wedding/',
  failureRedirect: '/login/'
}));

app.get('/rsvp/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('rsvp.pub', { user: req.user });
    console.log(req.user);
  });

app.get('/rsvp/brunch/',
  ensureLoggedIn('/login'),
  function(req, res) {
    res.render('rsvp.brunch', { user: req.user });
    console.log(req.user);
  });

//app.get( '/rsvp/',                       routes.rsvp.pub, routes.rsvp.edit);
app.post('/rsvp/',                       routes.rsvp.resend);
//app.get( '/rsvp/brunch/',                routes.rsvp.brunch);
app.post('/rsvp/brunch/',                routes.rsvp.brunch);
app.get( '/rsvp/brunch/:invitation_key', routes.rsvp.login);
app.get( '/rsvp/:invitation_key',        routes.rsvp.login);

app.all( '/invitations/:invitation/*',       middleware.auth.ensureInvitation);
app.get( '/invitations/:invitation/',        routes.invitations.read);
app.put( '/invitations/:invitation/',        routes.invitations.update);
app.get( '/invitations/:invitation/guests',  routes.invitations.readGuests);
app.post('/invitations/:invitation/confirm', routes.invitations.confirm);

app.all('/guests/:guest/', middleware.auth.ensureGuest);
app.get('/guests/:guest/', routes.guests.read);
app.put('/guests/:guest/', routes.guests.update);

app.get('/combo/:version', [
    combo.combine({rootPath: config.dirs.pub}),
    combo.respond
]);

module.exports = app;
<|endoftext|>


<commit_before>var request = require('request');
var cheerio = require('cheerio');
var wpi = require('wiring-pi');
var Sound = require('node-aplay');

wpi.setup('gpio');
wpi.pinMode(17, wpi.OUTPUT); // led R
wpi.pinMode(27, wpi.OUTPUT); // led G
wpi.pinMode(22, wpi.OUTPUT); // led B

var rgbColors = {
  red: [1, 0, 0],
  grey: [1, 1, 1],
  blue: [0, 0, 1],
  black: [0, 0, 0]
}

var lastColor, lastBliking;

var hasChanged = function (color, blinking) {
  var changed = false;
  if (lastColor !== color || lastBliking !== blinking) {
    changed = true;
  }
  lastColor = color;
  lastBliking = blinking;
  return changed;
}

var sounds = {
  red: 'sounds/red.wav',
  grey: 'sounds/grey.wav',
  blue: 'sounds/blue.wav',
  blinking: 'sounds/blinking.wav'
};

var ledInterval;

var setSound = function (color, isRunning) {
  if (isRunning) {
    new Sound(sounds['blinking']).play();
  } else {
    new Sound(sounds[color]).play();
  }
}

var setLedStatus = function (color, blinking) {
  console.log('led: ' + color);
  clearInterval(ledInterval);

  var currentColor = color;
  setLedColor(currentColor);

  if (blinking) {
    ledInterval = setInterval(function () {
      if (currentColor === 'black') {
        currentColor = color;
      } else {
        currentColor = 'black';
      }
      setLedColor(currentColor);
    }, 500);
  }

}

var setLedColor = function (color) {
  var rgbColor = rgbColors[color];
  wpi.digitalWrite(17, rgbColor[0]);
  wpi.digitalWrite(27, rgbColor[1]);
  wpi.digitalWrite(22, rgbColor[2]);
};

var refreshTime = 15000;
var refreshTimeWhenRunning = 5000;

var scrapJenking = function () {
  var url = 'http://jenkins.pub.dtvc.local/view/www_ccma_cat/job/www_ccma_cat-webapp-functionalTest-moduls-validate-parametrized/';
  request(url, function (error, response, html) {
    var colorStatus = 'blue';
    var isRunning = false;
    if (!error) {
      var $ = cheerio.load(html);
      var img = $('#buildHistory .build-row')[0];
      var imgSrc = $(img).find('img').attr('src');

      isRunning = (imgSrc.indexOf('anime.gif') !== -1);

      if (imgSrc.indexOf('/red') !== -1) {
        colorStatus = 'red';
      } else if (imgSrc.indexOf('/grey') !== -1) {
        colorStatus = 'grey';
      } else if (imgSrc.indexOf('/blue') !== -1) {
        colorStatus = 'blue';
      }
    }

    if (hasChanged(colorStatus, isRunning)) {
      setLedStatus(colorStatus, isRunning);
      setSound(colorStatus, isRunning);
    }
    //LED!!!!

    setTimeout(function () {
      scrapJenking();
    }, (isRunning) ? refreshTimeWhenRunning : refreshTime);

  })
};

scrapJenking();<commit_msg>Fixed bug on sound<commit_after>var request = require('request');
var cheerio = require('cheerio');
var wpi = require('wiring-pi');
var Sound = require('node-aplay');

wpi.setup('gpio');
wpi.pinMode(17, wpi.OUTPUT); // led R
wpi.pinMode(27, wpi.OUTPUT); // led G
wpi.pinMode(22, wpi.OUTPUT); // led B

var rgbColors = {
  red: [1, 0, 0],
  grey: [1, 1, 1],
  blue: [0, 0, 1],
  black: [0, 0, 0]
}

var lastColor, lastBliking;

var hasChanged = function (color, blinking) {
  var changed = false;
  if (lastColor !== color || lastBliking !== blinking) {
    changed = true;
  }
  lastColor = color;
  lastBliking = blinking;
  return changed;
}

var sounds = {
  red: 'sounds/red.wav',
  grey: 'sounds/grey.wav',
  blue: 'sounds/blue.wav',
  blinking: 'sounds/blinking.wav'
};

var ledInterval;

var setSound = function (color, isRunning) {
  if (isRunning) {
    color = 'blinking';
  }
  console.log('setSound: ' + sounds[color]);
  new Sound(sounds[color]).play();
}

var setLedStatus = function (color, blinking) {
  console.log('led: ' + color);
  clearInterval(ledInterval);

  var currentColor = color;
  setLedColor(currentColor);

  if (blinking) {
    ledInterval = setInterval(function () {
      if (currentColor === 'black') {
        currentColor = color;
      } else {
        currentColor = 'black';
      }
      setLedColor(currentColor);
    }, 500);
  }

}

var setLedColor = function (color) {
  var rgbColor = rgbColors[color];
  wpi.digitalWrite(17, rgbColor[0]);
  wpi.digitalWrite(27, rgbColor[1]);
  wpi.digitalWrite(22, rgbColor[2]);
};

var refreshTime = 15000;
var refreshTimeWhenRunning = 5000;

var scrapJenking = function () {
  var url = 'http://jenkins.pub.dtvc.local/view/www_ccma_cat/job/www_ccma_cat-webapp-functionalTest-moduls-validate-parametrized/';
  request(url, function (error, response, html) {
    var colorStatus = 'blue';
    var isRunning = false;
    if (!error) {
      var $ = cheerio.load(html);
      var img = $('#buildHistory .build-row')[0];
      var imgSrc = $(img).find('img').attr('src');

      isRunning = (imgSrc.indexOf('anime.gif') !== -1);

      if (imgSrc.indexOf('/red') !== -1) {
        colorStatus = 'red';
      } else if (imgSrc.indexOf('/grey') !== -1) {
        colorStatus = 'grey';
      } else if (imgSrc.indexOf('/blue') !== -1) {
        colorStatus = 'blue';
      }
    }

    if (hasChanged(colorStatus, isRunning)) {
      setLedStatus(colorStatus, isRunning);
      setSound(colorStatus, isRunning);
    }
    //LED!!!!

    setTimeout(function () {
      scrapJenking();
    }, (isRunning) ? refreshTimeWhenRunning : refreshTime);

  })
};

scrapJenking();<|endoftext|>


<commit_before>#!/usr/bin/env node

var gyp = require('node-gyp')()
var path = require('path')
var install = require('node-gyp-install')
var log = require('npmlog')
var zlib = require('zlib')
var tar = require('tar-stream')
var fs = require('fs')
var rc = require('./rc')

log.heading = 'prebuild'
var setupLog = log.info.bind(log, 'setup')

var NODE_GYP = path.join(process.env.HOME || process.env.USERPROFILE, '.node-gyp')

if (!fs.existsSync('package.json')) {
  log.error('No package.json found. Aborting...')
  process.exit(1)
}

var pkg = require(path.resolve('package.json'))

if (rc.help) {
  console.error(fs.readFileSync(path.join(__dirname, 'help.txt'), 'utf-8'))
  process.exit(0)
}

var targets = [].concat(rc.target)

prebuild(targets.shift(), function done (err, result) {
  if (err) {
    log.error(err.message)
    process.exit(2)
  }
  if (targets.length) prebuild(targets.shift(), done)
})

function getAbi (version, cb) {
  version = version.replace('v', '')
  fs.readFile(path.join(NODE_GYP, version, 'src/node_version.h'), 'utf-8', function (err, a) {
    if (err && err.code === 'ENOENT') retry()
    if (err) return cb(err)
    fs.readFile(path.join(NODE_GYP, version, 'src/node.h'), 'utf-8', function (err, b) {
      if (err && err.code === 'ENOENT') retry()
      if (err) return cb(err)
      var abi = parse(a) || parse(b)
      if (!abi) return cb(new Error('Could not detect abi for ' + version))
      cb(null, abi)
    })
  })

  function retry () {
    install({log: setupLog, version: version, force: true}, function (err) {
      if (err) return cb(err)
      getAbi(version, cb)
    })
  }

  function parse (file) {
    var res = file.match(/#define\s+NODE_MODULE_VERSION\s+\(?(\d+)/)
    return res && res[1]
  }
}

function build (version, cb) {
  var release = 'build/Release'

  install({log: setupLog, version: version}, function (err) {
    if (err) return cb(err)
    runGyp()
  })

  function runGyp () {
    gyp.parseArgv(['node', 'index.js', 'rebuild', '--target=' + version, '--target_arch=' + rc.arch])
    gyp.commands.rebuild(gyp.todo.shift().args, function run (err) {
      if (err) return cb(err)
      if (!gyp.todo.length) return done()
      if (gyp.todo[0].name === 'configure') configurePreGyp()
      gyp.commands[gyp.todo[0].name](gyp.todo.shift().args, run)
    })
  }

  function configurePreGyp () {
    if (pkg.binary && pkg.binary.module_name) {
      gyp.todo[0].args.push('-Dmodule_name=' + pkg.binary.module_name)
    }
    if (pkg.binary && pkg.binary.module_path) {
      release = pkg.binary.module_path
      gyp.todo[0].args.push('-Dmodule_path=' + pkg.binary.module_path)
    }
  }

  function done () {
    fs.readdir(release, function (err, files) {
      if (err) return cb(err)

      for (var i = 0; i < files.length; i++) {
        if (/\.node$/i.test(files[i])) return cb(null, path.join(release, files[i]), files[i])
      }

      cb(new Error('Could not find build in ' + release))
    })
  }
}

function prebuild (v, cb) {
  if (v[0] !== 'v') v = 'v' + v
  log.info('setup', 'Preparing to prebuild ' + pkg.name + '@' + pkg.version + ' for ' + v + ' on ' + rc.platform + '-' + rc.arch)
  build(v, function (err, filename) {
    if (err) return log.error(err.message)
    getAbi(v, function (err, abi) {
      if (err) return log.error(err.message)
      pack(filename, abi)
    })
  })

  function pack (filename, abi) {
    var name = pkg.name + '-' + pkg.version + '-node-v' + abi + '-' + rc.platform + '-' + rc.arch + '.tar.gz'
    var tarPath = path.join('prebuilds', name)
    fs.mkdir('prebuilds', function () {
      fs.stat(filename, function (err, st) {
        if (err) return cb(err)

        var pack = tar.pack()
        var ws = fs.createWriteStream(tarPath)
        var stream = pack.entry({
          name: filename,
          size: st.size,
          mode: st.mode,
          gid: st.gid,
          uid: st.uid
        })

        fs.createReadStream(filename).pipe(stream).on('finish', function () {
          pack.finalize()
        })

        pack.pipe(zlib.createGzip()).pipe(ws).on('close', function () {
          log.info('package', 'Prebuild written to ' + tarPath)
          cb(null, {path: tarPath, name: name, abi: abi, version: v, platform: rc.platform, arch: rc.arch})
        })
      })
    })
  }
}
<commit_msg>fix prebuild names<commit_after>#!/usr/bin/env node

var gyp = require('node-gyp')()
var path = require('path')
var install = require('node-gyp-install')
var log = require('npmlog')
var zlib = require('zlib')
var tar = require('tar-stream')
var fs = require('fs')
var rc = require('./rc')

log.heading = 'prebuild'
var setupLog = log.info.bind(log, 'setup')

var NODE_GYP = path.join(process.env.HOME || process.env.USERPROFILE, '.node-gyp')

if (!fs.existsSync('package.json')) {
  log.error('No package.json found. Aborting...')
  process.exit(1)
}

var pkg = require(path.resolve('package.json'))

if (rc.help) {
  console.error(fs.readFileSync(path.join(__dirname, 'help.txt'), 'utf-8'))
  process.exit(0)
}

var targets = [].concat(rc.target)

prebuild(targets.shift(), function done (err, result) {
  if (err) {
    log.error(err.message)
    process.exit(2)
  }
  if (targets.length) prebuild(targets.shift(), done)
})

function getAbi (version, cb) {
  version = version.replace('v', '')
  fs.readFile(path.join(NODE_GYP, version, 'src/node_version.h'), 'utf-8', function (err, a) {
    if (err && err.code === 'ENOENT') retry()
    if (err) return cb(err)
    fs.readFile(path.join(NODE_GYP, version, 'src/node.h'), 'utf-8', function (err, b) {
      if (err && err.code === 'ENOENT') retry()
      if (err) return cb(err)
      var abi = parse(a) || parse(b)
      if (!abi) return cb(new Error('Could not detect abi for ' + version))
      cb(null, abi)
    })
  })

  function retry () {
    install({log: setupLog, version: version, force: true}, function (err) {
      if (err) return cb(err)
      getAbi(version, cb)
    })
  }

  function parse (file) {
    var res = file.match(/#define\s+NODE_MODULE_VERSION\s+\(?(\d+)/)
    return res && res[1]
  }
}

function build (version, cb) {
  var release = 'build/Release'

  install({log: setupLog, version: version}, function (err) {
    if (err) return cb(err)
    runGyp()
  })

  function runGyp () {
    gyp.parseArgv(['node', 'index.js', 'rebuild', '--target=' + version, '--target_arch=' + rc.arch])
    gyp.commands.rebuild(gyp.todo.shift().args, function run (err) {
      if (err) return cb(err)
      if (!gyp.todo.length) return done()
      if (gyp.todo[0].name === 'configure') configurePreGyp()
      gyp.commands[gyp.todo[0].name](gyp.todo.shift().args, run)
    })
  }

  function configurePreGyp () {
    if (pkg.binary && pkg.binary.module_name) {
      gyp.todo[0].args.push('-Dmodule_name=' + pkg.binary.module_name)
    }
    if (pkg.binary && pkg.binary.module_path) {
      release = pkg.binary.module_path
      gyp.todo[0].args.push('-Dmodule_path=' + pkg.binary.module_path)
    }
  }

  function done () {
    fs.readdir(release, function (err, files) {
      if (err) return cb(err)

      for (var i = 0; i < files.length; i++) {
        if (/\.node$/i.test(files[i])) return cb(null, path.join(release, files[i]), files[i])
      }

      cb(new Error('Could not find build in ' + release))
    })
  }
}

function prebuild (v, cb) {
  if (v[0] !== 'v') v = 'v' + v
  log.info('setup', 'Preparing to prebuild ' + pkg.name + '@' + pkg.version + ' for ' + v + ' on ' + rc.platform + '-' + rc.arch)
  build(v, function (err, filename) {
    if (err) return log.error(err.message)
    getAbi(v, function (err, abi) {
      if (err) return log.error(err.message)
      pack(filename, abi)
    })
  })

  function pack (filename, abi) {
    var name = pkg.name + '-v' + pkg.version + '-node-v' + abi + '-' + rc.platform + '-' + rc.arch + '.tar.gz'
    var tarPath = path.join('prebuilds', name)
    fs.mkdir('prebuilds', function () {
      fs.stat(filename, function (err, st) {
        if (err) return cb(err)

        var pack = tar.pack()
        var ws = fs.createWriteStream(tarPath)
        var stream = pack.entry({
          name: filename,
          size: st.size,
          mode: st.mode,
          gid: st.gid,
          uid: st.uid
        })

        fs.createReadStream(filename).pipe(stream).on('finish', function () {
          pack.finalize()
        })

        pack.pipe(zlib.createGzip()).pipe(ws).on('close', function () {
          log.info('package', 'Prebuild written to ' + tarPath)
          cb(null, {path: tarPath, name: name, abi: abi, version: v, platform: rc.platform, arch: rc.arch})
        })
      })
    })
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs')
var peervision = require('peervision')
var airswarm = require('airswarm')
var signalhub = require('signalhub')
var net = require('net')
var choppa = require('choppa')
var minimist = require('minimist')
var pump = require('pump')
var DHT = require('bittorrent-dht')

var dht = new DHT()
var argv = minimist(process.argv)

var id = argv._[2]
var vision = peervision(id ? new Buffer(id, 'hex') : null)
var debug = argv.debug ? console.error.bind(console, 'DEBUG:') : function () {}

if (argv.webrtc) {
  var wrtc = require('wrtc')
  var swarm = require('webrtc-swarm')
  var sw = swarm(signalhub('pv-' + vision.id.toString('hex'), ['https://signalhub.mafintosh.com']), {wrtc: wrtc})
  sw.on('peer', function (p) {
    debug('WebRTC peer')
    pump(p, vision.createStream(), p)
  })
}

var server = airswarm('pv-' + vision.id.toString('hex'), function (p) {
  debug('Airswarm peer')
  pump(p, vision.createStream(), p)
})

dht.on('ready', function () {
  debug('DHT ready')
  dht.announce(vision.id.slice(0, 20), server.address().port)
})

var peers = {}

dht.on('peer', function (peer) {
  if (peers[peer]) return
  peers[peer] = true
  var socket = net.connect(Number(peer.split(':')[1]), peer.split(':')[0])
  pump(socket, vision.createStream(), socket)
})

vision.on('upload', function (index) {
  debug('Uploading block #' + index)
})

vision.on('download', function (index) {
  debug('Downloading block #' + index)
})

var blocks = 0

if (!id) {
  console.error('Stream id is', vision.id.toString('hex'))

  if (argv.stdin) {
    process.stdin.on('data', function (data) {
      vision.append(data)
    })
    return
  }

  console.error('Enter the files you want to stream:')
  process.stdin.on('data', function (data) {
    fs.createReadStream(data.toString().trim()).pipe(choppa(16 * 1024)).on('data', function (data) {
      blocks++
      vision.append(data)
    }).on('end', function () {
      debug('Appended', blocks, 'blocks')
    })
  })
} else {
  var offset = Number(argv.offset || 0)
  loop()

  var buffer = 5
  function noop () {}

  function loop () {
    // for (var i = 0; i < buffer; i++) vision.get(offset + i + 1, noop)
    vision.get(offset, function (err, data) {
      if (err) throw err
      offset++
      process.stdout.write(data, loop)
    })
  }
}
<commit_msg>do a lookup<commit_after>#!/usr/bin/env node

var fs = require('fs')
var peervision = require('peervision')
var airswarm = require('airswarm')
var signalhub = require('signalhub')
var net = require('net')
var choppa = require('choppa')
var minimist = require('minimist')
var pump = require('pump')
var DHT = require('bittorrent-dht')

var dht = new DHT()
var argv = minimist(process.argv)

var id = argv._[2]
var vision = peervision(id ? new Buffer(id, 'hex') : null)
var debug = argv.debug ? console.error.bind(console, 'DEBUG:') : function () {}

if (argv.webrtc) {
  var wrtc = require('wrtc')
  var swarm = require('webrtc-swarm')
  var sw = swarm(signalhub('pv-' + vision.id.toString('hex'), ['https://signalhub.mafintosh.com']), {wrtc: wrtc})
  sw.on('peer', function (p) {
    debug('WebRTC peer')
    pump(p, vision.createStream(), p)
  })
}

var server = airswarm('pv-' + vision.id.toString('hex'), function (p) {
  debug('Airswarm peer')
  pump(p, vision.createStream(), p)
})

dht.on('ready', function () {
  debug('DHT ready')
  dht.announce(vision.id.slice(0, 20), server.address().port)

  setInterval(lookup, 10000)
  lookup()

  function lookup () {
    dht.lookup(vision.id.slice(0, 20))
  }
})

var peers = {}

dht.on('peer', function (peer) {
  if (peers[peer]) return
  peers[peer] = true
  var socket = net.connect(Number(peer.split(':')[1]), peer.split(':')[0])
  pump(socket, vision.createStream(), socket)
})

vision.on('upload', function (index) {
  debug('Uploading block #' + index)
})

vision.on('download', function (index) {
  debug('Downloading block #' + index)
})

var blocks = 0

if (!id) {
  console.error('Stream id is', vision.id.toString('hex'))

  if (argv.stdin) {
    process.stdin.on('data', function (data) {
      vision.append(data)
    })
    return
  }

  console.error('Enter the files you want to stream:')
  process.stdin.on('data', function (data) {
    fs.createReadStream(data.toString().trim()).pipe(choppa(16 * 1024)).on('data', function (data) {
      blocks++
      vision.append(data)
    }).on('end', function () {
      debug('Appended', blocks, 'blocks')
    })
  })
} else {
  var offset = Number(argv.offset || 0)
  loop()

  var buffer = 5
  function noop () {}

  function loop () {
    // for (var i = 0; i < buffer; i++) vision.get(offset + i + 1, noop)
    vision.get(offset, function (err, data) {
      if (err) throw err
      offset++
      process.stdout.write(data, loop)
    })
  }
}
<|endoftext|>


<commit_before>#! /usr/bin/env node

var client = require('scuttlebot/client')
var config = require('ssb-config')
var ssbKeys = require('ssb-keys')
var path = require('path')
var explain = require('explain-error')
var fs = require('fs')
var pull = require('pull-stream')
var paramap = require('pull-paramap')
var stringify = require('pull-stringify')
var minimist = require('minimist')
var cont = require('cont')

var manifestFile = path.join(config.path, 'manifest.json')

var manifest
try {
  manifest = JSON.parse(fs.readFileSync(manifestFile))
} catch (err) {
  throw explain(err,
    'could not load manifest file'
    + '- should be generated first time server is run'
  )
}

var keys = ssbKeys.loadOrCreateSync(path.join(config.path, 'secret'))

var rpc = client(config, manifest)

rpc.auth(ssbKeys.signObj(keys, {
    role: 'client',
    ts: Date.now(),
    public: keys.public
  }), function (err) {
    //give up.
    if(err) throw err
  })

function isEmpty (obj) {
  for(var k in obj) return false
  return true
}

var opts = minimist(process.argv.slice(2))
var cmd = opts._.shift()
var arg = opts._.shift()
delete opts._

var bittodo = require('./api')(rpc, keys.id)

if(bittodo[cmd]) {
  var maybeStream = bittodo[cmd](arg || (isEmpty(opts) ? null : opts), function (err, out) {
    if(err) throw err
    console.log(JSON.stringify(_msg, null, 2))
    process.exit()
  })

  if(maybeStream)
    pull(
      maybeStream,
      pull.drain(function (msg) {
        console.log(JSON.stringify(msg, null, 2) + '\n')
      }, function (err) {
        if(err) throw err
        process.exit()
      })
    )
}

else if(cmd === 'done') {

  bittodo.update({state: 'done', root: arg}, function (err, msg) {
    if(err) throw err
    console.log(JSON.stringify(msg, null, 2))
    process.exit()
  })

}

else {
  console.error('bittodo cmd {opts}')
  process.exit(1)
}
<commit_msg>use ssb-client instead of baking it into this module<commit_after>#! /usr/bin/env node

var config = require('ssb-config')
var ssbKeys = require('ssb-keys')
var path = require('path')
var explain = require('explain-error')
var fs = require('fs')
var pull = require('pull-stream')
var paramap = require('pull-paramap')
var stringify = require('pull-stringify')
var minimist = require('minimist')
var cont = require('cont')

var keys = ssbKeys.loadOrCreateSync(config)
var client = require('ssb-client') (keys, config)
var rpc = client

function abortIf(err) {
  if(err) throw err
}

client.connect(abortIf)
.auth(ssbKeys.createAuth(keys), abortIf)

function isEmpty (obj) {
  for(var k in obj) return false
  return true
}

var opts = minimist(process.argv.slice(2))
var cmd = opts._.shift()
var arg = opts._.shift()
delete opts._

var bittodo = require('./api')(rpc, keys.id)

if(bittodo[cmd]) {
  var maybeStream = bittodo[cmd](arg || (isEmpty(opts) ? null : opts), function (err, msg) {
    if(err) throw err
    console.log(JSON.stringify(msg, null, 2))
    process.exit()
  })

  if(maybeStream)
    pull(
      maybeStream,
      pull.drain(function (msg) {
        console.log(JSON.stringify(msg, null, 2) + '\n')
      }, function (err) {
        if(err) throw err
        process.exit()
      })
    )
}

else if(cmd === 'done') {

  bittodo.update({state: 'done', root: arg}, function (err, msg) {
    if(err) throw err
    console.log(JSON.stringify(msg, null, 2))
    process.exit()
  })

}

else {
  console.error('bittodo cmd {opts}')
  process.exit(1)
}
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const client = new Discord.Client();
const figlet = require('figlet');
const fs = require('fs');
const irc = require('irc');

//process.argv.forEach((t) => console.log(t));

token = process.argv[2];
//console.log('Using token: ' + token);

client.on('ready', () => {
        console.log("BOT IS READY");
});

serverText = fs.readFileSync('servers.json');
var servers = JSON.parse(serverText);

const ircClient = new irc.Client(servers.irc.hostname, servers.irc.nick, {
        channels: servers.irc.channels,
        secure: servers.irc.secure,
        port: servers.irc.port
});

executorsText = fs.readFileSync('executors.json');
const executors = JSON.parse(executorsText).list;

function getChannelFromID(server, id) {
        return server.channels.resolve(id);
}

client.on('message', (msg) => {

        const re = /\?(?<command>\w*)(?<args> (\w*)*)?( ?```(?<code>.*)```)?/gms;
        input = re.exec(msg.content);

        if(input) {

                command = input.groups.command;
                args = input.groups.args;
                code = input.groups.code;

                //console.dir(input);

                if (input.groups.command == "fig") {
                        if (input.groups.args == undefined) {
                                msg.channel.send("You need to give some text to figlet");
                                return;
                        }

                        figlet(args, (err, data) => {
                                if (err) {
                                        console.log("figlet broke?");
                                }
                                msg.channel.send("```" + data + "```")
                        });
                }

                if (command == "setdel") {
                        var channel = args;
                        if (!servers[msg.guild.id]) {
                                servers[msg.guild.id] = {}
                        }
                        servers[msg.guild.id]["deletes"] = channel;

                        let newServer = JSON.stringify(servers);

                        fs.writeFile('servers.json', newServer, (err) => {
                                if (err) throw err;
                                console.log("delete prefs updated for " + msg.guild.name);
                        });

                        msg.channel.send("Delete channel preference set.")
                }

                if (command == "execute") {
                        if (executors.includes(""+msg.author.id)) {
                                if(code != undefined) {
                                        try {
                                                msg.channel.send(eval(code.trim(/(javascript)|(js)/gm)));
                                        } catch (e) {
                                                msg.channel.send("Your code caused an error");
                                        }
                                } else {
                                        msg.channel.send("You have to send some code using ```[code]```");
                                }
                        } else {
                                msg.channel.send("You are not an approved executor");
                        }
                }

        }

        if (msg.channel.id == servers.irc.cid && msg.author.id != "460651339358273546") {
                ircClient.say(servers.irc.channels[0], "<" + msg.member.displayName + ">: " + msg.content);
        }

});

client.on('messageDelete', (msg) => {
        if (servers[msg.guild.id]) {
                if (servers[msg.guild.id]["deletes"]) {
                        chan = getChannelFromID(msg.guild, servers[msg.guild.id]["deletes"]);

                        let delEmbed = new Discord.MessageEmbed()
                                .setColor('#992020')
                                .setTitle("Deleted Message from " + msg.author.tag)
                                .addFields(
                                        {name: "Message", value: msg.content},
                                        {name: "Channel", value: msg.channel.name},
                                        {name: "Timestamp", value: msg.createdAt}
                                );
                        try {
                                chan.send(delEmbed);
                        } catch (e) {
                                console.log("error sending deleted message log");
                        }

                        console.log("sent deleted message log to " + msg.guild.name);

                }
        }

});

ircClient.addListener('message', (from, to, message) => {
        if (servers.irc.channels.includes(to) && !from.includes("KholoBot")) {
                client.guilds.resolve(servers.irc.sid).channels.resolve(servers.irc.cid).send("<" + from + "> " + message);
        }
});

ircClient.addListener('error', (msg) => {
        console.log("IRC Error: " + msg);
});

client.login(token);
<commit_msg>made some things more arbitrary, fixed irc bridging with embeded images<commit_after>const Discord = require('discord.js');
const client = new Discord.Client();
const figlet = require('figlet');
const fs = require('fs');
const irc = require('irc');

//process.argv.forEach((t) => console.log(t));

token = process.argv[2];
//console.log('Using token: ' + token);

client.on('ready', () => {
        console.log("BOT IS READY");
});

serverText = fs.readFileSync('servers.json');
var servers = JSON.parse(serverText);

const ircClient = new irc.Client(servers.irc.hostname, servers.irc.nick, {
        channels: servers.irc.channels,
        secure: servers.irc.secure,
        port: servers.irc.port
});

executorsText = fs.readFileSync('executors.json');
const executors = JSON.parse(executorsText).list;

function getChannelFromID(server, id) {
        return server.channels.resolve(id);
}

client.on('message', (msg) => {

        const re = /\?(?<command>\w*)(?<args> (\w*)*)?( ?```(?<code>.*)```)?/gms;
        input = re.exec(msg.content);

        if(input) {

                command = input.groups.command;
                args = input.groups.args;
                code = input.groups.code;

                //console.dir(input);

                if (input.groups.command == "fig") {
                        if (input.groups.args == undefined) {
                                msg.channel.send("You need to give some text to figlet");
                                return;
                        }

                        figlet(args, (err, data) => {
                                if (err) {
                                        console.log("figlet broke?");
                                }
                                msg.channel.send("```" + data + "```")
                        });
                }

                if (command == "setdel") {
                        var channel = args;
                        if (!servers[msg.guild.id]) {
                                servers[msg.guild.id] = {}
                        }
                        servers[msg.guild.id]["deletes"] = channel;

                        let newServer = JSON.stringify(servers);

                        fs.writeFile('servers.json', newServer, (err) => {
                                if (err) throw err;
                                console.log("delete prefs updated for " + msg.guild.name);
                        });

                        msg.channel.send("Delete channel preference set.")
                }

                if (command == "execute") {
                        if (executors.includes(""+msg.author.id)) {
                                if(code != undefined) {
                                        try {
                                                msg.channel.send(eval(code.trim(/(javascript)|(js)/gm)));
                                        } catch (e) {
                                                msg.channel.send("Your code caused an error");
                                        }
                                } else {
                                        msg.channel.send("You have to send some code using ```[code]```");
                                }
                        } else {
                                msg.channel.send("You are not an approved executor");
                        }
                }

        }

        if (msg.channel.id == servers.irc.cid && msg.author.id != client.user.id) {

                if (msg.content != "")
                        ircClient.say(servers.irc.channels[0], "<" + msg.member.displayName + ">: " + msg.content);

                msg.embeds.forEach((e) => {
                        ircClient.say(servers.irc.channels[0], "<" + msg.member.displayName + "> " + e.url);
                });
        }

});

client.on('messageDelete', (msg) => {
        if (servers[msg.guild.id]) {
                if (servers[msg.guild.id]["deletes"]) {
                        chan = getChannelFromID(msg.guild, servers[msg.guild.id]["deletes"]);

                        let delEmbed = new Discord.MessageEmbed()
                                .setColor('#992020')
                                .setTitle("Deleted Message from " + msg.author.tag)
                                .addFields(
                                        {name: "Message", value: msg.content},
                                        {name: "Channel", value: msg.channel.name},
                                        {name: "Timestamp", value: msg.createdAt}
                                );
                        try {
                                chan.send(delEmbed);
                        } catch (e) {
                                console.log("error sending deleted message log");
                        }

                        console.log("sent deleted message log to " + msg.guild.name);

                }
        }

});

ircClient.addListener('message', (from, to, message) => {
        if (servers.irc.channels.includes(to) && !from.includes("KholoBot")) {
                client.guilds.resolve(servers.irc.sid).channels.resolve(servers.irc.cid).send("<" + from + "> " + message);
        }
});

ircClient.addListener('error', (msg) => {
        console.log("IRC Error: " + msg);
});

client.login(token);
<|endoftext|>


<commit_before>'use strict';

const fs =  require(`fs`);
const path = require('path');
const uuid = require(`uuid`);
const svg2png = require(`svg2png`);
const html2png = require('html2png');
const Jimp = require('jimp');

const NewsEngine = require('./src/news-engine');
const TwitterClient = require('./src/lib/api/twitter-client');
const mtgCardFinder = require('./src/lib/api/mtg-cardfinder');
const config = require('./config');

const fileLogger = (msg, isErr) => {
	const logToConsole = isErr ? console.error : console.log;

    logToConsole(`${msg}`);

    fs.appendFile(config.paths.logFile, `${msg}\n`, (err) => {
        if (err) throw err;
    });
};
const logError = msg => fileLogger(`ERROR: ${msg}`, true);

function postImageTweet(imageFilePath, status, cardName) {
	twitter.uploadTwitterImage(imageFilePath)
		.catch(e => logError('Failed to upload image: ' + e))
		.then(twitterImage => twitter.postImageTweet(twitterImage, cardName, status))
		.catch(e => logError('Failed to post tweet: ' + e));
}

function postCardImageTweet(status, cardName) {
	const outputPath = config.paths.tempDirectory + '/' + outputfile;
	const outputfile = cardName.replace(/\s+/g, '-').toLowerCase() + '-' + uuid() + '.jpg';

	mtgCardFinder.downloadCardImage(cardName, outputPath)
		.then(localFilePath => postImageTweet(localFilePath, status, cardName))
		.then(() => {
      return fs.unlink(outputPath, (err) => {
				if (!err) {
					console.log('Deleted ' + outputPath);
				} else {
					logError('Unable to delete local image file: ' + err);
				}
			});
		})
		.catch(e => logError('Failed to download image: ' + e));
}

function postSvgTweet(status, svgString, altText) {
	altText = altText || "Rendered Image";
	svg2png(new Buffer(svgString), { filename: path.resolve(__dirname, 'src') })
		.catch(e => logError('Failed to create png: ' + e))
		.then(data => twitter.uploadTwitterImageData(data.toString('base64')))
		.catch(e => logError('Failed to upload image: ' + e))
		.then(twitterImage => twitter.postImageTweet(twitterImage, altText, status))
		.catch(e => logError('Failed to post tweet: ' + e));
}

function resolveCssUrls(html) {
	var newHtml = html.toString();

	function fileUrl(url) {
    var pathName = path.resolve(url).replace(/\\/g, '/');
    // windows drive letters must be prefixed with a slash
    if (pathName[0] !== '/') {
        pathName = '/' + pathName;
    }
    return encodeURI('file://' + pathName);
	}

	const matches = newHtml.match(/url\(\..*?\)/g);
	if (!matches) {
		return html;
	}
	matches.forEach(match => {
		newHtml = newHtml.replace(match, 'url('+ fileUrl(match.match(/url\((\..*?)\)/)[1])  + ')');
	});
	return newHtml;
}

function renderImageFromHtml(html, outputPath) {
	return new Promise((resolve, reject) => {
		const screenshot = html2png({ width: 1024, height: 768, browser: 'phantomjs'});

		console.log('HTML:'); console.log(html);

		screenshot.render(html, function (err, data) {
			if (err) {
				console.log('\n *** Failed to create png:');
				reject(err);
			}
			return Jimp.read(data).then(image => image.autocrop().write(outputPath))
      .then(() => {
				console.log('\n *** Trimmed image saved to ' + outputPath);
				setTimeout(() => resolve(outputPath), 1000);
      })
      .catch(err => {
      	console.log('\n *** Failed to create trimmed png:');
      	console.log(err);
      	console.log(err.stack);
      	reject(err);
      });
			screenshot.close();
		});
	});
}

function postHtmlImageTweet(status, htmlString, altText) {
	const outputfile = uuid() + '.png';
	const outputPath = config.paths.tempDirectory + '/' + outputfile;

	console.log('postHtmlImageTweet | html:\n' + htmlString);

	renderImageFromHtml(htmlString, outputPath)
		.then(localFilePath => postImageTweet(localFilePath, status, altText))
		.then(() => {
      return fs.unlink(outputPath, (err) => {
				if (!err) {
					console.log('Deleted ' + outputPath);
				} else {
					logError('Unable to delete local image file: ' + err);
				}
			});
		})
		.catch(e => logError('Failed to download image: ' + e));
}

// Create tweet from grammar
let headline = NewsEngine.generateHeadline();

while (headline.text.length > config.tweetLength) {
  logError(`TWEET LENGTH ${headline.text.length} GREATER THAN MAX ${config.tweetLength}:\n${headline.text}`);
	headline = NewsEngine.generateHeadline();
}

fileLogger(`tweet: ${JSON.stringify(headline)}`);

// Create twitter client
const twitter = new TwitterClient();

if (headline.tags && headline.tags.imgCard && headline.tags.imgCard.cardName) {
	postCardImageTweet(headline.text, headline.tags.imgCard.cardName);
} else if (headline.tags && headline.tags.htmlImg && headline.tags.htmlImg.htmlImgString) {
	const html = resolveCssUrls(headline.tags.htmlImg.htmlImgString.replace(/`/g, '"'));
	postHtmlImageTweet(headline.text, html, headline.tags.htmlImg.altText || 'image');
} else if (headline.tags && headline.tags.svg && headline.tags.svg.svgString) {
	postSvgTweet(headline.text, headline.tags.svg.svgString.replace(/`/g, '"'), headline.tags.svg.altText || 'image');
} else {
	twitter.postTweet(headline.text);
}<commit_msg>fix bot<commit_after>'use strict';

const fs =  require(`fs`);
const path = require('path');
const uuid = require(`uuid`);
const svg2png = require(`svg2png`);
const html2png = require('html2png');
const Jimp = require('jimp');

const NewsEngine = require('./src/news-engine');
const TwitterClient = require('./src/lib/api/twitter-client');
const mtgCardFinder = require('./src/lib/api/mtg-cardfinder');
const config = require('./config');

const fileLogger = (msg, isErr) => {
	const logToConsole = isErr ? console.error : console.log;

    logToConsole(`${msg}`);

    fs.appendFile(config.paths.logFile, `${msg}\n`, (err) => {
        if (err) throw err;
    });
};
const logError = msg => fileLogger(`ERROR: ${msg}`, true);

function postImageTweet(imageFilePath, status, cardName) {
	twitter.uploadTwitterImage(imageFilePath)
		.catch(e => logError('Failed to upload image: ' + e))
		.then(twitterImage => twitter.postImageTweet(twitterImage, cardName, status))
		.catch(e => logError('Failed to post tweet: ' + e));
}

function postCardImageTweet(status, cardName) {
	const outputfile = cardName.replace(/\s+/g, '-').toLowerCase() + '-' + uuid() + '.jpg';
	const outputPath = config.paths.tempDirectory + '/' + outputfile;

	mtgCardFinder.downloadCardImage(cardName, outputPath)
		.then(localFilePath => postImageTweet(localFilePath, status, cardName))
		.then(() => {
      return fs.unlink(outputPath, (err) => {
				if (!err) {
					console.log('Deleted ' + outputPath);
				} else {
					logError('Unable to delete local image file: ' + err);
				}
			});
		})
		.catch(e => logError('Failed to download image: ' + e));
}

function postSvgTweet(status, svgString, altText) {
	altText = altText || "Rendered Image";
	svg2png(new Buffer(svgString), { filename: path.resolve(__dirname, 'src') })
		.catch(e => logError('Failed to create png: ' + e))
		.then(data => twitter.uploadTwitterImageData(data.toString('base64')))
		.catch(e => logError('Failed to upload image: ' + e))
		.then(twitterImage => twitter.postImageTweet(twitterImage, altText, status))
		.catch(e => logError('Failed to post tweet: ' + e));
}

function resolveCssUrls(html) {
	var newHtml = html.toString();

	function fileUrl(url) {
    var pathName = path.resolve(url).replace(/\\/g, '/');
    // windows drive letters must be prefixed with a slash
    if (pathName[0] !== '/') {
        pathName = '/' + pathName;
    }
    return encodeURI('file://' + pathName);
	}

	const matches = newHtml.match(/url\(\..*?\)/g);
	if (!matches) {
		return html;
	}
	matches.forEach(match => {
		newHtml = newHtml.replace(match, 'url('+ fileUrl(match.match(/url\((\..*?)\)/)[1])  + ')');
	});
	return newHtml;
}

function renderImageFromHtml(html, outputPath) {
	return new Promise((resolve, reject) => {
		const screenshot = html2png({ width: 1024, height: 768, browser: 'phantomjs'});

		console.log('HTML:'); console.log(html);

		screenshot.render(html, function (err, data) {
			if (err) {
				console.log('\n *** Failed to create png:');
				reject(err);
			}
			return Jimp.read(data).then(image => image.autocrop().write(outputPath))
      .then(() => {
				console.log('\n *** Trimmed image saved to ' + outputPath);
				setTimeout(() => resolve(outputPath), 1000);
      })
      .catch(err => {
      	console.log('\n *** Failed to create trimmed png:');
      	console.log(err);
      	console.log(err.stack);
      	reject(err);
      });
			screenshot.close();
		});
	});
}

function postHtmlImageTweet(status, htmlString, altText) {
	const outputfile = uuid() + '.png';
	const outputPath = config.paths.tempDirectory + '/' + outputfile;

	console.log('postHtmlImageTweet | html:\n' + htmlString);

	renderImageFromHtml(htmlString, outputPath)
		.then(localFilePath => postImageTweet(localFilePath, status, altText))
		.then(() => {
      return fs.unlink(outputPath, (err) => {
				if (!err) {
					console.log('Deleted ' + outputPath);
				} else {
					logError('Unable to delete local image file: ' + err);
				}
			});
		})
		.catch(e => logError('Failed to download image: ' + e));
}

// Create tweet from grammar
let headline = NewsEngine.generateHeadline();

while (headline.text.length > config.tweetLength) {
  logError(`TWEET LENGTH ${headline.text.length} GREATER THAN MAX ${config.tweetLength}:\n${headline.text}`);
	headline = NewsEngine.generateHeadline();
}

fileLogger(`tweet: ${JSON.stringify(headline)}`);

// Create twitter client
const twitter = new TwitterClient();

if (headline.tags && headline.tags.imgCard && headline.tags.imgCard.cardName) {
	postCardImageTweet(headline.text, headline.tags.imgCard.cardName);
} else if (headline.tags && headline.tags.htmlImg && headline.tags.htmlImg.htmlImgString) {
	const html = resolveCssUrls(headline.tags.htmlImg.htmlImgString.replace(/`/g, '"'));
	postHtmlImageTweet(headline.text, html, headline.tags.htmlImg.altText || 'image');
} else if (headline.tags && headline.tags.svg && headline.tags.svg.svgString) {
	postSvgTweet(headline.text, headline.tags.svg.svgString.replace(/`/g, '"'), headline.tags.svg.altText || 'image');
} else {
	twitter.postTweet(headline.text);
}<|endoftext|>


<commit_before>client.login("")

var prefix = "px;"

client.on("message", function(message) {

    if (message.author.equals(client.user)) return;

    if (!message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");

    switch (args[0]) {
        //ping command
        case "ping":
             const embed = new Discord.RichEmbed()
           	.setColor("#940000")
           	.setTitle(":ping_pong: Pong!", "Response time: " + client.ping + "ms")
           	.setFooter("Requested by " + message.author.username, message.author.displayAvatarURL)
           	.setTimestamp()
		message.channel.send({embed});
		break;
	// about command
	case "about":
	     const embed = new Discord.RichEmbed()
	        .setColor("#940000")
  		.setTitle("About PixaBot", "PixaBot is a Discord bot that features games, image manipulation, moderation and music commands written in JavaScript.")
           	.setFooter("Requested by " + message.author.username, message.author.displayAvatarURL)
           	.setTimestamp()
		message.channel.send({embed});
	// version command
        case "version":
            message.channel.send("The current version of PixaBot is " + 0.2  + " beta 1")
            break;
        case "kick":
		    message.channel.send("Coming Soon!")
			break;
		case "ban":
		    message.channel.send("Coming Soon!")
			break;
		case "help":
		    message.channel.send("coming soon!")
			break;
	    case "coming soon":
		    message.channel.send("kick: px;kick ban: px;ban and help command")
            break;
        case "CanIbeMod?":
		    message.channel.send("no but you can be jailed if you want (from kaiss)")
            break;
}
})
<commit_msg>Forgot the break;<commit_after>client.login("")

var prefix = "px;"

client.on("message", function(message) {

    if (message.author.equals(client.user)) return;

    if (!message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");

    switch (args[0]) {
        //ping command
        case "ping":
             const embed = new Discord.RichEmbed()
           	.setColor("#940000")
           	.setTitle(":ping_pong: Pong!", "Response time: " + client.ping + "ms")
           	.setFooter("Requested by " + message.author.username, message.author.displayAvatarURL)
           	.setTimestamp()
		message.channel.send({embed});
		break;
	// about command
	case "about":
	     const embed = new Discord.RichEmbed()
	        .setColor("#940000")
  		.setTitle("About PixaBot", "PixaBot is a Discord bot that features games, image manipulation, moderation and music commands written in JavaScript.")
           	.setFooter("Requested by " + message.author.username, message.author.displayAvatarURL)
           	.setTimestamp()
		message.channel.send({embed});
		break;
	// version command
        case "version":
            message.channel.send("The current version of PixaBot is " + 0.2  + " beta 1")
            break;
        case "kick":
		    message.channel.send("Coming Soon!")
			break;
		case "ban":
		    message.channel.send("Coming Soon!")
			break;
		case "help":
		    message.channel.send("coming soon!")
			break;
	    case "coming soon":
		    message.channel.send("kick: px;kick ban: px;ban and help command")
            break;
        case "CanIbeMod?":
		    message.channel.send("no but you can be jailed if you want (from kaiss)")
            break;
}
})
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const bot = new Discord.Client();
const prefix = "!";

bot.on('ready', () => {
        bot.user.setGame('!commands for help');
});

bot.on('message', (message) => {

    if (!message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");
    var query = message.content.substring(6);
    var charLook = message.content.substring(9);
    var 3dChar = message.content.substring(8);

    if (message.channel.id === '334783038162468864') {
        switch (args[0].toLowerCase()) {
            case "commands":
                message.channel.send("The following are the commands used in this channel.");
                message.channel.send({embed: {
                    color: 3447003,
                    fields: [{
                        name: "!aqwchar",
                        value: "Syntax: !aqwchar <Player>\nThis looks up the character page of your desire.",
                    },
                    {
                        name: "!sellback",
                        value: "Syntax: !sellback <Price> <AC/Gold>\nThis tells you the sellback price of the item. AC Items will tell produce 'Before/After 24 Hours' values.",
                    },
                    {
                        name: "!wiki",
                        value: "Syntax: !wiki <query>\nThis searches the AQW wikidot for the query you have inputed.",
                    }]
                }});
            break;
            case "aqwchar":
                var char = charLook.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("http://www.aq.com/character.asp?id=" + char.join("%20"));
                }
                else message.channel.sendMessage("Please specify a name after !aqwchar");
                break;
            case "sellback":
                var price = args[1];
                var curr = args[2];

                function isInt(price) {
                    return !isNaN(price) && price > 0 && (function(price) { return (price | 0) === price; })(parseFloat(price)); }

                if (isInt(price) == true) {
                    if ((/Gold/i).test(curr) == true) {
                        message.channel.sendMessage("The sellback price is** " + Math.ceil(price * 0.25) + " Gold.**");
                    }
                    else if ((/AC/i).test(curr) == true) {
                        message.channel.sendMessage("Before 24 hours: **" + Math.ceil(price * 0.90) + " AC**" + "\nAfter 24 hours: **" + Math.ceil(price * 0.25) + " AC**");
                    }
                    else message.reply("Please use the following syntax: !sellback <Price> <AC/Gold>")
                }
                else if (price > 0 || price == 0) {
                        message.channel.sendMessage("Please enter a non-zero positive integer.");
                }
                else message.channel.sendMessage("That's not a number!");
                break;
            case "wiki":
                var term = query.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("Wiki search: http://aqwwiki.wikidot.com/search:site/q/" + term.join("+")); }
                else message.channel.sendMessage("Please specify what you want to search after !wiki");
                break;
        }
    }

    if (message.channel.id === '355188935900790786') {
        switch (args[0].toLowerCase()) {
            case "commands":
                message.channel.send("The following are the commands used in this channel.");
                message.channel.send({embed: {
                    color: 3447003,
                    fields: [{
                        name: "!3dchar",
                        value: "Syntax: !3dchar <Player>\nThis looks up the character page of your desire.",
                    },
                    {
                        name: "!wiki",
                        value: "Syntax: !wiki <query>\nThis searches the AQ3D wikidot for the query you have inputed.",
                    }]
                }});
            break;
            case "3dchar":
                var char = 3dChar.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("https://game.aq3d.com/account/Character?id=" + char.join("%20"));
                }
                else message.channel.sendMessage("Please specify a name after !3dchar");
                break;
            case "wiki":
                var term = query.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("Wiki search: http://aq-3d.wikidot.com/search:site/q/" + term.join("%20")); }
                else message.channel.sendMessage("Please specify what you want to search after !wiki");
                break;
        }
    }
});

bot.login(process.env.BOT_TOKEN)<commit_msg>fixed splicer<commit_after>const Discord = require('discord.js');
const bot = new Discord.Client();
const prefix = "!";

bot.on('ready', () => {
        bot.user.setGame('!commands for help');
});

bot.on('message', (message) => {

    if (!message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");
    var query = message.content.substring(6);
    var charLook = message.content.substring(9);
    var aqChar = message.content.substring(8);

    if (message.channel.id === '334783038162468864') {
        switch (args[0].toLowerCase()) {
            case "commands":
                message.channel.send("The following are the commands used in this channel.");
                message.channel.send({embed: {
                    color: 3447003,
                    fields: [{
                        name: "!aqwchar",
                        value: "Syntax: !aqwchar <Player>\nThis looks up the character page of your desire.",
                    },
                    {
                        name: "!sellback",
                        value: "Syntax: !sellback <Price> <AC/Gold>\nThis tells you the sellback price of the item. AC Items will tell produce 'Before/After 24 Hours' values.",
                    },
                    {
                        name: "!wiki",
                        value: "Syntax: !wiki <query>\nThis searches the AQW wikidot for the query you have inputed.",
                    }]
                }});
            break;
            case "aqwchar":
                var char = charLook.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("http://www.aq.com/character.asp?id=" + char.join("%20"));
                }
                else message.channel.sendMessage("Please specify a name after !aqwchar");
                break;
            case "sellback":
                var price = args[1];
                var curr = args[2];

                function isInt(price) {
                    return !isNaN(price) && price > 0 && (function(price) { return (price | 0) === price; })(parseFloat(price)); }

                if (isInt(price) == true) {
                    if ((/Gold/i).test(curr) == true) {
                        message.channel.sendMessage("The sellback price is** " + Math.ceil(price * 0.25) + " Gold.**");
                    }
                    else if ((/AC/i).test(curr) == true) {
                        message.channel.sendMessage("Before 24 hours: **" + Math.ceil(price * 0.90) + " AC**" + "\nAfter 24 hours: **" + Math.ceil(price * 0.25) + " AC**");
                    }
                    else message.reply("Please use the following syntax: !sellback <Price> <AC/Gold>")
                }
                else if (price > 0 || price == 0) {
                        message.channel.sendMessage("Please enter a non-zero positive integer.");
                }
                else message.channel.sendMessage("That's not a number!");
                break;
            case "wiki":
                var term = query.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("Wiki search: http://aqwwiki.wikidot.com/search:site/q/" + term.join("+")); }
                else message.channel.sendMessage("Please specify what you want to search after !wiki");
                break;
        }
    }

    if (message.channel.id === '355188935900790786') {
        switch (args[0].toLowerCase()) {
            case "commands":
                message.channel.send("The following are the commands used in this channel.");
                message.channel.send({embed: {
                    color: 3447003,
                    fields: [{
                        name: "!3dchar",
                        value: "Syntax: !3dchar <Player>\nThis looks up the character page of your desire.",
                    },
                    {
                        name: "!wiki",
                        value: "Syntax: !wiki <query>\nThis searches the AQ3D wikidot for the query you have inputed.",
                    }]
                }});
            break;
            case "3dchar":
                var char = aqChar.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("https://game.aq3d.com/account/Character?id=" + char.join("%20"));
                }
                else message.channel.sendMessage("Please specify a name after !3dchar");
                break;
            case "wiki":
                var term = query.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("Wiki search: http://aq-3d.wikidot.com/search:site/q/" + term.join("%20")); }
                else message.channel.sendMessage("Please specify what you want to search after !wiki");
                break;
        }
    }
});

bot.login(process.env.BOT_TOKEN)<|endoftext|>


<commit_before>'use strict'

if (!process.env.TOKEN) {
    require('dotenv').config()
}

const destiny = require('./scripts/Destiny/destiny')
const halo = require('./scripts/Halo/halo')
const scripts = require('./scripts/scripts')
const Discord = require('discord.js')
const bot = new Discord.Client()

bot.login(process.env.TOKEN, function (token, err) {
  if(err){
      console.log(err)
  }
})

bot.on("ready", function() {
  console.log('LoreBot12-86 is ready and running!')

  //Today In Halo
  let channels =  bot.channels
  let lb_channel = channels.find('name', 'lore__halo')
  let lb_id = channels.find('name', 'lore__halo').id

  if (lb_channel) {
    setInterval(function() {
      halo.haloRequest(function (err, motd) {
        if (err) {
          return console.error(err)
        }
        lb_channel.sendMessage(motd).catch(console.error)
      })
    }, 1000*60*60*24, false)
  }
})

bot.on("message", function (message) {
    let input = message.content
    let channel = message.channel
    let user = message.author

    let quoteCmd = input.startsWith('!quotes')
    let helpCmd = input.startsWith('!lorehelp')
    let itemCmd = input.startsWith('!item')
    let cardCmd = input.startsWith('!card')
    let siteCmd = input.startsWith('!search')

    let reply = function(err, msg) {
        if(err) {
          return message.reply('something went wrong ```' + err + '```')
        } else {
          return channel.sendMessage(msg)
        }
    }

    // This really seems sloppy, but...
    if (quoteCmd) {
      if (input.indexOf('help') != -1) {
        user.sendMessage(destiny.quotesHelp())
      }else{
        destiny.quotes(input, reply)
      }
    }
    if (helpCmd) { user.sendMessage(destiny.help(input)) }
    if (itemCmd) { message.reply(destiny.searchItems(input)) }
    if (cardCmd) { message.reply(destiny.searchCard(input)) }
    if (siteCmd) { message.reply(destiny.searchGrimoire(input)) }
})

bot.on('error', function(error) {
  console.log('LoreBot returned an error: ', error)
})

bot.on('disconnect', function() {
  console.log('LoreBot12-86 has disconnected from Discord Services')
})
<commit_msg>correct call to find channel by name<commit_after>'use strict'

if (!process.env.TOKEN) {
    require('dotenv').config()
}

const destiny = require('./scripts/Destiny/destiny')
const halo = require('./scripts/Halo/halo')
const scripts = require('./scripts/scripts')
const Discord = require('discord.js')
const bot = new Discord.Client()

bot.login(process.env.TOKEN, function (token, err) {
  if(err){
      console.log(err)
  }
})

bot.on("ready", function() {
  console.log('LoreBot12-86 is ready and running!')

  //Today In Halo
  let channels =  bot.channels
  let lb_channel = channels.find('name', process.env.halo_channel)
  let lb_id = channels.find('name', process.env.halo_channel).id

  if (lb_channel) {
    setInterval(function() {
      halo.haloRequest(function (err, motd) {
        if (err) {
          return console.error(err)
        }
        lb_channel.sendMessage(motd).catch(console.error)
      })
    }, 1000*60*60*24)
  }
})

bot.on("message", function (message) {
    let input = message.content
    let channel = message.channel
    let user = message.author

    let quoteCmd = input.startsWith('!quotes')
    let helpCmd = input.startsWith('!lorehelp')
    let itemCmd = input.startsWith('!item')
    let cardCmd = input.startsWith('!card')
    let siteCmd = input.startsWith('!search')

    let reply = function(err, msg) {
        if(err) {
          return message.reply('something went wrong ```' + err + '```')
        } else {
          return channel.sendMessage(msg)
        }
    }

    // This really seems sloppy, but...
    if (quoteCmd) {
      if (input.indexOf('help') != -1) {
        user.sendMessage(destiny.quotesHelp())
      }else{
        destiny.quotes(input, reply)
      }
    }
    if (helpCmd) { user.sendMessage(destiny.help(input)) }
    if (itemCmd) { message.reply(destiny.searchItems(input)) }
    if (cardCmd) { message.reply(destiny.searchCard(input)) }
    if (siteCmd) { message.reply(destiny.searchGrimoire(input)) }
})

bot.on('error', function(error) {
  console.log('LoreBot returned an error: ', error)
})

bot.on('disconnect', function() {
  console.log('LoreBot12-86 has disconnected from Discord Services')
})
<|endoftext|>


<commit_before>/*
 * Avocado bot
 * copyright (c) 2015 Susisu
 */

"use strict";

var fs = require("fs");

var avocore    = require("avocore"),
    Action     = avocore.Action,
    pure       = avocore.pure,
    bind       = avocore.bind,
    then       = avocore.then,
    map        = avocore.map,
    filter     = avocore.filter,
    reduce     = avocore.reduce,
    merge      = avocore.merge,
    echo       = avocore.echo,
    cron       = avocore.cron,
    splitArray = avocore.splitArray;

var twitter = avocore.twitter;

var config = require("./config.json");

var keys =
    new twitter.KeySet(
        config["consumer_key"],
        config["consumer_secret"],
        config["access_token"],
        config["access_token_secret"]
    );

function readList(file) {
    return new Action(function (emit) {
        fs.readFile(file, { "encoding": "utf8" }, function (error, content) {
            if (!error) {
                emit(content.split("\n"));
            }
            else {
                console.log(error);
            }
        });
    });
}

function pickRandom(list) {
    return new Action(function (emit) {
        if (list.length > 0) {
            emit(list[Math.floor(Math.random() * list.length)]);
        }
    });
}

function tweet(status) {
    return twitter.post(keys, "statuses/update", {
        "status": status
    });
}

module.exports = [
    cron("00 */10 * * * *").then(readList("data/random.txt")).bind(pickRandom).bind(tweet)
];
<commit_msg>Create main program of the bot<commit_after>/*
 * Avocado bot
 * copyright (c) 2015 Susisu
 */

"use strict";

var avocore = require("avocore");

var twitter = avocore.twitter;

var config = require("./config.json");

var keys =
    new twitter.KeySet(
        config["consumer_key"],
        config["consumer_secret"],
        config["access_token"],
        config["access_token_secret"]
    );

module.exports = [
    avocore.cron("00 */10 * * * *")
        .then(twitter.tweetRandom(keys, "data/random.txt", "\n", "utf8")),
    avocore.cron("00 */5 * * * *")
        .then(avocore.readFile("data/reply_log.json", "utf8"))
        .bind(function (logJSON) {
            var logData;
            return new avocore.Action(function (emit) {
                    try {
                        logData = JSON.parse(logJSON);
                        if (logData["latest_reply_id_str"] !== undefined) {
                            emit(logData["latest_reply_id_str"]);
                        }
                        else {
                            console.log("\"latest_reply_id_str\" not found");
                        }
                    }
                    catch (error) {
                        console.log(error);
                    }
                })
                .bind(function (sinceIdStr) {
                    return twitter.replyMentions(keys, config["screen_name"],
                            100, sinceIdStr, require("./data/reply_patterns.js"))
                        .bind(function (latestIdStr) {
                            logData["latest_reply_id_str"] = latestIdStr;
                            return avocore.writeFile("data/reply_log.json",
                                    JSON.stringify(logData), "utf8");
                        });
                });
        }),
    avocore.cron("00 */5 * * * *")
        .then(avocore.readFile("data/reply_timeline_log.json", "utf8"))
        .bind(function (logJSON) {
            var logData;
            return new avocore.Action(function (emit) {
                    try {
                        logData = JSON.parse(logJSON);
                        if (logData["latest_reply_timeline_id_str"] !== undefined) {
                            emit(logData["latest_reply_timeline_id_str"]);
                        }
                        else {
                            console.log("\"latest_reply_timeline_id_str\" not found");
                        }
                    }
                    catch (error) {
                        console.log(error);
                    }
                })
                .bind(function (sinceIdStr) {
                    return twitter.replyHomeTimeline(keys, config["screen_name"],
                            100, sinceIdStr, require("./data/reply_timeline_patterns.js"))
                        .bind(function (latestIdStr) {
                            logData["latest_reply_timeline_id_str"] = latestIdStr;
                            return avocore.writeFile("data/reply_timeline_log.json",
                                    JSON.stringify(logData), "utf8");
                        });
                });
        }),
    avocore.cron("00 */10 * * * *")
        .then(twitter.followBack(keys, config["screen_name"], 20))
];
<|endoftext|>