forked from openwhyd/openwhyd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
234 lines (209 loc) Β· 7.62 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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
//@ts-check
var /*consoleWarn = console.warn,*/ consoleError = console.error;
if (!process.env.DISABLE_DATADOG) {
// Initialize Datadog APM
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore // cf https://docs.datadoghq.com/fr/tracing/trace_collection/dd_libraries/nodejs/?tab=autresenvironnements
process.datadogTracer = require('dd-trace').init({
profiling: true, // cf https://docs.datadoghq.com/fr/profiler/enabling/nodejs/?tab=incode
});
}
const util = require('util');
var openwhydVersion = require('./package.json').version;
function makeColorConsole(fct, color) {
return function () {
for (let i in arguments)
if (arguments[i] instanceof Object || arguments[i] instanceof Array)
arguments[i] = util.inspect(arguments[i]);
fct(Array.prototype.join.call(arguments, ' ')[color]);
};
}
function makeErrorLog(fct, type) {
return function () {
fct(
type === 'Warning' ? 'β ' : 'β',
type,
'--',
new Date().toUTCString(),
...arguments,
);
};
}
console.warn = makeErrorLog(consoleError, 'Warning');
console.error = makeErrorLog(consoleError, 'Error');
// app configuration
if (process.env['WHYD_GENUINE_SIGNUP_SECRET'] === undefined)
throw new Error(`missing env var: WHYD_GENUINE_SIGNUP_SECRET`);
if (process.env['WHYD_CONTACT_EMAIL'] === undefined)
throw new Error(`missing env var: WHYD_CONTACT_EMAIL`);
const dbCreds = {
mongoDbHost: process.env['MONGODB_HOST'] || 'localhost',
mongoDbPort: process.env['MONGODB_PORT'] || '27017',
mongoDbAuthUser: process.env['MONGODB_USER'],
mongoDbAuthPassword: process.env['MONGODB_PASS'],
mongoDbDatabase: process.env['MONGODB_DATABASE'], // || "openwhyd_data",
};
const params = (process.appParams = {
// server level
port: process.env['WHYD_PORT'] || 8080, // overrides app.conf
urlPrefix:
process.env['WHYD_URL_PREFIX'] ||
`http://localhost:${process.env['WHYD_PORT'] || 8080}`, // base URL of the app
isOnTestDatabase: dbCreds.mongoDbDatabase === 'openwhyd_test',
color: true,
// secrets
genuineSignupSecret: process.env.WHYD_GENUINE_SIGNUP_SECRET,
// workers and general site logic
searchModule:
process.env.ALGOLIA_APP_ID && process.env.ALGOLIA_API_KEY
? 'searchAlgolia'
: '', // "searchElastic" // "" => no search index
// recomPopulation: true, // populate recommendation index at startup
// email notification preferences
emailModule: 'emailSendgrid', // "DISABLED"/"null" => fake email sending
digestInterval: 60 * 1000, // digest worker checks for pending notifications every 60 seconds
digestImmediate: false, // when true, digests are sent at every interval, if any notifications are pending
feedbackEmail: process.env.WHYD_CONTACT_EMAIL, // mandatory
// rendering preferences
version: openwhydVersion,
startTime: new Date(),
nbPostsPerNewsfeedPage: 20,
nbTracksPerPlaylistEmbed: 100,
paths: {
whydPath: __dirname,
uploadDirName: 'upload_data',
uAvatarImgDirName: 'uAvatarImg',
uCoverImgDirName: 'uCoverImg',
uPlaylistDirName: 'uPlaylistImg',
},
});
const FLAGS = {
'--no-color': function () {
process.appParams.color = false;
},
'--fakeEmail': function () {
params.emailModule = '';
},
'--emailAdminsOnly': function () {
params.emailModule = 'emailAdminsOnly';
},
'--runner': function () {
/* ignore this parameter from start-stop-daemon -- note: still required? */
},
};
// when db is read
function makeMongoUrl(params) {
const host = params.mongoDbHost;
const port = parseInt(params.mongoDbPort);
const user = params.mongoDbAuthUser;
const password = params.mongoDbAuthPassword;
const db = params.mongoDbDatabase; // ?w=0
const auth =
user || password
? `${encodeURIComponent(user)}:${encodeURIComponent(password)}@`
: '';
return `mongodb://${auth}${host}:${port}/${db}`;
}
function start() {
if (process.env['WHYD_SESSION_SECRET'] === undefined)
throw new Error(`missing env var: WHYD_SESSION_SECRET`);
const myHttp = require('./app/lib/my-http-wrapper/http');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const sessionMiddleware = session({
secret: process.env.WHYD_SESSION_SECRET,
store: new MongoStore({
url: makeMongoUrl(dbCreds),
}),
cookie: {
maxAge: 365 * 24 * 60 * 60 * 1000, // cookies expire in 1 year (provided in milliseconds)
// secure: process.appParams.urlPrefix.startsWith('https://'), // if true, cookie will be accessible only when website if opened over HTTPS
sameSite: 'strict',
},
name: 'whydSid',
resave: false, // required, cf https://www.npmjs.com/package/express-session#resave
saveUninitialized: false, // required, cf https://www.npmjs.com/package/express-session#saveuninitialized
});
var serverOptions = {
urlPrefix: params.urlPrefix,
port: params.port,
appDir: __dirname,
sessionMiddleware,
errorHandler: function (req, params = {}, response, statusCode) {
// to render 404 and 401 error pages from server/router
console.log(
`[app] rendering server error page ${statusCode} for ${req.method} ${req.path}`,
);
require('./app/templates/error.js').renderErrorResponse(
{ errorCode: statusCode },
response,
params.format ||
(req.accepts('html')
? 'html'
: req.accepts('json')
? 'json'
: 'text'),
req.getUser(),
);
},
uploadSettings: {
uploadDir: params.paths.uploadDirName, // 'upload_data'
keepExtensions: true,
},
};
require('./app/models/logging.js'); // init logging methods (IncomingMessage extensions)
const appServer = new myHttp.Application(serverOptions);
appServer.start(() => {
const url = params.urlPrefix || `http://127.0.0.1:${params.port}/`;
console.log(`[app] Server running at ${url}`);
});
require('./app/workers/notifEmails.js'); // start digest worker
require('./app/workers/hotSnapshot.js'); // start hot tracks snapshot worker
function closeGracefully(signal) {
console.warn(`[app] ${signal} signal received: closing server...`);
appServer.stop((err) => {
console.warn(`[app] server.close => ${err || 'OK'}`);
process.exit(err ? 1 : 0);
});
}
process.on('SIGTERM', closeGracefully);
process.on('SIGINT', closeGracefully);
}
// startup
async function main() {
// apply command-line arguments
if (process.argv.length > 2) {
// ignore "node" and the filepath of this script
for (let i = 2; i < process.argv.length; ++i) {
var flag = process.argv[i];
var flagFct = FLAGS[flag];
if (flagFct) flagFct();
else if (flag.indexOf('--') == 0)
params[flag.substring(2)] = process.argv[++i];
}
}
if (params.color == true) {
require('colors'); // populates .grey, .cyan, etc... on strings, for logging.js and MyController.js
console.warn = makeErrorLog(
makeColorConsole(consoleError, 'yellow'),
'Warning',
);
console.error = makeErrorLog(
makeColorConsole(consoleError, 'red'),
'Error',
);
} else {
process.appParams.color = false;
}
console.log(`[app] Starting Openwhyd v${params.version}`);
const mongodb = require('./app/models/mongodb.js'); // we load it from here, so that process.appParams are initialized
await util.promisify(mongodb.init)(dbCreds);
await mongodb.initCollections();
start();
}
main().catch((err) => {
// in order to prevent UnhandledPromiseRejections, let's catch errors and exit as we should
console.log('[app] error from main():', err);
console.error('[app] error from main():', err);
process.exit(1);
});