<commit_before>"use strict";
// smtp network server

var net         = require('./tls_socket');
var logger      = require('./logger');
var config      = require('./config');
var conn        = require('./connection');
var out         = require('./outbound');
var plugins     = require('./plugins');
var constants   = require('./constants');
var os          = require('os');
var cluster     = require('cluster');
var async       = require('async');
var daemon      = require('daemon');

// Need these here so we can run hooks
for (var key in logger) {
    if (key.match(/^log\w/)) {
        exports[key] = (function (key) {
            return function () {
                var args = ["[server] "];
                for (var i=0, l=arguments.length; i<l; i++) {
                    args.push(arguments[i]);
                }
                logger[key].apply(logger, args);
            }
        })(key);
    }
}

var Server = exports;

var defaults = {
    inactivity_timeout: 600,
    daemonize: false,
    daemon_log_file: '/var/log/haraka.log',
    daemon_pid_file: '/var/run/haraka.pid'
};

function apply_defaults(obj) {
    var key;
    for (key in defaults) {
        obj[key] = obj[key] || defaults[key];
    }
}

Server.daemonize = function (config_data) {
    if (/^(?:1|true|yes|enabled|on)$/i.test(config_data.main.daemonize)) {
        if (!process.env.__daemon) {
            // Remove process.on('exit') listeners otherwise
            // we get a spurious 'Exiting' log entry.
            process.removeAllListeners('exit');
            logger.lognotice('Daemonizing...');
        }
        var log_fd = require('fs').openSync(config_data.main.daemon_log_file, 'a');
        daemon({stdout: log_fd});
        // We are the daemon from here on...
        var npid = require('npid');
        try {
            npid.create(config_data.main.daemon_pid_file);
        }
        catch (err) {
            logger.logerror(err.message);
            process.exit(1);
        }
    }
}

Server.flushQueue = function () {
    if (Server.cluster) {
        for (var id in cluster.workers) {
            cluster.workers[id].send({event: 'outbound.flush_queue'});
        }
    }
    else {
        out.flush_queue();
    }
}

Server.createServer = function (params) {
    var config_data = config.get('smtp.ini');
    var param_key;
    for (param_key in params) {
        if (typeof params[param_key] !== 'function') {
            config_data.main[param_key] = params[param_key];
        }
    }

    // config_data defaults
    apply_defaults(config_data.main);

    var listeners = (config_data.main.listen || '').split(/\s*,\s*/);
    if (listeners[0] === '') listeners = [];
    if (config_data.main.port) {
        var host = config_data.main.listen_host;
        if (!host) {
            host = '[::0]';
            Server.default_host = true;
        }
        listeners.unshift(host + ':' + config_data.main.port);
    }
    if (!listeners.length) {
        Server.default_host = true;
        listeners.push('[::0]:25');
    }

    Server.notes = {};
    plugins.server = Server;
    plugins.load_plugins();

    var inactivity_timeout = (config_data.main.inactivity_timeout || 300) * 1000;

    // Cluster
    if (cluster && config_data.main.nodes) {
        Server.cluster = cluster;
        if (cluster.isMaster) {
            out.scan_queue_pids(function (err, pids) {
                if (err) {
                    Server.logcrit("Scanning queue failed. Shutting down.");
                    process.exit(1);
                }
                Server.daemonize(config_data);
                // Fork workers
                var workers = (config_data.main.nodes === 'cpus') ?
                    os.cpus().length : config_data.main.nodes;
                var new_workers = [];
                for (var i=0; i<workers; i++) {
                    new_workers.push(cluster.fork({ CLUSTER_MASTER_PID: process.pid }));
                }
                for (var i=0; i<pids.length; i++) {
                    new_workers[i % new_workers.length].send({event: 'outbound.load_pid_queue', data: pids[i]});
                }
                cluster.on('online', function (worker) {
                    logger.lognotice('worker ' + worker.id + ' started pid=' + worker.process.pid);
                });
                cluster.on('listening', function (worker, address) {
                    logger.lognotice('worker ' + worker.id + ' listening on ' + address.address + ':' + address.port);
                });
                cluster.on('exit', function (worker, code, signal) {
                    if (signal) {
                        logger.lognotice('worker ' + worker.id + ' killed by signal ' + signal);
                    }
                    else if (code !== 0) {
                        logger.lognotice('worker ' + worker.id + ' exited with error code: ' + code);
                    }
                    if (signal || code !== 0) {
                        // Restart worker
                        var new_worker = cluster.fork({ CLUSTER_MASTER_PID: process.pid });
                        new_worker.send({event: 'outbound.load_pid_queue', data: worker.process.pid});
                    }
                });
                plugins.run_hooks('init_master', Server);
            });
        }
        else {
            // Workers
            setup_listeners(listeners, plugins, "child", inactivity_timeout);
        }
    }
    else {
        this.daemonize(config_data);
        setup_listeners(listeners, plugins, "master", inactivity_timeout);
    }
};

function setup_listeners (listeners, plugins, type, inactivity_timeout) {
    async.each(listeners, function (host_port, cb) {
        var hp = /^\[?([^\]]+)\]?:(\d+)$/.exec(host_port);
        if (!hp) {
            return cb(new Error("Invalid format for listen parameter in smtp.ini"));
        }

        var server;
        if (hp[2] == 465) {
            var options = {
                key: config.get('tls_key.pem', 'binary'),
                cert: config.get('tls_cert.pem', 'binary'),
            };
            if (!options.key) {
                return cb(new Error("Missing tls_key.pem for port 465"));
            }
            if (!options.cert) {
                return cb(new Error("Missing tls_cert.pem for port 465"));
            }
            logger.lognotice("Creating TLS server on " + host_port);
            server = require('tls').createServer(options, function (client) {
                client.setTimeout(inactivity_timeout);
                conn.createConnection(client, server);
            });
            server.has_tls=true;
        }
        else {
            server = net.createServer(function (client) {
                client.setTimeout(inactivity_timeout);
                conn.createConnection(client, server);
            });
        }

        server.notes = Server.notes;
        if (Server.cluster) server.cluster = Server.cluster;

        server.on('listening', function () {
            var addr = this.address();
            logger.lognotice("Listening on " + addr.address + ':' + addr.port);
            cb();
        });

        // Fallback from IPv6 to IPv4 if not supported
        // But only if we supplied the default of [::0]:25
        server.on('error', function (e) {
            if (e.code === 'EAFNOSUPPORT' && /^::0/.test(hp[1]) && Server.default_host) {
                server.listen(hp[2], '0.0.0.0');
            }
            else {
                // Pass error to callback
                cb(e);
            }
        });

        server.listen(hp[2], hp[1]);
    }, function (err) {
        if (err) {
            logger.logerror("Failed to setup listeners: " + err.message);
            return process.exit(-1);
        }
        listening();
        plugins.run_hooks('init_' + type, Server);
    });
}

Server.init_master_respond = function (retval, msg) {
    Server.ready = 1;
    switch(retval) {
        case constants.ok:
        case constants.cont:
                // Load the queue if we're just one process
                if (!(cluster && config.get('smtp.ini').main.nodes)) {
                    out.load_queue();
                }
                break;
        default:
                Server.logerror("init_master returned error" + ((msg) ? ': ' + msg : ''));
                process.exit(1);
    }
}

Server.init_child_respond = function (retval, msg) {
    switch(retval) {
        case constants.ok:
        case constants.cont:
                break;
        default:
                var pid = process.env.CLUSTER_MASTER_PID;
                Server.logerror("init_child returned error" + ((msg) ? ': ' + msg : ''));
                try {
                    if (pid) {
                        process.kill(pid);
                        Server.logerror('Killing master (pid=' + pid + ')');
                    }
                }
                catch (err) {
                    Server.logerror('Terminating child');
                }
                process.exit(1);
    }
}

function listening () {
    var config_data = config.get('smtp.ini');

    // Drop privileges
    if (config_data.main.group) {
        Server.lognotice('Switching from current gid: ' + process.getgid());
        process.setgid(config_data.main.group);
        Server.lognotice('New gid: ' + process.getgid());
    }
    if (config_data.main.user) {
        Server.lognotice('Switching from current uid: ' + process.getuid());
        process.setuid(config_data.main.user);
        Server.lognotice('New uid: ' + process.getuid());
    }

    Server.ready = 1;
}
<commit_msg>server: consoldiated duplicate callback<commit_after>"use strict";
// smtp network server

var net         = require('./tls_socket');
var logger      = require('./logger');
var config      = require('./config');
var conn        = require('./connection');
var out         = require('./outbound');
var plugins     = require('./plugins');
var constants   = require('./constants');
var os          = require('os');
var cluster     = require('cluster');
var async       = require('async');
var daemon      = require('daemon');

// Need these here so we can run hooks
for (var key in logger) {
    if (key.match(/^log\w/)) {
        exports[key] = (function (key) {
            return function () {
                var args = ["[server] "];
                for (var i=0, l=arguments.length; i<l; i++) {
                    args.push(arguments[i]);
                }
                logger[key].apply(logger, args);
            }
        })(key);
    }
}

var Server = exports;

var defaults = {
    inactivity_timeout: 600,
    daemonize: false,
    daemon_log_file: '/var/log/haraka.log',
    daemon_pid_file: '/var/run/haraka.pid'
};

function apply_defaults(obj) {
    var key;
    for (key in defaults) {
        obj[key] = obj[key] || defaults[key];
    }
}

Server.daemonize = function (config_data) {
    if (/^(?:1|true|yes|enabled|on)$/i.test(config_data.main.daemonize)) {
        if (!process.env.__daemon) {
            // Remove process.on('exit') listeners otherwise
            // we get a spurious 'Exiting' log entry.
            process.removeAllListeners('exit');
            logger.lognotice('Daemonizing...');
        }
        var log_fd = require('fs').openSync(config_data.main.daemon_log_file, 'a');
        daemon({stdout: log_fd});
        // We are the daemon from here on...
        var npid = require('npid');
        try {
            npid.create(config_data.main.daemon_pid_file);
        }
        catch (err) {
            logger.logerror(err.message);
            process.exit(1);
        }
    }
}

Server.flushQueue = function () {
    if (Server.cluster) {
        for (var id in cluster.workers) {
            cluster.workers[id].send({event: 'outbound.flush_queue'});
        }
    }
    else {
        out.flush_queue();
    }
}

Server.createServer = function (params) {
    var config_data = config.get('smtp.ini');
    var param_key;
    for (param_key in params) {
        if (typeof params[param_key] !== 'function') {
            config_data.main[param_key] = params[param_key];
        }
    }

    // config_data defaults
    apply_defaults(config_data.main);

    var listeners = (config_data.main.listen || '').split(/\s*,\s*/);
    if (listeners[0] === '') listeners = [];
    if (config_data.main.port) {
        var host = config_data.main.listen_host;
        if (!host) {
            host = '[::0]';
            Server.default_host = true;
        }
        listeners.unshift(host + ':' + config_data.main.port);
    }
    if (!listeners.length) {
        Server.default_host = true;
        listeners.push('[::0]:25');
    }

    Server.notes = {};
    plugins.server = Server;
    plugins.load_plugins();

    var inactivity_timeout = (config_data.main.inactivity_timeout || 300) * 1000;

    // Cluster
    if (cluster && config_data.main.nodes) {
        Server.cluster = cluster;
        if (cluster.isMaster) {
            out.scan_queue_pids(function (err, pids) {
                if (err) {
                    Server.logcrit("Scanning queue failed. Shutting down.");
                    process.exit(1);
                }
                Server.daemonize(config_data);
                // Fork workers
                var workers = (config_data.main.nodes === 'cpus') ?
                    os.cpus().length : config_data.main.nodes;
                var new_workers = [];
                for (var i=0; i<workers; i++) {
                    new_workers.push(cluster.fork({ CLUSTER_MASTER_PID: process.pid }));
                }
                for (var i=0; i<pids.length; i++) {
                    new_workers[i % new_workers.length].send({event: 'outbound.load_pid_queue', data: pids[i]});
                }
                cluster.on('online', function (worker) {
                    logger.lognotice('worker ' + worker.id + ' started pid=' + worker.process.pid);
                });
                cluster.on('listening', function (worker, address) {
                    logger.lognotice('worker ' + worker.id + ' listening on ' + address.address + ':' + address.port);
                });
                cluster.on('exit', function (worker, code, signal) {
                    if (signal) {
                        logger.lognotice('worker ' + worker.id + ' killed by signal ' + signal);
                    }
                    else if (code !== 0) {
                        logger.lognotice('worker ' + worker.id + ' exited with error code: ' + code);
                    }
                    if (signal || code !== 0) {
                        // Restart worker
                        var new_worker = cluster.fork({ CLUSTER_MASTER_PID: process.pid });
                        new_worker.send({event: 'outbound.load_pid_queue', data: worker.process.pid});
                    }
                });
                plugins.run_hooks('init_master', Server);
            });
        }
        else {
            // Workers
            setup_listeners(listeners, plugins, "child", inactivity_timeout);
        }
    }
    else {
        this.daemonize(config_data);
        setup_listeners(listeners, plugins, "master", inactivity_timeout);
    }
};

function setup_listeners (listeners, plugins, type, inactivity_timeout) {
    async.each(listeners, function (host_port, cb) {
        var hp = /^\[?([^\]]+)\]?:(\d+)$/.exec(host_port);
        if (!hp) {
            return cb(new Error("Invalid format for listen parameter in smtp.ini"));
        }

        var conn_cb = function (client) {
            client.setTimeout(inactivity_timeout);
            conn.createConnection(client, server);
        };

        var server;
        if (hp[2] == 465) {
            var options = {
                key: config.get('tls_key.pem', 'binary'),
                cert: config.get('tls_cert.pem', 'binary'),
            };
            if (!options.key) {
                return cb(new Error("Missing tls_key.pem for port 465"));
            }
            if (!options.cert) {
                return cb(new Error("Missing tls_cert.pem for port 465"));
            }
            logger.lognotice("Creating TLS server on " + host_port);
            server = require('tls').createServer(options, conn_cb);
            server.has_tls=true;
        }
        else {
            server = net.createServer(conn_cb);
        }

        server.notes = Server.notes;
        if (Server.cluster) server.cluster = Server.cluster;

        server.on('listening', function () {
            var addr = this.address();
            logger.lognotice("Listening on " + addr.address + ':' + addr.port);
            cb();
        });

        // Fallback from IPv6 to IPv4 if not supported
        // But only if we supplied the default of [::0]:25
        server.on('error', function (e) {
            if (e.code === 'EAFNOSUPPORT' && /^::0/.test(hp[1]) && Server.default_host) {
                server.listen(hp[2], '0.0.0.0');
            }
            else {
                // Pass error to callback
                cb(e);
            }
        });

        server.listen(hp[2], hp[1]);
    }, function (err) {
        if (err) {
            logger.logerror("Failed to setup listeners: " + err.message);
            return process.exit(-1);
        }
        listening();
        plugins.run_hooks('init_' + type, Server);
    });
}

Server.init_master_respond = function (retval, msg) {
    Server.ready = 1;
    switch(retval) {
        case constants.ok:
        case constants.cont:
                // Load the queue if we're just one process
                if (!(cluster && config.get('smtp.ini').main.nodes)) {
                    out.load_queue();
                }
                break;
        default:
                Server.logerror("init_master returned error" + ((msg) ? ': ' + msg : ''));
                process.exit(1);
    }
}

Server.init_child_respond = function (retval, msg) {
    switch(retval) {
        case constants.ok:
        case constants.cont:
                break;
        default:
                var pid = process.env.CLUSTER_MASTER_PID;
                Server.logerror("init_child returned error" + ((msg) ? ': ' + msg : ''));
                try {
                    if (pid) {
                        process.kill(pid);
                        Server.logerror('Killing master (pid=' + pid + ')');
                    }
                }
                catch (err) {
                    Server.logerror('Terminating child');
                }
                process.exit(1);
    }
}

function listening () {
    var config_data = config.get('smtp.ini');

    // Drop privileges
    if (config_data.main.group) {
        Server.lognotice('Switching from current gid: ' + process.getgid());
        process.setgid(config_data.main.group);
        Server.lognotice('New gid: ' + process.getgid());
    }
    if (config_data.main.user) {
        Server.lognotice('Switching from current uid: ' + process.getuid());
        process.setuid(config_data.main.user);
        Server.lognotice('New uid: ' + process.getuid());
    }

    Server.ready = 1;
}
<|endoftext|>


<commit_before>(function() {

})();

function TreeNode() {

}

/**
 * data structure
 * 初始化节点结构
 */
{
	'core': {
		'data': [
			// 根节点
			{"id": "root", "parent": "#", "text": "前端工程师"},
			// 二级节点
			{"id": "node_1", "parent": "root", "text": "技术"},
			{"id": "node_2", "parent": "root", "text": "IT公司"},
			{"id": "node_3", "parent": "root", "text": "技术"},
			// 三级节点
			// 技术
			{"id": "node_1_1", "parent": "node_1", "text": "HTML5"},
			{"id": "node_1_2", "parent": "node_1", "text": "JavaScript"},
			{"id": "node_1_3", "parent": "node_1", "text": "PHP"},
			{"id": "node_1_4", "parent": "node_1", "text": "Node.js"},
			// IT公司
			{"id": "node_2_1", "parent": "node_2", "text": "baidu"},
			{"id": "node_2_2", "parent": "node_2", "text": "meituan"},
			{"id": "node_2_3", "parent": "node_2", "text": "qunar"},
			// 生活
			{"id": "node_3_1", "parent": "node_3", "text": "美食"},
			{"id": "node_3_2", "parent": "node_3", "text": "旅游"},
			// 四级节点
			// Node.js
			{"id": "node_4_1", "parent": "node_1_4", "text": "grunt"},
			{"id": "node_4_2", "parent": "node_1_4", "text": "gulp"},
		]
	}
}

function addHandler(element, type, handler) {
	if (element.addEventListener) {
		addHandler = function(element, type, handler) {
			element.addEventListener(type, handler, false);
		}
	} else if (element.attachEvent) {
		addHandler = function(element, type, handler) {
			element.attachEvent("on" +type, handler ) ;
		}
	} else {
		addHandler = function(element, type, handler) {
			element["on" + type] = handler;
		}
	}
}<commit_msg>增加参考注释<commit_after>// 参考jsTree:  https://github.com/vakata/jstree

(function() {

})();

function TreeNode() {

}

/**
 * data structure
 * 初始化节点结构
 */
{
	'core': {
		'data': [
			// 根节点
			{"id": "root", "parent": "#", "text": "前端工程师"},
			// 二级节点
			{"id": "node_1", "parent": "root", "text": "技术"},
			{"id": "node_2", "parent": "root", "text": "IT公司"},
			{"id": "node_3", "parent": "root", "text": "技术"},
			// 三级节点
			// 技术
			{"id": "node_1_1", "parent": "node_1", "text": "HTML5"},
			{"id": "node_1_2", "parent": "node_1", "text": "JavaScript"},
			{"id": "node_1_3", "parent": "node_1", "text": "PHP"},
			{"id": "node_1_4", "parent": "node_1", "text": "Node.js"},
			// IT公司
			{"id": "node_2_1", "parent": "node_2", "text": "baidu"},
			{"id": "node_2_2", "parent": "node_2", "text": "meituan"},
			{"id": "node_2_3", "parent": "node_2", "text": "qunar"},
			// 生活
			{"id": "node_3_1", "parent": "node_3", "text": "美食"},
			{"id": "node_3_2", "parent": "node_3", "text": "旅游"},
			// 四级节点
			// Node.js
			{"id": "node_4_1", "parent": "node_1_4", "text": "grunt"},
			{"id": "node_4_2", "parent": "node_1_4", "text": "gulp"},
		]
	}
}

function addHandler(element, type, handler) {
	if (element.addEventListener) {
		addHandler = function(element, type, handler) {
			element.addEventListener(type, handler, false);
		}
	} else if (element.attachEvent) {
		addHandler = function(element, type, handler) {
			element.attachEvent("on" +type, handler ) ;
		}
	} else {
		addHandler = function(element, type, handler) {
			element["on" + type] = handler;
		}
	}
}<|endoftext|>


<commit_before>var config = module.exports = {};

var fs = require('fs');
config.data = [];

config.update = function (req) {

	var data = config.get(req);
	config.set()[data.id - 1] = data;

	return config.set();
};

config.get = function(req) {
	return {
		id: req.body.id,
		name: req.body.name,
		setting: req.body.setting
	};
};

config.set = function() {
	config.data = require('../config.json');
	return config.data;
};
<commit_msg>interchanged set to get<commit_after>var config = module.exports = {};

var fs = require('fs');

config.data = [];

config.update = function (req) {
	var data = config.get();
	var newConfig = {
		id: req.body.id,
		name: req.body.name,
		setting: req.body.setting
	};

	data[newConfig.id - 1] = newConfig;
	config.set(data);
	return data;
};

config.get = function() {
	config.data = require('../config.json');
	return config.data;
};

config.set = function(data) {
	fs.writeFile('../config.json', data, 'utf8', function (err) {
		if (err) {
			return console.log(err);
		}
	});
};
<|endoftext|>


<commit_before>'use strict';

var api = require('../core/api'),
    _ = require('../tools/tools'),
    http = require('http-browser'),
    $q = require('q-promise'),
    cssHack = require('../tools/css-hack');

function checkout (options) {

  options = options || {};
  var baseUrl = ( options.host === 'location' ? location.origin : options.host ) || 'https://aplazame.com/static/checkout/';

  if( !/\/$/.test(baseUrl) ) {
    baseUrl += '/';
  }

  var iframeSrc = baseUrl + 'iframe.html?' + new Date().getTime(),
      errorLoading = false,
      tmpOverlay = document.createElement('div'),
      cssOverlay = cssHack('overlay'),
      cssBlur = cssHack('blur'),
      cssLogo = cssHack('logo'),
      cssModal = cssHack('modal');

  tmpOverlay.className = 'aplazame-overlay aplazame-overlay-show';

  cssOverlay.hack(true);
  cssLogo.hack(true);
  cssBlur.hack(true);

  setTimeout(function () {
    if( !errorLoading ) {
      _.addClass(document.body, 'aplazame-blur');
    }
  }, 0);

  tmpOverlay.innerHTML = '

' +
  require('./loading-svg') + '

Cargando pasarela de pago...

';

  document.body.appendChild(tmpOverlay);

  var loadingText = tmpOverlay.querySelector('.aplazame-overlay-loading-text');

  setTimeout(function () {
    if( !errorLoading ) {
      tmpOverlay.querySelector('.logo-aplazame').className += ' animate';
    }
  }, 200);

  options.api = api;

  return http( iframeSrc ).then(function (response) {
      var iframeHtml = response.data.replace(//, '<base href="' + baseUrl + '" />'),
          iframe = _.getIFrame({
            top: 0,
            left: 0,
            width: '100%',
            height: '0',
            background: 'transparent'
          });

      iframe.className = 'aplazame-modal';
      iframe.style.display = 'none';

      document.body.appendChild(iframe);
      iframe.src = iframeSrc;

      if( !options.merchant ) {
        throw new Error('missing merchant parameters');
      }

      if( !options.merchant.public_api_key ) {
        if( api.publicKey ) {
          options.merchant.public_api_key = api.publicKey;
        } else {
          throw new Error('missing public key');
        }
      }

      options.origin = {
        href: location.href,
        host: location.host,
        protocol: location.protocol,
        origin: location.origin
      };

      _.onMessage('checkout', function (e, message) {

        switch( message.event ) {
          case 'merchant':
            iframe.style.display = null;
            e.source.postMessage({
              checkout: options
            }, '*');
            break;
          case 'show-iframe':
            _.removeClass(iframe, 'hide');
            cssModal.hack(true);
            cssOverlay.hack(false);
            document.body.removeChild(tmpOverlay);
            break;
          case 'loading-text':
            loadingText.textContent = message.text;
            break;
          case 'drop-blur':
            _.removeClass(document.body, 'aplazame-blur');
            _.addClass(document.body, 'aplazame-unblur');
            setTimeout(function () {
              document.head.removeChild(cssBlur);
            }, 600);
            break;
          case 'success':
            _.log('aplazame.checkout:success', message);

            http( options.merchant.confirmation_url, {
              method: 'post',
              contentType: 'application/json',
              data: message.data,
              params: message.params
            } ).then(function (response) {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'success',
                response: http.plainResponse(response)
              }, '*');
            }, function () {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'error',
                response: http.plainResponse(response)
              }, '*');
            });
            // confirmation_url
            break;
          case 'close':
            if( iframe ) {
              document.body.removeChild(iframe);
              cssModal.hack(false);
              iframe = null;

              switch( message.result ) {
                case 'dismiss':
                  location.replace(options.merchant.checkout_url || '/');
                  break;
                case 'success':
                  location.replace(options.merchant.success_url);
                  break;
                case 'cancel':
                  location.replace(options.merchant.cancel_url);
                  break;
              }
            }
            break;
        }

      });

    }).catch(function (reason) {
      // throw new Error('can not connect to ' + baseUrl);
      errorLoading = true;

      console.error('Aplazame ' + reason);

      _.removeClass(tmpOverlay.querySelector('.logo-aplazame'), 'animate');
      loadingText.innerHTML = '
Error cargando pasarela de pago

soporte: soporte@aplazame.com
';
      loadingText.style.lineHeight = '1.5';

      (options.onError || _.noop)(reason);
    });

}

module.exports = checkout;
<commit_msg>changing error text<commit_after>'use strict';

var api = require('../core/api'),
    _ = require('../tools/tools'),
    http = require('http-browser'),
    $q = require('q-promise'),
    cssHack = require('../tools/css-hack');

function checkout (options) {

  options = options || {};
  var baseUrl = ( options.host === 'location' ? location.origin : options.host ) || 'https://aplazame.com/static/checkout/';

  if( !/\/$/.test(baseUrl) ) {
    baseUrl += '/';
  }

  var iframeSrc = baseUrl + 'iframe.html?' + new Date().getTime(),
      errorLoading = false,
      tmpOverlay = document.createElement('div'),
      cssOverlay = cssHack('overlay'),
      cssBlur = cssHack('blur'),
      cssLogo = cssHack('logo'),
      cssModal = cssHack('modal');

  tmpOverlay.className = 'aplazame-overlay aplazame-overlay-show';

  cssOverlay.hack(true);
  cssLogo.hack(true);
  cssBlur.hack(true);

  setTimeout(function () {
    if( !errorLoading ) {
      _.addClass(document.body, 'aplazame-blur');
    }
  }, 0);

  tmpOverlay.innerHTML = '

' +
  require('./loading-svg') + '

Cargando pasarela de pago...

';

  document.body.appendChild(tmpOverlay);

  var loadingText = tmpOverlay.querySelector('.aplazame-overlay-loading-text');

  setTimeout(function () {
    if( !errorLoading ) {
      tmpOverlay.querySelector('.logo-aplazame').className += ' animate';
    }
  }, 200);

  options.api = api;

  return http( iframeSrc ).then(function (response) {
      var iframeHtml = response.data.replace(//, '<base href="' + baseUrl + '" />'),
          iframe = _.getIFrame({
            top: 0,
            left: 0,
            width: '100%',
            height: '0',
            background: 'transparent'
          });

      iframe.className = 'aplazame-modal';
      iframe.style.display = 'none';

      document.body.appendChild(iframe);
      iframe.src = iframeSrc;

      if( !options.merchant ) {
        throw new Error('missing merchant parameters');
      }

      if( !options.merchant.public_api_key ) {
        if( api.publicKey ) {
          options.merchant.public_api_key = api.publicKey;
        } else {
          throw new Error('missing public key');
        }
      }

      options.origin = {
        href: location.href,
        host: location.host,
        protocol: location.protocol,
        origin: location.origin
      };

      _.onMessage('checkout', function (e, message) {

        switch( message.event ) {
          case 'merchant':
            iframe.style.display = null;
            e.source.postMessage({
              checkout: options
            }, '*');
            break;
          case 'show-iframe':
            _.removeClass(iframe, 'hide');
            cssModal.hack(true);
            cssOverlay.hack(false);
            document.body.removeChild(tmpOverlay);
            break;
          case 'loading-text':
            loadingText.textContent = message.text;
            break;
          case 'drop-blur':
            _.removeClass(document.body, 'aplazame-blur');
            _.addClass(document.body, 'aplazame-unblur');
            setTimeout(function () {
              document.head.removeChild(cssBlur);
            }, 600);
            break;
          case 'success':
            _.log('aplazame.checkout:success', message);

            http( options.merchant.confirmation_url, {
              method: 'post',
              contentType: 'application/json',
              data: message.data,
              params: message.params
            } ).then(function (response) {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'success',
                response: http.plainResponse(response)
              }, '*');
            }, function () {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'error',
                response: http.plainResponse(response)
              }, '*');
            });
            // confirmation_url
            break;
          case 'close':
            if( iframe ) {
              document.body.removeChild(iframe);
              cssModal.hack(false);
              iframe = null;

              switch( message.result ) {
                case 'dismiss':
                  location.replace(options.merchant.checkout_url || '/');
                  break;
                case 'success':
                  location.replace(options.merchant.success_url);
                  break;
                case 'cancel':
                  location.replace(options.merchant.cancel_url);
                  break;
              }
            }
            break;
        }

      });

    }).catch(function (reason) {
      // throw new Error('can not connect to ' + baseUrl);
      errorLoading = true;

      console.error('Aplazame ' + reason);

      _.removeClass(tmpOverlay.querySelector('.logo-aplazame'), 'animate');
      loadingText.innerHTML = '
Error cargando pasarela de pago

soporte@aplazame.com
';
      loadingText.style.lineHeight = '1.5';

      (options.onError || _.noop)(reason);
    });

}

module.exports = checkout;
<|endoftext|>


<commit_before>var gulp = require('gulp'),
        runSequence = require('run-sequence'),
        clean = require('gulp-rimraf'),
        copy = require('gulp-copy'),
        less = require('gulp-less'),
        concat = require('gulp-concat'),
        jshint = require('gulp-jshint'),
        autoprefixer = require('gulp-autoprefixer'),
        minifyCss = require('gulp-minify-css'),
        uglify = require('gulp-uglify'),
        imagemin = require('gulp-imagemin'),
        pngquant = require('imagemin-pngquant'),
        watch = require('gulp-watch');

/*
 * Clear
 */
gulp.task('clear:admin', function () {
    return gulp.src('./_dev/admin/css/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:site', function () {
    return gulp.src('./_dev/site/css/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:global:css', function () {
    return gulp.src('./_dev/global/css/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:global:js', function () {
    return gulp.src([
        './_dev/global/js/all.js',
        './_dev/global/js/bootstrap.js',
        './_dev/global/js/jquery.js'
    ], {read: false}).pipe(clean());
});
gulp.task('clear:build:css', function () {
    return gulp.src('./_dev/build/**/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:build:js', function () {
    return gulp.src('./_dev/build/**/*.js', {read: false}).pipe(clean());
});
gulp.task('clear:minify:admin:css', function () {
    return gulp.src('./admin/css/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:minify:admin:js', function () {
    return gulp.src('./admin/js/*.js', {read: false}).pipe(clean());
});
gulp.task('clear:minify:site:css', function () {
    return gulp.src('./css/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:minify:site:js', function () {
    return gulp.src('./js/*.js', {read: false}).pipe(clean());
});
gulp.task('clear:minify', ['clear:minify:admin:css', 'clear:minify:admin:js', 'clear:minify:site:css', 'clear:minify:site:js']);
gulp.task('clear:build', ['clear:build:css', 'clear:build:js']);
gulp.task('clear:global', ['clear:global:css', 'clear:global:js']);
gulp.task('clear:css', ['clear:admin', 'clear:site', 'clear:global', 'clear:build:css', 'clear:minify:css']);
gulp.task('clear:js', ['clear:global:js', 'clear:build:js', 'clear:minify:js']);
gulp.task('clear', ['clear:admin', 'clear:site', 'clear:global', 'clear:build', 'clear:minify']);

/*
 * Bower copy
 */
gulp.task('bower:css', function () {
    return gulp.src('./bower_components/bootstrap/dist/css/bootstrap.css')
            .pipe(copy('./_dev/global/css', {prefix: 5}));
});
gulp.task('bower:js', function () {
    return gulp.src([
        './bower_components/jquery/dist/jquery.js',
        './bower_components/bootstrap/dist/js/bootstrap.js'
    ]).pipe(copy('./_dev/global/js', {prefix: 5}));
});
gulp.task('bower', ['bower:css', 'bower:js']);

/*
 * Less
 */
gulp.task('less:admin', function () {
    return gulp.src('./_dev/admin/css/*.less')
            .pipe(less())
            .pipe(gulp.dest('./_dev/admin/css'));
});
gulp.task('less:site', function () {
    return gulp.src('./_dev/site/css/*.less')
            .pipe(less())
            .pipe(gulp.dest('./_dev/site/css'));
});
gulp.task('less:global', function () {
    return gulp.src('./_dev/global/css/*.less')
            .pipe(less())
            .pipe(gulp.dest('./_dev/global/css'));
});
gulp.task('less', ['less:global', 'less:admin', 'less:site']);

/*
 * Auto prefixer
 */
gulp.task('prefix:admin', function () {
    return gulp.src('./_dev/admin/css/*.css')
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            })).pipe(gulp.dest('./_dev/admin/css'));
});
gulp.task('prefix:site', function () {
    return gulp.src('./_dev/site/css/*.css')
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            })).pipe(gulp.dest('./_dev/site/css'));
});
gulp.task('prefix:global', function () {
    return gulp.src('./_dev/global/css/global.css')
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            })).pipe(gulp.dest('./_dev/global/css'));
});
gulp.task('prefix', ['prefix:global', 'prefix:admin', 'prefix:site']);

/*
 * Concat site CSS & JS
 */
// CSS
gulp.task('concat:global:css', function () {
    return gulp.src([
        './_dev/global/css/bootstrap.css',
        './_dev/global/css/global.css'
    ]).pipe(concat('all.css')).pipe(gulp.dest('./_dev/global/css'));
});
gulp.task('concat:admin:css', function () {
    return gulp.src([
        './_dev/global/css/all.css',
        './_dev/admin/css/admin.css'
    ]).pipe(concat('style.min.css')).pipe(gulp.dest('./_dev/build/admin'));
});
gulp.task('concat:site:css', function () {
    return gulp.src([
        './_dev/global/css/all.css',
        './_dev/site/css/site.css'
    ]).pipe(concat('style.min.css')).pipe(gulp.dest('./_dev/build/site'));
});
// JS
gulp.task('concat:global:js', function () {
    return gulp.src([
        './_dev/global/js/jquery.js',
        './_dev/global/js/bootstrap.js',
        './_dev/global/js/script.js'
    ]).pipe(concat('all.js')).pipe(gulp.dest('./_dev/global/js'));
});
gulp.task('concat:site:js', function () {
    return gulp.src([
        './_dev/global/js/all.js',
        './_dev/site/js/*.js'
    ]).pipe(concat('style.min.js')).pipe(gulp.dest('./_dev/build/site'));
});
gulp.task('concat:admin:js', function () {
    return gulp.src([
        './_dev/global/js/all.js',
        './_dev/admin/js/*.js'
    ]).pipe(concat('script.min.js')).pipe(gulp.dest('./_dev/build/admin'));
});
gulp.task('concat:global', ['concat:global:css', 'concat:global:js']);
gulp.task('concat:admin', ['concat:admin:css', 'concat:admin:js']);
gulp.task('concat:site', ['concat:site:css', 'concat:site:js']);
gulp.task('concat', function (callback) {
    runSequence('concat:global', 'concat:admin', 'concat:site', callback);
});

/*
 * Minify CSS & JS
 */
// CSS
gulp.task('minify:admin:css', function () {
    return gulp.src('./_dev/build/admin/*.css')
            .pipe(minifyCss({compatibility: 'ie8'}))
            .pipe(gulp.dest('./admin/css'));
});
gulp.task('minify:site:css', function () {
    return gulp.src('./_dev/build/site/*.css')
            .pipe(minifyCss({compatibility: 'ie8'}))
            .pipe(gulp.dest('./css'));
});
// JS
gulp.task('minify:admin:js', function () {
    return gulp.src('./_dev/build/admin/*.js')
            .pipe(uglify())
            .pipe(gulp.dest('./admin/js'));
});
gulp.task('minify:site:js', function () {
    return gulp.src('./_dev/build/site/*.js')
            .pipe(uglify())
            .pipe(gulp.dest('./js'));
});
gulp.task('minify:admin', ['minify:admin:css', 'minify:admin:js']);
gulp.task('minify:site', ['minify:site:css', 'minify:site:js']);
gulp.task('minify', ['minify:admin', 'minify:site']);

/*
 * Minify images
 */
gulp.task('imagemin:admin', function() {
    return gulp.src('./_dev/admin/img/**/*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest('./admin/img'));
});
gulp.task('imagemin:site', function() {
    return gulp.src('./_dev/site/img/**/*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest('./img'));
});
gulp.task('imagemin', ['imagemin:admin', 'imagemin:site']);

/*
 * JS Hint
 */
gulp.task('jshint', function () {
    return gulp.src([
        './_dev/admin/js/*.js',
        './_dev/site/js/*.js',
        './_dev/global/js/script.js',
        './gulpfile.js'
    ]).pipe(jshint()).pipe(jshint.reporter('default'));
});

gulp.task('default', function (callback) {
    runSequence('clear', 'bower', 'less', 'prefix', 'concat', 'minify', 'imagemin', 'jshint', callback);
});

/*
 * Watch
 */
gulp.task('watch', function () {
    // Less
    gulp.watch('./_dev/global/css/global.less', ['less:global']);
    gulp.watch('./_dev/admin/css/admin.less', ['less:admin']);
    gulp.watch('./_dev/site/css/site.less', ['less:site']);
    // Concat CSS
    gulp.watch('./_dev/global/css/global.css', ['concat:global:css']);
    gulp.watch('./_dev/admin/css/admin.css', ['concat:admin:css']);
    gulp.watch('./_dev/site/css/site.css', ['concat:site:css']);
    // Concat JS
    gulp.watch('./_dev/global/js/script.js', ['concat:global:js', 'concat:admin:js', 'concat:site:js', 'jshint']);
    gulp.watch('./_dev/admin/js/script.js', ['concat:admin:js', 'jshint']);
    gulp.watch('./_dev/site/js/script.js', ['concat:site:js', 'jshint']);
    // Minify JS
    gulp.watch('./_dev/build/admin/*.js', ['minify:admin:js']);
    gulp.watch('./_dev/build/site/*.js', ['minify:site:js']);
    // Minify CSS
    gulp.watch('./_dev/build/admin/*.css', ['minify:admin:css']);
    gulp.watch('./_dev/build/site/*.css', ['minify:site:css']);
    // Images
    gulp.watch('./_dev/admin/img/**/*', ['imagemin:admin']);
    gulp.watch('./_dev/site/img/**/*', ['imagemin:site']);
});
<commit_msg>Update gulpfile.js<commit_after>var gulp = require('gulp'),
        runSequence = require('run-sequence'),
        clean = require('gulp-rimraf'),
        copy = require('gulp-copy'),
        less = require('gulp-less'),
        concat = require('gulp-concat'),
        jshint = require('gulp-jshint'),
        autoprefixer = require('gulp-autoprefixer'),
        minifyCss = require('gulp-minify-css'),
        uglify = require('gulp-uglify'),
        imagemin = require('gulp-imagemin'),
        pngquant = require('imagemin-pngquant'),
        watch = require('gulp-watch');

/*
 * Clear
 */
gulp.task('clear:admin', function () {
    return gulp.src('./_dev/admin/css/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:site', function () {
    return gulp.src('./_dev/site/css/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:global:css', function () {
    return gulp.src('./_dev/global/css/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:global:js', function () {
    return gulp.src([
        './_dev/global/js/all.js',
        './_dev/global/js/bootstrap.js',
        './_dev/global/js/jquery.js'
    ], {read: false}).pipe(clean());
});
gulp.task('clear:build:css', function () {
    return gulp.src('./_dev/build/**/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:build:js', function () {
    return gulp.src('./_dev/build/**/*.js', {read: false}).pipe(clean());
});
gulp.task('clear:minify:admin:css', function () {
    return gulp.src('./admin/css/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:minify:admin:js', function () {
    return gulp.src('./admin/js/*.js', {read: false}).pipe(clean());
});
gulp.task('clear:minify:site:css', function () {
    return gulp.src('./css/*.css', {read: false}).pipe(clean());
});
gulp.task('clear:minify:site:js', function () {
    return gulp.src('./js/*.js', {read: false}).pipe(clean());
});
gulp.task('clear:minify', ['clear:minify:admin:css', 'clear:minify:admin:js', 'clear:minify:site:css', 'clear:minify:site:js']);
gulp.task('clear:build', ['clear:build:css', 'clear:build:js']);
gulp.task('clear:global', ['clear:global:css', 'clear:global:js']);
gulp.task('clear:css', ['clear:admin', 'clear:site', 'clear:global', 'clear:build:css', 'clear:minify:css']);
gulp.task('clear:js', ['clear:global:js', 'clear:build:js', 'clear:minify:js']);
gulp.task('clear', ['clear:admin', 'clear:site', 'clear:global', 'clear:build', 'clear:minify']);

/*
 * Bower copy
 */
gulp.task('bower:css', function () {
    return gulp.src('./bower_components/bootstrap/dist/css/bootstrap.css')
            .pipe(copy('./_dev/global/css', {prefix: 5}));
});
gulp.task('bower:js', function () {
    return gulp.src([
        './bower_components/jquery/dist/jquery.js',
        './bower_components/bootstrap/dist/js/bootstrap.js'
    ]).pipe(copy('./_dev/global/js', {prefix: 5}));
});
gulp.task('bower', ['bower:css', 'bower:js']);

/*
 * Less
 */
gulp.task('less:admin', function () {
    return gulp.src('./_dev/admin/css/*.less')
            .pipe(less())
            .pipe(gulp.dest('./_dev/admin/css'));
});
gulp.task('less:site', function () {
    return gulp.src('./_dev/site/css/*.less')
            .pipe(less())
            .pipe(gulp.dest('./_dev/site/css'));
});
gulp.task('less:global', function () {
    return gulp.src('./_dev/global/css/*.less')
            .pipe(less())
            .pipe(gulp.dest('./_dev/global/css'));
});
gulp.task('less', ['less:global', 'less:admin', 'less:site']);

/*
 * Auto prefixer
 */
gulp.task('prefix:admin', function () {
    return gulp.src('./_dev/admin/css/*.css')
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            })).pipe(gulp.dest('./_dev/admin/css'));
});
gulp.task('prefix:site', function () {
    return gulp.src('./_dev/site/css/*.css')
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            })).pipe(gulp.dest('./_dev/site/css'));
});
gulp.task('prefix:global', function () {
    return gulp.src('./_dev/global/css/global.css')
            .pipe(autoprefixer({
                browsers: ['last 2 versions'],
                cascade: false
            })).pipe(gulp.dest('./_dev/global/css'));
});
gulp.task('prefix', ['prefix:global', 'prefix:admin', 'prefix:site']);

/*
 * Concat site CSS & JS
 */
// CSS
gulp.task('concat:global:css', function () {
    return gulp.src([
        './_dev/global/css/bootstrap.css',
        './_dev/global/css/global.css'
    ]).pipe(concat('all.css')).pipe(gulp.dest('./_dev/global/css'));
});
gulp.task('concat:admin:css', function () {
    return gulp.src([
        './_dev/global/css/all.css',
        './_dev/admin/css/admin.css'
    ]).pipe(concat('style.min.css')).pipe(gulp.dest('./_dev/build/admin'));
});
gulp.task('concat:site:css', function () {
    return gulp.src([
        './_dev/global/css/all.css',
        './_dev/site/css/site.css'
    ]).pipe(concat('style.min.css')).pipe(gulp.dest('./_dev/build/site'));
});
// JS
gulp.task('concat:global:js', function () {
    return gulp.src([
        './_dev/global/js/jquery.js',
        './_dev/global/js/bootstrap.js',
        './_dev/global/js/script.js'
    ]).pipe(concat('all.js')).pipe(gulp.dest('./_dev/global/js'));
});
gulp.task('concat:site:js', function () {
    return gulp.src([
        './_dev/global/js/all.js',
        './_dev/site/js/*.js'
    ]).pipe(concat('script.min.js')).pipe(gulp.dest('./_dev/build/site'));
});
gulp.task('concat:admin:js', function () {
    return gulp.src([
        './_dev/global/js/all.js',
        './_dev/admin/js/*.js'
    ]).pipe(concat('script.min.js')).pipe(gulp.dest('./_dev/build/admin'));
});
gulp.task('concat:global', ['concat:global:css', 'concat:global:js']);
gulp.task('concat:admin', ['concat:admin:css', 'concat:admin:js']);
gulp.task('concat:site', ['concat:site:css', 'concat:site:js']);
gulp.task('concat', function (callback) {
    runSequence('concat:global', 'concat:admin', 'concat:site', callback);
});

/*
 * Minify CSS & JS
 */
// CSS
gulp.task('minify:admin:css', function () {
    return gulp.src('./_dev/build/admin/*.css')
            .pipe(minifyCss({compatibility: 'ie8'}))
            .pipe(gulp.dest('./admin/css'));
});
gulp.task('minify:site:css', function () {
    return gulp.src('./_dev/build/site/*.css')
            .pipe(minifyCss({compatibility: 'ie8'}))
            .pipe(gulp.dest('./css'));
});
// JS
gulp.task('minify:admin:js', function () {
    return gulp.src('./_dev/build/admin/*.js')
            .pipe(uglify())
            .pipe(gulp.dest('./admin/js'));
});
gulp.task('minify:site:js', function () {
    return gulp.src('./_dev/build/site/*.js')
            .pipe(uglify())
            .pipe(gulp.dest('./js'));
});
gulp.task('minify:admin', ['minify:admin:css', 'minify:admin:js']);
gulp.task('minify:site', ['minify:site:css', 'minify:site:js']);
gulp.task('minify', ['minify:admin', 'minify:site']);

/*
 * Minify images
 */
gulp.task('imagemin:admin', function() {
    return gulp.src('./_dev/admin/img/**/*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest('./admin/img'));
});
gulp.task('imagemin:site', function() {
    return gulp.src('./_dev/site/img/**/*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest('./img'));
});
gulp.task('imagemin', ['imagemin:admin', 'imagemin:site']);

/*
 * JS Hint
 */
gulp.task('jshint', function () {
    return gulp.src([
        './_dev/admin/js/*.js',
        './_dev/site/js/*.js',
        './_dev/global/js/script.js',
        './gulpfile.js'
    ]).pipe(jshint()).pipe(jshint.reporter('default'));
});

gulp.task('default', function (callback) {
    runSequence('clear', 'bower', 'less', 'prefix', 'concat', 'minify', 'imagemin', 'jshint', callback);
});

/*
 * Watch
 */
gulp.task('watch', function () {
    // Less
    gulp.watch('./_dev/global/css/global.less', ['less:global']);
    gulp.watch('./_dev/admin/css/admin.less', ['less:admin']);
    gulp.watch('./_dev/site/css/site.less', ['less:site']);
    // Concat CSS
    gulp.watch('./_dev/global/css/global.css', ['concat:global:css']);
    gulp.watch('./_dev/admin/css/admin.css', ['concat:admin:css']);
    gulp.watch('./_dev/site/css/site.css', ['concat:site:css']);
    // Concat JS
    gulp.watch('./_dev/global/js/script.js', ['concat:global:js', 'concat:admin:js', 'concat:site:js', 'jshint']);
    gulp.watch('./_dev/admin/js/script.js', ['concat:admin:js', 'jshint']);
    gulp.watch('./_dev/site/js/script.js', ['concat:site:js', 'jshint']);
    // Minify JS
    gulp.watch('./_dev/build/admin/*.js', ['minify:admin:js']);
    gulp.watch('./_dev/build/site/*.js', ['minify:site:js']);
    // Minify CSS
    gulp.watch('./_dev/build/admin/*.css', ['minify:admin:css']);
    gulp.watch('./_dev/build/site/*.css', ['minify:site:css']);
    // Images
    gulp.watch('./_dev/admin/img/**/*', ['imagemin:admin']);
    gulp.watch('./_dev/site/img/**/*', ['imagemin:site']);
});
<|endoftext|>


<commit_before>// # Ghost Configuration
// Setup your Ghost install for various [environments](http://support.ghost.org/config/#about-environments).

// Ghost runs in `development` mode by default. Full documentation can be found at http://support.ghost.org/config/

var path = require('path'),
    config;

config = {
    // ### Production
    // When running Ghost in the wild, use the production environment.
    // Configure your URL and mail settings here
    production: {
        url: 'https://whispering-depths-9307.herokuapp.com/',
        mail: 'hello@colemanrollins.io',
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost.db')
            },
            debug: false
        },

        server: {
            host: '127.0.0.1',
            port: '5000'
        }
    },

    // ### Development **(default)**
    development: {
        // The url to use when providing links to the site, E.g. in RSS and email.
        // Change this to your Ghost blog's published URL.
        url: 'http://localhost:2368',

        // Example mail config
        // Visit http://support.ghost.org/mail for instructions
        // ```
        //  mail: {
        //      transport: 'SMTP',
        //      options: {
        //          service: 'Mailgun',
        //          auth: {
        //              user: '', // mailgun username
        //              pass: ''  // mailgun password
        //          }
        //      }
        //  },
        // ```

        // #### Database
        // Ghost supports sqlite3 (default), MySQL & PostgreSQL
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost-dev.db')
            },
            debug: false
        },
        // #### Server
        // Can be host & port (default), or socket
        server: {
            // Host to be passed to node's `net.Server#listen()`
            host: '127.0.0.1',
            // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
            port: '2368'
        },
        // #### Paths
        // Specify where your content directory lives
        paths: {
            contentPath: path.join(__dirname, '/content/')
        }
    },

    // **Developers only need to edit below here**

    // ### Testing
    // Used when developing Ghost to run tests and check the health of Ghost
    // Uses a different port number
    testing: {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost-test.db')
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    },

    // ### Testing MySQL
    // Used by Travis - Automated testing run through GitHub
    'testing-mysql': {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'mysql',
            connection: {
                host     : '127.0.0.1',
                user     : 'root',
                password : '',
                database : 'ghost_testing',
                charset  : 'utf8'
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    },

    // ### Testing pg
    // Used by Travis - Automated testing run through GitHub
    'testing-pg': {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'pg',
            connection: {
                host     : '127.0.0.1',
                user     : 'postgres',
                password : '',
                database : 'ghost_testing',
                charset  : 'utf8'
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    }
};

module.exports = config;
<commit_msg>Trying more server config for heroku<commit_after>// # Ghost Configuration
// Setup your Ghost install for various [environments](http://support.ghost.org/config/#about-environments).

// Ghost runs in `development` mode by default. Full documentation can be found at http://support.ghost.org/config/

var path = require('path'),
    config;

config = {
    // ### Production
    // When running Ghost in the wild, use the production environment.
    // Configure your URL and mail settings here
    production: {
        url: 'https://whispering-depths-9307.herokuapp.com/',
        mail: 'hello@colemanrollins.io',
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost.db')
            },
            debug: false
        },

        server: {
            host: '',
            port: '5000'
        }
    },

    // ### Development **(default)**
    development: {
        // The url to use when providing links to the site, E.g. in RSS and email.
        // Change this to your Ghost blog's published URL.
        url: 'http://localhost:2368',

        // Example mail config
        // Visit http://support.ghost.org/mail for instructions
        // ```
        //  mail: {
        //      transport: 'SMTP',
        //      options: {
        //          service: 'Mailgun',
        //          auth: {
        //              user: '', // mailgun username
        //              pass: ''  // mailgun password
        //          }
        //      }
        //  },
        // ```

        // #### Database
        // Ghost supports sqlite3 (default), MySQL & PostgreSQL
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost-dev.db')
            },
            debug: false
        },
        // #### Server
        // Can be host & port (default), or socket
        server: {
            // Host to be passed to node's `net.Server#listen()`
            host: '127.0.0.1',
            // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT`
            port: '2368'
        },
        // #### Paths
        // Specify where your content directory lives
        paths: {
            contentPath: path.join(__dirname, '/content/')
        }
    },

    // **Developers only need to edit below here**

    // ### Testing
    // Used when developing Ghost to run tests and check the health of Ghost
    // Uses a different port number
    testing: {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'sqlite3',
            connection: {
                filename: path.join(__dirname, '/content/data/ghost-test.db')
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    },

    // ### Testing MySQL
    // Used by Travis - Automated testing run through GitHub
    'testing-mysql': {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'mysql',
            connection: {
                host     : '127.0.0.1',
                user     : 'root',
                password : '',
                database : 'ghost_testing',
                charset  : 'utf8'
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    },

    // ### Testing pg
    // Used by Travis - Automated testing run through GitHub
    'testing-pg': {
        url: 'http://127.0.0.1:2369',
        database: {
            client: 'pg',
            connection: {
                host     : '127.0.0.1',
                user     : 'postgres',
                password : '',
                database : 'ghost_testing',
                charset  : 'utf8'
            }
        },
        server: {
            host: '127.0.0.1',
            port: '2369'
        },
        logging: false
    }
};

module.exports = config;
<|endoftext|>


<commit_before>const TeleBot = require('telebot');
const config = require('./config');

const bot = new TeleBot({
  token: config.token, // Add telegram token bot here.
  sleep: 1000, // Optional. How often check updates (in ms).
  timeout: 0, // Optional. Update pulling timeout (0 - short polling).
  limit: 100, // Optional. Limits the number of updates to be retrieved.
  retryTimeout: 5000, // Optional. Reconnecting timeout (in ms).
});

// console logs
bot.on('text', function(msg) {
  console.log(`[Logs] ${ msg.from.first_name } ${ msg.chat.id } ${ msg.text }`);
});

// ping telechan
bot.on('/ping', msg => {
  let id = msg.user.id;
  let firstName = msg.from.first_name;
  let reply = msg.message_id;
  return bot.sendMessage(id, `Pong, ${ firstName }! como vas ?`);
});

bot.on('/about', msg => {
  let id = msg.chat.id;
  let reply = msg.message_id;
  const execSync = require('child_process').execSync;
  uptime = execSync('uptime');
  return bot.sendMessage(id, `Telechan v0.1` + '\n' + uptime, { reply });

});

bot.connect();
<commit_msg>ping fix<commit_after>const TeleBot = require('telebot');
const config = require('./config');

const bot = new TeleBot({
  token: config.token, // Add telegram token bot here.
  sleep: 1000, // Optional. How often check updates (in ms).
  timeout: 0, // Optional. Update pulling timeout (0 - short polling).
  limit: 100, // Optional. Limits the number of updates to be retrieved.
  retryTimeout: 5000, // Optional. Reconnecting timeout (in ms).
});

// console logs
bot.on('text', function(msg) {
  console.log(`[Logs] ${ msg.from.first_name } ${ msg.chat.id } ${ msg.text }`);
});

// ping telechan
bot.on('/ping', msg => {
  let id = msg.from.id;
  let firstName = msg.from.first_name;
  let reply = msg.message_id;
  return bot.sendMessage(id, `Pong, ${ firstName }! como vas ?`);
});

bot.on('/about', msg => {
  let id = msg.from.id;
  let reply = msg.message_id;
  const execSync = require('child_process').execSync;
  uptime = execSync('uptime');
  return bot.sendMessage(id, `Telechan v0.1` + '\n' + uptime, { reply });

});

bot.connect();
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var mongoose = require('mongoose')
  , Proposal = mongoose.model('Proposal')
  , tagApi = require('./tag')
  , log = require('debug')('db-api:proposal');

/**
 * Get all proposals
 *
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposals' list items found or `undefined`
 * @return {Module} `proposal` module
 * @api public
 */

exports.all = function all(fn) {
  log('Looking for all proposals.')

  Proposal.find(function (err, proposals) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering proposals %j', mapByProperty(proposals, 'id'));
    fn(null, proposals);
  });

  return this;
}

/**
 * Create or retrieve Proposal from `proposal` descriptor
 *
 * @param {Object} proposal object descriptor
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposal' single object created or `undefined`
 * @return {Module} `proposal` module
 * @api public
 */

exports.create = function create(proposal, fn) {
  log('Creating new proposal %j', proposal);

  // wrong using tag api within proposal's
  log('Looking for tag %s in database.', proposal.tag);
  tagApi.create(proposal.tag, function (err, tag) {
    if (err) {
      log('Found error from tag creation %j', err);
      return fn(err);
    };

    proposal.tag = tag;
    (new Proposal(proposal)).save(function (err, saved) {
      if (err) {
        log('Found error %j', err);
        return fn(err);
      };
      console.log(saved.populate);
      log('Delivering proposal %j', saved);
      fn(null, saved);
    });
  })

  return this;
};

/**
 * Get Proposal form `id` string or `ObjectId`
 *
 * @param {String|ObjectId} id Proposal's `id`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposal' single object created or `undefined`
 * @api public
 */

exports.get = function get(id, fn) {
  log('Loking for proposal %s', id);

  Proposal.findById(id, function (err, proposal) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering proposal %j', proposal);
    fn(null, proposal);
  });
};

/**
 * Map array of objects by `property`
 *
 * @param {Array} source array of objects to map
 * @param {String} property to map from objects
 * @return {Array} array of listed properties
 * @api private
 */

function mapByProperty (source, property) {
  return source.map(function(item) { return item[prop]; });
}<commit_msg>[db-api] - Proposal: Add comment action to proposal<commit_after>/**
 * Module dependencies.
 */

var mongoose = require('mongoose')
  , Proposal = mongoose.model('Proposal')
  , tagApi = require('./tag')
  , commentApi = require('./comment')
  , log = require('debug')('db-api:proposal');

/**
 * Get all proposals
 *
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposals' list items found or `undefined`
 * @return {Module} `proposal` module
 * @api public
 */

exports.all = function all(fn) {
  log('Looking for all proposals.')

  Proposal.find(function (err, proposals) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering proposals %j', mapByProperty(proposals, 'id'));
    fn(null, proposals);
  });

  return this;
}

/**
 * Create or retrieve Proposal from `proposal` descriptor
 *
 * @param {Object} proposal object descriptor
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposal' single object created or `undefined`
 * @return {Module} `proposal` module
 * @api public
 */

exports.create = function create(proposal, fn) {
  log('Creating new proposal %j', proposal);

  // wrong using tag api within proposal's
  log('Looking for tag %s in database.', proposal.tag);
  tagApi.create(proposal.tag, function (err, tag) {
    if (err) {
      log('Found error from tag creation %j', err);
      return fn(err);
    };

    proposal.tag = tag;
    (new Proposal(proposal)).save(function (err, saved) {
      if (err) {
        log('Found error %j', err);
        return fn(err);
      };
      console.log(saved.populate);
      log('Delivering proposal %j', saved);
      fn(null, saved);
    });
  })

  return this;
};

/**
 * Get Proposal form `id` string or `ObjectId`
 *
 * @param {String|ObjectId} id Proposal's `id`
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposal' single object created or `undefined`
 * @api public
 */

exports.get = function get(id, fn) {
  log('Loking for proposal %s', id);

  Proposal.findById(id, function (err, proposal) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering proposal %j', proposal);
    fn(null, proposal);
  });
};

/**
 * Direct comment to proposal
 *
 * @param {String} id Proposal's `id`
 * @param {Object} comment to attach
 * @param {Function} fn callback function
 *   - 'err' error found while process or `null`
 *   - 'proposal' single object created or `undefined`
 * @api public
 */

exports.comment = function comment(id, comment, fn) {
  log('Creating comment %j for proposal %s', comment, id);
  commentApi.create(id, comment, function (err, commentDoc) {
    if (err) {
      log('Found error %j', err);
      return fn(err);
    };

    log('Delivering comment %j', commentDoc);
    fn(null, commentDoc);
  });
};

/**
 * Map array of objects by `property`
 *
 * @param {Array} source array of objects to map
 * @param {String} property to map from objects
 * @return {Array} array of listed properties
 * @api private
 */

function mapByProperty (source, property) {
  return source.map(function (item) { return item[prop]; });
}<|endoftext|>


<commit_before>const express = require('express'); // Express web server framework
const request = require('request'); // "Request" library
const cookieParser = require('cookie-parser');
const querystring = require('querystring');
const bodyParser = require('body-parser');
const async = require('async');
const passport = require('passport');
const SpotifyStrategy = require('passport-spotify').Strategy;
const favicon = require('serve-favicon');
const path = require('path');
const spotify = require('./spotifyCredentials');
const config = require('./config');

const client_id = spotify.client_id;
const client_secret = spotify.client_secret;

const redirect_uri = config.spotify_callback; // Your redirect uri

passport.use(new SpotifyStrategy({
	clientID: client_id,
	clientSecret: client_secret,
	callbackURL: redirect_uri
}, function (accessToken, refreshToken, profile, done) {
	process.nextTick(function () {
		return done(null, accessToken);
	})
}));

// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session. Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing. However, since this example does not
//   have a database of user records, the complete spotify profile is serialized
//   and deserialized.
passport.serializeUser(function(user, done) {
	done(null, user);
});

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

function isAuthenticated(req, res, next) {
	if (req.isAuthenticated())
		return next();
	res.send(req.body);
	// res.redirect('/');
}

let app = express();

app.use(express.static(path.join(__dirname ,'frontend', 'public')))
	.use(cookieParser());

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

app.use(favicon(path.join(__dirname, 'frontend', 'public', 'img', 'favicon.ico')));

app.use(bodyParser.json());

app.set('view engine', 'ejs');
app.set('views', './frontend/views');

// Initiate passport
app.use(passport.initialize());
// .. also support for Passport persistent login sessions
app.use(passport.session());

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

/**
 * Checks if a user is logged in by sending a request with the access token to Spotify.
 * If valid, a user is considered authenticated to Spotify and PowerHourGame
 */
app.get('/auth/loggedin', function (req, res) {
	let spotify_access_token = req.cookies.spotify_access_token || null;
	let data = {};

	// Return 403 of no access token provided
	if (spotify_access_token === null) {
		data.loggedin = false;
		res.send(data);
	} else {
		// Set options for request to Spotify API
		let options = {
			url: 'https://api.spotify.com/v1/me',
			headers: { 'Authorization': 'Bearer ' + spotify_access_token },
			json: true
		};

		// Try access
		request.get(options, function(error, response, body) {
			let status_code  = response.statusCode;
			if (status_code === 200) {
				data.user = {id: body.id, name: body.display_name};
				data.loggedin = true;
				res.cookie("username", body.display_name ? body.display_name : body.id);
				res.cookie("spotify_id", body.id);
				res.status(200);
				res.send(data);
			} else {
				data = {};
				data.loggedin = false;
				res.status(403);
				res.send(data);
			}
		});
	}
});

/**
 * Login using Spotify. Will redirect to Spotify authentication page
 */
app.get('/auth/login',
	passport.authenticate('spotify', {scope: ['user-read-private', 'user-read-email', 'playlist-modify-private', 'playlist-modify-public'], showDialog: true}),
	function(req, res) {
		// Will not be called...
	}
);

/**
 * Callback endpoint for the Spotify Authentication using passport
 */
app.get('/auth/callback', passport.authenticate('spotify', {failureRedirect: '/'}), function(req, res) {
		let spotify_access_token = req.user || null;
		res.cookie("spotify_access_token", spotify_access_token);
		res.redirect('/');
	}
);

/**
 * Fetches playlists of logged in from Spotify
 */
app.get('/api/user/me/playlist', function (req, res) {
	let spotify_access_token = req.cookies.spotify_access_token || null;
	if (spotify_access_token === null) {
		res.status(403);
		res.send("No access token provided");
	} else {
		// Set options for request to Spotify API
		let options = {
			url: `https://api.spotify.com/v1/me/playlists`,
			headers: { 'Authorization': 'Bearer ' + spotify_access_token},
			json: true
		};
		request.get(options, function (error, response, body) {
			if (error)
				res.send(error);
			else
				res.send(body);
		})
	}
});

/**
 * Fetches playlist for a user with matching user_id and playlist_id from Spotify
 */
app.get('/api/user/:user_id/playlist/:playlist_id', function (req, res) {
	let spotify_access_token = req.cookies.spotify_access_token || null;
	if (spotify_access_token === null) {
		res.status(403);
		res.send("No access token provided");
	} else {
		// Set options for request to Spotify API
		let options = {
			url: `https://api.spotify.com/v1/users/${req.params.user_id}/playlists/${req.params.playlist_id}`,
			headers: { 'Authorization': 'Bearer ' + spotify_access_token},
			json: true
		};
		request.get(options, function (error, response, body) {
			if (!error && response.statusCode === 200)
				res.send(body);
			else
				res.send(error);
		})
	}
});

let port = config.port;
console.log('Listening on ' + port);
app.listen(port);<commit_msg>Read Spotiy secrets from environment variables to start with<commit_after>const express = require('express'); // Express web server framework
const request = require('request'); // "Request" library
const cookieParser = require('cookie-parser');
const querystring = require('querystring');
const bodyParser = require('body-parser');
const async = require('async');
const passport = require('passport');
const SpotifyStrategy = require('passport-spotify').Strategy;
const favicon = require('serve-favicon');
const path = require('path');
const config = require('./config');

let client_id, client_secret;
if (process.env.NODE_ENV !== 'production') {
	const spotify = require('./spotifyCredentials');
	client_id = spotify.client_id;
	client_secret = spotify.client_secret;
}

const redirect_uri = config.spotify_callback; // Your redirect uri

passport.use(new SpotifyStrategy({
	clientID: process.env.SPOTIFY_CLIENT_ID || client_id,
	clientSecret: process.env.SPOTIFY_CLIENT_SECRET || client_secret,
	callbackURL: redirect_uri
}, function (accessToken, refreshToken, profile, done) {
	process.nextTick(function () {
		return done(null, accessToken);
	})
}));

// Passport session setup.
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session. Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing. However, since this example does not
//   have a database of user records, the complete spotify profile is serialized
//   and deserialized.
passport.serializeUser(function(user, done) {
	done(null, user);
});

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

function isAuthenticated(req, res, next) {
	if (req.isAuthenticated())
		return next();
	res.send(req.body);
	// res.redirect('/');
}

let app = express();

app.use(express.static(path.join(__dirname ,'frontend', 'public')))
	.use(cookieParser());

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

app.use(favicon(path.join(__dirname, 'frontend', 'public', 'img', 'favicon.ico')));

app.use(bodyParser.json());

app.set('view engine', 'ejs');
app.set('views', './frontend/views');

// Initiate passport
app.use(passport.initialize());
// .. also support for Passport persistent login sessions
app.use(passport.session());

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

/**
 * Checks if a user is logged in by sending a request with the access token to Spotify.
 * If valid, a user is considered authenticated to Spotify and PowerHourGame
 */
app.get('/auth/loggedin', function (req, res) {
	let spotify_access_token = req.cookies.spotify_access_token || null;
	let data = {};

	// Return 403 of no access token provided
	if (spotify_access_token === null) {
		data.loggedin = false;
		res.send(data);
	} else {
		// Set options for request to Spotify API
		let options = {
			url: 'https://api.spotify.com/v1/me',
			headers: { 'Authorization': 'Bearer ' + spotify_access_token },
			json: true
		};

		// Try access
		request.get(options, function(error, response, body) {
			let status_code  = response.statusCode;
			if (status_code === 200) {
				data.user = {id: body.id, name: body.display_name};
				data.loggedin = true;
				res.cookie("username", body.display_name ? body.display_name : body.id);
				res.cookie("spotify_id", body.id);
				res.status(200);
				res.send(data);
			} else {
				data = {};
				data.loggedin = false;
				res.status(403);
				res.send(data);
			}
		});
	}
});

/**
 * Login using Spotify. Will redirect to Spotify authentication page
 */
app.get('/auth/login',
	passport.authenticate('spotify', {scope: ['user-read-private', 'user-read-email', 'playlist-modify-private', 'playlist-modify-public'], showDialog: true}),
	function(req, res) {
		// Will not be called...
	}
);

/**
 * Callback endpoint for the Spotify Authentication using passport
 */
app.get('/auth/callback', passport.authenticate('spotify', {failureRedirect: '/'}), function(req, res) {
		let spotify_access_token = req.user || null;
		res.cookie("spotify_access_token", spotify_access_token);
		res.redirect('/');
	}
);

/**
 * Fetches playlists of logged in from Spotify
 */
app.get('/api/user/me/playlist', function (req, res) {
	let spotify_access_token = req.cookies.spotify_access_token || null;
	if (spotify_access_token === null) {
		res.status(403);
		res.send("No access token provided");
	} else {
		// Set options for request to Spotify API
		let options = {
			url: `https://api.spotify.com/v1/me/playlists`,
			headers: { 'Authorization': 'Bearer ' + spotify_access_token},
			json: true
		};
		request.get(options, function (error, response, body) {
			if (error)
				res.send(error);
			else
				res.send(body);
		})
	}
});

/**
 * Fetches playlist for a user with matching user_id and playlist_id from Spotify
 */
app.get('/api/user/:user_id/playlist/:playlist_id', function (req, res) {
	let spotify_access_token = req.cookies.spotify_access_token || null;
	if (spotify_access_token === null) {
		res.status(403);
		res.send("No access token provided");
	} else {
		// Set options for request to Spotify API
		let options = {
			url: `https://api.spotify.com/v1/users/${req.params.user_id}/playlists/${req.params.playlist_id}`,
			headers: { 'Authorization': 'Bearer ' + spotify_access_token},
			json: true
		};
		request.get(options, function (error, response, body) {
			if (!error && response.statusCode === 200)
				res.send(body);
			else
				res.send(error);
		})
	}
});

let port = config.port;
console.log('Listening on ' + port);
app.listen(port);<|endoftext|>