File size: 17,827 Bytes
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{% extends "base.html" %}

{% block title %}Admin Dashboard - Telegram Stremio{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div class="mb-8 flex justify-between items-center">
        <div>
            <h1 class="text-3xl font-bold text-gray-900 dark:text-white">Admin Dashboard</h1>
            <p class="mt-2 text-sm text-gray-600 dark:text-gray-400">Monitor system health and manage flagged dead
                links.</p>
        </div>
    </div>

    <!-- System Health Section -->
    <div class="mb-10">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200">System Health</h2>
            <button onclick="clearCache()"
                class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium transition-colors shadow-sm flex items-center justify-center">
                <i class="fas fa-trash-alt mr-2"></i> Clear File Cache
            </button>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-6" id="stats-container">
            <!-- Cache Card -->
            <div class="theme-card rounded-xl border p-6 shadow-sm">
                <div class="flex items-center">
                    <div class="flex-shrink-0 bg-blue-100 dark:bg-blue-900/30 p-3 rounded-lg">
                        <i class="fas fa-memory text-xl text-blue-600 dark:text-blue-400"></i>
                    </div>
                    <div class="ml-4">
                        <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400">Cached File IDs</h3>
                        <p class="text-2xl font-bold text-gray-900 dark:text-white" id="stat-cache-size">-</p>
                    </div>
                </div>
            </div>

            <!-- Active Bots Card -->
            <div class="theme-card rounded-xl border p-6 shadow-sm">
                <div class="flex items-center">
                    <div class="flex-shrink-0 bg-green-100 dark:bg-green-900/30 p-3 rounded-lg">
                        <i class="fas fa-robot text-xl text-green-600 dark:text-green-400"></i>
                    </div>
                    <div class="ml-4">
                        <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400">Connected Bots</h3>
                        <p class="text-2xl font-bold text-gray-900 dark:text-white" id="stat-bot-count">-</p>
                    </div>
                </div>
            </div>

        </div>

        <!-- Bot Health & Load - Full Width -->
        <div class="theme-card rounded-xl border shadow-sm mt-6">
            <div class="flex items-center justify-between px-6 py-4 border-b">
                <div class="flex items-center gap-3">
                    <div class="bg-purple-100 dark:bg-purple-900/30 p-2 rounded-lg">
                        <i class="fas fa-heartbeat text-purple-600 dark:text-purple-400"></i>
                    </div>
                    <h3 class="text-base font-semibold text-gray-800 dark:text-gray-200">Bot Health & Load</h3>
                </div>
            </div>
            <div id="stat-workloads" class="divide-y divide-gray-100 dark:divide-gray-800">
                <div class="px-6 py-4 text-sm text-gray-500">Loading...</div>
            </div>
        </div>
    </div>

    <!-- Stream Analytics Section -->
    <div class="mb-10">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200">Recent Stream Analytics</h2>
            <button onclick="clearAnalytics()"
                class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md text-sm font-medium transition-colors shadow-sm flex items-center">
                <i class="fas fa-trash-alt mr-2"></i> Clear Analytics
            </button>
        </div>
        <div class="theme-card border rounded-xl overflow-hidden shadow-sm">
            <div class="overflow-x-auto">
                <table class="w-full text-sm text-left">
                    <thead class="text-xs uppercase bg-gray-50 dark:bg-gray-800 dark:text-gray-300 border-b">
                        <tr>
                            <th class="px-6 py-4 font-semibold">Stream ID</th>
                            <th class="px-6 py-4 font-semibold">Title</th>
                            <th class="px-6 py-4 font-semibold text-center">Bot (DC)</th>
                            <th class="px-6 py-4 font-semibold text-right">Data Transferred</th>
                            <th class="px-6 py-4 font-semibold text-right">Avg / Peak Speed</th>
                            <th class="px-6 py-4 font-semibold text-center">Duration</th>
                            <th class="px-6 py-4 font-semibold text-center">Status</th>
                            <th class="px-6 py-4 font-semibold text-right">Time</th>
                        </tr>
                    </thead>
                    <tbody id="analytics-tbody" class="divide-y divide-gray-100 dark:divide-gray-800">
                        <tr>
                            <td colspan="8" class="px-6 py-8 text-center text-gray-500">
                                <i class="fas fa-spinner fa-spin mr-2"></i> Loading analytics...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Dead Links Section -->
    <div>
        <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-4">Flagged Dead Links</h2>
        <div class="theme-card border rounded-xl overflow-hidden shadow-sm">
            <div class="overflow-x-auto">
                <table class="w-full text-sm text-left">
                    <thead class="text-xs uppercase bg-gray-50 dark:bg-gray-800 dark:text-gray-300 border-b">
                        <tr>
                            <th class="px-6 py-4 font-semibold">Title</th>
                            <th class="px-6 py-4 font-semibold w-24">Type</th>
                            <th class="px-6 py-4 font-semibold">Quality Details</th>
                            <th class="px-6 py-4 font-semibold w-32 text-center">Date Added</th>
                            <th class="px-6 py-4 font-semibold w-24 text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody id="dead-links-tbody" class="divide-y divide-gray-100 dark:divide-gray-800">
                        <tr>
                            <td colspan="5" class="px-6 py-8 text-center text-gray-500">
                                <i class="fas fa-spinner fa-spin mr-2"></i> Loading dead links...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
    async function fetchStats() {
        try {
            const res = await fetch('/api/admin/system-stats');
            if (res.ok) {
                const data = await res.json();
                document.getElementById('stat-cache-size').textContent = data.cache_size;
                document.getElementById('stat-bot-count').textContent = data.total_bots;

                let wlHtml = '';
                if (data.bot_workloads && data.bot_workloads.length > 0) {
                    data.bot_workloads.forEach(b => {
                        let statusColor = 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
                        if (b.status === 'degraded') statusColor = 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
                        if (b.status === 'failing') statusColor = 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400';

                        wlHtml += `
                            <div class="flex items-center justify-between px-6 py-4 hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                                <div class="flex items-center gap-3">
                                    <span class="font-semibold text-gray-900 dark:text-white">${b.display_name}</span>
                                    <span class="text-[10px] px-2 py-0.5 rounded-full uppercase font-bold tracking-wider ${statusColor}">${b.status}</span>
                                </div>
                                <div class="flex items-center gap-6 text-sm">
                                    <div class="text-center">
                                        <div class="text-xs text-gray-500 mb-0.5">Active Streams</div>
                                        <div class="font-bold text-gray-900 dark:text-white">${b.current_load}</div>
                                    </div>
                                    <div class="text-center">
                                        <div class="text-xs text-gray-500 mb-0.5">Avg Speed</div>
                                        <div class="font-bold text-gray-900 dark:text-white">${b.avg_mbps} <span class="font-normal text-xs text-gray-400">MB/s</span></div>
                                    </div>
                                    <div class="text-center">
                                        <div class="text-xs text-gray-500 mb-0.5">Recent Failures</div>
                                        <div class="font-bold ${b.failures > 0 ? 'text-red-500' : 'text-gray-400'}">${b.failures}</div>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                } else {
                    wlHtml = '<div class="px-6 py-8 text-center text-gray-500">No bot data available</div>';
                }
                document.getElementById('stat-workloads').innerHTML = wlHtml;
            }
        } catch (err) {
            console.error(err);
        }
    }

    async function fetchAnalytics() {
        try {
            const res = await fetch('/api/admin/stream-analytics');
            const tbody = document.getElementById('analytics-tbody');
            if (res.ok) {
                const data = await res.json();
                const streams = data.data.recent;

                if (!streams || streams.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="8" class="px-6 py-8 text-center text-gray-500">No recent streams recorded.</td></tr>';
                    return;
                }

                let html = '';
                streams.forEach(s => {
                    const mbpsStr = `${s.avg_mbps.toFixed(1)} / <span class="text-gray-400">${s.peak_mbps.toFixed(1)}</span>`;
                    const bytesStr = (s.total_bytes / (1024 * 1024)).toFixed(1) + ' MB';
                    const timeStr = new Date(s.logged_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                    const durationStr = s.duration_sec ? `${s.duration_sec.toFixed(1)}s` : '—';
                    const titleStr = s.title || s.meta?.title || '—';

                    let statusColor = 'text-green-500';
                    if (s.status === 'error') statusColor = 'text-red-500';
                    if (s.status === 'cancelled') statusColor = 'text-yellow-500';

                    html += `
                        <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                            <td class="px-6 py-3 font-mono text-xs text-gray-500 truncate max-w-[120px]" title="${s.stream_id}">${s.stream_id}</td>
                            <td class="px-6 py-3 text-sm font-medium text-gray-800 dark:text-gray-200 max-w-[160px] truncate" title="${titleStr}">${titleStr}</td>
                            <td class="px-6 py-3 text-center">Bot ${s.client_index + 1} <span class="text-xs text-gray-400 ml-1">(DC${s.dc_id})</span></td>
                            <td class="px-6 py-3 text-right font-medium">${bytesStr}</td>
                            <td class="px-6 py-3 text-right font-medium text-gray-700 dark:text-gray-300">${mbpsStr} <span class="text-xs text-gray-500">MB/s</span></td>
                            <td class="px-6 py-3 text-center text-gray-500">${durationStr}</td>
                            <td class="px-6 py-3 text-center capitalize text-xs font-bold ${statusColor}">${s.status}</td>
                            <td class="px-6 py-3 text-right text-gray-500 text-xs">${timeStr}</td>
                        </tr>
                    `;
                });
                tbody.innerHTML = html;
            }
        } catch (err) {
            console.error(err);
        }
    }

    async function fetchDeadLinks() {
        try {
            const res = await fetch('/api/admin/dead-links');
            const tbody = document.getElementById('dead-links-tbody');
            if (res.ok) {
                const data = await res.json();
                const links = data.data;

                if (links.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="5" class="px-6 py-8 text-center text-gray-500">No dead links found. All files are healthy!</td></tr>';
                    return;
                }

                let html = '';
                links.forEach(l => {
                    const typeBadge = l.type === 'movie'
                        ? '<span class="px-2 py-1 rounded bg-blue-100 text-blue-800 text-xs font-medium">Movie</span>'
                        : '<span class="px-2 py-1 rounded bg-purple-100 text-purple-800 text-xs font-medium">TV Series</span>';

                    html += `
                        <tr class="hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors">
                            <td class="px-6 py-4">
                                <div class="font-medium text-gray-900 dark:text-gray-100">${l.title}</div>
                                <div class="text-xs text-gray-500">${l.year || ''}</div>
                            </td>
                            <td class="px-6 py-4">${typeBadge}</td>
                            <td class="px-6 py-4">
                                <div class="text-sm font-medium text-red-600 dark:text-red-400">${l.quality}</div>
                                <div class="text-xs text-gray-500">${l.size || 'Unknown size'}</div>
                            </td>
                            <td class="px-6 py-4 text-center text-gray-500 text-xs">${l.date_added ? new Date(l.date_added).toLocaleDateString() : '—'}</td>
                            <td class="px-6 py-4 text-center">
                                <button onclick="deleteDeadLink(${l.tmdb_id}, ${l.db_index}, '${l.type}', '${l.quality_id}', ${l.season || -1}, ${l.episode || -1})" 
                                        class="text-red-600 hover:text-red-800 bg-red-50 hover:bg-red-100 rounded p-2 transition-colors" title="Delete from Database">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    `;
                });
                tbody.innerHTML = html;
            }
        } catch (err) {
            console.error(err);
        }
    }

    async function clearCache() {
        if (!confirm("Are you sure you want to clear the Telegram FileId cache? This will force bots to re-fetch metadata on the next stream.")) return;

        try {
            const res = await fetch('/api/admin/clear-cache', { method: 'POST' });
            if (res.ok) {
                const data = await res.json();
                alert(data.message);
                fetchStats();
            } else {
                alert("Failed to clear cache.");
            }
        } catch (err) {
            alert("Error clearing cache.");
        }
    }

    async function clearAnalytics() {
        if (!confirm("Are you sure you want to clear all stream analytics history? This cannot be undone.")) return;

        try {
            const res = await fetch('/api/admin/clear-analytics', { method: 'POST' });
            if (res.ok) {
                const data = await res.json();
                alert(data.message || 'Analytics cleared successfully.');
                fetchAnalytics();
            } else {
                const err = await res.json().catch(() => ({}));
                alert(err.detail || 'Failed to clear analytics.');
            }
        } catch (err) {
            alert('Error clearing analytics.');
        }
    }

    async function deleteDeadLink(tmdb_id, db_index, type, quality_id, season, episode) {
        if (!confirm("Are you sure you want to purge this dead link from the database? Users will no longer see this quality in Stremio.")) return;

        try {
            let endpoint = '';
            if (type === 'movie') {
                endpoint = `/api/media/delete-quality?tmdb_id=${tmdb_id}&db_index=${db_index}&id=${quality_id}`;
            } else {
                endpoint = `/api/media/delete-tv-quality?tmdb_id=${tmdb_id}&db_index=${db_index}&season=${season}&episode=${episode}&id=${quality_id}`;
            }

            const res = await fetch(endpoint, { method: 'DELETE' });
            if (res.ok) {
                fetchDeadLinks(); // Refresh table
            } else {
                alert("Failed to delete the dead link.");
            }
        } catch (err) {
            alert("Error communicating with server.");
        }
    }

    // Initial fetch on load
    document.addEventListener('DOMContentLoaded', () => {
        fetchStats();
        fetchAnalytics();
        fetchDeadLinks();
        // Refresh dynamic stats
        setInterval(fetchStats, 10000);
        setInterval(fetchAnalytics, 15000);
    });
</script>
{% endblock %}