-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
252 lines (204 loc) · 6.54 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/* dotenv */
if (process.env.NODE_ENV !== "production") {
require("dotenv").config();
};
/* libraries */
const express = require("express");
const path = require("path");
const ejs = require('ejs');
const fs = require('fs');
const { google } = require('googleapis');
const i18n = require('./config/i18n');
const cookieParser = require('cookie-parser');
const { convertXmlToHtml, convertCommentXMLToHtml, convertXmlToHtmlWithImages, convertTranslationXMLToHtml } = require('./assets/js/convert.js');
//const { xmlInfo } = require('./assets/js/collect_info.js');
/* app */
const app = express();
app.use(cookieParser());
app.use(i18n.init);
/* static files */
app.use("/assets", express.static("assets"));
app.use("/data", express.static("data"));
/* views */
app.set("views", [
path.join(__dirname, "views")
]);
app.set("view engine", "ejs");
// app.use("/views", express.static("views"));
app.get('/change-language/:lang', (req, res) => {
const lang = req.params.lang;
if (['en', 'it'].includes(lang)) {
res.cookie('lang', lang);
// Redirect back to the previous page
res.redirect(req.headers.referer || '/');
} else {
res.redirect('/');
}
});
/* index */
app.get(process.env.URL_PATH, (req, res) => {
var arrayN = ["1", "2", "3"];
res.render("index", {
arrayN: arrayN,
currentLang: req.getLocale()
});
});
/* introduzione */
const introduzione = require("./routes/introduzione");
app.use("/", introduzione);
/* progetto */
const progetto = require("./routes/progetto");
app.use("/", progetto);
/* commenti */
const commenti = require("./routes/commenti");
app.use("/", commenti);
/* commenti */
const traduzione = require("./routes/traduzione");
app.use("/", traduzione);
/* reader */
const reader = require("./routes/reader");
app.use("/", reader);
/* traduco */
const traduco = require("./routes/traduco");
app.use("/", traduco);
/* vedo */
const vedo = require("./routes/vedo");
app.use("/", vedo);
/* vignette */
const vignette = require("./routes/vignette");
app.use("/", vignette);
/* credits */
const credits = require("./routes/credits");
app.use("/", credits);
/* prova estrazione id */
function extractIds(html) {
const idArray = [];
const regex = /<span[^>]*id=["']([^"']+-[^"']+)["'][^>]*>/g;
let match;
while ((match = regex.exec(html)) !== null) {
const id = match[1];
idArray.push(id.split("-")[1]); //all the ids are "2b-01"; if [0] it would print only 2b
}
return idArray;
};
app.get('/extract-ids', (req, res) => {
fs.readFile('./quarantana/html/cap1.html', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the EJS file:', err);
res.status(500).send('Error reading the EJS file');
return;
}
const renderedHtml = ejs.render(data);
const idArray = extractIds(renderedHtml);
res.json(idArray);
});
});
app.get('/get-chapter/:chapterName', function (req, res) {
var chapterName = req.params.chapterName;
if (chapterName === "Introduzione") {
chapterName = "intro";
}
converted_data = convertXmlToHtml(chapterName);
res.send(converted_data);
});
app.get('/get-chapter-with-images/:chapterName', function (req, res) {
var chapterName = req.params.chapterName;
if (chapterName === "Introduzione") {
chapterName = "intro";
} else if (chapterName === "Frontespizio") {
chapterName = "header";
}
converted_data = convertXmlToHtmlWithImages(chapterName);
res.send(converted_data);
});
// app.get('/get-comment/:authorName?', function (req, res) {
// var author = req.params.authorName;
// if (author) {
// try {
// var converted_data = convertCommentXMLToHtml(author);
// res.send(converted_data);
// } catch (error) {
// // Handle errors that might occur during conversion
// console.error(error);
// res.status(500).send('An error occurred while processing your request.');
// }
// } else {
// // Send an empty object if the authorName parameter is not provided
// res.status(200).send("");
// }
// });
app.get('/get-comment/:authorName/:chapterName?', function (req, res) {
var author = req.params.authorName;
var chapter = req.params.chapterName || 'intro'; // Default to 'intro' if chapterName is not provided
if (chapter === 'Introduzione') {
chapter = 'intro';
}
if (author && chapter) {
try {
var converted_data = convertCommentXMLToHtml(author, chapter);
if (converted_data && converted_data.trim()) {
res.send(converted_data);
} else {
// Comment not found
res.status(204).send(); // No Content
}
} catch (error) {
console.error(error);
res.status(500).send('An error occurred while processing your request.');
}
} else {
res.status(400).send('Author name and chapter are required.');
}
});
app.get('/get-translation/:language/:chapterName?', function (req, res) {
var language = req.params.language;
var chapter = req.params.chapterName;
if (chapter === "Introduzione") {
chapter = "intro";
}
if (language && chapter) {
try {
var converted_data = convertTranslationXMLToHtml(language, chapter);
res.send(converted_data);
} catch (error) {
// Handle errors that might occur during conversion
console.error(error);
res.status(500).send('An error occurred while processing your request.');
}
} else {
// Send an empty object if the authorName parameter is not provided
res.status(200).send("");
}
});
// Function to get GA4 analytics data
async function getAnalyticsData() {
const auth = new google.auth.GoogleAuth({
keyFile: process.env.GOOGLE_APPLICATION_CREDENTIALS,
scopes: 'https://www.googleapis.com/auth/analytics.readonly',
});
const authClient = await auth.getClient();
const analyticsData = google.analyticsdata('v1beta');
const request = {
auth: authClient,
property: `properties/${process.env.GA_PROPERTY_ID}`,
requestBody: {
dateRanges: [{ startDate: '2023-01-12', endDate: 'today' }],
dimensions: [{ name: 'country' }],
metrics: [{ name: 'activeUsers' }],
},
};
const response = await analyticsData.properties.runReport(request);
return response.data;
};
app.get('/visitors', async (req, res) => {
try {
const data = await getAnalyticsData();
res.json(data);
} catch (error) {
console.error('Error fetching analytics data:', error);
res.status(500).send('Error fetching analytics data');
}
});
/* port */
const port = 8000;
app.listen(port, () => console.log(`Quaranta commenti is listening on localhost:${port}${process.env.URL_PATH}`));