upd:编码规范

This commit is contained in:
2025-02-26 21:14:42 +08:00
parent b1d07345b1
commit 2873327ba5
23 changed files with 1052 additions and 933 deletions
+32
View File
@@ -0,0 +1,32 @@
package util
import (
"fmt"
"strconv"
"time"
)
// String2int 字符串转int
func String2int(str string) int {
intValue, err := strconv.Atoi(str)
if err != nil {
return 0
}
return intValue
}
// SecondsToHms 将秒数转换为小时、分钟、秒的格式
func SecondsToHms(seconds int) string {
t := time.Duration(seconds) * time.Second
h := t / time.Hour
t -= h * time.Hour
m := t / time.Minute
t -= m * time.Minute
s := t / time.Second
return fmt.Sprintf("%02d-%02d-%02d", h, m, s)
}
// CalcPercentage 计算percentage相对于total的百分比
func CalcPercentage(percentage int, total int) int {
return int(float64(percentage) / float64(total) * 100)
}
+111
View File
@@ -0,0 +1,111 @@
package util
import (
"github.com/gabriel-vasile/mimetype"
"io/ioutil"
"log"
"os"
"path/filepath"
)
// CreateDir 创建目录
func CreateDir(dirPath string) bool {
err := os.Mkdir(dirPath, 0755)
return err == nil
}
// GetFileDirectory 获取文件所在文件夹
func GetFileDirectory(filePath string) string {
directoryPath, _ := filepath.Split(filePath)
return directoryPath
}
// ReadFileMimeInfo 获取文件mime信息
func ReadFileMimeInfo(filepath string) *mimetype.MIME {
mt, err := mimetype.DetectFile(filepath)
if err != nil {
log.Fatal(err)
}
return mt
}
// CheckFileIsExist 判断文件是否存在,存在返回 true,不存在返回false
func CheckFileIsExist(filename string) bool {
var exist = true
if _, err := os.Stat(filename); os.IsNotExist(err) {
exist = false
}
return exist
}
// WriteByteArraysToFile 写字节数组到文件
func WriteByteArraysToFile(content []byte, filename string) error {
return ioutil.WriteFile(filename, content, 0777)
}
//// 移动文件到根目录
//func renameFile(rootDir string, modelType string, videoList []string, pathSeparator string) {
// total := len(videoList)
// var count = 0
// bar := goPrint.NewBar(100)
// bar.SetNotice("=== 重命名文件:")
// bar.SetGraph(">")
// for _, videoFilePath := range videoList {
// wh := videoPath2WidthHeightTagMap[videoFilePath]
// fileName := vars.GlobalFilePath2FileNameMap[videoFilePath]
// if strings.Contains(fileName, videoTag) { // 处理过了
// fileNames := strings.Split(fileName, videoTag)
// if len(fileNames) == 2 {
// fileName = fileNames[1]
// targetFilePath := rootDir + pathSeparator + "[" + videoPath2DurationMap[videoFilePath] + "]" + modelType + wh + videoTag + fileName
// err := os.Rename(videoFilePath, targetFilePath)
// if err != nil {
// fmt.Printf("=== 重命名异常: %s \n", videoFilePath)
// }
// }
// } else {
// targetFilePath := rootDir + pathSeparator + "[" + videoPath2DurationMap[videoFilePath] + "]" + modelType + wh + videoTag + " - " + fileName
// err := os.Rename(videoFilePath, targetFilePath)
// if err != nil {
// fmt.Printf("=== 重命名异常: %s \n", videoFilePath)
// }
// }
// count = count + 1
// bar.PrintBar(util.CalcPercentage(count, total))
// }
// bar.PrintEnd("=== Finish")
//}
//
//// 移动文件到原目录
//func renameFileV2(modelType string, videoList []string) {
// total := len(videoList)
// var count = 0
// bar := goPrint.NewBar(100)
// bar.SetNotice("=== 重命名文件:")
// bar.SetGraph(">")
// for _, videoFilePath := range videoList {
// wh := videoPath2WidthHeightTagMap[videoFilePath]
// fileName := vars.GlobalFilePath2FileNameMap[videoFilePath]
// filePath := util.GetFileDirectory(videoFilePath)
// if strings.Contains(fileName, videoTag) { // 处理过了
// fileNames := strings.Split(fileName, videoTag)
// if len(fileNames) == 2 {
// fileName = fileNames[1]
// targetFilePath := filePath + "[" + videoPath2DurationMap[videoFilePath] + "]" + modelType + wh + videoTag + fileName
// err := os.Rename(videoFilePath, targetFilePath)
// if err != nil {
// fmt.Printf("=== 重命名异常: %s \n", videoFilePath)
// }
// }
// } else {
// targetFilePath := filePath + "[" + videoPath2DurationMap[videoFilePath] + "]" + modelType + wh + videoTag + " - " + fileName
// err := os.Rename(videoFilePath, targetFilePath)
// if err != nil {
// fmt.Printf("=== 重命名异常: %s \n", videoFilePath)
// }
// }
// count = count + 1
// bar.PrintBar(util.CalcPercentage(count, total))
// }
// bar.PrintEnd("=== Finish")
//}
+43
View File
@@ -0,0 +1,43 @@
package util
import (
"image"
"os"
"strings"
)
var supportImageTypes = []string{
".bmp",
".gif",
".jpg",
".jpeg",
".jpe",
".png",
".webp",
".psb",
".jfif",
}
// IsSupportImage 判断是否属于支持的图片文件
func IsSupportImage(imageType string) bool {
for _, supportImageType := range supportImageTypes {
if strings.EqualFold(supportImageType, strings.ToLower(imageType)) {
return true
}
}
return false
}
// ReadImageInfo 读取一般图片文件信息
func ReadImageInfo(filePath string) (err error, width int, height int) {
file, err := os.Open(filePath) // 图片文件路径
if err != nil {
return err, 0, 0
}
defer file.Close()
img, _, err := image.DecodeConfig(file)
if err != nil {
return err, 0, 0
}
return nil, img.Width, img.Height
}
-72
View File
@@ -1,72 +0,0 @@
package util
import (
"fmt"
"github.com/gabriel-vasile/mimetype"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"time"
)
// CheckFileIsExist 判断文件是否存在,存在返回 true,不存在返回false
func CheckFileIsExist(filename string) bool {
var exist = true
if _, err := os.Stat(filename); os.IsNotExist(err) {
exist = false
}
return exist
}
// WriteByteArraysToFile 写字节数组到文件
func WriteByteArraysToFile(content []byte, filename string) error {
return ioutil.WriteFile(filename, content, 0777)
}
// String2int 字符串转int
func String2int(str string) int {
intValue, err := strconv.Atoi(str)
if err != nil {
return 0
}
return intValue
}
// CreateDir 创建目录
func CreateDir(dirPath string) bool {
err := os.Mkdir(dirPath, 0755)
return err == nil
}
// ReadFileMimeInfo 获取文件mime信息
func ReadFileMimeInfo(filepath string) *mimetype.MIME {
mt, err := mimetype.DetectFile(filepath)
if err != nil {
log.Fatal(err)
}
return mt
}
// SecondsToHms 将秒数转换为小时、分钟、秒的格式
func SecondsToHms(seconds int) string {
t := time.Duration(seconds) * time.Second
h := t / time.Hour
t -= h * time.Hour
m := t / time.Minute
t -= m * time.Minute
s := t / time.Second
return fmt.Sprintf("%02d-%02d-%02d", h, m, s)
}
// CalcPercentage 计算percentage相对于total的百分比
func CalcPercentage(percentage int, total int) int {
return int(float64(percentage) / float64(total) * 100)
}
// 获取文件所在文件夹
func GetFileDirectory(filePath string) string {
directoryPath, _ := filepath.Split(filePath)
return directoryPath
}
+158
View File
@@ -0,0 +1,158 @@
package util
import (
"bytes"
"fmt"
"github.com/redmask-hb/GoSimplePrint/goPrint"
"math"
"os"
"os/exec"
"strconv"
"strings"
)
var supportVideoTypes = []string{
".ts",
".flv",
".rm",
".avi",
".mp4",
".mov",
".mpg",
".mkv",
".m4v",
".rmvb",
".3gp",
".3g2",
".webm",
".wmv",
}
func getVideoDuration(ffmpegExecPath string, videoPath string) (float64, error) {
// ffprobe命令,-v error 用于减少输出信息,-show_entries format=duration -of compact=p=0,nk=1 用于只输出时长
cmd := exec.Command(ffmpegExecPath, "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", videoPath)
var stderr bytes.Buffer
cmd.Stderr = &stderr
output, err := cmd.Output()
if err != nil {
return 0, fmt.Errorf("ffprobe failed with error: %v, stderr: %q", err, stderr.String())
}
// 解析输出的时长字符串为浮点数
durationStr := strings.TrimSpace(string(output))
duration, err := strconv.ParseFloat(durationStr, 64)
if err != nil {
return 0, fmt.Errorf("failed to parse duration: %q, error: %v", durationStr, err)
}
return duration, nil
}
func getVideoResolution(ffmpegExecPath string, filePath string) (width int, height int, err error) {
// 构建ffprobe命令
cmd := exec.Command(ffmpegExecPath, "-v", "error", "-show_entries", "stream=width,height", "-of", "csv=p=0:s=x", filePath)
// 执行命令并捕获输出
output, err := cmd.Output()
if err != nil {
return 0, 0, fmt.Errorf("failed to run ffprobe: %w", err)
}
// 解析输出字符串,格式应为 "宽度,高度"
resolutionStr := strings.TrimSpace(string(output))
parts := strings.Split(resolutionStr, ",")
if len(parts) == 2 {
width = String2int(parts[0])
height = String2int(parts[1])
return width, height, nil
}
parts = strings.Split(resolutionStr, "x")
if len(parts) == 2 {
width = String2int(parts[0])
height = String2int(parts[1])
return width, height, nil
}
parts = strings.Split(resolutionStr, "\r\n\r\n\r\n\r\n")
if len(parts) == 2 {
tempHw := parts[0]
parts = strings.Split(tempHw, "x")
if len(parts) == 2 {
width = String2int(parts[0])
height = String2int(parts[1])
return width, height, nil
}
}
parts = strings.Split(resolutionStr, "x")
if len(parts) == 3 {
width = String2int(parts[0])
height = String2int(parts[1])
return width, height, nil
}
resolutionStr = strings.ReplaceAll(resolutionStr, "\r", "")
resolutionStr = strings.ReplaceAll(resolutionStr, "\n", "")
resolutionStr = strings.ReplaceAll(resolutionStr, "N/AxN/A", "")
parts = strings.Split(resolutionStr, "x")
if len(parts) == 2 {
width = String2int(parts[0])
height = String2int(parts[1])
return width, height, nil
}
return 0, 0, fmt.Errorf("invalid resolution format: %s", resolutionStr)
}
// ReadVideoDuration 获取视频的时长,单位秒
func ReadVideoDuration(videoFilePath string) int {
duration, err := getVideoDuration("./ffprobe.exe", videoFilePath)
if err != nil {
fmt.Println("=== Error getting video duration:", err)
return 0
}
//fmt.Printf("=== Video duration: %.2f seconds\n", duration)
return int(math.Floor(duration)) // 向下取整
}
// ReadVideoWidthHeight 获取视频的分辨率
func ReadVideoWidthHeight(videoFilePath string) (int, int, error) {
width, height, err := getVideoResolution("./ffprobe.exe", videoFilePath)
if err != nil {
fmt.Printf("=== Error getting resolution: %v\n", err)
return 0, 0, err
}
//fmt.Printf("=== Video resolution: %dx%d\n", width, height)
return width, height, nil
}
// IsSupportVideo 判断是否属于支持的视频
func IsSupportVideo(videoType string) bool {
for _, supportVideoType := range supportVideoTypes {
if strings.EqualFold(videoType, supportVideoType) {
return true
}
}
return false
}
// DoMoveFileToDir 批量移动文件到目录
func DoMoveFileToDir(filePathList []string, videoDirPath string) {
total := len(filePathList)
var count = 0
bar := goPrint.NewBar(100)
bar.SetNotice("=== 移动文件到目录:")
bar.SetGraph(">")
pathSeparator := string(os.PathSeparator)
for _, videoFilePath := range filePathList {
moveFileToDir(videoFilePath, videoDirPath+pathSeparator)
count = count + 1
bar.PrintBar(CalcPercentage(count, total))
}
bar.PrintEnd("=== Finish")
}
// 移动文件到目录
func moveFileToDir(sourceFilePath string, targetDirectory string) bool {
splits := strings.Split(sourceFilePath, string(os.PathSeparator))
fileName := splits[len(splits)-1]
targetFilePath := targetDirectory + fileName
err := os.Rename(sourceFilePath, targetFilePath)
//fmt.Printf("=== 移动文件, 源: %s, 目标: %s \n", sourceFilePath, targetFilePath)
return err == nil
}