-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
318 lines (245 loc) · 9.32 KB
/
index.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
//Entry point index.js
//Exposes main REST endpoints
require('dotenv').config();
const express = require('express');
const fileUpload = require('express-fileupload');
const bodyParser = require('body-parser');
const { promisify } = require('util');
const cors = require('cors');
const morgan = require('morgan');
const _ = require('lodash');
const { v4: uuidv4 } = require('uuid');
var crypto = require('crypto');
const authMiddleware = require('./auth');
const helperLCPencrypt = require('./helperLCPencrypt');
const helperES = require('./helperES');
const helperLCPServer = require('./helperLCPServer');
const helperEPUB = require('./helperEPUB');
const Sentry = require("@sentry/node");
const Tracing = require("@sentry/tracing");
const SENTRY_DSN = process.env.SENTRY_DSN;
const app = express();
Sentry.init({
dsn: SENTRY_DSN,
integrations: [
// enable HTTP calls tracing
new Sentry.Integrations.Http({ tracing: true }),
// enable Express.js middleware tracing
new Tracing.Integrations.Express({ app }),
],
// Adjust this value in production, or using tracesSampler for finer control
tracesSampleRate: 1.0,
});
// RequestHandler creates a separate execution context using domains, so that every
// transaction/span/breadcrumb is attached to its own Hub instance
app.use(Sentry.Handlers.requestHandler());
// TracingHandler creates a trace for every incoming request
app.use(Sentry.Handlers.tracingHandler());
// enable files upload
app.use(fileUpload({
createParentPath: true,
limits: {
fileSize: 200 * 1024 * 1024 * 1024 //200MB max file(s) size
},
abortOnLimit: true
}));
//add other middleware
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(morgan('dev'));
app.use(authMiddleware)
app.get('/hello', (req, res) => {
res.send('Hello World!')
console.log(authMiddleware)
});
//#region publisher endpoints
//Uploads and stores a new .epub
app.post('/publisher/contents/uploadepub', async (req, res) => {
var ret = 'abc'
const BookClubReaderId = authMiddleware.BookClubReaderId
try {
if(!req.files) {
res.send({
status: false,
message: 'No file uploaded'
});
}
else {
//Using name of the input field to retrieve the uploaded file
let publicationFile = req.files.publication;
//console.log(req.body.publicationinfo);
const contentid = uuidv4()
const fileName = contentid + '.epub';
const baseUploadFolder = process.env.UPLOAD_FOLDER
const ePubFolder = baseUploadFolder + 'epub/'
const inputFile = ePubFolder + fileName
const outputFile = baseUploadFolder + 'epub/out' + fileName //+ publicationFile.name
console.log('About to move From: ' + inputFile + ' To: ' + outputFile)
const coverPageFileName = contentid //Will set extension latter when processing the ePub
const JPEGFolder = baseUploadFolder + 'jpeg/'
const coverPageFile = JPEGFolder + coverPageFileName
let pubInfoJSON = JSON.parse(req.body.publicationinfo);
pubInfoJSON['content-id'] = contentid
pubInfoJSON['BookClubReaderId'] = BookClubReaderId
publicationFile.mv(inputFile, coverPageFile) //MOVE FILE TO PREFERED LOCATION
.then(async (respublicationFile) => {
console.log('File MOVED Successfully')
await helperEPUB.readEPUBAsync(inputFile, coverPageFile, pubInfoJSON) //READ EPUB FILE
.then(async (reshelperEPUB) => {
console.log('EPUB read Successfully')
pubInfoJSON = reshelperEPUB
console.log(reshelperEPUB)
console.log('---------------------')
//pubInfoJSON['ePUBINFO'] = reshelperEPUB //[{"Type": "car"}]
//console.log(pubInfoJSON)
await helperLCPencrypt.encryptAsync(inputFile, outputFile, contentid) //ENCRYPT THE EPUB
.then(async (reshelperLCPencrypt) => {
console.log('Encrypted Successfully')
console.log(reshelperLCPencrypt)
const LCPEncryptJSON = JSON.parse(reshelperLCPencrypt)
//store the Publication
await helperLCPServer.storePublicationAsync(LCPEncryptJSON) //STORE THE PUBLICATION WITH THE LCP SERVER
.then( async (reshelperLCPServer) => {
console.log('Store Pub successful')
await helperES.addPublicationAsync(pubInfoJSON) //STORE ON ELASTIC
.then( helperES => {
console.log('Add Pub to ES successfull')
console.log(helperES)
})
.catch(err => {
console.log('Add Pub to ES failed')
console.error(err)
//res.status(500).send(err);
});
})
.catch(err => {
console.log('Store Pub Failed')
res.status(500).send(err);
});
})
.catch(err => {
console.log('LCPEncrypt failed')
console.error(err)
//res.status(500).send(err);
});
})
.catch(err => {
console.log('EPUB read failed')
console.error(err)
res.send({
status: 500,
message: err
});
});
})
console.log('wrapping up again')
res.send({
status: true,
message: {
'content-id': contentid ,// publicationFile.name,
publicationURL: process.env.CLIENT_BASE_URL +':' + process.env.SERVER_PORT + '/publisher/contents/?content-id=' + pubInfoJSON['content-id']
}
});
}
} catch (err) {
console.log("ERROR999: " + err)
res.status(500).send(err);
}
});
//#endregion publisher endpoints
//#region eStore endpoints
app.post('/estore/contents/generatelicense', async (req, res) => {
var ret = 'abc'
console.log(ret)
const BookClubReaderId = authMiddleware.BookClubReaderId
const BookClubReaderEmail = authMiddleware.email
try {
if(!req.body.contentid || !req.body.licenserequestinfo) {
res.send({
status: 500,
message: 'Either content id or licenserequestinfo is missing on request body'
});
}
else {
console.log('BookClubReaderId: ' + BookClubReaderId)
let licenseRequestInfoJSON = JSON.parse(req.body.licenserequestinfo)
let contentid = req.body.contentid
const secret = licenseRequestInfoJSON['encryption']['user_key']['hex_value'];
const hash = crypto.createHmac('sha256', secret)
.update(licenseRequestInfoJSON['encryption']['user_key']['text_hint'])
.digest('hex');
licenseRequestInfoJSON['encryption']['user_key']['hex_value'] = hash
console.log(licenseRequestInfoJSON['encryption']['user_key']['hex_value']);
await helperLCPServer.generatePublicationLicenseAsync(contentid, licenseRequestInfoJSON)
.then( async reshelperLCPServer => {
console.log('LICENSE Retrieval from LCP Server successful')
console.log(reshelperLCPServer.status)
console.log(reshelperLCPServer.data)
let publicationLicenseJSON = {license_data: reshelperLCPServer.data}
await helperES.addPublicationLicenseAsync(publicationLicenseJSON)
.then(resHelper =>{
console.log('Store new license in ES successful')
res.send({
status: true,
message: {
'content-id': contentid,
publicationURL: process.env.CLIENT_BASE_URL +':' + process.env.SERVER_PORT + '/estore/pub/?id=' + contentid
},
license_data: reshelperLCPServer.data
});
})
.catch(err => {
console.log('Store new license in ES failed')
console.error(err)
res.send({
status: 500,
message: 'License generation failed'
});
});
})
.catch(err => {
console.log('LICENSE Retrieval from LCP Server failed')
console.error(err)
res.send({
status: 500,
message: 'License generation failed'
});
});
}
} catch (err) {
//res.status(500).send(err);
res.send({
status: 500,
message: 'Error occured',
data: err
});
}
});
//#endregion eStore endpoints
app.get("/debug-sentry", function mainHandler(req, res) {
throw new Error("Fake Sentry error!");
});
app.use(
Sentry.Handlers.errorHandler({
shouldHandleError(error) {
// Capture all 404 and 500 errors
if (error.status === 404 || error.status === 500) {
return true;
}
return false;
},
})
);
app.use(function onError(err, req, res, next) {
// The error id is attached to `res.sentry` to be returned
// and optionally displayed to the user for support.
res.statusCode = 500;
res.end(res.sentry + "\n");
});
const startServer = async () => {
const port = process.env.SERVER_PORT || 3000
await promisify(app.listen).bind(app)(port)
console.log(`Listening on port ${port}`)
}
startServer()