Spaces:
Runtime error
Runtime error
File size: 57,850 Bytes
272dfc6 c9cf26b 272dfc6 64e57ec 95a6aa2 272dfc6 c9cf26b 272dfc6 95a6aa2 13267b3 8c6f70f 13267b3 43c7d49 2ebfe6c 13267b3 7f1f6ab 95a6aa2 7f1f6ab 95a6aa2 c9cf26b 1b96d8b 64e57ec c9cf26b 55a57c5 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 64e57ec c9cf26b 64e57ec 272dfc6 64e57ec 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 55a57c5 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 55a57c5 272dfc6 55a57c5 272dfc6 55a57c5 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 64e57ec 272dfc6 95a6aa2 c9cf26b 95a6aa2 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 95a6aa2 272dfc6 c9cf26b 272dfc6 95a6aa2 272dfc6 95a6aa2 272dfc6 c9cf26b 272dfc6 64e57ec 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 95a6aa2 64e57ec 95a6aa2 64e57ec 272dfc6 55a57c5 272dfc6 55a57c5 c9cf26b 272dfc6 70a3190 272dfc6 70a3190 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 64e57ec 272dfc6 c9cf26b 272dfc6 95a6aa2 272dfc6 95a6aa2 13267b3 55a57c5 95a6aa2 13267b3 95a6aa2 272dfc6 95a6aa2 13267b3 55a57c5 13267b3 55a57c5 13267b3 55a57c5 13267b3 55a57c5 13267b3 55a57c5 13267b3 55a57c5 13267b3 55a57c5 13267b3 55a57c5 272dfc6 c9cf26b 272dfc6 13267b3 272dfc6 13267b3 272dfc6 c9cf26b 55a57c5 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 272dfc6 95a6aa2 272dfc6 c9cf26b 272dfc6 c9cf26b 95a6aa2 64e57ec 95a6aa2 55a57c5 272dfc6 95a6aa2 13267b3 95a6aa2 13267b3 95a6aa2 13267b3 95a6aa2 13267b3 95a6aa2 13267b3 95a6aa2 13267b3 55a57c5 13267b3 55a57c5 13267b3 95a6aa2 13267b3 95a6aa2 13267b3 95a6aa2 13267b3 95a6aa2 13267b3 95a6aa2 55a57c5 95a6aa2 13267b3 95a6aa2 272dfc6 c9cf26b 272dfc6 13267b3 272dfc6 13267b3 272dfc6 64e57ec c9cf26b 64e57ec c9cf26b 64e57ec c9cf26b 95a6aa2 55a57c5 95a6aa2 55a57c5 95a6aa2 13267b3 95a6aa2 1b96d8b c9cf26b 95a6aa2 c9cf26b 272dfc6 c9cf26b 272dfc6 c9cf26b 1b96d8b c9cf26b 13267b3 95a6aa2 | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 | const express = require('express');
const fs = require('fs');
const os = require('os');
const path = require('path');
const http = require('http');
const https = require('https');
const { Sequelize, DataTypes, Op } = require('sequelize');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const multer = require('multer');
const bodyParser = require('body-parser');
const { v4: uuidv4 } = require('uuid');
require('dotenv').config();
const app = express();
const cors = require('cors');
const allowedOrigins = process.env.CORS_ORIGIN ? process.env.CORS_ORIGIN.split(',').map(o => o.trim()).filter(Boolean) : ['*'];
function isAllowedOrigin(origin) {
if (!origin) return true;
if (allowedOrigins.includes('*')) return true;
return allowedOrigins.some((allowed) => {
if (allowed === origin) return true;
if (allowed.endsWith(':*')) {
const prefix = allowed.slice(0, -2);
return origin.startsWith(prefix + ':');
}
return false;
});
}
app.use(cors({
origin: (origin, callback) => {
if (isAllowedOrigin(origin)) return callback(null, true);
return callback(new Error('Not allowed by CORS'));
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use((req, res, next) => {
if (req.path.endsWith('.html') || req.path.endsWith('.js') || req.path.endsWith('.css')) {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
res.setHeader('Surrogate-Control', 'no-store');
}
next();
});
app.use(express.static(__dirname));
app.get('/api/version', (req, res) => {
try {
const packageJson = require('./package.json');
res.json({ version: packageJson.version || 'unknown' });
} catch (error) {
res.status(500).json({ version: 'unknown' });
}
});
app.get('/api/rtc-config', (req, res) => {
const defaultIceServers = [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
{ urls: 'stun:stun2.l.google.com:19302' },
{ urls: 'stun:stun3.l.google.com:19302' },
{ urls: 'stun:stun4.l.google.com:19302' },
{ urls: 'stun:stun.cloudflare.com:3478' }
];
const turnUrlsRaw = process.env.TURN_URLS || '';
const turnUsername = process.env.TURN_USERNAME || '';
const turnCredential = process.env.TURN_CREDENTIAL || '';
const relayFlag = String(process.env.RTC_FORCE_RELAY || 'false').toLowerCase();
const forceRelay = relayFlag === 'true' || relayFlag === '1' || relayFlag === 'yes';
let iceServers = [...defaultIceServers];
if (turnUrlsRaw && turnUsername && turnCredential) {
const turnUrls = turnUrlsRaw
.split(',')
.map((entry) => entry.trim())
.filter(Boolean);
if (turnUrls.length) {
iceServers = [
...defaultIceServers,
{
urls: turnUrls,
username: turnUsername,
credential: turnCredential
}
];
}
}
res.json({
iceServers,
iceTransportPolicy: forceRelay ? 'relay' : 'all'
});
});
const isProduction = process.env.NODE_ENV === 'production';
const connectionString = process.env.DATABASE_URL;
if (isProduction && !connectionString) {
console.error('Missing DATABASE_URL in production. Add it in Render Environment settings or via render.yaml fromDatabase binding.');
process.exit(1);
}
const resolvedConnectionString = connectionString || 'postgres://postgres:postgres@localhost:5432/discord-app';
const isLocalConnection = resolvedConnectionString.includes('localhost') || resolvedConnectionString.includes('127.0.0.1');
const sequelize = new Sequelize(resolvedConnectionString, {
dialect: 'postgres',
logging: false,
protocol: 'postgres',
dialectOptions: isLocalConnection ? {} : { ssl: { require: true, rejectUnauthorized: false } }
});
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function syncDatabaseWithRetry(maxAttempts = 8) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
await sequelize.authenticate();
await sequelize.sync({ alter: true });
return;
} catch (err) {
const message = err && err.message ? err.message : String(err);
const retryable = /ECONNRESET|ECONNREFUSED|ETIMEDOUT|SequelizeConnection/i.test(message);
const shouldRetry = retryable && attempt < maxAttempts;
console.error(`Database connect/sync attempt ${attempt}/${maxAttempts} failed:`, err);
if (!shouldRetry) {
throw err;
}
const delayMs = Math.min(30000, 2000 * attempt);
console.log(`Retrying database connection in ${delayMs}ms...`);
await sleep(delayMs);
}
}
}
const User = sequelize.define('User', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: false
},
avatar: {
type: DataTypes.TEXT,
defaultValue: ''
},
bio: {
type: DataTypes.STRING,
defaultValue: 'No bio yet'
},
phoneNumber: {
type: DataTypes.STRING,
defaultValue: ''
},
status: {
type: DataTypes.ENUM('online', 'offline', 'away'),
defaultValue: 'offline'
},
coins: {
type: DataTypes.INTEGER,
defaultValue: 0
}
});
const Channel = sequelize.define('Channel', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
channelId: DataTypes.STRING,
name: DataTypes.STRING,
type: {
type: DataTypes.ENUM('text', 'voice'),
defaultValue: 'text'
},
description: DataTypes.STRING,
isPrivate: {
type: DataTypes.BOOLEAN,
defaultValue: false
}
});
const Message = sequelize.define('Message', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
messageId: DataTypes.STRING,
channelId: DataTypes.STRING,
senderUsername: DataTypes.STRING,
content: DataTypes.TEXT,
mediaType: {
type: DataTypes.ENUM('text', 'image', 'video', 'emoji', 'sticker', 'gif', 'voice'),
defaultValue: 'text'
},
mediaUrl: DataTypes.TEXT
});
const ShopItem = sequelize.define('ShopItem', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
itemId: DataTypes.STRING,
name: DataTypes.STRING,
description: DataTypes.STRING,
price: DataTypes.INTEGER,
category: DataTypes.STRING,
image: DataTypes.TEXT
});
const Inventory = sequelize.define('Inventory', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
itemId: DataTypes.STRING,
quantity: {
type: DataTypes.INTEGER,
defaultValue: 1
}
});
const FriendRequest = sequelize.define('FriendRequest', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
status: {
type: DataTypes.ENUM('pending', 'accepted', 'rejected'),
defaultValue: 'pending'
}
});
const DirectMessage = sequelize.define('DirectMessage', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
messageId: DataTypes.STRING,
fromUsername: DataTypes.STRING,
toUsername: DataTypes.STRING,
content: DataTypes.TEXT,
mediaType: {
type: DataTypes.ENUM('text', 'image', 'video', 'emoji', 'sticker', 'gif', 'voice'),
defaultValue: 'text'
},
mediaUrl: DataTypes.TEXT
});
User.belongsToMany(User, {
as: 'friends',
through: 'UserFriends',
foreignKey: 'UserId',
otherKey: 'FriendId'
});
User.hasMany(Channel, { foreignKey: 'createdById', as: 'channels' });
Channel.belongsTo(User, { foreignKey: 'createdById', as: 'creator' });
Channel.belongsToMany(User, { through: 'ChannelMembers', foreignKey: 'ChannelId', otherKey: 'UserId' });
User.belongsToMany(Channel, { through: 'ChannelMembers', foreignKey: 'UserId', otherKey: 'ChannelId' });
User.hasMany(Message, { foreignKey: 'senderId' });
Message.belongsTo(User, { foreignKey: 'senderId' });
User.hasMany(Inventory, { foreignKey: 'userId' });
Inventory.belongsTo(User, { foreignKey: 'userId' });
ShopItem.hasMany(Inventory, { foreignKey: 'shopItemId' });
Inventory.belongsTo(ShopItem, { foreignKey: 'shopItemId' });
FriendRequest.belongsTo(User, { as: 'from', foreignKey: 'fromId' });
FriendRequest.belongsTo(User, { as: 'to', foreignKey: 'toId' });
DirectMessage.belongsTo(User, { as: 'sender', foreignKey: 'fromId' });
DirectMessage.belongsTo(User, { as: 'recipient', foreignKey: 'toId' });
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.status(401).json({ error: 'Access token required' });
jwt.verify(token, process.env.JWT_SECRET || 'secret_key', (err, user) => {
if (err) return res.status(403).json({ error: 'Invalid token' });
req.user = user;
next();
});
};
app.post('/api/register', async (req, res) => {
try {
const { username, email, password } = req.body;
if (!username || !email || !password) {
return res.status(400).json({ error: 'All fields required' });
}
const existingUser = await User.findOne({ where: { [Op.or]: [{ username }, { email }] } });
if (existingUser) {
return res.status(400).json({ error: existingUser.username === username ? 'Username already taken' : 'Email already registered' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await User.create({ username, email, password: hashedPassword });
const token = jwt.sign(
{ userId: user.id, username: user.username },
process.env.JWT_SECRET || 'secret_key'
);
res.status(201).json({
token,
user: {
id: user.id,
username: user.username,
email: user.email,
avatar: user.avatar,
bio: user.bio,
phoneNumber: user.phoneNumber,
coins: user.coins
}
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/login', async (req, res) => {
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Email and password required' });
}
const user = await User.findOne({ where: { email } });
if (!user) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const token = jwt.sign(
{ userId: user.id, username: user.username },
process.env.JWT_SECRET || 'secret_key'
);
res.json({
token,
user: {
id: user.id,
username: user.username,
email: user.email,
avatar: user.avatar,
bio: user.bio,
phoneNumber: user.phoneNumber,
coins: user.coins
}
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/reset-password', async (req, res) => {
try {
const { email, newPassword } = req.body;
if (!email || !newPassword) {
return res.status(400).json({ error: 'Email and new password are required' });
}
if (String(newPassword).length < 6) {
return res.status(400).json({ error: 'New password must be at least 6 characters' });
}
const user = await User.findOne({ where: { email } });
if (!user) {
return res.status(404).json({ error: 'No account found with this email' });
}
user.password = await bcrypt.hash(newPassword, 10);
await user.save();
res.json({ success: true, message: 'Password reset successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/profile/:userId', authenticateToken, async (req, res) => {
try {
const user = await User.findByPk(req.params.userId, {
attributes: ['id', 'username', 'avatar', 'bio', 'phoneNumber', 'coins', 'status']
});
if (!user) return res.status(404).json({ error: 'User not found' });
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/profile/coins', authenticateToken, async (req, res) => {
try {
const { coins } = req.body;
if (typeof coins !== 'number' || !Number.isFinite(coins) || coins < 0) {
return res.status(400).json({ error: 'Invalid coins value' });
}
const user = await User.findByPk(req.user.userId);
if (!user) return res.status(404).json({ error: 'User not found' });
user.coins = Math.floor(coins);
await user.save();
res.json({ message: 'Coins synced', coins: user.coins });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.put('/api/profile', authenticateToken, async (req, res) => {
try {
const { username, bio, avatar, phoneNumber } = req.body;
const user = await User.findByPk(req.user.userId);
if (!user) return res.status(404).json({ error: 'User not found' });
if (username && username !== user.username) {
const existing = await User.findOne({ where: { username } });
if (existing) {
return res.status(400).json({ error: 'Username already taken' });
}
user.username = username;
}
if (bio) user.bio = bio;
if (avatar) user.avatar = avatar;
if (typeof phoneNumber === 'string') user.phoneNumber = phoneNumber;
await user.save();
for (const [socketId, onlineUser] of onlineUsers.entries()) {
if (onlineUser.userId === user.id) {
onlineUsers.set(socketId, {
...onlineUser,
username: user.username,
avatar: user.avatar
});
}
}
io.emit('users update', Array.from(onlineUsers.values()));
res.json({
message: 'Profile updated',
user: {
id: user.id,
username: user.username,
avatar: user.avatar,
bio: user.bio,
phoneNumber: user.phoneNumber
}
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/profile/upload', authenticateToken, async (req, res) => {
try {
const { avatar } = req.body;
const user = await User.findByPk(req.user.userId);
if (!user) return res.status(404).json({ error: 'User not found' });
if (avatar) {
user.avatar = avatar;
await user.save();
for (const [socketId, onlineUser] of onlineUsers.entries()) {
if (onlineUser.userId === user.id) {
onlineUsers.set(socketId, {
...onlineUser,
avatar: user.avatar
});
}
}
io.emit('users update', Array.from(onlineUsers.values()));
}
res.json({
message: 'Profile image updated',
avatar: user.avatar
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/friends/request', authenticateToken, async (req, res) => {
try {
const { toUserId } = req.body;
if (!toUserId) return res.status(400).json({ error: 'toUserId is required' });
if (String(toUserId) === String(req.user.userId)) return res.status(400).json({ error: 'Cannot send request to yourself' });
const targetUser = await User.findByPk(toUserId);
if (!targetUser) return res.status(404).json({ error: 'User not found' });
const fromUser = await User.findByPk(req.user.userId);
const existingFriend = await fromUser.getFriends({ where: { id: toUserId } });
if (existingFriend.length > 0) return res.status(400).json({ error: 'Already friends' });
const existingPending = await FriendRequest.findOne({
where: {
status: 'pending',
[Op.or]: [
{ fromId: req.user.userId, toId: toUserId },
{ fromId: toUserId, toId: req.user.userId }
]
}
});
if (existingPending) return res.status(400).json({ error: 'Friend request already pending' });
await FriendRequest.create({ fromId: req.user.userId, toId: toUserId });
io.emit('friend request update', { toUserId });
res.status(201).json({ message: 'Friend request sent' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/friends/requests', authenticateToken, async (req, res) => {
try {
const requests = await FriendRequest.findAll({
where: { toId: req.user.userId, status: 'pending' },
include: [{ model: User, as: 'from', attributes: ['id', 'username', 'avatar'] }]
});
res.json(requests);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/friends/accept', authenticateToken, async (req, res) => {
try {
const { requestId } = req.body;
const request = await FriendRequest.findByPk(requestId);
if (!request) return res.status(404).json({ error: 'Request not found' });
if (String(request.toId) !== String(req.user.userId)) {
return res.status(403).json({ error: 'Not allowed to accept this request' });
}
if (request.status !== 'pending') {
return res.status(400).json({ error: `Request already ${request.status}` });
}
request.status = 'accepted';
await request.save();
const fromUser = await User.findByPk(request.fromId);
const toUser = await User.findByPk(request.toId);
await fromUser.addFriend(toUser);
await toUser.addFriend(fromUser);
io.emit('friend request accepted', {
requestId: request.id,
fromId: request.fromId,
toId: request.toId
});
res.json({ message: 'Friend request accepted' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/friends/reject', authenticateToken, async (req, res) => {
try {
const { requestId } = req.body;
const request = await FriendRequest.findByPk(requestId);
if (!request) return res.status(404).json({ error: 'Request not found' });
if (String(request.toId) !== String(req.user.userId)) {
return res.status(403).json({ error: 'Not allowed to reject this request' });
}
if (request.status !== 'pending') {
return res.status(400).json({ error: `Request already ${request.status}` });
}
request.status = 'rejected';
await request.save();
io.emit('friend request rejected', {
requestId: request.id,
fromId: request.fromId,
toId: request.toId
});
res.json({ message: 'Friend request rejected' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/friends', authenticateToken, async (req, res) => {
try {
const user = await User.findByPk(req.user.userId, {
include: {
association: 'friends',
attributes: ['id', 'username', 'avatar', 'status', 'bio'],
through: { attributes: [] }
}
});
res.json(user.friends || []);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/dms/:friendId', authenticateToken, async (req, res) => {
try {
const { friendId } = req.params;
const messages = await DirectMessage.findAll({
where: {
[Op.or]: [
{ fromId: req.user.userId, toId: friendId },
{ fromId: friendId, toId: req.user.userId }
]
},
order: [['createdAt', 'ASC']]
});
const userIds = [...new Set(messages.map(msg => msg.fromId))];
const users = await User.findAll({
where: { id: userIds },
attributes: ['id', 'avatar', 'username']
});
const userMap = new Map(users.map(user => [String(user.id), user]));
const enriched = messages.map(msg => {
const sender = userMap.get(String(msg.fromId));
return {
...msg.toJSON(),
fromAvatar: sender?.avatar || null,
fromUsername: sender?.username || msg.fromUsername,
timestamp: msg.createdAt
};
});
res.json(enriched);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/dms', authenticateToken, async (req, res) => {
try {
const { toUserId, content, mediaType, mediaUrl } = req.body;
const fromUser = await User.findByPk(req.user.userId);
const toUser = await User.findByPk(toUserId);
if (!toUser) return res.status(404).json({ error: 'User not found' });
const dm = await DirectMessage.create({
messageId: uuidv4(),
fromId: req.user.userId,
toId: toUserId,
fromUsername: fromUser.username,
toUsername: toUser.username,
content,
mediaType: mediaType || 'text',
mediaUrl: mediaUrl || null
});
res.status(201).json(dm);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.delete('/api/dms/:friendId', authenticateToken, async (req, res) => {
try {
const { friendId } = req.params;
await DirectMessage.destroy({
where: {
[Op.or]: [
{ fromId: req.user.userId, toId: friendId },
{ fromId: friendId, toId: req.user.userId }
]
}
});
emitToUser(friendId, 'dm history cleared', {
fromUserId: req.user.userId,
clearedAt: new Date().toISOString()
});
res.json({ message: 'DM history cleared for both users' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/shop', authenticateToken, async (req, res) => {
try {
const items = await ensureShopItemsAvailable();
res.json(items);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/shop/buy', authenticateToken, async (req, res) => {
try {
const requestedItemId = String(req.body?.itemId || '').trim();
if (!requestedItemId) {
return res.status(400).json({ error: 'itemId is required' });
}
let item = await ShopItem.findByPk(requestedItemId);
if (!item) {
item = await ShopItem.findOne({ where: { itemId: requestedItemId } });
}
const user = await User.findByPk(req.user.userId);
if (!item) return res.status(404).json({ error: 'Item not found' });
if (user.coins < item.price) return res.status(400).json({ error: 'Not enough coins' });
user.coins -= item.price;
await user.save();
let inventoryItem = await Inventory.findOne({
where: {
userId: user.id,
shopItemId: item.id
}
});
if (inventoryItem) {
inventoryItem.quantity += 1;
await inventoryItem.save();
} else {
inventoryItem = await Inventory.create({ userId: user.id, shopItemId: item.id, quantity: 1 });
}
res.json({
message: 'Item purchased',
coins: user.coins,
purchasedItem: {
id: item.id,
itemId: item.itemId,
name: item.name,
category: item.category,
description: item.description
},
quantity: inventoryItem.quantity
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/inventory', authenticateToken, async (req, res) => {
try {
const inventory = await Inventory.findAll({
where: { userId: req.user.userId },
include: [{ model: ShopItem }]
});
res.json(inventory);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
function createServer(appInstance) {
const pfxPath = process.env.SSL_PFX_PATH;
const pfxPassphrase = process.env.SSL_PFX_PASSPHRASE;
const keyPath = process.env.SSL_KEY_PATH;
const certPath = process.env.SSL_CERT_PATH;
if (pfxPath) {
const httpsOptions = {
pfx: fs.readFileSync(path.resolve(pfxPath)),
passphrase: pfxPassphrase
};
return { server: https.createServer(httpsOptions, appInstance), protocol: 'https' };
}
if (keyPath && certPath) {
const httpsOptions = {
key: fs.readFileSync(path.resolve(keyPath)),
cert: fs.readFileSync(path.resolve(certPath))
};
return { server: https.createServer(httpsOptions, appInstance), protocol: 'https' };
}
return { server: http.createServer(appInstance), protocol: 'http' };
}
const { server, protocol } = createServer(app);
const io = require('socket.io')(server, {
maxHttpBufferSize: 40 * 1024 * 1024,
cors: {
origin: (origin, callback) => {
if (isAllowedOrigin(origin)) return callback(null, true);
return callback(new Error('Not allowed by Socket.IO CORS'));
},
methods: ['GET', 'POST']
}
});
const onlineUsers = new Map();
const roomMessages = new Map();
const roomMembers = new Map();
const roomRoles = new Map();
const roomProfiles = new Map();
const roomMeta = new Map();
function normalizeRoomKey(roomType, roomName) {
return String(roomType || 'community') + ':' + String(roomName || '').trim().toLowerCase();
}
function getRoomMessages(roomType, roomName) {
const key = normalizeRoomKey(roomType, roomName);
return roomMessages.get(key) || [];
}
async function loadRoomMessagesFromDb(roomType, roomName, limit = 150) {
const key = normalizeRoomKey(roomType, roomName);
const rows = await Message.findAll({
where: { channelId: key },
include: [{ model: User, attributes: ['id', 'username', 'avatar'], required: false }],
order: [['createdAt', 'ASC']],
limit
});
return rows.map((row) => ({
messageId: row.messageId || row.id,
from: row.senderId || row.User?.id || null,
fromUsername: row.senderUsername || row.User?.username || 'User',
fromAvatar: row.User?.avatar || null,
content: row.content || '',
mediaType: row.mediaType || 'text',
mediaUrl: row.mediaUrl || null,
roomType,
roomName,
timestamp: row.createdAt
}));
}
function appendRoomMessage(roomType, roomName, payload) {
const key = normalizeRoomKey(roomType, roomName);
const messages = roomMessages.get(key) || [];
messages.push(payload);
if (messages.length > 300) {
messages.splice(0, messages.length - 300);
}
roomMessages.set(key, messages);
}
function emitToUser(userId, eventName, payload) {
let delivered = 0;
for (const [socketId, userData] of onlineUsers.entries()) {
if (String(userData.userId) === String(userId)) {
io.to(socketId).emit(eventName, payload);
delivered += 1;
}
}
return delivered;
}
function getRoomMembersPayload(roomType, roomName) {
const roomKey = normalizeRoomKey(roomType, roomName);
const membersBySocket = roomMembers.get(roomKey) || new Map();
const dedupByUserId = new Map();
for (const member of membersBySocket.values()) {
const userId = String(member.userId);
if (!dedupByUserId.has(userId)) {
dedupByUserId.set(userId, {
id: member.userId,
username: member.username,
avatar: member.avatar || null,
status: 'online',
role: member.role || 'Member'
});
}
}
return Array.from(dedupByUserId.values());
}
function emitRoomMembersUpdate(roomType, roomName) {
const roomKey = normalizeRoomKey(roomType, roomName);
io.to(roomKey).emit('room members update', {
roomType,
roomName,
members: getRoomMembersPayload(roomType, roomName)
});
}
function upsertRoomMember(roomType, roomName, socket) {
const roomKey = normalizeRoomKey(roomType, roomName);
if (!roomMembers.has(roomKey)) {
roomMembers.set(roomKey, new Map());
}
if (!roomRoles.has(roomKey)) {
roomRoles.set(roomKey, new Map());
}
const membersBySocket = roomMembers.get(roomKey);
const rolesByUser = roomRoles.get(roomKey);
const userIdKey = String(socket.userId);
const meta = getOrCreateRoomMeta(roomType, roomName, socket.userId);
if (!meta.creatorId) {
meta.creatorId = userIdKey;
}
if (!rolesByUser.has(userIdKey)) {
if (String(meta.creatorId) === userIdKey) {
rolesByUser.set(userIdKey, 'Owner');
} else if (meta.contributorIds.has(userIdKey)) {
rolesByUser.set(userIdKey, 'Admin');
} else {
rolesByUser.set(userIdKey, 'Member');
}
}
membersBySocket.set(socket.id, {
userId: socket.userId,
username: socket.username,
avatar: socket.userAvatar || null,
role: rolesByUser.get(userIdKey)
});
emitRoomMembersUpdate(roomType, roomName);
}
function removeRoomMember(roomType, roomName, socketId) {
const roomKey = normalizeRoomKey(roomType, roomName);
const membersBySocket = roomMembers.get(roomKey);
if (!membersBySocket) return;
membersBySocket.delete(socketId);
if (membersBySocket.size === 0) {
roomMembers.delete(roomKey);
roomRoles.delete(roomKey);
roomMeta.delete(roomKey);
return;
}
emitRoomMembersUpdate(roomType, roomName);
}
function emitUsersUpdate() {
io.emit('users update', Array.from(onlineUsers.values()));
}
function getOrCreateRoomMeta(roomType, roomName, creatorId = null) {
const roomKey = normalizeRoomKey(roomType, roomName);
if (!roomMeta.has(roomKey)) {
roomMeta.set(roomKey, {
creatorId: creatorId ? String(creatorId) : null,
contributorIds: new Set(),
updatedAt: new Date().toISOString()
});
}
return roomMeta.get(roomKey);
}
function getOrCreateRoomProfile(roomType, roomName) {
const roomKey = normalizeRoomKey(roomType, roomName);
if (!roomProfiles.has(roomKey)) {
roomProfiles.set(roomKey, {
name: String(roomName || ''),
icon: roomType === 'community' ? 'π' : 'π₯',
image: ''
});
}
return roomProfiles.get(roomKey);
}
function emitRoomProfileUpdate(roomType, roomName, profile, previousRoomName = null) {
const roomKey = normalizeRoomKey(roomType, roomName);
// Broadcast to room members first
io.to(roomKey).emit('room profile updated', {
roomType,
roomName,
previousRoomName,
profile
});
// Also broadcast to all connected users so they see updates in lists/modals even if not in the room
io.emit('room profile updated broadcast', {
roomType,
roomName,
previousRoomName,
profile
});
}
function renameRoomState(roomType, previousRoomName, nextRoomName) {
const oldKey = normalizeRoomKey(roomType, previousRoomName);
const newKey = normalizeRoomKey(roomType, nextRoomName);
if (oldKey === newKey) return newKey;
if (roomMessages.has(oldKey)) {
roomMessages.set(newKey, roomMessages.get(oldKey));
roomMessages.delete(oldKey);
}
if (roomRoles.has(oldKey)) {
roomRoles.set(newKey, roomRoles.get(oldKey));
roomRoles.delete(oldKey);
}
if (roomProfiles.has(oldKey)) {
roomProfiles.set(newKey, roomProfiles.get(oldKey));
roomProfiles.delete(oldKey);
}
if (roomMeta.has(oldKey)) {
roomMeta.set(newKey, roomMeta.get(oldKey));
roomMeta.delete(oldKey);
}
if (roomMembers.has(oldKey)) {
const membersBySocket = roomMembers.get(oldKey);
roomMembers.set(newKey, membersBySocket);
roomMembers.delete(oldKey);
for (const socketId of membersBySocket.keys()) {
const memberSocket = io.sockets.sockets.get(socketId);
if (!memberSocket) continue;
memberSocket.leave(oldKey);
memberSocket.join(newKey);
memberSocket.currentRoomKey = newKey;
memberSocket.currentRoomMeta = {
roomType,
roomName: nextRoomName
};
}
}
return newKey;
}
function getBotResponse(input = '') {
const text = String(input || '').trim().toLowerCase();
const cleaned = text.replace(/^\/firetech\s*/i, '').replace(/^@firetech\s*/i, '').trim();
if (!cleaned || cleaned.includes('help')) {
return 'FireTech commands: help, security, encryption, network, password, twofa, phishing, malware, vpn, hello';
}
if (cleaned.includes('security')) {
return 'Security tip: Keep software updated, use strong passwords, enable 2FA, and never share credentials.';
}
if (cleaned.includes('encryption')) {
return 'Encryption fact: End-to-end encryption ensures only sender and receiver can read messages. FireTech uses modern protocols.';
}
if (cleaned.includes('network')) {
return 'Network insight: Your messages are routed through secure servers. Network traffic is protected from eavesdropping.';
}
if (cleaned.includes('password')) {
return 'Password best practice: Use 12+ characters, mix uppercase/lowercase/numbers/symbols, and never reuse passwords.';
}
if (cleaned.includes('2fa') || cleaned.includes('twofa')) {
return '2FA (Two-Factor Authentication) significantly reduces account takeover risk. Enable it on all important accounts.';
}
if (cleaned.includes('phishing')) {
return 'Phishing warning: Check sender email, verify links before clicking, and never provide credentials to unsolicited requests.';
}
if (cleaned.includes('malware')) {
return 'Malware protection: Use antivirus software, avoid downloading from untrusted sources, and keep OS updated.';
}
if (cleaned.includes('vpn')) {
return 'VPN (Virtual Private Network) encrypts your connection and masks your IP. Useful on public WiFi networks.';
}
if (cleaned.includes('hello') || cleaned.includes('hi')) {
return 'β‘ FireTech Bot online. Your security is my priority. Ask for security tips or network info!';
}
return `I heard: "${cleaned}". Type "help" for my security commands.`;
}
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
socket.on('join', async (data) => {
try {
const decoded = jwt.verify(data.token, process.env.JWT_SECRET || 'secret_key');
const user = await User.findByPk(decoded.userId);
if (user) {
socket.userId = decoded.userId;
socket.username = user.username;
socket.userAvatar = user.avatar;
onlineUsers.set(socket.id, {
userId: decoded.userId,
username: user.username,
avatar: user.avatar,
status: 'online'
});
user.status = 'online';
await user.save();
emitUsersUpdate();
}
} catch (error) {
socket.emit('error', 'Authentication failed');
}
});
socket.on('update profile cache', (data) => {
const nextUsername = String(data?.username || socket.username || '').trim();
const nextAvatar = data?.avatar ?? socket.userAvatar ?? null;
if (nextUsername) {
socket.username = nextUsername;
}
socket.userAvatar = nextAvatar;
const existing = onlineUsers.get(socket.id);
if (existing) {
existing.username = socket.username;
existing.avatar = socket.userAvatar;
onlineUsers.set(socket.id, existing);
}
if (socket.currentRoomMeta) {
const { roomType, roomName } = socket.currentRoomMeta;
const roomKey = normalizeRoomKey(roomType, roomName);
const membersBySocket = roomMembers.get(roomKey);
if (membersBySocket && membersBySocket.has(socket.id)) {
const member = membersBySocket.get(socket.id);
member.username = socket.username;
member.avatar = socket.userAvatar;
membersBySocket.set(socket.id, member);
emitRoomMembersUpdate(roomType, roomName);
}
}
emitUsersUpdate();
});
socket.on('join dm', (friendId) => {
const roomId = [socket.userId, friendId].sort().join('_');
socket.join(roomId);
socket.currentDmRoom = roomId;
});
socket.on('leave dm', (friendId) => {
const roomId = [socket.userId, friendId].sort().join('_');
socket.leave(roomId);
socket.currentDmRoom = null;
});
socket.on('send dm', async (data) => {
try {
const { toUserId, content, mediaType, mediaUrl } = data;
const fromUser = await User.findByPk(socket.userId);
if (String(toUserId) === 'bot_firetech_0') {
const dmPayload = {
messageId: uuidv4(),
from: socket.userId,
fromUsername: fromUser.username,
fromAvatar: fromUser.avatar,
to: 'bot_firetech_0',
toUsername: 'β‘ FireTech Bot',
content,
mediaType: mediaType || 'text',
mediaUrl: mediaUrl || null,
timestamp: new Date().toISOString()
};
emitToUser(socket.userId, 'dm message', dmPayload);
const botPayload = {
messageId: uuidv4(),
from: 'bot_firetech_0',
fromUsername: 'β‘ FireTech Bot',
fromAvatar: null,
to: socket.userId,
toUsername: fromUser.username,
content: getBotResponse(content),
mediaType: 'text',
mediaUrl: null,
isBot: true,
timestamp: new Date().toISOString()
};
setTimeout(() => {
emitToUser(socket.userId, 'dm message', botPayload);
}, 350 + Math.floor(Math.random() * 500));
return;
}
const toUser = await User.findByPk(toUserId);
if (!toUser) {
socket.emit('error', 'User not found');
return;
}
const dm = await DirectMessage.create({
messageId: uuidv4(),
fromId: socket.userId,
toId: toUserId,
fromUsername: fromUser.username,
toUsername: toUser.username,
content,
mediaType: mediaType || 'text',
mediaUrl: mediaUrl || null
});
const dmPayload = {
messageId: dm.messageId,
from: socket.userId,
fromUsername: fromUser.username,
fromAvatar: fromUser.avatar,
to: toUserId,
toUsername: toUser.username,
content: dm.content,
mediaType: dm.mediaType,
mediaUrl: dm.mediaUrl,
timestamp: dm.createdAt
};
emitToUser(socket.userId, 'dm message', dmPayload);
const deliveredToRecipient = emitToUser(toUserId, 'dm message', dmPayload);
if (deliveredToRecipient === 0) {
socket.emit('dm delivery status', {
messageId: dm.messageId,
toUserId,
delivered: false
});
}
const rawContent = String(content || '').trim();
const askBot = rawContent.toLowerCase().startsWith('/firetech') || rawContent.toLowerCase().startsWith('@firetech');
if (askBot) {
const botPayload = {
messageId: uuidv4(),
from: 'bot_firetech_0',
fromUsername: 'β‘ FireTech Bot',
fromAvatar: null,
to: toUserId,
toUsername: toUser.username,
content: getBotResponse(rawContent),
mediaType: 'text',
mediaUrl: null,
isBot: true,
timestamp: new Date().toISOString()
};
setTimeout(() => {
emitToUser(socket.userId, 'dm message', botPayload);
emitToUser(toUserId, 'dm message', botPayload);
}, 400 + Math.floor(Math.random() * 600));
}
} catch (error) {
socket.emit('error', error.message);
}
});
socket.on('dm typing', (friendId) => {
const roomId = [socket.userId, friendId].sort().join('_');
socket.broadcast.to(roomId).emit('dm user typing', {
userId: socket.userId,
username: socket.username
});
});
socket.on('dm stop typing', (friendId) => {
const roomId = [socket.userId, friendId].sort().join('_');
socket.broadcast.to(roomId).emit('dm user stop typing', {
userId: socket.userId,
username: socket.username
});
});
socket.on('community typing', (data) => {
const roomName = data?.community;
if (!roomName) return;
const roomKey = normalizeRoomKey('community', roomName);
socket.broadcast.to(roomKey).emit('community user typing', {
community: roomName,
userId: socket.userId,
username: socket.username
});
});
socket.on('community stop typing', (data) => {
const roomName = data?.community;
if (!roomName) return;
const roomKey = normalizeRoomKey('community', roomName);
socket.broadcast.to(roomKey).emit('community user stop typing', {
community: roomName,
userId: socket.userId,
username: socket.username
});
});
socket.on('room typing', (data) => {
const roomName = data?.roomName || data?.roomId;
if (!roomName) return;
const roomType = data?.roomType || 'group';
const roomKey = normalizeRoomKey(roomType, roomName);
socket.broadcast.to(roomKey).emit('room user typing', {
roomType,
roomId: roomName,
userId: socket.userId,
username: socket.username
});
});
socket.on('room stop typing', (data) => {
const roomName = data?.roomName || data?.roomId;
if (!roomName) return;
const roomType = data?.roomType || 'group';
const roomKey = normalizeRoomKey(roomType, roomName);
socket.broadcast.to(roomKey).emit('room user stop typing', {
roomType,
roomId: roomName,
userId: socket.userId,
username: socket.username
});
});
socket.on('join room chat', async (data) => {
const roomType = data?.roomType;
const roomName = data?.roomName;
if (!roomType || !roomName) return;
const roomKey = normalizeRoomKey(roomType, roomName);
if (socket.currentRoomKey && socket.currentRoomKey !== roomKey) {
if (socket.currentRoomMeta) {
removeRoomMember(socket.currentRoomMeta.roomType, socket.currentRoomMeta.roomName, socket.id);
}
socket.leave(socket.currentRoomKey);
}
socket.join(roomKey);
socket.currentRoomKey = roomKey;
socket.currentRoomMeta = { roomType, roomName };
upsertRoomMember(roomType, roomName, socket);
const roomProfile = getOrCreateRoomProfile(roomType, roomName);
socket.emit('room profile updated', {
roomType,
roomName,
previousRoomName: roomName,
profile: roomProfile
});
let history = getRoomMessages(roomType, roomName);
try {
history = await loadRoomMessagesFromDb(roomType, roomName, 180);
roomMessages.set(roomKey, history);
} catch (error) {
console.warn('Failed loading DB room history:', error.message);
}
socket.emit('room chat history', {
roomType,
roomName,
messages: history
});
});
socket.on('leave room chat', (data) => {
const roomType = data?.roomType;
const roomName = data?.roomName;
if (!roomType || !roomName) return;
const roomKey = normalizeRoomKey(roomType, roomName);
socket.leave(roomKey);
removeRoomMember(roomType, roomName, socket.id);
if (socket.currentRoomKey === roomKey) {
socket.currentRoomKey = null;
socket.currentRoomMeta = null;
}
});
socket.on('set room role', (data) => {
const roomType = data?.roomType;
const roomName = data?.roomName;
const targetUserId = data?.targetUserId;
const nextRoleRaw = String(data?.role || '').trim();
const nextRole = ['Owner', 'Admin', 'Member'].includes(nextRoleRaw) ? nextRoleRaw : null;
if (!roomType || !roomName || !targetUserId || !nextRole) return;
const roomKey = normalizeRoomKey(roomType, roomName);
const rolesByUser = roomRoles.get(roomKey);
if (!rolesByUser) return;
const actorRole = rolesByUser.get(String(socket.userId));
if (actorRole !== 'Owner' && actorRole !== 'Admin') {
socket.emit('error', 'Only Owner/Admin can change roles');
return;
}
if (actorRole === 'Admin' && nextRole === 'Owner') {
socket.emit('error', 'Admin cannot assign Owner role');
return;
}
rolesByUser.set(String(targetUserId), nextRole);
const membersBySocket = roomMembers.get(roomKey);
if (membersBySocket) {
for (const [memberSocketId, member] of membersBySocket.entries()) {
if (String(member.userId) === String(targetUserId)) {
member.role = nextRole;
membersBySocket.set(memberSocketId, member);
}
}
}
emitRoomMembersUpdate(roomType, roomName);
});
socket.on('update room profile', (data) => {
const roomType = data?.roomType;
const roomName = String(data?.roomName || '').trim();
const patch = data?.profilePatch || {};
if (!roomType || !roomName) return;
const roomKey = normalizeRoomKey(roomType, roomName);
const meta = getOrCreateRoomMeta(roomType, roomName, socket.userId);
if (!meta.creatorId) {
meta.creatorId = String(socket.userId);
}
let rolesByUser = roomRoles.get(roomKey);
if (!rolesByUser) {
rolesByUser = new Map();
rolesByUser.set(String(socket.userId), 'Owner');
roomRoles.set(roomKey, rolesByUser);
}
const actorRole = rolesByUser.get(String(socket.userId));
let effectiveRole = actorRole;
if (roomType === 'group' && !effectiveRole) {
effectiveRole = 'Owner';
rolesByUser.set(String(socket.userId), effectiveRole);
}
if (effectiveRole !== 'Owner' && effectiveRole !== 'Admin') {
socket.emit('error', roomType === 'group'
? 'Only Owner or Admin can edit group appearance'
: 'Only Leader/Vice Leader can edit room appearance');
return;
}
if (effectiveRole === 'Owner' || effectiveRole === 'Admin') {
meta.contributorIds.add(String(socket.userId));
meta.updatedAt = new Date().toISOString();
}
const safeName = String(patch?.name || '').trim();
const safeIcon = typeof patch?.icon === 'string' ? patch.icon.trim().slice(0, 4) : null;
const safeImage = typeof patch?.image === 'string' ? patch.image : null;
let nextRoomName = roomName;
if (safeName) {
nextRoomName = safeName;
renameRoomState(roomType, roomName, nextRoomName);
}
const profile = getOrCreateRoomProfile(roomType, nextRoomName);
if (safeName) profile.name = safeName;
if (safeIcon !== null) profile.icon = safeIcon;
if (safeImage !== null) profile.image = safeImage;
const nextRoomKey = normalizeRoomKey(roomType, nextRoomName);
roomProfiles.set(nextRoomKey, profile);
emitRoomProfileUpdate(roomType, nextRoomName, profile, roomName);
emitRoomMembersUpdate(roomType, nextRoomName);
});
socket.on('send room message', async (data) => {
const roomType = data?.roomType;
const roomName = data?.roomName;
if (!roomType || !roomName) return;
const roomKey = normalizeRoomKey(roomType, roomName);
const messagePayload = {
messageId: uuidv4(),
from: socket.userId,
fromUsername: socket.username,
fromAvatar: socket.userAvatar || null,
content: data?.content || '',
mediaType: data?.mediaType || 'text',
mediaUrl: data?.mediaUrl || null,
roomType,
roomName,
timestamp: new Date().toISOString()
};
appendRoomMessage(roomType, roomName, messagePayload);
try {
await Message.create({
messageId: messagePayload.messageId,
channelId: roomKey,
senderId: socket.userId,
senderUsername: socket.username,
content: messagePayload.content,
mediaType: messagePayload.mediaType,
mediaUrl: messagePayload.mediaUrl || null
});
} catch (error) {
console.warn('Failed persisting room message:', error.message);
}
io.to(roomKey).emit('room message', messagePayload);
const rawContent = String(data?.content || '').trim();
const askBot = rawContent.toLowerCase().startsWith('/firetech') || rawContent.toLowerCase().startsWith('@firetech');
if (askBot) {
const botPayload = {
messageId: uuidv4(),
from: 'bot_firetech_0',
fromUsername: 'β‘ FireTech Bot',
fromAvatar: null,
content: getBotResponse(rawContent),
mediaType: 'text',
mediaUrl: null,
roomType,
roomName,
isBot: true,
timestamp: new Date().toISOString()
};
setTimeout(() => {
appendRoomMessage(roomType, roomName, botPayload);
io.to(roomKey).emit('room message', botPayload);
}, 500 + Math.floor(Math.random() * 800));
}
});
socket.on('clear room chat', (data) => {
const roomType = data?.roomType;
const roomName = data?.roomName;
if (!roomType || !roomName) return;
const roomKey = normalizeRoomKey(roomType, roomName);
roomMessages.set(roomKey, []);
Message.destroy({ where: { channelId: roomKey } }).catch(() => {});
io.to(roomKey).emit('room chat cleared', { roomType, roomName, clearedBy: socket.userId });
});
socket.on('send friend request', async (data) => {
try {
const toUserId = data?.toUserId;
if (!toUserId) {
socket.emit('error', 'Target user is required');
return;
}
if (String(toUserId) === String(socket.userId)) {
socket.emit('error', 'Cannot send request to yourself');
return;
}
const targetUser = await User.findByPk(toUserId);
if (!targetUser) {
socket.emit('error', 'User not found');
return;
}
const fromUser = await User.findByPk(socket.userId);
const existingFriend = await fromUser.getFriends({ where: { id: toUserId } });
if (existingFriend.length > 0) {
socket.emit('error', 'Already friends');
return;
}
const existingPending = await FriendRequest.findOne({
where: {
status: 'pending',
[Op.or]: [
{ fromId: socket.userId, toId: toUserId },
{ fromId: toUserId, toId: socket.userId }
]
}
});
if (existingPending) {
socket.emit('error', 'Friend request already pending');
return;
}
const newRequest = await FriendRequest.create({ fromId: socket.userId, toId: toUserId });
socket.emit('friend request sent', { requestId: newRequest.id, toUserId });
emitToUser(toUserId, 'friend request received', {
requestId: newRequest.id,
fromId: socket.userId,
fromUsername: socket.username,
fromAvatar: socket.userAvatar || null
});
} catch (error) {
socket.emit('error', error.message);
}
});
socket.on('start video call', async (data) => {
try {
const targetId = data?.targetId;
if (!targetId) {
socket.emit('error', 'Call target is required');
return;
}
const targetUser = await User.findByPk(targetId);
if (!targetUser) {
socket.emit('error', 'User not found');
return;
}
const callId = uuidv4();
const payload = {
callId,
fromId: socket.userId,
fromUsername: socket.username,
fromAvatar: socket.userAvatar || null,
toId: targetId,
type: data?.type || 'dm',
startedAt: new Date().toISOString()
};
const deliveredToTarget = emitToUser(targetId, 'incoming video call', payload);
socket.emit('video call ringing', {
...payload,
deliveredToTarget: deliveredToTarget > 0
});
if (deliveredToTarget === 0) {
socket.emit('video call unavailable', {
callId,
targetId,
message: 'User is currently offline or not connected.'
});
}
} catch (error) {
socket.emit('error', error.message);
}
});
socket.on('accept video call', (data) => {
const callId = data?.callId;
const targetCallerId = data?.toId;
if (!callId || !targetCallerId) return;
emitToUser(targetCallerId, 'video call accepted', {
callId,
byUserId: socket.userId,
byUsername: socket.username,
acceptedAt: new Date().toISOString()
});
});
socket.on('reject video call', (data) => {
const callId = data?.callId;
const targetCallerId = data?.toId;
if (!callId || !targetCallerId) return;
emitToUser(targetCallerId, 'video call rejected', {
callId,
byUserId: socket.userId,
byUsername: socket.username,
rejectedAt: new Date().toISOString()
});
});
socket.on('end video call', (data) => {
const callId = data?.callId;
const peerUserId = data?.toId;
if (!callId || !peerUserId) return;
emitToUser(peerUserId, 'video call ended', {
callId,
byUserId: socket.userId,
byUsername: socket.username,
endedAt: new Date().toISOString()
});
});
socket.on('video signal', (data) => {
const toId = data?.toId;
const signal = data?.signal;
if (!toId || !signal) return;
emitToUser(toId, 'video signal', {
fromId: socket.userId,
fromUsername: socket.username,
callId: data?.callId || null,
signal
});
});
socket.on('disconnect', async () => {
try {
const userData = onlineUsers.get(socket.id);
if (userData) {
const user = await User.findByPk(socket.userId);
if (user) {
user.status = 'offline';
await user.save();
}
onlineUsers.delete(socket.id);
if (socket.currentRoomMeta) {
removeRoomMember(socket.currentRoomMeta.roomType, socket.currentRoomMeta.roomName, socket.id);
}
emitUsersUpdate();
}
} catch (error) {
console.error(error);
}
});
});
function getLocalNetworkAddress() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const net of interfaces[name]) {
if (net.family === 'IPv4' && !net.internal) {
return net.address;
}
}
}
return '127.0.0.1';
}
async function migrateMediaTypeEnum() {
try {
const [results] = await sequelize.query(`
SELECT EXISTS (
SELECT 1 FROM pg_type t
JOIN pg_enum e ON t.oid = e.enumtypid
WHERE t.typname = 'enum_DirectMessages_mediaType'
AND e.enumlabel = 'voice'
) as has_voice;
`);
if (!results[0].has_voice) {
console.log('π¦ Migrating mediaType ENUM to include sticker, gif, voice...');
await sequelize.query(`
ALTER TYPE "enum_DirectMessages_mediaType" ADD VALUE IF NOT EXISTS 'sticker';
ALTER TYPE "enum_DirectMessages_mediaType" ADD VALUE IF NOT EXISTS 'gif';
ALTER TYPE "enum_DirectMessages_mediaType" ADD VALUE IF NOT EXISTS 'voice';
`);
await sequelize.query(`
ALTER TYPE "enum_Messages_mediaType" ADD VALUE IF NOT EXISTS 'sticker';
ALTER TYPE "enum_Messages_mediaType" ADD VALUE IF NOT EXISTS 'gif';
ALTER TYPE "enum_Messages_mediaType" ADD VALUE IF NOT EXISTS 'voice';
`);
console.log('β
ENUM migration complete!');
} else {
console.log('β
mediaType ENUM already up to date');
}
} catch (error) {
console.log('βΉοΈ ENUM migration skipped (likely first run or different DB)');
}
}
async function seedShopItems() {
const existingCount = await ShopItem.count();
if (existingCount > 0) return;
await ShopItem.bulkCreate(DEFAULT_SHOP_ITEMS);
}
const DEFAULT_SHOP_ITEMS = [
{ itemId: 'banner_neon', name: 'Neon Banner Effect', description: 'Animated neon gradient banner for your profile.', price: 450, category: 'Banners', image: '' },
{ itemId: 'badge_founder', name: 'Founder Badge', description: 'Exclusive badge shown next to your username.', price: 320, category: 'Badges', image: '' },
{ itemId: 'color_pack_burst', name: 'Color Burst Pack', description: 'Unlock vibrant accent color themes.', price: 380, category: 'Themes', image: '' },
{ itemId: 'chat_fx_glow', name: 'Message Glow FX', description: 'Subtle glow animation for sent messages.', price: 260, category: 'Effects', image: '' },
{ itemId: 'avatar_ring_aura', name: 'Aura Avatar Ring', description: 'Premium animated ring around your avatar.', price: 520, category: 'Avatar', image: '' },
{ itemId: 'nameplate_crystal', name: 'Crystal Nameplate', description: 'Polished nameplate style in member list.', price: 410, category: 'Nameplates', image: '' },
{ itemId: 'theme_midnight', name: 'Midnight Theme Pack', description: 'Elegant dark gradients and UI accents.', price: 290, category: 'Themes', image: '' },
{ itemId: 'emoji_pack_pro', name: 'Pro Emoji Pack', description: 'Premium emoji reactions collection.', price: 210, category: 'Emotes', image: '' }
];
async function ensureShopItemsAvailable() {
let items = await ShopItem.findAll();
if (items.length > 0) return items;
await ShopItem.bulkCreate(DEFAULT_SHOP_ITEMS);
items = await ShopItem.findAll();
return items;
}
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';
syncDatabaseWithRetry().then(async () => {
await migrateMediaTypeEnum();
await seedShopItems();
server.listen(PORT, HOST, () => {
const networkAddress = getLocalNetworkAddress();
console.log(`
βββββββββββββββββββββββββββββββββββββββββ
β π Discord-Like Server Running β
β β
β π‘ Local: ${protocol}://localhost:${PORT} β
β π LAN: ${protocol}://${networkAddress}:${PORT} β
β β¨ Status: Online & Ready β
β β
β Features: β
β β User Authentication β
β β Profiles & Friends β
β β Text & Voice Channels β
β β Media Sharing β
β β Shop System β
β β Real-time Messaging β
β β PostgreSQL Database β
β β
βββββββββββββββββββββββββββββββββββββββββ
`);
});
}).catch(err => {
console.error('Database startup error:', err);
process.exit(1);
});
|