-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
144 lines (116 loc) · 4.33 KB
/
server.js
File metadata and controls
144 lines (116 loc) · 4.33 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
const { Server } = require('socket.io')
const { createServer } = require('http')
const { initDatabase, getUser, updateBalance, createTransaction, addToEscrow, getBalance, saveMessage, getUserMessages, getUnreadCount } = require('./lib/database')
const httpServer = createServer()
const io = new Server(httpServer, {
cors: {
origin: [
'http://localhost:3000',
'http://localhost:5173',
'http://localhost:8080',
'http://localhost:8081',
'https://sunerichat.netlify.app',
'https://sunerichat.onrender.com'
],
methods: ['GET', 'POST']
}
})
// Initialize database (now JSON-based)
let db = initDatabase()
// Store connected users: Map<npub, socketId>
const users = new Map()
io.on('connection', (socket) => {
console.log('User connected:', socket.id)
const userNpub = socket.handshake.query.userNpub
if (userNpub) {
users.set(userNpub, socket.id)
console.log('User registered:', userNpub)
// Verify user exists before sending data
const user = getUser(db, userNpub)
if (!user) {
console.log('User not found in database:', userNpub)
socket.emit('error', { message: 'User not found' })
return
}
// Send current balance
console.log('Sending balance to user:', user.balance)
socket.emit('balance-update', user.balance)
// Send unread count
const unreadCount = getUnreadCount(db, userNpub)
socket.emit('unread-count', unreadCount)
// Send all messages for this user
const userMessages = getUserMessages(db, userNpub)
socket.emit('message-history', userMessages)
}
socket.on('send-message', async (message) => {
console.log('Message received:', message)
try {
// Reload database to get latest state
db = initDatabase()
// Check sender's balance
const senderBalance = getBalance(db, message.sender)
if (senderBalance < message.amount) {
socket.emit('error', { message: 'Insufficient sunc balance' })
return
}
// Deduct sunc from sender and add to recipient
updateBalance(db, message.sender, -message.amount)
updateBalance(db, message.recipient, message.amount)
// Create transaction record
createTransaction(db, {
from: message.sender,
to: message.recipient,
amount: message.amount,
type: 'message_payment',
message_id: message.id
})
// Save message to database
saveMessage(db, { ...message, read: false })
console.log(`Deducted ${message.amount} sunc from ${message.sender}`)
// Send updated balance to sender
const newBalance = getBalance(db, message.sender)
socket.emit('balance-update', newBalance)
// Broadcast to recipient if online
const recipientSocketId = users.get(message.recipient)
if (recipientSocketId) {
io.to(recipientSocketId).emit('new-message', message)
// Send updated unread count to recipient
const unreadCount = getUnreadCount(db, message.recipient)
io.to(recipientSocketId).emit('unread-count', unreadCount)
// Also update recipient's balance display
const recipientBalance = getBalance(db, message.recipient)
io.to(recipientSocketId).emit('balance-update', recipientBalance)
}
// Don't echo back to sender - they'll see it in their sent messages
} catch (error) {
console.error('Error processing message:', error)
socket.emit('error', { message: 'Failed to process payment' })
}
})
// Handle user updates (price change, username change)
socket.on('user-updated', (updatedUser) => {
console.log('User updated:', updatedUser.npub, updatedUser)
// Broadcast to all connected clients
io.emit('user-price-updated', updatedUser)
})
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id)
// Remove user from active users
for (const [npub, socketId] of users.entries()) {
if (socketId === socket.id) {
users.delete(npub)
break
}
}
})
})
const PORT = 3001
httpServer.listen(PORT, () => {
console.log(`WebSocket server running on port ${PORT}`)
console.log('Database initialized (JSON-based)')
})
// Cleanup on exit
process.on('SIGINT', () => {
console.log('Shutting down...')
process.exit()
})