<commit_before>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var morganLog = require('morgan');
var favicon = require('serve-favicon');

var tracklist = require('./tracklist');
var redis = require('redis').createClient();
var config = require('./config');
var trackBuilder = require('./track_builder');
var socket = require('./socket')();
var playerState = require('./player_state');
var listeners = [];
var logger = require('./logger');

module.exports = function (app, playerManager) {
  playerManager.stream.on('data', _sendChunk);

  app.use(express.static(__dirname + '/../public'));
  app.use(morganLog('dev'));
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());
  app.set('views', __dirname + '/../public');
  app.set('view engine', 'ejs');
  app.engine('html', require('ejs').renderFile);
  app.use(favicon(__dirname + '/../public/jukebox.png'));

  var allowedMethods = 'GET,PUT,POST,DELETE,OPTIONS';
  var allowedHeaders = 'Content-Length,Content-Type';
  var allowedHosts = [
    'http://soundcloud.com',
    'https://soundcloud.com',
    'http://youtube.com',
    'https://youtube.com',
    'http://www.youtube.com',
    'https://www.youtube.com'
  ];
  function _allowCrossDomain(req, res, next) {
    if (allowedHosts.indexOf(req.headers.origin) !== -1) {
      res.header('Access-Control-Allow-Origin', req.headers.origin);
      res.header('Access-Control-Allow-Methods', allowedMethods);
      res.header('Access-Control-Allow-Headers', allowedHeaders);
      if ('OPTIONS' === req.method) return res.status(200).end();
    }
    next();
  }

  app.route('/player')
  .get(function (req, res) {
    res.send(playerState);
  })
  .post(function (req, res) {
    if (!playerState.playing) playerManager.start();
    res.status(201).end();
  })
  .delete(function (req, res) {
    if (playerState.playing) playerManager.stop();
    res.status(201).end();
  });

  app.route('/tracks')
  .options(_allowCrossDomain)
  .get(function (req, res) {
    tracklist.get()
    .then(function (list) {
      res.send(list);
    }, function (err) {
      res.status(503).send(err.message);
    });
  })
  .post(_allowCrossDomain, function (req, res) {
    if (!req.body.url) return res.status(400).send('You need to provide a track URL.');
    trackBuilder.fromString(req.body.url)
    .then(tracklist.add)
    .then(function (track) {
      socket.emit('tracks:new');
      res.status(201).send(track);
    }, function (err) {
      res.status(500).send(err.message);
    });
  });

  app.route('/current')
  .get(function (req, res) {
    tracklist.current()
    .then(function (track) {
      if (!track) return res.send({});

      redis.scard('jukebox:votes', function (err, count) {
        if (err) return res.status(500).send(err);
        track.votes = {
          favorable: count,
          total: config.minVotes
        };
        res.send(track);
      });
    }, function (err) {
      res.status(500).send(err.message);
    });
  })
  .post(function (req, res) {
    redis.sadd('jukebox:votes', req.ip, function (err, newCount) {
      if (err) return res.status(500).send(err);
      res.send(201).end();
      if (newCount > 0) {
        socket.emit('current:votes');
        _checkVotesNext();
      }
    });
  })
  .delete(function (req, res) {
    playerManager.stop();
    tracklist.next().then(function () {
      playerManager.start();
    });
    res.status(201).end();
  });

  app.get('/history', function (req, res) {
    tracklist.history()
    .then(function (list) {
      res.send(list);
    }, function (err) {
      res.status(500).send(err.message);
    });
  });

  app.get('/stream', function (req, res) {
    res.set({
      'Content-Type': 'audio/mpeg',
      'Transfer-Encoding': 'chunked'
    });

    _addListener(res);

    function _onEnd() {
      _removeListener(res);
    }

    res.on('close', _onEnd);
    res.on('finish', _onEnd);
  });

  /**<commit_msg>Added: no cache headers on the stream<commit_after>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var morganLog = require('morgan');
var favicon = require('serve-favicon');

var tracklist = require('./tracklist');
var redis = require('redis').createClient();
var config = require('./config');
var trackBuilder = require('./track_builder');
var socket = require('./socket')();
var playerState = require('./player_state');
var listeners = [];
var logger = require('./logger');

module.exports = function (app, playerManager) {
  playerManager.stream.on('data', _sendChunk);

  app.use(express.static(__dirname + '/../public'));
  app.use(morganLog('dev'));
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());
  app.set('views', __dirname + '/../public');
  app.set('view engine', 'ejs');
  app.engine('html', require('ejs').renderFile);
  app.use(favicon(__dirname + '/../public/jukebox.png'));

  var allowedMethods = 'GET,PUT,POST,DELETE,OPTIONS';
  var allowedHeaders = 'Content-Length,Content-Type';
  var allowedHosts = [
    'http://soundcloud.com',
    'https://soundcloud.com',
    'http://youtube.com',
    'https://youtube.com',
    'http://www.youtube.com',
    'https://www.youtube.com'
  ];
  function _allowCrossDomain(req, res, next) {
    if (allowedHosts.indexOf(req.headers.origin) !== -1) {
      res.header('Access-Control-Allow-Origin', req.headers.origin);
      res.header('Access-Control-Allow-Methods', allowedMethods);
      res.header('Access-Control-Allow-Headers', allowedHeaders);
      if ('OPTIONS' === req.method) return res.status(200).end();
    }
    next();
  }

  app.route('/player')
  .get(function (req, res) {
    res.send(playerState);
  })
  .post(function (req, res) {
    if (!playerState.playing) playerManager.start();
    res.status(201).end();
  })
  .delete(function (req, res) {
    if (playerState.playing) playerManager.stop();
    res.status(201).end();
  });

  app.route('/tracks')
  .options(_allowCrossDomain)
  .get(function (req, res) {
    tracklist.get()
    .then(function (list) {
      res.send(list);
    }, function (err) {
      res.status(503).send(err.message);
    });
  })
  .post(_allowCrossDomain, function (req, res) {
    if (!req.body.url) return res.status(400).send('You need to provide a track URL.');
    trackBuilder.fromString(req.body.url)
    .then(tracklist.add)
    .then(function (track) {
      socket.emit('tracks:new');
      res.status(201).send(track);
    }, function (err) {
      res.status(500).send(err.message);
    });
  });

  app.route('/current')
  .get(function (req, res) {
    tracklist.current()
    .then(function (track) {
      if (!track) return res.send({});

      redis.scard('jukebox:votes', function (err, count) {
        if (err) return res.status(500).send(err);
        track.votes = {
          favorable: count,
          total: config.minVotes
        };
        res.send(track);
      });
    }, function (err) {
      res.status(500).send(err.message);
    });
  })
  .post(function (req, res) {
    redis.sadd('jukebox:votes', req.ip, function (err, newCount) {
      if (err) return res.status(500).send(err);
      res.send(201).end();
      if (newCount > 0) {
        socket.emit('current:votes');
        _checkVotesNext();
      }
    });
  })
  .delete(function (req, res) {
    playerManager.stop();
    tracklist.next().then(function () {
      playerManager.start();
    });
    res.status(201).end();
  });

  app.get('/history', function (req, res) {
    tracklist.history()
    .then(function (list) {
      res.send(list);
    }, function (err) {
      res.status(500).send(err.message);
    });
  });

  app.get('/stream', function (req, res) {
    res.set({
      'Content-Type': 'audio/mpeg',
      'Transfer-Encoding': 'chunked',
      'Cache-Control': 'private, no-cache, no-store, must-revalidate',
      'Expires': '-1',
      'Pragma': 'no-cache',
    });

    _addListener(res);

    function _onEnd() {
      _removeListener(res);
    }

    res.on('close', _onEnd);
    res.on('finish', _onEnd);
  });

  /**
{'fraction_non_alphanumeric': 0.1954674220963173, 'fraction_numerical': 0.010222933858849611, 'mean_word_length': 3.1134751773049647, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 6, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3163807', 'n_tokens_mistral': 2757, 'n_tokens_neox': 2670, 'n_words': 471}