-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1111 lines (934 loc) · 38.2 KB
/
index.js
File metadata and controls
1111 lines (934 loc) · 38.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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const db = require('./db');
const dotenv = require('dotenv');
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
const JWT_SECRET = process.env.JWT_SECRET || 'your_jwt_secret_key_change_this';
app.use(cors());
app.use(express.json());
// Initialize axios and cache for CoinGecko API calls
const axios = require('axios');
const NodeCache = require('node-cache');
const myCache = new NodeCache({ stdTTL: 300 }); // Cache for 5 minutes
let apiHitsToday = 0;
// Unique visitor tracking (Set of IPs, resets daily at midnight EST)
let visitorsToday = new Set();
// Timezone handling for EST midnight reset
const moment = require('moment-timezone');
// Helper function to get today's date in EST timezone (YYYY-MM-DD format)
const getTodayDateEST = () => {
return moment().tz('America/New_York').format('YYYY-MM-DD');
};
// Helper function to get next midnight EST as a Date object
const getNextMidnightEST = () => {
const now = moment().tz('America/New_York');
const nextMidnight = now.clone().add(1, 'day').startOf('day');
return nextMidnight.toDate();
};
// Helper function to get milliseconds until next midnight EST
const getMsUntilMidnightEST = () => {
const now = moment().tz('America/New_York');
const nextMidnight = now.clone().add(1, 'day').startOf('day');
return nextMidnight.diff(now);
};
// Schedule a reset of daily counters at the next midnight EST, then every 24h after that
const scheduleMidnightReset = () => {
const msUntilMidnight = getMsUntilMidnightEST();
setTimeout(() => {
apiHitsToday = 0;
visitorsToday = new Set();
// Schedule again for the following midnight
setInterval(() => {
apiHitsToday = 0;
visitorsToday = new Set();
}, 24 * 60 * 60 * 1000);
}, msUntilMidnight);
};
scheduleMidnightReset();
// Middleware: track unique visitors by IP
app.use((req, res, next) => {
const ip = req.headers['x-forwarded-for']?.split(',')[0].trim() || req.socket.remoteAddress || 'unknown';
visitorsToday.add(ip);
next();
});
// Middleware to verify JWT token
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, JWT_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
};
// Middleware to verify super admin password
const SUPER_ADMIN_PASSWORD = process.env.SUPER_ADMIN_PASSWORD || 'cryptocardiac_super_admin_2026';
const authenticateSuperAdmin = (req, res, next) => {
const password = req.headers['x-admin-password'];
if (!password || password !== SUPER_ADMIN_PASSWORD) {
return res.status(403).json({ error: 'Forbidden: Super admin access required' });
}
next();
};
// --- Auth Routes ---
// Signup
app.post('/api/auth/signup', async (req, res) => {
const { email, password, captchaToken } = req.body;
const TURNSTILE_SECRET_KEY = process.env.TURNSTILE_SECRET_KEY || '1x0000000000000000000000000000000AA'; // Secret Key
if (!email || !password) {
return res.status(400).json({ error: 'Email and password are required' });
}
if (!captchaToken) {
return res.status(400).json({ error: 'CAPTCHA verification failed' });
}
try {
// Verify Turnstile Token
const verifyResponse = await axios.post('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
secret: TURNSTILE_SECRET_KEY,
response: captchaToken
});
if (!verifyResponse.data.success) {
return res.status(400).json({ error: 'CAPTCHA verification failed. Please try again.' });
}
// Check if user exists
const [existingUsers] = await db.query('SELECT * FROM users WHERE email = ?', [email]);
if (existingUsers.length > 0) {
return res.status(400).json({ error: 'User already exists' });
}
// Hash password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(password, salt);
// Insert user
const [result] = await db.query('INSERT INTO users (email, password_hash) VALUES (?, ?)', [email, hashedPassword]);
// Create token
const token = jwt.sign({ id: result.insertId, email }, JWT_SECRET, { expiresIn: '24h' });
res.status(201).json({
token,
user: {
id: result.insertId,
email,
share_points: 0
}
});
} catch (error) {
console.error('Signup error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Login
app.post('/api/auth/login', async (req, res) => {
const { email, password } = req.body;
try {
const [users] = await db.query('SELECT * FROM users WHERE email = ?', [email]);
if (users.length === 0) {
return res.status(400).json({ error: 'Invalid credentials' });
}
const user = users[0];
const isMatch = await bcrypt.compare(password, user.password_hash);
if (!isMatch) {
return res.status(400).json({ error: 'Invalid credentials' });
}
const token = jwt.sign({ id: user.id, email: user.email }, JWT_SECRET, { expiresIn: '24h' });
res.json({
token,
user: {
id: user.id,
email: user.email,
share_points: user.share_points
}
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Get Current User (Verify Token)
app.get('/api/auth/me', authenticateToken, async (req, res) => {
try {
const [users] = await db.query('SELECT id, email, share_points FROM users WHERE id = ?', [req.user.id]);
if (users.length === 0) return res.sendStatus(404);
res.json({ user: users[0] });
} catch (error) {
console.error('Get me error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// --- Voting Routes ---
// Get all vote counts
// Get all vote counts (Votes + Shares)
app.get('/api/votes', async (req, res) => {
try {
// Get regular votes
const [voteRows] = await db.query('SELECT coin_id, COUNT(*) as count FROM votes GROUP BY coin_id');
// Get share logs (these now count as votes for the coin)
const [shareRows] = await db.query('SELECT coin_id, COUNT(*) as count FROM share_logs GROUP BY coin_id');
const votes = {};
// Add regular votes
voteRows.forEach(row => {
votes[row.coin_id] = (votes[row.coin_id] || 0) + row.count;
});
// Add share votes
shareRows.forEach(row => {
votes[row.coin_id] = (votes[row.coin_id] || 0) + row.count;
});
res.json(votes);
} catch (error) {
console.error('Get votes error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Get time-based vote counts (24h, 7d, 3 months)
// 24h = Today's votes (resets at midnight EST)
// 7d = Last 7 days (rolling window)
// 3m = Last 90 days (rolling window)
app.get('/api/votes/time-based', async (req, res) => {
try {
const todayEST = getTodayDateEST(); // Get today's date in EST (YYYY-MM-DD)
// Count for 24h (Today)
const [votes24h] = await db.query(`
SELECT coin_id, COUNT(*) as count
FROM (
SELECT coin_id FROM votes WHERE DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) = ?
UNION ALL
SELECT coin_id FROM share_logs WHERE DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) = ?
) as combined
GROUP BY coin_id
`, [todayEST, todayEST]);
// Count for 7d
const [votes7d] = await db.query(`
SELECT coin_id, COUNT(*) as count
FROM (
SELECT coin_id FROM votes WHERE created_at >= NOW() - INTERVAL 7 DAY
UNION ALL
SELECT coin_id FROM share_logs WHERE created_at >= NOW() - INTERVAL 7 DAY
) as combined
GROUP BY coin_id
`);
// Count for 3m
const [votes3m] = await db.query(`
SELECT coin_id, COUNT(*) as count
FROM (
SELECT coin_id FROM votes WHERE created_at >= NOW() - INTERVAL 90 DAY
UNION ALL
SELECT coin_id FROM share_logs WHERE created_at >= NOW() - INTERVAL 90 DAY
) as combined
GROUP BY coin_id
`);
// Combine all results into a single object
const timeBasedVotes = {};
const addCount = (coinId, type, count) => {
if (!timeBasedVotes[coinId]) {
timeBasedVotes[coinId] = { votes_24h: 0, votes_7d: 0, votes_3m: 0 };
}
timeBasedVotes[coinId][type] = count;
};
votes24h.forEach(row => addCount(row.coin_id, 'votes_24h', row.count));
votes7d.forEach(row => addCount(row.coin_id, 'votes_7d', row.count));
votes3m.forEach(row => addCount(row.coin_id, 'votes_3m', row.count));
res.json(timeBasedVotes);
} catch (error) {
console.error('Get time-based votes error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Get most consistent communities (streak calculation)
app.get('/api/votes/consistent', async (req, res) => {
try {
const todayEST = getTodayDateEST();
// 1. Get all dates where votes occurred, grouped by coin
// We order by date DESC to easily check streaks
// Use MAX(coin_name) to comply with ONLY_FULL_GROUP_BY
const [rows] = await db.query(`
SELECT coin_id, MAX(coin_name) as coin_name, DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) as vote_date
FROM votes
GROUP BY coin_id, vote_date
ORDER BY coin_id, vote_date DESC
`);
if (rows.length === 0) {
return res.json([]);
}
// 2. Process streaks in memory
const streaks = {}; // { coinId: { streak: number, name: string, lastDate: string } }
rows.forEach(row => {
const coinId = row.coin_id;
const voteDate = moment(row.vote_date).format('YYYY-MM-DD');
if (!streaks[coinId]) {
streaks[coinId] = {
coinId: coinId,
coinName: row.coin_name,
streak: 0,
dates: []
};
}
streaks[coinId].dates.push(voteDate);
});
const consistentCoins = [];
const today = moment(todayEST);
const yesterday = moment(todayEST).subtract(1, 'days');
Object.values(streaks).forEach(coin => {
let currentStreak = 0;
const dates = new Set(coin.dates); // Unique dates already ensured by SQL GROUP BY but safe to be sure
// Check if they have a vote today OR yesterday to keep streak alive
const hasVoteToday = dates.has(today.format('YYYY-MM-DD'));
const hasVoteYesterday = dates.has(yesterday.format('YYYY-MM-DD'));
if (!hasVoteToday && !hasVoteYesterday) {
// Streak broken if no vote today AND no vote yesterday
currentStreak = 0;
} else {
// Calculate streak walking backwards
// If they voted today, start checking from today
// If they didn't vote today but did yesterday, start checking from yesterday
let checkDate = hasVoteToday ? today.clone() : yesterday.clone();
while (dates.has(checkDate.format('YYYY-MM-DD'))) {
currentStreak++;
checkDate.subtract(1, 'days');
}
}
if (currentStreak > 0) {
consistentCoins.push({
coinId: coin.coinId,
coinName: coin.coinName,
streak: currentStreak
});
}
});
// 3. Sort by streak DESC
consistentCoins.sort((a, b) => b.streak - a.streak);
// 4. Top 10 only
const topConsistent = consistentCoins.slice(0, 10);
// 5. Fetch images/symbols for these coins
const coinIds = topConsistent.map(c => c.coinId).join(',');
if (coinIds) {
const cacheKey = `details_${coinIds}_usd`; // Reuse existing cache pattern if possible or make new
// We can just use the existing helper logic or call the API directly if helper not exposed well
// Let's call API via axios if not in cache (simplified)
// Or better, reuse the existing CoinGecko logic pattern
try {
let coinDetails = myCache.get(cacheKey);
if (!coinDetails) {
apiHitsToday++;
const response = await axios.get('https://api.coingecko.com/api/v3/coins/markets', {
params: {
vs_currency: 'usd',
ids: coinIds,
order: 'market_cap_desc',
sparkline: false
}
});
coinDetails = response.data;
myCache.set(cacheKey, coinDetails);
}
// Merge details
const detailsMap = {};
coinDetails.forEach(c => detailsMap[c.id] = c);
topConsistent.forEach(c => {
const details = detailsMap[c.coinId];
if (details) {
c.image = details.image;
c.symbol = details.symbol;
}
});
} catch (err) {
console.error('Error fetching details for consistent coins:', err.message);
}
}
res.json(topConsistent);
} catch (error) {
console.error('Get consistent communities error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Check user's per-coin voting status
app.get('/api/votes/status', authenticateToken, async (req, res) => {
const userId = req.user.id;
try {
const todayEST = getTodayDateEST();
// Get all votes by this user today (EST)
const [rows] = await db.query(
`SELECT coin_id, created_at FROM votes
WHERE user_id = ?
AND DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) = ?`,
[userId, todayEST]
);
console.log(`Checking status for user ${userId}. Found ${rows.length} votes today (EST).`);
// Return list of coins the user has voted for today
const votedCoins = rows.map(row => ({
coinId: row.coin_id,
votedAt: row.created_at
}));
res.json({ votedCoins });
} catch (error) {
console.error('Check vote status error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Check if user can vote for a specific coin (daily reset at midnight EST)
app.get('/api/votes/check/:coinId', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { coinId } = req.params;
try {
const todayEST = getTodayDateEST();
// Check for vote on THIS specific coin today (EST)
const [rows] = await db.query(
`SELECT created_at FROM votes
WHERE user_id = ? AND coin_id = ?
AND DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) = ?`,
[userId, coinId, todayEST]
);
if (rows.length > 0) {
const remainingMs = getMsUntilMidnightEST();
return res.json({
canVote: false,
remainingMs,
lastVoteTime: rows[0].created_at
});
}
res.json({ canVote: true });
} catch (error) {
console.error('Check vote status error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Cast a vote
app.post('/api/votes', authenticateToken, async (req, res) => {
const { coinId, coinName } = req.body;
const userId = req.user.id;
try {
const todayEST = getTodayDateEST();
// Check restriction for THIS specific coin (per-coin, per-day restriction)
const [rows] = await db.query(
`SELECT created_at FROM votes
WHERE user_id = ? AND coin_id = ?
AND DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) = ?`,
[userId, coinId, todayEST]
);
if (rows.length > 0) {
const remainingMs = getMsUntilMidnightEST();
const remainingHours = Math.floor(remainingMs / (1000 * 60 * 60));
const remainingMinutes = Math.floor((remainingMs % (1000 * 60 * 60)) / (1000 * 60));
return res.status(400).json({
error: `You already voted for ${coinName} today. You can vote again at midnight EST (in ${remainingHours}h ${remainingMinutes}m).`
});
}
// Start transaction
await db.query('START TRANSACTION');
try {
await db.query(
'INSERT INTO votes (user_id, coin_id, coin_name) VALUES (?, ?, ?)',
[userId, coinId, coinName]
);
// Increment user points for voting
await db.query('UPDATE users SET share_points = COALESCE(share_points, 0) + 1 WHERE id = ?', [userId]);
// Commit transaction
await db.query('COMMIT');
// Get updated points
const [users] = await db.query('SELECT share_points FROM users WHERE id = ?', [userId]);
const newPoints = users[0].share_points;
res.json({ message: 'Vote cast successfully', share_points: newPoints });
} catch (err) {
await db.query('ROLLBACK');
throw err;
}
} catch (error) {
console.error('Cast vote error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Increment share points (with daily limit per coin)
app.post('/api/share/x', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { coinId, coinName } = req.body;
if (!coinId) {
return res.status(400).json({ error: 'Coin ID is required' });
}
try {
const todayEST = getTodayDateEST();
// Check if user has already shared this coin today (EST)
const [rows] = await db.query(
`SELECT created_at FROM share_logs
WHERE user_id = ? AND coin_id = ?
AND DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) = ?`,
[userId, coinId, todayEST]
);
if (rows.length > 0) {
return res.status(400).json({ error: 'You have already received points for sharing this coin today.' });
}
// Start transaction
await db.query('START TRANSACTION');
try {
// Insert into share_logs
await db.query(
'INSERT INTO share_logs (user_id, coin_id) VALUES (?, ?)',
[userId, coinId]
);
// Increment user points (sharing does NOT count as a vote)
await db.query('UPDATE users SET share_points = COALESCE(share_points, 0) + 1 WHERE id = ?', [userId]);
// Commit transaction
await db.query('COMMIT');
const [users] = await db.query('SELECT share_points FROM users WHERE id = ?', [userId]);
const newPoints = users[0].share_points;
res.json({ message: 'Share points updated', share_points: newPoints });
} catch (err) {
await db.query('ROLLBACK');
throw err;
}
} catch (error) {
console.error('Share points error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Increment share points for Discord (with daily limit per coin)
app.post('/api/share/discord', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { coinId, coinName } = req.body;
if (!coinId) {
return res.status(400).json({ error: 'Coin ID is required' });
}
try {
const todayEST = getTodayDateEST();
// Check if user has already shared this coin today (EST)
const [rows] = await db.query(
`SELECT created_at FROM share_logs
WHERE user_id = ? AND coin_id = ?
AND DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) = ?`,
[userId, coinId, todayEST]
);
if (rows.length > 0) {
return res.status(400).json({ error: 'You have already received points for sharing this coin today.' });
}
// Start transaction
await db.query('START TRANSACTION');
try {
// Insert into share_logs
await db.query(
'INSERT INTO share_logs (user_id, coin_id) VALUES (?, ?)',
[userId, coinId]
);
// Increment user points (sharing does NOT count as a vote)
await db.query('UPDATE users SET share_points = COALESCE(share_points, 0) + 1 WHERE id = ?', [userId]);
// Commit transaction
await db.query('COMMIT');
const [users] = await db.query('SELECT share_points FROM users WHERE id = ?', [userId]);
const newPoints = users[0].share_points;
res.json({ message: 'Share points updated', share_points: newPoints });
} catch (err) {
await db.query('ROLLBACK');
throw err;
}
} catch (error) {
console.error('Share points error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Increment share points for Reddit (with daily limit per coin)
app.post('/api/share/reddit', authenticateToken, async (req, res) => {
const userId = req.user.id;
const { coinId, coinName } = req.body;
if (!coinId) {
return res.status(400).json({ error: 'Coin ID is required' });
}
try {
const todayEST = getTodayDateEST();
// Check if user has already shared this coin today (EST)
const [rows] = await db.query(
`SELECT created_at FROM share_logs
WHERE user_id = ? AND coin_id = ?
AND DATE(CONVERT_TZ(created_at, '+00:00', '-05:00')) = ?`,
[userId, coinId, todayEST]
);
if (rows.length > 0) {
return res.status(400).json({ error: 'You have already received points for sharing this coin today.' });
}
// Start transaction
await db.query('START TRANSACTION');
try {
// Insert into share_logs
await db.query(
'INSERT INTO share_logs (user_id, coin_id) VALUES (?, ?)',
[userId, coinId]
);
// Increment user points (sharing does NOT count as a vote)
await db.query('UPDATE users SET share_points = COALESCE(share_points, 0) + 1 WHERE id = ?', [userId]);
// Commit transaction
await db.query('COMMIT');
const [users] = await db.query('SELECT share_points FROM users WHERE id = ?', [userId]);
const newPoints = users[0].share_points;
res.json({ message: 'Share points updated', share_points: newPoints });
} catch (err) {
await db.query('ROLLBACK');
throw err;
}
} catch (error) {
console.error('Share points error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// Get user's complete voting history with coin details
app.get('/api/votes/history', authenticateToken, async (req, res) => {
const userId = req.user.id;
try {
// Get only the MOST RECENT vote per coin (no duplicates)
const [votes] = await db.query(
`SELECT v.coin_id, v.coin_name, v.created_at
FROM votes v
INNER JOIN (
SELECT coin_id, MAX(created_at) as max_created_at
FROM votes
WHERE user_id = ?
GROUP BY coin_id
) latest ON v.coin_id = latest.coin_id AND v.created_at = latest.max_created_at
WHERE v.user_id = ?
ORDER BY v.created_at DESC`,
[userId, userId]
);
if (votes.length === 0) {
return res.json({ votes: [] });
}
// Get unique coin IDs
const uniqueCoinIds = [...new Set(votes.map(v => v.coin_id))];
// Fetch coin details from CoinGecko (with caching)
const coinDetailsMap = {};
try {
const cacheKey = `coin_details_${uniqueCoinIds.join(',')}`;
let coinDetails = myCache.get(cacheKey);
if (!coinDetails) {
const response = await axios.get('https://api.coingecko.com/api/v3/coins/markets', {
params: {
vs_currency: 'usd',
ids: uniqueCoinIds.join(','),
order: 'market_cap_desc',
sparkline: false
}
});
coinDetails = response.data;
myCache.set(cacheKey, coinDetails);
apiHitsToday++;
}
// Create a map for quick lookup
coinDetails.forEach(coin => {
coinDetailsMap[coin.id] = {
image: coin.image,
currentPrice: coin.current_price,
symbol: coin.symbol
};
});
} catch (error) {
console.error('Error fetching coin details:', error.message);
// Continue without coin details if API fails
}
// Merge vote data with coin details
const votesWithDetails = votes.map(vote => ({
coinId: vote.coin_id,
coinName: vote.coin_name,
votedAt: vote.created_at,
coinImage: coinDetailsMap[vote.coin_id]?.image || null,
currentPrice: coinDetailsMap[vote.coin_id]?.currentPrice || null,
symbol: coinDetailsMap[vote.coin_id]?.symbol || null
}));
res.json({ votes: votesWithDetails });
} catch (error) {
console.error('Get voting history error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// --- CoinGecko Proxy Route ---
app.get('/api/coins', async (req, res) => {
const { vs_currency = 'usd', order = 'market_cap_desc', per_page = 100, page = 1, sparkline = false } = req.query;
const cacheKey = `coins_${vs_currency}_${order}_${per_page}_${page}_${sparkline}`;
const cachedData = myCache.get(cacheKey);
if (cachedData) {
return res.json(cachedData);
}
try {
apiHitsToday++;
const response = await axios.get('https://api.coingecko.com/api/v3/coins/markets', {
params: {
vs_currency,
order,
per_page,
page,
sparkline
}
});
myCache.set(cacheKey, response.data);
res.json(response.data);
} catch (error) {
console.error('CoinGecko API error:', error.message);
res.status(500).json({ error: 'Failed to fetch coin data' });
}
});
// Search for cryptocurrencies
app.get('/api/coins/search', async (req, res) => {
const { query } = req.query;
if (!query) {
return res.status(400).json({ error: 'Query parameter is required' });
}
const cacheKey = `search_${query}`;
const cachedData = myCache.get(cacheKey);
if (cachedData) {
return res.json(cachedData);
}
try {
apiHitsToday++;
const response = await axios.get('https://api.coingecko.com/api/v3/search', {
params: { query }
});
myCache.set(cacheKey, response.data);
res.json(response.data);
} catch (error) {
console.error('CoinGecko Search API error:', error.message);
res.status(500).json({ error: 'Failed to search coins' });
}
});
// Get detailed data for specific coins by IDs
app.get('/api/coins/details', async (req, res) => {
const { ids, vs_currency = 'usd' } = req.query;
if (!ids) {
return res.status(400).json({ error: 'IDs parameter is required' });
}
const cacheKey = `details_${ids}_${vs_currency}`;
const cachedData = myCache.get(cacheKey);
if (cachedData) {
return res.json(cachedData);
}
try {
apiHitsToday++;
const response = await axios.get('https://api.coingecko.com/api/v3/coins/markets', {
params: {
vs_currency,
ids,
order: 'market_cap_desc',
sparkline: false
}
});
myCache.set(cacheKey, response.data);
res.json(response.data);
} catch (error) {
console.error('CoinGecko Details API error:', error.message);
res.status(500).json({ error: 'Failed to fetch coin details' });
}
});
// --- Articles Routes ---
// GET all active articles (newest first by created_at)
app.get('/api/articles', async (req, res) => {
try {
const [rows] = await db.query(
'SELECT id, title, source, category, description, full_content, created_at, updated_at FROM articles WHERE is_active = 1 ORDER BY created_at DESC'
);
const articles = rows.map(row => ({
...row,
fullContent: JSON.parse(row.full_content)
}));
res.json(articles);
} catch (error) {
console.error('Get articles error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// GET single article by ID
app.get('/api/articles/:id', async (req, res) => {
try {
const [rows] = await db.query(
'SELECT id, title, source, category, description, full_content, created_at, updated_at FROM articles WHERE id = ? AND is_active = 1',
[req.params.id]
);
if (rows.length === 0) return res.status(404).json({ error: 'Article not found' });
const article = { ...rows[0], fullContent: JSON.parse(rows[0].full_content) };
res.json(article);
} catch (error) {
console.error('Get article error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// POST create new article (super admin only)
app.post('/api/articles', authenticateSuperAdmin, async (req, res) => {
const { title, source, category, description, fullContent } = req.body;
if (!title || !source || !category || !description || !fullContent) {
return res.status(400).json({ error: 'All fields are required: title, source, category, description, fullContent (array)' });
}
if (!Array.isArray(fullContent) || fullContent.length === 0) {
return res.status(400).json({ error: 'fullContent must be a non-empty array of paragraphs' });
}
try {
const [result] = await db.query(
'INSERT INTO articles (title, source, category, description, full_content) VALUES (?, ?, ?, ?, ?)',
[title, source, category, description, JSON.stringify(fullContent)]
);
res.status(201).json({ message: 'Article created', id: result.insertId });
} catch (error) {
console.error('Create article error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// PUT update article (super admin only)
app.put('/api/articles/:id', authenticateSuperAdmin, async (req, res) => {
const { title, source, category, description, fullContent } = req.body;
try {
const updates = {};
if (title) updates.title = title;
if (source) updates.source = source;
if (category) updates.category = category;
if (description) updates.description = description;
if (fullContent) updates.full_content = JSON.stringify(fullContent);
if (Object.keys(updates).length === 0) {
return res.status(400).json({ error: 'Nothing to update' });
}
const fields = Object.keys(updates).map(k => `${k} = ?`).join(', ');
const values = [...Object.values(updates), req.params.id];
await db.query(`UPDATE articles SET ${fields} WHERE id = ?`, values);
res.json({ message: 'Article updated' });
} catch (error) {
console.error('Update article error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// DELETE article (soft delete, super admin only)
app.delete('/api/articles/:id', authenticateSuperAdmin, async (req, res) => {
try {
await db.query('UPDATE articles SET is_active = 0 WHERE id = ?', [req.params.id]);
res.json({ message: 'Article deleted' });
} catch (error) {
console.error('Delete article error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// --- Trending Topics Routes ---
// GET all active trending topics
app.get('/api/trending-topics', async (req, res) => {
try {
const [rows] = await db.query(
'SELECT id, title, trend FROM trending_topics WHERE is_active = 1 ORDER BY sort_order ASC'
);
res.json(rows);
} catch (error) {
console.error('Get trending topics error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// POST create trending topic (super admin only)
app.post('/api/trending-topics', authenticateSuperAdmin, async (req, res) => {
const { title, trend } = req.body;
if (!title || !trend) {
return res.status(400).json({ error: 'title and trend are required' });
}
try {
const [result] = await db.query(
'INSERT INTO trending_topics (title, trend) VALUES (?, ?)',
[title, trend]
);
res.status(201).json({ message: 'Trending topic created', id: result.insertId });
} catch (error) {
console.error('Create trending topic error:', error);
res.status(500).json({ error: 'Server error' });
}
});
// PUT update trending topic (super admin only)
app.put('/api/trending-topics/:id', authenticateSuperAdmin, async (req, res) => {
const { title, trend } = req.body;
try {
const updates = {};
if (title) updates.title = title;
if (trend) updates.trend = trend;
if (Object.keys(updates).length === 0) {