From 777978a2a2ac2232050ba44521f107b85646081b Mon Sep 17 00:00:00 2001
From: yinbangzhong <zhongbangyin@126.com>
Date: 星期五, 14 六月 2024 15:40:45 +0800
Subject: [PATCH] watch preloads file to autoload

---
 service/process.go |  115 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 115 insertions(+), 0 deletions(-)

diff --git a/service/process.go b/service/process.go
index 29eb5f3..1c08e55 100644
--- a/service/process.go
+++ b/service/process.go
@@ -2,18 +2,24 @@
 
 import (
 	"bytes"
+	"context"
 	"encoding/json"
 	"errors"
+	"fmt"
+	"github.com/fsnotify/fsnotify"
 	"gorm.io/gorm"
 	"io"
+	"log"
 	"mime/multipart"
 	"net/http"
 	"os"
+	"path/filepath"
 	"speechAnalysis/conf"
 	"speechAnalysis/constvar"
 	"speechAnalysis/models"
 	"speechAnalysis/pkg/logx"
 	"strings"
+	"time"
 )
 
 // Response 缁撴瀯浣撶敤浜庡瓨鍌ㄥ搷搴斾綋鐨勫唴瀹�
@@ -153,3 +159,112 @@
 	}
 	return words
 }
+
+func PreLoad(cxt context.Context) {
+	mkdirErr := os.MkdirAll(conf.LocalConf.PreLoadPath, os.ModePerm)
+	if mkdirErr != nil {
+		logx.Errorf("function os.MkdirAll() err:%v", mkdirErr)
+	}
+	//鏂囦欢澶逛笅鏂板闊抽鏂囦欢鏃惰Е鍙�
+	watcher, err := fsnotify.NewWatcher()
+	if err != nil {
+		log.Fatal(err)
+	}
+	defer watcher.Close()
+	err = watcher.Add(conf.LocalConf.PreLoadPath)
+	if err != nil {
+		log.Fatal(err)
+	}
+	for {
+		select {
+		case <-cxt.Done():
+			fmt.Println("preload stop")
+		case event, ok := <-watcher.Events:
+			if !ok {
+				continue
+			}
+			if event.Op&fsnotify.Create == fsnotify.Create {
+				// 鍒ゆ柇鏂囦欢绫诲瀷鏄惁涓�.mp3鎴�.wav
+				if filepath.Ext(event.Name) == ".mp3" || filepath.Ext(event.Name) == ".wav" {
+					// 鏂囦欢鍚�
+					fileName := filepath.Base(event.Name)
+					// 鏂囦欢澶у皬
+					bs, _ := os.ReadFile(event.Name)
+					size := len(bs)
+					//鏍¢獙鏂囦欢鍛藉悕
+					arr := strings.Split(fileName, "_")
+					if len(arr) != 6 {
+						logx.Errorf(fmt.Sprintf("%s:%s", fileName, "鏂囦欢鍚嶇О閿欒"))
+						continue
+					}
+					timeStr := arr[4] + strings.Split(arr[5], ".")[0]
+					t, err := time.ParseInLocation("20060102150405", timeStr, time.Local)
+					if err != nil {
+						logx.Errorf(fmt.Sprintf("%s:%s", fileName, "鏃堕棿鏍煎紡涓嶅"))
+					}
+
+					//鏌ラ噸
+					_, err = models.NewAudioSearch().SetName(fileName).First()
+					if err != gorm.ErrRecordNotFound {
+						logx.Errorf(fmt.Sprintf("%s:%s", fileName, "閲嶅涓婁紶"))
+						continue
+					}
+
+					//灏嗘枃浠剁Щ鍔ㄥ埌uploads鏂囦欢澶逛笅
+					src := conf.LocalConf.StorePath + "/" + fileName
+					err = os.Rename(event.Name, src)
+					if err != nil {
+						logx.Errorf(fmt.Sprintf("%s:%s", fileName, "绉诲姩鏂囦欢澶辫触"))
+						continue
+					}
+
+					audio := &models.Audio{
+						Name:             fileName,
+						Size:             int64(size),
+						FilePath:         src,
+						AudioStatus:      constvar.AudioStatusUploadOk,
+						LocomotiveNumber: arr[0],
+						TrainNumber:      arr[1],
+						DriverNumber:     arr[2],
+						Station:          arr[3],
+						OccurrenceAt:     t,
+						IsFollowed:       0,
+					}
+
+					if err = models.NewAudioSearch().Create(audio); err != nil {
+						logx.Errorf(fmt.Sprintf("%s:%s", fileName, "鏁版嵁搴揷reate澶辫触"))
+						continue
+					}
+
+					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)
+							}
+							parent = *info
+						}
+
+					}()
+				}
+			}
+		case err, ok := <-watcher.Errors:
+			if !ok {
+				logx.Errorf(err.Error())
+			}
+		}
+	}
+}

--
Gitblit v1.8.0