This repository was archived by the owner on Jun 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
363 lines (311 loc) · 11.3 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const Utils = require('./bin/lib/utils/utils');
const express = require('express');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const app = express();
const helmet = require('helmet');
const express_enforces_ssl = require('express-enforces-ssl');
const OktaMiddleware = require('@financial-times/okta-express-middleware');
const session = require('cookie-session');
const PORT = Utils.processEnv('PORT', {validateInteger: true, default: "2018"});
const extract = require('./bin/lib/utils/extract-text');
const hbs = require('hbs');
const LIMITS = require('./bin/lib/aws/translation-api-limit');
const CACHE = require('./bin/lib/aws/translation-cache-table');
const CHECKS = require('./bin/lib/utils/display-checks');
const { get: getFile} = require('./bin/lib/aws/translation-cache-bucket');
const Tracking = require('./bin/lib/utils/tracking');
if (process.env.NODE_ENV === 'production') {
app.use(helmet());
app.enable('trust proxy');
app.use(express_enforces_ssl());
}
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const okta = new OktaMiddleware({
client_id: process.env.OKTA_CLIENT,
client_secret: process.env.OKTA_SECRET,
issuer: process.env.OKTA_ISSUER,
appBaseUrl: process.env.BASE_URL,
scope: 'openid offline_access'
});
const CAPI = require('./bin/lib/ft/capi').init(Utils.processEnv('FT_API_KEY'));
const Translator = require('./bin/lib/translators/multi-translator');
const Audio = require('./bin/lib/utils/get-audio');
const Lexicon = require('./bin/lib/ft/lexicon').init(Utils.processEnv('LEXICON_API_KEY'));
async function generateTranslations(
translatorNames,
text,
lang,
firstChunkOnly,
hasStandfirst = false,
langFrom = false
) {
const extractedText = extract(text);
let translations = {
texts: {}, // name -> text
translatorNames: [], // names
audioUrls: {}, // name -> url
audioButtonText: {} // name -> text
};
translations.texts = await Translator.translate(translatorNames, {
text: extractedText,
to: lang,
from: langFrom,
firstChunkOnly: firstChunkOnly
});
translations.texts['original'] = extractedText;
translations.translatorNames = ['original'].concat(translatorNames);
LIMITS.updateApiLimitUsed(translatorNames, extractedText.replace(/\s/g, "").length);
translations = Utils.formatOutput(translations, hasStandfirst);
translations = Audio.get(translations, lang);
return translations;
}
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept'
);
next();
});
app.use(session({
secret: process.env.SESSION_TOKEN,
maxAge: 24 * 3600 * 1000, //24h
httpOnly: true
}));
app.post('/article/:uuid/:lang', (req, res, next) => {
res.uuid = req.params.uuid;
res.lang = req.params.lang;
res.langFrom = req.body.from;
const fromCache = req.body.fromCache;
const checkCache = req.body.checkCache;
res.translators = JSON.parse(req.body.translators);
if (fromCache) {
Tracking.splunk(`request=article uuid=${res.uuid} language=${res.lang} type=fromCache translators=${res.translators}`);
return getFile(`${res.uuid}_${res.translators[0]}`)
.then(data => res.json(data))
.catch(err => Tracking.splunk(`error="getFile error" message=${JSON.stringify(err)} route=/article/${res.uuid}/${res.lang}`));
}
Tracking.splunk(`request=article uuid=${res.uuid} language=${res.lang} translators=${res.translators}`);
res.firstChunkOnly =
!req.query.hasOwnProperty('firstChunkOnly') || !!req.query.firstChunkOnly; // default is firstChunkOnly=true
CAPI.get(res.uuid)
.then(async data => {
const text = data.bodyXML;
const title = Utils.maybeAppendDot(data.title);
res.standfirst = '';
if (data.standfirst) {
res.standfirst = Utils.maybeAppendDot(data.standfirst);
} // adding a closing . improves the translation
res.combinedText = title + '\n\n' + res.standfirst + '\n\n' + text;
res.pubDate = data.lastModified;
if(checkCache) {
const promises = [];
for(let i = 0; i < res.translators.length; ++i) {
const check = CACHE.checkAndGet(`${res.uuid}_${res.translators[i]}`, res.lang.toLowerCase(), res.pubDate);
promises.push(check);
}
return Promise.all(promises)
.then(data => {
if(data.length !== 1 && data.every( item => item === data[0] )) {
return next();
}
const names = ['original'].concat(res.translators);
const newTranslations = [];
const cachedTranslations = [];
let formattedResult = {
article: res.uuid,
texts: {
'original': extract(res.combinedText)
},
translatorNames: names,
audioUrls: {},
audioButtonText: {}
}
for(let i = 0; i < data.length; ++i) {
if(!data[i]) {
newTranslations.push(res.translators[i]);
} else {
cachedTranslations.push(res.translators[i]);
formattedResult.texts[res.translators[i]] = JSON.parse(data[i])[res.lang.toLowerCase()];
}
}
formattedResult = Utils.formatOutput(formattedResult, !!res.standfirst, true, cachedTranslations.concat('original'));
formattedResult = Audio.get(formattedResult, res.lang, cachedTranslations.concat('original'));
if(newTranslations.length > 0) {
if(cachedTranslations.length > 0) {
res.translators = newTranslations;
res.formattedResult = formattedResult;
}
return next();
} else {
return res.json(formattedResult);
}
})
.catch(err => Tracking.splunk(`error="Check cache error" message=${JSON.stringify(err)} route=/article/${res.uuid}/${res.lang}`));
} else {
return next();
}
})
.catch(err => {
Tracking.splunk(`error="CAPI error" message=${JSON.stringify(err)} route=/article/${res.uuid}/${res.lang}`);
res.json({
original: { error: `Error, cannot find article with uuid ${res.uuid}` },
outputs: ['original']
});
});
}, (req, res) => {
generateTranslations(
res.translators,
res.combinedText,
res.lang,
res.firstChunkOnly,
res.standfirst,
res.langFrom
).then(translations => {
for(let i = 0; i < res.translators.length; ++i) {
if(res.translators[i] !== 'original') {
CACHE.update({uuid: res.uuid, lang: res.lang, lastPubDate: res.pubDate, translation: translations.texts[res.translators[i]], translator: res.translators[i]});
}
}
translations.article = res.uuid;
if(res.formattedResult) {
translations.translatorNames = res.formattedResult.translatorNames;
translations.texts = Object.assign(res.formattedResult.texts, translations.texts);
translations.audioUrls = Object.assign(res.formattedResult.audioUrls, translations.audioUrls);
translations.audioButtonText = Object.assign(res.formattedResult.audioButtonText, translations.audioButtonText);
}
return res.json(translations);
})
.catch(err => Tracking.splunk(`error=Generate translations message=${JSON.stringify(err)} route=/article/${res.uuid}/${res.lang}`));
});
app.post('/translation/:lang', (req, res) => {
const text = req.body.text;
const lang = req.params.lang;
const translators = JSON.parse(req.body.translators);
const firstChunkOnly =
!req.query.hasOwnProperty('firstChunkOnly') || !!req.query.firstChunkOnly; // default is firstChunkOnly=true
Tracking.splunk(`request=freeText language=${lang} translators=${translators}`);
generateTranslations(translators, text, lang, firstChunkOnly)
.then(translations => {
res.json(translations);
})
.catch(err => {
Tracking.splunk(`error="Generate translation error" message=${JSON.stringify(err)} route=/translation/${lang}`);
res.json({
original: { error: `Error, cannot translate text` },
outputs: err
});
});
});
app.post('/lexicon/:lang', (req, res) => {
const lexQuery = req.body.text;
const lang = req.params.lang;
const langFrom = req.body.from;
const translators = JSON.parse(req.body.translators);
const firstChunkOnly =
!req.query.hasOwnProperty('firstChunkOnly') || !!req.query.firstChunkOnly; // default is firstChunkOnly=true
Tracking.splunk(`request=lexicon term=${lexQuery} language=${lang} translators=${translators}`);
return Lexicon.search(lexQuery)
.then(async text => {
const combinedText = 'Lexicon Search Term: ' + lexQuery + '\n\n' + extract(text);
const translations = await generateTranslations(
translators,
combinedText,
lang,
firstChunkOnly,
false,
langFrom
);
res.json(translations);
})
.catch(err => {
Tracking.splunk(`error="Lexicon error" message=${JSON.stringify(err)} route=/lexicon/${lang}`);
res.json({
original: {
error: `Error, cannot translate lexicon query ${lexQuery}`
},
outputs: err
});
});
});
app.get('/check/:uuid/:pubDate', async (req, res) => {
const uuid = req.params.uuid;
const translator = Utils.processEnv('NEXT_TRANSLATOR');
const clientPubDate = req.params.pubDate;
const lastPubDate = await CAPI.get(uuid)
.then(async data => {
if(data.lastModified) {
return data.lastModified;
}
return data.publishedDate;
})
.catch(err => {
console.log(err);
return clientPubDate;
});
Tracking.splunk(`request=NextDisplay uuid=${res.uuid}`);
CHECKS.check(uuid, translator, lastPubDate)
.then(data => { return res.json(data) })
.catch(err => Tracking.splunk(`error="Display check" message=${JSON.stringify(err)} route=/check/${uuid}/${lastPubDate}`));
});
app.use('/client', express.static(path.resolve(__dirname + '/public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
hbs.registerPartials(__dirname + '/views/partials');
app.get('/content/:uuid', (req,res) => {
const uuid = req.params.uuid;
const exampleUUIDs = process.env.USER_TEST_UUIDS.split(',');
const data = {};
Tracking.splunk(`request=content uuid=${uuid}`);
const contentID = exampleUUIDs.findIndex(item => {
return item === uuid;
});
if(contentID === -1) {
data.partial1 = true;
} else {
data[`partial${contentID + 1}`] = true;
}
res.render('content', data);
});
app.use(okta.router);
app.use(okta.ensureAuthenticated());
app.use(okta.verifyJwts());
app.get('/', async (req, res) => {
const settings = await Translator.settings(Utils.extractUser(req.userContext.userinfo));
return res.render('index', settings);
});
app.get('/demo/:uuid', (req, res) => {
CAPI.get(req.params.uuid).then(data => {
const text = data.bodyXML;
const { title, byline, standfirst } = data;
res.render('demo', { text, title, byline, standfirst });
});
});
app.get('/demo-static/:demoType', (req, res) => {
const demoType = req.params.demoType;
const availableDemos = ['side-by-side', 'toggle'];
let toggle = false;
if (demoType === 'toggle') toggle = true;
if (availableDemos.includes(demoType)) {
res.render('demoStatic', { demoType, toggle });
} else {
res
.status(500)
.send(
`Demo type not recognised. The available types are: ${availableDemos.join(', ')}`
);
}
});
app.get('/get-translation/:uuid/:language', (req, res) => {
const uuid = req.params.uuid;
const language = req.params.language;
fs.readFile(`./public/demoTranslations/${uuid}.json`, (err, data) => {
res.json(JSON.parse(data)[language]);
});
});
if (process.env.NODE_ENV !== 'production') console.log(`Server is running locally on port ${PORT}`);
app.listen(PORT);