-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
327 lines (244 loc) · 7.03 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
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
import express from 'express';
// Node File Interaction
import fs from 'fs';
// Generate uuids
import { nanoid } from 'nanoid'
import path from 'path';
// Check valid urls
import validUrl from 'valid-url';
import { fileURLToPath } from 'url';
// Template Engine
import * as eta from "eta"
const __filename = fileURLToPath(import.meta.url);
// const __dirname = path.dirname(__filename);
const app = express();
const port = 80;
const delimiter = " ";
// Enable render engine
app.engine("eta", eta.renderFile);
app.set("view engine", "eta");
app.set('views', './views');
app.use(express.json());
app.use(express.static('public'));
// Include static files of bulma and fontawesome
app.use(express.static('node_modules/bulma/css'));
app.use(express.static('node_modules/@fortawesome/fontawesome-free/'));
// variable to hold urls
let keyUrlPairs = "";
let subtitles = "";
// Serve the index page
app.get('/', (req, res) => {
let subtitle = subtitles[Math.floor(Math.random() * subtitles.length)];
res.render("index", {
numberOfUrls: countUrls(),
numberOfRedirects: countRedirects(),
title: "FlowerLink",
subtitle: subtitle
})
})
// forwarding route
app.get('/:key', (req, res, next) => {
let urlFound = getUrlUsingKey(req.params.key);
if (typeof urlFound !== "undefined") {
increaseClicksOf(req.params.key);
res.redirect(urlFound);
} else {
// Continue to the next handler (404)
next();
}
})
/**
* POST Route to submit urls
*/
app.post('/submit-url', (req, res) => {
// get url from post body
let url = req.body.url;
let target = req.body.target;
// Check if it is a proper url
if (!validUrl.isUri(url)) {
res.json({error: "Sorry it seems that this is no proper URL."});
return;
}
if (url.length > 500) {
res.json({error: "This URL is unfortunately too long with over 500 characters."});
return;
}
let uuid;
// If the target exists and it is not a uri, check further
if (target != null && !validUrl.isUri(target)) {
// Check if the target is already taken
if (isUuidAlreadyTaken(target)) {
res.json({error: "Sorry, this target is already taken."});
return;
}
// Check if the target is a valid string
if (!testTarget(target)) {
res.json({error: "Sorry, this target is not valid. Only use letters, numbers and hyphens"});
return;
}
// Check if it is too long
if (target.length > 30) {
res.json({error: "Why are you using an shortener?! Make it shorter!"});
return;
}
uuid = target;
} else {
// Generate uuid
uuid = generateUuid();
}
// send response with the key
res.json({key: uuid});
// Prepare the string to be appended
let append = uuid + delimiter + 0 + delimiter + url;
// Write to file
fs.appendFileSync('urls.txt', "\n" + append, function (err) {
if (err) throw err;
});
// then load the paths into the variable
readPaths();
console.log("New url added at " + new Date().toISOString() + " with a total now of " + countUrls() + " urls");
});
/**
* 404 Handler
*/
app.use(function(req, res, next) {
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.status(404).send('Sorry cant find that!');
return;
}
// respond with json
if (req.accepts('json')) {
res.json({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
/**
* Start the server
*/
app.listen(port, () => {
console.log('App listening at port ' + port);
// console.log("Paths variable is: " + keyUrlPairs)
})
/**
* Read the paths file and update the variable
*/
function readPaths() {
fs.readFile('urls.txt', 'utf8' , (err, data) => {
if (err) {
console.log("No urls.txt could be found. Therefore a new one will be created.");
return
}
//console.log(new Date().toISOString());
// console.log(data);
keyUrlPairs = data.split("\n");
});
}
function generateUuid() {
let uuid;
do {
uuid = nanoid(4);
} while (isUuidAlreadyTaken(uuid));
return uuid;
}
/**
* Find URL using the key
*/
function getUrlUsingKey(key) {
let index, value, result;
for (index = 0; index < keyUrlPairs.length; ++index) {
value = keyUrlPairs[index].split(delimiter);
if (value[0] == key) {
result = value[2];
break;
}
}
return result;
}
/**
* Increase the click count of the link with key
*/
function increaseClicksOf(key) {
let index, row;
for (index = 0; index < keyUrlPairs.length; ++index) {
// Split the current row
row = keyUrlPairs[index].split(delimiter);
// If we have the right row
if (row[0] == key) {
// Increase the number
row[1] = (parseInt(row[1]) + 1);
// Reattach it back into the array
keyUrlPairs[index] = row.join(" ");
// Write it down
writeUrlsToFile();
break;
}
};
}
/**
* Increase the click count of the link with key
*/
function writeUrlsToFile() {
// Remove content
fs.truncateSync('urls.txt', 0, function (err) {
if (err) throw err;
});
let toWrite = keyUrlPairs.join("\n").replace(/[\r\n]+$/, '');
// Write current array to file
fs.appendFileSync('urls.txt', toWrite, function (err) {
if (err) throw err;
});
// then load the paths into the variable
readPaths();
}
function isUuidAlreadyTaken(uuid) {
let index;
let currentUuid;
for (index = 0; index < keyUrlPairs.length; ++index) {
currentUuid = keyUrlPairs[index].split(delimiter)[0];
if (currentUuid == uuid) {
return true;
}
}
return false;
}
function countUrls() {
return keyUrlPairs.length;
}
/**
* Function to count the total number of redirects of all links
*/
function countRedirects() {
let index;
let redirects = 0;
for (index = 0; index < keyUrlPairs.length; ++index) {
// Add all redirects. In case of NaN, return 0
redirects += parseInt(keyUrlPairs[index].split(delimiter)[1]) || 0;
}
return redirects;
}
/**
* Function to read the subtitles text file and store it in a variable
*/
function readSubtitlesFile() {
fs.readFile('subtitles.txt', 'utf8' , (err, data) => {
if (err) {
console.log("No urls.txt could be found. Therefore a new one will be created.");
return
}
//console.log(new Date().toISOString());
// console.log(data);
subtitles = data.split("\n");
});
}
function testTarget(target) {
const regex = /^[a-zA-Z0-9-]+$/;
return regex.test(target);
}
// Read the current paths
console.log("Initial scan at " + new Date().toISOString());
readPaths();
readSubtitlesFile();