fix26.2: полная UI-полировка peer/dashboard и завершение i18n
This commit is contained in:
@@ -36,4 +36,3 @@ func AdminSecurity(c *gin.Context) {
|
||||
}
|
||||
vo.Success(gin.H{"forcePasswordChange": info.ForcePasswordChange}, c)
|
||||
}
|
||||
|
||||
|
||||
@@ -50,4 +50,3 @@ func DashboardSecurity(c *gin.Context) {
|
||||
}
|
||||
vo.Success(data, c)
|
||||
}
|
||||
|
||||
|
||||
@@ -222,4 +222,3 @@ func PeerClientConfig(c *gin.Context) {
|
||||
}
|
||||
vo.Success(data, c)
|
||||
}
|
||||
|
||||
|
||||
@@ -40,4 +40,3 @@ func UpdateAdminUser(ids []int64, updates map[string]interface{}) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -152,4 +152,3 @@ func DashboardSystemTimeseries(fromMs int64, toMs int64) ([]vo.DashboardSeriesPo
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -80,23 +80,3 @@ func PagePeer(peerPageDto dto.PeerPageDto) ([]entity.Peer, int64, error) {
|
||||
}
|
||||
return peers, total, nil
|
||||
}
|
||||
|
||||
func UpdatePeerTraffic(name string, download int64, upload int64) error {
|
||||
if upload == 0 && download == 0 {
|
||||
return nil
|
||||
}
|
||||
updates := map[string]interface{}{}
|
||||
if download != 0 {
|
||||
updates["download_bytes"] = gorm.Expr("download_bytes + ?", download)
|
||||
}
|
||||
if upload != 0 {
|
||||
updates["upload_bytes"] = gorm.Expr("upload_bytes + ?", upload)
|
||||
}
|
||||
updates["update_time"] = time.Now().Format("2006-01-02 15:04:05")
|
||||
if tx := sqliteDB.Model(&entity.Peer{}).Where("name = ?", name).Updates(updates); tx.Error != nil {
|
||||
logrus.Errorf("%v", tx.Error)
|
||||
return errors.New(constant.SysError)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+2
-3
@@ -289,8 +289,8 @@ func migrateLegacyAccounts() error {
|
||||
if !tableExists("account") {
|
||||
return nil
|
||||
}
|
||||
var accounts []entity.Account
|
||||
if tx := sqliteDB.Model(&entity.Account{}).Order("id asc").Find(&accounts); tx.Error != nil {
|
||||
var accounts []entity.LegacyAccount
|
||||
if tx := sqliteDB.Model(&entity.LegacyAccount{}).Order("id asc").Find(&accounts); tx.Error != nil {
|
||||
logrus.Errorf("sqlite legacy account query err: %v", tx.Error)
|
||||
return errors.New("sqlite legacy account query err")
|
||||
}
|
||||
@@ -641,4 +641,3 @@ func Paginate(pageNum *int64, pageSize *int64) func(db *gorm.DB) *gorm.DB {
|
||||
return db.Offset(int((num - 1) * size)).Limit(int(size))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -72,4 +72,3 @@ func UpsertTrafficAggregateDaily(peerId int64, dayStart int64, rxBytes int64, tx
|
||||
func gormExprAdd(column string, delta int64) interface{} {
|
||||
return gorm.Expr(fmt.Sprintf("%s + ?", column), delta)
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,18 @@ export default {
|
||||
stale: "Dashboard data is stale. Retrying automatically...",
|
||||
topPeers24h: "Top peers (24h)",
|
||||
refreshFailed: "Failed to refresh dashboard data",
|
||||
cpu: "CPU",
|
||||
ram: "RAM",
|
||||
disk: "Disk",
|
||||
peers: "Peers",
|
||||
onlinePeers: "Online peers",
|
||||
onlineDevices: "Online devices",
|
||||
todayDownload: "Today download",
|
||||
todayUpload: "Today upload",
|
||||
trafficChart: "Traffic & System Timeseries",
|
||||
download: "Download",
|
||||
upload: "Upload",
|
||||
total: "Total",
|
||||
},
|
||||
admin: {
|
||||
changePasswordTitle: "Change password",
|
||||
@@ -102,8 +114,22 @@ export default {
|
||||
"I want to be a shooting star, cutting through the darkness, just to illuminate your dreams, good night🌛!",
|
||||
},
|
||||
peer: {
|
||||
name: "Peer",
|
||||
remark: "Remark",
|
||||
username: "Username",
|
||||
secret: "Secret",
|
||||
maxDevices: "Max devices",
|
||||
disabled: "Disabled",
|
||||
status: "Status",
|
||||
traffic: "Traffic",
|
||||
devices: "Devices",
|
||||
lastConnectionAt: "Last connection",
|
||||
overview: "Overview",
|
||||
authId: "Auth ID",
|
||||
clientUri: "Client URI",
|
||||
clientQr: "Client QR",
|
||||
unlimited: "Unlimited",
|
||||
secretRotateConfirm: "Rotate peer secret? Existing client configurations will stop working until updated.",
|
||||
pass: "Pass",
|
||||
conPass: "ConPass",
|
||||
quota: "Quota",
|
||||
|
||||
@@ -23,6 +23,18 @@ export default {
|
||||
stale: "Данные дашборда устарели. Выполняется автоматическая повторная попытка...",
|
||||
topPeers24h: "Топ пиров (24ч)",
|
||||
refreshFailed: "Не удалось обновить данные дашборда",
|
||||
cpu: "CPU",
|
||||
ram: "RAM",
|
||||
disk: "Диск",
|
||||
peers: "Пиры",
|
||||
onlinePeers: "Пиры онлайн",
|
||||
onlineDevices: "Устройства онлайн",
|
||||
todayDownload: "Скачано за сегодня",
|
||||
todayUpload: "Отдано за сегодня",
|
||||
trafficChart: "Трафик и системные метрики",
|
||||
download: "Скачано",
|
||||
upload: "Отдано",
|
||||
total: "Всего",
|
||||
},
|
||||
admin: {
|
||||
changePasswordTitle: "Смена пароля",
|
||||
@@ -97,8 +109,22 @@ export default {
|
||||
greeting5: "Доброй ночи,",
|
||||
},
|
||||
peer: {
|
||||
name: "Пир",
|
||||
remark: "Комментарий",
|
||||
username: "Логин",
|
||||
secret: "Секрет",
|
||||
maxDevices: "Лимит устройств",
|
||||
disabled: "Отключён",
|
||||
status: "Статус",
|
||||
traffic: "Трафик",
|
||||
devices: "Устройства",
|
||||
lastConnectionAt: "Последнее подключение",
|
||||
overview: "Обзор",
|
||||
authId: "Auth ID",
|
||||
clientUri: "URI клиента",
|
||||
clientQr: "QR клиента",
|
||||
unlimited: "Безлимит",
|
||||
secretRotateConfirm: "Сменить секрет пира? Текущие клиентские конфиги перестанут работать до обновления.",
|
||||
pass: "Пароль входа",
|
||||
conPass: "Пароль подключения",
|
||||
quota: "Квота",
|
||||
|
||||
+4
@@ -14,6 +14,7 @@ declare module '@vue/runtime-core' {
|
||||
ElDatePicker: typeof import('element-plus/es')['ElDatePicker']
|
||||
ElDialog: typeof import('element-plus/es')['ElDialog']
|
||||
ElDivider: typeof import('element-plus/es')['ElDivider']
|
||||
ElDrawer: typeof import('element-plus/es')['ElDrawer']
|
||||
ElDropdown: typeof import('element-plus/es')['ElDropdown']
|
||||
ElDropdownItem: typeof import('element-plus/es')['ElDropdownItem']
|
||||
ElDropdownMenu: typeof import('element-plus/es')['ElDropdownMenu']
|
||||
@@ -26,6 +27,9 @@ declare module '@vue/runtime-core' {
|
||||
ElMenuItem: typeof import('element-plus/es')['ElMenuItem']
|
||||
ElOption: typeof import('element-plus/es')['ElOption']
|
||||
ElPagination: typeof import('element-plus/es')['ElPagination']
|
||||
ElProgress: typeof import('element-plus/es')['ElProgress']
|
||||
ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
|
||||
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
|
||||
ElRow: typeof import('element-plus/es')['ElRow']
|
||||
ElScrollbar: typeof import('element-plus/es')['ElScrollbar']
|
||||
ElSelect: typeof import('element-plus/es')['ElSelect']
|
||||
|
||||
@@ -29,27 +29,48 @@
|
||||
/>
|
||||
|
||||
<el-row :gutter="10" class="mt-2">
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">CPU: {{ summary.system.cpuPercent }}%</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">RAM: {{ summary.system.memPercent }}%</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">Disk: {{ summary.system.diskPercent }}%</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">Peers: {{ summary.peers.total }}</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">Online peers: {{ summary.peers.onlinePeers }}</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">Online devices: {{ summary.peers.onlineDevices }}</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">Today download: {{ formatBytes(summary.traffic.todayDownloadBytes || 0) }}</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">Today upload: {{ formatBytes(summary.traffic.todayUploadBytes || 0) }}</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">{{ $t("dashboard.cpu") }}: {{ summary.system.cpuPercent }}%</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">{{ $t("dashboard.ram") }}: {{ summary.system.memPercent }}%</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">{{ $t("dashboard.disk") }}: {{ summary.system.diskPercent }}%</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">{{ $t("dashboard.peers") }}: {{ summary.peers.total }}</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">{{ $t("dashboard.onlinePeers") }}: {{ summary.peers.onlinePeers }}</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">{{ $t("dashboard.onlineDevices") }}: {{ summary.peers.onlineDevices }}</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">{{ $t("dashboard.todayDownload") }}: {{ formatBytes(summary.traffic.todayDownloadBytes || 0) }}</el-card></el-col>
|
||||
<el-col :xs="24" :sm="12" :lg="6"><el-card shadow="never">{{ $t("dashboard.todayUpload") }}: {{ formatBytes(summary.traffic.todayUploadBytes || 0) }}</el-card></el-col>
|
||||
</el-row>
|
||||
|
||||
<el-card shadow="never" class="mt-3">
|
||||
<template #header>
|
||||
<div class="chart-header">
|
||||
<span>{{ $t("dashboard.trafficChart") }}</span>
|
||||
<el-radio-group v-model="range" size="small" @change="loadDashboard">
|
||||
<el-radio-button label="1h">1h</el-radio-button>
|
||||
<el-radio-button label="24h">24h</el-radio-button>
|
||||
<el-radio-button label="7d">7d</el-radio-button>
|
||||
<el-radio-button label="30d">30d</el-radio-button>
|
||||
</el-radio-group>
|
||||
</div>
|
||||
</template>
|
||||
<el-table :data="timeseriesRows" size="small" v-loading="timeseriesLoading">
|
||||
<el-table-column prop="ts" :label="$t('common.createTime')" width="180" />
|
||||
<el-table-column prop="download" :label="$t('dashboard.download')" />
|
||||
<el-table-column prop="upload" :label="$t('dashboard.upload')" />
|
||||
<el-table-column prop="cpu" :label="$t('dashboard.cpu')" width="120" />
|
||||
<el-table-column prop="mem" :label="$t('dashboard.ram')" width="120" />
|
||||
</el-table>
|
||||
</el-card>
|
||||
|
||||
<el-card shadow="never" class="mt-3">
|
||||
<template #header>{{ $t("dashboard.topPeers24h") }}</template>
|
||||
<el-table :data="topPeers" size="small">
|
||||
<el-table-column prop="name" label="Peer" />
|
||||
<el-table-column prop="download" label="Download">
|
||||
<el-table-column prop="name" :label="$t('peer.name')" />
|
||||
<el-table-column prop="download" :label="$t('dashboard.download')">
|
||||
<template #default="scope">{{ formatBytes(scope.row.download || 0) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="upload" label="Upload">
|
||||
<el-table-column prop="upload" :label="$t('dashboard.upload')">
|
||||
<template #default="scope">{{ formatBytes(scope.row.upload || 0) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="total" label="Total">
|
||||
<el-table-column prop="total" :label="$t('dashboard.total')">
|
||||
<template #default="scope">{{ formatBytes(scope.row.total || 0) }}</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
@@ -60,9 +81,10 @@
|
||||
<script setup lang="ts">
|
||||
import { useIntervalFn } from "@vueuse/core";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { dashboardSecurityApi, dashboardSummaryApi, dashboardTopPeersApi } from "@/api/dashboard";
|
||||
import { DashboardSummaryVo, DashboardTopPeerVo, SecurityRiskVo } from "@/api/dashboard/types";
|
||||
import { dashboardSecurityApi, dashboardSummaryApi, dashboardTimeseriesApi, dashboardTopPeersApi } from "@/api/dashboard";
|
||||
import { DashboardSummaryVo, DashboardTimeseriesVo, DashboardTopPeerVo, SecurityRiskVo } from "@/api/dashboard/types";
|
||||
import { formatBytes } from "@/utils/byte";
|
||||
import { timestampToDateTime } from "@/utils/time";
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
@@ -80,6 +102,9 @@ const summary = ref<DashboardSummaryVo>({
|
||||
});
|
||||
const topPeers = ref<DashboardTopPeerVo[]>([]);
|
||||
const securityRisks = ref<SecurityRiskVo[]>([]);
|
||||
const timeseries = ref<DashboardTimeseriesVo>({ range: "24h", traffic: [], system: [], collectedAt: 0 });
|
||||
const timeseriesLoading = ref(false);
|
||||
const range = ref("24h");
|
||||
const loadError = ref("");
|
||||
const loading = ref(false);
|
||||
const lastSuccessAt = ref(0);
|
||||
@@ -102,7 +127,7 @@ const loadDashboard = async () => {
|
||||
try {
|
||||
const [summaryRes, topRes, secRes] = await Promise.all([
|
||||
dashboardSummaryApi(),
|
||||
dashboardTopPeersApi("24h", 10),
|
||||
dashboardTopPeersApi(range.value, 10),
|
||||
dashboardSecurityApi(),
|
||||
]);
|
||||
summary.value = summaryRes.data;
|
||||
@@ -115,8 +140,33 @@ const loadDashboard = async () => {
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
|
||||
timeseriesLoading.value = true;
|
||||
try {
|
||||
const tsRes = await dashboardTimeseriesApi(range.value);
|
||||
timeseries.value = tsRes.data;
|
||||
} finally {
|
||||
timeseriesLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const timeseriesRows = computed(() => {
|
||||
const trafficMap: Record<number, { download: number; upload: number }> = {};
|
||||
for (const t of timeseries.value.traffic || []) {
|
||||
trafficMap[t.ts] = { download: t.download || 0, upload: t.upload || 0 };
|
||||
}
|
||||
return (timeseries.value.system || []).map((s) => {
|
||||
const tm = trafficMap[s.ts] || { download: 0, upload: 0 };
|
||||
return {
|
||||
ts: timestampToDateTime(s.ts),
|
||||
download: formatBytes(tm.download),
|
||||
upload: formatBytes(tm.upload),
|
||||
cpu: `${Math.round((s.cpu || 0) * 10) / 10}%`,
|
||||
mem: `${Math.round((s.mem || 0) * 10) / 10}%`,
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
const { pause: stopPolling, resume: startPolling } = useIntervalFn(
|
||||
() => {
|
||||
loadDashboard();
|
||||
@@ -155,5 +205,11 @@ onUnmounted(() => {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.chart-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
@@ -17,27 +17,50 @@
|
||||
<el-button type="primary" @click="handleAdd">{{ $t("common.add") }}</el-button>
|
||||
</div>
|
||||
<el-table v-loading="loading" :data="records">
|
||||
<el-table-column prop="id" :label="$t('common.id')" width="80" />
|
||||
<el-table-column prop="name" :label="$t('peer.username')" min-width="180" />
|
||||
<el-table-column prop="remark" :label="$t('peer.remark')" min-width="200" />
|
||||
<el-table-column :label="$t('peer.quota')" min-width="140">
|
||||
<template #default="scope">{{ formatBytes(scope.row.quotaBytes) }}</template>
|
||||
<el-table-column :label="$t('peer.name')" min-width="220">
|
||||
<template #default="scope">
|
||||
<div class="peer-title">{{ scope.row.name }}</div>
|
||||
<div class="peer-sub">{{ scope.row.remark || "-" }}</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('peer.download')" min-width="140">
|
||||
<template #default="scope">{{ formatBytes(scope.row.downloadBytes) }}</template>
|
||||
<el-table-column :label="$t('peer.status')" min-width="180">
|
||||
<template #default="scope">
|
||||
<el-tag size="small" :type="scope.row.disabled === 1 ? 'danger' : 'success'">{{ scope.row.disabled === 1 ? $t('common.disable') : $t('common.enable') }}</el-tag>
|
||||
<el-tag size="small" class="ml-1" :type="scope.row.online ? 'success' : 'info'">{{ scope.row.online ? $t('peer.online') : $t('peer.offline') }}</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('peer.upload')" min-width="140">
|
||||
<template #default="scope">{{ formatBytes(scope.row.uploadBytes) }}</template>
|
||||
<el-table-column :label="$t('peer.traffic')" min-width="260">
|
||||
<template #default="scope">
|
||||
<div>{{ formatBytes(scope.row.downloadBytes + scope.row.uploadBytes) }} / {{ quotaText(scope.row.quotaBytes) }}</div>
|
||||
<el-progress :percentage="trafficPercent(scope.row)" :status="scope.row.quotaBytes < 0 ? undefined : (trafficPercent(scope.row) >= 90 ? 'exception' : undefined)" :show-text="false" />
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('peer.devices')" min-width="120">
|
||||
<template #default="scope">{{ scope.row.onlineDevices }} / {{ scope.row.maxDevices }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('peer.expireTime')" min-width="170">
|
||||
<template #default="scope">{{ timestampToDateTime(scope.row.expiresAt) }}</template>
|
||||
<template #default="scope">{{ scope.row.expiresAt === 0 ? $t('peer.unlimited') : timestampToDateTime(scope.row.expiresAt) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('common.operate')" width="320">
|
||||
<el-table-column :label="$t('peer.lastConnectionAt')" min-width="170">
|
||||
<template #default="scope">{{ scope.row.lastConnectionAt ? timestampToDateTime(scope.row.lastConnectionAt) : '-' }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="$t('common.operate')" width="340" fixed="right">
|
||||
<template #default="scope">
|
||||
<el-button link type="primary" @click="copyUri(scope.row)">URI</el-button>
|
||||
<el-button link type="primary" @click="showQr(scope.row)">QR</el-button>
|
||||
<el-button link type="primary" @click="handleUpdate(scope.row)">{{ $t("common.edit") }}</el-button>
|
||||
<el-button link type="danger" @click="handleDelete(scope.row)">{{ $t("common.delete") }}</el-button>
|
||||
<el-button link type="primary" @click="openOverview(scope.row)">{{ $t("peer.overview") }}</el-button>
|
||||
<el-button link type="primary" @click="copyUri(scope.row)">{{ $t("peer.clientUri") }}</el-button>
|
||||
<el-button link type="primary" @click="showQr(scope.row)">{{ $t("peer.clientQr") }}</el-button>
|
||||
<el-dropdown>
|
||||
<span class="el-dropdown-link">{{ $t("common.operate") }}</span>
|
||||
<template #dropdown>
|
||||
<el-dropdown-menu>
|
||||
<el-dropdown-item @click="handleUpdate(scope.row)">{{ $t("common.edit") }}</el-dropdown-item>
|
||||
<el-dropdown-item @click="handleResetTraffic(scope.row)">{{ $t("common.resetTraffic") }}</el-dropdown-item>
|
||||
<el-dropdown-item @click="handleKick(scope.row)">{{ $t("peer.kick") }}</el-dropdown-item>
|
||||
<el-dropdown-item @click="handleReleaseKick(scope.row)">{{ $t("peer.releaseKick") }}</el-dropdown-item>
|
||||
<el-dropdown-item divided @click="handleDelete(scope.row)">{{ $t("common.delete") }}</el-dropdown-item>
|
||||
</el-dropdown-menu>
|
||||
</template>
|
||||
</el-dropdown>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
@@ -51,14 +74,14 @@
|
||||
</el-card>
|
||||
|
||||
<el-dialog v-model="dialog.visible" :title="dialog.title" width="620px">
|
||||
<el-form :model="dataForm" label-width="140px">
|
||||
<el-form-item label="Name"><el-input v-model="dataForm.name" /></el-form-item>
|
||||
<el-form-item label="Remark"><el-input v-model="dataForm.remark" /></el-form-item>
|
||||
<el-form-item label="Secret"><el-input v-model="dataForm.secret" show-password /></el-form-item>
|
||||
<el-form-item label="Quota"><el-input-number v-model="dataForm.quotaBytes" :min="-1" /></el-form-item>
|
||||
<el-form-item label="Expires"><el-date-picker v-model="dataForm.expiresAt" type="datetime" value-format="x" /></el-form-item>
|
||||
<el-form-item label="Max devices"><el-input-number v-model="dataForm.maxDevices" :min="1" /></el-form-item>
|
||||
<el-form-item label="Disabled"><el-switch v-model="disabledBool" /></el-form-item>
|
||||
<el-form ref="formRef" :model="dataForm" :rules="rules" label-width="140px">
|
||||
<el-form-item :label="$t('peer.name')" prop="name"><el-input v-model="dataForm.name" /></el-form-item>
|
||||
<el-form-item :label="$t('peer.remark')"><el-input v-model="dataForm.remark" /></el-form-item>
|
||||
<el-form-item :label="$t('peer.secret')" prop="secret"><el-input v-model="dataForm.secret" show-password /></el-form-item>
|
||||
<el-form-item :label="$t('peer.quota')"><el-input-number v-model="dataForm.quotaBytes" :min="-1" /></el-form-item>
|
||||
<el-form-item :label="$t('peer.expireTime')"><el-date-picker v-model="dataForm.expiresAt" type="datetime" value-format="x" /></el-form-item>
|
||||
<el-form-item :label="$t('peer.maxDevices')"><el-input-number v-model="dataForm.maxDevices" :min="1" /></el-form-item>
|
||||
<el-form-item :label="$t('peer.disabled')"><el-switch v-model="disabledBool" /></el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button type="primary" @click="submitForm">{{ $t("common.confirm") }}</el-button>
|
||||
@@ -68,6 +91,24 @@
|
||||
<el-dialog v-model="qrDialog" title="QR" width="420px">
|
||||
<el-image style="width:300px;height:300px" :src="qrSrc" />
|
||||
</el-dialog>
|
||||
|
||||
<el-drawer v-model="overview.visible" :title="$t('peer.overview')" size="45%">
|
||||
<div v-if="overview.data">
|
||||
<p><b>{{ $t('peer.authId') }}:</b> {{ overview.data.authId }}</p>
|
||||
<p><b>{{ $t('peer.name') }}:</b> {{ overview.data.name }}</p>
|
||||
<p><b>{{ $t('peer.remark') }}:</b> {{ overview.data.remark || '-' }}</p>
|
||||
<p><b>{{ $t('peer.quota') }}:</b> {{ quotaText(overview.data.quotaBytes) }}</p>
|
||||
<p><b>{{ $t('peer.download') }}:</b> {{ formatBytes(overview.data.downloadBytes) }}</p>
|
||||
<p><b>{{ $t('peer.upload') }}:</b> {{ formatBytes(overview.data.uploadBytes) }}</p>
|
||||
<p><b>{{ $t('peer.devices') }}:</b> {{ overview.data.onlineDevices }} / {{ overview.data.maxDevices }}</p>
|
||||
<p><b>{{ $t('peer.expireTime') }}:</b> {{ overview.data.expiresAt === 0 ? $t('peer.unlimited') : timestampToDateTime(overview.data.expiresAt) }}</p>
|
||||
<p><b>{{ $t('peer.lastConnectionAt') }}:</b> {{ overview.data.lastConnectionAt ? timestampToDateTime(overview.data.lastConnectionAt) : '-' }}</p>
|
||||
<div class="mt-2">
|
||||
<el-button type="primary" @click="copyUri(overview.data)">{{ $t("peer.clientUri") }}</el-button>
|
||||
<el-button @click="showQr(overview.data)">{{ $t("peer.clientQr") }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</el-drawer>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -75,13 +116,17 @@
|
||||
import { computed, onMounted, reactive, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import copy from "copy-to-clipboard";
|
||||
import { ElMessageBox } from "element-plus";
|
||||
import { formatBytes } from "@/utils/byte";
|
||||
import { getMonthLater, timestampToDateTime } from "@/utils/time";
|
||||
import {
|
||||
deletePeerApi,
|
||||
getPeerApi,
|
||||
getPeerClientConfigApi,
|
||||
kickPeerApi,
|
||||
pagePeerApi,
|
||||
releaseKickPeerApi,
|
||||
resetPeerTrafficApi,
|
||||
savePeerApi,
|
||||
updatePeerApi,
|
||||
} from "@/api/peer";
|
||||
@@ -93,6 +138,8 @@ const total = ref(0);
|
||||
const records = ref<PeerVo[]>([]);
|
||||
const qrDialog = ref(false);
|
||||
const qrSrc = ref("");
|
||||
const formRef = ref();
|
||||
const overview = reactive<{ visible: boolean; data: PeerVo | null }>({ visible: false, data: null });
|
||||
|
||||
const queryParams = reactive<PeerPageDto>({ pageNum: 1, pageSize: 10, name: undefined, remark: undefined, disabled: undefined });
|
||||
const dialog = reactive({ visible: false, title: "", editId: 0 });
|
||||
@@ -111,6 +158,25 @@ const disabledBool = computed({
|
||||
set: (v: boolean) => (dataForm.disabled = v ? 1 : 0),
|
||||
});
|
||||
|
||||
const rules = {
|
||||
name: [{ required: true, message: t("common.required"), trigger: ["change", "blur"] }],
|
||||
};
|
||||
|
||||
function quotaText(v: number) {
|
||||
return v < 0 ? t("peer.unlimited") : formatBytes(v);
|
||||
}
|
||||
|
||||
function trafficPercent(row: PeerVo) {
|
||||
if (row.quotaBytes < 0 || row.quotaBytes === 0) return 0;
|
||||
const used = row.downloadBytes + row.uploadBytes;
|
||||
return Math.max(0, Math.min(100, Math.round((used / row.quotaBytes) * 100)));
|
||||
}
|
||||
|
||||
function openOverview(row: PeerVo) {
|
||||
overview.data = row;
|
||||
overview.visible = true;
|
||||
}
|
||||
|
||||
async function handleQuery() {
|
||||
loading.value = true;
|
||||
try {
|
||||
@@ -138,6 +204,13 @@ async function handleUpdate(row: PeerVo) {
|
||||
}
|
||||
|
||||
async function submitForm() {
|
||||
if (formRef.value) {
|
||||
const ok = await formRef.value.validate().catch(() => false);
|
||||
if (!ok) return;
|
||||
}
|
||||
if (dialog.editId > 0 && dataForm.secret) {
|
||||
await ElMessageBox.confirm(t("peer.secretRotateConfirm"), t("common.warning"), { type: "warning" });
|
||||
}
|
||||
if (dialog.editId > 0) {
|
||||
const payload: PeerUpdateDto = { id: dialog.editId, name: dataForm.name, secret: dataForm.secret || undefined, quotaBytes: dataForm.quotaBytes, expiresAt: dataForm.expiresAt, maxDevices: dataForm.maxDevices, disabled: dataForm.disabled, remark: dataForm.remark };
|
||||
await updatePeerApi(payload);
|
||||
@@ -149,10 +222,27 @@ async function submitForm() {
|
||||
}
|
||||
|
||||
async function handleDelete(row: PeerVo) {
|
||||
await ElMessageBox.confirm(t("common.deleteConfirm", { username: row.name }), t("common.warning"), { type: "warning" });
|
||||
await deletePeerApi({ id: row.id });
|
||||
await handleQuery();
|
||||
}
|
||||
|
||||
async function handleResetTraffic(row: PeerVo) {
|
||||
await ElMessageBox.confirm(t("common.resetTrafficConfirm"), t("common.warning"), { type: "warning" });
|
||||
await resetPeerTrafficApi({ id: row.id });
|
||||
await handleQuery();
|
||||
}
|
||||
|
||||
async function handleKick(row: PeerVo) {
|
||||
await kickPeerApi(row.id, { bannedUntil: Date.now() + 60 * 60 * 1000 });
|
||||
await handleQuery();
|
||||
}
|
||||
|
||||
async function handleReleaseKick(row: PeerVo) {
|
||||
await releaseKickPeerApi({ id: row.id });
|
||||
await handleQuery();
|
||||
}
|
||||
|
||||
async function copyUri(row: PeerVo) {
|
||||
const { data } = await getPeerClientConfigApi(row.id);
|
||||
copy(data.url);
|
||||
@@ -167,3 +257,8 @@ async function showQr(row: PeerVo) {
|
||||
onMounted(handleQuery);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.peer-title { font-weight: 600; }
|
||||
.peer-sub { color: #909399; font-size: 12px; }
|
||||
</style>
|
||||
|
||||
|
||||
@@ -2,21 +2,27 @@ package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"hy2xs-admin/model/bo"
|
||||
"hy2xs-admin/model/constant"
|
||||
"hy2xs-admin/model/vo"
|
||||
"hy2xs-admin/service"
|
||||
"hy2xs-admin/util"
|
||||
)
|
||||
|
||||
func AdminHandler() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
myClaims, err := service.ParseToken(service.GetToken(c))
|
||||
if err != nil {
|
||||
vo.Fail(err.Error(), c)
|
||||
claimsRaw, ok := c.Get("adminClaims")
|
||||
if !ok {
|
||||
vo.Fail(constant.UnauthorizedError, c)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if !util.ArrContain(myClaims.Admin.Roles, "admin") {
|
||||
claims, castOK := claimsRaw.(bo.AccountBo)
|
||||
if !castOK {
|
||||
vo.Fail(constant.IllegalTokenError, c)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if !util.ArrContain(claims.Roles, "admin") {
|
||||
vo.Fail(constant.ForbiddenError, c)
|
||||
c.Abort()
|
||||
return
|
||||
|
||||
@@ -48,6 +48,7 @@ func JWTHandler() gin.HandlerFunc {
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Set("adminClaims", myClaims.Admin)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
package bo
|
||||
|
||||
import "time"
|
||||
|
||||
type AccountBo struct {
|
||||
Id int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
@@ -10,26 +8,6 @@ type AccountBo struct {
|
||||
TokenVersion int64 `json:"tokenVersion"`
|
||||
}
|
||||
|
||||
type AccountExport struct {
|
||||
Id int64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Pass string `json:"pass"`
|
||||
ConPass string `json:"conPass"`
|
||||
Quota int64 `json:"quota"`
|
||||
Download int64 `json:"download"`
|
||||
Upload int64 `json:"upload"`
|
||||
ExpireTime int64 `json:"expireTime"`
|
||||
DeviceNo int64 `json:"deviceNo"`
|
||||
KickUtilTime int64 `json:"kickUtilTime"`
|
||||
Role string `json:"role"`
|
||||
Deleted int64 `json:"deleted"`
|
||||
CreateTime time.Time `json:"createTime"`
|
||||
UpdateTime time.Time `json:"updateTime"`
|
||||
LoginAt int64 `json:"loginAt"`
|
||||
ConAt int64 `json:"conAt"`
|
||||
Remark string `json:"remark"`
|
||||
}
|
||||
|
||||
type PeerExport struct {
|
||||
Id int64 `json:"id,omitempty"`
|
||||
AuthId string `json:"authId,omitempty"`
|
||||
|
||||
@@ -4,4 +4,3 @@ type AdminChangePasswordDto struct {
|
||||
OldPassword *string `json:"oldPassword" form:"oldPassword" validate:"required,min=6,max=64"`
|
||||
NewPassword *string `json:"newPassword" form:"newPassword" validate:"required,min=6,max=64"`
|
||||
}
|
||||
|
||||
|
||||
@@ -4,4 +4,3 @@ type LoginDto struct {
|
||||
Username *string `json:"username" form:"username" validate:"required,min=6,max=32,validateStr"`
|
||||
Pass *string `json:"pass" form:"pass" validate:"required,min=6,max=64"`
|
||||
}
|
||||
|
||||
|
||||
@@ -31,4 +31,3 @@ type PeerUpdateDto struct {
|
||||
type PeerKickDto struct {
|
||||
BannedUntil *int64 `json:"bannedUntil" form:"bannedUntil" validate:"required,min=0"`
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package entity
|
||||
|
||||
type Account struct {
|
||||
type LegacyAccount struct {
|
||||
Username *string `gorm:"column:username;default:''" json:"username"`
|
||||
Pass *string `gorm:"column:pass;default:''" json:"pass"`
|
||||
ConPass *string `gorm:"column:con_pass;default:''" json:"conPass"`
|
||||
@@ -19,3 +19,7 @@ type Account struct {
|
||||
Remark *string `gorm:"column:remark;default:''" json:"remark"`
|
||||
ForcePasswordChange *int64 `gorm:"column:force_password_change;default:0" json:"forcePasswordChange"`
|
||||
}
|
||||
|
||||
func (LegacyAccount) TableName() string {
|
||||
return "account"
|
||||
}
|
||||
|
||||
@@ -14,4 +14,3 @@ type AdminUser struct {
|
||||
func (AdminUser) TableName() string {
|
||||
return "admin_user"
|
||||
}
|
||||
|
||||
|
||||
@@ -20,4 +20,3 @@ type MetricSample struct {
|
||||
func (MetricSample) TableName() string {
|
||||
return "metric_sample"
|
||||
}
|
||||
|
||||
|
||||
@@ -20,4 +20,3 @@ type Peer struct {
|
||||
func (Peer) TableName() string {
|
||||
return "peer"
|
||||
}
|
||||
|
||||
|
||||
@@ -11,4 +11,3 @@ type TrafficAggregateDaily struct {
|
||||
func (TrafficAggregateDaily) TableName() string {
|
||||
return "traffic_aggregate_daily"
|
||||
}
|
||||
|
||||
|
||||
@@ -11,4 +11,3 @@ type TrafficAggregateHourly struct {
|
||||
func (TrafficAggregateHourly) TableName() string {
|
||||
return "traffic_aggregate_hourly"
|
||||
}
|
||||
|
||||
|
||||
@@ -12,4 +12,3 @@ type TrafficSample struct {
|
||||
func (TrafficSample) TableName() string {
|
||||
return "traffic_sample"
|
||||
}
|
||||
|
||||
|
||||
@@ -6,4 +6,3 @@ type AdminInfoVo struct {
|
||||
Roles []string `json:"roles"`
|
||||
ForcePasswordChange bool `json:"forcePasswordChange"`
|
||||
}
|
||||
|
||||
|
||||
@@ -87,4 +87,3 @@ type DashboardTimeseriesVo struct {
|
||||
System []DashboardSeriesPointVo `json:"system"`
|
||||
CollectedAt int64 `json:"collectedAt"`
|
||||
}
|
||||
|
||||
|
||||
@@ -27,4 +27,3 @@ type PeerClientConfigVo struct {
|
||||
Url string `json:"url"`
|
||||
QrCode []byte `json:"qrCode"`
|
||||
}
|
||||
|
||||
|
||||
@@ -13,4 +13,3 @@ func initAdminRouter(adminApi *gin.RouterGroup) {
|
||||
admin.GET("/security", controller.AdminSecurity)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,4 +14,3 @@ func initDashboardRouter(api *gin.RouterGroup) {
|
||||
dashboard.GET("/security", controller.DashboardSecurity)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,18 @@ import (
|
||||
"hy2xs-admin/util"
|
||||
)
|
||||
|
||||
func adminClaimsFromContext(c *gin.Context) (bo.AccountBo, bool) {
|
||||
if c == nil {
|
||||
return bo.AccountBo{}, false
|
||||
}
|
||||
v, ok := c.Get("adminClaims")
|
||||
if !ok {
|
||||
return bo.AccountBo{}, false
|
||||
}
|
||||
claims, castOK := v.(bo.AccountBo)
|
||||
return claims, castOK
|
||||
}
|
||||
|
||||
func Login(username string, plainPassword string) (string, bool, error) {
|
||||
admin, err := dao.GetAdminUser("username = ? and status = 1", username)
|
||||
if err != nil {
|
||||
@@ -45,11 +57,15 @@ func Login(username string, plainPassword string) (string, bool, error) {
|
||||
}
|
||||
|
||||
func GetAdminInfo(c *gin.Context) (vo.AdminInfoVo, error) {
|
||||
claims, ok := adminClaimsFromContext(c)
|
||||
if !ok {
|
||||
myClaims, err := ParseToken(GetToken(c))
|
||||
if err != nil {
|
||||
return vo.AdminInfoVo{}, err
|
||||
}
|
||||
admin, err := dao.GetAdminUser("id = ?", myClaims.Admin.Id)
|
||||
claims = myClaims.Admin
|
||||
}
|
||||
admin, err := dao.GetAdminUser("id = ?", claims.Id)
|
||||
if err != nil {
|
||||
return vo.AdminInfoVo{}, err
|
||||
}
|
||||
@@ -57,7 +73,7 @@ func GetAdminInfo(c *gin.Context) (vo.AdminInfoVo, error) {
|
||||
return vo.AdminInfoVo{}, errors.New("this account has been disabled")
|
||||
}
|
||||
force := admin.ForcePasswordChange != nil && *admin.ForcePasswordChange != 0
|
||||
return vo.AdminInfoVo{Id: myClaims.Admin.Id, Username: myClaims.Admin.Username, Roles: myClaims.Admin.Roles, ForcePasswordChange: force}, nil
|
||||
return vo.AdminInfoVo{Id: claims.Id, Username: claims.Username, Roles: claims.Roles, ForcePasswordChange: force}, nil
|
||||
}
|
||||
|
||||
func UpdateAdminLastLoginAt(id int64, loginAt int64) error {
|
||||
@@ -100,4 +116,3 @@ func ChangeAdminPassword(c *gin.Context, oldPassword string, newPassword string)
|
||||
func GetAdminForTokenValidation(id int64) (entity.AdminUser, error) {
|
||||
return dao.GetAdminUser("id = ?", id)
|
||||
}
|
||||
|
||||
|
||||
@@ -102,4 +102,3 @@ func DashboardSecurityRisks(summary vo.DashboardSummaryVo) []vo.SecurityRiskVo {
|
||||
}
|
||||
return risks
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/sirupsen/logrus"
|
||||
"hy2xs-admin/dao"
|
||||
"hy2xs-admin/model/constant"
|
||||
"hy2xs-admin/proxy"
|
||||
@@ -51,7 +52,8 @@ func Hysteria2Auth(conPass string) (int64, string, error) {
|
||||
// Ограничение количества устройств
|
||||
onlineUsers, err := Hysteria2Online()
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
logrus.WithError(err).Warn("hysteria2 online users unavailable; skip device-limit check")
|
||||
return *peer.Id, *peer.AuthId, nil
|
||||
}
|
||||
device, exist := onlineUsers[*peer.AuthId]
|
||||
if exist && *peer.MaxDevices <= device {
|
||||
|
||||
@@ -71,4 +71,3 @@ func TestBuildHysteria2Url_MinimalConfig(t *testing.T) {
|
||||
t.Fatalf("unexpected optional query params in minimal config: %s", parsed.RawQuery)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const hysteriaVersionCacheTTL = 15 * time.Minute
|
||||
|
||||
type metricsSnapshot struct {
|
||||
CollectedAt int64
|
||||
System vo.DashboardSystemVo
|
||||
@@ -23,8 +25,37 @@ var metricsStore = struct {
|
||||
sync.RWMutex
|
||||
snapshot metricsSnapshot
|
||||
lastSuccessAt int64
|
||||
version string
|
||||
versionAt time.Time
|
||||
}{}
|
||||
|
||||
func getCachedHysteriaVersion(now time.Time) string {
|
||||
metricsStore.RLock()
|
||||
if metricsStore.version != "" && now.Sub(metricsStore.versionAt) < hysteriaVersionCacheTTL {
|
||||
v := metricsStore.version
|
||||
metricsStore.RUnlock()
|
||||
return v
|
||||
}
|
||||
metricsStore.RUnlock()
|
||||
|
||||
content, err := util.Exec(util.GetHysteria2BinPath() + " version")
|
||||
if err != nil {
|
||||
metricsStore.RLock()
|
||||
v := metricsStore.version
|
||||
metricsStore.RUnlock()
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
return "-"
|
||||
}
|
||||
|
||||
metricsStore.Lock()
|
||||
metricsStore.version = content
|
||||
metricsStore.versionAt = now
|
||||
metricsStore.Unlock()
|
||||
return content
|
||||
}
|
||||
|
||||
func CollectMetricsSnapshot() {
|
||||
nowMs := time.Now().UnixMilli()
|
||||
s := metricsSnapshot{
|
||||
@@ -52,10 +83,7 @@ func CollectMetricsSnapshot() {
|
||||
}
|
||||
|
||||
s.Hysteria.Running = Hysteria2IsRunning()
|
||||
s.Hysteria.Version = "-"
|
||||
if content, err := util.Exec(util.GetHysteria2BinPath() + " version"); err == nil {
|
||||
s.Hysteria.Version = content
|
||||
}
|
||||
s.Hysteria.Version = getCachedHysteriaVersion(time.Now())
|
||||
|
||||
if onlineMap, err := Hysteria2Online(); err == nil {
|
||||
s.Hysteria.ApiReachable = true
|
||||
@@ -80,6 +108,9 @@ func CollectMetricsSnapshot() {
|
||||
running = 1
|
||||
}
|
||||
diskPath := "/"
|
||||
if configured := util.GetEnvDiskPath(); configured != "" {
|
||||
diskPath = configured
|
||||
}
|
||||
metric := entity.MetricSample{
|
||||
SampledAt: &nowMs,
|
||||
CpuPercent: &s.System.CpuPercent,
|
||||
@@ -108,4 +139,3 @@ func DashboardSnapshot() metricsSnapshot {
|
||||
defer metricsStore.RUnlock()
|
||||
return metricsStore.snapshot
|
||||
}
|
||||
|
||||
|
||||
+18
-5
@@ -152,8 +152,12 @@ func GetPeerVo(id int64) (vo.PeerVo, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ResetPeerTraffic(id int64) error { return dao.UpdatePeer([]int64{id}, map[string]interface{}{"download_bytes": 0, "upload_bytes": 0}) }
|
||||
func ReleaseKickPeer(id int64) error { return dao.UpdatePeer([]int64{id}, map[string]interface{}{"banned_until": 0}) }
|
||||
func ResetPeerTraffic(id int64) error {
|
||||
return dao.UpdatePeer([]int64{id}, map[string]interface{}{"download_bytes": 0, "upload_bytes": 0})
|
||||
}
|
||||
func ReleaseKickPeer(id int64) error {
|
||||
return dao.UpdatePeer([]int64{id}, map[string]interface{}{"banned_until": 0})
|
||||
}
|
||||
|
||||
func KickPeer(id int64, bannedUntil int64) error {
|
||||
if err := dao.UpdatePeer([]int64{id}, map[string]interface{}{"banned_until": bannedUntil}); err != nil {
|
||||
@@ -324,6 +328,15 @@ func UpdatePeerLastConnectionAt(id int64, conAt int64) error {
|
||||
return dao.UpdatePeer([]int64{id}, map[string]interface{}{"last_connection_at": conAt})
|
||||
}
|
||||
|
||||
func strVal(v *string) string { if v == nil { return "" }; return *v }
|
||||
func int64Val(v *int64) int64 { if v == nil { return 0 }; return *v }
|
||||
|
||||
func strVal(v *string) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
return *v
|
||||
}
|
||||
func int64Val(v *int64) int64 {
|
||||
if v == nil {
|
||||
return 0
|
||||
}
|
||||
return *v
|
||||
}
|
||||
|
||||
@@ -82,4 +82,3 @@ func DecryptPeerSecret(stored string) (string, error) {
|
||||
}
|
||||
return util.DecryptAESGCM(stored, key)
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,6 @@ func HmacSHA256Hex(payload string, secret string) string {
|
||||
return str
|
||||
}
|
||||
|
||||
|
||||
func DecodeBase64Key(raw string, expectedLen int) ([]byte, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
@@ -122,4 +121,3 @@ func DecryptAESGCM(cipherText string, key []byte) (string, error) {
|
||||
}
|
||||
return string(plain), nil
|
||||
}
|
||||
|
||||
|
||||
+20
-7
@@ -11,9 +11,21 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func resolveDiskPath() string {
|
||||
if configured := strings.TrimSpace(os.Getenv("HY2XS_DISK_PATH")); configured != "" {
|
||||
return configured
|
||||
}
|
||||
return "/"
|
||||
}
|
||||
|
||||
func GetEnvDiskPath() string {
|
||||
return strings.TrimSpace(os.Getenv("HY2XS_DISK_PATH"))
|
||||
}
|
||||
|
||||
func Exec(cmd string) (string, error) {
|
||||
command := exec.Command("bash", "-c", cmd)
|
||||
command.Env = os.Environ()
|
||||
@@ -83,22 +95,23 @@ func GetMemInfo() (*mem.VirtualMemoryStat, error) {
|
||||
}
|
||||
|
||||
func GetDiskPercent() (float64, error) {
|
||||
var err error
|
||||
parts, err := disk.Partitions(true)
|
||||
diskInfo, err := disk.Usage(parts[0].Mountpoint)
|
||||
diskInfo, err := disk.Usage(resolveDiskPath())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
value, err := strconv.ParseFloat(fmt.Sprintf("%.1f", diskInfo.UsedPercent), 64)
|
||||
return value, err
|
||||
}
|
||||
|
||||
func GetDiskInfo() (*disk.UsageStat, error) {
|
||||
parts, err := disk.Partitions(true)
|
||||
usage, err := disk.Usage(resolveDiskPath())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return nil, errors.New("disk partition not found")
|
||||
if usage == nil {
|
||||
return nil, errors.New("disk usage not found")
|
||||
}
|
||||
return disk.Usage(parts[0].Mountpoint)
|
||||
return usage, nil
|
||||
}
|
||||
|
||||
func VerifyPort(port string) error {
|
||||
|
||||
Reference in New Issue
Block a user