<commit_before>const express = require('express');
const request = require('superagent');
const jsonParser = require('body-parser').json();
const passport = require('passport');
const OAuth2Strategy = require('passport-oauth2');
const mongoose = require('mongoose');
const User = require('./model/user');

const uriString =
    process.env.MONGOLAB_URI ||
    'mongodb://localhost/saldot';

mongoose.connect(uriString, (err, res) => {
    if (err) {
        console.log('ERROR connecting to: ' + uriString + '. ' + err);
    } else {
        console.log('Connected to: ' + uriString);
    }
});

const app = express()

app.use(passport.initialize());
app.use(passport.session());
app.use(forceSsl);

const forceSsl = function(req, res, next) {
    if (req.headers['x-forwarded-proto'] !== 'https') {
        return res.redirect(['https://', req.get('Host'), req.url].join(''));
    }
    return next();
};

passport.serializeUser(function(user, done) {
    // console.log('user: ', user);
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});

passport.use(
    'oauth2',
    new OAuth2Strategy({
            authorizationURL: 'https://wunderdog.harvestapp.com/oauth2/authorize',
            tokenURL: 'https://wunderdog.harvestapp.com/oauth2/token',
            clientID: process.env.CLIENT_ID,
            clientSecret: process.env.CLIENT_SECRET,
            callbackURL: 'https://saldot.herokuapp.com/auth/callback'
        },
        function(accessToken, refreshToken, profile, done) {
            request
                .get('https://wunderdog.harvestapp.com/account/who_am_i')
                .type('json')
                .accept('json')
                .query({
                    access_token: accessToken
                })
                .end((err, res) => {
                    const harvestUser = res.body.user;
                    const user = {
                        id: harvestUser.id,
                        firstName: harvestUser.first_name,
                        lastName: harvestUser.last_name,
                        accessToken: accessToken
                    };
                    // findOrCreateUser(user, err);
                    // done(null, user);

                    User.findOne({
                        id: user.id
                    }, function(err, dbUser) {
                        if (err) {
                            console.log(err);
                        } else if (dbUser === null) {
                            new User(user).save(err => {
                                if (err) {
                                    console.log(err)
                                }
                            });
                        }
                        done(err, user);
                    });
                });
        }
    ));

const findOrCreateUser = function(user) {}

app.get('/login', passport.authenticate('oauth2'));

app.get(
    '/auth/callback',
    passport.authenticate('oauth2', {
        failureRedirect: '/error'
    }),
    function(req, res) {
        res.end(`${req.user.firstName} ${req.user.lastName} logged in.`);
    });

app.use('/', express.static(__dirname + '/dist'));

const port = process.env.PORT || 8080;
app.listen(port);
console.log('Server listening in port: ' + port);<commit_msg>Fix forceSsl.<commit_after>const express = require('express');
const request = require('superagent');
const jsonParser = require('body-parser').json();
const passport = require('passport');
const OAuth2Strategy = require('passport-oauth2');
const mongoose = require('mongoose');
const User = require('./model/user');

const uriString =
    process.env.MONGOLAB_URI ||
    'mongodb://localhost/saldot';

mongoose.connect(uriString, (err, res) => {
    if (err) {
        console.log('ERROR connecting to: ' + uriString + '. ' + err);
    } else {
        console.log('Connected to: ' + uriString);
    }
});

const app = express()

const forceSsl = function(req, res, next) {
    if (req.headers['x-forwarded-proto'] !== 'https') {
        return res.redirect(['https://', req.get('Host'), req.url].join(''));
    }
    return next();
};

app.use(passport.initialize());
app.use(passport.session());
app.use(forceSsl);

passport.serializeUser(function(user, done) {
    // console.log('user: ', user);
    done(null, user);
});

passport.deserializeUser(function(user, done) {
    done(null, user);
});

passport.use(
    'oauth2',
    new OAuth2Strategy({
            authorizationURL: 'https://wunderdog.harvestapp.com/oauth2/authorize',
            tokenURL: 'https://wunderdog.harvestapp.com/oauth2/token',
            clientID: process.env.CLIENT_ID,
            clientSecret: process.env.CLIENT_SECRET,
            callbackURL: 'https://saldot.herokuapp.com/auth/callback'
        },
        function(accessToken, refreshToken, profile, done) {
            request
                .get('https://wunderdog.harvestapp.com/account/who_am_i')
                .type('json')
                .accept('json')
                .query({
                    access_token: accessToken
                })
                .end((err, res) => {
                    const harvestUser = res.body.user;
                    const user = {
                        id: harvestUser.id,
                        firstName: harvestUser.first_name,
                        lastName: harvestUser.last_name,
                        accessToken: accessToken
                    };
                    // findOrCreateUser(user, err);
                    // done(null, user);

                    User.findOne({
                        id: user.id
                    }, function(err, dbUser) {
                        if (err) {
                            console.log(err);
                        } else if (dbUser === null) {
                            new User(user).save(err => {
                                if (err) {
                                    console.log(err)
                                }
                            });
                        }
                        done(err, user);
                    });
                });
        }
    ));

const findOrCreateUser = function(user) {}

app.get('/login', passport.authenticate('oauth2'));

app.get(
    '/auth/callback',
    passport.authenticate('oauth2', {
        failureRedirect: '/error'
    }),
    function(req, res) {
        res.end(`${req.user.firstName} ${req.user.lastName} logged in.`);
    });

app.use('/', express.static(__dirname + '/dist'));

const port = process.env.PORT || 8080;
app.listen(port);
console.log('Server listening in port: ' + port);<|endoftext|>


<commit_before>/*jshint node:true */
/*
 * grunt-component
 * https://github.com/anthonyshort/grunt-component-build
 *
 * Copyright (c) 2012 Anthony Short
 * Licensed under the MIT license.
 */

'use strict';

var Builder = require('component-builder');
var fs = require('fs');
var path = require('path');
var template = fs.readFileSync(__dirname + '/../lib/require.tmpl').toString();

module.exports = function(grunt) {

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('component_build', 'component-build for grunt.', function() {
    var self = this;
    var opts = this.data;
    var name = opts.name || this.target;
    var verbose = opts.verbose;
    var dir = path.resolve(opts.base || '');
    var defaultOutput = 'build';
    var output = path.resolve(this.data.output || defaultOutput);
    var done = this.async();

    var verboseLog = function(str) {
      if (verbose) {
        grunt.log.writeln(str);
      }
    };

    // The component builder
    var builder = new Builder(dir);

    // Where to output the final file
    builder.copyAssetsTo(output);

    // Prefix urls
    if (opts.prefix) {
      builder.prefixUrls(opts.prefix);
    }

    // Development mode
    if (opts.dev) {
      builder.development();
    }

    if (opts.sourceUrls === true) {
      builder.addSourceURLs();
    }

    // Ignore component parts
    if (opts.ignore) {
      Object.keys(opts.ignore).forEach(function(n) {
        var type = opts.ignore[n];
        builder.ignore(n, type);
      });
    }

    // By default Builder takes the paths of the dependencies
    // from the current directory (here the Gruntfile path).
    // So in case the dependencies are not stored in the /components
    // but in the baseOption/components, we have to add it to the lookup.
    builder.addLookup(path.join(dir, 'components'));

    // The component config
    var config = require(path.join(dir, 'component.json'));

    if (config.paths) {
      config.paths = config.paths.map(function(p) {
        return path.resolve(dir, p);
      });

      builder.addLookup(config.paths);
    }

    // Set the config on the builder. We've modified
    // the original config from the file and this will
    // override settings during the build
    builder.config = config;

    if (opts.plugins) {
      opts.plugins.forEach(function(name) {
        var plugin = require('../plugins/' + name);
        builder.use(plugin);
      });
    }

    // Configure hook
    if (opts.configure) {
      opts.configure.call(this, builder);
    }

    var start = new Date();

    // Build the component
    builder.build(function(err, obj) {
      if (err) {
        grunt.log.error(err.message);
        grunt.fatal(err.message);
      }

      verboseLog('duration: ' + (new Date() - start) + 'ms');

      // Write CSS file
      if (opts.styles !== false) {
        var cssFile = path.join(output, name + '.css');
        grunt.file.write(cssFile, obj.css.trim());

        verboseLog('write: ' + path.join(self.data.output || defaultOutput, name + '.css') + ' (' + (obj.css.trim().length / 1024 | 0) + 'kb)');
      }

      // Write JS file
      if (opts.scripts !== false) {
        var jsFile = path.join(output, name + '.js');
        var size = 0;
        if (opts.standalone) {
          // Defines the name of the global variable (window[opts.name]).
          // By default we use the name defined in the component.json,
          // else we use the `standalone` option defined in the Gruntfile.
          obj.name = (typeof opts.standalone === 'string') ? opts.standalone : config.name;
          obj.config = config;

          var string = grunt.template.process(template, { data: obj });
          grunt.file.write(jsFile, string);
          size = string.length;
        } else {
          grunt.file.write(jsFile, obj.require + obj.js);
          size = obj.require.length + obj.js.length;
        }

        verboseLog( 'write: ' + path.join(self.data.output || defaultOutput, name + '.js') + ' (' + ( size / 1024 | 0 ) + 'kb)' );
      }

      done();
    });
  });
};
<commit_msg>Add noRequire option<commit_after>/*jshint node:true */
/*
 * grunt-component
 * https://github.com/anthonyshort/grunt-component-build
 *
 * Copyright (c) 2012 Anthony Short
 * Licensed under the MIT license.
 */

'use strict';

var Builder = require('component-builder');
var fs = require('fs');
var path = require('path');
var template = fs.readFileSync(__dirname + '/../lib/require.tmpl').toString();

module.exports = function(grunt) {

  // Please see the grunt documentation for more information regarding task and
  // helper creation: https://github.com/cowboy/grunt/blob/master/docs/toc.md

  // ==========================================================================
  // TASKS
  // ==========================================================================

  grunt.registerMultiTask('component_build', 'component-build for grunt.', function() {
    var self = this;
    var opts = this.data;
    var name = opts.name || this.target;
    var verbose = opts.verbose;
    var dir = path.resolve(opts.base || '');
    var defaultOutput = 'build';
    var output = path.resolve(this.data.output || defaultOutput);
    var done = this.async();

    var verboseLog = function(str) {
      if (verbose) {
        grunt.log.writeln(str);
      }
    };

    // The component builder
    var builder = new Builder(dir);

    // Where to output the final file
    builder.copyAssetsTo(output);

    // Prefix urls
    if (opts.prefix) {
      builder.prefixUrls(opts.prefix);
    }

    // Development mode
    if (opts.dev) {
      builder.development();
    }

    if (opts.sourceUrls === true) {
      builder.addSourceURLs();
    }

    // Ignore component parts
    if (opts.ignore) {
      Object.keys(opts.ignore).forEach(function(n) {
        var type = opts.ignore[n];
        builder.ignore(n, type);
      });
    }

    // By default Builder takes the paths of the dependencies
    // from the current directory (here the Gruntfile path).
    // So in case the dependencies are not stored in the /components
    // but in the baseOption/components, we have to add it to the lookup.
    builder.addLookup(path.join(dir, 'components'));

    // The component config
    var config = require(path.join(dir, 'component.json'));

    if (config.paths) {
      config.paths = config.paths.map(function(p) {
        return path.resolve(dir, p);
      });

      builder.addLookup(config.paths);
    }

    // Set the config on the builder. We've modified
    // the original config from the file and this will
    // override settings during the build
    builder.config = config;

    if (opts.plugins) {
      opts.plugins.forEach(function(name) {
        var plugin = require('../plugins/' + name);
        builder.use(plugin);
      });
    }

    // Configure hook
    if (opts.configure) {
      opts.configure.call(this, builder);
    }

    var start = new Date();

    // Build the component
    builder.build(function(err, obj) {
      if (err) {
        grunt.log.error(err.message);
        grunt.fatal(err.message);
      }

      verboseLog('duration: ' + (new Date() - start) + 'ms');

      // Write CSS file
      if (opts.styles !== false) {
        var cssFile = path.join(output, name + '.css');
        grunt.file.write(cssFile, obj.css.trim());

        verboseLog('write: ' + path.join(self.data.output || defaultOutput, name + '.css') + ' (' + (obj.css.trim().length / 1024 | 0) + 'kb)');
      }

      // Write JS file
      if (opts.scripts !== false) {
        var jsFile = path.join(output, name + '.js');
        var size = 0;
        if (opts.standalone) {
          // Defines the name of the global variable (window[opts.name]).
          // By default we use the name defined in the component.json,
          // else we use the `standalone` option defined in the Gruntfile.
          obj.name = (typeof opts.standalone === 'string') ? opts.standalone : config.name;
          obj.config = config;

          var string = grunt.template.process(template, { data: obj });
          grunt.file.write(jsFile, string);
          size = string.length;
        } else if (opts.noRequire) {
          grunt.file.write(jsFile, obj.js);
          size = obj.js.length;
        } else {
          grunt.file.write(jsFile, obj.require + obj.js);
          size = obj.require.length + obj.js.length;
        }

        verboseLog( 'write: ' + path.join(self.data.output || defaultOutput, name + '.js') + ' (' + ( size / 1024 | 0 ) + 'kb)' );
      }

      done();
    });
  });
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('underscore');

var RegexCheck = function (pattern, listOfExcludedFiles, gruntLog, gruntFile) {
    var log = gruntLog;
    var file = gruntFile;

    var excludedFiles = listOfExcludedFiles || [];
    if (pattern === undefined) {
        throw "Configuration option 'pattern' was not specified";
    }
    if (typeof pattern !== 'object') {
        throw "Configuration option 'pattern' should be a javascript regular expression";
    }

    var isExcluded = function (filepath) {
        var isExcluded = false;
        excludedFiles.forEach(function (excludedFile) {
            if (excludedFile === filepath) {
                isExcluded = true;
            }
        });
        return isExcluded;
    };

    return {
        check: function (files) {
            var ranOnce = false;

            files.forEach(function (f) {
                var matchingFiles = f.src.filter(function (filepath) {
                    // Warn on and remove invalid source files (if nonull was set).
                    if (!file.exists(filepath)) {
                        log.warn('Source file "' + filepath + '" not found.');
                        return false;
                    } else {
                        return true;
                    }
                }).filter(function (filepath) {
                        ranOnce = true;
                        var source = file.read(filepath);
                        var matchesPattern = source.match(pattern) !== null;
                        var isNotExcluded = !isExcluded(filepath, excludedFiles);
                        return matchesPattern && isNotExcluded;
                    });

                var allFiles = matchingFiles.join('\n');
                if (matchingFiles.length === 0) {
                    log.writeln('grunt-regex-check passed');
                } else {
                    log.error("The following files contained unwanted patterns:\n\n" + allFiles +
                        "\n\nFiles that were excluded:\n" + excludedFiles.join('\n'));
                }

            });
            if(!ranOnce) {
                log.warn("No files were processed. You may want to check you configuration. Files detected: " + files.join(','));
            }
        }
    };
};

module.exports = RegexCheck;

<commit_msg>Printing the pattern that causes a file to fail.<commit_after>'use strict';

var _ = require('underscore');

var RegexCheck = function (pattern, listOfExcludedFiles, gruntLog, gruntFile) {
    var log = gruntLog;
    var file = gruntFile;

    var excludedFiles = listOfExcludedFiles || [];
    if (pattern === undefined) {
        throw "Configuration option 'pattern' was not specified";
    }
    if (typeof pattern !== 'object') {
        throw "Configuration option 'pattern' should be a javascript regular expression";
    }

    var isExcluded = function (filepath) {
        var isExcluded = false;
        excludedFiles.forEach(function (excludedFile) {
            if (excludedFile === filepath) {
                isExcluded = true;
            }
        });
        return isExcluded;
    };

    return {
        check: function (files) {
            var ranOnce = false;

            files.forEach(function (f) {
                var matchingFiles = f.src.filter(function (filepath) {
                    // Warn on and remove invalid source files (if nonull was set).
                    if (!file.exists(filepath)) {
                        log.warn('Source file "' + filepath + '" not found.');
                        return false;
                    } else {
                        return true;
                    }
                }).map(function (filepath) {
                    ranOnce = true;
                    var source = file.read(filepath);
                    var match = source.match(pattern);
                    return {
                      filepath: filepath,
                      match: match,
                      isNotExcluded: !isExcluded(filepath, excludedFiles)
                    };
                }).filter(function (result) {
                    return result.match !== null && result.isNotExcluded;
                    });

                if (matchingFiles.length === 0) {
                    log.writeln('grunt-regex-check passed');
                } else {
                    var filesMessages = matchingFiles.map(function (matchingFile) {
                      return matchingFile.filepath + " - failed because it matched '" + matchingFile.match[0] + "'";
                    }).join('\n');
                    log.error("The following files contained unwanted patterns:\n\n" + filesMessages +
                        "\n\nFiles that were excluded:\n" + excludedFiles.join('\n'));
                }

            });
            if(!ranOnce) {
                log.warn("No files were processed. You may want to check you configuration. Files detected: " + files.join(','));
            }
        }
    };
};

module.exports = RegexCheck;

<|endoftext|>


<commit_before>/**
 * Simple webserver with logging. By default, serves whatever files are
 * reachable from the directory where node is running.
 */
var VERSION = "0.1"
var posix = require('posix'),
    pathlib = require('path'),
    uri = require('url')
    mime = require('./lib/content-type'),
    log = require('./lib/log');

log.level = log.levels.DEBUG;

var settings = {
    "max_bytes_per_read": 1024 * 1024 * 5, // 5MB
    "timeout_milliseconds": 1000 * 30, //30 sec
    "hosts" : [],
    "port" : 8080,
    "default_host" : {
        "root" : "./"
    }
}

try {
    log.debug("Reading/parsing settings.json");
    var custom_settings = JSON.parse(posix.cat('./settings.json').wait());
    process.mixin(settings, custom_settings);
} catch(e) {
    log.warn("Using default settings: cannot read settings.json.",e);
}

log.info( "Starting server on port", settings.port);
require("http").createServer(function(req,resp) {
    log.info("Request:", JSON.stringify(req.headers));
    var vhost = get_vhost(req.headers["host"]);
    var path = get_file_path(vhost.root, req.url);
    log.debug( "Streaming", path);
    resp.die = setTimeout(finish, settings.timeout_milliseconds);
    stream(path, resp);

    function get_vhost(hostname) {
        return settings.hosts[hostname] || settings.default_host;
    }

    function get_file_path(webroot, url) {
        var path = uri.parse(url || '/').pathname;
        path = path.replace(/\.\.\//g,''); //don't allow access to parent dirs
        return pathlib.join(webroot, path);
    }
}).listen(settings.port);

function stream(path, resp) {
    function sendHeaders(httpstatus, content_length, content_type) {
        resp.sendHeader(httpstatus,
            {
                "Content-Type" : content_type ||
                                 "application/octet-stream",
                "Server" : "Antinode/" + VERSION +
                           " Node.js/" + process.version +
                           " " + process.platform,
                "Date" : (new Date()).toUTCString(),
                "Content-Length" : content_length
            });
    }
    posix.stat(path).addCallback(function (stat) {
        if (stat.isDirectory()) {
            stream(pathlib.join(path, "index.html"), resp); //try dir/index.html
        } else {
            streamFile(path, stat.size);
        }
    }).addErrback(fileNotFound);

    function streamFile(file, filesize) {
        posix.open(file,process.O_RDONLY, 0660).addCallback(function(fd) {
            var position = 0;
            log.debug("opened",path,"on fd",fd);
            if(fd) {
                sendHeaders(200, filesize, mime.mime_type(path));
                read();
                function read() {
                  posix.read(fd,settings.max_bytes_per_read,position, "binary")
                    .addCallback(function(data,bytes_read) {
                        log.debug("read",bytes_read,"bytes of",file);
                        if(bytes_read > 0) {
                            resp.sendBody(data, "binary");
                            position += bytes_read;
                            read(); // read more
                        } else {
                            finish(resp,fd);
                        }
                    }).addErrback(function() {
                        log.error("Error reading from",file,"position:",position,
                            ">",arguments);
                        resp.sendBody("Error reading from " + file);
                        finish(resp,fd);
                    });
                }
            } else {
                log.warn("Invalid fd for file:",file);
                var body = file + " couldn't be opened.";
                sendHeaders(500, body.length, "text/plain");
                resp.sendBody(body);
                finish(resp,fd);
            }
        }).addErrback(fileNotFound);
    }
    function fileNotFound() {
        log.debug("404 opening",path,">",arguments);
        var body = "404: " + path + " not found.";
        sendHeaders(404,body.length,"text/plain");
        resp.sendBody(body);
        finish(resp);
    }
}

function finish(resp, fd) {
    clearTimeout(resp.die);
    resp.finish();
    log.debug("finished request for",resp.url);
    if(fd) {
        posix.close(fd);
        log.debug("closing fd",fd);
    }
}
<commit_msg>posix -> fs<commit_after>/**
 * Simple webserver with logging. By default, serves whatever files are
 * reachable from the directory where node is running.
 */
var VERSION = "0.1"
var fs = require('fs'),
    pathlib = require('path'),
    uri = require('url')
    mime = require('./lib/content-type'),
    log = require('./lib/log');

log.level = log.levels.DEBUG;

var settings = {
    "max_bytes_per_read": 1024 * 1024 * 5, // 5MB
    "timeout_milliseconds": 1000 * 30, //30 sec
    "hosts" : [],
    "port" : 8080,
    "default_host" : {
        "root" : "./"
    }
}

try {
    log.debug("Reading/parsing settings.json");
    var custom_settings = JSON.parse(fs.cat('./settings.json').wait());
    process.mixin(settings, custom_settings);
} catch(e) {
    log.warn("Using default settings: cannot read settings.json.",e);
}

log.info( "Starting server on port", settings.port);
require("http").createServer(function(req,resp) {
    log.info("Request:", JSON.stringify(req.headers));
    var vhost = get_vhost(req.headers["host"]);
    var path = get_file_path(vhost.root, req.url);
    log.debug( "Streaming", path);
    resp.die = setTimeout(finish, settings.timeout_milliseconds);
    stream(path, resp);

    function get_vhost(hostname) {
        return settings.hosts[hostname] || settings.default_host;
    }

    function get_file_path(webroot, url) {
        var path = uri.parse(url || '/').pathname;
        path = path.replace(/\.\.\//g,''); //don't allow access to parent dirs
        return pathlib.join(webroot, path);
    }
}).listen(settings.port);

function stream(path, resp) {
    function sendHeaders(httpstatus, content_length, content_type) {
        resp.sendHeader(httpstatus,
            {
                "Content-Type" : content_type ||
                                 "application/octet-stream",
                "Server" : "Antinode/" + VERSION +
                           " Node.js/" + process.version +
                           " " + process.platform,
                "Date" : (new Date()).toUTCString(),
                "Content-Length" : content_length
            });
    }
    fs.stat(path).addCallback(function (stat) {
        if (stat.isDirectory()) {
            stream(pathlib.join(path, "index.html"), resp); //try dir/index.html
        } else {
            streamFile(path, stat.size);
        }
    }).addErrback(fileNotFound);

    function streamFile(file, filesize) {
        fs.open(file,process.O_RDONLY, 0660).addCallback(function(fd) {
            var position = 0;
            log.debug("opened",path,"on fd",fd);
            if(fd) {
                sendHeaders(200, filesize, mime.mime_type(path));
                read();
                function read() {
                  fs.read(fd,settings.max_bytes_per_read,position, "binary")
                    .addCallback(function(data,bytes_read) {
                        log.debug("read",bytes_read,"bytes of",file);
                        if(bytes_read > 0) {
                            resp.sendBody(data, "binary");
                            position += bytes_read;
                            read(); // read more
                        } else {
                            finish(resp,fd);
                        }
                    }).addErrback(function() {
                        log.error("Error reading from",file,"position:",position,
                            ">",arguments);
                        resp.sendBody("Error reading from " + file);
                        finish(resp,fd);
                    });
                }
            } else {
                log.warn("Invalid fd for file:",file);
                var body = file + " couldn't be opened.";
                sendHeaders(500, body.length, "text/plain");
                resp.sendBody(body);
                finish(resp,fd);
            }
        }).addErrback(fileNotFound);
    }
    function fileNotFound() {
        log.debug("404 opening",path,">",arguments);
        var body = "404: " + path + " not found.";
        sendHeaders(404,body.length,"text/plain");
        resp.sendBody(body);
        finish(resp);
    }
}

function finish(resp, fd) {
    clearTimeout(resp.die);
    resp.finish();
    log.debug("finished request for",resp.url);
    if(fd) {
        fs.close(fd);
        log.debug("closing fd",fd);
    }
}
<|endoftext|>


<commit_before>'use strict';

//var SlackAssistBot = require('./lib/SlackAssist');
var express = require('express');
var app = express(); // create our app w/ express
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();
var path = require('path');

var path = require('path');
var methodOverride = require('method-override');

var token = process.env.BOT_API_KEY;

/*var slackAssistBot = new SlackAssistBot({
  token: token
});*/

var mimeTypes = {
  "css" : "text/css",
  "js"  : "text/javascript"
}

app.use(express.static(__dirname + 'www'));
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({
  'extended': 'true'
})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({
  type: 'application/vnd.api+json'
})); // parse application/vnd.api+json as json
app.use(methodOverride());

app.use('/www/*', function(req, res) {
  var extention = req.originalUrl.split('.').reverse()[0];
  var mimeType = mimeTypes[extention];
  if(typeof mimeType === 'undefined') {
    console.log('undefined type');
    mimeType = 'text/plain';
  }
  res.set('Content-Type', mimeType);
  res.sendFile(path.join(__dirname, req.originalUrl));
});

app.get('/auth/github', function(req, res) {
  console.log(req.query.code);
  res.sendFile(__dirname + '/www/public/app.html'); // load the single view file (angular will handle the page changes on the front-end)
});

app.get('/*', function(req, res) {
  res.sendFile(__dirname + '/www/public/app.html'); // load the single view file (angular will handle the page changes on the front-end)
});

var port = process.env.PORT || 3000;
app.listen(port, function() {
  console.log('listening on', port);
});

//slackAssistBot.run();<commit_msg>Added Authentication + EJS templating support<commit_after>'use strict';

var SlackAssistBot = require('./lib/SlackAssist');
var express = require('express');
var app = express(); // create our app w/ express
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var router = express.Router();
var path = require('path');
var methodOverride = require('method-override');
var postAccount = require('./api/accounts/post.js');

var token = process.env.BOT_API_KEY;

var slackAssistBot = new SlackAssistBot({token: token});

var mimeTypes = {
  "css" : "text/css",
  "js"  : "text/javascript",
  "ico" : "image/x-icon",
  "jpg" : "image/jpeg",
  "jpeg" : "image/jpeg",
  "png" : "image/png",
};

app.set('view engine', 'ejs');
app.set('views', __dirname + '/www/public/views');
app.use(express.static(__dirname + 'www'));
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({
  'extended': 'true'
})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({
  type: 'application/vnd.api+json'
})); // parse application/vnd.api+json as json
app.use(methodOverride());

app.get('/www/*', function(req, res) {
  var extention = req.originalUrl.split('.').reverse()[0];
  var mimeType = mimeTypes[extention];
  if(typeof mimeType === 'undefined') {
    console.log('undefined type');
    mimeType = 'text/plain';
  }
  res.set('Content-Type', mimeType);
  res.sendFile(path.join(__dirname, req.originalUrl));
});

app.get('/auth/github', function(req, res) {
  console.log('code reveived: ',req.query.code);
  getAccessToken(req.query.code,function(err,data){
    if(err){
     res.render('pages/app',{error:err});
    }else{
      res.render('pages/app',{status:"Successfully Authenticated"});
    }
  });
});

app.get('/*', function(req, res) {
  res.render('pages/app');
});

var port = process.env.PORT || 3000;
app.listen(port, function() {
  console.log('listening on', port);
});

function getAccessToken(code,callback) {
  var Client = require('node-rest-client').Client;
  var client = new Client();

  var args = {
    data: {
      client_id       : "4cb2e781eaea4040f99d",
      client_secret   : process.env.BOT_CLIENT_SECRET,
      code            : code,
      redirect_uri    : "http://localhost:3000/auth/github"
    },
    headers: {
      "Content-Type": "application/json"
    }
  };

  console.log("\nCalling github for getting access_token\n");

  client.post("https://github.com/login/oauth/access_token", args, function(data, response) {
    var message = data.toString();
    console.log("Message reveived: ",message);
    var firstWord = message.split('=')[0];
    if(firstWord === 'access_token'){
      var token = message.split("=")[1].split("&")[0];
      var account = {token : token , url : null};
      postAccount(account,function(err,data){
        if(err)
          callback("Error in saving data to db: "+err);
        else
          callback(null)
      });
    }else{
      if( message.split("=")[1] === 'bad_verification_code&error_description')
        callback("The Code sent is expired. Please click on the button again.");
      else
        callback(message.split("=")[1]); // erro message
    }
  });
}

slackAssistBot.run();
<|endoftext|>


<commit_before>// Third-party dependencies
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var express = require('express');
var bodyParser = require('body-parser');

// Local dependencies
var configService = require('./services/configuration.js');
var commandsController = require("./commands.js");
var apputil = require("./util.js");
var db = require('./db.js');

// Retrieve the configuration from file
var configFileName = "config.json";
var config = configService.GetConfigurationSync(configFileName);

// Constants
const app = express();

// Globals

// Install express middleware
app.use(bodyParser.json());

// Handle root
app.get('/', function(req, res) {
	if (config.tacoBotWebUrl) { res.redirect(`${config.tacoBotWebUrl}`); }
	else { res.send("invalid request"); }
});

// Return log, should this be an admin call?
app.get('/log', function(req, res) {
	var logName = "server.log";
	apputil.readFile(logName, function(error, logData){
		if (error) {
			apputil.log(`Error retrieving log: \r\n ${error.stack}`);
			res.end(error);
		} else {
			// fs.readFileSync returns a buffer. Convert to string here
			res.send(logData.toString());
		}
	});
});

// Return api status
app.get('/status', function(req, res) {
	res.send('UP');
});

// Return array of commands
app.get("/commands", function(req, res) {
	db.get().collection("commands").find().toArray(function(error, results) {
		if (error) {
			apputil.log(`Error retrieving commands: ${error}`);
		} else {
			res.setHeader('Content-Type', 'application/json');
			res.jsonp(results);
		}
	});
});

// Receive messages from groupme bot api
app.post("/command", function(req, res) {
	res.writeHead(200);
	res.end(commandsController.investigate(req.body));
});

// Handle Error response
app.use(function(err, req, res, next) {
	apputil.log(`Error with server:\r\nError:\r\n ${err.stack} \r\nStack: ${err.stack}`);
	res.status(500).send('Something broke!');
});

db.connect(config.mongoConnectionString, function(err) {
	if (err) {
		apputil.log(`Unable to connect to mongo. Error:\r\n${err}`);
		process.exit(1);
	}
	apputil.log("Opened db connection");

	app.listen(config.port, function () {
		apputil.log("Server listening on port " + config.port, null, true);
	});
});<commit_msg>Updated use of new commandsController.investigate, moved groupme response to server.js [skip ci]<commit_after>// Third-party dependencies
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var express = require('express');
var bodyParser = require('body-parser');

// Local dependencies
var configService = require('./services/configuration.js');
var commandsController = require("./commands.js");
var apputil = require("./util.js");
var db = require('./db.js');

// Retrieve the configuration from file
var configFileName = "config.json";
var config = configService.GetConfigurationSync(configFileName);

// Constants
const app = express();

// Globals

// Install express middleware
app.use(bodyParser.json());

// Handle root
app.get('/', function(req, res) {
	if (config.tacoBotWebUrl) { res.redirect(`${config.tacoBotWebUrl}`); }
	else { res.send("invalid request"); }
});

// Return log, should this be an admin call?
app.get('/log', function(req, res) {
	var logName = "server.log";
	apputil.readFile(logName, function(error, logData){
		if (error) {
			apputil.log(`Error retrieving log: \r\n ${error.stack}`);
			res.end(error);
		} else {
			// fs.readFileSync returns a buffer. Convert to string here
			res.send(logData.toString());
		}
	});
});

// Return api status
app.get('/status', function(req, res) {
	res.send('UP');
});

// Return array of commands
app.get("/commands", function(req, res) {
	db.get().collection("commands").find().toArray(function(error, results) {
		if (error) {
			apputil.log(`Error retrieving commands: ${error}`);
		} else {
			res.setHeader('Content-Type', 'application/json');
			res.jsonp(results);
		}
	});
});

// Receive messages from groupme bot api
app.post("/command", function(req, res) {
	res.writeHead(200);
	if (!apputil.isIgnoredGroupMeAccount(req.body))
	{
		commandsController.investigate(req.body.text, function(err, replies){
			for(var i = 0; i < replies.length; i++) {
				apputil.groupme_text_post(replies[i], req.body.group_id, function(e, r){
					if (!e) {
						apputil.log(r);
					} else {
						apputil.log(e);
					}
				});
			}
		});
	}
	res.end();
});

// Handle Error response
app.use(function(err, req, res, next) {
	apputil.log(`Error with server:\r\nError:\r\n ${err.stack} \r\nStack: ${err.stack}`);
	res.status(500).send('Something broke!');
});

db.connect(config.mongoConnectionString, function(err) {
	if (err) {
		apputil.log(`Unable to connect to mongo. Error:\r\n${err}`);
		process.exit(1);
	}
	apputil.log("Opened db connection");

	app.listen(config.port, function () {
		apputil.log("Server listening on port " + config.port, null, true);
	});
});<|endoftext|>


<commit_before>var express = require("express");
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.post('/webhook', function (req, res) {
    var data = req.body;

    // Make sure this is a page subscription
    if (data.object === 'page') {

        // Iterate over each entry - there may be multiple if batched
        data.entry.forEach(function(entry) {
            var pageID = entry.id;
            var timeOfEvent = entry.time;

            // Iterate over each messaging event
            entry.messaging.forEach(function(event) {
                if (event.message) {
                    receivedMessage(event);
                } else {
                    console.log("Webhook received unknown event: ", event);
                }
            });
        });

        // Assume all went well.
        //
        // You must send back a 200, within 20 seconds, to let us know
        // you've successfully received the callback. Otherwise, the request
        // will time out and we will keep trying to resend.
        res.sendStatus(200);
    }
});

function receivedMessage(event) {
    var senderID = event.sender.id;
    var recipientID = event.recipient.id;
    var timeOfMessage = event.timestamp;
    var message = event.message;

    console.log("Received message for user %d and page %d at %d with message:",
        senderID, recipientID, timeOfMessage);
    console.log(JSON.stringify(message));

    var messageId = message.mid;

    var messageText = message.text;
    var messageAttachments = message.attachments;

    if (messageText) {

        // If we receive a text message, check to see if it matches a keyword
        // and send back the example. Otherwise, just echo the text we received.
        switch (messageText) {
            case 'generic':
                sendGenericMessage(senderID);
                break;

            default:
                sendTextMessage(senderID, messageText);
        }
    } else if (messageAttachments) {
        sendTextMessage(senderID, "Message with attachment received");
    }
}

function sendGenericMessage(recipientId, messageText) {
    // To be expanded in later sections
}

function sendTextMessage(recipientId, messageText) {
    var messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            text: messageText
        }
    };

    callSendAPI(messageData);
}

function callSendAPI(messageData) {
    request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: { access_token: process.env.TOKEN },
        method: 'POST',
        json: messageData

    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var recipientId = body.recipient_id;
            var messageId = body.message_id;

            console.log("Successfully sent generic message with id %s to recipient %s",
                messageId, recipientId);
        } else {
            console.error("Unable to send message.");
            console.error(response);
            console.error(error);
        }
    });
}

app.get('/webhook', function (req, res) {
    if (req.query['hub.mode'] === 'subscribe' &&
        req.query['hub.verify_token'] === process.env.TOKEN) {
        console.log("Validating webhook");
        res.status(200).send(req.query['hub.challenge']);
    } else {
        console.error("Failed validation. Make sure the validation tokens match.");
        res.sendStatus(403);
    }
});

app.get("/test", function (req, res) {
    res.send("Ok");
});

// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
    console.log("ERROR: " + reason);
    res.status(code || 500).json({"error": message});
}

// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
});
<commit_msg>Added code for sendGenericMessage method; Added receivedPostback method.<commit_after>var express = require("express");
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.post('/webhook', function (req, res) {
    var data = req.body;

    // Make sure this is a page subscription
    if (data.object === 'page') {

        // Iterate over each entry - there may be multiple if batched
        data.entry.forEach(function(entry) {
            var pageID = entry.id;
            var timeOfEvent = entry.time;

            // Iterate over each messaging event
            entry.messaging.forEach(function(event) {
                if (event.message) {
                    receivedMessage(event);
                }
                else if (event.postback) {
                    receivedPostback(event);
                }
                else {
                    console.log("Webhook received unknown event: ", event);
                }
            });
        });

        // Assume all went well.
        //
        // You must send back a 200, within 20 seconds, to let us know
        // you've successfully received the callback. Otherwise, the request
        // will time out and we will keep trying to resend.
        res.sendStatus(200);
    }
});

function receivedMessage(event) {
    var senderID = event.sender.id;
    var recipientID = event.recipient.id;
    var timeOfMessage = event.timestamp;
    var message = event.message;

    console.log("Received message for user %d and page %d at %d with message:",
        senderID, recipientID, timeOfMessage);
    console.log(JSON.stringify(message));

    var messageId = message.mid;

    var messageText = message.text;
    var messageAttachments = message.attachments;

    if (messageText) {

        // If we receive a text message, check to see if it matches a keyword
        // and send back the example. Otherwise, just echo the text we received.
        switch (messageText) {
            case 'generic':
                sendGenericMessage(senderID);
                break;

            default:
                sendTextMessage(senderID, messageText);
        }
    } else if (messageAttachments) {
        sendTextMessage(senderID, "Message with attachment received");
    }
}

function sendGenericMessage(recipientId) {
    var messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            attachment: {
                type: "template",
                payload: {
                    template_type: "generic",
                    elements: [{
                        title: "rift",
                        subtitle: "Next-generation virtual reality",
                        item_url: "https://www.oculus.com/en-us/rift/",
                        image_url: "http://messengerdemo.parseapp.com/img/rift.png",
                        buttons: [{
                            type: "web_url",
                            url: "https://www.oculus.com/en-us/rift/",
                            title: "Open Web URL"
                        }, {
                            type: "postback",
                            title: "Call Postback",
                            payload: "Payload for first bubble",
                        }],
                    }, {
                        title: "touch",
                        subtitle: "Your Hands, Now in VR",
                        item_url: "https://www.oculus.com/en-us/touch/",
                        image_url: "http://messengerdemo.parseapp.com/img/touch.png",
                        buttons: [{
                            type: "web_url",
                            url: "https://www.oculus.com/en-us/touch/",
                            title: "Open Web URL"
                        }, {
                            type: "postback",
                            title: "Call Postback",
                            payload: "Payload for second bubble",
                        }]
                    }]
                }
            }
        }
    };

    callSendAPI(messageData);
}

function sendTextMessage(recipientId, messageText) {
    var messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            text: messageText
        }
    };

    callSendAPI(messageData);
}

function callSendAPI(messageData) {
    request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: { access_token: process.env.TOKEN },
        method: 'POST',
        json: messageData

    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var recipientId = body.recipient_id;
            var messageId = body.message_id;

            console.log("Successfully sent generic message with id %s to recipient %s",
                messageId, recipientId);
        } else {
            console.error("Unable to send message.");
            console.error(response);
            console.error(error);
        }
    });
}

function receivedPostback(event) {
    var senderID = event.sender.id;
    var recipientID = event.recipient.id;
    var timeOfPostback = event.timestamp;

    // The 'payload' param is a developer-defined field which is set in a postback
    // button for Structured Messages.
    var payload = event.postback.payload;

    console.log("Received postback for user %d and page %d with payload '%s' " +
        "at %d", senderID, recipientID, payload, timeOfPostback);

    // When a postback is called, we'll send a message back to the sender to
    // let them know it was successful
    sendTextMessage(senderID, "Postback called");
}

app.get('/webhook', function (req, res) {
    if (req.query['hub.mode'] === 'subscribe' &&
        req.query['hub.verify_token'] === process.env.TOKEN) {
        console.log("Validating webhook");
        res.status(200).send(req.query['hub.challenge']);
    } else {
        console.error("Failed validation. Make sure the validation tokens match.");
        res.sendStatus(403);
    }
});

app.get("/test", function (req, res) {
    res.send("Ok");
});

// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
    console.log("ERROR: " + reason);
    res.status(code || 500).json({"error": message});
}

// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
});
<|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')
const BeepBoop = require('beepboop')
const bodyParser = require('body-parser')
const parameters = require('parameters-middleware');
var request = require('request')
const slackey = require('slackey')

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

var slackAPIClient
var beepboop = BeepBoop.start()

beepboop.on('open', () => {
  console.log('connection to Beep Boop server opened')
})
beepboop.on('error', (error) => {
  console.log('Error from Beep Boop connection: ', err)
})
beepboop.on('close', (code, message) => {
  console.log('Connection to Beep Boop was closed')
})
beepboop.on('add_resource', (message) => {
  console.log('Team added: ', message.resource.SlackTeamName);
  slackAPIClient = slackey.getAPIClient(message.resource.SlackBotAccessToken);
	fetchChannels();
})
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 app = express()
app.use(bodyParser.json());
app.post('/recommendations',
  parameters({body : ["channel", "title", "url"]}),
  (req, res) => {
    var channelId = req.body.channel
    var channel = channels[channelId]
    if (channel == null) return res.status(400).send("Channel not found")
    var verifiedIcon = req.body.verified ? "https://cdn3.iconfinder.com/data/icons/basicolor-arrows-checks/24/154_check_ok_sticker_success-512.png" : "http://www.clker.com/cliparts/H/Z/0/R/f/S/warning-icon-hi.png"
    var attachment = {
    	callback_id: "share",
	      author_icon: verifiedIcon,
	      title_link: req.body.url,
	      title: req.body.title,
	      actions: [
	          {
	            "name": "post",
	            "text": "Post",
	            "type": "button",
	            "style": "primary",
	            "value": channelId
	          },
	          {
	            "name": "discard",
	            "text": "Discard",
	            "type": "button",
	            "style": "danger",
	            "value": "discarded"
	          },
	          {
                  "name": "post",
                  "text": "Share to channel...",
                  "type": "select",
                  "options": [
            		   {
            		      "text":"1 - Test",
            		      "value":1
            		   },
            		   {
        			     "text":"7 - Digital Marketing",
        			     "value":7
        			   },
        			   {
        			      "text":"40 - Legal",
        			      "value":40
        			   },
        			   {
        			      "text":"43 - Innovation & Startups",
        			      "value":43
        			   },
        			   {
        			      "text":"66 - Journalism",
        			      "value":66
        			   },
        			   {
        			      "text":"76 - Ondernemen",
        			      "value":76
        			   },
        			   {
        			      "text":"82 - Market Trends",
        			      "value":82
        			   },
        			   {
        			      "text":"83 - 9x Awesome Content",
        			      "value":83
        			   },
        			   {
        			      "text":"84 - Business Practices",
        			      "value":84
        			   },
        			   {
        			      "text":"86 - Education Market",
        			      "value":86
        			   },
        			   {
        			      "text":"87 - Venture Capital & Startups",
        			      "value":87
        			   },
        			   {
        			      "text":"89 - Fintech",
        			      "value":89
        			   },
        			   {
        			      "text":"101 - Direct Marketing",
        			      "value":101
        			   },
        			   {
        			      "text":"109 - IT Business",
        			      "value":109
        			   },
        			   {
        			      "text":"116 - NN Algemeen",
        			      "value":116
        			   },
        			   {
        			      "text":"120 - Customer Insights",
        			      "value":120
        			   },
        			   {
        			      "text":"125 - CPS",
        			      "value":125
        			   },
        			   {
        			      "text":"126 - RMS",
        			      "value":126
        			   },
        			   {
        			      "text":"136 - IBM in the Media",
        			      "value":136
        			   },
        			   {
        			      "text":"151 - Randstad in the News",
        			      "value":151
        			   },
        			   {
        			      "text":"152 - Randstad Market Watch",
        			      "value":152
        			   },
        			   {
        			      "text":"170 - IBM Cloud Market Watch",
        			      "value":170
        			   },
        			   {
        			      "text":"219 - IBM Developer Advocates",
        			      "value":219
        			   },
        			   {
        			      "text":"250 - Achmea Transport",
        			      "value":250
        			   },
        			   {
        			      "text":"251 - Achmea Automotive",
        			      "value":251
        			   },
        			   {
        			      "text":"253 - Achmea Innovation",
        			      "value":253
        			   }
        			]
              }
	        ]
    }
    if (req.body.host) {
      attachment.author_name = req.body.host;
      attachment.author_link = `http://${req.body.host}`;
    }
    if (req.body.summary) {
        attachment.text = req.body.summary
    }
    if (req.body.image_url) {
        attachment.image_url = req.body.image_url
    }
    if (req.body.pub_date) {
        attachment.ts = Date.parse(req.body.pub_date) / 1000
    }

    // Populating fields
    var fields = []
    if (req.body.keywords) {
    	if (!req.body.keywords.includes(", ")) {
    		req.body.keywords = req.body.keywords.replace(/,/g, ", ")
    	}
	    fields.push({
	    	title: "Keywords",
	    	short: false,
	    	value: req.body.keywords
	    })
    }
    if (req.body.companies) {
    	if (!req.body.companies.includes(", ")) {
    		req.body.companies = req.body.companies.replace(/,/g, ", ")
    	}
	    fields.push({
	        title: "Companies",
	        short: false,
	        value: req.body.companies
	    })
    }
    if (req.body.word_count) {
    	var length = req.body.word_count
    	var prefix = ""
    	if (length > 1000 )
    		prefix = ":snail: "
    	else if (length < 300)
    		prefix = ":fast_forward: "
    	fields.push({
    		title: "Length",
    		short: true,
    		value: `${prefix}${length} words`
    	})
    }
    if (req.body.shares) {
      fields.push({
        title: "Shares",
        short: true,
        value: formatCount(req.body.shares)
      })
    }
    if (req.body.sentiment) {
    	var sentiment
    	switch (req.body.sentiment) {
    		case "negative":
    			sentiment = ":rage: Negative";
    			break;
    		case "positive":
    			sentiment = ":smile: Positive";
    			break;
    		case "neutral":
    			sentiment = "Neutral"
    			break;
    	}
    	fields.push({
            title: "Sentiment",
            short: true,
            value: sentiment
          })
    }
//    Unsupported for now
//    fields.push({
//    	"title": "Sponsored",
//        "value": ":warning: Undetected",
//        "short": true
//    })
    attachment.fields = fields
    slackAPIClient.send('chat.postMessage',
          {
          channel,
          attachments: [attachment]
          },
          (err, response) => {
	          if (err) {
	            console.log(err)
	            res.status(500).send(err)
	          } else {
	            res.status(201).send(response)
	          }
          }
        )
  }
)

slapp.action('share', 'post', (msg, value) => {
	var sharedInChannel = true
	if (!value) {
		sharedInChannel = false
		value = msg.body.actions[0].selected_options[0].value
	}
	var url = msg.body.original_message.attachments[0].title_link
	var userId = msg.body.user.id
    var originalMsg = msg.body.original_message;
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1]
	addUrlToChannel(value, url)
		.then(() => {
			var attachment = {
				color: '#006600',
				text: `${url}
:postbox: Article posted to channel ${value} by <@${userId}>`
			}
			originalMsg.attachments = []
			if (!sharedInChannel) {
				originalMsg.attachments.push(chosenAttachment)
			}
			originalMsg.attachments.push(attachment)
			msg.respond(msg.body.response_url, originalMsg)
		})
		.catch((err) => {
			console.log(err)
			chosenAttachment.color = '#ff9933'
			var lastAttachment = {
					pretext: `:exclamation: Error posting article to channel ${value}`
			}
			originalMsg.attachments = [chosenAttachment, lastAttachment]
			msg.respond(msg.body.response_url, originalMsg)
		})
})

function addUrlToChannel(channelId, url) {
	return new Promise((resolve, reject) => {
		request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/item/add/url',
			{body: url}, (err, res, body) => {
				if (err) return reject(err);
				try {
					JSON.parse(body)[0]
				} catch (err) {
					return reject(err + JSON.stringify(body));
				}
				request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/channel/item/add',
	    			{ json: {
	    				channel_id: channelId,
	    				url: url
	    			}}, (err2, res2, body2) => {
	    				if (err2) return reject(err);
	    				try {
	    					var success = body2.success
	    					if (!success) return reject("No success" + JSON.stringify(body));
	    				} catch (err) {
	    					return reject(err + JSON.stringify(body));
	    				}
	    				resolve();
			})
		})
	})
}

slapp.action('share', 'discard', (msg, value) => {
	var originalMsg = msg.body.original_message
	var url = msg.body.original_message.attachments[0].title_link
	var userId = msg.body.user.id
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1]
    chosenAttachment.actions = []
	var attachment = {
		color: '#800000',
		text: `${url}
:no_entry: Article discarded by <@${userId}>`,
	}
	originalMsg.attachments = [attachment]
	msg.respond(msg.body.response_url, originalMsg)
})

function fetchChannels() {
  slackAPIClient.send('channels.list',
      function(err, response) {
        if (err) console.log(err)
          for (var i = 0; i < response.channels.length; i++) {
            var channel = response.channels[i]
            try {
              var channelNumber = channel.name.split("-")[0]
              if (!isNaN(channelNumber)) {
                channels[channelNumber] = channel.id
              }
            } catch (err) {
              console.log(err)
            }
          }
        console.log(`${Object.keys(channels).length} channels loaded`)
        }
  )
}

function formatCount(x) {
	var magnitude = Math.max(Math.floor(Math.log10(Math.abs(x))), 0);
	var postfix = ""
	var prefix = ""
	if (magnitude >= 6) {
		prefix = ":fire: "
		magnitude -= 6
		postfix = "M"
	} else if (magnitude >= 3) {
		prefix = ":fire: "
		magnitude -= 3
		postfix = "k"
	}
	var first_digit = String(x).charAt(0);
	var rounded_significant = first_digit >= 5 ? 5 : 1;
	return `${prefix}${rounded_significant * Math.pow(10, magnitude)}${postfix}+`
}

// attach Slapp to express server
var server = slapp.attachToExpress(app)
// start http server
server.listen(port, (err) => {
  if (err) {
    return console.log(err)
  }

  console.log(`Listening on port ${port}`)
})<commit_msg>removed success check<commit_after>'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const BeepBoop = require('beepboop')
const bodyParser = require('body-parser')
const parameters = require('parameters-middleware');
var request = require('request')
const slackey = require('slackey')

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

var slackAPIClient
var beepboop = BeepBoop.start()

beepboop.on('open', () => {
  console.log('connection to Beep Boop server opened')
})
beepboop.on('error', (error) => {
  console.log('Error from Beep Boop connection: ', err)
})
beepboop.on('close', (code, message) => {
  console.log('Connection to Beep Boop was closed')
})
beepboop.on('add_resource', (message) => {
  console.log('Team added: ', message.resource.SlackTeamName);
  slackAPIClient = slackey.getAPIClient(message.resource.SlackBotAccessToken);
	fetchChannels();
})
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 app = express()
app.use(bodyParser.json());
app.post('/recommendations',
  parameters({body : ["channel", "title", "url"]}),
  (req, res) => {
    var channelId = req.body.channel
    var channel = channels[channelId]
    if (channel == null) return res.status(400).send("Channel not found")
    var verifiedIcon = req.body.verified ? "https://cdn3.iconfinder.com/data/icons/basicolor-arrows-checks/24/154_check_ok_sticker_success-512.png" : "http://www.clker.com/cliparts/H/Z/0/R/f/S/warning-icon-hi.png"
    var attachment = {
    	callback_id: "share",
	      author_icon: verifiedIcon,
	      title_link: req.body.url,
	      title: req.body.title,
	      actions: [
	          {
	            "name": "post",
	            "text": "Post",
	            "type": "button",
	            "style": "primary",
	            "value": channelId
	          },
	          {
	            "name": "discard",
	            "text": "Discard",
	            "type": "button",
	            "style": "danger",
	            "value": "discarded"
	          },
	          {
                  "name": "post",
                  "text": "Share to channel...",
                  "type": "select",
                  "options": [
            		   {
            		      "text":"1 - Test",
            		      "value":1
            		   },
            		   {
        			     "text":"7 - Digital Marketing",
        			     "value":7
        			   },
        			   {
        			      "text":"40 - Legal",
        			      "value":40
        			   },
        			   {
        			      "text":"43 - Innovation & Startups",
        			      "value":43
        			   },
        			   {
        			      "text":"66 - Journalism",
        			      "value":66
        			   },
        			   {
        			      "text":"76 - Ondernemen",
        			      "value":76
        			   },
        			   {
        			      "text":"82 - Market Trends",
        			      "value":82
        			   },
        			   {
        			      "text":"83 - 9x Awesome Content",
        			      "value":83
        			   },
        			   {
        			      "text":"84 - Business Practices",
        			      "value":84
        			   },
        			   {
        			      "text":"86 - Education Market",
        			      "value":86
        			   },
        			   {
        			      "text":"87 - Venture Capital & Startups",
        			      "value":87
        			   },
        			   {
        			      "text":"89 - Fintech",
        			      "value":89
        			   },
        			   {
        			      "text":"101 - Direct Marketing",
        			      "value":101
        			   },
        			   {
        			      "text":"109 - IT Business",
        			      "value":109
        			   },
        			   {
        			      "text":"116 - NN Algemeen",
        			      "value":116
        			   },
        			   {
        			      "text":"120 - Customer Insights",
        			      "value":120
        			   },
        			   {
        			      "text":"125 - CPS",
        			      "value":125
        			   },
        			   {
        			      "text":"126 - RMS",
        			      "value":126
        			   },
        			   {
        			      "text":"136 - IBM in the Media",
        			      "value":136
        			   },
        			   {
        			      "text":"151 - Randstad in the News",
        			      "value":151
        			   },
        			   {
        			      "text":"152 - Randstad Market Watch",
        			      "value":152
        			   },
        			   {
        			      "text":"170 - IBM Cloud Market Watch",
        			      "value":170
        			   },
        			   {
        			      "text":"219 - IBM Developer Advocates",
        			      "value":219
        			   },
        			   {
        			      "text":"250 - Achmea Transport",
        			      "value":250
        			   },
        			   {
        			      "text":"251 - Achmea Automotive",
        			      "value":251
        			   },
        			   {
        			      "text":"253 - Achmea Innovation",
        			      "value":253
        			   }
        			]
              }
	        ]
    }
    if (req.body.host) {
      attachment.author_name = req.body.host;
      attachment.author_link = `http://${req.body.host}`;
    }
    if (req.body.summary) {
        attachment.text = req.body.summary
    }
    if (req.body.image_url) {
        attachment.image_url = req.body.image_url
    }
    if (req.body.pub_date) {
        attachment.ts = Date.parse(req.body.pub_date) / 1000
    }

    // Populating fields
    var fields = []
    if (req.body.keywords) {
    	if (!req.body.keywords.includes(", ")) {
    		req.body.keywords = req.body.keywords.replace(/,/g, ", ")
    	}
	    fields.push({
	    	title: "Keywords",
	    	short: false,
	    	value: req.body.keywords
	    })
    }
    if (req.body.companies) {
    	if (!req.body.companies.includes(", ")) {
    		req.body.companies = req.body.companies.replace(/,/g, ", ")
    	}
	    fields.push({
	        title: "Companies",
	        short: false,
	        value: req.body.companies
	    })
    }
    if (req.body.word_count) {
    	var length = req.body.word_count
    	var prefix = ""
    	if (length > 1000 )
    		prefix = ":snail: "
    	else if (length < 300)
    		prefix = ":fast_forward: "
    	fields.push({
    		title: "Length",
    		short: true,
    		value: `${prefix}${length} words`
    	})
    }
    if (req.body.shares) {
      fields.push({
        title: "Shares",
        short: true,
        value: formatCount(req.body.shares)
      })
    }
    if (req.body.sentiment) {
    	var sentiment
    	switch (req.body.sentiment) {
    		case "negative":
    			sentiment = ":rage: Negative";
    			break;
    		case "positive":
    			sentiment = ":smile: Positive";
    			break;
    		case "neutral":
    			sentiment = "Neutral"
    			break;
    	}
    	fields.push({
            title: "Sentiment",
            short: true,
            value: sentiment
          })
    }
//    Unsupported for now
//    fields.push({
//    	"title": "Sponsored",
//        "value": ":warning: Undetected",
//        "short": true
//    })
    attachment.fields = fields
    slackAPIClient.send('chat.postMessage',
          {
          channel,
          attachments: [attachment]
          },
          (err, response) => {
	          if (err) {
	            console.log(err)
	            res.status(500).send(err)
	          } else {
	            res.status(201).send(response)
	          }
          }
        )
  }
)

slapp.action('share', 'post', (msg, value) => {
	var sharedInChannel = true
	if (!value) {
		sharedInChannel = false
		value = msg.body.actions[0].selected_options[0].value
	}
	var url = msg.body.original_message.attachments[0].title_link
	var userId = msg.body.user.id
    var originalMsg = msg.body.original_message;
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1]
	addUrlToChannel(value, url)
		.then(() => {
			var attachment = {
				color: '#006600',
				text: `${url}
:postbox: Article posted to channel ${value} by <@${userId}>`
			}
			originalMsg.attachments = []
			if (!sharedInChannel) {
				originalMsg.attachments.push(chosenAttachment)
			}
			originalMsg.attachments.push(attachment)
			msg.respond(msg.body.response_url, originalMsg)
		})
		.catch((err) => {
			console.log(err)
			chosenAttachment.color = '#ff9933'
			var lastAttachment = {
					pretext: `:exclamation: Error posting article to channel ${value}`
			}
			originalMsg.attachments = [chosenAttachment, lastAttachment]
			msg.respond(msg.body.response_url, originalMsg)
		})
})

function addUrlToChannel(channelId, url) {
	return new Promise((resolve, reject) => {
		request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/item/add/url',
			{body: url}, (err, res, body) => {
				if (err) return reject(err);
				try {
					JSON.parse(body)[0]
				} catch (err) {
					return reject(err + JSON.stringify(body));
				}
				request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/channel/item/add',
	    			{ json: {
	    				channel_id: channelId,
	    				url: url
	    			}}, (err2, res2, body2) => {
	    				if (err2) return reject(err);
	    				resolve();
			})
		})
	})
}

slapp.action('share', 'discard', (msg, value) => {
	var originalMsg = msg.body.original_message
	var url = msg.body.original_message.attachments[0].title_link
	var userId = msg.body.user.id
	var chosenAttachment = originalMsg.attachments[msg.body.attachment_id - 1]
    chosenAttachment.actions = []
	var attachment = {
		color: '#800000',
		text: `${url}
:no_entry: Article discarded by <@${userId}>`,
	}
	originalMsg.attachments = [attachment]
	msg.respond(msg.body.response_url, originalMsg)
})

function fetchChannels() {
  slackAPIClient.send('channels.list',
      function(err, response) {
        if (err) console.log(err)
          for (var i = 0; i < response.channels.length; i++) {
            var channel = response.channels[i]
            try {
              var channelNumber = channel.name.split("-")[0]
              if (!isNaN(channelNumber)) {
                channels[channelNumber] = channel.id
              }
            } catch (err) {
              console.log(err)
            }
          }
        console.log(`${Object.keys(channels).length} channels loaded`)
        }
  )
}

function formatCount(x) {
	var magnitude = Math.max(Math.floor(Math.log10(Math.abs(x))), 0);
	var postfix = ""
	var prefix = ""
	if (magnitude >= 6) {
		prefix = ":fire: "
		magnitude -= 6
		postfix = "M"
	} else if (magnitude >= 3) {
		prefix = ":fire: "
		magnitude -= 3
		postfix = "k"
	}
	var first_digit = String(x).charAt(0);
	var rounded_significant = first_digit >= 5 ? 5 : 1;
	return `${prefix}${rounded_significant * Math.pow(10, magnitude)}${postfix}+`
}

// attach Slapp to express server
var server = slapp.attachToExpress(app)
// start http server
server.listen(port, (err) => {
  if (err) {
    return console.log(err)
  }

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


<commit_before>'use strict';

/**
 * App server
 */

require('dotenv').config();

const express = require('express');
const router = express.Router();
const app = express();
const env = process.env.NODE_ENV;
const port = process.env.PORT || process.env.DEV_PORT;

app.set('view engine', 'jade');
app.use(require('morgan')('combined'));
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('compression')());

app.use(require('express-session')({
  secret: process.env.APP_SECRET,
  resave: false,
  saveUninitialized: false
}));

// setup webpack
require('./api/lib/webpack_setup')(app);

// authentication route
require('./api/routes/auth')(app);

// setup proxy for static assets
app.use('/public', require('proxy-middleware')(require('url').parse(`http://localhost:${port}/public/build`)));

app.get('/*', (request, response) => {
  response.render(__dirname + '/public/index.jade');
});

// start server
app.listen(port, () => {
  console.log(`Tweet-threader server running on http://localhost:${port} in ${env} mode`);
});
<commit_msg>remove morgan logger<commit_after>'use strict';

/**
 * App server
 */

require('dotenv').config();

const express = require('express');
const router = express.Router();
const app = express();
const env = process.env.NODE_ENV;
const port = process.env.PORT || process.env.DEV_PORT;

app.set('view engine', 'jade');
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('compression')());

app.use(require('express-session')({
  secret: process.env.APP_SECRET,
  resave: false,
  saveUninitialized: false
}));

// setup webpack
require('./api/lib/webpack_setup')(app);

// authentication route
require('./api/routes/auth')(app);

// setup proxy for static assets
app.use('/public', require('proxy-middleware')(require('url').parse(`http://localhost:${port}/public/build`)));

app.get('/*', (request, response) => {
  response.render(__dirname + '/public/index.jade');
});

// start server
app.listen(port, () => {
  console.log(`Tweet-threader server running on http://localhost:${port} in ${env} mode`);
});
<|endoftext|>


<commit_before>var EngineIO = require("engine.io")
var EventEmitter = require("events").EventEmitter

var EngineStream = require("./eiostream")

module.exports = EngineServer

function EngineServer(onConnection) {
    var engine = new EventEmitter
    var servers = []

    engine.attach = attach
    engine.close = close

    if (onConnection) {
        engine.on("connection", onConnection)
    }

    function attach(httpServer, options) {
        options = options || {}

        if (typeof options === "string") {
            options = { path: options }
        }

        var server = EngineIO.attach(httpServer, options)

        servers.push(server)

        server.on("error", engine.emit.bind(engine, "error"));

        server.on("connection", function (socket) {
            engine.emit("connection", EngineStream(socket))
        })
    }

    function close() {
        servers.forEach(invoke("close"))
    }

    return engine
}

function invoke(method) {
    return function (obj) {
        return obj[method].call(obj)
    }
}
<commit_msg>Replace .call with a normal method call (faster)<commit_after>var EngineIO = require("engine.io")
var EventEmitter = require("events").EventEmitter

var EngineStream = require("./eiostream")

module.exports = EngineServer

function EngineServer(onConnection) {
    var engine = new EventEmitter
    var servers = []

    engine.attach = attach
    engine.close = close

    if (onConnection) {
        engine.on("connection", onConnection)
    }

    function attach(httpServer, options) {
        options = options || {}

        if (typeof options === "string") {
            options = { path: options }
        }

        var server = EngineIO.attach(httpServer, options)

        servers.push(server)

        server.on("error", engine.emit.bind(engine, "error"));

        server.on("connection", function (socket) {
            engine.emit("connection", EngineStream(socket))
        })
    }

    function close() {
        servers.forEach(invoke("close"))
    }

    return engine
}

function invoke(method) {
    return function (obj) {
        return (obj[method])()
    }
}
<|endoftext|>


<commit_before>
//Requires
var express     =   require("express");
var app         =   express();
var bodyParser  =   require("body-parser");
var mongoUser   =   require("./models/mongo").User;
var mongoNote   =   require("./models/mongo").Notes;
var path        =   require("path");
var router      =   express.Router();
var fs          =   require("fs");
var formidable = require("formidable");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
app.use(express.static(path.join(__dirname ,'ficheros')));
app.use(express.static(path.join(__dirname ,'public')));

//Resource users
router.route("/users")
    .get(function(req,res){
        var response = {};
        mongoUser.find({},function(err,data){
            // Mongo command to fetch all data from collection.
            if(err) {
                response = {"error" : true,"message" : "Error fetching data"};
            } else {
                response = {"error" : false,"message" : data};
            }
            res.json(response);
        });
    })
    .post(function(req,res){
        console.log(req.body);
        var db = new mongoUser();
        var response = {};
        // fetch email and password from REST request.
        // Add strict validation when you use this in Production.
        db.user = req.body.email;
        // Hash the password using SHA1 algorithm.
        db.pass =  require('crypto')
            .createHash('sha1')
            .update(req.body.password)
            .digest('base64');

        db.save(function(err){
            // save() will run insert() command of MongoDB.
            // it will add new data in collection.
            if(err) {
                response = {"error" : true,"message" : "Error adding data"};
                res.json(response);

            } else {

                mongoUser.find({},function(err,data){
                    // Mongo command to fetch all data from collection.
                    if(err) {
                        response = {"error" : true,"message" : "Error fetching data"};
                    } else {
                        response = {"error" : false,"message" : data};
                    }
                    res.json(response);
                });

            }
        });
    });

//Resource users/:id
router.route("/users/:id")
    .get(function(req,res){
        var response = {};
        mongoUser.findById(req.params.id,function(err,data){
            // This will run Mongo Query to fetch data based on ID.
            if(err) {
                response = {"error" : true,"message" : "Error fetching data"};
            } else {
                response = {"error" : false,"message" : data};
            }
            res.json(response);
        });
    })
    .put(function(req,res){
        var response = {};
        // first find out record exists or not
        // if it does then update the record
        mongoUser.findById(req.params.id,function(err,data){
            if(err) {
                response = {"error" : true,"message" : "Error fetching data"};
            } else {
                // we got data from Mongo.
                // change it accordingly.
                if(req.body.userEmail !== undefined) {
                    // case where email needs to be updated.
                    data.user = req.body.userEmail;
                }
                if(req.body.userPassword !== undefined) {
                    // case where password needs to be updated
                    data.pass = req.body.userPassword;
                }
                // save the data
                data.save(function(err){
                    if(err) {
                        response = {"error" : true,"message" : "Error updating data"};
                    } else {
                        response = {"error" : false,"message" : "Data is updated for "+req.params.id};
                    }
                    res.json(response);
                })
            }
        });
    })
    .delete(function(req,res){
        var response = {};
        // find the data
        mongoUser.findById(req.params.id,function(err,data){
            if(err) {
                response = {"error" : true,"message" : "Error fetching data"};
            } else {
                // data exists, remove it.
                mongoUser.remove({_id : req.params.id},function(err){
                    if(err) {
                        response = {"error" : true,"message" : "Error deleting data"};
                        res.json(response);
                    } else {

                        mongoUser.find({},function(err,data){
                            // Mongo command to fetch all data from collection.
                            if(err) {
                                response = {"error" : true,"message" : "Error fetching data"};
                            } else {
                                response = {"error" : false,"message" : data};
                            }
                            res.json(response);
                        });

                    }
                });
            }
        });
    });

// Devuelve un Json con todas las notas en la bbdd
app.get("/notes",function(req,res){
    mongoNote.find({},function(err,data){
        // Mongo command to fetch all data from collection.
        if(err) {
            response = {"error" : true,"message" : "Error fetching data"};
        } else {
            response = {"error" : false,"message" : data};
        }
        res.json(response);
    });
});

// Añade una nueva nota a la bbdd y almancena el fichero si es necesario
app.post("/notes",function(req,res){
    console.log("Post note");
    var parse = new formidable.IncomingForm();
    parse.parse(req, function(err,fields,files){
        var db = new mongoNote();
        db.artist = fields.artist;
        db.title = fields.title;
        db.file = files.file.name;
        if(files.file.name != ''){
            var name = files.file.name.replace(/ /g,"_");
            fs.rename(files.file.path,"ficheros/"+name, function(err){
                if(err){
                    console.log("Error");
                }else{
                    db.file = name;
                    db.save(function (err) {
                        if (err) console.log("Error");
                    });
                }
            });
        }else{
            db.save(function (err) {
                if (err) console.log("Error");
            });
        }
        res.writeHead(302, {'Location': '/'});
        res.end();
    });

});

//Borra una nota de la bbdd eliminando el fichero si necesario
app.delete("/notes/:id",function(req,res){
    mongoNote.findById(req.params.id,function(err,data){
        mongoNote.remove({"_id":req.params.id},function(err){
            if(err){
                res.writeHead(500, {'Location': '/error'});
                res.end();
            }else{
                if(data.file != ""){
                    mongoNote.find({"fichero":data.file},function (err,data2) {
                        if (data2.length == 0){
                            fs.unlink("ficheros/"+ data.file, function (err) {
                                if (err) console.log("Error al eliminar fichero");
                            });
                        }
                    });
                }
                res.writeHead(302, {'Location': '/'});
                res.end();
            }
        });
    });
});

app.get("/login",function(req,res){
    res.sendfile('./public/login.html');
});
app.get("/register",function(req,res){
    res.sendfile('./public/register.html');
});
//Main page
app.get('/', function(req, res) {
    res.sendfile('./public/generic.html');
});

//Fichero angular
app.get('/core.js', function(req, res) {
    res.sendfile('./public/core.js');
});

//Server error
app.get('/error', function(req,res){
    res.status(404).send('
500 SERVER ERROR
')
});

//Not Found
app.get('*', function(req,res){
    console.log(req.path);
   res.status(404).send('
404 This is not the Webpage you are looking for
')
});

app.listen(3000);
console.log("Listening to PORT 3000");<commit_msg>Commented some server.js code and changed port<commit_after>
//Requires
var express     =   require("express");
var app         =   express();
var bodyParser  =   require("body-parser");
var mongoUser   =   require("./models/mongo").User;
var mongoNote   =   require("./models/mongo").Notes;
var path        =   require("path");
var router      =   express.Router();
var fs          =   require("fs");
var formidable = require("formidable");

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({"extended" : false}));
app.use(express.static(path.join(__dirname ,'ficheros')));
app.use(express.static(path.join(__dirname ,'public')));

//Resource users
// router.route("/users")
//     .get(function(req,res){
//         var response = {};
//         mongoUser.find({},function(err,data){
//             // Mongo command to fetch all data from collection.
//             if(err) {
//                 response = {"error" : true,"message" : "Error fetching data"};
//             } else {
//                 response = {"error" : false,"message" : data};
//             }
//             res.json(response);
//         });
//     })
//     .post(function(req,res){
//         console.log(req.body);
//         var db = new mongoUser();
//         var response = {};
//         // fetch email and password from REST request.
//         // Add strict validation when you use this in Production.
//         db.user = req.body.email;
//         // Hash the password using SHA1 algorithm.
//         db.pass =  require('crypto')
//             .createHash('sha1')
//             .update(req.body.password)
//             .digest('base64');
//
//         db.save(function(err){
//             // save() will run insert() command of MongoDB.
//             // it will add new data in collection.
//             if(err) {
//                 response = {"error" : true,"message" : "Error adding data"};
//                 res.json(response);
//
//             } else {
//
//                 mongoUser.find({},function(err,data){
//                     // Mongo command to fetch all data from collection.
//                     if(err) {
//                         response = {"error" : true,"message" : "Error fetching data"};
//                     } else {
//                         response = {"error" : false,"message" : data};
//                     }
//                     res.json(response);
//                 });
//
//             }
//         });
//     });
//
// //Resource users/:id
// router.route("/users/:id")
//     .get(function(req,res){
//         var response = {};
//         mongoUser.findById(req.params.id,function(err,data){
//             // This will run Mongo Query to fetch data based on ID.
//             if(err) {
//                 response = {"error" : true,"message" : "Error fetching data"};
//             } else {
//                 response = {"error" : false,"message" : data};
//             }
//             res.json(response);
//         });
//     })
//     .put(function(req,res){
//         var response = {};
//         // first find out record exists or not
//         // if it does then update the record
//         mongoUser.findById(req.params.id,function(err,data){
//             if(err) {
//                 response = {"error" : true,"message" : "Error fetching data"};
//             } else {
//                 // we got data from Mongo.
//                 // change it accordingly.
//                 if(req.body.userEmail !== undefined) {
//                     // case where email needs to be updated.
//                     data.user = req.body.userEmail;
//                 }
//                 if(req.body.userPassword !== undefined) {
//                     // case where password needs to be updated
//                     data.pass = req.body.userPassword;
//                 }
//                 // save the data
//                 data.save(function(err){
//                     if(err) {
//                         response = {"error" : true,"message" : "Error updating data"};
//                     } else {
//                         response = {"error" : false,"message" : "Data is updated for "+req.params.id};
//                     }
//                     res.json(response);
//                 })
//             }
//         });
//     })
//     .delete(function(req,res){
//         var response = {};
//         // find the data
//         mongoUser.findById(req.params.id,function(err,data){
//             if(err) {
//                 response = {"error" : true,"message" : "Error fetching data"};
//             } else {
//                 // data exists, remove it.
//                 mongoUser.remove({_id : req.params.id},function(err){
//                     if(err) {
//                         response = {"error" : true,"message" : "Error deleting data"};
//                         res.json(response);
//                     } else {
//
//                         mongoUser.find({},function(err,data){
//                             // Mongo command to fetch all data from collection.
//                             if(err) {
//                                 response = {"error" : true,"message" : "Error fetching data"};
//                             } else {
//                                 response = {"error" : false,"message" : data};
//                             }
//                             res.json(response);
//                         });
//
//                     }
//                 });
//             }
//         });
//     });

// Devuelve un Json con todas las notas en la bbdd
app.get("/notes",function(req,res){
    mongoNote.find({},function(err,data){
        // Mongo command to fetch all data from collection.
        if(err) {
            response = {"error" : true,"message" : "Error fetching data"};
        } else {
            response = {"error" : false,"message" : data};
        }
        res.json(response);
    });
});

// Añade una nueva nota a la bbdd y almancena el fichero si es necesario
app.post("/notes",function(req,res){
    console.log("Post note");
    var parse = new formidable.IncomingForm();
    parse.parse(req, function(err,fields,files){
        var db = new mongoNote();
        db.artist = fields.artist;
        db.title = fields.title;
        db.file = files.file.name;
        if(files.file.name != ''){
            var name = files.file.name.replace(/ /g,"_");
            fs.rename(files.file.path,"ficheros/"+name, function(err){
                if(err){
                    console.log("Error");
                }else{
                    db.file = name;
                    db.save(function (err) {
                        if (err) console.log("Error");
                    });
                }
            });
        }else{
            db.save(function (err) {
                if (err) console.log("Error");
            });
        }
        res.writeHead(302, {'Location': '/'});
        res.end();
    });

});

//Borra una nota de la bbdd eliminando el fichero si necesario
app.delete("/notes/:id",function(req,res){
    mongoNote.findById(req.params.id,function(err,data){
        mongoNote.remove({"_id":req.params.id},function(err){
            if(err){
                res.writeHead(500, {'Location': '/error'});
                res.end();
            }else{
                if(data.file != ""){
                    mongoNote.find({"fichero":data.file},function (err,data2) {
                        if (data2.length == 0){
                            fs.unlink("ficheros/"+ data.file, function (err) {
                                if (err) console.log("Error al eliminar fichero");
                            });
                        }
                    });
                }
                res.writeHead(302, {'Location': '/'});
                res.end();
            }
        });
    });
});

app.get("/login",function(req,res){
    res.sendfile('./public/login.html');
});
app.get("/register",function(req,res){
    res.sendfile('./public/register.html');
});
//Main page
app.get('/', function(req, res) {
    res.sendfile('./public/generic.html');
});

//Fichero angular
app.get('/core.js', function(req, res) {
    res.sendfile('./public/core.js');
});

//Server error
app.get('/error', function(req,res){
    res.status(404).send('
500 SERVER ERROR
')
});

//Not Found
app.get('*', function(req,res){
    console.log(req.path);
   res.status(404).send('
404 This is not the Webpage you are looking for
')
});

app.listen(8080);
console.log("Listening to PORT 8080");<|endoftext|>


<commit_before>console.log('Starting server in ' + process.env.NODE_ENV + ' mode');

// var express = require('express');
// var app = express();
// app.use(express.static('www'));
// var port = process.env.PORT || 3000;
// app.listen(port);
// console.log('Web server listening on port ' + port);

var sslRedirect = require('heroku-ssl-redirect');
var express = require('express');
var app = express();
app.use(sslRedirect());
app.use(express.static('www'));
var port = process.env.PORT || 3000;
app.listen(port);
console.log('Web server listening on port ' + port);<commit_msg>removing ssl redirect<commit_after>console.log('Starting server in ' + process.env.NODE_ENV + ' mode');

// var express = require('express');
// var app = express();
// app.use(express.static('www'));
// var port = process.env.PORT || 3000;
// app.listen(port);
// console.log('Web server listening on port ' + port);

// var sslRedirect = require('heroku-ssl-redirect');
var express = require('express');
var app = express();
// app.use(sslRedirect());
app.use(express.static('www'));
var port = process.env.PORT || 3000;
app.listen(port);
console.log('Web server listening on port ' + port);<|endoftext|>