<commit_before>"use strict";
var io = require('socket.io').listen(1337);
var LightStrips = require('./LPD8806').LightStrips;

var numberOfLEDs = 54;
var lights = new LightStrips('/dev/spidev0.0', numberOfLEDs);

var xbeeSerialPort = '/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A800csie-if00-port0';

var serialport = require('serialport');
var serialPort = new serialport.SerialPort(xbeeSerialPort,
{//Listening on the serial port for data coming from Arduino over USB
	baudRate: 57600,
	parser: serialport.parsers.readline('\n')
});

var off = function(){
   lights.off();
};

var half = numberOfLEDs/2;

var tailSize = 5,
	fade = 0.7;

var lightsOn = function(percentage, rgb){
	var i = 0;
	var ledArray = [];;
	var ledsOn = ~~((numberOfLEDs/2) * (percentage / 100));
	var ledsOff = half - ledsOn;

	var ts = ledsOff <= tailSize ? ledsOff  : tailSize;

	ledsOff = Math.max(ledsOff - tailSize, 0);

	for( i = 0; i < ledsOff; i++){
		ledArray.push([0,0,0]);
	}
	for( i = ts; i > 0; i--){
		//var level = ((tailSize - i) / tailSize) * fade;
		var level =((tailSize - i) / tailSize) * fade;
		ledArray.push([rgb[0] * level, rgb[1] * level, rgb[2] * level]);
	}
	for( i = 0; i < ledsOn; i++){
		ledArray.push(rgb);
	}

//	console.log(ledArray);
	var revercedLedArray = ledArray.slice(0).reverse();
	for( i = 0; i < half; i++){
		lights.set(i, ledArray[i][0],ledArray[i][1],ledArray[i][2]);
		lights.set(i + half , revercedLedArray[i][0],revercedLedArray[i][1],revercedLedArray[i][2]);
	}

	/*var start = 0;
	var end = ~~((numberOfLEDs/2) * (percentage / 100));
	lights.fill(0, 0, 0, start, half - end);
	lights.fill(rgb[0], rgb[1], rgb[2], half - end, half);

	lights.fill(rgb[0], rgb[1], rgb[2], half - end, end + half);
	lights.fill(0, 0, 0, end + half, numberOfLEDs);
	*/

	lights.sync();
};

var showAmplitude = function(data){
	var rgb = [255,0,0];
	if(data.rgb ){
        	rgb = data.rgb;
        }
	lightsOn(data.percentage, rgb);
};

io.sockets.on('connection', function (socket) {
	var rgb = [0,0,0];
	socket.on('volume', function (data) {
		//console.log(data);
		rgb = data.data.rgb;
		showAmplitude(data.data);
  	});
        socket.on('beat', function (msg) {
                //console.log(data);
		var data = msg.data;
		if(data.rgb && !((data.rgb[0] == 0) && (data.rgb[1] == 0) &&  (data.rgb[2] == 0)) ){
                	rgb = data.rgb;
        	}
        	try{
                        serialPort.write(new Buffer([4, rgb[0], rgb[1], rgb[2], 10]));
        	}catch(e){
                	console.log(e);
        	}

        });

	socket.on('disconnect', function () {
   		 off();
 	 });
});
<commit_msg>fixes<commit_after>"use strict";
var io = require('socket.io').listen(1337);
var LightStrips = require('./LPD8806').LightStrips;

var numberOfLEDs = 64;
var lights = new LightStrips('/dev/spidev0.0', numberOfLEDs);

var xbeeSerialPort = '/dev/serial/by-id/usb-FTDI_FT232R_USB_UART_A800csie-if00-port0';

var serialport = require('serialport');
var serialPort = new serialport.SerialPort(xbeeSerialPort,
{//Listening on the serial port for data coming from Arduino over USB
	baudRate: 57600,
	parser: serialport.parsers.readline('\n')
});

var off = function(){
   lights.off();
};

var half = numberOfLEDs/2;

var tailSize = 5,
	fade = 0.7;

var lightsOn = function(percentage, rgb){
	var i = 0;
	var ledArray = [];;
	var ledsOn = ~~((numberOfLEDs/2) * (percentage / 100));
	var ledsOff = half - ledsOn;

	var ts = ledsOff <= tailSize ? ledsOff  : tailSize;

	ledsOff = Math.max(ledsOff - tailSize, 0);

	for( i = 0; i < ledsOff; i++){
		ledArray.push([0,0,0]);
	}
	for( i = ts; i > 0; i--){
		//var level = ((tailSize - i) / tailSize) * fade;
		var level =((tailSize - i) / tailSize) * fade;
		ledArray.push([rgb[0] * level, rgb[1] * level, rgb[2] * level]);
	}
	for( i = 0; i < ledsOn; i++){
		ledArray.push(rgb);
	}

//	console.log(ledArray);
	var revercedLedArray = ledArray.slice(0).reverse();
	for( i = 0; i < half; i++){
		lights.set(i, ledArray[i][0],ledArray[i][1],ledArray[i][2]);
		lights.set(i + half , revercedLedArray[i][0],revercedLedArray[i][1],revercedLedArray[i][2]);
	}

	/*var start = 0;
	var end = ~~((numberOfLEDs/2) * (percentage / 100));
	lights.fill(0, 0, 0, start, half - end);
	lights.fill(rgb[0], rgb[1], rgb[2], half - end, half);

	lights.fill(rgb[0], rgb[1], rgb[2], half - end, end + half);
	lights.fill(0, 0, 0, end + half, numberOfLEDs);
	*/

	lights.sync();
};

var showAmplitude = function(data){
	var rgb = [255,0,0];
	if(data.rgb ){
        	rgb = data.rgb;
        }
	lightsOn(data.percentage, rgb);
};

io.sockets.on('connection', function (socket) {
	socket.on('volume', function (data) {
		//console.log(data);
		showAmplitude(data.data);
  	});
        socket.on('beat', function (msg) {
                //console.log(data);
		var data = msg.data;
		var level = data.percentage / 100;
               	var rgb = [Math.round(data.rgb[0] * level),
			   Math.round(data.rgb[1] * level),
			   Math.round(data.rgb[2] * level)];

        	try{
                        serialPort.write(new Buffer([4, rgb[0], rgb[1], rgb[2], 10]));
        	}catch(e){
                	console.log(e);
        	}

        });

	socket.on('disconnect', function () {
   		 off();
 	 });
});
<|endoftext|>


<commit_before>var fs = require('fs');
var EPub = require('epub');
var mkdirp = require('mkdirp');

// epub json
var books = [
    {
        'epubfile': './epub/A Game Of Thrones.epub',
        'imagewebroot': '',
        'chapterwebroot': '',
        'jsonfile': './a-game-of-thrones.json',
        'jsonfolder': 'books/a-game-of-thrones/'
    }, {
        'epubfile': './epub/A Clash of Kings.epub',
        'imagewebroot': '',
        'chapterwebroot': '',
        'jsonfile': './a-clash-of-kings.json',
        'jsonfolder': 'books/a-clash-of-kings/'
    }, {
        'epubfile': './epub/A Storm of Swords.epub',
        'imagewebroot': '',
        'chapterwebroot': '',
        'jsonfile': './a-storm-of-swords.json',
        'jsonfolder': 'books/a-storm-of-swords/'
    }, {
        'epubfile': './epub/A Feast for Crows.epub',
        'imagewebroot': '',
        'chapterwebroot': '',
        'jsonfile': './a-feast-for-crows.json',
        'jsonfolder': 'books/a-feast-for-crows/'
    }, {
        'epubfile': './epub/A Dance With Dragons.epub',
        'imagewebroot': '/OEBPS/Images/',
        'chapterwebroot': '/OEBPS/Text/',
        'jsonfile': './a-dance-with-dragons.json',
        'jsonfolder': 'books/a-dance-with-dragons/'
    }
];

// Apply the function epubFunc to each book in the books array
books.map(epubFunc);

function epubFunc(book) {
    var epub = new EPub(book.epubfile, book.imagewebroot, book.chapterwebroot);

    epub.on('end', function() {
        createBookMetadata(book, epub);
        createBookChapterFolder(book, epub);
        console.log(epub.metadata.title + ' Finished!');
    });
    epub.parse();
}

function createBookMetadata(book, epub) {
    // Create book folder
    var bookFolder = __dirname + '/' + book.jsonfolder;
    mkdirp.sync(bookFolder);
    // TODO: Turn the JSON coming from the epub into a finished product
    // Create the metadata file
    var epubMetadata = extractMetadata(epub);
    var epubMetadataFileLocation = bookFolder + 'metadata.json';
    fs.writeFile(epubMetadataFileLocation, epubMetadata);
    // TODO: Remove this second writeFile when we have a finished JSON
    // metadata file
    fs.writeFile(bookFolder + book.jsonfile, JSON.stringify(epub, null, 2));
}

function createBookChapterFolder(book, epub) {
    var chapterdir = book.jsonfolder + 'chapters/';
    mkdirp.sync(__dirname + '/' + chapterdir);
    epub.flow.forEach(function(chapter) {
        epub.getChapter(chapter.id, function(error, text) {
            var chapterfile = chapterdir;
            chapterfile += stripFilename(chapter.href);
            fs.writeFile(chapterfile, text, 'utf-8');
        });
    });
}

function extractMetadata(epub) {
    // Extract the metadata from the epub file
    var epubMetadata = epub.metadata;
    // Create a new JSON object to store the book metadata
    var json = {};
    // Add the title of the book to json
    var title = epubMetadata.title;
    // TODO: Strip the extra content
    json.title = title;
    // Turn json into a string to be stored
    var result = JSON.stringify(json, null, 2);
    return result;
}

// TODO: Abstract this function
function stripFilename(file) {
    var newFilename = '';
    var pos = file.lastIndexOf('/');
    if (pos == -1) {
        newFilename += file;
    } else {
        newFilename += file.slice(pos);
    }
    return newFilename;
}
<commit_msg>:art: Abstract the function that cleans filenames<commit_after>var fs = require('fs');
var EPub = require('epub');
var mkdirp = require('mkdirp');

// epub json
var books = [
    {
        'epubfile': './epub/A Game Of Thrones.epub',
        'imagewebroot': '',
        'chapterwebroot': '',
        'jsonfile': './a-game-of-thrones.json',
        'jsonfolder': 'books/a-game-of-thrones/'
    }, {
        'epubfile': './epub/A Clash of Kings.epub',
        'imagewebroot': '',
        'chapterwebroot': '',
        'jsonfile': './a-clash-of-kings.json',
        'jsonfolder': 'books/a-clash-of-kings/'
    }, {
        'epubfile': './epub/A Storm of Swords.epub',
        'imagewebroot': '',
        'chapterwebroot': '',
        'jsonfile': './a-storm-of-swords.json',
        'jsonfolder': 'books/a-storm-of-swords/'
    }, {
        'epubfile': './epub/A Feast for Crows.epub',
        'imagewebroot': '',
        'chapterwebroot': '',
        'jsonfile': './a-feast-for-crows.json',
        'jsonfolder': 'books/a-feast-for-crows/'
    }, {
        'epubfile': './epub/A Dance With Dragons.epub',
        'imagewebroot': '/OEBPS/Images/',
        'chapterwebroot': '/OEBPS/Text/',
        'jsonfile': './a-dance-with-dragons.json',
        'jsonfolder': 'books/a-dance-with-dragons/'
    }
];

// Apply the function epubFunc to each book in the books array
books.map(epubFunc);

function epubFunc(book) {
    var epub = new EPub(book.epubfile, book.imagewebroot, book.chapterwebroot);

    epub.on('end', function() {
        createBookMetadata(book, epub);
        createBookChapterFolder(book, epub);
        console.log(epub.metadata.title + ' Finished!');
    });
    epub.parse();
}

function createBookMetadata(book, epub) {
    // Create book folder
    var bookFolder = __dirname + '/' + book.jsonfolder;
    mkdirp.sync(bookFolder);
    // TODO: Turn the JSON coming from the epub into a finished product
    // Create the metadata file
    var epubMetadata = extractMetadata(epub);
    var epubMetadataFileLocation = bookFolder + 'metadata.json';
    fs.writeFile(epubMetadataFileLocation, epubMetadata);
    // TODO: Remove this second writeFile when we have a finished JSON
    // metadata file
    fs.writeFile(bookFolder + book.jsonfile, JSON.stringify(epub, null, 2));
}

function createBookChapterFolder(book, epub) {
    var chapterdir = book.jsonfolder + 'chapters/';
    mkdirp.sync(__dirname + '/' + chapterdir);
    epub.flow.forEach(function(chapter) {
        epub.getChapter(chapter.id, function(error, text) {
            var chapterfile = chapterdir;
            chapterfile += cleanString(chapter.href, '/', true);
            fs.writeFile(chapterfile, text, 'utf-8');
        });
    });
}

function extractMetadata(epub) {
    // Extract the metadata from the epub file
    var epubMetadata = epub.metadata;
    // Create a new JSON object to store the book metadata
    var json = {};
    // Add the title of the book to json
    var title = epubMetadata.title;
    json.title = cleanString(title, ':');
    // Turn json into a string to be stored
    var result = JSON.stringify(json, null, 2);
    return result;
}

/**
 * Strips a string from content before or after a chosen substring.
 * @arg {string} string - The original string to be stripped.
 * @arg {string} substring - The string that will separate the part of the
    original string that you want to keep from the rest of the original
    string.
 * @arg {boolean} fromTheEnd - Start the search for the substring at the end of
    the original string. The default value is false.
 * @return {string} A string without the content before or after a chosen
    substring. If the original string did not contain said substring, a copy
    of the original string is returned instead.
 */
function cleanString(string, substring, fromTheEnd) {
    var newString = string;
    var pos;
    if (fromTheEnd) {
        pos = string.lastIndexOf(substring);
        if (pos != -1) {
            newString = string.slice(pos);
        }
    } else {
        pos = string.indexOf(substring);
        if (pos != -1) {
            newString = string.slice(0, pos);
        }
    }
    return newString;
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 */

// some environments run the app from a different directory
process.chdir(__dirname);

var config = require('./configs').create();
var settings = config.get('settings');

require('node-jsx').install({ extension: '.jsx' });

var protocol = require(settings.web.ssl ? 'https' : 'http');
var path = require('path');
var fs = require('fs');
var express = require('express');
var favicon = require('serve-favicon');
var compress = require('compression');
var logger = require('morgan');
var serialize = require('serialize-javascript');
var navigateAction = require('flux-router-component').navigateAction;
var debug = require('debug')('Example');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var errorHandler = require('express-error-handler');
var React = require('react');
var fluxibleApp = require('./app');
var HtmlComponent = React.createFactory(require('./components/Html.jsx'));

var app = express();
var server = protocol.createServer(app);

app.set('state namespace', 'App');
app.use(favicon(path.join(__dirname, settings.dist.favicon)));
app.use(logger(settings.loggerFormat));
app.use(compress());
app.use(errorHandler.maintenance());
app.use(settings.web.baseDir, express.static(
  path.join(__dirname, settings.dist.baseDir), { maxAge: settings.web.assetAge }
));
app.use(cookieParser({ httpOnly: true, secure: settings.web.ssl }));
app.use(bodyParser.json());
app.use(csrf({cookie: true}));

// Access fetchr plugin instance, register services, and setup middleware
var fetchrPlugin = fluxibleApp.getPlugin('FetchrPlugin');
// fetchrPlugin.registerService(require('./services/docs'));
// fetchrPlugin.registerService(require('./services/api'));
app.use(fetchrPlugin.getXhrPath(), fetchrPlugin.getMiddleware());

// Every other request gets the app bootstrap
app.use(function main(req, res, next) {
  var context = fluxibleApp.createContext({
    req: req, // The fetchr plugin depends on this
    xhrContext: {
      _csrf: req.csrfToken() // Make sure all XHR requests have the CSRF token
    }
  });

  debug('Executing navigate action');
  context.executeAction(navigateAction, {
    url: req.url
  }, function (err) {
    if (err) {
      return next(err);
    }

    debug('Exposing context state');
    var exposed = 'window.App=' + serialize(fluxibleApp.dehydrate(context)) + ';';

    debug('Rendering Application component into html');
    var AppComponent = fluxibleApp.getAppComponent();
    var doctype = '<!DOCTYPE html>';
    React.withContext(context.getComponentContext(), function () {
      var html = React.renderToStaticMarkup(HtmlComponent({
        mainScript: settings.web.assets.mainScript(),
        trackingSnippet: config.get('analytics:snippet'),
        styles: fs.readFileSync(settings.dist.css, { encoding: 'utf8' }),
        state: exposed,
        markup: React.renderToString(AppComponent({
            context: context.getComponentContext()
        }))
      }));
      res.send(doctype + html);
    });
  });
});

app.use(errorHandler({
  server: server,
  static: {
    '404': settings.dist.four04,
    '503': settings.dist.five03
  }
}));

server.listen(config.get('PORT'), function() {
  console.log('Listening on port ' + config.get('PORT'));
});
<commit_msg>Updated debug namespace to server<commit_after>/**
 * Copyright (c) 2015 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 */

// some environments run the app from a different directory
process.chdir(__dirname);

var config = require('./configs').create();
var settings = config.get('settings');

require('node-jsx').install({ extension: '.jsx' });

var protocol = require(settings.web.ssl ? 'https' : 'http');
var path = require('path');
var fs = require('fs');
var express = require('express');
var favicon = require('serve-favicon');
var compress = require('compression');
var logger = require('morgan');
var serialize = require('serialize-javascript');
var navigateAction = require('flux-router-component').navigateAction;
var debug = require('debug')('Server');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var errorHandler = require('express-error-handler');
var React = require('react');
var fluxibleApp = require('./app');
var HtmlComponent = React.createFactory(require('./components/Html.jsx'));

var app = express();
var server = protocol.createServer(app);

app.set('state namespace', 'App');
app.use(favicon(path.join(__dirname, settings.dist.favicon)));
app.use(logger(settings.loggerFormat));
app.use(compress());
app.use(errorHandler.maintenance());
app.use(settings.web.baseDir, express.static(
  path.join(__dirname, settings.dist.baseDir), { maxAge: settings.web.assetAge }
));
app.use(cookieParser({ httpOnly: true, secure: settings.web.ssl }));
app.use(bodyParser.json());
app.use(csrf({cookie: true}));

// Access fetchr plugin instance, register services, and setup middleware
var fetchrPlugin = fluxibleApp.getPlugin('FetchrPlugin');
// fetchrPlugin.registerService(require('./services/docs'));
// fetchrPlugin.registerService(require('./services/api'));
app.use(fetchrPlugin.getXhrPath(), fetchrPlugin.getMiddleware());

// Every other request gets the app bootstrap
app.use(function main(req, res, next) {
  var context = fluxibleApp.createContext({
    req: req, // The fetchr plugin depends on this
    xhrContext: {
      _csrf: req.csrfToken() // Make sure all XHR requests have the CSRF token
    }
  });

  debug('Executing navigate action');
  context.executeAction(navigateAction, {
    url: req.url
  }, function (err) {
    if (err) {
      return next(err);
    }

    debug('Exposing context state');
    var exposed = 'window.App=' + serialize(fluxibleApp.dehydrate(context)) + ';';

    debug('Rendering Application component into html');
    var AppComponent = fluxibleApp.getAppComponent();
    var doctype = '<!DOCTYPE html>';
    React.withContext(context.getComponentContext(), function () {
      var html = React.renderToStaticMarkup(HtmlComponent({
        mainScript: settings.web.assets.mainScript(),
        trackingSnippet: config.get('analytics:snippet'),
        styles: fs.readFileSync(settings.dist.css, { encoding: 'utf8' }),
        state: exposed,
        markup: React.renderToString(AppComponent({
            context: context.getComponentContext()
        }))
      }));
      res.send(doctype + html);
    });
  });
});

app.use(errorHandler({
  server: server,
  static: {
    '404': settings.dist.four04,
    '503': settings.dist.five03
  }
}));

server.listen(config.get('PORT'), function() {
  console.log('Listening on port ' + config.get('PORT'));
});
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var MailChimpWebhook = require('mailchimp').MailChimpWebhook;
    var CapsuleCRM = require('capsule-crm');

    var config = require('./config');

    var webhook = new MailChimpWebhook(config.webhook);
    var capsule = CapsuleCRM.createConnection(config.capsule.account, config.capsule.token);

    console.log('UCN Hooks server listening on port ' + config.webhook.port + '...');

    var _syncPartyDataTags = function(type, party_data, webhook_data) {
        console.log('type', type);
        console.log('party_data', party_data);
        console.log('webhook_data', webhook_data);
        console.log('GROUPINGS', webhook_data.merges.GROUPINGS);

        if (typeof party_data.parties.person !== 'undefined' && party_data.parties.person.id) {
            var person_id = party_data.parties.person.id;
            var mailing_list = config.mailchimp.lists[webhook_data.list_id];

            var note_action = '';
            var segments = [];
            switch (type) {
                case 'subscribe':
                    note_action = 'subscribed to';
                    segments = _extractSegments(webhook_data);
                    break;
                case 'profile':
                    note_action = 'updated their preferences for';
                    segments = _extractSegments(webhook_data);
                    break;
                case 'unsubscribe':
                    note_action = 'unsubscribed from';
                    segments = [ 'unsubscribed' ];
                    break;
                case 'cleaned':
                    note_action = 'been cleaned from';
                    segments = [ 'cleaned' ];
                    break;
                default:
                    break;
            }

            if (note_action) {
                var note = { historyItem: { note: 'Contact has ' + note_action + ' mailing list ' + mailing_list.name + '' } };
                capsule.addHistoryFor('party', person_id, note, function(err, history_data) {
                    console.log('addHistoryFor err', err);
                    console.log('addHistoryFor data', history_data);
                });
            }

            var tag_name = mailing_list.tag;
            if (tag_name && config.capsule.datatags[tag_name]) {
                var tags = { customFields: { customField: _segmentsToFields(segments, tag_name) } };
                console.log('tags', tags);
                capsule.setCustomFieldFor('party', person_id, tags, function(err, custom_field_data) {
                    console.log('setCustomFieldFor err', err);
                    console.log('setCustomFieldFor data', custom_field_data);
                    capsule.setPartyTag(person_id, tag_name, function(err, party_tag_data) {
                        console.log('setPartyTag err', err);
                        console.log('setPartyTag data', party_tag_data);
                    });
                });
            }
        }
    };

    var _extractSegments = function(data) {
        var segments = [];
        if (typeof data.merges !== 'undefined' && data.merges.GROUPINGS) {
            data.merges.GROUPINGS.forEach(function(grouping) {
                console.log('grouping', grouping);
                if (grouping.groups) {
                    var groups = grouping.groups.split(',');
                    groups.forEach(function(group) {
                        segments.push(group.trim());
                    });
                }
            });
        }
        console.log('segments', segments);
        return segments;
    };

    var _segmentsToFields = function(segments, tag_name) {
        var fields = [];
        config.capsule.datatags[tag_name].forEach(function(tag_label) {
            var field = {
                tag: tag_name,
                label: tag_label
            };

            if (tag_label == 'unsubscribed' && segments.length === 0) {
                field.boolean = true;
            }
            else {
                if (segments.indexOf(tag_label) >= 0) {
                    field.boolean = true;
                }
            }
            fields.push(field);
        });
        console.log('fields', fields);
        return fields;
    };

    var _addPartyEmailAddress = function(party_data, webhook_data) {
        console.log('party_data', party_data);
        console.log('webhook_data', webhook_data);

        if (typeof party_data.parties.person !== 'undefined' && party_data.parties.person.id) {
            var person_id = party_data.parties.person.id;
            var mailing_list = config.mailchimp.lists[webhook_data.list_id];

            var note = { historyItem: { note: 'Email address updated by mailchimp from ' + webhook_data.old_email + ' to ' + webhook_data.new_email + ' on mailing list ' + mailing_list.name + '' } };
            capsule.addHistoryFor('party', person_id, note, function(err, history_data) {
                console.log('addHistoryFor err', err);
                console.log('addHistoryFor data', history_data);
            });

            capsule.addEmailFor('person', person_id, webhook_data.new_email, function(err, email_data) {
                console.log('addEmailFor err', err);
                console.log('addEmailFor data', email_data);
            });
        }
    };

    webhook.on('error', function (error) {
        console.log('error', error);
    });

    webhook.on('subscribe', function (webhook_data, webhook_meta) {
        console.log(webhook_data.email + ' subscribed to your newsletter!');
        capsule.personByEmail(webhook_data.email, function(err, party_data) {
            console.log('personByEmail err', err);
            if (!err) {
                _syncPartyDataTags(webhook_meta.type, party_data, webhook_data);
            }
        });
    });
    webhook.on('unsubscribe', function (webhook_data, webhook_meta) {
        console.log(webhook_data.email + ' unsubscribed from your newsletter!');
        capsule.personByEmail(webhook_data.email, function(err, party_data) {
            console.log('personByEmail err', err);
            if (!err) {
                _syncPartyDataTags(webhook_meta.type, party_data, webhook_data);
            }
        });
    });

    webhook.on('profile', function (webhook_data, webhook_meta) {
        console.log(webhook_data.email + ' updated his profile!');
        capsule.personByEmail(webhook_data.email, function(err, party_data) {
            console.log('personByEmail err', err);
            if (!err) {
                _syncPartyDataTags(webhook_meta.type, party_data, webhook_data);
            }
        });
    });
    webhook.on('upemail', function (webhook_data, webhook_meta) {
        console.log('[ upemail ] ' + webhook_data.old_email + ' updated his email address to ' + webhook_data.new_email + '!');
        console.log('[ upemail ] webhook_data', webhook_data);
        console.log('[ upemail ] webhook_meta', webhook_meta);
        capsule.personByEmail(webhook_data.old_email, function(err, party_data) {
            if (!err) {
                _addPartyEmailAddress(party_data, webhook_data);
            }
        });
    });

    webhook.on('cleaned', function (webhook_data, webhook_meta) {
        console.log(webhook_data.email + ' has been cleaned from your newsletter!');
        capsule.personByEmail(webhook_data.email, function(err, party_data) {
            console.log('personByEmail err', err);
            if (!err) {
                _syncPartyDataTags(webhook_meta.type, party_data, webhook_data);
            }
        });
    });

    webhook.on('campaign', function (webhook_data, webhook_meta) {
        console.log('status of campaign \'' + data.subject + '\' has been changed!');
        console.log('webhook_data', webhook_data);
        console.log('webhook_meta', webhook_meta);
    });
})();
<commit_msg>Additional note added to Capsule on hard bounces [#113206659]<commit_after>(function() {
    'use strict';

    var MailChimpWebhook = require('mailchimp').MailChimpWebhook;
    var CapsuleCRM = require('capsule-crm');

    var config = require('./config');

    var webhook = new MailChimpWebhook(config.webhook);
    var capsule = CapsuleCRM.createConnection(config.capsule.account, config.capsule.token);

    console.log('UCN Hooks server listening on port ' + config.webhook.port + '...');

    var _syncPartyDataTags = function(type, party_data, webhook_data) {
        console.log('type', type);
        console.log('party_data', party_data);
        console.log('webhook_data', webhook_data);

        if (typeof party_data.parties.person !== 'undefined' && party_data.parties.person.id) {
            var person_id = party_data.parties.person.id;
            var mailing_list = config.mailchimp.lists[webhook_data.list_id];

            var note_action = '';
            var segments = [];
            switch (type) {
                case 'subscribe':
                    note_action = 'subscribed to';
                    segments = _extractSegments(webhook_data);
                    break;
                case 'profile':
                    note_action = 'updated their preferences for';
                    segments = _extractSegments(webhook_data);
                    break;
                case 'unsubscribe':
                    note_action = 'unsubscribed from';
                    segments = [ 'unsubscribed' ];
                    break;
                case 'cleaned':
                    if (webhook_data.reason == 'hard') {
                        var hard_note = { historyItem: { note: 'Cannot deliver to email address ' + webhook_data.email + ' for mailing list ' + mailing_list.name + '' } };
                        capsule.addHistoryFor('party', person_id, hard_note, function(err, history_data) {
                            console.log('addHistoryFor err', err);
                            console.log('addHistoryFor data', history_data);
                        });
                    }
                    note_action = 'been cleaned from';
                    segments = [ 'cleaned' ];
                    break;
                default:
                    break;
            }

            if (note_action) {
                var note = { historyItem: { note: 'Contact has ' + note_action + ' mailing list ' + mailing_list.name + '' } };
                capsule.addHistoryFor('party', person_id, note, function(err, history_data) {
                    console.log('addHistoryFor err', err);
                    console.log('addHistoryFor data', history_data);
                });
            }

            var tag_name = mailing_list.tag;
            if (tag_name && config.capsule.datatags[tag_name]) {
                var tags = { customFields: { customField: _segmentsToFields(segments, tag_name) } };
                console.log('tags', tags);
                capsule.setCustomFieldFor('party', person_id, tags, function(err, custom_field_data) {
                    console.log('setCustomFieldFor err', err);
                    console.log('setCustomFieldFor data', custom_field_data);
                    capsule.setPartyTag(person_id, tag_name, function(err, party_tag_data) {
                        console.log('setPartyTag err', err);
                        console.log('setPartyTag data', party_tag_data);
                    });
                });
            }
        }
    };

    var _extractSegments = function(data) {
        var segments = [];
        if (typeof data.merges !== 'undefined' && data.merges.GROUPINGS) {
            console.log('GROUPINGS', webhook_data.merges.GROUPINGS);
            data.merges.GROUPINGS.forEach(function(grouping) {
                console.log('grouping', grouping);
                if (grouping.groups) {
                    var groups = grouping.groups.split(',');
                    groups.forEach(function(group) {
                        segments.push(group.trim());
                    });
                }
            });
        }
        console.log('segments', segments);
        return segments;
    };

    var _segmentsToFields = function(segments, tag_name) {
        var fields = [];
        config.capsule.datatags[tag_name].forEach(function(tag_label) {
            var field = {
                tag: tag_name,
                label: tag_label
            };

            if (tag_label == 'unsubscribed' && segments.length === 0) {
                field.boolean = true;
            }
            else {
                if (segments.indexOf(tag_label) >= 0) {
                    field.boolean = true;
                }
            }
            fields.push(field);
        });
        console.log('fields', fields);
        return fields;
    };

    var _addPartyEmailAddress = function(party_data, webhook_data) {
        console.log('party_data', party_data);
        console.log('webhook_data', webhook_data);

        if (typeof party_data.parties.person !== 'undefined' && party_data.parties.person.id) {
            var person_id = party_data.parties.person.id;
            var mailing_list = config.mailchimp.lists[webhook_data.list_id];

            var note = { historyItem: { note: 'Email address updated by mailchimp from ' + webhook_data.old_email + ' to ' + webhook_data.new_email + ' on mailing list ' + mailing_list.name + '' } };
            capsule.addHistoryFor('party', person_id, note, function(err, history_data) {
                console.log('addHistoryFor err', err);
                console.log('addHistoryFor data', history_data);
            });

            capsule.addEmailFor('person', person_id, webhook_data.new_email, function(err, email_data) {
                console.log('addEmailFor err', err);
                console.log('addEmailFor data', email_data);
            });
        }
    };

    webhook.on('error', function (error) {
        console.log('error', error);
    });

    webhook.on('subscribe', function (webhook_data, webhook_meta) {
        console.log(webhook_data.email + ' subscribed to your newsletter!');
        capsule.personByEmail(webhook_data.email, function(err, party_data) {
            console.log('personByEmail err', err);
            if (!err) {
                _syncPartyDataTags(webhook_meta.type, party_data, webhook_data);
            }
        });
    });
    webhook.on('unsubscribe', function (webhook_data, webhook_meta) {
        console.log(webhook_data.email + ' unsubscribed from your newsletter!');
        capsule.personByEmail(webhook_data.email, function(err, party_data) {
            console.log('personByEmail err', err);
            if (!err) {
                _syncPartyDataTags(webhook_meta.type, party_data, webhook_data);
            }
        });
    });

    webhook.on('profile', function (webhook_data, webhook_meta) {
        console.log(webhook_data.email + ' updated his profile!');
        capsule.personByEmail(webhook_data.email, function(err, party_data) {
            console.log('personByEmail err', err);
            if (!err) {
                _syncPartyDataTags(webhook_meta.type, party_data, webhook_data);
            }
        });
    });
    webhook.on('upemail', function (webhook_data, webhook_meta) {
        console.log('[ upemail ] ' + webhook_data.old_email + ' updated his email address to ' + webhook_data.new_email + '!');
        console.log('[ upemail ] webhook_data', webhook_data);
        console.log('[ upemail ] webhook_meta', webhook_meta);
        capsule.personByEmail(webhook_data.old_email, function(err, party_data) {
            if (!err) {
                _addPartyEmailAddress(party_data, webhook_data);
            }
        });
    });

    webhook.on('cleaned', function (webhook_data, webhook_meta) {
        console.log(webhook_data.email + ' has been cleaned from your newsletter!');
        capsule.personByEmail(webhook_data.email, function(err, party_data) {
            console.log('personByEmail err', err);
            if (!err) {
                _syncPartyDataTags(webhook_meta.type, party_data, webhook_data);
            }
        });
    });

    webhook.on('campaign', function (webhook_data, webhook_meta) {
        console.log('status of campaign \'' + data.subject + '\' has been changed!');
        console.log('webhook_data', webhook_data);
        console.log('webhook_meta', webhook_meta);
    });
})();
<|endoftext|>


<commit_before>'use strict';

var Hapi = require('hapi');
var routes = require('./routes');
var config = require('./config');
var server = new Hapi.Server();

server.connection({
  port:config.SERVER_PORT,
  routes:{cors:true}
});

server.route(routes);

function startServer(){
  server.start(function () {
    console.log('Server running at:', server.info.uri);
  });
}

function stopServer(){
  server.stop(function () {
    console.log('Server stopped');
  });
}

module.exports.start = startServer;

module.exports.stop =  stopServer;<commit_msg>Changes to please jscs<commit_after>'use strict';

var Hapi = require('hapi');
var routes = require('./routes');
var config = require('./config');
var server = new Hapi.Server();

server.connection({
  port:config.SERVER_PORT,
  routes:{cors:true}
});

server.route(routes);

function startServer() {
  server.start(function() {
    console.log('Server running at:', server.info.uri);
  });
}

function stopServer() {
  server.stop(function() {
    console.log('Server stopped');
  });
}

module.exports.start = startServer;

module.exports.stop =  stopServer;
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var mailConfig = require('./config/mailConfig');
var nodemailer = require('nodemailer');

var port = process.env.PORT || 5000;

var transporter = nodemailer.createTransport(mailConfig);

app.get('/', function(req, res) {
	res.send('hello world');
});

// setup e-mail data with unicode symbols
var mailOptions = {
    from: 'Merry Crosstmas ✔ <kikou@lol.fr>', // sender address
    to: 'sam@yopmail.com', // list of receivers
    subject: 'Hello ✔', // Subject line
    text: 'Hello world ✔', // plaintext body
    html: 'Hello world ✔' // html body
};

app.post('/send', function(req, res) {
	// send mail with defined transport object
	transporter.sendMail(mailOptions, function(error, info) {
		if (error) {
			console.log('sendMail', error);
		} else {
			console.log('Message sent: ' + info.response);
		}
	});
});

process.on('uncaughtException', function (err) {
    console.log('uncaughtException', err);
});

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port :', port);
<commit_msg>test sensgrid<commit_after>var express = require('express');
var app = express();
var mailConfig = require('./config/mailConfig');
var nodemailer = require('nodemailer');

var port = process.env.PORT || 5000;

var transporter = nodemailer.createTransport(mailConfig);

app.get('/', function(req, res) {
	res.send('hello world');
});

// setup e-mail data with unicode symbols
var mailOptions = {
    from: 'Merry Crosstmas ✔ <kikou@lol.fr>', // sender address
    to: 'martineau.samuel.1990+test@gmail.com', // list of receivers
    subject: 'Hello ✔', // Subject line
    text: 'Hello world ✔', // plaintext body
    html: 'Hello world ✔' // html body
};

app.post('/send', function(req, res) {

	// send mail with defined transport object
	transporter.sendMail(mailOptions, function(error, info) {
		if (error) {
			console.log('sendMail', error);
		} else {
			console.log('Message sent: ' + info.response);
		}
	});
});

process.on('uncaughtException', function (err) {
    console.log('uncaughtException', err);
});

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port :', port);
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var shuffle = require('shuffle-array');
var spawn = require('child_process').spawn;
var net = require('net');
var notifier = require('node-notifier');
var config = require('config-prompt')({
    musicPath: { type: 'string', required: true },
    keepFeature: { type: 'boolean', default: true, required: true },
    deleteFeature: { type: 'boolean', default: true, required: true },
    shuffleMusic: { type: 'boolean', default: true }
});
// var argv = require('minimist')(process.argv.slice(2));
// console.log(argv);

/***
 *    ___▄▄▄▄▄___▄███▄___█▄▄▄▄____▄___▄███▄___█▄▄▄▄_
 *    __█_____▀▄_█▀___▀__█__▄▀_____█__█▀___▀__█__▄▀_
 *    ▄__▀▀▀▀▄___██▄▄____█▀▀▌_█_____█_██▄▄____█▀▀▌__
 *    _▀▄▄▄▄▀____█▄___▄▀_█__█__█____█_█▄___▄▀_█__█__
 *    ___________▀███▀_____█____█__█__▀███▀_____█___
 *    ____________________▀______█▐____________▀____
 *    ___________________________▐__________________
 */
var port = 6666;
var server = net.createServer();
server.on('connection', handleConnection);
server.listen(port, function () {
    console.log('Musitop server listen on ' + port);
});
function handleConnection (connection) {
    // var remoteAddress = connection.remoteAddress + ':' + connection.remotePort;
    // notify('New connection','From ' + remoteAddress);
    connection.on('data', function (data) {
        var message = data.toString();
        if (message === 'good') {
            notify('Client', 'Keep this song :D');
            keepSong();
        } else if (message === 'bad') {
            notify('Client', 'Delete this song :|');
            deleteSong();
        } else if (message === 'next') {
            notify('Client', 'Next song please :)');
            player.kill();
        } else {
            notify('Error', 'Client said non-handled message "' + message + '"', 'error');
        }
    });
    connection.on('error', function (e) {
        notify('Error', 'Client error, see logs', 'error');
        console.log(e);
    });
}

/***
 *    █_▄▄__█____██__▀▄____▄_▄███▄___█▄▄▄▄_
 *    █___█_█____█_█___█__█__█▀___▀__█__▄▀_
 *    █▀▀▀__█____█▄▄█___▀█___██▄▄____█▀▀▌__
 *    █_____███▄_█__█___█____█▄___▄▀_█__█__
 *    _█________▀___█_▄▀_____▀███▀_____█___
 *    __▀__________█__________________▀____
 *    ____________▀________________________
 */
var playlist = [];
var song = '';
var player = null;
var keep = false;

function playFolder () {
    var musicPath = config.get('musicPath');
    notify('Scanning', '"' + musicPath + '"' + ' for songs');
    fs.readdir(musicPath, function (err, files) {
        if (err) {
            config.trash();
            notify('Error', 'Fail at reading musicPath, see logs', 'error');
            throw new Error(err);
        }
        files.forEach(function (fileName) {
            //noinspection JSCheckFunctionSignatures
            var filePath = path.join(musicPath, fileName);
            var fileStat = fs.statSync(filePath);
            if (fileStat.isFile()) {
                playlist.push(filePath)
            }
        });
        if (config.get('shuffleMusic')) {
            shuffle(playlist);
        }
        playNext();
    });
}

function fileName (filePath) {
    // input  : "C:\Stuff\Music\to test\Mike feat. Snowball - Animal.mp3"
    // output : "Mike feat. Snowball - Animal"
    return path.basename(filePath).split('.').reverse().splice(1).reverse().join('.');
}

function playNext () {
    // by default, don't keep newly playing song
    keep = false;
    // here splice return first item & remove it from playlist
    song = playlist.splice(0, 1)[0];
    playSong();
    setTimeout(function () {
        notify('Remaining', playlist.length + ' track(s)');
        notify('Playing', fileName(song), 'info');
    }, 1100);
}

function keepSong () {
    keep = true;
}

function moveSong () {
    doAsync(function (lastSongPath) {
        //noinspection JSCheckFunctionSignatures
        fs.rename(lastSongPath, path.join(path.dirname(lastSongPath) + '/keep', path.basename(lastSongPath)), function (err) {
            if (err) throw err;
            notify('Moved', fileName(lastSongPath));
        });
    });
    playNext();
}

function deleteSong () {
    keep = false;
    doAsync(function (lastSongPath) {
        fs.unlink(lastSongPath, function (err) {
            if (err) throw err;
            notify('Deleted', fileName(lastSongPath));
        });
    });
    player.kill();
}

function doAsync (callback) {
    if (!callback) {
        notify('Error', 'Do Async need a callback', 'error');
    } else {
        var lastSongPath = song + '';
        setTimeout(function () {
            callback(lastSongPath);
        }, 1000);
    }
}

function notify (action, message, type) {
    if (type) {
        // notify client side
        notifier.notify({
            title: action,
            message: message,
            type: type
        });
    }
    // in order to align logs :p
    while (action.length < 9) {
        action += ' ';
    }
    console.log(action + ' : ' + message);
}

function playSong () {
    player = spawn('lib/1by1/1by1.exe', [song, '/hide', '/close']);
    player.stderr.on('data', function (stderr) {
        notify('Stderr', stderr, 'error');
    });
    player.on('close', function (code) {
        if (code === null || code === 0) {
            if (keep) {
                moveSong();
            } else {
                playNext();
            }
        } else {
            notify('Error', 'Player process exited with non-handled code "' + code + '"', 'error');
        }
    });
}

function getConfig () {
    config.prompt({ all: true, nodeEnv: false, silent: false }, function (err) {
        if (err) {
            config.trash();
            notify('Error', 'Fail at reading config, see logs', 'error');
            throw new Error(err);
        }
        notify('Config path', config.path);
        playFolder();
    });
}

// init
setTimeout(getConfig, 100);
spawn('node_modules/electron/dist/electron', ['systray']); // add systray controls

<commit_msg>added keepPath config<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var shuffle = require('shuffle-array');
var spawn = require('child_process').spawn;
var net = require('net');
var notifier = require('node-notifier');
var config = require('config-prompt')({
    musicPath: { type: 'string', required: true },
    keepPath: { type: 'string', required: false },
    keepFeature: { type: 'boolean', default: true, required: true },
    deleteFeature: { type: 'boolean', default: true, required: true },
    shuffleMusic: { type: 'boolean', default: true }
});
// var argv = require('minimist')(process.argv.slice(2));
// console.log(argv);

/***
 *    ___▄▄▄▄▄___▄███▄___█▄▄▄▄____▄___▄███▄___█▄▄▄▄_
 *    __█_____▀▄_█▀___▀__█__▄▀_____█__█▀___▀__█__▄▀_
 *    ▄__▀▀▀▀▄___██▄▄____█▀▀▌_█_____█_██▄▄____█▀▀▌__
 *    _▀▄▄▄▄▀____█▄___▄▀_█__█__█____█_█▄___▄▀_█__█__
 *    ___________▀███▀_____█____█__█__▀███▀_____█___
 *    ____________________▀______█▐____________▀____
 *    ___________________________▐__________________
 */
var port = 6666;
var server = net.createServer();
server.on('connection', handleConnection);
server.listen(port, function () {
    console.log('Musitop server listen on ' + port);
});
function handleConnection (connection) {
    // var remoteAddress = connection.remoteAddress + ':' + connection.remotePort;
    // notify('New connection','From ' + remoteAddress);
    connection.on('data', function (data) {
        var message = data.toString();
        if (message === 'good') {
            notify('Client', 'Keep this song :D');
            keepSong();
        } else if (message === 'bad') {
            notify('Client', 'Delete this song :|');
            deleteSong();
        } else if (message === 'next') {
            notify('Client', 'Next song please :)');
            player.kill();
        } else {
            notify('Error', 'Client said non-handled message "' + message + '"', 'error');
        }
    });
    connection.on('error', function (e) {
        notify('Error', 'Client error, see logs', 'error');
        console.log(e);
    });
}

/***
 *    █_▄▄__█____██__▀▄____▄_▄███▄___█▄▄▄▄_
 *    █___█_█____█_█___█__█__█▀___▀__█__▄▀_
 *    █▀▀▀__█____█▄▄█___▀█___██▄▄____█▀▀▌__
 *    █_____███▄_█__█___█____█▄___▄▀_█__█__
 *    _█________▀___█_▄▀_____▀███▀_____█___
 *    __▀__________█__________________▀____
 *    ____________▀________________________
 */
var playlist = [];
var song = '';
var player = null;
var keep = false;

function playFolder () {
    var musicPath = config.get('musicPath');
    notify('Scanning', '"' + musicPath + '"' + ' for songs');
    fs.readdir(musicPath, function (err, files) {
        if (err) {
            config.trash();
            notify('Error', 'Fail at reading musicPath, see logs', 'error');
            throw new Error(err);
        }
        files.forEach(function (fileName) {
            //noinspection JSCheckFunctionSignatures
            var filePath = path.join(musicPath, fileName);
            var fileStat = fs.statSync(filePath);
            if (fileStat.isFile()) {
                playlist.push(filePath)
            }
        });
        if (config.get('shuffleMusic')) {
            shuffle(playlist);
        }
        playNext();
    });
}

function fileName (filePath) {
    // input  : "C:\Stuff\Music\to test\Mike feat. Snowball - Animal.mp3"
    // output : "Mike feat. Snowball - Animal"
    return path.basename(filePath).split('.').reverse().splice(1).reverse().join('.');
}

function playNext () {
    // by default, don't keep newly playing song
    keep = false;
    // here splice return first item & remove it from playlist
    song = playlist.splice(0, 1)[0];
    playSong();
    setTimeout(function () {
        notify('Remaining', playlist.length + ' track(s)');
        notify('Playing', fileName(song), 'info');
    }, 1100);
}

function keepSong () {
    keep = true;
}

function moveSong () {
    doAsync(function (lastSongPath) {
        //noinspection JSCheckFunctionSignatures
        fs.rename(lastSongPath, path.join(config.get('keepPath'), path.basename(lastSongPath)), function (err) {
            if (err) throw err;
            notify('Moved', fileName(lastSongPath));
        });
    });
    playNext();
}

function deleteSong () {
    keep = false;
    doAsync(function (lastSongPath) {
        fs.unlink(lastSongPath, function (err) {
            if (err) throw err;
            notify('Deleted', fileName(lastSongPath));
        });
    });
    player.kill();
}

function doAsync (callback) {
    if (!callback) {
        notify('Error', 'Do Async need a callback', 'error');
    } else {
        var lastSongPath = song + '';
        setTimeout(function () {
            callback(lastSongPath);
        }, 1000);
    }
}

function notify (action, message, type) {
    if (type) {
        // notify client side
        notifier.notify({
            title: action,
            message: message,
            type: type
        });
    }
    // in order to align logs :p
    while (action.length < 9) {
        action += ' ';
    }
    console.log(action + ' : ' + message);
}

function playSong () {
    player = spawn('lib/1by1/1by1.exe', [song, '/hide', '/close']);
    player.stderr.on('data', function (stderr) {
        notify('Stderr', stderr, 'error');
    });
    player.on('close', function (code) {
        if (code === null || code === 0) {
            if (keep) {
                moveSong();
            } else {
                playNext();
            }
        } else {
            notify('Error', 'Player process exited with non-handled code "' + code + '"', 'error');
        }
    });
}

function getConfig () {
    config.prompt({ all: true, nodeEnv: false, silent: false }, function (err) {
        if (err) {
            config.trash();
            notify('Error', 'Fail at reading config, see logs', 'error');
            throw new Error(err);
        }
        notify('Config path', config.path);
        playFolder();
    });
}

// init
setTimeout(getConfig, 100);
spawn('node_modules/electron/dist/electron', ['systray']); // add systray controls

<|endoftext|>


<commit_before>var HOST, PORT, Snake, autoClient, checkCollisions, server, snakes, sys, tick, updateState, util, websocket;
sys = require('sys');
util = require('util');
websocket = require('websocket-server');
server = websocket.createServer();
HOST = null;
PORT = 5000;
Array.prototype.remove = function(e) {
  var t, _ref;
  if ((t = this.indexOf(e)) > -1) {
    return ([].splice.apply(this, [t, t - t + 1].concat(_ref = [])), _ref);
  }
};
autoClient = 1;
snakes = [];
/* Snake Class */
Snake = (function() {
  function Snake(id) {
    this.id = id;
    this.reset();
  }
  Snake.prototype.reset = function() {
    var rH;
    rH = Math.floor(Math.random() * 49);
    this.direction = "right";
    return this.elements = [[-8, rH], [-7, rH], [-6, rH], [-5, rH], [-4, rH], [-3, rH], [-2, rH], [-1, rH]];
  };
  Snake.prototype.doStep = function() {
    var i;
    for (i = 0; i <= 6; i++) {
      this.moveTail(i);
    }
    return this.moveHead(7);
  };
  Snake.prototype.moveTail = function(i) {
    this.elements[i][0] = this.elements[i + 1][0];
    return this.elements[i][1] = this.elements[i + 1][1];
  };
  Snake.prototype.moveHead = function(i) {
    switch (this.direction) {
      case "left":
        this.elements[i][0] -= 1;
        break;
      case "right":
        this.elements[i][0] += 1;
        break;
      case "up":
        this.elements[i][1] -= 1;
        break;
      case "down":
        this.elements[i][1] += 1;
    }
    if (this.elements[i][0] < 0) {
      this.elements[i][0] = 49;
    }
    if (this.elements[i][1] < 0) {
      this.elements[i][1] = 49;
    }
    if (this.elements[i][0] > 49) {
      this.elements[i][0] = 0;
    }
    if (this.elements[i][1] > 49) {
      return this.elements[i][1] = 0;
    }
  };
  Snake.prototype.head = function() {
    return this.elements[7];
  };
  Snake.prototype.blocks = function(other) {
    var collision, element, head, _i, _len, _ref;
    head = other.elements[7];
    collision = false;
    _ref = this.elements;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      element = _ref[_i];
      if (head[0] === element[0] && head[1] === element[1]) {
        collision = true;
      }
    }
    return collision;
  };
  Snake.prototype.blocksSelf = function() {
    var collision, head, i;
    head = this.elements[7];
    collision = false;
    for (i = 0; i <= 6; i++) {
      if (head[0] === this.elements[i][0] && head[1] === this.elements[i][1]) {
        collision = true;
      }
    }
    return collision;
  };
  return Snake;
})();
/* Handle Connections */
server.addListener("connection", function(connection) {
  var clientId, clientSnake;
  clientId = autoClient;
  clientSnake = new Snake(clientId);
  autoClient += 1;
  snakes.push(clientSnake);
  sys.puts("Client " + clientId + " connected");
  connection.send(JSON.stringify({
    type: 'id',
    value: clientId
  }));
  connection.addListener("message", function(message) {
    message = JSON.parse(message);
    return clientSnake.direction = message.direction;
  });
  return connection.addListener("close", function(message) {
    snakes.remove(clientSnake);
    return sys.puts("Client " + clientId + " disconnected");
  });
});
/* Update Game State */
updateState = function() {
  var snake, _i, _len;
  for (_i = 0, _len = snakes.length; _i < _len; _i++) {
    snake = snakes[_i];
    snake.doStep();
  }
  checkCollisions();
  return server.broadcast(JSON.stringify({
    type: 'snakes',
    value: snakes
  }));
};
checkCollisions = function() {
  var other, resetSnakes, snake, _i, _j, _k, _len, _len2, _len3, _results;
  resetSnakes = [];
  for (_i = 0, _len = snakes.length; _i < _len; _i++) {
    snake = snakes[_i];
    if (snake.blocksSelf()) {
      resetSnakes.push(snake);
    }
    for (_j = 0, _len2 = snakes.length; _j < _len2; _j++) {
      other = snakes[_j];
      if (other !== snake) {
        if (other.blocks(snake)) {
          resetSnakes.push(snake);
        }
      }
    }
  }
  _results = [];
  for (_k = 0, _len3 = resetSnakes.length; _k < _len3; _k++) {
    snake = resetSnakes[_k];
    _results.push(snake.reset());
  }
  return _results;
};
tick = setInterval(updateState, 100);
/* Start Server */
server.listen(Number(process.env.PORT || PORT), HOST);
sys.puts("Server started");<commit_msg>Fogot compiled js...<commit_after>var HOST, PORT, Snake, autoClient, checkCollisions, port, server, snakes, sys, tick, updateState, util, websocket;
sys = require('sys');
util = require('util');
websocket = require('websocket-server');
server = websocket.createServer();
HOST = null;
PORT = 5000;
Array.prototype.remove = function(e) {
  var t, _ref;
  if ((t = this.indexOf(e)) > -1) {
    return ([].splice.apply(this, [t, t - t + 1].concat(_ref = [])), _ref);
  }
};
autoClient = 1;
snakes = [];
/* Snake Class */
Snake = (function() {
  function Snake(id) {
    this.id = id;
    this.reset();
  }
  Snake.prototype.reset = function() {
    var rH;
    rH = Math.floor(Math.random() * 49);
    this.direction = "right";
    return this.elements = [[-8, rH], [-7, rH], [-6, rH], [-5, rH], [-4, rH], [-3, rH], [-2, rH], [-1, rH]];
  };
  Snake.prototype.doStep = function() {
    var i;
    for (i = 0; i <= 6; i++) {
      this.moveTail(i);
    }
    return this.moveHead(7);
  };
  Snake.prototype.moveTail = function(i) {
    this.elements[i][0] = this.elements[i + 1][0];
    return this.elements[i][1] = this.elements[i + 1][1];
  };
  Snake.prototype.moveHead = function(i) {
    switch (this.direction) {
      case "left":
        this.elements[i][0] -= 1;
        break;
      case "right":
        this.elements[i][0] += 1;
        break;
      case "up":
        this.elements[i][1] -= 1;
        break;
      case "down":
        this.elements[i][1] += 1;
    }
    if (this.elements[i][0] < 0) {
      this.elements[i][0] = 49;
    }
    if (this.elements[i][1] < 0) {
      this.elements[i][1] = 49;
    }
    if (this.elements[i][0] > 49) {
      this.elements[i][0] = 0;
    }
    if (this.elements[i][1] > 49) {
      return this.elements[i][1] = 0;
    }
  };
  Snake.prototype.head = function() {
    return this.elements[7];
  };
  Snake.prototype.blocks = function(other) {
    var collision, element, head, _i, _len, _ref;
    head = other.elements[7];
    collision = false;
    _ref = this.elements;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      element = _ref[_i];
      if (head[0] === element[0] && head[1] === element[1]) {
        collision = true;
      }
    }
    return collision;
  };
  Snake.prototype.blocksSelf = function() {
    var collision, head, i;
    head = this.elements[7];
    collision = false;
    for (i = 0; i <= 6; i++) {
      if (head[0] === this.elements[i][0] && head[1] === this.elements[i][1]) {
        collision = true;
      }
    }
    return collision;
  };
  return Snake;
})();
/* Handle Connections */
server.addListener("connection", function(connection) {
  var clientId, clientSnake;
  clientId = autoClient;
  clientSnake = new Snake(clientId);
  autoClient += 1;
  snakes.push(clientSnake);
  sys.puts("Client " + clientId + " connected");
  connection.send(JSON.stringify({
    type: 'id',
    value: clientId
  }));
  connection.addListener("message", function(message) {
    message = JSON.parse(message);
    return clientSnake.direction = message.direction;
  });
  return connection.addListener("close", function(message) {
    snakes.remove(clientSnake);
    return sys.puts("Client " + clientId + " disconnected");
  });
});
/* Update Game State */
updateState = function() {
  var snake, _i, _len;
  for (_i = 0, _len = snakes.length; _i < _len; _i++) {
    snake = snakes[_i];
    snake.doStep();
  }
  checkCollisions();
  return server.broadcast(JSON.stringify({
    type: 'snakes',
    value: snakes
  }));
};
checkCollisions = function() {
  var other, resetSnakes, snake, _i, _j, _k, _len, _len2, _len3, _results;
  resetSnakes = [];
  for (_i = 0, _len = snakes.length; _i < _len; _i++) {
    snake = snakes[_i];
    if (snake.blocksSelf()) {
      resetSnakes.push(snake);
    }
    for (_j = 0, _len2 = snakes.length; _j < _len2; _j++) {
      other = snakes[_j];
      if (other !== snake) {
        if (other.blocks(snake)) {
          resetSnakes.push(snake);
        }
      }
    }
  }
  _results = [];
  for (_k = 0, _len3 = resetSnakes.length; _k < _len3; _k++) {
    snake = resetSnakes[_k];
    _results.push(snake.reset());
  }
  return _results;
};
tick = setInterval(updateState, 100);
/* Start Server */
server.listen(port = Number(process.env.PORT || PORT), HOST);
sys.puts("Server running on port " + port);<|endoftext|>


<commit_before>var express = require('express'),
    path    = require('path'),
    exec    = require('child_process').exec,
    io      = require('socket.io'),
    i18n    = require('i18n-abide');

var dirs = {
    pub    : path.join(__dirname, 'public'),
    views  : path.join(__dirname, 'views') ,
    styles : path.join(__dirname, 'styles'),
    models : path.join(__dirname, 'models'),
    vendor : path.join(__dirname, 'vendor'),
    uploads: path.join(__dirname, 'public/uploads/incoming')
};

/* make sure at runtime that we atempt to get the dirs we need */
for (d in dirs) {
    /* HACK: but I'm not going to waist time writing mkdir -p */
    exec ('mkdir -p ' + dirs[d], function (error, stdout, stderr) {
        if (error !== null) {
            console.log('exec error: ' + error);
        }
    });
}

var app = express();

app.configure(function () {
    app.use(i18n.abide({
        supported_languages: ['en-US', 'es', 'db-LB', 'it-CH'],
        default_lang: 'es',
        debug_lang: 'it-CH',
        locale_directory: 'locale'
    }));
    app.set('port', process.env.PORT || 3000);
    app.set('views', dirs.views);
    app.set('view engine', 'jade');
    app.use(express.logger('dev'));
/*    app.use('/uploads', upload({
        tmpDir:    dirs.uploads + '/incoming',
        uploadDir: dirs.upolads,
        uploadUrl: '/uploads/',
        safeFileTypes: /\.(webm|mkv|mov|mp4|avi|ogg)$/i,
    }));*/
    app.use(express.bodyParser({
            uploadDir: dirs.uploads,
            maxFieldsSize: 10 * 1024 * 1024
    })); /* */
    app.use(express.methodOverride());
    app.use(express.cookieParser('your secret here'));
    app.use(express.session());
    app.use(app.router);
    app.use(require('less-middleware')({
        src:  dirs.styles,
        dest: dirs.pub,
        compress: true}
    ));
    app.use(express.static(dirs.pub));
    app.use('/models', express.static(dirs.models));
    app.use('/lib',    express.static(dirs.vendor));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  app.set('io.loglevel', 100);
  app.set('minify', false);
});

app.configure('production', function(){
  app.use(express.errorHandler());
  app.set('io.loglevel', 1);
  app.set('minify', true);
});

var appModel = require('./routes')(app);
var media    = require('./routes/media')(app);

console.log ('hohohoh', media, media.mediaList);

io = io.listen(app.listen(app.get('port'), function(){
  console.log("Express server listening on port %d in %s mode", app.get('port'), app.settings.env);
}));

io.enable('browser client minification');  // send minified client
io.enable('browser client etag');          // apply etag caching logic based on version number
io.enable('browser client gzip');          // gzip the file
io.set('log level', app.get('io.loglevel'));
io.set('transports', [                     // enable all transports (optional if you want flashsocket)
    'websocket'
  , 'flashsocket'
  , 'htmlfile'
  , 'xhr-polling'
  , 'jsonp-polling'
]);

io.sockets.on('connection', function (socket) {
    media.mediaList.bindServer(socket);
    appModel.bindServer(socket);

    socket.on('disconnect', function () {
        media.mediaList.unbindServer(socket);
        appModel.unbindServer(socket);
    });
    socket.on('medias:moved', function (move) {
        socket.broadcast.emit ('medias:moved', move);
        media.mediaList.move(move.from, move.to);

    });
});

<commit_msg>make usefull dirs on init<commit_after>var express = require('express'),
    path    = require('path'),
    exec    = require('child_process').exec,
    io      = require('socket.io'),
    i18n    = require('i18n-abide'),
    _       = require('underscore'),
    exec    = require('child_process').exec;

var dirs = {
    pub    : path.join(__dirname, 'public'),
    views  : path.join(__dirname, 'views') ,
    styles : path.join(__dirname, 'styles'),
    models : path.join(__dirname, 'models'),
    vendor : path.join(__dirname, 'vendor'),
    uploads: path.join(__dirname, 'public/uploads/incoming')
};

/* make sure at runtime that we atempt to get the dirs we need */
for (d in dirs) {
    /* HACK: but I'm not going to waist time writing mkdir -p */
    exec ('mkdir -p ' + dirs[d], function (error, stdout, stderr) {
        if (error !== null) {
            console.log('exec error: ' + error);
        }
    });
}

var app = express();

app.configure(function () {
    app.use(i18n.abide({
        supported_languages: ['en-US', 'es', 'db-LB', 'it-CH'],
        default_lang: 'es',
        debug_lang: 'it-CH',
        locale_directory: 'locale'
    }));
    app.set('port', process.env.PORT || 3000);
    app.set('views', dirs.views);
    app.set('view engine', 'jade');
    app.use(express.logger('dev'));
/*    app.use('/uploads', upload({
        tmpDir:    dirs.uploads + '/incoming',
        uploadDir: dirs.upolads,
        uploadUrl: '/uploads/',
        safeFileTypes: /\.(webm|mkv|mov|mp4|avi|ogg)$/i,
    }));*/
    app.use(express.bodyParser({
            uploadDir: dirs.uploads,
            maxFieldsSize: 10 * 1024 * 1024
    })); /* */
    app.use(express.methodOverride());
    app.use(express.cookieParser('your secret here'));
    app.use(express.session());
    app.use(app.router);
    app.use(require('less-middleware')({
        src:  dirs.styles,
        dest: dirs.pub,
        compress: true}
    ));
    app.use(express.static(dirs.pub));
    app.use('/models', express.static(dirs.models));
    app.use('/lib',    express.static(dirs.vendor));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  app.set('io.loglevel', 100);
  app.set('minify', false);
});

app.configure('production', function(){
  app.use(express.errorHandler());
  app.set('io.loglevel', 1);
  app.set('minify', true);
});

var appModel = require('./routes')(app);
var media    = require('./routes/media')(app);

console.log ('hohohoh', media, media.mediaList);

io = io.listen(app.listen(app.get('port'), function(){
  console.log("Express server listening on port %d in %s mode", app.get('port'), app.settings.env);
}));

io.enable('browser client minification');  // send minified client
io.enable('browser client etag');          // apply etag caching logic based on version number
io.enable('browser client gzip');          // gzip the file
io.set('log level', app.get('io.loglevel'));
io.set('transports', [                     // enable all transports (optional if you want flashsocket)
    'websocket'
  , 'flashsocket'
  , 'htmlfile'
  , 'xhr-polling'
  , 'jsonp-polling'
]);

io.sockets.on('connection', function (socket) {
    media.mediaList.bindServer(socket);
    appModel.bindServer(socket);

    socket.on('disconnect', function () {
        media.mediaList.unbindServer(socket);
        appModel.unbindServer(socket);
    });
    socket.on('medias:moved', function (move) {
        socket.broadcast.emit ('medias:moved', move);
        media.mediaList.move(move.from, move.to);

    });
});

<|endoftext|>


<commit_before>const express = require('express');
const path = require('path');
const fs = require('fs');
const formidable = require('formidable');
const helper = require('sendgrid').mail;
require('dotenv').config();
const sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
const fetch = require('node-fetch');
const fieType = require('file-type');

const app = express();
const PORT = process.env.PORT || 9000;
// const CLIENT_PORT = process.env.PORT || 3000;
const PROTOCOL = process.env.PROTOCOL || 'http';
const HOSTNAME = process.env.HOST || 'localhost';
const UPLOAD_DIR = path.join(__dirname, 'uploads/');
const CORS = process.env.NODE_ENV === 'production' ? `${PROTOCOL}://${HOSTNAME}` : `*`;
const ENABLE_SEND_EMAILS = process.env.NODE_ENV === 'production' || process.env.ENABLE_SEND_EMAILS === 'true';
const ENABLE_WRIKE = process.env.NODE_ENV === 'production' || process.env.ENABLE_WRIKE === 'true';

if (ENABLE_SEND_EMAILS) {
  console.info('Sending emails is enabled');
} else {
  console.info('Sending emails is disabled');
}

if (ENABLE_WRIKE) {
  console.info('Wrike integration is enabled');
} else {
  console.info('Wrike integration is disabled');
}

// This converts {a:1, b:2} into 'a=1&b=2'
const queryParams = obj =>
  Object.keys(obj)
    .map(key => [key, obj[key]]) // There is no Object.entries() in node 6
    .map(
      ([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`
    )
    .join('&');

const wrikeMkFolder = (name, content) =>
  fetch(process.env.WRIKE_URL, {
    body: queryParams({
      title: name,
      description: content,
      shareds: process.env.WRIKE_SHARE_ID,
      project: process.env.WRIKE_OWNER_ID,
    }),
    method: 'post',
    headers: {
      Authorization: `bearer ${process.env.WRIKE_TOKEN}`,
      ContentType: 'application/xwwwformurlencoded',
    },
  }).then(res => res.json());

const wrikeAddAttachments = (id, file, name, type) =>
  fetch(`https://www.wrike.com/api/v3/folders/${id}/attachments`, {
    body: file,
    method: 'post',
    headers: {
      Authorization: `bearer ${process.env.WRIKE_TOKEN}`,
      xrequestedwith: 'XMLHttpRequest',
      xfilename: name,
      contenttype: type,
      cachecontrol: 'nocache',
    },
  }).then(res => res.json());

const makeSgRequest = body =>
  sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: body.toJSON(),
  });

if (!fs.existsSync(UPLOAD_DIR)) {
  console.warn('==========================');
  console.warn('Creating uploads folder...');
  console.warn('==========================');
  fs.mkdirSync(UPLOAD_DIR);
}
console.info('======================================');
console.info(`Uploads will be saved in ${UPLOAD_DIR}`);
console.info('======================================');

app.use(express.static(path.join(__dirname, 'build')));

app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.post('/uploads', (req, res) => {
  const form = new formidable.IncomingForm();
  form.maxFileSize = 2

  // In any case send the cors headers (even on error)
  res.header('AccessControlAllowOrigin', CORS);
  res.header(
    'AccessControlAllowHeaders',
    'Origin, XRequestedWith, ContentType, Accept'
  );

  form.parse(req);

  // The events we subscribe to in the form occur in the following order
  // field  multiple times
  // fileBegin then file  once per file
  // error  only if there was a parsing error
  // end  when all other events have been handled and the files have
  //       finished being written to the disk, this event happens even
  //       if there was an error

  form.on('fileBegin', (name, file) => {
    // https://stackoverflow.com/a/30550190/4718107
    const fileType = file.type.split('/').pop()

    if (fileType === 'jpg' || fileType === 'png' || fileType === 'plain') {
      file.path = path.join(UPLOAD_DIR, file.name)
    } else {
      console.log(`incorrect file type: ${fileType}`)
    }
  });

  form.on('file', (name, file) => {
    console.log(`Uploaded ${file.name}`);
  });

  const files = [];

  form.on('file', (name, file) => {
    files.push(file);
  });

  const fields = {};
  let fieldsString = '';
  form.on('field', (name, value) => {
    fields[name] = value;
    fieldsString = `fieldsString${name}: ${value}<br />`;
  });

  // Handle a possible error while parsing the request
  // We need a variable in this scope to hold whether there was an error
  // because we need to know that in a different callback
  let error = false;
  form.on('error', (err) => {
    error = true;
    console.log('Error while parsing request to /uploads: ', err);
    res
      .status(400) // Bad request
      .json({
        success: false,
        status: 'Error parsing the request',
      });
  });

  form.on('end', () => {
    // The end event is fired even if an error occurs, so we
    // need to prevent from sending a second response, otherwise the
    // server crashes
    if (error) return;
    console.log('Received fields:\n', JSON.stringify(fields, null, 2));

    // TODO: Validate fields

    // Here is a good place to send the emails since we have the fields
    // We don't want to actually send emails during testing since it
    // would send a test email on every single commit
    if (ENABLE_SEND_EMAILS) {
      const toEmail = new helper.Email('paulius.rimg1990@gmail.com');
      const fromEmail = new helper.Email('test@example.com');
      const subject = 'New Service Request Form Submission';
      const content = new helper.Content('text/plain', fieldsString);
      const mail = new helper.Mail(fromEmail, subject, toEmail, content);
      const request = makeSgRequest(mail);
      console.log('Sending email...');
      sg.API(request, (err, res) => {
        if (error) {
          console.log('Error response received');
        }
        console.log(res.statusCode);
        console.log(res.body);
        console.log(res.headers);
      });
    }

    // Create project and attach files in wrike

    if (ENABLE_WRIKE) {
      // eslint-disable-next-line
      wrikeMkFolder(fields['email'], fieldsString)
        .then((status) => {
          const folderId = status.data[0].id;
          // eslint-disable-next-line
          for (const file of files) {
            // Formidable files are just metadata, not the actual file
            // Use the file name to create a ReadStream and pass it to
            // node-fetch which can handle ReadStreams
            // To pass a ReadStream is something like piping the file
            // instead of reading the whole file and passing it
            const readStream = fs.createReadStream(file.path);
            wrikeAddAttachment(
              folderId,
              readStream,
              file.name,
              file.type
            ).catch((err) => {
              console.log(`Error while reading file for upload to Wrike: ${err}`);
              console.log(`Filename: ${file.path}`);
            });
          }
        })
        .catch((err) => {
          console.log(`Error while creating a project in Wrike: ${err}`);
        });
    }

    // Send the success response
    res
      .status(200)
      .json({ success: true, status: 'Form successfully submitted' });
  });
});

app.listen(PORT, _ =>
  console.info('============================'),
console.info(`Server listening on PORT ${PORT}...`),
console.info('============================'));
<commit_msg>Add file extension check<commit_after>const express = require('express');
const path = require('path');
const fs = require('fs');
const formidable = require('formidable');
const helper = require('sendgrid').mail;
require('dotenv').config();
const sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
const fetch = require('node-fetch');
const fieType = require('file-type');

const app = express();
const PORT = process.env.PORT || 9000;
// const CLIENT_PORT = process.env.PORT || 3000;
const PROTOCOL = process.env.PROTOCOL || 'http';
const HOSTNAME = process.env.HOST || 'localhost';
const UPLOAD_DIR = path.join(__dirname, 'uploads/');
const CORS = process.env.NODE_ENV === 'production' ? `${PROTOCOL}://${HOSTNAME}` : `*`;
const ENABLE_SEND_EMAILS = process.env.NODE_ENV === 'production' || process.env.ENABLE_SEND_EMAILS === 'true';
const ENABLE_WRIKE = process.env.NODE_ENV === 'production' || process.env.ENABLE_WRIKE === 'true';

if (ENABLE_SEND_EMAILS) {
  console.info('Sending emails is enabled');
} else {
  console.info('Sending emails is disabled');
}

if (ENABLE_WRIKE) {
  console.info('Wrike integration is enabled');
} else {
  console.info('Wrike integration is disabled');
}

// This converts {a:1, b:2} into 'a=1&b=2'
const queryParams = obj =>
  Object.keys(obj)
    .map(key => [key, obj[key]]) // There is no Object.entries() in node 6
    .map(
      ([key, val]) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`
    )
    .join('&');

const wrikeMkFolder = (name, content) =>
  fetch(process.env.WRIKE_URL, {
    body: queryParams({
      title: name,
      description: content,
      shareds: process.env.WRIKE_SHARE_ID,
      project: process.env.WRIKE_OWNER_ID,
    }),
    method: 'post',
    headers: {
      Authorization: `bearer ${process.env.WRIKE_TOKEN}`,
      ContentType: 'application/xwwwformurlencoded',
    },
  }).then(res => res.json());

const wrikeAddAttachments = (id, file, name, type) =>
  fetch(`https://www.wrike.com/api/v3/folders/${id}/attachments`, {
    body: file,
    method: 'post',
    headers: {
      Authorization: `bearer ${process.env.WRIKE_TOKEN}`,
      xrequestedwith: 'XMLHttpRequest',
      xfilename: name,
      contenttype: type,
      cachecontrol: 'nocache',
    },
  }).then(res => res.json());

const makeSgRequest = body =>
  sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: body.toJSON(),
  });

if (!fs.existsSync(UPLOAD_DIR)) {
  console.warn('==========================');
  console.warn('Creating uploads folder...');
  console.warn('==========================');
  fs.mkdirSync(UPLOAD_DIR);
}
console.info('======================================');
console.info(`Uploads will be saved in ${UPLOAD_DIR}`);
console.info('======================================');

app.use(express.static(path.join(__dirname, 'build')));

app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.post('/uploads', (req, res) => {
  const form = new formidable.IncomingForm();
  form.maxFileSize = 2

  // In any case send the cors headers (even on error)
  res.header('AccessControlAllowOrigin', CORS);
  res.header(
    'AccessControlAllowHeaders',
    'Origin, XRequestedWith, ContentType, Accept'
  );

  form.parse(req);

  // The events we subscribe to in the form occur in the following order
  // field  multiple times
  // fileBegin then file  once per file
  // error  only if there was a parsing error
  // end  when all other events have been handled and the files have
  //       finished being written to the disk, this event happens even
  //       if there was an error

  form.on('fileBegin', (name, file) => {
    // https://stackoverflow.com/a/30550190/4718107
    const fileType = file.type.split('/').pop()
    const fileExtension = file.name.split('.').pop()
    const hasDots = file.name.match('.').length > 1
    const hasSlash = file.name.includes('/')
    const fileTypes = /(vnd.rar|pdf|msword|vnd.openxmlformats-officedocument.wordprocessingml.document|vnd.openxmlformats-officedocument.spreadsheetml.sheet|vnd.ms-excel|vnd.ms-powerpoint|vnd.openxmlformats-officedocument.presentationml.presentation|mp4|mpeg|plain|zip|quicktime|avi|wav|jpeg|octet-stream|png)$/i
    const fileExtensions = /(zip|pdf|docx?|xlsx?|pptx?|mp3|txt|plain|rar|wma|mov|avi|wmv|mp4|flv|wav|jpe?g|psd|png)$/i
    // https://docs.nodejitsu.com/articles/file-system/security/introduction/
    const posionNullBytesCheck = file.name.indexOf('\0') !== -1

    console.log(fileExtensions.test(fileExtension))
    if (!posionNullBytesCheck &&
      fileTypes.test(fileType) &&
      fileExtensions.test(fileExtension) &&
      !hasDots &&
      !hasSlash &&
      form.bytesExpected < 10 * 1024 * 1024 &&
      form.bytesReceived < 10 * 1024 * 1024
    ) {
      file.path = path.join(UPLOAD_DIR, file.name)
    } else {
      console.log(`incorrect file type: ${fileType}`)
    }
  });

  form.on('file', (name, file) => {
    console.log(`Uploaded ${file.name}`);
  });

  const files = [];

  form.on('file', (name, file) => {
    files.push(file);
  });

  const fields = {};
  let fieldsString = '';
  form.on('field', (name, value) => {
    fields[name] = value;
    fieldsString = `fieldsString${name}: ${value}<br />`;
  });

  // Handle a possible error while parsing the request
  // We need a variable in this scope to hold whether there was an error
  // because we need to know that in a different callback
  let error = false;
  form.on('error', (err) => {
    error = true;
    console.log('Error while parsing request to /uploads: ', err);
    res
      .status(400) // Bad request
      .json({
        success: false,
        status: 'Error parsing the request',
      });
  });

  form.on('end', () => {
    // The end event is fired even if an error occurs, so we
    // need to prevent from sending a second response, otherwise the
    // server crashes
    if (error) return;
    console.log('Received fields:\n', JSON.stringify(fields, null, 2));

    // TODO: Validate fields

    // Here is a good place to send the emails since we have the fields
    // We don't want to actually send emails during testing since it
    // would send a test email on every single commit
    if (ENABLE_SEND_EMAILS) {
      const toEmail = new helper.Email('paulius.rimg1990@gmail.com');
      const fromEmail = new helper.Email('test@example.com');
      const subject = 'New Service Request Form Submission';
      const content = new helper.Content('text/plain', fieldsString);
      const mail = new helper.Mail(fromEmail, subject, toEmail, content);
      const request = makeSgRequest(mail);
      console.log('Sending email...');
      sg.API(request, (err, res) => {
        if (error) {
          console.log('Error response received');
        }
        console.log(res.statusCode);
        console.log(res.body);
        console.log(res.headers);
      });
    }

    // Create project and attach files in wrike

    if (ENABLE_WRIKE) {
      // eslint-disable-next-line
      wrikeMkFolder(fields['email'], fieldsString)
        .then((status) => {
          const folderId = status.data[0].id;
          // eslint-disable-next-line
          for (const file of files) {
            // Formidable files are just metadata, not the actual file
            // Use the file name to create a ReadStream and pass it to
            // node-fetch which can handle ReadStreams
            // To pass a ReadStream is something like piping the file
            // instead of reading the whole file and passing it
            const readStream = fs.createReadStream(file.path);
            wrikeAddAttachment(
              folderId,
              readStream,
              file.name,
              file.type
            ).catch((err) => {
              console.log(`Error while reading file for upload to Wrike: ${err}`);
              console.log(`Filename: ${file.path}`);
            });
          }
        })
        .catch((err) => {
          console.log(`Error while creating a project in Wrike: ${err}`);
        });
    }

    // Send the success response
    res
      .status(200)
      .json({ success: true, status: 'Form successfully submitted' });
  });
});

app.listen(PORT, _ =>
  console.info('============================'),
console.info(`Server listening on PORT ${PORT}...`),
console.info('============================'));
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
var request = require('ajax-request');

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages 😎:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {

	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function () {
	  var DONE = 4; // readyState 4 means the request is done.
	  var OK = 200; // status 200 is a successful return.
	  if (xhr.readyState === DONE) {
	    if (xhr.status === OK)
	      console.log(xhr.responseText); // 'This is the returned text.'
		  msg.say("RESPONSE: "+xhr.responseText);
	    } else {
	      console.log('Error: ' + xhr.status); // An error occurred during the request.
		  msg.say("Error: "+xhr.status);
	    }
	  }
	};
	xhr.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=reaction');
	xhr.send(null);
	msg.say(HELP_TEXT)
})

// slapp.message('Robert', ['mention', 'direct_message'], (msg) => {
//   msg.say('What a dick!')
// })

// slapp.message('jens', ['mention', 'direct_message'], (msg) => {
//   msg.say('What a dick!')
// })

slapp.message(/^(Ralf|Jens|Robert|Frank|Isa|Jan|Daniel)/i, ['mention', 'direct_message'], (msg) => {
	// var text = (msg.body.event && msg.body.event.text) || '';

	msg.say([
      '🚀',
      '💩',
      ':+1: That\'s my man',
      'Best colleague :sun_with_face: :full_moon_with_face:'
    ])
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// http://giphy.com/gifs/thread-appreciation-rappers-Mqz2DNuhWjFyU

// http://giphy.com/gifs/kpop-k-pop-wink-26mfytBsu0XC9bVss

// http://giphy.com/gifs/reactionseditor-reaction-l0IyjeA5mmMZjhyPm

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>ajax update<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages 😎:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {

	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function () {
	  var DONE = 4; // readyState 4 means the request is done.
	  var OK = 200; // status 200 is a successful return.
	  if (xhr.readyState === DONE) {
	    if (xhr.status === OK)
	      console.log(xhr.responseText); // 'This is the returned text.'
		  msg.say("RESPONSE: "+xhr.responseText);
	    } else {
	      console.log('Error: ' + xhr.status); // An error occurred during the request.
		  msg.say("Error: "+xhr.status);
	    }
	  }
	};
	xhr.open('GET', 'http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=reaction');
	xhr.send(null);
	msg.say(HELP_TEXT)
})

// slapp.message('Robert', ['mention', 'direct_message'], (msg) => {
//   msg.say('What a dick!')
// })

// slapp.message('jens', ['mention', 'direct_message'], (msg) => {
//   msg.say('What a dick!')
// })

slapp.message(/^(Ralf|Jens|Robert|Frank|Isa|Jan|Daniel)/i, ['mention', 'direct_message'], (msg) => {
	// var text = (msg.body.event && msg.body.event.text) || '';

	msg.say([
      '🚀',
      '💩',
      ':+1: That\'s my man',
      'Best colleague :sun_with_face: :full_moon_with_face:'
    ])
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// http://giphy.com/gifs/thread-appreciation-rappers-Mqz2DNuhWjFyU

// http://giphy.com/gifs/kpop-k-pop-wink-26mfytBsu0XC9bVss

// http://giphy.com/gifs/reactionseditor-reaction-l0IyjeA5mmMZjhyPm

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>// Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

WebApp.rawConnectHandlers.use(function (req, res, next) {
  if (req.url === "/.sandstorm-credentials") {
    handleCredentials(req, res);
    return;
  }
  return next();
});

var handleCredentials = Meteor.bindEnvironment(function (req, res) {
  try {
    var permissions = req.headers["x-sandstorm-permissions"];
    if (permissions && permissions !== "") {
      permissions = permissions.split(",");
    } else {
      permissions = [];
    }

    var credentials = {
      sandstormId: req.headers["x-sandstorm-user-id"] || null,
      name: req.headers["x-sandstorm-username"],
      permissions: permissions
    };

    if (credentials.sandstormId) {
      var login = Accounts.updateOrCreateUserFromExternalService(
          "sandstorm", { id: credentials.sandstormId, permissions: permissions },
          { profile: { name: credentials.name } });
      console.log(login);
      credentials.meteorId = login.userId;
      var token = Accounts._generateStampedLoginToken();
      credentials.token = token.token;
      Accounts._insertLoginToken(login.userId, token);
    }

    var text = JSON.stringify(credentials);

    res.writeHead(200, {
      "Content-Type": "application/json",
      "Content-Length": text.length
    });
    res.end(text);
  } catch (err) {
    res.writeHead(500, {
      "Content-Type": "text/plain"
    });
    res.end(err.stack);
  }
});
<commit_msg>Decode special urlencoded characters in the name<commit_after>// Copyright (c) 2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

WebApp.rawConnectHandlers.use(function (req, res, next) {
  if (req.url === "/.sandstorm-credentials") {
    handleCredentials(req, res);
    return;
  }
  return next();
});

var handleCredentials = Meteor.bindEnvironment(function (req, res) {
  try {
    var permissions = req.headers["x-sandstorm-permissions"];
    if (permissions && permissions !== "") {
      permissions = permissions.split(",");
    } else {
      permissions = [];
    }

    var credentials = {
      sandstormId: req.headers["x-sandstorm-user-id"] || null,
      name: decodeURI(req.headers["x-sandstorm-username"]),
      permissions: permissions
    };

    if (credentials.sandstormId) {
      var login = Accounts.updateOrCreateUserFromExternalService(
          "sandstorm", { id: credentials.sandstormId, permissions: permissions },
          { profile: { name: credentials.name } });
      console.log(login);
      credentials.meteorId = login.userId;
      var token = Accounts._generateStampedLoginToken();
      credentials.token = token.token;
      Accounts._insertLoginToken(login.userId, token);
    }

    var text = JSON.stringify(credentials);

    res.writeHead(200, {
      "Content-Type": "application/json",
      "Content-Length": text.length
    });
    res.end(text);
  } catch (err) {
    res.writeHead(500, {
      "Content-Type": "text/plain"
    });
    res.end(err.stack);
  }
});
<|endoftext|>