Pārlūkot izejas kodu

watch preloads file to autoload

yinbangzhong 2 gadi atpakaļ
vecāks
revīzija
db7e3c55ce
6 mainītis faili ar 102 papildinājumiem un 111 dzēšanām
  1. 93 90
      controllers/audio.go
  2. 1 7
      docs/docs.go
  3. 1 7
      docs/swagger.json
  4. 1 5
      docs/swagger.yaml
  5. 4 1
      models/audio.go
  6. 2 1
      request/audio.go

+ 93 - 90
controllers/audio.go

@@ -9,6 +9,7 @@ import (
 	"mime/multipart"
 	"os"
 	"path"
+	"path/filepath"
 	"speechAnalysis/constvar"
 	"speechAnalysis/extend/code"
 	"speechAnalysis/extend/util"
@@ -28,114 +29,108 @@ type AudioCtl struct{}
 // @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, "上传失败"))
-		}
-
-		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, "上传失败"))
-		}
-
-		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,
+			util.ResponseFormat(c, code.RequestParamError, "上传失败")
+			return
 		}
-
-		if err = models.NewAudioSearch().Create(audio); err != nil {
-			//util.ResponseFormat(c, code.SaveFail, "上传失败")
-			return errors.New(fmt.Sprintf(logFormat, filename, "上传失败"))
+		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
+			}
+			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
 		}
-		go func() {
-
-			var trainInfoNames = []string{arr[0], arr[1], arr[3]}
-
-			var (
-				info   *models.TrainInfo
-				err    error
-				parent models.TrainInfo
-			)
-			for i := 0; i < 3; i++ {
-				name := trainInfoNames[i]
-				class := constvar.Class(i + 1)
-				info, err = models.NewTrainInfoSearch().SetName(name).SetClass(class).First()
-				if err == gorm.ErrRecordNotFound {
-					info = &models.TrainInfo{
-						Name:     name,
-						Class:    class,
-						ParentID: parent.ID,
-					}
-					_ = models.NewTrainInfoSearch().Create(info)
+		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
 				}
-				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, "添加成功")
+	if err := models.NewAudioSearch().Create(audio); err != nil {
+		util.ResponseFormat(c, code.SaveFail, "上传失败")
 		return
 	}
+	go func() {
+		var trainInfoNames = []string{audio.LocomotiveNumber, audio.TrainNumber, audio.Station}
+		var (
+			info   *models.TrainInfo
+			err    error
+			parent models.TrainInfo
+		)
+		for i := 0; i < 3; i++ {
+			name := trainInfoNames[i]
+			class := constvar.Class(i + 1)
+			info, err = models.NewTrainInfoSearch().SetName(name).SetClass(class).First()
+			if err == gorm.ErrRecordNotFound {
+				info = &models.TrainInfo{
+					Name:     name,
+					Class:    class,
+					ParentID: parent.ID,
+				}
+				_ = models.NewTrainInfoSearch().Create(info)
+			}
+			parent = *info
+		}
+	}()
 }
 
 func (slf AudioCtl) ParamsCheck(filename string) (err error) {
@@ -289,13 +284,22 @@ func (slf AudioCtl) AudioDownload(c *gin.Context) {
 		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 @@ func (slf AudioCtl) AudioDownload(c *gin.Context) {
 
 	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, "文件传输失败")

+ 1 - 7
docs/docs.go

@@ -465,19 +465,13 @@ const docTemplate = `{
                 ],
                 "summary": "上传音频",
                 "parameters": [
-                    {
-                        "type": "file",
-                        "description": "音频文件",
-                        "name": "file",
-                        "in": "formData"
-                    },
                     {
                         "type": "array",
                         "items": {
                             "type": "file"
                         },
                         "collectionFormat": "csv",
-                        "description": "多个音频文件",
+                        "description": "多文件上传",
                         "name": "files",
                         "in": "formData"
                     }

+ 1 - 7
docs/swagger.json

@@ -454,19 +454,13 @@
                 ],
                 "summary": "上传音频",
                 "parameters": [
-                    {
-                        "type": "file",
-                        "description": "音频文件",
-                        "name": "file",
-                        "in": "formData"
-                    },
                     {
                         "type": "array",
                         "items": {
                             "type": "file"
                         },
                         "collectionFormat": "csv",
-                        "description": "多个音频文件",
+                        "description": "多文件上传",
                         "name": "files",
                         "in": "formData"
                     }

+ 1 - 5
docs/swagger.yaml

@@ -484,12 +484,8 @@ paths:
   /api-sa/v1/audio/upload:
     post:
       parameters:
-      - description: 音频文件
-        in: formData
-        name: file
-        type: file
       - collectionFormat: csv
-        description: 多个音频文件
+        description: 多文件上传
         in: formData
         items:
           type: file

+ 4 - 1
models/audio.go

@@ -15,12 +15,15 @@ type (
 		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未关注

+ 2 - 1
request/audio.go

@@ -19,7 +19,8 @@ type GetAudioList struct {
 }
 
 type ProcessAudio struct {
-	ID uint `json:"id" form:"id" binding:"required"`
+	ID       uint `json:"id" form:"id" binding:"required"`
+	Filetype int  `json:"fileType" form:"fileType"`
 }
 
 type BatchProcessAudio struct {