-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
303 lines (251 loc) · 9.29 KB
/
server.js
File metadata and controls
303 lines (251 loc) · 9.29 KB
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
const express = require('express');
const bodyParser = require('body-parser');
const qrcode = require('qrcode');
const { encode } = require('base62');
const http = require('http');
const socketIo = require('socket.io');
const fs = require('fs');
const app = express();
const io = socketIo();
const cors = require('cors');
const corsOptions = {
origin: 'http://127.0.0.1:5501', // Specify the allowed origin
credentials: true, // Indicate that cookies should be included in cross-site requests
};
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
const urlDatabase = {};
let idCounter = 1;
// Function to generate a 5-letter encoded short URL
function generateShortUrl() {
return encode(idCounter++, { characters: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' }).slice(0, 5);
}
// User tracking by IP address and daily URL count
const userTracking = {};
// Serve the dynamic dashboard
app.get('/dashboard', (req, res) => {
// Read the dashboard.html file
fs.readFile('public/dashboard.html', 'utf8', (err, data) => {
if (err) {
console.error(err);
res.status(500).send('Error reading dashboard.html');
} else {
res.send(data);
}
});
});
// Create Short URL with Custom Short Link and Timestamp
app.post('/api/shorten', async (req, res) => {
const { originalUrl, customShortUrl } = req.body;
const userIp = req.ip;
// Check if the user has reached the daily limit (5 URLs)
if (!userTracking[userIp]) {
userTracking[userIp] = [];
}
if (userTracking[userIp].length >= 5) {
return res.status(400).json({ error: 'Daily limit exceeded. You can only create 5 URLs per day.' });
}
let shortUrl;
if (customShortUrl) {
// Check if custom short URL already exists
if (urlDatabase.hasOwnProperty(customShortUrl)) {
return res.status(400).json({ error: 'Custom short URL already in use' });
}
shortUrl = customShortUrl;
} else {
// Generate a new 5-letter short URL using base62 encoding
shortUrl = generateShortUrl();
}
const urlData = {
originalUrl,
createdAt: new Date(),
usageCount: 0,
createdBy: userIp, // Track the user who created the URL
};
urlDatabase[shortUrl] = urlData;
userTracking[userIp].push(shortUrl); // Track URL creation for the user
// Emit a 'urlCreated' event with the new URL data
io.emit('urlCreated', urlData);
res.json({
originalUrl,
shortenedUrl: `http://localhost:3000/${shortUrl}`,
customShortUrl: customShortUrl || 'None',
});
});
// Resolve Short URL
app.get('/:shortUrl', async (req, res) => {
const { shortUrl } = req.params;
// Check if shortUrl exists in your database
if (urlDatabase.hasOwnProperty(shortUrl)) {
const { originalUrl } = urlDatabase[shortUrl];
urlDatabase[shortUrl].usageCount++; // Update usage count
return res.redirect(originalUrl); // Redirect to the original URL
}
// If shortUrl is not found, return a "Not Found" error
return res.status(404).send(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 Error - Page Not Found</title>
<!-- Include Bootstrap CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS for your 404 error page -->
<style>
body {
background-color: #f8f9fa;
}
.error-container {
text-align: center;
padding: 100px 0;
}
.error-heading {
font-size: 72px;
color: #343a40;
}
.error-message {
font-size: 24px;
color: #6c757d;
}
.back-button {
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container">
<div class="error-container">
<h1 class="error-heading">404</h1>
<p class="error-message">Oops! The url you're looking for could not be found.</p>
<a href="/" class="btn btn-primary back-button">Go Back to Home</a>
</div>
</div>
<!-- Include Bootstrap JS (optional) -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>`);
});
// Route to handle QR code generation
app.get('/:shortUrl/qrcode', async (req, res) => {
const { shortUrl } = req.params;
if (shortUrl === 'None') {
// Handle the case where the custom short URL is 'None'
return res.status(404).se({ error: 'Short URL not found' });
}
if (urlDatabase.hasOwnProperty(shortUrl)) {
const shortenedUrl = `http://localhost:3000/${shortUrl}`;
// Generate QR code for the shortened URL
try {
const qrCodeData = await qrcode.toDataURL(shortenedUrl);
res.type('png'); // Set the response content type to PNG image
res.send(Buffer.from(qrCodeData.split(',')[1], 'base64')); // Send the QR code image data
} catch (error) {
console.error('QR code generation error:', error);
res.status(500).json({ error: 'Internal server error' });
}
} else {
res.status(404).send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Short URL Not Found</title>
<!-- Include Bootstrap CSS or any other styling you prefer -->
<style>
body {
background-color: #f8f9fa;
font-family: Arial, sans-serif;
text-align: center;
}
.error-container {
padding: 100px 0;
}
.error-heading {
font-size: 72px;
color: #343a40;
margin-bottom: 20px;
}
.error-message {
font-size: 24px;
color: #6c757d;
margin-bottom: 40px;
}
/* Additional CSS for custom styling */
.container {
max-width: 600px;
margin: 0 auto;
}
.btn-primary {
background-color: #007bff;
border-color: #007bff;
}
.btn-primary:hover {
background-color: #0056b3;
border-color: #0056b3;
}
</style>
</head>
<body>
<div class="container">
<div class="error-container">
<h1 class="error-heading">Short URL Not Found</h1>
<p class="error-message">Sorry, there is no QR code available for this short URL.</p>
<a href="/" class="btn btn-primary">Go Back to Home</a>
</div>
</div>
</body>
</html>
`);
}
});
// Get URLs created by the user
app.get('/api/urls/user/:userIp', (req, res) => {
const { userIp } = req.params;
const userUrls = Object.keys(urlDatabase)
.filter(shortUrl => urlDatabase[shortUrl].createdBy === userIp)
.map(shortUrl => ({
shortUrl,
originalUrl: urlDatabase[shortUrl].originalUrl,
usageCount: urlDatabase[shortUrl].usageCount,
}));
res.json(userUrls);
});
setInterval(() => {
const analyticsData = {
totalUrls: Object.keys(urlDatabase).length,
usageCounts: Object.values(urlDatabase).map((url) => url.usageCount),
};
io.emit('realtimeData', analyticsData);
}, 5000); // Emit data every 5 seconds
app.get('/api/urls/user/:userIp', (req, res) => {
const { userIp } = req.params;
const userUrls = Object.keys(urlDatabase)
.filter(shortUrl => urlDatabase[shortUrl].createdBy === userIp)
.map(shortUrl => ({
shortUrl,
originalUrl: urlDatabase[shortUrl].originalUrl,
usageCount: urlDatabase[shortUrl].usageCount,
}));
res.json(userUrls);
});
app.use((req, res, next) => {
const userIp = req.ip;
req.userIp = userIp;
next();
});
// Socket.io event listeners can be added here
// Fetch and send the URL list data
app.get('/api/urllist-data', (req, res) => {
const urlData = Object.keys(urlDatabase).map((shortUrl) => {
const { originalUrl, createdAt } = urlDatabase[shortUrl];
return {
shortUrl, // Include the short URL in the response
originalUrl,
createdAt,
};
});
// Send the URL list data as JSON
res.json(urlData);
});