This repository has been archived by the owner on Aug 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
131 lines (118 loc) · 3.43 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
const sslRedirect = require('heroku-ssl-redirect');
const express = require('express');
const path = require('path');
const log = require('loglevel');
const morgan = require('morgan');
const helmet = require('helmet');
const bodyParser = require('body-parser');
const cors = require('cors');
const cache = require('memory-cache');
const youtubeAudioStream = require('@isolution/youtube-audio-stream');
const apiRequest = require('./apiRequest');
const config = require('./config');
const port = process.env.PORT || 3001;
const app = express();
app.use(helmet());
app.use(cors());
// app.use(sslRedirect());
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(express.static(path.join(__dirname, 'client/build')));
// Middleware to cache response for a specific amount of seconds
const cacheMiddleware = duration => (req, res, next) => {
const key = `__express__${req.originalUrl || req.url}`;
const cachedBody = cache.get(key);
if (cachedBody) {
res.send(cachedBody);
} else {
res.sendResponse = res.send;
res.send = body => {
cache.put(key, body, duration * 1000);
res.sendResponse(body);
};
next();
}
};
// Audio Route
app.get('/api/play/:videoId', (req, res, next) => {
log.warn('AUDIO ROUTE HIT');
const { videoId } = req.params;
const requestUrl = `https://www.youtube.com/watch?v=${videoId}`;
apiRequest
.getDuration(videoId)
.then(duration => {
const bitrate = req.body.bitrate || 128;
const ratio = 0.0234353085554361;
const size = parseInt(
((bitrate - bitrate * ratio) / 8) * 1024 * duration,
10
);
log.warn(`DURATION IS ${duration}`);
// don't set content-length header for livestreams
if (duration !== 0) {
res.set({
'Content-Length': size,
'Content-Type': 'audio/mpeg',
'Accept-Ranges': 'bytes'
});
}
const streamPromise = youtubeAudioStream(requestUrl);
return streamPromise;
})
.then(stream => {
// remove all the previous listeners before registering new ones
stream.emitter.removeAllListeners('error');
stream.emitter.on('error', err => {
next(err);
});
log.warn(`HIT PROMISE RESOLVED`);
stream.pipe(res);
})
.catch(err => {
log.warn(`HIT PROMISE REJECTED`);
next(err);
});
});
// Search Route - cache response for 24hrs
app.get('/api/results', cacheMiddleware(86400), (req, res, next) => {
apiRequest
.buildSearch(req.query.searchQuery)
.then(searchResults => {
res.json(searchResults);
})
.catch(err => {
next(err);
});
});
// Trending Route - caches response for 24hrs
app.get('/api/trending', cacheMiddleware(86400), (req, res, next) => {
apiRequest
.buildTrendingVideos()
.then(results => {
res.json(results);
})
.catch(err => {
next(err);
});
});
// Send build page for React app
app.get('*', (req, res) => {
res.sendFile(path.join(`${__dirname}/client/build/index.html`));
});
// Error Handler
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
log.error(err.message);
if (!config.isProduction) {
log.trace(err.stack);
}
// TODO: send socket.io error messages here
// if (res.headersSent) {
// return res.end();
// }
res.end();
// return res.status(err.status || 500).send(err.message || 'Internal Server Error');
});
app.listen(port, () => {
log.info(`Server started on ${port}`);
});