-
Notifications
You must be signed in to change notification settings - Fork 27
/
app.js
1170 lines (1025 loc) · 37.9 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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pg from 'pg';
const { Client } = pg;
import express from "express";
import bodyParser from "body-parser";
import isBot from "isbot";
import querystring from "querystring";
import dotenv from "dotenv";
import bolt from "@slack/bolt";
const { App, LogLevel } = bolt;
import responseTime from "response-time";
import metrics from './metrics.js';
import { LRUCache } from 'lru-cache';
import { writeFile } from 'fs/promises';
import { createReadStream } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
dotenv.config();
const cache_ttl_milliseconds = 60 * 1000 // 1 minute
const cache = new LRUCache({ max: parseInt(process.env.CACHE_SIZE), ttl:cache_ttl_milliseconds });
const SlackApp = new App({
token: process.env.SLACK_BOT_TOKEN,
appToken: process.env.SLACK_APP_TOKEN,
socketMode: true,
logLevel: LogLevel.DEBUG,
});
const connectionString = process.env.DATABASE_URL;
async function connectToDatabase() {
let attempt = 0;
const maxRetries = 5;
while (attempt < maxRetries) {
try {
const client = new Client({
connectionString,
ssl: {
rejectUnauthorized: false
}
});
await client.connect();
console.log("Connected to the database successfully");
return client;
} catch (error) {
console.error(`Database connection attempt ${attempt + 1} failed:`, error);
attempt++;
const delay = Math.pow(2, attempt) * 1000;
console.log(`Retrying in ${delay / 1000} seconds...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw new Error("Failed to connect to the database after multiple attempts.");
}
let client;
(async () => {
try {
client = await connectToDatabase();
} catch (error) {
console.error("Could not establish a database connection:", error);
process.exit(1);
}
})();
const app = express();
app.use(forceHttps);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log("Hack.club is up and running on port", port);
});
app.use(responseTime(function (req, res, time) {
const reqTrace = req.method + "-" + res.statusCode;
const timingStatKey = `http.response.${reqTrace}`;
const codeStatKey = `http.response.${reqTrace}`
metrics.timing(timingStatKey, time)
metrics.increment(codeStatKey, 1)
}))
SlackApp.command("/hack.af", async ({ command, ack, respond }) => {
await ack();
const args = command.text.split(' ');
const originalCommand = `${command.command} ${command.text}`;
const isStaff = await isStaffMember(command.user_id);
async function changeSlug(slug, newDestination) {
newDestination = newDestination.replace(/^[\*_`]+|[\*_`]+$/g, '');
let existingRes;
try {
existingRes = await client.query(
`SELECT * FROM "Links" WHERE slug = $1`,
[slug]
);
} catch (error) {
console.error("Database error during SELECT:", error);
throw new Error("Error checking for existing slug");
}
const isUpdate = existingRes && existingRes.rowCount > 0;
if (isUpdate) {
const lastDestination = decodeURIComponent(existingRes.rows[0].destination);
try {
await client.query(
`UPDATE "Links" SET destination = $1 WHERE slug = $2`,
[newDestination, slug]
);
// Invalidate the cache entry since we've updated the slug such that it reloads next request
cache.delete(slug);
await insertSlugHistory(slug, newDestination, 'Updated', '', command.user_id);
return {
text: `Updated! Now hack.club/${slug} is switched from ${decodeURIComponent(lastDestination)} to ${newDestination}.`,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `Updated! Now hack.club/${slug} is switched from ${decodeURIComponent(lastDestination)} to ${newDestination}.`,
},
},
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `Request made by <@${command.user_id}>`,
},
],
},
],
};
} catch (error) {
console.error("Database error during UPDATE:", error);
throw new Error("Error updating the slug");
}
} else {
try {
await client.query(
`INSERT INTO "Links" ("Record Id", slug, destination)
VALUES ($1, $2, $3)`,
[Math.random().toString(36).substring(2, 15), slug, newDestination]
);
await insertSlugHistory(slug, newDestination, 'Created', '', command.user_id);
return {
text: `Created! Now hack.club/${slug} goes to ${newDestination}.`,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `Created! Now hack.club/${slug} goes to ${newDestination}.`,
},
},
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `Request made by <@${command.user_id}>`,
},
],
},
],
};
} catch (error) {
console.error("Database error during INSERT:", error);
throw new Error("Error creating the slug");
}
}
}
async function searchSlug(searchTerm) {
if (!searchTerm) {
return {
text: 'No slug provided. Please provide a slug to search for.',
response_type: 'ephemeral'
};
}
const isURL = searchTerm.startsWith('http://') || searchTerm.startsWith('https://');
let searchQuery = "";
let queryParams = [];
const similarityThreshold = 0.3;
if (isURL) {
searchQuery = `
SELECT * FROM "Links"
WHERE destination ILIKE $1
AND similarity(destination, $2) > $3
ORDER BY similarity(destination, $2) DESC
LIMIT 50;
`;
queryParams = [`%${encodeURIComponent(searchTerm)}%`, encodeURIComponent(searchTerm), similarityThreshold];
} else {
searchQuery = `
SELECT * FROM "Links"
WHERE (slug ILIKE $1 OR destination ILIKE $1)
AND (similarity(slug, $2) > $3 OR similarity(destination, $2) > $3)
ORDER BY GREATEST(similarity(slug, $2), similarity(destination, $2)) DESC
LIMIT 50;
`;
queryParams = [`%${searchTerm}%`, searchTerm, similarityThreshold];
}
try {
let res = await client.query(searchQuery, queryParams);
let records = res.rows;
if (records.length > 0) {
const blocks = records.map(record => {
return {
type: 'section',
fields: [
{
type: 'mrkdwn',
text: `*Slug:* ${record.slug}`
},
{
type: 'mrkdwn',
text: `*Destination:* <${decodeURIComponent(record.destination)}|${decodeURIComponent(record.destination)}>`
}
]
};
});
blocks.push({
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `Request made by <@${command.user_id}>`
}
]
});
return {
blocks
};
} else {
if (isURL) searchTerm = decodeURIComponent(searchTerm);
return {
text: `No matches found for ${searchTerm}.`,
response_type: 'ephemeral'
};
}
} catch (error) {
console.error('SQL error:', error);
return {
text: 'No slug found or there was an error with the query.',
response_type: 'ephemeral'
};
}
}
async function shortenUrl(url) {
const originalUrl = encodeURIComponent(url);
let slug = Math.random().toString(36).substring(7);
const recordId = Math.random().toString(36).substring(2, 15);
const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?data=https://hack.club/${slug}`;
await client.query(`
INSERT INTO "Links" ("Record Id", slug, destination, "Log", "Clicks", "QR URL", "Visitor IPs", "Notes")
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
`, [recordId, slug, originalUrl, [], 0, qrUrl, [], '']);
let msg = `Your short URL: https://hack.club/${slug} -> ${url}`;
let blockMsg = `Your short URL: *<https://hack.club/${slug}|hack.club/${slug}>* -> ${url}`;
if (isStaff) {
msg += '\nTo change the destination URL, use `/hack.af set [slug] [new destination URL]`.';
blockMsg += '\nTo change the destination URL, use `/hack.af set [slug] [new destination URL]`.';
}
// Invalidate the cache entry that has been updated
cache.delete(slug)
return {
text: msg,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: blockMsg,
}
},
{
type: 'image',
title: {
type: 'plain_text',
text: 'QR Code'
},
image_url: qrUrl,
alt_text: 'QR Code for your URL'
},
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `Request made by <@${command.user_id}>`
}
]
}
]
};
}
async function deleteSlug(slug) {
cache.delete(slug)
await client.query(`
DELETE FROM "Links"
WHERE slug = $1
`, [slug]);
return {
text: `URL for slug ${slug} has been successfully deleted.`,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `URL for slug ${slug} has been successfully deleted.`
}
},
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `Request made by <@${command.user_id}>`
}
]
}
]
};
}
async function showHelp(commandName) {
return {
text: `Hack.af help`,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: commandName
? generateHelpText(commandName)
: Object.keys(commands).map((key) => generateHelpText(key)).join("\n\n")
}
},
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `Request made by <@${command.user_id}>`
}
]
}
]
}
}
function generateHelpText(commandName) {
const { usage, helpEntry, parameters, staffRequired } = commands[commandName];
let helpText = `\`${usage}\``;
if (staffRequired) {
helpText += `: (*Admin only*)`;
}
helpText += ` ${helpEntry}`;
if (parameters) {
helpText += `\n*Parameters*: ${parameters}`;
}
return helpText;
}
const commands = {
set: {
run: changeSlug,
arguments: [2],
staffRequired: true,
helpEntry: "Shorten a URL to a custom slug.",
usage: "/hack.af set [slug-name] [destination-url]",
parameters: "[slug-name]: The custom slug you want to use.\n[destination-url]: The URL you want to shorten."
},
search: {
run: searchSlug,
arguments: [1],
staffRequired: false,
helpEntry: "Search for a particular slug in the database.",
usage: "/hack.af search [slug-name]",
parameters: "[slug-name]: The slug you want to search for."
},
shorten: {
run: shortenUrl,
arguments: [1],
staffRequired: false,
helpEntry: "Shorten any URL to a random hack.club link.",
usage: "/hack.af shorten [url]",
parameters: "[url]: The URL you want to shorten."
},
'delete': {
run: deleteSlug,
arguments: [1],
staffRequired: true,
helpEntry: "Delete a slug from the database.",
usage: "/hack.af delete [slug-name]",
parameters: "[slug-name]: The slug you want to delete."
},
help: {
run: showHelp,
arguments: [0, 1],
staffRequired: false,
helpEntry: "Show help documentation.",
usage: "/hack.af help"
},
metrics: {
run: getMetrics,
arguments: [1],
staffRequired: true,
helpEntry: "Retrieve and display metrics for a specific slug.",
usage: "/hack.af metrics [slug-name]",
parameters: "[slug-name]: The slug you want to retrieve metrics for."
},
history: {
run: getHistory,
arguments: [1],
staffRequired: true,
helpEntry: "Retrieve history of slugs over time.",
usage: "/hack.af history [slug-name]",
parameters: "[slug-name]: The slug you want to retrieve history of."
},
note: {
run: updateNotes,
arguments: [-1],
staffRequired: true,
helpEntry: "Add or update notes to a slug.",
usage: "/hack.af note [slug-name] [note-content]",
parameters: "[slug-name]: The slug you want to add/update a note for.\n[note-content]: The content of the note."
},
audit: {
run: auditChanges,
arguments: [2],
staffRequired: true,
helpEntry: "List all changes to slugs within a given time period.",
usage: "/hack.af audit [YYYY-MM-DD] [YYYY-MM-DD]",
parameters: "[YYYY-MM-DD]: The start date for the audit search.\n[YYYY-MM-DD]: The end date for the audit search."
},
geolocation: {
run: getGeolocation,
arguments: [1],
staffRequired: true,
helpEntry: "Retrieve IP addresses for a specific slug.",
usage: "/hack.af geolocation [slug-name]",
parameters: "[slug-name]: The slug you want to retrieve IP addresses for."
}
}
const commandEntry = commands[args[0]] || commands.help
if (commandEntry.staffRequired && !isStaff)
return await respond({
text: `Sorry, only staff can use this command. \`${originalCommand}\``,
response_type: 'ephemeral'
});
const acceptsVariableArguments = commandEntry.arguments.includes(-1);
if (!acceptsVariableArguments && !commandEntry.arguments.includes(args.length - 1))
return await respond({
text: `The command accepts ${commandEntry.arguments.join(', ')} arguments, but you supplied ${args.length - 1}. Please check your formatting. \`${originalCommand}\``,
response_type: 'ephemeral'
});
try {
metrics.increment(`botcommands.${args[0]}.attempt`, 1);
let result;
console.log("Command entry:", commandEntry);
if (commandEntry.run === getGeolocation) {
result = await getGeolocation(command);
} else {
result = acceptsVariableArguments ?
await commandEntry.run(...args.slice(1)) :
await commandEntry.run(...args.slice(1, commandEntry.arguments[0] + 1));
result.blocks.push({
type: 'context',
elements: [{
type: 'mrkdwn',
text: `\`${originalCommand}\``
}]
});
}
await respondEphemeral(respond, result);
metrics.increment(`botcommands.${args[0]}.success`, 1);
} catch (error) {
metrics.increment(`botcommands.${args[0]}.error`, 1);
await respond({
text: `There was an error processing your request: ${error.message}. \`${originalCommand}\``,
response_type: 'ephemeral'
});
console.error(error);
}
})
app.get("/ping", (_req, res) => {
res.send("pong");
});
app.get("/vip/:id", (req, res) => {
lookup("vip").then(
(result) => {
res.redirect(302, result + req.params.id);
},
(error) => {
res.status(error);
}
);
});
app.get("/glitch", (req, res) => {
res.set('Content-Type', 'text/html');
res.send(Buffer.from(`<meta http-equiv="refresh" content="0; url='https://glitch.com/edit/#!/remix/intro-workshop-starter/84e5e504-d255-4505-b104-fa2955ef8311'" />`));
});
app.get("/gib/:org", (req, res) => {
res.redirect(302, "https://hcb.hackclub.com/donations/start/" + req.params.org);
});
app.get("/gh/:repo", (req, res) => {
res.redirect(302, "https://github.com/hackclub/" + req.params.repo);
});
app.get("/*", (req, res) => {
let slug = decodeURIComponent(req.path.substring(1));
const query = req.query;
if (slug.endsWith("/")) {
slug = slug.substring(0, slug.length - 1);
}
if (slug === "") slug = "/";
logAccess(
getClientIp(req),
req.headers["user-agent"],
slug,
req.protocol + "://" + req.get("host") + req.originalUrl
);
lookup(decodeURI(slug)).then(
(destination) => {
var fullUrl = decodeURIComponent(destination.destination);
if (!/^https?:\/\//i.test(fullUrl)) {
fullUrl = 'http://' + fullUrl;
}
var resultQuery = combineQueries(
querystring.parse(new URL(fullUrl).search),
query
);
const parsedDestination = new URL(fullUrl);
const finalURL = parsedDestination.origin + parsedDestination.pathname + resultQuery + parsedDestination.hash;
// console.log("Destination: ", destination);
// console.log("Full URL: ", fullUrl);
// console.log("Parsed Destination: ", parsedDestination.href);
// console.log("Result Query: ", resultQuery);
// console.log("Final URL: ", finalURL);
res.redirect(307, finalURL);
},
(_err) => {
res.redirect(302, "https://hackclub.com/404");
}
).catch((_err) => {
res.redirect(302, "https://goo.gl/" + slug);
});
});
function combineQueries(q1, q2) {
for (let key in q1) {
if (key[0] === "?") {
q1[key.substring(1)] = q1[key];
delete q1[key];
}
}
for (let key in q2) {
if (key[0] === "?") {
q2[key.substring(1)] = q2[key];
delete q2[key];
}
}
const combinedQuery = { ...q1, ...q2 };
let combinedQueryString = querystring.stringify(combinedQuery);
if (combinedQueryString) {
combinedQueryString = "?" + combinedQueryString;
}
return combinedQueryString;
}
const lookup = async (slug) => {
try {
if (cache.has(slug)) {
metrics.increment("lookup.cache.hit", 1);
//console.log(cache.get(slug));
return cache.get(slug);
} else {
metrics.increment("lookup.cache.miss", 1);
console.log("Cache miss");
const res = await client.query('SELECT * FROM "Links" WHERE slug=$1', [slug]);
if (res.rows.length > 0) {
const record = res.rows[0];
cache.set(slug, record);
return cache.get(slug);
} else {
console.log(`No match found for slug: ${slug}`);
throw new Error('Slug not found');
}
}
} catch (error) {
console.error(error);
throw error;
}
};
async function logAccess(ip, ua, slug, url) {
if (process.env.LOGGING === "off") return;
const botUA = ["apex/ping/v1.0"];
if (process.env.BOT_LOGGING === "off" && (isBot(ua) || botUA.includes(ua))) return;
let linkData;
try {
linkData = await lookup(slug);
if (linkData === null) {
console.log("Slug not found, skipping logging");
return;
}
} catch (e) {
console.log(e);
}
const recordId = Math.random().toString(36).substring(2, 15);
const timestamp = new Date().toISOString();
const descriptiveTimestamp = new Date();
const data = {
record_id: recordId,
timestamp: timestamp,
descriptive_timestamp: descriptiveTimestamp,
client_ip: ip,
slug: slug,
url: url,
user_agent: ua,
bot: isBot(ua) || botUA.includes(ua),
counter: 1
};
client.query(
`INSERT INTO "Log" ("Record Id", "Timestamp", "Descriptive Timestamp", "Client IP", "Slug", "URL", "User Agent", "Counter") VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
[data.record_id, data.timestamp, data.descriptive_timestamp, data.client_ip, data.slug, data.url, data.user_agent, data.counter],
(err, _res) => {
if (err) {
console.error('Error inserting log:', err);
} else {
client.query(
`UPDATE "Links" SET "Clicks" = "Clicks" + 1, "Log" = array_append("Log", $1), "Visitor IPs" = array_append("Visitor IPs", $2) WHERE "slug" = $3`,
[data.record_id, data.client_ip, data.slug],
(updateErr, updateRes) => {
if (updateErr) {
console.error('Error updating Links:', updateErr);
}
}
);
}
}
);
}
async function getMetrics(slug) {
try {
console.log(`Getting metrics for slug: ${slug}`);
const logRes = await client.query('SELECT * FROM "Log" WHERE "Slug"=$1', [slug]);
console.log('Log Query result:', logRes);
const linkRes = await client.query('SELECT "Clicks" FROM "Links" WHERE "slug"=$1', [slug]);
console.log('Link Query result:', linkRes);
if (logRes.rows.length > 0 || (linkRes.rows.length > 0 && linkRes.rows[0].Clicks > 0)) {
const logData = logRes.rows.length > 0 ? logRes.rows[0] : null;
const clicks = linkRes.rows.length > 0 ? linkRes.rows[0].Clicks : 0;
console.log('Raw log data:', logData);
console.log('Clicks:', clicks);
const formattedLogData = formatLogData(logData, clicks);
return {
text: `Metrics for slug ${slug}:`,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: formattedLogData
}
}
]
};
} else {
return {
text: `No metrics found for slug ${slug}.`,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `No metrics found for slug ${slug}.`
}
}
]
};
}
} catch (error) {
console.error('Error in getMetrics:', error);
return {
text: 'There was an error retrieving metrics.',
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: 'There was an error retrieving metrics.'
}
}
]
};
}
}
async function getHistory(slug) {
const history = await getSlugHistory(slug);
const note = await getNotes(slug)
return formatHistory(history, note);
}
async function updateNotes(...args) {
console.log(args);
const slug = args[0];
const Note = args.slice(1).join(' ');
try {
const res = await client.query(`
UPDATE "Links" SET "Notes" = $1 WHERE "slug" = $2 RETURNING *
`, [Note, slug]);
if (res.rowCount > 0) {
console.log("Note updated successfully");
return {
text: `Note updated successfully \n New Note for ${slug} is ${Note}`,
response_type: 'ephemeral'
}
} else {
console.log("Slug not found");
return {
text: `Slug not found`,
response_type: 'ephemeral'
}
}
} catch (error) {
console.error("Database error:", error);
return {
text: `An error occurred while updating the note`,
response_type: 'ephemeral'
}
}
}
async function getNotes(slug) {
try {
const res = await client.query(`
SELECT "Notes" FROM "Links" WHERE slug = $1 LIMIT 1
`, [slug]);
if (res.rows.length > 0) {
return res.rows[0]["Notes"];
} else {
console.log(`No notes found for slug=${slug}`);
return '';
}
} catch (error) {
console.error("Database error in getNotes:", error);
throw error;
}
}
async function respondEphemeral(response, message) {
return await response({
...message,
response_type: 'ephemeral'
});
}
async function insertSlugHistory(slug, newDestination, actionType, note, changedBy) {
console.log("Inside insertSlugHistory with values:", slug, newDestination, actionType, note, changedBy);
try {
const result = await client.query(`
SELECT MAX(version) as latest_version FROM "slughistory" WHERE slug = $1;
`, [slug]);
const latestVersion = result.rows[0].latest_version || 0;
const nextVersion = latestVersion + 1;
await client.query(`
INSERT INTO "slughistory" (slug, new_url, action_type, note, version, changed_by, changed_at)
VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP);
`, [slug, newDestination, actionType, note, nextVersion, changedBy]);
} catch (error) {
console.error("Database error in insertSlugHistory:", error);
}
}
async function getSlugHistory(slug) {
console.log("Fetching slug history for slug:", slug);
try {
let res = await client.query(`
SELECT * FROM "slughistory" WHERE slug = $1 ORDER BY version DESC;
`, [slug]);
console.log("Query result rows:", res.rows);
if (res.rows.length === 0) {
console.log("No records found for slug in 'slughistory':", slug, ". Fetching from 'Log'...");
let logResult = await client.query(`
SELECT * FROM "Log" WHERE "Slug" = $1 LIMIT 1;
`, [slug]);
if (logResult.rows.length === 0) {
logResult = await client.query(`
SELECT * FROM "Log" WHERE "Slug" = $1 LIMIT 1;
`, [`{${slug}}`]);
}
if (logResult.rows.length > 0) {
const logData = logResult.rows[0];
const cleanSlug = logData["Slug"].replace(/[{}]/g, '');
const newDestination = logData["URL"];
const date = logData["Descriptive Timestamp"]
console.log(`Found slug=${slug} in "Log". Inserting into "slughistory"...`);
await client.query(`
INSERT INTO "slughistory" (slug, new_url, action_type, note, version, changed_by, changed_at)
VALUES ($1, $2, $3, $4, $5, $6, $7);
`, [cleanSlug, newDestination, 'Created', '', 1, '', date]);
res = await client.query(`
SELECT * FROM "slughistory" WHERE slug = $1 ORDER BY version DESC;
`, [slug]);
} else {
console.log("No records found for slug in 'Log':", slug);
return {
text: `No records found for slug in 'Log': ${slug}`,
response_type: 'ephemeral'
}
}
}
return res.rows;
} catch (error) {
console.error("SQL Error: ", error);
return {
text: 'No slug found or Error fetching slug history.',
response_type: 'ephemeral'
}
}
}
function formatHistory(history, note) {
console.log("history: " + history);
const blocks = history.map(record => {
return {
type: 'section',
fields: [
{
type: 'mrkdwn',
text: `*Version:* ${record.version}`
},
{
type: 'mrkdwn',
text: `*New URL:* ${decodeURIComponent(record.new_url)}`
},
{
type: 'mrkdwn',
text: `*Changed By:* ${record.changed_by}`
},
{
type: 'mrkdwn',
text: `*Changed At:* ${new Date(record.changed_at).toLocaleString()}`
},
{
type: 'mrkdwn',
text: `*Action Type:* ${record.action_type}`
},
{
type: 'mrkdwn',
text: `*Note:* ${note}`
}
]
};
});
return {
blocks
};
}
function formatLogData(logData, clicks) {
return `
*Timestamp:* ${logData?.["Timestamp"] || 'N/A'}
*Slug:* ${logData?.["Slug"] || 'N/A'}
*URL:* ${logData?.["URL"] || 'N/A'}
*Clicks:* ${clicks || 'N/A'}
`;
}
async function auditChanges(date1, date2, limit = 50) {
if (!date1 || !date2) {
console.error(`recordChanges: One or both dates are undefined - date1: ${date1}, date2: ${date2}`);
return {
text: 'There was an error with the dates. Please use the format YYYY-MM-DD for both dates.',
response_type: 'ephemeral'
};
}
const startDate = new Date(date1).toISOString();
const endDate = new Date(date2);
endDate.setUTCHours(23, 59, 59, 999);
const endDateString = endDate.toISOString();
try {
const res = await client.query(`
SELECT * FROM "slughistory"
WHERE changed_at >= $1 AND changed_at <= $2
ORDER BY changed_at DESC
LIMIT $3;
`, [startDate, endDateString, limit]);
if (res.rows.length > 0) {
const blocks = res.rows.map(record => {
const slugText = /^https?:\/\//.test(record.slug)
? record.slug
: `hack.club/${record.slug}`;