-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
337 lines (270 loc) · 7.48 KB
/
server.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
import { startConnectionDB } from "./connectiondb.js"
import express from "express";
import { createServer } from "http";
import { Server } from "socket.io";
import { getLinkPreview } from "link-preview-js";
import * as fs from'fs';
// Init imports
const config = JSON.parse(fs.readFileSync('./config.json', 'utf-8'));
const app = express();
const dbCollection = await startConnectionDB().catch(console.error);
const httpServer = createServer(app);
const io = new Server(httpServer);
// Init Consts
const PORT = config.port;
const __dirname = process.cwd();
// Set public folder
app.use('/public', express.static('public'));
// Edit Page
app.get('/', function (req, res) {
//if(req.headers.host.startsWith("localhost")){
res.sendFile(__dirname + '/editionmode.htm');
//}
});
// Redirect Page
app.get(/\/\w*$/, async function (req, res) {
// Take and filter the adress
let path = req.url;
path = path.substring(1, path.lenght);
const dbDocumentFound = { shortLink: path };
// search in DB
const search = await dbCollection.findOne(dbDocumentFound);
// delete if expired
const currentDate = new Date().getTime();
let allowFindURL = true;
if (search) {
const expiredAfterDate = (search.expire.afterDate !== 0) && (currentDate > search.expire.afterDate);
const expiredAfterNclicks = (search.expire.afterNclicks !== 0) && ((search.clicks + 1) > search.expire.afterNclicks);
if (expiredAfterDate || expiredAfterNclicks) {
await dbCollection.deleteOne(dbDocumentFound);
allowFindURL = false;
}
}
// Redirect URL ?
if (search && allowFindURL) {
// Yes, found in DB
// Increase Clicks
await dbCollection.updateOne(dbDocumentFound, { $inc: { clicks: 1 } })
// Send HTML
const html = `
<!doctype html>
<html>
<head>
<title>Redirecionando</title>
<script>
window.location.href = "${search.originalLink}";
</script>
</head>
<body>
//${search.originalLink}<br>
//${search.clicks + 1 /*+1 to show equal to db*/}<br>
</body>
</html>`;
res.write(html);
} else {
// No, not found in DB
const html = `
<!doctype html>
<html dir="ltr" lang="pt">
<head>
<meta charset="utf-8">
<title>Redirecionando</title>
<style>
body {
background: #fff;
margin: 0;
font-family: 'VarelaRound';
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.warning {
color: #b50505;
text-align: center;
margin-bottom: 150px;
}
.warning img {
filter: hue-rotate(187deg);
}
.container {
background: radial-gradient(circle, rgb(255 0 0 / 7%) 72%, rgb(255 0 0 / 39%) 100%);
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
@font-face {
font-family: 'VarelaRound';
font-style: normal;
font-weight: 400;
font-display: block;
src: url("/public/webfonts/VarelaRound-Regular.ttf") format("truetype");
}
</style>
</head>
<body>
<div class="warning">
<img src="public/img/logo.png" /><br>
Link não encontrado
</div>
<div class="container"></div>
</body>
</html>
`;
res.write(html);
}
res.end();
});
io.on('connection', function(socket){
console.log("user connected");
socket.on('search', async function(searchvalues){
// SEARCH
console.log(searchvalues)
// Declarations
let {pagenumber, nperpage, maxNum, minNum, maxDate, minDate, orderby, ordersense, q} = searchvalues;
const isReverse = ordersense.includes("reverse") ? -1 : 1;
// Adjust search parameters
let findValues = {};
switch (orderby) {
case 'general':
if (q.length > 0) {
orderby = '_id';
findValues = { $text: { $search: q, $caseSensitive: false } }; break;
} else {
orderby = '_id';
findValues = {}; break;
}
case 'tags':
findValues = { tags: { $all: [...(q.split(","))] } }; break;
case 'title':
findValues = { title: q }; break;
case 'shortlink':
findValues = { shortLink: q }; break;
case 'clicks':
findValues = { clicks: { $gt: minNum, $lt: maxNum } }; break;
case 'expireafternclicks':
findValues = { "expire.afterNclicks": { $gt: minNum, $lt: maxNum } }; break;
case 'creation':
findValues = { creation: { $gt: minDate, $lt: maxDate } }; break;
case 'expireafterdate':
findValues = { "expire.afterDate": { $gt: minDate, $lt: maxDate } }; break;
default:
findValues = {};
}
// GET RESULTS
let links = []
const find = await dbCollection.find(findValues)
const nresults = await find.count();
await find.sort( { [orderby]: isReverse } )
.skip( pagenumber > 0 ? ( ( pagenumber - 1 ) * nperpage ) : 0 )
.limit( nperpage )
.forEach( link => {
links = [...links, link]
});
// SEND
//console.log(links)
socket.emit('searchResults', {links,nresults});
});
socket.on('updatelink', async function(link){ // link: [{filter}, {link update}]
await dbCollection.updateOne(link[0],{$set: link[1]});
socket.emit('done');
});
socket.on('newlink', async function(link){ // link: [{link new}]
await dbCollection.insertOne(link);
socket.emit('done');
});
socket.on('excludelink', async function(link){ // link: [{link new}]
await dbCollection.deleteOne(link);
socket.emit('done');
});
socket.on('generateshort', async function(){
let nresults = 1;
let newShort;
while(nresults!==0){
// Generate hash based on all milisseconds since 1970 (Unix-time), convert it to base-36 (0-9 and continues a-z)
newShort = (new Date().getTime()).toString(36);
// Verify existence on actual DB
const find = await dbCollection.find({shortLink: newShort})
nresults = await find.count();
}
socket.emit('generateshort',newShort);
});
socket.on('verifyshort', async function(short){
const find = await dbCollection.find({shortLink: short})
const nresults = await find.count();
if(nresults===0){
socket.emit('verifyshort',true);
}else{
socket.emit('verifyshort',false);
}
});
socket.on('linkinfo', async function(link){
const info = await getLinkPreview(link);
socket.emit('linkinfo',info);
});
socket.on('shortlinkdomain', function(){
socket.emit('shortlinkdomain',config.shortlinkdomain);
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
httpServer.listen(PORT, () => console.log("Server started at " + PORT));
// MISSING
// escrever como montar também
// subir no github
/*
// TEST DB
dbCollection.insertMany([
{
title: "Google",
shortLink: "g",
originalLink: "https://www.google.com/",
favicon: "https://www.google.com/images/branding/googleg/1x/googleg_standard_color_128dp.png",
tags: ["google", "search"],
clicks: 0,
creation: 1627246501761,
expire:{
afterDate: Infinity,
afterNclicks: 10
}
},
{
title: "Youtube",
shortLink: "yt",
originalLink: "https://www.youtube.com/",
favicon: "https://www.youtube.com/s/desktop/1802aa0e/img/favicon_32x32.png",
tags: ["youtube", "videos"],
clicks: 0,
creation: 1627246501761,
expire:{
afterDate: Infinity,
afterNclicks: 10
}
},
{
title: "Google Maps",
shortLink: "gm",
originalLink: "https://www.google.com/maps/",
favicon: "https://www.google.com/images/branding/product/ico/maps15_bnuw3a_32dp.ico",
tags: ["maps", "earth"],
clicks: 0,
creation: 1627246501761,
expire:{
afterDate: Infinity,
afterNclicks: 10
}
}
]);
/**/
/*
// Show DB
const cursor = await dbCollection.find({clicks: {$gt:-1}});
if ((await cursor.count()) === 0) {
console.log("No documents found!");
}else{
cursor.forEach(console.dir);
}
*/