Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions agent/app/api/v2/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,38 @@ func (b *BaseApi) UpdateAppLauncher(c *gin.Context) {
helper.Success(c)
}

// @Tags Dashboard
// @Summary Load quick jump options
// @Success 200 {Array} dto.QuickJump
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /dashboard/quick/option [post]
func (b *BaseApi) LoadQuickOption(c *gin.Context) {
helper.SuccessWithData(c, dashboardService.LoadQuickOptions())
}

// @Tags Dashboard
// @Summary Update quick jump
// @Accept json
// @Param request body dto.ChangeQuicks true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /dashboard/quick/change [post]
// @x-panel-log {"bodyKeys":[],"paramKeys":[],"BeforeFunctions":[],"formatZH":"切换快速跳转","formatEN":"change quick jump"}
func (b *BaseApi) UpdateQuickJump(c *gin.Context) {
var req dto.ChangeQuicks
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}

if err := dashboardService.ChangeQuick(req); err != nil {
helper.InternalServer(c, err)
return
}
helper.Success(c)
}

// @Tags Dashboard
// @Summary Load dashboard base info
// @Accept json
Expand Down
20 changes: 15 additions & 5 deletions agent/app/dto/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@ package dto
import "time"

type DashboardBase struct {
WebsiteNumber int `json:"websiteNumber"`
DatabaseNumber int `json:"databaseNumber"`
CronjobNumber int `json:"cronjobNumber"`
AppInstalledNumber int `json:"appInstalledNumber"`

Hostname string `json:"hostname"`
OS string `json:"os"`
Platform string `json:"platform"`
Expand All @@ -23,9 +18,24 @@ type DashboardBase struct {
CPULogicalCores int `json:"cpuLogicalCores"`
CPUModelName string `json:"cpuModelName"`

QuickJumps []QuickJump `json:"quickJump"`
CurrentInfo DashboardCurrent `json:"currentInfo"`
}

type ChangeQuicks struct {
Quicks []QuickJump `json:"quicks"`
}

type QuickJump struct {
ID uint `json:"id"`
Name string `json:"name"`
Title string `json:"title"`
Detail string `json:"detail"`
Recommend int `json:"recommend"`
IsShow bool `json:"isShow"`
Router string `json:"router"`
}

type OsInfo struct {
OS string `json:"os"`
Platform string `json:"platform"`
Expand Down
10 changes: 10 additions & 0 deletions agent/app/model/app_launcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,13 @@ type AppLauncher struct {
BaseModel
Key string `json:"key"`
}

type QuickJump struct {
BaseModel
Name string `json:"name"`
Title string `json:"title"`
Detail string `json:"detail"`
Recommend int `json:"recommend"`
IsShow bool `json:"isShow"`
Router string `json:"router"`
}
46 changes: 46 additions & 0 deletions agent/app/repo/app_launcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ type ILauncherRepo interface {
Create(launcher *model.AppLauncher) error
Save(launcher *model.AppLauncher) error
Delete(opts ...DBOption) error

GetQuickJump(opts ...DBOption) (model.QuickJump, error)
ListQuickJump(withAll bool) []model.QuickJump
UpdateQuicks(quicks []model.QuickJump) error
}

func NewILauncherRepo() ILauncherRepo {
Expand Down Expand Up @@ -57,3 +61,45 @@ func (u *LauncherRepo) Delete(opts ...DBOption) error {
}
return db.Delete(&model.AppLauncher{}).Error
}

func (u *LauncherRepo) GetQuickJump(opts ...DBOption) (model.QuickJump, error) {
var launcher model.QuickJump
db := global.DB
for _, opt := range opts {
db = opt(db)
}
err := db.First(&launcher).Error
return launcher, err
}
func (u *LauncherRepo) ListQuickJump(withAll bool) []model.QuickJump {
var quicks []model.QuickJump
if withAll {
_ = global.DB.Find(&quicks).Error
} else {
_ = global.DB.Where("is_show = ?", true).Find(&quicks).Error
}
if !withAll && len(quicks) == 0 {
return []model.QuickJump{
{Name: "Website", Title: "menu.website", Recommend: 10, IsShow: true, Router: "/websites"},
{Name: "Database", Title: "menu.database", Recommend: 30, IsShow: true, Router: "/databases"},
{Name: "Cronjob", Title: "menu.cronjob", Recommend: 50, IsShow: true, Router: "/cronjobs"},
{Name: "AppInstalled", Title: "home.appInstalled", Recommend: 70, IsShow: true, Router: "/apps/installed"},
}
}

return quicks
}
func (u *LauncherRepo) UpdateQuicks(quicks []model.QuickJump) error {
tx := global.DB.Begin()
for _, item := range quicks {
if err := tx.Model(&model.QuickJump{}).Where("id = ?", item.ID).Updates(map[string]interface{}{
"is_show": item.IsShow,
"detail": item.Detail,
}).Error; err != nil {
tx.Rollback()
return err
}
}
tx.Commit()
return nil
}
93 changes: 67 additions & 26 deletions agent/app/service/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/1Panel-dev/1Panel/agent/app/dto"
"github.com/1Panel-dev/1Panel/agent/app/model"
"github.com/1Panel-dev/1Panel/agent/app/repo"
"github.com/1Panel-dev/1Panel/agent/buserr"
"github.com/1Panel-dev/1Panel/agent/constant"
"github.com/1Panel-dev/1Panel/agent/global"
"github.com/1Panel-dev/1Panel/agent/utils/ai_tools/gpu"
Expand All @@ -38,6 +39,9 @@ type IDashboardService interface {
LoadCurrentInfoForNode() *dto.NodeCurrent
LoadCurrentInfo(ioOption string, netOption string) *dto.DashboardCurrent

LoadQuickOptions() []dto.QuickJump
ChangeQuick(req dto.ChangeQuicks) error

LoadAppLauncher(ctx *gin.Context) ([]dto.AppLauncher, error)
ChangeShow(req dto.SettingUpdate) error
ListLauncherOption(filter string) ([]dto.LauncherOption, error)
Expand Down Expand Up @@ -140,7 +144,7 @@ func (u *DashboardService) LoadBaseInfo(ioOption string, netOption string) (*dto
baseInfo.KernelVersion = hostInfo.KernelVersion
ss, _ := json.Marshal(hostInfo)
baseInfo.VirtualizationSystem = string(ss)
baseInfo.IpV4Addr = GetOutboundIP()
baseInfo.IpV4Addr = loadOutboundIP()
httpProxy := os.Getenv("http_proxy")
if httpProxy == "" {
httpProxy = os.Getenv("HTTP_PROXY")
Expand All @@ -150,30 +154,7 @@ func (u *DashboardService) LoadBaseInfo(ioOption string, netOption string) (*dto
}
baseInfo.SystemProxy = "noProxy"

appInstall, err := appInstallRepo.ListBy(context.Background())
if err != nil {
return nil, err
}
baseInfo.AppInstalledNumber = len(appInstall)
postgresqlDbs, err := postgresqlRepo.List()
if err != nil {
return nil, err
}
mysqlDbs, err := mysqlRepo.List()
if err != nil {
return nil, err
}
baseInfo.DatabaseNumber = len(mysqlDbs) + len(postgresqlDbs)
website, err := websiteRepo.GetBy()
if err != nil {
return nil, err
}
baseInfo.WebsiteNumber = len(website)
cronjobs, err := cronjobRepo.List()
if err != nil {
return nil, err
}
baseInfo.CronjobNumber = len(cronjobs)
loadQuickJump(&baseInfo)

cpuInfo, err := cpu.Info()
if err == nil {
Expand Down Expand Up @@ -347,6 +328,39 @@ func (u *DashboardService) ChangeShow(req dto.SettingUpdate) error {
return nil
}

func (u *DashboardService) LoadQuickOptions() []dto.QuickJump {
quicks := launcherRepo.ListQuickJump(true)
var list []dto.QuickJump
for _, quick := range quicks {
var item dto.QuickJump
_ = copier.Copy(&item, &quick)
list = append(list, item)
}
return list
}
func (u *DashboardService) ChangeQuick(req dto.ChangeQuicks) error {
showCount := 0
var quicks []model.QuickJump
for _, item := range req.Quicks {
var quick model.QuickJump
if item.IsShow {
showCount++
}
if err := copier.Copy(&quick, &item); err != nil {
return err
}
quicks = append(quicks, quick)
}
if showCount == 0 {
return buserr.New("ErrMinQuickJump")
}
if showCount > 4 {
return buserr.New("ErrMaxQuickJump")
}

return launcherRepo.UpdateQuicks(quicks)
}

func (u *DashboardService) ListLauncherOption(filter string) ([]dto.LauncherOption, error) {
showList, _ := launcherRepo.ListName()
var data []dto.LauncherOption
Expand Down Expand Up @@ -545,7 +559,7 @@ func loadXpuInfo() []dto.XPUInfo {
return data
}

func GetOutboundIP() string {
func loadOutboundIP() string {
conn, err := network.Dial("udp", "8.8.8.8:80")

if err != nil {
Expand All @@ -556,3 +570,30 @@ func GetOutboundIP() string {
localAddr := conn.LocalAddr().(*network.UDPAddr)
return localAddr.IP.String()
}

func loadQuickJump(base *dto.DashboardBase) {
quicks := launcherRepo.ListQuickJump(false)
for i := 0; i < len(quicks); i++ {
switch quicks[i].Name {
case "Website":
website, _ := websiteRepo.GetBy()
quicks[i].Detail = fmt.Sprintf("%d", len(website))
case "Database":
postgresqlDbs, _ := postgresqlRepo.List()
mysqlDbs, _ := mysqlRepo.List()
quicks[i].Detail = fmt.Sprintf("%d", len(mysqlDbs)+len(postgresqlDbs))
case "Cronjob":
cronjobs, _ := cronjobRepo.List()
quicks[i].Detail = fmt.Sprintf("%d", len(cronjobs))
case "AppInstalled":
appInstall, _ := appInstallRepo.ListBy(context.Background())
quicks[i].Detail = fmt.Sprintf("%d", len(appInstall))
}
var item dto.QuickJump
_ = copier.Copy(&item, quicks[i])
base.QuickJumps = append(base.QuickJumps, item)
}
sort.Slice(quicks, func(i, j int) bool {
return quicks[i].Recommend < quicks[j].Recommend
})
}
3 changes: 3 additions & 0 deletions agent/i18n/lang/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ ErrApiConfigIPInvalid: 'The IP used to call the API interface is not in the whit
ErrApiConfigDisable: 'This interface prohibits the use of API interface calls: {{ .detail }}'
ErrApiConfigKeyTimeInvalid: 'API interface timestamp error: {{ .detail }}'

ErrMinQuickJump: "Please set at least one quick jump entry!"
ErrMaxQuickJump: "You can set up to four quick jump entries!"

#common
ErrUsernameIsExist: 'Username already exists'
ErrNameIsExist: 'Name already exists'
Expand Down
3 changes: 3 additions & 0 deletions agent/i18n/lang/ja.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ ErrApiConfigIPInvalid: 'API インターフェースの呼び出しに使用さ
ErrApiConfigDisable: 'このインターフェースは、API インターフェース呼び出しの使用を禁止しています: {{ .detail }}'
ErrApiConfigKeyTimeInvalid: 'API インターフェースのタイムスタンプ エラー: {{ .detail }}'

ErrMinQuickJump: "少なくとも1つのクイックジャンプエントリを設定してください!"
ErrMaxQuickJump: "最大4つのクイックジャンプエントリを設定できます!"

#common
ErrUsernameIsExist: 'ユーザー名は既に存在します'
ErrNameIsExist: '名前は既に存在します'
Expand Down
3 changes: 3 additions & 0 deletions agent/i18n/lang/ko.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ ErrApiConfigIPInvalid: 'API 인터페이스를 호출하는 데 사용된 IP가
ErrApiConfigDisable: '이 인터페이스는 API 인터페이스 호출 사용을 금지합니다: {{ .detail }}'
ErrApiConfigKeyTimeInvalid: 'API 인터페이스 타임스탬프 오류: {{ .detail }}'

ErrMinQuickJump: "최소 하나의 빠른 점프 항목을 설정해 주세요!"
ErrMaxQuickJump: "최대 네 개의 빠른 점프 항목을 설정할 수 있습니다!"

#흔한
ErrUsernameIsExist: '사용자 이름이 이미 존재합니다'
ErrNameIsExist: '이름이 이미 존재합니다'
Expand Down
3 changes: 3 additions & 0 deletions agent/i18n/lang/ms.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ StartPushSSLToNode: "Mula menolak sijil ke nod"
PushSSLToNodeFailed: "Gagal menolak sijil ke nod: {{ .err }}"
PushSSLToNodeSuccess: "Berjaya menolak sijil ke nod"

ErrMinQuickJump: "Sila tetapkan sekurang-kurangnya satu entri lompat pantas!"
ErrMaxQuickJump: "Anda boleh menetapkan sehingga empat entri lompat pantas!"

#biasa
ErrUsernameIsExist: 'Nama pengguna sudah wujud'
ErrNameIsExist: 'Nama sudah wujud'
Expand Down
3 changes: 3 additions & 0 deletions agent/i18n/lang/pt-BR.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ StartPushSSLToNode: "Iniciando o envio do certificado para o nó"
PushSSLToNodeFailed: "Falha ao enviar o certificado para o nó: {{ .err }}"
PushSSLToNodeSuccess: "Certificado enviado com sucesso para o nó"

ErrMinQuickJump: "Defina pelo menos uma entrada de salto rápido!"
ErrMaxQuickJump: "Você pode definir até quatro entradas de salto rápido!"

#comum
ErrUsernameIsExist: 'Nome de usuário já existe'
ErrNameIsExist: 'Nome já existe'
Expand Down
3 changes: 3 additions & 0 deletions agent/i18n/lang/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ StartPushSSLToNode: "Начало отправки сертификата на
PushSSLToNodeFailed: "Не удалось отправить сертификат на узел: {{ .err }}"
PushSSLToNodeSuccess: "Сертификат успешно отправлен на узел"

ErrMinQuickJump: "Пожалуйста, установите хотя бы одну запись быстрого перехода!"
ErrMaxQuickJump: "Можно установить до четырех записей быстрого перехода!"

#общий
ErrUsernameIsExist: 'Имя пользователя уже существует'
ErrNameIsExist: 'Имя уже существует'
Expand Down
3 changes: 3 additions & 0 deletions agent/i18n/lang/tr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ StartPushSSLToNode: "Sertifika düğüme gönderilmeye başlandı"
PushSSLToNodeFailed: "Sertifika düğüme gönderilemedi: {{ .err }}"
PushSSLToNodeSuccess: "Sertifika düğüme başarıyla gönderildi"

ErrMinQuickJump: "Lütfen en az bir hızlı atlama girişi ayarlayın!"
ErrMaxQuickJump: "En fazla dört hızlı atlama girişi ayarlayabilirsiniz!"

#common
ErrUsernameIsExist: 'Kullanıcı adı zaten mevcut'
ErrNameIsExist: 'İsim zaten mevcut'
Expand Down
3 changes: 3 additions & 0 deletions agent/i18n/lang/zh-Hant.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ ErrApiConfigIPInvalid: '呼叫 API 介面 IP 不在白名單: {{ .detail }}'
ErrApiConfigDisable: '此介面禁止使用 API 介面呼叫: {{ .detail }}'
ErrApiConfigKeyTimeInvalid: 'API 介面時間戳記錯誤: {{ .detail }}'

ErrMinQuickJump: "請至少設定一個快速跳轉入口!"
ErrMaxQuickJump: "最多可設定四個快速跳轉入口!"

#common
ErrUsernameIsExist: '使用者名稱已存在'
ErrNameIsExist: '名稱已存在'
Expand Down
3 changes: 3 additions & 0 deletions agent/i18n/lang/zh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ ErrApiConfigIPInvalid: "调用 API 接口 IP 不在白名单: {{ .detail }}"
ErrApiConfigDisable: "此接口禁止使用 API 接口调用: {{ .detail }}"
ErrApiConfigKeyTimeInvalid: "API 接口时间戳错误: {{ .detail }}"

ErrMinQuickJump: "请至少设置一个快速跳转入口!"
ErrMaxQuickJump: "最多可设置四个快速跳转入口!"

#common
ErrUsernameIsExist: "用户名已存在"
ErrNameIsExist: "名称已存在"
Expand Down
1 change: 1 addition & 0 deletions agent/init/migration/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func InitAgentDB() {
migrations.InitCronjobGroup,
migrations.AddColumnToAlert,
migrations.UpdateWebsiteSSL,
migrations.AddQuickJump,
})
if err := m.Migrate(); err != nil {
global.LOG.Error(err)
Expand Down
Loading
Loading