tshare 1.0.5

Share your terminal session with anyone through a simple web link
Documentation
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
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>TShare - Terminal Session {{ session_id }}</title>
        <script src="https://unpkg.com/xterm@5.3.0/lib/xterm.js"></script>
        <script src="https://unpkg.com/xterm-addon-fit@0.8.0/lib/xterm-addon-fit.js"></script>
        <link href="https://unpkg.com/xterm@5.3.0/css/xterm.css" rel="stylesheet">
        <script src="https://cdn.tailwindcss.com"></script>
        <style>
        .terminal-container {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
        }
        .glass-effect {
            backdrop-filter: blur(10px);
            background: rgba(255, 255, 255, 0.1);
        }
        </style>
    </head>
    <body class="bg-gray-900 text-white font-sans">
        <div id="auth-modal"
             class="{{ modal_display }} fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-75">
            <div class="bg-gray-800 p-8 rounded-lg shadow-2xl max-w-md w-full mx-4">
                <h2 class="text-2xl font-bold mb-6 text-center bg-gradient-to-r from-green-400 to-blue-500 bg-clip-text text-transparent">
                    Join Terminal Session
                </h2>
                <p class="text-gray-300 text-center mb-6">Session ID: {{ session_id }}</p>
                <div class="space-y-4">
                    <input type="password"
                           id="password-input"
                           placeholder="Enter password (leave empty if none)"
                           class="w-full p-3 bg-gray-700 border border-gray-600 rounded focus:border-blue-500 focus:outline-none">
                    <div id="auth-error" class="text-red-400 text-sm hidden"></div>
                    <button id="connect-btn"
                            class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-4 rounded transition duration-200">
                        Connect
                    </button>
                </div>
            </div>
        </div>
        <div id="terminal-container"
             class="{{ terminal_display }} min-h-screen bg-gray-900 text-white">
            <div class="p-6">
                <div class="mb-6 bg-gray-800 rounded-lg p-4 shadow-lg">
                    <div class="grid grid-cols-3 items-start">
                        <div>
                            <h1 class="text-2xl font-bold bg-gradient-to-r from-green-400 to-blue-500 bg-clip-text text-transparent">
                                Terminal Session
                            </h1>
                            <p class="text-sm text-gray-400 mt-1">Session ID: {{ session_id }}</p>
                            <div class="flex items-center gap-3 mt-2">
                                <div class="text-xs px-2 py-1 rounded bg-blue-600 text-white"
                                     id="user-type-badge">Guest</div>
                                <div class="text-xs px-2 py-1 rounded bg-green-600 text-white hidden"
                                     id="readonly-badge">Read-only</div>
                            </div>
                        </div>
                        <!-- Connected Users Dropdown - Center -->
                        <div class="relative flex justify-center">
                            <button id="users-dropdown-btn"
                                    class="bg-gray-700 hover:bg-gray-600 text-white px-3 py-2 rounded-lg transition duration-200 flex items-center gap-2 text-sm">
                                <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                                    <path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3z" />
                                </svg>
                                <span id="users-count">Loading...</span>
                                <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                                </svg>
                            </button>
                            <div id="users-dropdown"
                                 class="hidden absolute top-full mt-2 left-1/2 transform -translate-x-1/2 bg-gray-800 rounded-lg shadow-xl border border-gray-600 min-w-48 z-50">
                                <div class="p-2 border-b border-gray-600">
                                    <div class="text-sm font-medium text-gray-300">Connected Users</div>
                                </div>
                                <div id="users-list" class="p-2">
                                    <div class="text-sm text-gray-400">Loading...</div>
                                </div>
                            </div>
                        </div>
                        <div class="flex items-center gap-4 justify-end">
                            <div class="flex items-center space-x-3">
                                <div class="w-2 h-2 rounded-full bg-red-400" id="status-indicator"></div>
                                <div id="status" class="text-sm font-medium text-red-400">Disconnected</div>
                            </div>
                            <!-- Logout button placeholder -->
                            <button id="logout-btn"
                                    class="hidden text-xs px-3 py-1 bg-red-600 hover:bg-red-700 text-white rounded transition duration-200">
                                Logout
                            </button>
                        </div>
                    </div>
                </div>
                <div class="bg-gray-800 rounded-lg p-4 shadow-xl border border-gray-700">
                    <div id="terminal"
                         class="bg-black rounded border border-gray-600"
                         style="width: 100%;
                                height: calc(100vh - 280px);
                                min-height: 400px"></div>
                </div>
            </div>
        </div>
        <script>
        const sessionId = '{{ session_id }}';
        const needsAuth = {{ needs_auth_js }};
        let term = null;
        let ws = null;
        let sessionEnded = false;
        let historyReceived = false;
        let userType = 'guest';
        let isReadonly = false;
        let usersRefreshInterval = null;
        let usersCountInterval = null;
        let currentUserId = null;
        let heartbeatInterval = null;

        const authModal = document.getElementById('auth-modal');
        const terminalContainer = document.getElementById('terminal-container');
        const passwordInput = document.getElementById('password-input');
        const connectBtn = document.getElementById('connect-btn');
        const authError = document.getElementById('auth-error');
        const status = document.getElementById('status');
        const statusIndicator = document.getElementById('status-indicator');
        const userTypeBadge = document.getElementById('user-type-badge');
        const readonlyBadge = document.getElementById('readonly-badge');
        const usersDropdownBtn = document.getElementById('users-dropdown-btn');
        const usersDropdown = document.getElementById('users-dropdown');
        const usersCount = document.getElementById('users-count');
        const usersList = document.getElementById('users-list');
        const logoutBtn = document.getElementById('logout-btn');

        async function authenticate() {
            const password = passwordInput.value || '';
            
            // Show loading state
            connectBtn.disabled = true;
            const originalText = connectBtn.textContent;
            connectBtn.innerHTML = `
                <svg class="animate-spin h-4 w-4 text-white inline mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                Connecting...
            `;
            
            try {
                const response = await fetch(`/api/auth/${sessionId}?password=${encodeURIComponent(password)}`);
                const result = await response.json();
                
                if (result.authenticated) {
                    userType = result.user_type || 'guest';
                    isReadonly = result.is_readonly || false;
                    
                    console.log('Authenticated as:', userType, 'readonly:', isReadonly);
                    updateStatusBadges();
                    showLogoutButton();
                    authModal.style.display = 'none';
                    terminalContainer.style.display = 'block';
                    initializeTerminal();
                    startUsersCountPolling();
                } else {
                    authError.textContent = 'Invalid password';
                    authError.classList.remove('hidden');
                }
            } catch (e) {
                authError.textContent = 'Authentication failed';
                authError.classList.remove('hidden');
            } finally {
                // Reset button state
                connectBtn.disabled = false;
                connectBtn.textContent = originalText;
            }
        }

        function updateStatusBadges() {
            // Update user type badge
            userTypeBadge.textContent = userType.charAt(0).toUpperCase() + userType.slice(1);
            
            if (userType === 'owner') {
                userTypeBadge.className = 'text-xs px-2 py-1 rounded bg-purple-600 text-white';
            } else {
                userTypeBadge.className = 'text-xs px-2 py-1 rounded bg-blue-600 text-white';
            }
            
            // Update readonly badge
            if (isReadonly) {
                readonlyBadge.classList.remove('hidden');
                readonlyBadge.className = 'text-xs px-2 py-1 rounded bg-orange-600 text-white';
            } else {
                readonlyBadge.classList.add('hidden');
            }
        }

        function showLogoutButton() {
            logoutBtn.classList.remove('hidden');
        }

        function hideLogoutButton() {
            logoutBtn.classList.add('hidden');
        }

        async function logout() {
            try {
                await fetch('/api/logout', { method: 'POST' });
                
                // Reset state
                userType = 'guest';
                isReadonly = false;
                hideLogoutButton();
                
                // Stop polling
                stopUsersCountPolling();
                
                // Clean up terminal
                cleanupTerminal(true);
                
                // Go back to auth modal if needed
                if (needsAuth) {
                    terminalContainer.style.display = 'none';
                    authModal.style.display = 'flex';
                    passwordInput.value = '';
                    authError.classList.add('hidden');
                }
                
                // Close websocket
                if (ws) {
                    ws.close();
                }
                
                console.log('Logged out successfully');
            } catch (e) {
                console.error('Logout failed:', e);
            }
        }

        async function fetchConnectedUsers() {
            try {
                const response = await fetch(`/api/session/${sessionId}/users`);
                if (response.ok) {
                    const users = await response.json();
                    updateUsersDisplay(users);
                } else {
                    console.error('Failed to fetch connected users');
                    usersCount.textContent = 'Error';
                }
            } catch (e) {
                console.error('Error fetching connected users:', e);
                usersCount.textContent = 'Error';
            }
        }

        function startUsersCountPolling() {
            // Poll user count every 3 seconds
            usersCountInterval = setInterval(fetchConnectedUsers, 3000);
            // Fetch immediately
            fetchConnectedUsers();
        }

        function stopUsersCountPolling() {
            if (usersCountInterval) {
                clearInterval(usersCountInterval);
                usersCountInterval = null;
            }
        }

        async function sendHeartbeat() {
            if (currentUserId) {
                try {
                    await fetch(`/api/session/${sessionId}/heartbeat/${currentUserId}`, {
                        method: 'POST'
                    });
                } catch (e) {
                    console.error('Failed to send heartbeat:', e);
                }
            }
        }

        function startHeartbeat() {
            // Send heartbeat every 5 seconds
            heartbeatInterval = setInterval(sendHeartbeat, 5000);
        }

        function stopHeartbeat() {
            if (heartbeatInterval) {
                clearInterval(heartbeatInterval);
                heartbeatInterval = null;
            }
        }

        function updateUsersDisplay(users) {
            // Count users by type
            const ownerCount = users.filter(u => u.user_type === 'owner').length;
            const guestCount = users.filter(u => u.user_type === 'guest').length;
            
            // Update button text
            const totalCount = users.length;
            if (totalCount === 0) {
                usersCount.textContent = 'No users connected';
            } else if (totalCount === 1) {
                usersCount.textContent = '1 user connected';
            } else {
                usersCount.textContent = `${totalCount} users connected`;
            }
            
            // Update dropdown list
            usersList.innerHTML = '';
            
            if (users.length === 0) {
                const emptyDiv = document.createElement('div');
                emptyDiv.className = 'text-sm text-gray-400';
                emptyDiv.textContent = 'No users connected';
                usersList.appendChild(emptyDiv);
            } else {
                // Show owner first
                if (ownerCount > 0) {
                    const ownerDiv = document.createElement('div');
                    ownerDiv.className = 'flex items-center gap-2 py-1 text-sm';
                    ownerDiv.innerHTML = `
                        <div class="w-2 h-2 rounded-full bg-purple-400"></div>
                        <span class="text-purple-300">Owner connected</span>
                    `;
                    usersList.appendChild(ownerDiv);
                }
                
                // Show guests with smart numbering (lowest available numbers)
                const guests = users.filter(u => u.user_type === 'guest');
                const usedNumbers = new Set();
                const guestNumbers = [];
                
                // Assign lowest available numbers
                guests.forEach((guest, index) => {
                    let number = 1;
                    while (usedNumbers.has(number)) {
                        number++;
                    }
                    usedNumbers.add(number);
                    guestNumbers.push(number);
                });
                
                guests.forEach((guest, index) => {
                    const guestDiv = document.createElement('div');
                    guestDiv.className = 'flex items-center gap-2 py-1 text-sm';
                    guestDiv.innerHTML = `
                        <div class="w-2 h-2 rounded-full bg-blue-400"></div>
                        <span class="text-blue-300">Guest ${guestNumbers[index]}</span>
                    `;
                    usersList.appendChild(guestDiv);
                });
            }
        }

        function toggleUsersDropdown() {
            usersDropdown.classList.toggle('hidden');
            if (!usersDropdown.classList.contains('hidden')) {
                fetchConnectedUsers();
                // Refresh user list every 2 seconds while dropdown is open
                usersRefreshInterval = setInterval(fetchConnectedUsers, 2000);
            } else {
                // Stop refreshing when dropdown is closed
                if (usersRefreshInterval) {
                    clearInterval(usersRefreshInterval);
                    usersRefreshInterval = null;
                }
            }
        }

        // Close dropdown when clicking outside
        document.addEventListener('click', function(event) {
            if (!usersDropdownBtn.contains(event.target) && !usersDropdown.contains(event.target)) {
                usersDropdown.classList.add('hidden');
                // Stop refreshing when dropdown is closed
                if (usersRefreshInterval) {
                    clearInterval(usersRefreshInterval);
                    usersRefreshInterval = null;
                }
            }
        });

        function cleanupTerminal(resetStatus = true) {
            // Close websocket if open
            if (ws) {
                ws.close();
                ws = null;
            }
            
            // Clear terminal if it exists
            if (term) {
                term.dispose();
                term = null;
            }
            
            // Clear the terminal container
            const terminalElement = document.getElementById('terminal');
            if (terminalElement) {
                terminalElement.innerHTML = '';
            }
            
            // Clear all intervals
            if (usersRefreshInterval) {
                clearInterval(usersRefreshInterval);
                usersRefreshInterval = null;
            }
            
            stopHeartbeat();
            
            // Reset flags
            sessionEnded = false;
            historyReceived = false;
            
            // Only reset status if requested (not during re-initialization)
            if (resetStatus) {
                status.textContent = 'Disconnected';
                status.className = 'text-sm font-medium text-red-400';
                statusIndicator.className = 'w-2 h-2 rounded-full bg-red-400';
            }
            
            console.log('Terminal cleaned up');
        }

        function initializeTerminal() {
            // Clean up any existing terminal first (don't reset status during re-initialization)
            cleanupTerminal(false);
            term = new Terminal({
                theme: {
                    background: '#000000',
                    foreground: '#ffffff',
                    cursor: '#ffffff',
                    selection: '#ffffff33'
                },
                fontFamily: 'Monaco, "Cascadia Code", "SF Mono", Consolas, "Liberation Mono", Menlo, Courier, monospace',
                fontSize: 14,
                lineHeight: 1.2,
                cursorBlink: true,
                cursorStyle: 'block',
                allowTransparency: false
            });
            
            const fitAddon = new FitAddon.FitAddon();
            term.loadAddon(fitAddon);
            
            const terminalElement = document.getElementById('terminal');
            term.open(terminalElement);
            
            // Small delay to ensure DOM is ready, then fit
            setTimeout(() => {
                fitAddon.fit();
                sendTerminalSize();
                term.focus();
            }, 100);
            
            // Resize terminal when window resizes
            window.addEventListener('resize', () => {
                setTimeout(() => {
                    fitAddon.fit();
                    sendTerminalSize();
                }, 100);
            });
            
            // Send resize when terminal is manually resized
            term.onResize((size) => {
                sendTerminalSize();
            });
            
            connectWebSocket();
        }

        function sendTerminalSize() {
            if (ws && ws.readyState === WebSocket.OPEN) {
                const cols = term.cols;
                const rows = term.rows;
                const resizeMsg = JSON.stringify({
                    type: 'resize',
                    cols: cols,
                    rows: rows
                });
                ws.send(resizeMsg);
                console.log(`Sent terminal resize: ${cols}x${rows}`);
            }
        }

        function connectWebSocket() {
            // Reset status to connecting first
            status.textContent = 'Connecting...';
            status.className = 'text-sm font-medium text-yellow-400';
            statusIndicator.className = 'w-2 h-2 rounded-full bg-yellow-400';
            
            const wsUrl = `ws://${window.location.host}/ws/session/${sessionId}?user_type=${userType}`;
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function() {
                console.log('WebSocket connected');
                status.textContent = 'Connected';
                status.className = 'text-sm font-medium text-green-400';
                statusIndicator.className = 'w-2 h-2 rounded-full bg-green-400';
                
                // Send initial terminal size
                setTimeout(() => sendTerminalSize(), 200);
                
                term.onData(function(data) {
                    if (ws.readyState === WebSocket.OPEN) {
                        ws.send(new TextEncoder().encode(data));
                    }
                });
            };
            
            ws.onmessage = function(event) {
                // Handle text messages (control messages)
                if (typeof event.data === 'string') {
                    try {
                        const message = JSON.parse(event.data);
                        if (message.type === 'user_id') {
                            currentUserId = message.user_id;
                            console.log('Received user ID:', currentUserId);
                            startHeartbeat();
                            return;
                        }
                    } catch (e) {
                        // Not JSON, treat as terminal data
                        if (!historyReceived) {
                            term.clear();
                            historyReceived = true;
                            console.log('Received terminal history, cleared terminal and writing history');
                        }
                        term.write(event.data);
                    }
                } else if (event.data instanceof Blob) {
                    event.data.arrayBuffer().then(function(buffer) {
                        const text = new TextDecoder().decode(buffer);
                        // Check for session end marker
                        if (text === '__TSHARE_SESSION_ENDED__') {
                            console.log('Session ended signal received');
                            if (!sessionEnded) {
                                sessionEnded = true;
                                status.textContent = 'Session ended';
                                status.className = 'text-sm font-medium text-red-400';
                                statusIndicator.className = 'w-2 h-2 rounded-full bg-red-400';
                                term.write('\r\n\x1b[31mTerminal session has ended.\x1b[0m\r\n');
                            }
                            ws.close(1000, 'Session ended');
                            return;
                        }
                        
                        // If this is the first message and we haven't marked history as received,
                        // this is likely the history data. Clear terminal first.
                        if (!historyReceived) {
                            term.clear();
                            historyReceived = true;
                            console.log('Received terminal history, cleared terminal and writing history');
                        }
                        
                        term.write(text);
                    });
                }
            };
            
            ws.onclose = function(event) {
                console.log('WebSocket disconnected:', event.code, event.reason);
                if (!sessionEnded) {
                    status.textContent = event.code === 1000 ? 'Session ended' : 'Disconnected';
                    status.className = 'text-sm font-medium text-red-400';
                    statusIndicator.className = 'w-2 h-2 rounded-full bg-red-400';
                    
                    if (event.code === 1000) {
                        term.write('\r\n\x1b[31mTerminal session has ended.\x1b[0m\r\n');
                    }
                }
            };
            
            ws.onerror = function(error) {
                console.error('WebSocket error:', error);
                status.textContent = 'Error';
                status.className = 'text-sm font-medium text-red-400';
                statusIndicator.className = 'w-2 h-2 rounded-full bg-red-400';
            };
        }

        connectBtn.addEventListener('click', authenticate);
        passwordInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                authenticate();
            }
        });
        
        usersDropdownBtn.addEventListener('click', toggleUsersDropdown);
        logoutBtn.addEventListener('click', logout);

        // Cleanup on page unload
        window.addEventListener('beforeunload', function() {
            cleanupTerminal(true);
            stopUsersCountPolling();
            stopHeartbeat();
        });

        // Handle page visibility changes
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                // Page is hidden, stop polling to save resources
                stopUsersCountPolling();
            } else {
                // Page is visible again, restart polling if authenticated
                if (term && !sessionEnded) {
                    startUsersCountPolling();
                }
            }
        });

        // Auto-connect if no auth needed
        if (!needsAuth) {
            userType = 'owner'; // No auth means owner access
            isReadonly = false; // Owners are never readonly
            updateStatusBadges();
            showLogoutButton();
            authModal.style.display = 'none';
            terminalContainer.style.display = 'block';
            initializeTerminal();
            startUsersCountPolling();
        }
        </script>
    </body>
</html>