forked from David-Savio/ExploreNaija
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
976 lines (887 loc) · 30.2 KB
/
Copy pathserver.js
File metadata and controls
976 lines (887 loc) · 30.2 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
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
import express from "express";
import path from "path";
import fs from "fs";
import https from "https";
import http from "http";
import axios from "axios";
import { v4 as uuidv4 } from "uuid";
import dotenv from "dotenv";
import { createApi } from "unsplash-js";
import mongoose from "mongoose";
import urlModule from "url";
import { fileURLToPath } from "url";
import nodemailer from "nodemailer";
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Load environment variables from .env (check current dir, then parent dir)
dotenv.config();
if (!process.env.MONGO_URI) {
dotenv.config({ path: path.join(__dirname, "..", ".env") });
}
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// Serve static public files
app.use(express.static(path.join(__dirname, "Public")));
// Connect to MongoDB
const MONGO_URI =
process.env.MONGO_URI || "mongodb://localhost:27017/explorenaija";
// Define Mongoose Schemas & Models
const attractionSchema = new mongoose.Schema({
id: String,
name: String,
location: String,
description: String,
image: String,
rating: Number,
created: { type: Date, default: Date.now },
});
const Attraction = mongoose.model("Attraction", attractionSchema);
const contactSchema = new mongoose.Schema({
id: String,
name: String,
email: String,
subject: String,
message: String,
created: { type: Date, default: Date.now },
});
const Contact = mongoose.model("Contact", contactSchema);
const suggestionSchema = new mongoose.Schema({
id: String,
name: String,
email: String,
placeName: String,
location: String,
suggestion: String,
created: { type: Date, default: Date.now },
});
const Suggestion = mongoose.model("Suggestion", suggestionSchema);
const userSchema = new mongoose.Schema({
id: String,
name: String,
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
created: { type: Date, default: Date.now },
});
const User = mongoose.model("User", userSchema);
// Explicitly serve settings.html to ensure it is accessible
app.get("/settings.html", (req, res) => {
res.sendFile(path.join(__dirname, "Public", "settings.html"));
});
// Helper to create email transporter with sanitized credentials
const createTransporter = () => {
if (!process.env.EMAIL_USER || !process.env.EMAIL_PASS) return null;
return nodemailer.createTransport({
service: "gmail",
auth: {
user: process.env.EMAIL_USER,
// Fix: Remove spaces from App Password if copied directly from Google
pass: process.env.EMAIL_PASS.replace(/\s+/g, ""),
},
});
};
// API: GET /api/attractions
app.get("/api/attractions", async (req, res) => {
try {
const items = await Attraction.find().sort({ rating: -1 });
res.json(items);
} catch (err) {
res.status(500).json({ error: "Failed to fetch attractions" });
}
});
// API: GET /api/images?place=<place_name>
// Returns an array of image URLs from Wikimedia Commons for a given place
app.get("/api/images", async (req, res) => {
const place = req.query.place || "";
// Validate input
if (!place || place.trim().length === 0) {
return res.status(400).json({
error: "Missing required query parameter",
message:
'Please provide a "place" query parameter (e.g., /api/images?place=Olumo%20Rock)',
example: "/api/images?place=Olumo+Rock+Nigeria",
});
}
try {
console.log(`Searching Wikimedia Commons for: "${place}"`);
// Query Wikimedia Commons API
const response = await axios.get(
"https://commons.wikimedia.org/w/api.php",
{
headers: { "User-Agent": "ExploreNaija/1.0 (Educational Project)" },
params: {
action: "query",
generator: "search",
gsrnamespace: 6, // Namespace 6 is for Files/Images
gsrsearch: place,
gsrlimit: 10,
prop: "imageinfo",
iiprop: "url|extmetadata",
iiurlwidth: 600, // Request 600px thumbnails
format: "json",
origin: "*",
},
},
);
const pages = response.data.query ? response.data.query.pages : {};
const photos = Object.values(pages);
if (photos.length === 0) {
return res.json({
place: place,
count: 0,
images: [],
message: `No images found for "${place}"`,
});
}
// Map photos to image URLs with metadata
const images = photos
.map((photo) => {
const info = photo.imageinfo ? photo.imageinfo[0] : null;
if (!info) return null;
const meta = info.extmetadata || {};
// Strip HTML from artist field if present
const artist = meta.Artist
? meta.Artist.value.replace(/<[^>]*>?/gm, "")
: "Unknown";
return {
url: info.url, // Return full-size original URL
thumb: info.thumburl || info.url,
alt: photo.title.replace("File:", "").replace(/\.[^/.]+$/, ""), // Remove extension
photographer: artist,
photographerUrl: info.descriptionurl,
sourceUrl: info.descriptionurl,
};
})
.filter((img) => img !== null);
return res.json({
place: place,
count: images.length,
images: images,
message: `Found ${images.length} image(s) for "${place}"`,
});
} catch (err) {
console.error("Error fetching images from Wikimedia:", err.message);
return res.status(500).json({
error: "Internal server error",
message:
"An error occurred while searching for images. Please try again later.",
details: err.message,
});
}
});
// API: POST /api/contact
app.post("/api/contact", async (req, res) => {
const { name, email, subject, message } = req.body || {};
if (!email || !message)
return res.status(400).json({ message: "Missing required fields" });
try {
await Contact.create({
id: uuidv4(),
name: name || "",
email,
subject: subject || "",
message,
created: new Date().toISOString(),
});
// Send email notification
const transporter = createTransporter();
if (transporter) {
await transporter.sendMail({
from: `"ExploreNaija Form" <${process.env.EMAIL_USER}>`,
to: process.env.ADMIN_EMAIL || process.env.EMAIL_USER, // Send to yourself
replyTo: email, // Allows you to reply directly to the sender
subject: `New Message from ${name}: ${subject || "No Subject"}`,
text: `You have received a new message.\n\nName: ${name}\nEmail: ${email}\n\nMessage:\n${message}`,
});
} else {
console.warn(
"Email not sent: EMAIL_USER or EMAIL_PASS is missing in .env",
);
}
res.json({ message: "Thank you — your message was received." });
} catch (err) {
console.error("Contact form error:", err);
res.status(500).json({ message: "Failed to save contact" });
}
});
// API: POST /api/suggestions
app.post("/api/suggestions", async (req, res) => {
const { name, email, placeName, location, suggestion } = req.body || {};
if (!placeName || !location || !suggestion)
return res.status(400).json({ message: "Missing required fields" });
try {
await Suggestion.create({
id: uuidv4(),
name: name || "",
email: email || "",
placeName,
location,
suggestion,
created: new Date().toISOString(),
});
// Send email notification
const transporter = createTransporter();
if (transporter) {
await transporter.sendMail({
from: `"ExploreNaija Suggestions" <${process.env.EMAIL_USER}>`,
to: process.env.ADMIN_EMAIL || process.env.EMAIL_USER,
replyTo: email || process.env.EMAIL_USER,
subject: `New Place Suggestion: ${placeName}`,
text: `New suggestion received.\n\nPlace: ${placeName}\nLocation: ${location}\nSubmitted by: ${name || "Anonymous"} (${email || "No email"})\n\nDetails:\n${suggestion}`,
});
} else {
console.warn(
"Email not sent: EMAIL_USER or EMAIL_PASS is missing in .env",
);
}
res.json({ message: "Thanks — suggestion received. We will review it." });
} catch (err) {
res.status(500).json({ message: "Failed to save suggestion" });
}
});
// API: POST /api/newsletter
app.post("/api/newsletter", async (req, res) => {
const { email } = req.body || {};
if (!email) return res.status(400).json({ message: "Email is required" });
// Basic email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return res.status(400).json({ message: "Invalid email address" });
}
try {
// Send email notification
const transporter = createTransporter();
if (transporter) {
await transporter.sendMail({
from: `"ExploreNaija" <${process.env.EMAIL_USER}>`,
to: email,
subject: "Welcome to ExploreNaija! 🌍",
text: `Hi there,\n\nThank you for subscribing to the ExploreNaija newsletter! You're now on the list to receive our monthly travel guides, hidden gems, and exclusive tips for exploring Nigeria.\n\nHappy exploring,\nThe ExploreNaija Team`,
html: `
<div style="font-family: sans-serif; color: #333; max-width: 600px; margin: 0 auto;">
<h2 style="color: #0e7728;">Welcome to ExploreNaija! 🌍</h2>
<p>Hi there,</p>
<p>Thank you for subscribing to our newsletter! You're now on the list to receive:</p>
<ul>
<li>Monthly travel guides</li>
<li>Hidden gems across Nigeria</li>
<li>Exclusive travel tips</li>
</ul>
<p>We can't wait to help you discover your next adventure.</p>
<hr style="border: 0; border-top: 1px solid #eee; margin: 20px 0;">
<p style="font-size: 0.9em; color: #666;">Happy exploring,<br><strong>The ExploreNaija Team</strong></p>
</div>
`,
});
} else {
console.warn(
"Email not sent: EMAIL_USER or EMAIL_PASS is missing in .env",
);
}
res.json({ message: "Subscription successful! Please check your inbox." });
} catch (err) {
console.error("Newsletter subscription error:", err);
res.status(500).json({ message: "Failed to subscribe. Please try again later." });
}
});
// API: POST /api/auth/register
app.post("/api/auth/register", async (req, res) => {
const { name, email, password } = req.body || {};
if (!name || !email || !password) {
return res.status(400).json({ message: "All fields are required" });
}
try {
const existing = await User.findOne({ email });
if (existing) {
return res.status(400).json({ message: "Email already registered" });
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await User.create({
id: uuidv4(),
name,
email,
password: hashedPassword,
});
res.json({ message: "Registration successful. Please login." });
} catch (err) {
res.status(500).json({ message: "Registration failed" });
}
});
// API: POST /api/auth/login
app.post("/api/auth/login", async (req, res) => {
const { email, password } = req.body || {};
try {
const user = await User.findOne({ email });
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ message: "Invalid email or password" });
}
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET || "secret", {
expiresIn: "1d",
});
res.json({ token, user: { name: user.name, email: user.email } });
} catch (err) {
res.status(500).json({ message: "Login failed" });
}
});
// Middleware to verify JWT
const authenticateToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (!token) return res.sendStatus(401);
jwt.verify(token, process.env.JWT_SECRET || "secret", (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
// API: PUT /api/auth/profile (Change Username)
app.put("/api/auth/profile", authenticateToken, async (req, res) => {
const { name } = req.body;
if (!name) return res.status(400).json({ message: "Name is required" });
try {
const user = await User.findOne({ id: req.user.id });
if (!user) return res.status(404).json({ message: "User not found" });
user.name = name;
await user.save();
res.json({ message: "Profile updated successfully", user: { name: user.name, email: user.email } });
} catch (err) {
res.status(500).json({ message: "Failed to update profile" });
}
});
// API: PUT /api/auth/password (Change Password)
app.put("/api/auth/password", authenticateToken, async (req, res) => {
const { currentPassword, newPassword } = req.body;
if (!currentPassword || !newPassword) {
return res.status(400).json({ message: "All fields are required" });
}
try {
const user = await User.findOne({ id: req.user.id });
if (!user) return res.status(404).json({ message: "User not found" });
const isMatch = await bcrypt.compare(currentPassword, user.password);
if (!isMatch) return res.status(400).json({ message: "Incorrect current password" });
user.password = await bcrypt.hash(newPassword, 10);
await user.save();
// Send email notification
const transporter = createTransporter();
if (transporter) {
try {
await transporter.sendMail({
from: `"ExploreNaija Security" <${process.env.EMAIL_USER}>`,
to: user.email,
subject: "Security Alert: Password Changed",
text: `Hello ${user.name},\n\nYour password for ExploreNaija was recently changed. If this was you, you can ignore this email. If you did not make this change, please contact support immediately.\n\nBest regards,\nExploreNaija Team`,
});
} catch (emailErr) {
console.error("Failed to send password change email:", emailErr);
}
}
res.json({ message: "Password updated successfully" });
} catch (err) {
console.error("Password update error:", err);
res.status(500).json({ message: "Failed to update password" });
}
});
// API: DELETE /api/auth/account (Delete Account)
app.delete("/api/auth/account", authenticateToken, async (req, res) => {
try {
await User.deleteOne({ id: req.user.id });
res.json({ message: "Account deleted successfully" });
} catch (err) {
res.status(500).json({ message: "Failed to delete account" });
}
});
// Seed database if empty
async function seedDatabase() {
try {
const existing = await Attraction.find({}, { name: 1 });
const existingNames = new Set(existing.map((e) => e.name));
const sample = [
{
id: uuidv4(),
name: "Olumo Rock",
location: "Abeokuta, Ogun",
description:
"Historic granite rock with panoramic views and stair climbs to lookout points.",
image: "/images/olumo.jpg",
rating: 4.6,
},
{
id: uuidv4(),
name: "Yankari Game Reserve",
location: "Bauchi",
description:
"Large wildlife reserve with hot springs and guided game drives.",
image: "/images/yankari.jpg",
rating: 4.5,
},
{
id: uuidv4(),
name: "Nike Art Gallery",
location: "Lagos",
description:
"Vibrant art gallery showcasing contemporary and traditional Nigerian art.",
image: "/images/nike-gallery.jpg",
rating: 4.3,
},
{
id: uuidv4(),
name: "Obudu Mountain Resort",
location: "Cross River",
description:
"Scenic mountain resort with cable car, temperate climate and panoramic views.",
image: "/images/obudu.jpg",
rating: 4.7,
},
{
id: uuidv4(),
name: "Zuma Rock",
location: "Gwagwalada, Abuja",
description:
'Iconic natural monolith often called the "Gateway to Abuja". Great for photos and short hikes.',
image: "/images/zuma.jpg",
rating: 4.7,
},
{
id: uuidv4(),
name: "Awhum Waterfall & Cave",
location: "Enugu",
description:
"Tall waterfall with a nearby cave; peaceful spot for nature walks and photography.",
image: "/images/awhum.jpg",
rating: 4.4,
},
{
id: uuidv4(),
name: "Erin-Ijesha (Olumirin) Waterfall",
location: "Osun",
description:
"Multi-tiered waterfall with crystal-clear pools and scenic hiking routes.",
image: "/images/erinijesha.jpg",
rating: 4.5,
},
{
id: uuidv4(),
name: "Tarkwa Bay Beach",
location: "Lagos",
description:
"Calm sheltered beach accessible by boat — popular for swimming and relaxation.",
image: "/images/tarkwa.jpg",
rating: 4.1,
},
{
id: uuidv4(),
name: "Ogbunike Caves",
location: "Anambra",
description:
"Ancient karst cave system with cultural significance and guided tours available.",
image: "/images/ogbunike.jpg",
rating: 4.3,
},
{
id: uuidv4(),
name: "Idanre Hills",
location: "Ondo",
description:
"Dramatic hills with ancient settlements, panoramic views and historic sites.",
image: "/images/idanre.jpg",
rating: 4.6,
},
{
id: uuidv4(),
name: "Lekki Conservation Centre",
location: "Lagos",
description:
"Famous for the longest canopy walk in Africa and diverse wildlife.",
image: "/images/lekki-cc.jpg",
rating: 4.5,
},
{
id: uuidv4(),
name: "Gurara Waterfalls",
location: "Niger",
description:
"A spectacular waterfall located in Gurara, a local government area of Niger State.",
image: "/images/gurara.jpg",
rating: 4.4,
},
{
id: uuidv4(),
name: "Kajuru Castle",
location: "Kaduna",
description:
"A luxury medieval-German style villa, built over 3 decades ago.",
image: "/images/kajuru.jpg",
rating: 4.6,
},
{
id: uuidv4(),
name: "Osun-Osogbo Sacred Grove",
location: "Osun",
description:
"A UNESCO World Heritage Site and dense forest of the Osun Sacred Grove.",
image: "/images/osun-osogbo.jpg",
rating: 4.7,
},
{
id: uuidv4(),
name: "Agodi Gardens",
location: "Ibadan, Oyo",
description:
"A serene park with a swimming pool, mini zoo, and picnic spots.",
image: "/images/agodi.jpg",
rating: 4.3,
},
{
id: uuidv4(),
name: "Millennium Park",
location: "Abuja",
description:
"The largest public park of Abuja and is in the Maitama district of the city.",
image: "/images/millennium-park.jpg",
rating: 4.4,
},
{
id: uuidv4(),
name: "Gashaka Gumti National Park",
location: "Taraba",
description:
"Nigeria's largest national park, offering diverse wildlife and rugged terrain.",
image: "/images/gashaka.jpg",
rating: 4.6,
},
{
id: uuidv4(),
name: "Kainji Lake National Park",
location: "Niger",
description:
"Includes part of the Kainji Lake and the Borgu Game Reserve.",
image: "/images/kainji.jpg",
rating: 4.2,
},
{
id: uuidv4(),
name: "Royal Palace Of The Oba Of Benin",
location: "Edo",
description:
"A UNESCO listed heritage site, central to the history of the Benin Kingdom.",
image: "/images/oba-palace.jpg",
rating: 4.7,
},
{
id: uuidv4(),
name: "Okomu National Park",
location: "Edo",
description:
"A rain forest sanctuary for the endangered white-throated monkey.",
image: "/images/okomu.jpg",
rating: 4.3,
},
{
id: uuidv4(),
name: "Isaac Boro Park",
location: "Port Harcourt, Rivers",
description:
"A public park dedicated to Major Isaac Boro, a Nigerian nationalist.",
image: "/images/isaac-boro.jpg",
rating: 4.1,
},
{
id: uuidv4(),
name: "National Museum of Unity",
location: "Enugu",
description:
"Established to foster unity, housing diverse cultural artifacts from across Nigeria.",
image: "/images/museum-unity.jpg",
rating: 4.2,
},
{
id: uuidv4(),
name: "Matsirga Waterfalls",
location: "Kaduna",
description:
"A spectacular waterfall that drops 30 meters into a gorge.",
image: "/images/matsirga.jpg",
rating: 4.4,
},
{
id: uuidv4(),
name: "Sukur Cultural Landscape",
location: "Adamawa",
description:
"A UNESCO World Heritage site featuring the Palace of the Hidi.",
image: "/images/sukur.jpg",
rating: 4.5,
},
{
id: uuidv4(),
name: "Surame Cultural Landscape",
location: "Sokoto",
description:
"An ancient city with massive stone walls and palace ruins.",
image: "/images/surame.jpg",
rating: 4.2,
},
{
id: uuidv4(),
name: "Ibeno Beach",
location: "Akwa Ibom",
description:
"The longest sand beach in West Africa, stretching for 45km.",
image: "/images/ibeno.jpg",
rating: 4.2,
},
{
id: uuidv4(),
name: "Mambilla Plateau",
location: "Taraba",
description:
"A high plateau with a cool climate, tea plantations, and scenic views.",
image: "/images/mambilla.jpg",
rating: 4.8,
},
];
// Filter out items that already exist
const newItems = sample.filter((item) => !existingNames.has(item.name));
if (newItems.length > 0) {
await Attraction.insertMany(newItems);
console.log(
`✓ Database seeded with ${newItems.length} new sample attractions`,
);
} else {
console.log("✓ Database already up to date");
}
// Force update ratings to ensure Zuma Rock appears on home page and Ibeno Beach in view more
await Attraction.updateOne(
{ name: "Zuma Rock" },
{ $set: { rating: 4.7 } },
);
await Attraction.updateOne(
{ name: "Ibeno Beach" },
{ $set: { rating: 4.2 } },
);
// Remove unwanted attractions entirely
await Attraction.deleteMany({
name: {
$in: [
"Ngwo Pine Forest",
"Nike Lake Resort",
"Mbari Cultural Centre",
"Tinapa Business Resort",
],
},
});
} catch (err) {
console.error("Error seeding database:", err);
}
}
// Fetch image URL from Wikimedia Commons API
async function fetchWikimediaImage(query) {
try {
const response = await axios.get(
"https://commons.wikimedia.org/w/api.php",
{
headers: { "User-Agent": "ExploreNaija/1.0 (Educational Project)" },
params: {
action: "query",
generator: "search",
gsrnamespace: 6,
gsrsearch: query,
gsrlimit: 1,
prop: "imageinfo",
iiprop: "url",
iiurlwidth: 1024, // Get a reasonable size (1024px)
format: "json",
origin: "*",
},
},
);
const pages = response.data.query ? response.data.query.pages : {};
const photos = Object.values(pages);
if (photos.length > 0 && photos[0].imageinfo && photos[0].imageinfo[0]) {
// Return the resized URL (thumburl) or original if not resized
return photos[0].imageinfo[0].thumburl || photos[0].imageinfo[0].url;
}
return null;
} catch (err) {
if (err.response && err.response.status === 429) {
throw err;
}
console.warn(`Wikimedia API search failed for "${query}":`, err.message);
return null;
}
}
// Download helper that follows redirects, supports http/https, and returns final path
function downloadImage(url, dest, attempt = 1) {
return new Promise((resolve, reject) => {
if (attempt > 5) return reject(new Error("Max redirects exceeded"));
let parsed;
try {
parsed = urlModule.parse(url);
} catch (err) {
return reject(err);
}
const client = parsed.protocol === "http:" ? http : https;
const req = client.get(
url,
{
timeout: 15000,
headers: { "User-Agent": "ExploreNaija/1.0 (Educational Project)" },
},
(res) => {
// Follow redirects
if (
res.statusCode >= 300 &&
res.statusCode < 400 &&
res.headers.location
) {
const nextUrl = res.headers.location.startsWith("http")
? res.headers.location
: urlModule.resolve(url, res.headers.location);
return downloadImage(nextUrl, dest, attempt + 1)
.then(resolve)
.catch(reject);
}
if (res.statusCode !== 200) {
return reject(new Error(`Status ${res.statusCode}`));
}
// Ensure images directory exists
const dir = path.dirname(dest);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
// Determine extension from content-type
const ct = (res.headers["content-type"] || "").toLowerCase();
let ext = path.extname(dest).toLowerCase();
if (!ext) {
if (ct.includes("svg")) ext = ".svg";
else if (ct.includes("png")) ext = ".png";
else if (ct.includes("jpeg") || ct.includes("jpg")) ext = ".jpg";
else if (ct.includes("gif")) ext = ".gif";
else ext = "";
}
let finalDest = dest;
if (ext && path.extname(dest).toLowerCase() !== ext) {
finalDest = path.join(
dir,
path.basename(dest, path.extname(dest)) + ext,
);
}
const file = fs.createWriteStream(finalDest);
res.pipe(file);
file.on("finish", () => {
file.close(() => resolve(finalDest));
});
file.on("error", (err) => {
try {
fs.unlinkSync(finalDest);
} catch (e) {}
reject(err);
});
},
);
req.on("error", reject);
req.on("timeout", function () {
req.destroy();
reject(new Error("Download timeout"));
});
});
}
// Ensure attraction images exist locally; if missing, fetch from Wikimedia
async function ensureAttractionImages() {
try {
const items = await Attraction.find();
const imagesDir = path.join(__dirname, "Public", "images");
if (!fs.existsSync(imagesDir)) fs.mkdirSync(imagesDir, { recursive: true });
for (let idx = 0; idx < items.length; idx++) {
const item = items[idx];
if (!item.image) continue;
const rel = item.image.startsWith("/") ? item.image.slice(1) : item.image;
const localPath = path.join(__dirname, rel);
if (fs.existsSync(localPath)) continue; // already present
const filename = path.basename(rel) || item.id + ".jpg";
const dest = path.join(imagesDir, filename);
console.log(
`[${idx + 1}/${items.length}] Fetching image for ${item.name}...`,
);
const queryRaw = `${item.name} Nigeria`;
let attempts = 0;
let success = false;
while (!success && attempts < 3) {
try {
if (attempts > 0) console.log(` → Retry attempt ${attempts + 1}...`);
console.log(` → Querying Wikimedia for "${queryRaw}"...`);
const imageUrl = await fetchWikimediaImage(queryRaw);
if (imageUrl) {
const finalPath = await downloadImage(imageUrl, dest);
const finalName = path.basename(finalPath);
console.log(` ✓ Downloaded from Wikimedia: ${finalName}`);
item.image = `/images/${finalName}`;
await item.save();
success = true;
} else {
console.log(` → No image found on Wikimedia for "${queryRaw}"`);
success = true; // Stop retrying if not found
}
} catch (err) {
const isRateLimit =
(err.response && err.response.status === 429) ||
(err.message && err.message.includes("429"));
if (isRateLimit) {
attempts++;
const wait = attempts * 5000;
console.warn(` ⚠ Rate limited (429). Waiting ${wait / 1000}s...`);
await new Promise((resolve) => setTimeout(resolve, wait));
} else {
console.warn(
` ✗ Error: ${err && err.message ? err.message : err}`,
);
break; // Don't retry other errors
}
}
}
// Add a delay to respect API rate limits
await new Promise((resolve) => setTimeout(resolve, 3000));
}
console.log("\n✓ Image setup complete. Ready to serve attractions.\n");
} catch (err) {
console.error("ensureAttractionImages error", err);
}
}
// Start server with retry on EADDRINUSE, then run image setup in background
function startServer(port, attempts = 0) {
const server = app.listen(port, () =>
console.log(`ExploreNaija server running on http://localhost:${port}`),
);
server.on("error", (err) => {
if (err && err.code === "EADDRINUSE" && attempts < 5) {
const next = port + 1;
console.warn(`Port ${port} in use — trying ${next}...`);
setTimeout(() => startServer(next, attempts + 1), 300);
} else {
console.error("Failed to start server:", err);
process.exit(1);
}
});
}
async function startApp() {
try {
console.log("Connecting to MongoDB...");
await mongoose.connect(MONGO_URI);
console.log("✓ MongoDB connected");
// Check email config
if (process.env.EMAIL_USER && process.env.EMAIL_PASS) {
console.log("✓ Email configuration detected");
} else {
console.warn("⚠ Email configuration missing (EMAIL_USER or EMAIL_PASS)");
}
startServer(PORT);
await seedDatabase();
await ensureAttractionImages();
console.log("Image setup finished");
} catch (err) {
console.error("✗ MongoDB connection error:", err.message);
console.log("Retrying connection in 5 seconds...");
setTimeout(startApp, 5000);
}
}
startApp();