yinbangzhong
2024-06-17 db7e3c55cef94793dcc0b651c90e5c8b21b8bcc9
watch preloads file to autoload
6个文件已修改
171 ■■■■ 已修改文件
controllers/audio.go 143 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/docs.go 8 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/swagger.json 8 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
docs/swagger.yaml 6 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
models/audio.go 5 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
request/audio.go 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
controllers/audio.go
@@ -9,6 +9,7 @@
    "mime/multipart"
    "os"
    "path"
    "path/filepath"
    "speechAnalysis/constvar"
    "speechAnalysis/extend/code"
    "speechAnalysis/extend/util"
@@ -28,66 +29,88 @@
// @Tags      音频
// @Summary   上传音频
// @Produce   application/json
// @Param file formData file false "音频文件"
// @Param files formData []file false "多个音频文件"
// @Param files formData []file false "多文件上传"
// @Success   200 {object} util.Response "成功"
// @Router    /api-sa/v1/audio/upload [post]
func (slf AudioCtl) Upload(c *gin.Context) {
    f := func(header *multipart.FileHeader) error {
        logFormat := "%s,%s   "
    var headers []*multipart.FileHeader
    if len(c.Request.MultipartForm.File["file"]) > 1 {
        headers = c.Request.MultipartForm.File["file"]
    } else {
        util.ResponseFormat(c, code.RequestParamError, "文件需要一一对应")
        return
    }
    audio := &models.Audio{}
    for _, header := range headers {
        filename := path.Base(header.Filename)
        arr := strings.Split(filename, "_")
        if len(arr) != 6 {
            //util.ResponseFormat(c, code.RequestParamError, "文件名称错误")
            return errors.New(fmt.Sprintf(logFormat, filename, "文件名称错误"))
            util.ResponseFormat(c, code.RequestParamError, "文件名称错误")
            return
        }
        _, err := models.NewAudioSearch().SetName(filename).First()
        if err != gorm.ErrRecordNotFound {
            //util.ResponseFormat(c, code.RequestParamError, "重复上传")
            return errors.New(fmt.Sprintf(logFormat, filename, "重复上传"))
            util.ResponseFormat(c, code.RequestParamError, "重复上传")
            return
        }
        oss := upload.NewOss()
        filePath, filename, uploadErr := oss.UploadFile(header)
        if uploadErr != nil {
            logx.Errorf("upload audio err: %v", err)
            //util.ResponseFormat(c, code.RequestParamError, "上传失败")
            return errors.New(fmt.Sprintf(logFormat, filename, "上传失败"))
            util.ResponseFormat(c, code.RequestParamError, "上传失败")
            return
        }
        if filepath.Ext(filename) == ".mp3" || filepath.Ext(filename) == ".wav" {
        timeStr := arr[4] + strings.Split(arr[5], ".")[0]
        t, err := time.ParseInLocation("20060102150405", timeStr, time.Local)
        if err != nil {
            //util.ResponseFormat(c, code.RequestParamError, "时间格式不对")
            return errors.New(fmt.Sprintf(logFormat, filename, "上传失败"))
                util.ResponseFormat(c, code.RequestParamError, "时间格式不对")
                return
        }
        audio := &models.Audio{
            Name:             filename,
            Size:             header.Size,
            FilePath:         filePath,
            AudioStatus:      constvar.AudioStatusUploadOk,
            LocomotiveNumber: arr[0],
            TrainNumber:      arr[1],
            DriverNumber:     arr[2],
            Station:          arr[3],
            OccurrenceAt:     t,
            IsFollowed:       0,
            audio.Name = filename
            audio.Size = header.Size
            audio.FilePath = filePath
            audio.AudioStatus = constvar.AudioStatusUploadOk
            audio.LocomotiveNumber = arr[0]
            audio.TrainNumber = arr[1]
            audio.DriverNumber = arr[2]
            audio.Station = arr[3]
            audio.OccurrenceAt = t
            audio.IsFollowed = 0
        }
        if err = models.NewAudioSearch().Create(audio); err != nil {
            //util.ResponseFormat(c, code.SaveFail, "上传失败")
            return errors.New(fmt.Sprintf(logFormat, filename, "上传失败"))
        if filepath.Ext(filename) == ".txt" {
            audio.TxtFilePath = filePath
            //读取filepath文件内容到bts
            bts, err := os.ReadFile(filePath)
            if err != nil {
                util.ResponseFormat(c, code.RequestParamError, "读取文件失败")
                return
            }
            //解析 交路号:123_公里标:321
            fileds := string(bts)
            arr = strings.Split(fileds, "_")
            if len(arr) > 1 {
                util.ResponseFormat(c, code.RequestParamError, "文件内容格式不对")
                return
            } else {
                RouteNumber := strings.Split(arr[0], ":")
                KilometerMarker := strings.Split(arr[1], ":")
                if len(RouteNumber) > 1 && len(KilometerMarker) > 1 {
                    audio.RouteNumber = RouteNumber[1]
                    audio.KilometerMarker = KilometerMarker[1]
                } else {
                    util.ResponseFormat(c, code.RequestParamError, "文件内容格式不对")
                    return
                }
            }
        }
    }
    if err := models.NewAudioSearch().Create(audio); err != nil {
        util.ResponseFormat(c, code.SaveFail, "上传失败")
        return
        }
        go func() {
            var trainInfoNames = []string{arr[0], arr[1], arr[3]}
        var trainInfoNames = []string{audio.LocomotiveNumber, audio.TrainNumber, audio.Station}
            var (
                info   *models.TrainInfo
                err    error
@@ -107,35 +130,7 @@
                }
                parent = *info
            }
        }()
        return nil
    }
    var headers []*multipart.FileHeader
    _, header, _ := c.Request.FormFile("file")
    if header != nil {
        headers = append(headers, header)
    }
    if len(c.Request.MultipartForm.File["files"]) > 0 {
        headers = c.Request.MultipartForm.File["files"]
    }
    var errs []error
    for _, h := range headers {
        if e := f(h); e != nil {
            errs = append(errs, e)
        }
    }
    if len(errs) > 0 {
        var r strings.Builder
        for _, e := range errs {
            r.WriteString(e.Error())
        }
        util.ResponseFormat(c, code.RequestParamError, r.String())
        return
    } else {
        util.ResponseFormat(c, code.Success, "添加成功")
        return
    }
}
func (slf AudioCtl) ParamsCheck(filename string) (err error) {
@@ -289,13 +284,22 @@
        util.ResponseFormat(c, code.InternalError, "查询失败")
        return
    }
    if audio.FilePath == "" {
    filepath := ""
    if params.Filetype == 1 {
        filepath = audio.FilePath
        c.Header("Content-Type", "audio/mpeg") // 设置音频文件类型
    }
    if params.Filetype == 2 {
        filepath = audio.TxtFilePath
        //设置Content-Type为txt文件类型
        c.Header("Content-Type", "text/plain")
    }
    if filepath == "" {
        util.ResponseFormat(c, code.InternalError, "查询失败")
        return
    }
    file, err := os.Open(audio.FilePath)
    file, err := os.Open(filepath)
    if err != nil {
        util.ResponseFormat(c, code.InternalError, "文件打开失败")
        return
@@ -310,7 +314,6 @@
    c.Header("Content-Disposition", "inline; filename="+audio.Name) // 在浏览器中直接打开
    c.Header("Content-Length", fmt.Sprint(fileInfo.Size()))
    c.Header("Content-Type", "audio/mpeg") // 设置音频文件类型
    if _, err := io.Copy(c.Writer, file); err != nil {
        util.ResponseFormat(c, code.InternalError, "文件传输失败")
docs/docs.go
@@ -466,18 +466,12 @@
                "summary": "上传音频",
                "parameters": [
                    {
                        "type": "file",
                        "description": "音频文件",
                        "name": "file",
                        "in": "formData"
                    },
                    {
                        "type": "array",
                        "items": {
                            "type": "file"
                        },
                        "collectionFormat": "csv",
                        "description": "多个音频文件",
                        "description": "多文件上传",
                        "name": "files",
                        "in": "formData"
                    }
docs/swagger.json
@@ -455,18 +455,12 @@
                "summary": "上传音频",
                "parameters": [
                    {
                        "type": "file",
                        "description": "音频文件",
                        "name": "file",
                        "in": "formData"
                    },
                    {
                        "type": "array",
                        "items": {
                            "type": "file"
                        },
                        "collectionFormat": "csv",
                        "description": "多个音频文件",
                        "description": "多文件上传",
                        "name": "files",
                        "in": "formData"
                    }
docs/swagger.yaml
@@ -484,12 +484,8 @@
  /api-sa/v1/audio/upload:
    post:
      parameters:
      - description: 音频文件
        in: formData
        name: file
        type: file
      - collectionFormat: csv
        description: 多个音频文件
        description: 多文件上传
        in: formData
        items:
          type: file
models/audio.go
@@ -15,12 +15,15 @@
        gorm.Model
        Name             string               `gorm:"index;type:varchar(255);not null;default:'';comment:音频名称" json:"name"`            // 音频名称
        Size             int64                `gorm:"type:int;not null;default:0;comment:文件大小" json:"size"`                            // 音频大小
        FilePath         string               `gorm:"type:varchar(255);not null;default:'';comment:音频路径" json:"-"`                     //音频路径                                               // 音频路径
        FilePath         string               `gorm:"type:varchar(255);not null;default:'';comment:音频路径" json:"-"`                     //音频路径
        TxtFilePath      string               `gorm:"type:varchar(255);not null;default:'';comment:txt路径" json:"-"`                    //txt路径
        AudioStatus      constvar.AudioStatus `gorm:"type:tinyint;not null;default:0;comment:状态" json:"audioStatus"`                   // 音频状态
        LocomotiveNumber string               `gorm:"index;type:varchar(255);not null;default:'';comment:机车号" json:"locomotiveNumber"` // 机车号
        TrainNumber      string               `gorm:"index;type:varchar(255);not null;default:'';comment:车次" json:"trainNumber"`       // 车次
        DriverNumber     string               `gorm:"index;type:varchar(255);not null;default:'';comment:司机号" json:"driverNumber"`     // 司机号
        Station          string               `gorm:"index;type:varchar(255);not null;default:'';comment:车站号" json:"station"`          // 车站
        RouteNumber      string               `gorm:"index;type:varchar(255);not null;default:'';comment:交路号" json:"station"`          // 交路号
        KilometerMarker  string               `gorm:"index;type:varchar(255);not null;default:'';comment:公里标" json:"station"`          // 公里标
        OccurrenceAt     time.Time            `json:"-"`
        OccurrenceTime   string               `json:"occurrenceTime" gorm:"-"`
        IsFollowed       constvar.BoolType    `gorm:"type:tinyint;not null;default:2;comment:是否关注"`                        //是否关注 1关注 2未关注
request/audio.go
@@ -20,6 +20,7 @@
type ProcessAudio struct {
    ID uint `json:"id" form:"id" binding:"required"`
    Filetype int  `json:"fileType" form:"fileType"`
}
type BatchProcessAudio struct {