265 lines
10 KiB
Go
265 lines
10 KiB
Go
package main
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"io"
|
||
"log"
|
||
"os"
|
||
"path/filepath"
|
||
"time"
|
||
|
||
"fyne.io/fyne/v2"
|
||
"fyne.io/fyne/v2/container"
|
||
"fyne.io/fyne/v2/dialog"
|
||
"fyne.io/fyne/v2/storage"
|
||
"fyne.io/fyne/v2/widget"
|
||
)
|
||
|
||
// Очистка вкладок server
|
||
func (a *App) clearServerTabs() {
|
||
// Удаляем все вкладки, кроме первой (если она нужна)
|
||
items := a.serverTab.Items
|
||
if len(items) > 0 {
|
||
// Удаляем все вкладки после первой (если первая - это какая-то базовая)
|
||
// Или удаляем все, если нужно полностью очистить
|
||
for i := len(items) - 1; i >= 0; i-- {
|
||
a.serverTab.RemoveIndex(i)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Очистка вкладок platform
|
||
func (a *App) clearPlatformTabs() {
|
||
items := a.platformTab.Items
|
||
if len(items) > 0 {
|
||
for i := len(items) - 1; i >= 0; i-- {
|
||
a.platformTab.RemoveIndex(i)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Обновление UI после загрузки
|
||
func (a *App) updateUIAfterUpload(uiFunc string) {
|
||
// Обновляем статус
|
||
a.statusLabel.SetText("✅ Файл загружен")
|
||
a.statusLabel.TextStyle = fyne.TextStyle{Bold: true, Italic: true}
|
||
a.statusLabel.Refresh()
|
||
|
||
// Обновляем информацию о файле
|
||
fileInfoText := fmt.Sprintf("📄 %s | 📦 %s | 🕒 %s",
|
||
a.fileName,
|
||
formatFileSize(a.fileSize),
|
||
time.Now().Format("15:04:05"))
|
||
a.fileInfo.SetText(fileInfoText)
|
||
|
||
if uiFunc == "server" {
|
||
a.updateServer()
|
||
}
|
||
if uiFunc == "platform" {
|
||
a.updatePlatform()
|
||
}
|
||
}
|
||
|
||
// Обновление содержимого server
|
||
func (a *App) updateServer() {
|
||
a.clearServerTabs()
|
||
var server outputStruct
|
||
err := json.Unmarshal(a.serverContent, &server)
|
||
if err != nil {
|
||
log.Printf("Unmarshall server: %s", err)
|
||
}
|
||
|
||
a.serverTab.Append(container.NewTabItem("БИОС", widget.NewLabel(server.BiosInfo.Name)))
|
||
if server.OperatingSystem.AstraLicense == "" || server.OperatingSystem.AstraVersion == "" {
|
||
a.serverTab.Append(container.NewTabItem("ОС", widget.NewLabel(server.OperatingSystem.OsRelease)))
|
||
} else {
|
||
a.serverTab.Append(container.NewTabItem("ОС", widget.NewLabel(fmt.Sprintf("Версия: %s, Версия ALSE: %s, Уровень защиты ALSE: %s", server.OperatingSystem.OsRelease, server.OperatingSystem.AstraLicense, server.OperatingSystem.AstraVersion))))
|
||
}
|
||
|
||
installedPkgsTab := createInstalledPkgsTab(server)
|
||
a.serverTab.Append(container.NewTabItem("Пакеты", installedPkgsTab))
|
||
fsInfoTab := createFsInfoTab(server)
|
||
a.serverTab.Append(container.NewTabItem("ФС", fsInfoTab))
|
||
a.serverTab.Append(container.NewTabItem("LA", widget.NewLabel(fmt.Sprintf("Средняя загрузка: 15м %s\n, \t5м %s\n, \t1м %s\n, Процессы %s", server.LoadAverage.FifteenMin, server.LoadAverage.FiveMin, server.LoadAverage.OneMin, server.LoadAverage.Processes))))
|
||
cpuTab := createCpuTab(server)
|
||
a.serverTab.Append(container.NewTabItem("ЦП", cpuTab))
|
||
a.serverTab.Append(container.NewTabItem("ОЗУ", widget.NewLabel(fmt.Sprintf("Доступно: %s\nСвободно: %s\nВсего: %s", server.Ram.MemAvailable, server.Ram.MemFree, server.Ram.MemTotal))))
|
||
a.serverTab.Append(container.NewTabItem("Uptime", widget.NewLabel(server.Uptime.WorkSeconds)))
|
||
a.serverTab.Append(container.NewTabItem("Фаерволы", createFirewallTab(server)))
|
||
a.serverTab.Append(container.NewTabItem("Время", widget.NewLabel(fmt.Sprintf("Служба времени\t\t\t%s, \nВремя синхронизировано\t%s", server.TimeService.TimeService, server.TimeService.TimeSync))))
|
||
a.serverTab.Append(container.NewTabItem("Сеть", createNetworkTab(server)))
|
||
// a.serverTab.Append(container.NewTabItem("Интеренет", widget.NewLabel(fmt.Sprintf("docker-registry.ispsystem.com :: %d\ndownload.ispsystem.com :: %d\nlicense6.ispsystem.com :: %d\nmetricreport.ispsystem.net :: %d\ndownload.docker.com :: %d", server.InternetRequired.IspRegistry, server.InternetRequired.IspDownload, server.InternetRequired.IspLicense, server.InternetRequired.IspMetric, server.InternetRequired.DockerDownload))))
|
||
a.serverTab.Append(container.NewTabItem("Интернет", createInternetRequiredTab(server)))
|
||
a.serverTab.Append(container.NewTabItem("Сесюрити", createSecSetTab(server)))
|
||
a.serverTab.Append(container.NewTabItem("Docker", createDockerTab(server)))
|
||
a.serverTab.Append(container.NewTabItem("Jrnlctl", createJournalTab(server)))
|
||
a.serverTab.Append(container.NewTabItem("root history", createRootHistoryTab(server)))
|
||
}
|
||
|
||
func (a *App) updatePlatform() {
|
||
a.clearPlatformTabs()
|
||
var platform platformStruct
|
||
err := json.Unmarshal(a.platformContent, &platform)
|
||
if err != nil {
|
||
log.Printf("Unmarshall platform: %s", err)
|
||
}
|
||
a.platformTab.Append(container.NewTabItem("Лицензия", createLicenseTab(platform)))
|
||
a.platformTab.Append(container.NewTabItem("Локации", createLocationTab(platform)))
|
||
// a.platformTab.Append(container.NewTabItem("Compose Локация", createLocationComposeTab(platform)))
|
||
a.platformTab.Append(container.NewTabItem("Имена файлов", createCopiedFileListTab(platform)))
|
||
a.platformTab.Append(container.NewTabItem("Taskmgr", createTaskManagerFailedTab(platform)))
|
||
a.platformTab.Append(container.NewTabItem("Оборудование", createHwByLocationsTab(platform)))
|
||
a.platformTab.Append(container.NewTabItem("Плагины", createInstalledPluginTab(platform)))
|
||
a.platformTab.Append(container.NewTabItem("Пользователи", widget.NewLabel(fmt.Sprintf("Количество пользователей: %d", platform.Users.Count))))
|
||
a.platformTab.Append(container.NewTabItem("LDAP", createLdapTab(platform)))
|
||
a.platformTab.Append(container.NewTabItem("Репозитории", createRepoTab(platform)))
|
||
a.platformTab.Append(container.NewTabItem("Шаблоны ОС", createOsTemplateTab(platform)))
|
||
a.platformTab.Append(container.NewTabItem("Real ip", widget.NewLabel(fmt.Sprintf("%s : %s", platform.RealIP.Name, platform.RealIP.Value))))
|
||
a.platformTab.Append(container.NewTabItem("Бэкап", createBackupTasksTab(platform)))
|
||
}
|
||
|
||
func (a *App) onUploadServer() {
|
||
a.statusLabel.SetText("Выбор файла...")
|
||
|
||
// Фильтр json файлов
|
||
jsonFilter := storage.NewExtensionFileFilter([]string{".json"})
|
||
|
||
// Создаем диалог выбора файла
|
||
fileDialog := dialog.NewFileOpen(func(reader fyne.URIReadCloser, err error) {
|
||
if err != nil {
|
||
a.showError("Ошибка", fmt.Sprintf("Не удалось открыть диалог: %v", err))
|
||
return
|
||
}
|
||
|
||
if reader == nil {
|
||
a.statusLabel.SetText("Отменено")
|
||
return
|
||
}
|
||
|
||
defer reader.Close()
|
||
|
||
// Получаем информацию о файле
|
||
fileURI := reader.URI()
|
||
a.filePath = fileURI.Path()
|
||
a.fileName = fileURI.Name()
|
||
|
||
// Читаем файл
|
||
content, err := io.ReadAll(reader)
|
||
if err != nil {
|
||
a.showError("Ошибка чтения", fmt.Sprintf("Не удалось прочитать файл: %v", err))
|
||
a.progressBar.Hide()
|
||
return
|
||
}
|
||
|
||
// Сохраняем данные
|
||
a.serverContent = content
|
||
a.fileSize = int64(len(content))
|
||
|
||
// Завершаем прогресс
|
||
a.progressBar.SetValue(1.0)
|
||
time.Sleep(300 * time.Millisecond)
|
||
a.progressBar.Hide()
|
||
|
||
// Обновляем UI
|
||
a.updateUIAfterUpload("server")
|
||
|
||
// Показываем уведомление
|
||
a.showSuccess("Файл загружен",
|
||
fmt.Sprintf("Файл '%s' успешно загружен", a.fileName))
|
||
|
||
}, a.window)
|
||
|
||
fileDialog.SetFilter(jsonFilter)
|
||
// Альтернативный способ установки начальной директории
|
||
// Используем домашнюю директорию пользователя
|
||
homeDir, err := os.UserHomeDir()
|
||
if err == nil {
|
||
// Пытаемся использовать Downloads
|
||
downloadsPath := filepath.Join(homeDir, "Downloads")
|
||
if _, err := os.Stat(downloadsPath); err == nil {
|
||
// Создаем URI из пути
|
||
uri := storage.NewFileURI(downloadsPath)
|
||
listableURI, err := storage.ListerForURI(uri)
|
||
if err == nil {
|
||
fileDialog.SetLocation(listableURI)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Показываем диалог
|
||
fileDialog.Show()
|
||
}
|
||
|
||
func (a *App) onUploadPlatform() {
|
||
a.statusLabel.SetText("Выбор файла...")
|
||
|
||
// Фильтр json файлов
|
||
jsonFilter := storage.NewExtensionFileFilter([]string{".json"})
|
||
|
||
// Создаем диалог выбора файла
|
||
fileDialog := dialog.NewFileOpen(func(reader fyne.URIReadCloser, err error) {
|
||
if err != nil {
|
||
a.showError("Ошибка", fmt.Sprintf("Не удалось открыть диалог: %v", err))
|
||
return
|
||
}
|
||
|
||
if reader == nil {
|
||
a.statusLabel.SetText("Отменено")
|
||
return
|
||
}
|
||
|
||
defer reader.Close()
|
||
|
||
// Получаем информацию о файле
|
||
fileURI := reader.URI()
|
||
a.filePath = fileURI.Path()
|
||
a.fileName = fileURI.Name()
|
||
|
||
// Читаем файл
|
||
content, err := io.ReadAll(reader)
|
||
if err != nil {
|
||
a.showError("Ошибка чтения", fmt.Sprintf("Не удалось прочитать файл: %v", err))
|
||
a.progressBar.Hide()
|
||
return
|
||
}
|
||
|
||
// Сохраняем данные
|
||
a.platformContent = content
|
||
a.fileSize = int64(len(content))
|
||
|
||
// Завершаем прогресс
|
||
a.progressBar.SetValue(1.0)
|
||
time.Sleep(300 * time.Millisecond)
|
||
a.progressBar.Hide()
|
||
|
||
// Обновляем UI
|
||
a.updateUIAfterUpload("platform")
|
||
|
||
// Показываем уведомление
|
||
a.showSuccess("Файл загружен",
|
||
fmt.Sprintf("Файл '%s' успешно загружен", a.fileName))
|
||
|
||
}, a.window)
|
||
|
||
fileDialog.SetFilter(jsonFilter)
|
||
// Альтернативный способ установки начальной директории
|
||
// Используем домашнюю директорию пользователя
|
||
homeDir, err := os.UserHomeDir()
|
||
if err == nil {
|
||
// Пытаемся использовать Downloads
|
||
downloadsPath := filepath.Join(homeDir, "Downloads")
|
||
if _, err := os.Stat(downloadsPath); err == nil {
|
||
// Создаем URI из пути
|
||
uri := storage.NewFileURI(downloadsPath)
|
||
listableURI, err := storage.ListerForURI(uri)
|
||
if err == nil {
|
||
fileDialog.SetLocation(listableURI)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Показываем диалог
|
||
fileDialog.Show()
|
||
}
|