From c3583d93eaa2ff1e83275774c2abe32fc52a26ef Mon Sep 17 00:00:00 2001 From: "Satur@it-depot.ru" Date: Mon, 10 Mar 2025 14:35:45 +0300 Subject: [PATCH] dynamic --- app.py | 25 +++++++++++++++++++---- templates/index.html | 48 +++++++++++++++++++++++++++++++++++++++----- 2 files changed, 64 insertions(+), 9 deletions(-) diff --git a/app.py b/app.py index 7d93bae..b74f777 100644 --- a/app.py +++ b/app.py @@ -91,6 +91,7 @@ class InstallData(BaseModel): folder_id: int | None = None protocol: str | None = 'rustdesk' note: str | None = '' + last_seen: str | None = None # Добавлено для поддержки обновлений статуса # Функция форматирования времени def format_time(time_str): @@ -202,7 +203,7 @@ async def add_install(data: InstallData): folder_id = data.folder_id if data.folder_id is not None else unsorted_folder_id protocol = data.protocol or 'rustdesk' note = data.note or '' - last_seen = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + last_seen = data.last_seen or datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") cursor.execute("SELECT id FROM installs WHERE rust_id = ?", (rust_id,)) existing = cursor.fetchone() @@ -219,9 +220,25 @@ async def add_install(data: InstallData): """, (rust_id, computer_name, install_time, folder_id, protocol, note, last_seen)) conn.commit() - # Отправка обновления через WebSocket - installs = get_installs() - await manager.broadcast(json.dumps(installs)) + # Получаем обновленную запись + cursor.execute(""" + SELECT id, rust_id, computer_name, install_time, folder_id, protocol, note, last_seen + FROM installs WHERE rust_id = ? + """, (rust_id,)) + updated_install = cursor.fetchone() + install_data = { + "id": updated_install[0], + "rust_id": updated_install[1], + "computer_name": updated_install[2], + "install_time": format_time(updated_install[3]), + "folder_id": updated_install[4], + "protocol": updated_install[5], + "note": updated_install[6], + "last_seen": updated_install[7] + } + # Отправляем только обновленную запись через WebSocket + await manager.broadcast(json.dumps({"type": "update", "data": install_data})) + return {"status": "success"} @api_app.put("/api/install/{install_id}") diff --git a/templates/index.html b/templates/index.html index 291987c..dd4c22c 100644 --- a/templates/index.html +++ b/templates/index.html @@ -601,18 +601,43 @@ if (ws) { ws.close(); } - // Используем wss для соответствия HTTPS ws = new WebSocket(`wss://${window.location.host}/ws`); ws.onmessage = function(event) { - allInstalls = JSON.parse(event.data); - displayInstalls(allInstalls.filter(i => !selectedFolderId || i.folder_id == selectedFolderId)); + const data = JSON.parse(event.data); + if (data.type === "update") { + const updatedInstall = data.data; + const index = allInstalls.findIndex(i => i.id === updatedInstall.id); + if (index !== -1) { + allInstalls[index] = updatedInstall; + } else { + allInstalls.push(updatedInstall); + alert(`Новое подключение добавлено: ${updatedInstall.computer_name} (ID: ${updatedInstall.rust_id})`); + } + displayInstalls(allInstalls.filter(i => !selectedFolderId || i.folder_id == selectedFolderId)); + } }; ws.onerror = function(error) { console.error('WebSocket error:', error); }; ws.onclose = function() { - console.log('WebSocket disconnected, retrying in 5 seconds...'); - setTimeout(connectWebSocket, 5000); + console.log('WebSocket disconnected, retrying...'); + let retryDelay = 1000; // Начальная задержка 1 секунда + const maxDelay = 30000; // Максимальная задержка 30 секунд + const maxAttempts = 10; + let attempts = 0; + + function reconnect() { + if (attempts < maxAttempts) { + setTimeout(() => { + connectWebSocket(); + retryDelay = Math.min(retryDelay * 2, maxDelay); + attempts++; + }, retryDelay); + } else { + console.error('Max reconnect attempts reached'); + } + } + reconnect(); }; } @@ -1162,6 +1187,19 @@ } }); } + + function startPeriodicSync() { + setInterval(() => { + $.getJSON(`${API_URL}/installs`, function (data) { + allInstalls = data; + displayInstalls(allInstalls.filter(i => !selectedFolderId || i.folder_id == selectedFolderId)); + }).fail(function(jqxhr, textStatus, error) { + console.error("Error syncing installs:", textStatus, error); + }); + }, 60000); // Каждые 60 секунд + } + + startPeriodicSync(); \ No newline at end of file