From dc8b1fd99f7c648a8118a13dd72b614666767780 Mon Sep 17 00:00:00 2001 From: yuan_rh <545873205@qq.com> Date: Wed, 18 Nov 2020 11:32:28 +0800 Subject: [PATCH] fix --- handle/handle.go | 49 ++++++++++++++++++------- main.go | 94 ++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 115 insertions(+), 28 deletions(-) diff --git a/handle/handle.go b/handle/handle.go index dffba1c..dffb6d9 100644 --- a/handle/handle.go +++ b/handle/handle.go @@ -33,11 +33,12 @@ var ipfsPath=os.Getenv("IPFS-PATH") /** 文件上传下载进度 - */ +*/ type processStruct struct { Size string `json:"size"` CurrentSize string `json:"currentSize"` Unit string `json:"unit"` + CurrentUnit string `json:"currentUnit"` Process float64 `json:"process"` Hash string `json:"hash"` } @@ -61,7 +62,7 @@ func main() { 初始化本地工作目录 @param userId 用户ID @param projectName 项目名称 - */ +*/ func InitLocalWorkSpace(conn *websocket.Conn,userId,projectName string) (error){ //空格路径处理 @@ -98,7 +99,7 @@ func InitLocalWorkSpace(conn *websocket.Conn,userId,projectName string) (error){ @param projectName 项目名称 @para fileName 文件名称 @param dir 云文件目录 - */ +*/ func DownCommand(conn *websocket.Conn, hash, projectName, fileName, dir string) error{ absoluteDir := config.LocalWorkSpaceDir+"\\"+gobalLoginUserId+"\\"+projectName+"\\"+dir @@ -113,8 +114,22 @@ func DownCommand(conn *websocket.Conn, hash, projectName, fileName, dir string) } } + var downloading bool = false + //检测文件打开状态 + tfile,err := os.OpenFile(fmt.Sprint(absoluteDir+"\\"+fileName),os.O_RDWR,1) + + if err != nil && (!os.IsNotExist(err)) { + + log.Println("文件被占用,请关闭打开的软件") + if err := conn.WriteMessage(websocket.TextMessage, []byte("-2")); err != nil { + return err + } + return err + } + defer tfile.Close() + cmd := exec.Command(ipfsPath,"get", hash,"-o",fmt.Sprint(absoluteDir+"\\"+fileName)) progress := make(chan string,10000) var stdout, stderr []byte @@ -133,6 +148,7 @@ func DownCommand(conn *websocket.Conn, hash, projectName, fileName, dir string) millSeconds := time.Now().UnixNano() / 1e6 for content := range progress { // 通道关闭后会退出for range循环 current :=time.Now().UnixNano() / 1e6 + if current-millSeconds>500{ projson,err := contentToJSONByte(content) if projson==nil && err==nil{ @@ -142,12 +158,14 @@ func DownCommand(conn *websocket.Conn, hash, projectName, fileName, dir string) if err != nil { log.Printf("json.Marshal error %s\n", err) } + millSeconds = current downloading = true + if err := conn.WriteMessage(websocket.TextMessage, projson); err != nil { log.Println(err) break } - millSeconds = current + } if strings.Index(content,"100.00%")!=-1{ @@ -200,18 +218,21 @@ func DownCommand(conn *websocket.Conn, hash, projectName, fileName, dir string) outStr, errStr := string(stdout), string(stderr) log.Printf("out:%s ,err:%s", outStr, errStr) - defer close(progress) - if err==nil{ log.Println("下载成功") } - return nil + time.Sleep(time.Duration(6)*time.Second) + + defer close(progress) + + return nil } func contentToJSONByte(content string) ([]byte,error){ sts :=strings.Split(content," ") if len(sts)<8{ + log.Println("字符长度小于8") return nil,nil } var processFloat float64 @@ -222,15 +243,15 @@ func contentToJSONByte(content string) ([]byte,error){ } if processFloat==0{ + //log.Println("当前进度0") return nil,nil - } - pro :=&processStruct{ Size:sts[4], CurrentSize: sts[1], Unit: sts[2], + CurrentUnit: sts[5], Process: processFloat, Hash: "", @@ -247,7 +268,7 @@ func contentToJSONByte(content string) ([]byte,error){ @param fileName 文件名称 @param projectName 项目名称 @param dir 云文件目录 - */ +*/ func UploadCommand(conn *websocket.Conn,absolutePath,fileName,projectName,dir string) error{ //本地拷贝文件 @@ -263,7 +284,7 @@ func UploadCommand(conn *websocket.Conn,absolutePath,fileName,projectName,dir st } //检测文件打开状态 - _,err = os.OpenFile(absolutePath,os.O_RDWR,1) + tfile,err := os.OpenFile(absolutePath,os.O_RDWR,1) if err != nil { log.Println("文件被占用,请关闭打开的软件") if err := conn.WriteMessage(websocket.TextMessage, []byte("-2")); err != nil { @@ -271,6 +292,7 @@ func UploadCommand(conn *websocket.Conn,absolutePath,fileName,projectName,dir st } return err } + defer tfile.Close() var uploading bool=false @@ -289,7 +311,7 @@ func UploadCommand(conn *websocket.Conn,absolutePath,fileName,projectName,dir st }() go func(){ - millSeconds := time.Now().UnixNano() / 1e6 + millSeconds := time.Now().UnixNano() / 1e6 for content := range uploadProgress { // 通道关闭后会退出for range循环 current :=time.Now().UnixNano() / 1e6 if current-millSeconds>500{ @@ -442,7 +464,7 @@ func NotifyFileChange(id string, changeType int){ /** 获取本地文件列表 - */ +*/ func SubscriptionFileChange(conn *websocket.Conn, projectName string) error{ getLocalFileListDir = fmt.Sprint(config.LocalWorkSpaceDir+"\\"+gobalLoginUserId+"\\"+projectName+"\\") @@ -451,6 +473,7 @@ func SubscriptionFileChange(conn *websocket.Conn, projectName string) error{ err :=filepath.Walk(getLocalFileListDir,walkfunc) if err != nil { log.Println(err) + time.Sleep(time.Duration(1)*time.Minute) continue } diff --git a/main.go b/main.go index 9a08442..a9e52ba 100644 --- a/main.go +++ b/main.go @@ -5,13 +5,14 @@ import ( _ "fmt" "fts/config" "fts/websocket" + "github.com/fsnotify/fsnotify" _ "github.com/ipfs/go-ipfs-api" "io" - "io/ioutil" "log" "net/http" "os" _ "os" + "path/filepath" _ "strings" ) @@ -46,19 +47,82 @@ func main() { } -// 递归扫描目录 -func ScanDirs(dirName string) []string { - files, err := ioutil.ReadDir(dirName) - if err != nil { - log.Println(err) - } - var fileList []string - for _, file := range files { - fmt.Println(file.Name()+" "+file.ModTime().String()) - fileList = append(fileList, dirName + string(os.PathSeparator) + file.Name()) - if file.IsDir() { - fileList = append(fileList, ScanDirs(dirName + string(os.PathSeparator) + file.Name())...) +//func main() { +// watch, _ := fsnotify.NewWatcher() +// w := Watch{ +// watch: watch, +// } +// w.watchDir("C:\\Users\\yuan_rh\\easycloud\\324523676458291200"); +// select {}; +//} + +type Watch struct { + watch *fsnotify.Watcher; +} + +//监控目录 +func (w *Watch) watchDir(dir string) { + //通过Walk来遍历目录下的所有子目录 + filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + //这里判断是否为目录,只需监控目录即可 + //目录下的文件也在监控范围内,不需要我们一个一个加 + if info.IsDir() { + path, err := filepath.Abs(path); + if err != nil { + return err; + } + err = w.watch.Add(path); + if err != nil { + return err; + } + fmt.Println("监控 : ", path); } - } - return fileList + return nil; + }); + go func() { + for { + select { + case ev := <-w.watch.Events: + { + if ev.Op&fsnotify.Create == fsnotify.Create { + fmt.Println("创建文件 : ", ev.Name); + //这里获取新创建文件的信息,如果是目录,则加入监控中 + fi, err := os.Stat(ev.Name); + if err == nil && fi.IsDir() { + w.watch.Add(ev.Name); + fmt.Println("添加监控 : ", ev.Name); + } + } + if ev.Op&fsnotify.Write == fsnotify.Write { + fmt.Println("写入文件 : ", ev.Name); + } + if ev.Op&fsnotify.Remove == fsnotify.Remove { + fmt.Println("删除文件 : ", ev.Name); + //如果删除文件是目录,则移除监控 + fi, err := os.Stat(ev.Name); + if err == nil && fi.IsDir() { + w.watch.Remove(ev.Name); + fmt.Println("删除监控 : ", ev.Name); + } + } + if ev.Op&fsnotify.Rename == fsnotify.Rename { + fmt.Println("重命名文件 : ", ev.Name); + //如果重命名文件是目录,则移除监控 + //注意这里无法使用os.Stat来判断是否是目录了 + //因为重命名后,go已经无法找到原文件来获取信息了 + //所以这里就简单粗爆的直接remove好了 + w.watch.Remove(ev.Name); + } + if ev.Op&fsnotify.Chmod == fsnotify.Chmod { + fmt.Println("修改权限 : ", ev.Name); + } + } + case err := <-w.watch.Errors: + { + fmt.Println("error : ", err); + return; + } + } + } + }(); } \ No newline at end of file