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
41 changes: 41 additions & 0 deletions agent/app/api/v2/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -901,3 +901,44 @@ func (b *BaseApi) GetUsersAndGroups(c *gin.Context) {
}
helper.SuccessWithData(c, res)
}

// @Tags File
// @Summary Convert file
// @Accept json
// @Param request body request.FileConvert true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /files/convert [post]
func (b *BaseApi) ConvertFile(c *gin.Context) {
var req request.FileConvertRequest
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
fileService.Convert(req)
helper.SuccessWithData(c, nil)
}

// @Tags File
// @Summary Convert file
// @Accept json
// @Param request body dto.PageInfo true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /files/convert/log [post]
func (b *BaseApi) ConvertLog(c *gin.Context) {
var req dto.PageInfo
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
total, logs, err := fileService.ConvertLog(req)
if err != nil {
helper.InternalServer(c, err)
return
}
helper.SuccessWithData(c, dto.PageResult{
Items: logs,
Total: total,
})
}
16 changes: 16 additions & 0 deletions agent/app/dto/request/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,19 @@ type FileExistReq struct {
Name string `json:"name" validate:"required"`
Dir string `json:"dir" validate:"required"`
}

type FileConvert struct {
Path string `json:"path" validate:"required"`
Type string `json:"type" validate:"required"`
InputFile string `json:"inputFile" validate:"required"`
Extension string `json:"extension" validate:"required"`
OutputFormat string `json:"outputFormat" validate:"required"`
Status string `json:"status"`
}

type FileConvertRequest struct {
Files []FileConvert `json:"files" validate:"required"`
OutputPath string `json:"outputPath" validate:"required"`
DeleteSource bool `json:"deleteSource"`
TaskID string `json:"taskID"`
}
8 changes: 8 additions & 0 deletions agent/app/dto/response/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,11 @@ type DepthDirSizeRes struct {
Path string `json:"path"`
Size int64 `json:"size"`
}

type FileConvertLog struct {
Date string `json:"date"`
Type string `json:"type"`
Log string `json:"log"`
Status string `json:"status"`
Message string `json:"message"`
}
105 changes: 105 additions & 0 deletions agent/app/service/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ package service
import (
"bufio"
"context"
"encoding/json"
"fmt"
"github.com/1Panel-dev/1Panel/agent/app/task"
"github.com/1Panel-dev/1Panel/agent/i18n"
"github.com/1Panel-dev/1Panel/agent/utils/convert"
"io"
"io/fs"
"os"
Expand Down Expand Up @@ -66,6 +70,8 @@ type IFileService interface {
BatchCheckFiles(req request.FilePathsCheck) []response.ExistFileInfo
GetHostMount() []dto.DiskInfo
GetUsersAndGroups() (*response.UserGroupResponse, error)
Convert(req request.FileConvertRequest)
ConvertLog(req dto.PageInfo) (int64, []response.FileConvertLog, error)
}

var filteredPaths = []string{
Expand Down Expand Up @@ -723,3 +729,102 @@ func getValidUsers(validGroups map[string]bool) ([]response.UserInfo, map[string
}
return users, groupSet, nil
}

func (f *FileService) Convert(req request.FileConvertRequest) {
convertTask, err := task.NewTaskWithOps(i18n.GetMsgByKey("FileConvert"), task.TaskExec, task.TaskScopeFileConvert, req.TaskID, 1)
if err != nil {
global.LOG.Errorf("Create convert task failed %v", err)
return
}
convertTask.AddSubTask(task.GetTaskName(i18n.GetMsgByKey("FileConvert"), task.TaskExec, task.TaskScopeFileConvert), func(t *task.Task) (err error) {
for _, file := range req.Files {
input := filepath.Join(file.Path, file.InputFile)
nameOnly := file.InputFile[0 : len(file.InputFile)-len(file.Extension)]
output := filepath.Join(req.OutputPath, nameOnly+"."+file.OutputFormat)
status, errMsg := convert.MediaFile(input, output, file.OutputFormat, req.DeleteSource)
if status == "FAILED" {
convertTask.Log(fmt.Sprintf("%s -> %s [%s]: %s\n",
input, output, status, errMsg))
} else {
convertTask.Log(fmt.Sprintf("%s -> %s [%s]: %s\n",
input, output, status, "SUCCESS"))
}
}
return nil
}, nil)
go func() {
_ = convertTask.Execute()
}()
}

func (f *FileService) ConvertLog(req dto.PageInfo) (total int64, data []response.FileConvertLog, err error) {
logFilePath := filepath.Join(global.Dir.ConvertLogDir, "convert.log")
file, err := os.Open(logFilePath)
if err != nil {
return 0, nil, err
}
defer file.Close()

stat, err := file.Stat()
if err != nil {
return 0, nil, err
}
size := stat.Size()

buffer := make([]byte, 1)
var line strings.Builder
var lines []response.FileConvertLog
var lineCount int64

skipCount := int64((req.Page - 1) * req.PageSize)

for offset := size - 1; offset >= 0; offset-- {
_, err := file.ReadAt(buffer, offset)
if err != nil {
break
}

if buffer[0] == '\n' {
text := reverse(line.String())
line.Reset()
if text == "" {
continue
}

var entry response.FileConvertLog
if err := json.Unmarshal([]byte(text), &entry); err != nil {
continue
}

if lineCount >= skipCount && len(lines) < req.PageSize {
lines = append(lines, entry)
}
lineCount++
} else {
line.WriteByte(buffer[0])
}
}

if line.Len() > 0 {
text := reverse(line.String())
var entry response.FileConvertLog
if err := json.Unmarshal([]byte(text), &entry); err == nil {
if lineCount >= skipCount && len(lines) < req.PageSize {
lines = append(lines, entry)
}
lineCount++
}
}

total = lineCount
data = lines
return total, data, nil
}

func reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
2 changes: 2 additions & 0 deletions agent/app/task/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ const (
TaskExec = "TaskExec"
TaskBatch = "TaskBatch"
TaskProtect = "TaskProtect"
TaskConvert = "TaskConvert"
)

const (
Expand All @@ -93,6 +94,7 @@ const (
TaskScopeRuntimeExtension = "RuntimeExtension"
TaskScopeCustomAppstore = "CustomAppstore"
TaskScopeTamper = "Tamper"
TaskScopeFileConvert = "Convert"
)

func GetTaskName(resourceName, operate, scope string) string {
Expand Down
1 change: 1 addition & 0 deletions agent/global/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ type SystemDir struct {
RecycleBinDir string
SSLLogDir string
McpDir string
ConvertLogDir string
}

type LogConfig struct {
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ TaskIsExecuting: 'Task is running'
CustomAppstore: 'Custom application warehouse'
TaskExec: 'Execute'
TaskBatch: "Batch Operation"
FileConvert: 'File Conversion'

# task - clam
Clamscan: "Scan {{ .name }}"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/es-ES.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,7 @@ CustomAppstore: 'Almacén de aplicaciones personalizado'
TaskClean: "Limpieza"
TaskExec: "Ejecutar"
TaskBatch: "Operación por Lotes"
FileConvert: 'Conversión de Formato de Archivo'

# task - ai
OllamaModelPull: 'Descargar modelo Ollama {{ .name }}'
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ja.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,7 @@ TaskIsExecuting: 'タスクは実行中です'
CustomAppstore: 'カスタム アプリケーション ウェアハウス'
TaskExec: '実行'
TaskBatch: "一括操作"
FileConvert: 'ファイル形式の変換'

# task - clam
Clamscan: "{{ .name }} をスキャン"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ko.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ TaskIsExecuting: '작업이 실행 중입니다'
CustomAppstore: '사용자 정의 애플리케이션 웨어하우스'
TaskExec: '실행'
TaskBatch: "일괄 작업"
FileConvert: '파일 형식 변환'

# task - clam
Clamscan: "{{ .name }} 스캔"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ms.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ TaskIsExecuting: 'Tugas sedang berjalan'
CustomAppstore: 'Gudang aplikasi tersuai'
TaskExec: 'Laksanakan'
TaskBatch: "Operasi Batch"
FileConvert: 'Penukaran Format Fail'

# task - clam
Clamscan: "Imbas {{ .name }}"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/pt-BR.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ TaskIsExecuting: 'A tarefa está em execução'
CustomAppstore: 'Armazém de aplicativos personalizados'
TaskExec: 'Executar'
TaskBatch: "Operação em Lote"
FileConvert: 'Conversão de Formato de Arquivo'

# task - clam
Clamscan: "Escanear {{ .name }}"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,7 @@ TaskIsExecuting: 'Задача выполняется'
CustomAppstore: 'Хранилище пользовательских приложений'
TaskExec: 'Выполнить'
TaskBatch: "Пакетная операция"
FileConvert: 'Преобразование формата файла'

# task - clam
Clamscan: "Сканировать {{ .name }}"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/tr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ TaskIsExecuting: 'Görev çalışıyor'
CustomAppstore: 'Özel uygulama deposu'
TaskExec: 'Çalıştır'
TaskBatch: "Toplu İşlem"
FileConvert: 'Dosya Formatı Dönüştürme'

# task - clam
Clamscan: "{{ .name }} Tara"
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/zh-Hant.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,7 @@ TaskIsExecuting: '任務正在運作'
CustomAppstore: '自訂應用程式倉庫'
TaskExec: '執行'
TaskBatch: "批量操作"
FileConvert: '文件格式轉換'

# task - clam
Clamscan: "掃描 {{ .name }}"
Expand Down
3 changes: 2 additions & 1 deletion agent/i18n/lang/zh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ ErrAppVersionDeprecated: " {{ .name }} 应用不适配当前 1Panel 版本,跳
ErrDockerFailed: "Docker 状态异常,请检查服务状态"
ErrDockerComposeCmdNotFound: "Docker Compose 命令不存在,请先在宿主机安装此命令"

#ssh
#ssh
ExportIP: "登录 IP"
ExportArea: "归属地"
ExportPort: "端口"
Expand Down Expand Up @@ -369,6 +369,7 @@ TaskIsExecuting: "任务正在运行"
CustomAppstore: "自定义应用仓库"
TaskExec: "执行"
TaskBatch: "批量操作"
FileConvert: "文件格式转换"

# task - clam
Clamscan: "扫描 {{ .name }}"
Expand Down
1 change: 1 addition & 0 deletions agent/init/dir/dir.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,5 @@ func Init() {
global.Dir.RecycleBinDir, _ = fileOp.CreateDirWithPath(true, "/.1panel_clash")
global.Dir.SSLLogDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/log/ssl"))
global.Dir.McpDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/mcp"))
global.Dir.ConvertLogDir, _ = fileOp.CreateDirWithPath(true, path.Join(baseDir, "1panel/log/convert"))
}
2 changes: 2 additions & 0 deletions agent/router/ro_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,7 @@ func (f *FileRouter) InitRouter(Router *gin.RouterGroup) {
fileRouter.GET("/path/:type", baseApi.GetPathByType)
fileRouter.POST("/mount", baseApi.GetHostMount)
fileRouter.POST("/user/group", baseApi.GetUsersAndGroups)
fileRouter.POST("/convert", baseApi.ConvertFile)
fileRouter.POST("/convert/log", baseApi.ConvertLog)
}
}
Loading
Loading