File size: 10,283 Bytes
eebf5c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * WebSocket Client برای اتصال بلادرنگ به سرور

 */

class CryptoWebSocketClient {
    constructor(url = null) {
        this.url = url || `ws://${window.location.host}/ws`;
        this.ws = null;
        this.sessionId = null;
        this.isConnected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 3000;
        this.messageHandlers = {};
        this.connectionCallbacks = [];
        
        this.connect();
    }
    
    connect() {
        try {
            console.log('🔌 اتصال به WebSocket:', this.url);
            this.ws = new WebSocket(this.url);
            
            this.ws.onopen = this.onOpen.bind(this);
            this.ws.onmessage = this.onMessage.bind(this);
            this.ws.onerror = this.onError.bind(this);
            this.ws.onclose = this.onClose.bind(this);
            
        } catch (error) {
            console.error('❌ خطا در اتصال WebSocket:', error);
            this.scheduleReconnect();
        }
    }
    
    onOpen(event) {
        console.log('✅ WebSocket متصل شد');
        this.isConnected = true;
        this.reconnectAttempts = 0;
        
        // فراخوانی callback‌ها
        this.connectionCallbacks.forEach(cb => cb(true));
        
        // نمایش وضعیت اتصال
        this.updateConnectionStatus(true);
    }
    
    onMessage(event) {
        try {
            const message = JSON.parse(event.data);
            const type = message.type;
            
            // مدیریت پیام‌های سیستمی
            if (type === 'welcome') {
                this.sessionId = message.session_id;
                console.log('📝 Session ID:', this.sessionId);
            }
            
            else if (type === 'stats_update') {
                this.handleStatsUpdate(message.data);
            }
            
            else if (type === 'provider_stats') {
                this.handleProviderStats(message.data);
            }
            
            else if (type === 'market_update') {
                this.handleMarketUpdate(message.data);
            }
            
            else if (type === 'price_update') {
                this.handlePriceUpdate(message.data);
            }
            
            else if (type === 'alert') {
                this.handleAlert(message.data);
            }
            
            else if (type === 'heartbeat') {
                // پاسخ به heartbeat
                this.send({ type: 'pong' });
            }
            
            // فراخوانی handler سفارشی
            if (this.messageHandlers[type]) {
                this.messageHandlers[type](message);
            }
            
        } catch (error) {
            console.error('❌ خطا در پردازش پیام:', error);
        }
    }
    
    onError(error) {
        console.error('❌ خطای WebSocket:', error);
        this.isConnected = false;
        this.updateConnectionStatus(false);
    }
    
    onClose(event) {
        console.log('🔌 WebSocket قطع شد');
        this.isConnected = false;
        this.sessionId = null;
        
        this.connectionCallbacks.forEach(cb => cb(false));
        this.updateConnectionStatus(false);
        
        // تلاش مجدد برای اتصال
        this.scheduleReconnect();
    }
    
    scheduleReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`🔄 تلاش مجدد برای اتصال (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`);
            
            setTimeout(() => {
                this.connect();
            }, this.reconnectDelay);
        } else {
            console.error('❌ تعداد تلاش‌های اتصال به پایان رسید');
            this.showReconnectButton();
        }
    }
    
    send(data) {
        if (this.isConnected && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(data));
        } else {
            console.warn('⚠️ WebSocket متصل نیست');
        }
    }
    
    subscribe(group) {
        this.send({
            type: 'subscribe',
            group: group
        });
    }
    
    unsubscribe(group) {
        this.send({
            type: 'unsubscribe',
            group: group
        });
    }
    
    requestStats() {
        this.send({
            type: 'get_stats'
        });
    }
    
    on(type, handler) {
        this.messageHandlers[type] = handler;
    }
    
    onConnection(callback) {
        this.connectionCallbacks.push(callback);
    }
    
    // ===== Handlers برای انواع پیام‌ها =====
    
    handleStatsUpdate(data) {
        // به‌روزرسانی نمایش تعداد کاربران
        const activeConnections = data.active_connections || 0;
        const totalSessions = data.total_sessions || 0;
        
        // به‌روزرسانی UI
        this.updateOnlineUsers(activeConnections, totalSessions);
        
        // آپدیت سایر آمار
        if (data.client_types) {
            this.updateClientTypes(data.client_types);
        }
    }
    
    handleProviderStats(data) {
        // به‌روزرسانی آمار Provider
        const summary = data.summary || {};
        
        // آپدیت نمایش
        if (window.updateProviderStats) {
            window.updateProviderStats(summary);
        }
    }
    
    handleMarketUpdate(data) {
        if (window.updateMarketData) {
            window.updateMarketData(data);
        }
    }
    
    handlePriceUpdate(data) {
        if (window.updatePrice) {
            window.updatePrice(data.symbol, data.price, data.change_24h);
        }
    }
    
    handleAlert(data) {
        this.showAlert(data.message, data.severity);
    }
    
    // ===== UI Updates =====
    
    updateConnectionStatus(connected) {
        const statusEl = document.getElementById('ws-connection-status');
        const statusDot = document.getElementById('ws-status-dot');
        const statusText = document.getElementById('ws-status-text');
        
        if (statusEl && statusDot && statusText) {
            if (connected) {
                statusDot.className = 'status-dot status-dot-online';
                statusText.textContent = 'متصل';
                statusEl.classList.add('connected');
                statusEl.classList.remove('disconnected');
            } else {
                statusDot.className = 'status-dot status-dot-offline';
                statusText.textContent = 'قطع شده';
                statusEl.classList.add('disconnected');
                statusEl.classList.remove('connected');
            }
        }
    }
    
    updateOnlineUsers(active, total) {
        const activeEl = document.getElementById('active-users-count');
        const totalEl = document.getElementById('total-sessions-count');
        const badgeEl = document.getElementById('online-users-badge');
        
        if (activeEl) {
            activeEl.textContent = active;
            // انیمیشن تغییر
            activeEl.classList.add('count-updated');
            setTimeout(() => activeEl.classList.remove('count-updated'), 500);
        }
        
        if (totalEl) {
            totalEl.textContent = total;
        }
        
        if (badgeEl) {
            badgeEl.textContent = active;
            badgeEl.classList.add('pulse');
            setTimeout(() => badgeEl.classList.remove('pulse'), 1000);
        }
    }
    
    updateClientTypes(types) {
        const listEl = document.getElementById('client-types-list');
        if (listEl && types) {
            const html = Object.entries(types).map(([type, count]) => 
                `<div class="client-type-item">

                    <span class="client-type-name">${type}</span>

                    <span class="client-type-count">${count}</span>

                </div>`
            ).join('');
            listEl.innerHTML = html;
        }
    }
    
    showAlert(message, severity = 'info') {
        // ساخت alert
        const alert = document.createElement('div');
        alert.className = `alert alert-${severity} alert-dismissible fade show`;
        alert.innerHTML = `

            <strong>${severity === 'error' ? '❌' : severity === 'warning' ? '⚠️' : 'ℹ️'}</strong>

            ${message}

            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>

        `;
        
        const container = document.getElementById('alerts-container') || document.body;
        container.appendChild(alert);
        
        // حذف خودکار بعد از 5 ثانیه
        setTimeout(() => {
            alert.classList.remove('show');
            setTimeout(() => alert.remove(), 300);
        }, 5000);
    }
    
    showReconnectButton() {
        const button = document.createElement('button');
        button.className = 'btn btn-warning reconnect-btn';
        button.innerHTML = '🔄 اتصال مجدد';
        button.onclick = () => {
            this.reconnectAttempts = 0;
            this.connect();
            button.remove();
        };
        
        const statusEl = document.getElementById('ws-connection-status');
        if (statusEl) {
            statusEl.appendChild(button);
        }
    }
    
    close() {
        if (this.ws) {
            this.ws.close();
        }
    }
}

// ایجاد instance سراسری
window.wsClient = null;

// اتصال خودکار
document.addEventListener('DOMContentLoaded', () => {
    try {
        window.wsClient = new CryptoWebSocketClient();
        console.log('✅ WebSocket Client آماده است');
    } catch (error) {
        console.error('❌ خطا در راه‌اندازی WebSocket Client:', error);
    }
});