main
Satur@it-depot.ru 2025-03-10 14:35:45 +03:00
parent f1d4a2401b
commit c3583d93ea
2 changed files with 64 additions and 9 deletions

25
app.py
View File

@ -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}")

View File

@ -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();
</script>
</body>
</html>