forked from jenkins-infra/plugin-site
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
140 lines (129 loc) · 4.8 KB
/
server.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
132
133
134
135
136
137
138
139
140
import React from 'react';
import express from 'express';
import exphbs from 'express-handlebars';
import { match, RouterContext } from 'react-router';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import routes from './app/routes';
import chalk from 'chalk';
import configureStore from './app/store/configureStore';
import compression from 'compression';
import helmet from 'helmet';
import hpp from 'hpp';
import morgan from 'morgan';
import fs from 'fs';
import unirest from 'unirest';
import cheerio from 'cheerio';
import schedule from 'node-schedule';
const app = express();
const port = 5000;
const jsPath = '/assets/js';
// Using helmet to secure Express with various HTTP headers
app.use(helmet());
// Prevent HTTP parameter pollution.
app.use(hpp());
// Compress all requests
app.use(compression());
// Use morgan for http request debug (only show error)
app.use(morgan('dev', { skip: (req, res) => res.statusCode < 400 }));
app.use(express.static('./public'));
app.use(jsPath, express.static('./dist/client'));
app.engine('hbs', exphbs({extname: '.hbs'}));
app.set('view engine', 'hbs');
const downloadHeader = () => {
var headerFile = __HEADER_FILE__;
if (headerFile !== null && headerFile !== undefined) {
console.info(`Downloading header file from '${headerFile}'`);
unirest.get(headerFile).end((response) => {
if (response.statusCode == 200) {
var $ = cheerio.load(response.body, { decodeEntities: false });
$('img, script').each(function() {
var src = $(this).attr('src');
if (src !== undefined && src.startsWith('/')) {
$(this).attr('src', 'https://jenkins.io' + src);
}
});
$('a, link').each(function() {
var href = $(this).attr('href');
if (href !== undefined && href.startsWith('/')) {
$(this).attr('href', 'https://jenkins.io' + href);
}
});
$('head').prepend('{{> header }}');
// Even though we're supplying our own this one still causes a conflict.
$('link[href="https://jenkins.io/css/font-icons.css"]').remove();
$('head').append('<script>window.__REDUX_STATE__ = {{{reduxState}}};</script>');
$('#grid-box').append('{{{rendered}}}');
$('#grid-box').after('<script type="text/javascript" src="{{jsPath}}/main.js"></script>');
$('#creativecommons').append('{{> version }}');
fs.writeFileSync('./views/index.hbs', $.html());
} else {
console.error(response.statusCode);
console.error(error);
}
});
} else {
console.info("HEADER_FILE environment variable null");
}
}
downloadHeader();
const getPluginSiteVersion = () => {
const file = './GIT_COMMIT';
try {
return fs.existsSync(file) ? fs.readFileSync(file, 'utf-8').substring(0, 7) : 'TBD';
} catch (err) {
console.error(chalk.red(`Problem accessing ${file}`), err);
}
}
const pluginSiteVersion = getPluginSiteVersion();
app.get('*', (req, res, next) => {
match({ routes: routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (!renderProps) {
res.sendStatus(404);
} else {
const store = configureStore();
const { location, params, history } = renderProps;
const promises = renderProps.components
.filter(component => component.fetchData)
// Should the component have a static method `fetchData({ store, location, params, history })` then
// call it.
.map(component => component.fetchData({ store, location, params, history }));
Promise.all(promises).then(() => {
const rendered = renderToString(
<div>
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
</div>
);
const pluginSiteApiVersion = store.getState().data.info.commit.substring(0, 7);
const reduxState = JSON.stringify(store.getState()).replace(/</g, '\\x3c');
const pluginNotFound = req.url !== '/' && store.getState().ui.plugin === null;
res.status(pluginNotFound ? 404 : 200).render('index', {
rendered,
reduxState,
jsPath,
pluginSiteVersion,
pluginSiteApiVersion
});
}).catch((err) => {
console.error(chalk.red(error));
res.sendStatus(404);
});
}
});
});
app.listen(port, (error) => {
if (error) {
console.error(chalk.red(error)); // eslint-disable-line no-console
} else {
console.info(chalk.green(`==> Listening on port ${port}`)); // eslint-disable-line no-console
schedule.scheduleJob('*/15 * * * *', () => {
downloadHeader();
});
}
});