-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
151 lines (124 loc) · 4.85 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
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const app = express();
const path = require('path');
const connection = require('./sql-config.js');
const env = require('dotenv').config();
const corsOptions = {
origin: '*', // Allow all origins. Change this to specific origins if needed for security.
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Allowed HTTP methods
allowedHeaders: ['Content-Type', 'Authorization'], // Allowed headers
};
app.use(cors(corsOptions));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
async function qrgererator(shortlink) {
const data = {
workspace: '132e744b-fb1c-4d27-bc70-4924c70aca4f',
qr_data: `${shortlink}`,
primary_color: '#ffffff',
pattern: 'Circles',
eye_style: 'Rounded',
generate_png: true,
frame: 'polkadot'
};
try {
const response = await axios.post('https://hovercode.com/api/v2/hovercode/create/', data, {
headers: { Authorization: `Token ${process.env.API_KEY}` },
timeout: 10000
});
return response.data.png;
} catch (error) {
console.error("QR not generated", error.message);
return null;
}
}
app.get('/', async (req, res) => {
let { link, url } = req.query;
let qrurl = "";
if (link) qrurl = await qrgererator(link);
res.render('index.ejs', { link: link || '', url: url || '', qrurl: qrurl });
});
const randomString = "1234567890@^&_qwertyuiopasdfghjklzxcvbnm";
function generateshortlink(callback) {
let shortlink = '';
for (let i = 0; i < 3; i++) {
const randomIndex = Math.floor(Math.random() * randomString.length);
shortlink += randomString[randomIndex];
}
connection.query(`SELECT url FROM URLTABLE WHERE shortlink = $1`, [shortlink], function (err, results) {
if (results && results.rowCount > 0) {
// If a collision is detected, try again
generateshortlink(callback);
} else {
callback(shortlink);
}
});
}
// New endpoint for shortening URL and generating QR
app.post('/api/shorten', async (req, res) => {
const { url } = req.body;
if (!url || url.trim() === '') {
return res.status(400).json({ error: 'Invalid URL' });
}
// Check if the URL already exists
connection.query(`SELECT shortlink FROM URLTABLE WHERE url = $1`, [url], async (err, results) => {
if (err) {
return res.status(500).json({ error: 'Database query failed' });
}
if (results.rowCount > 0) {
const shortlink = results.rows[0].shortlink;
const fullShortlink = `https://tinyu.vercel.app/${shortlink}`;
const qrurl = await qrgererator(url);
return res.json({ shortlink: fullShortlink, qrurl });
} else {
// Generate a new shortlink
generateshortlink(async (shortlink) => {
const insertQuery = `INSERT INTO URLTABLE (url, shortlink) VALUES ($1, $2)`;
const values = [url, shortlink];
connection.query(insertQuery, values, async (err) => {
if (err) {
return res.status(500).json({ error: 'Database query failed' });
}
const fullShortlink = `https://tinyu.vercel.app/${shortlink}`;
const qrurl = await qrgererator(url);
return res.json({ shortlink: fullShortlink, qrurl });
});
});
}
});
});
app.get('/:s', (req, res) => {
const shortlink = req.params.s;
connection.query(`SELECT url FROM URLTABLE WHERE shortlink = $1`, [shortlink], (err, results) => {
if (err || results.rowCount === 0) {
return res.sendStatus(404);
}
const url = results.rows[0].url;
res.redirect(url);
});
});
app.post('/customurl', (req, res) => {
const { link, url } = req.body;
connection.query(`SELECT url FROM URLTABLE WHERE shortlink = $1`, [link], (err, results) => {
if (results.rowCount > 0) {
return res.status(409).json({ error: 'Custom URL already exists' });
}
const insertQuery = `INSERT INTO URLTABLE (url, shortlink) VALUES ($1, $2)`;
const values = [url, link];
connection.query(insertQuery, values, (err) => {
if (err) {
return res.status(500).json({ error: 'Database query failed' });
}
const fullShortlink = `${req.headers.origin}/${link}`;
res.json({ shortlink: fullShortlink });
});
});
});
app.listen(process.env.PORT || 3000, () => {
console.log('Server is running...');
});