main
Satur@it-depot.ru 2025-03-05 10:59:14 +03:00
parent 9360a1a671
commit 62c0e37b6d
2 changed files with 56 additions and 7 deletions

29
app.py
View File

@ -63,7 +63,7 @@ class FolderUpdate(BaseModel):
class InstallData(BaseModel):
rust_id: str | None = None
computer_name: str | None = None
install_time: str | None = None
install_time: str | None = None # Принимаем строку в формате YYYY-MM-DD HH:MM:SS
folder_id: int | None = None
protocol: str | None = 'rustdesk' # По умолчанию RustDesk
@ -121,13 +121,15 @@ def get_installs():
LEFT JOIN folders f ON i.folder_id = f.id
""")
rows = cursor.fetchall()
# Форматируем время для вывода в читаемом формате
return [{"id": row[0], "rust_id": row[1], "computer_name": row[2],
"install_time": row[3], "folder_id": row[4], "folder_name": row[5], "protocol": row[6]}
"install_time": datetime.datetime.strptime(row[3], "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S") if row[3] else None,
"folder_id": row[4], "folder_name": row[5], "protocol": row[6]}
for row in rows]
@app.post("/api/install")
def add_install(data: InstallData):
install_time = data.install_time or datetime.datetime.now().isoformat()
install_time = data.install_time or datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Форматируем в читаемый формат
folder_id = data.folder_id if data.folder_id is not None else unsorted_folder_id
protocol = data.protocol or 'rustdesk' # По умолчанию RustDesk для POST-запросов
cursor.execute("INSERT INTO installs (rust_id, computer_name, install_time, folder_id, protocol) VALUES (?, ?, ?, ?, ?)",
@ -148,6 +150,16 @@ def update_install(install_id: int, data: InstallData):
new_folder_id = data.folder_id if data.folder_id is not None else current[3]
new_protocol = data.protocol if data.protocol is not None else current[4]
# Форматируем время, если оно предоставлено в запросе
if new_install_time:
try:
# Проверяем, что время в формате YYYY-MM-DD HH:MM:SS
datetime.datetime.strptime(new_install_time, "%Y-%m-%d %H:%M:%S")
except ValueError:
raise HTTPException(status_code=400, detail="Неверный формат времени. Используйте YYYY-MM-DD HH:MM:SS")
else:
new_install_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute("""
UPDATE installs
SET rust_id = ?, computer_name = ?, install_time = ?, folder_id = ?, protocol = ?
@ -186,7 +198,9 @@ async def export_csv(folder_id: int | None = Query(None, description="ID пап
writer = csv.writer(output, lineterminator='\n')
writer.writerow(['ID подключения', 'Имя компьютера', 'Время установки', 'Папка', 'Протокол'])
for row in rows:
writer.writerow(row)
# Форматируем время для CSV в читаемом формате
install_time = datetime.datetime.strptime(row[2], "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M:%S") if row[2] else ""
writer.writerow([row[0], row[1], install_time, row[3], row[4]])
headers = {
'Content-Disposition': 'attachment; filename="rustdesk_data.csv"',
@ -215,6 +229,13 @@ async def import_csv(file: UploadFile = File(...), folder_id: int | None = Query
if cursor.fetchone():
continue # Пропускаем дублирующуюся запись
# Проверяем формат времени
if install_time:
try:
datetime.datetime.strptime(install_time, "%Y-%m-%d %H:%M:%S")
except ValueError:
raise HTTPException(status_code=400, detail=f"Неверный формат времени для записи с ID {rust_id}. Используйте YYYY-MM-DD HH:MM:SS")
# Получаем или создаем ID папки
if folder_name:
cursor.execute("SELECT id FROM folders WHERE name = ?", (folder_name,))

View File

@ -28,6 +28,7 @@
#import-label { cursor: pointer; background: #007bff; color: white; padding: 5px 10px; border-radius: 5px; }
#import-label:hover { background: #0056b3; }
.folder-select { margin: 5px 0; }
.time-hint { font-size: 12px; color: #666; margin-top: 5px; }
</style>
</head>
<body>
@ -61,7 +62,7 @@
<h2>Добавить запись</h2>
<input type="text" id="rustId" placeholder="ID подключения" required>
<input type="text" id="computerName" placeholder="Имя компьютера" required>
<input type="text" id="installTime" placeholder="Время (опционально)">
<input type="text" id="installTime" placeholder="Время (опционально, формат: ГГГГ-ММ-ДД ЧЧ:ММ:СС)">
<select id="protocol">
<option value="rustdesk" selected>RustDesk</option>
<option value="anydesk">AnyDesk</option>
@ -71,6 +72,7 @@
<option value="rdp">RDP</option>
</select>
<button onclick="addInstall()">Добавить</button>
<div class="time-hint">Пример: 2025-03-05 14:30:00</div>
</div>
<div class="header">
<div onclick="sortInstalls('rust_id')">ID подключения<span class="sort-arrow"></span></div>
@ -302,8 +304,14 @@
function addInstall() {
const rustId = $('#rustId').val();
const computerName = $('#computerName').val();
const installTime = $('#installTime').val() || new Date().toISOString();
const installTime = $('#installTime').val() || ''; // Пустая строка, если не указано
const protocol = $('#protocol').val();
if (installTime && !/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$/.test(installTime)) {
alert("Неверный формат времени. Используйте ГГГГ-ММ-ДД ЧЧ:ММ:СС (например, 2025-03-05 14:30:00)");
return;
}
$.ajax({
url: `${API_URL}/install`,
type: 'POST',
@ -311,6 +319,13 @@
data: JSON.stringify({ rust_id: rustId, computer_name: computerName, install_time: installTime, folder_id: selectedFolderId, protocol: protocol }),
success: function () {
loadInstalls(selectedFolderId);
},
error: function (xhr, status, error) {
if (xhr.status === 400) {
alert(xhr.responseJSON.detail);
} else {
console.error("Ошибка добавления:", status, error);
}
}
});
}
@ -318,8 +333,14 @@
function editInstall(id, rustId, computerName, installTime, protocol) {
const newRustId = prompt("ID подключения:", rustId);
const newComputerName = prompt("Имя компьютера:", computerName);
const newInstallTime = prompt("Время установки:", installTime);
let newInstallTime = prompt("Время установки (опционально, формат: ГГГГ-ММ-ДД ЧЧ:ММ:СС):", installTime || '');
const newProtocol = prompt("Протокол (rustdesk, anydesk, ammyy, teamviewer, vnc, rdp):", protocol);
if (newInstallTime && !/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$/.test(newInstallTime)) {
alert("Неверный формат времени. Используйте ГГГГ-ММ-ДД ЧЧ:ММ:СС (например, 2025-03-05 14:30:00)");
return;
}
if (newRustId && newComputerName) {
$.ajax({
url: `${API_URL}/install/${id}`,
@ -328,6 +349,13 @@
data: JSON.stringify({ rust_id: newRustId, computer_name: newComputerName, install_time: newInstallTime, folder_id: selectedFolderId, protocol: newProtocol }),
success: function () {
loadInstalls(selectedFolderId);
},
error: function (xhr, status, error) {
if (xhr.status === 400) {
alert(xhr.responseJSON.detail);
} else {
console.error("Ошибка редактирования:", status, error);
}
}
});
}