FileManager.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. package controllers
  2. import (
  3. "Cold_Api/conf"
  4. "Cold_Api/controllers/lib"
  5. "Cold_Api/models/Account"
  6. "Cold_Api/models/FileManager"
  7. "encoding/json"
  8. "fmt"
  9. "math"
  10. "path/filepath"
  11. "strings"
  12. "github.com/beego/beego/v2/adapter/orm"
  13. beego "github.com/beego/beego/v2/server/web"
  14. )
  15. type FileManagerController struct {
  16. beego.Controller
  17. Admin_r Account.Admin // 登陆的用户
  18. T_pid int // 公司id
  19. }
  20. func (c *FileManagerController) Prepare() {
  21. GetCookie := c.Ctx.GetCookie("User_tokey")
  22. GetString := c.GetString("User_tokey")
  23. User_tokey := GetString
  24. if len(User_tokey) == 0 {
  25. User_tokey = GetCookie
  26. }
  27. if Account.Admin_r == nil {
  28. return
  29. }
  30. c.Admin_r = *Account.Admin_r
  31. T_pid := c.T_pid
  32. EntryPid, _ := Account.Redis_Tokey_T_pid_Get(User_tokey)
  33. if EntryPid > 0 {
  34. T_pid = EntryPid
  35. }
  36. c.T_pid = T_pid
  37. }
  38. // AddFileManager 添加文件记录(使用form-data格式)
  39. func (c *FileManagerController) AddFileManager() {
  40. // 获取form-data参数
  41. filesParam := c.GetString("files")
  42. overwriteParam := c.GetString("overwrite")
  43. pathParam := c.GetString("path")
  44. // 定义文件信息结构体
  45. type FileInfo struct {
  46. Name string `json:"name"` // 文件名
  47. Url string `json:"url"` // 文件URL
  48. Size int64 `json:"size"` // 文件大小
  49. }
  50. // 参数验证
  51. if len(filesParam) == 0 {
  52. c.Data["json"] = lib.JSONS{Code: 202, Msg: "文件参数不能为空"}
  53. c.ServeJSON()
  54. return
  55. }
  56. // 解析文件列表JSON
  57. var files []FileInfo
  58. err := json.Unmarshal([]byte(filesParam), &files)
  59. if err != nil {
  60. c.Data["json"] = lib.JSONS{Code: 202, Msg: "文件参数格式错误"}
  61. c.ServeJSON()
  62. return
  63. }
  64. // 验证文件列表
  65. if len(files) == 0 {
  66. c.Data["json"] = lib.JSONS{Code: 202, Msg: "文件列表不能为空"}
  67. c.ServeJSON()
  68. return
  69. }
  70. // 解析覆盖参数
  71. overwrite := false
  72. if overwriteParam == "true" || overwriteParam == "1" {
  73. overwrite = true
  74. }
  75. // 验证每个文件的参数
  76. var totalSize int64
  77. for i, file := range files {
  78. if len(file.Name) == 0 {
  79. c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("第%d个文件名不能为空", i+1)}
  80. c.ServeJSON()
  81. return
  82. }
  83. if len(file.Url) == 0 {
  84. c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("第%d个文件链接不能为空", i+1)}
  85. c.ServeJSON()
  86. return
  87. }
  88. if file.Size <= 0 {
  89. c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("第%d个文件大小必须大于0", i+1)}
  90. c.ServeJSON()
  91. return
  92. }
  93. totalSize += file.Size
  94. }
  95. // 检查公司存储空间是否足够
  96. if c.T_pid > 0 {
  97. available, usedStorage, storageLimit, err := FileManager.Check_Company_Storage_Available(c.T_pid, totalSize)
  98. if err != nil {
  99. c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("检查存储空间失败: %v", err)}
  100. c.ServeJSON()
  101. return
  102. }
  103. if !available {
  104. c.Data["json"] = lib.JSONS{
  105. Code: 202,
  106. Msg: fmt.Sprintf("存储空间不足,已使用: %s,限制: %s,当前批量文件: %s",
  107. FileManager.FormatFileSize(usedStorage),
  108. FileManager.FormatFileSize(storageLimit),
  109. FileManager.FormatFileSize(totalSize)),
  110. }
  111. c.ServeJSON()
  112. return
  113. }
  114. }
  115. // 处理上传路径
  116. T_path := pathParam
  117. if len(T_path) == 0 {
  118. T_path = "/"
  119. }
  120. if !strings.HasSuffix(T_path, "/") {
  121. T_path += "/"
  122. }
  123. // 自动创建路径中不存在的文件夹
  124. if T_path != "/" {
  125. err := FileManager.Auto_Create_Folders(c.T_pid, T_path, c.Admin_r.T_uuid)
  126. if err != nil {
  127. c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("创建路径失败: %v", err)}
  128. c.ServeJSON()
  129. return
  130. }
  131. }
  132. // 批量处理文件
  133. var successFiles []FileManager.FileManager_R
  134. var failedFiles []map[string]interface{}
  135. var successCount int
  136. for _, fileInfo := range files {
  137. // 构建完整路径
  138. fullPath := T_path + fileInfo.Name
  139. // 检查是否存在同名文件
  140. if !overwrite && FileManager.Check_FileManager_Name_Exists(c.T_pid, T_path, fileInfo.Name, 0) {
  141. failedFiles = append(failedFiles, map[string]interface{}{
  142. "name": fileInfo.Name,
  143. "reason": "文件已存在",
  144. })
  145. continue
  146. }
  147. // 如果覆盖模式,先删除旧文件
  148. if overwrite {
  149. o := orm.NewOrm()
  150. var existingFile FileManager.FileManager
  151. err := o.QueryTable(new(FileManager.FileManager)).Filter("T_pid", c.T_pid).Filter("T_path", fullPath).Filter("T_state", 1).One(&existingFile)
  152. if err == nil {
  153. FileManager.Delete_FileManager_ByUuid(existingFile.T_uuid)
  154. }
  155. }
  156. // 保存文件信息到数据库
  157. fileManager := FileManager.FileManager{
  158. T_pid: c.T_pid,
  159. T_name: fileInfo.Name,
  160. T_path: fullPath,
  161. T_url: fileInfo.Url,
  162. T_size: fileInfo.Size,
  163. T_type: FileManager.GenerateFileType(fileInfo.Name, fullPath), // 生成文件类型
  164. T_uploaded_by: c.Admin_r.T_uuid,
  165. T_state: 1,
  166. }
  167. id, err := FileManager.Add_FileManager(fileManager)
  168. if err != nil {
  169. failedFiles = append(failedFiles, map[string]interface{}{
  170. "name": fileInfo.Name,
  171. "reason": fmt.Sprintf("保存失败: %v", err),
  172. })
  173. continue
  174. }
  175. fileManager.Id = int(id)
  176. uploadedFile := FileManager.FileManagerToFileManager_R(fileManager)
  177. successFiles = append(successFiles, uploadedFile)
  178. successCount++
  179. }
  180. // 构建返回结果
  181. response := map[string]interface{}{
  182. "success_count": successCount,
  183. "failed_count": len(failedFiles),
  184. "total_count": len(files),
  185. "success_files": successFiles,
  186. "failed_files": failedFiles,
  187. }
  188. // 根据结果返回不同的消息
  189. if len(failedFiles) == 0 {
  190. c.Data["json"] = lib.JSONS{Code: 200, Msg: fmt.Sprintf("所有文件添加成功,共%d个文件", successCount), Data: response}
  191. } else if successCount == 0 {
  192. c.Data["json"] = lib.JSONS{Code: 202, Msg: "所有文件添加失败", Data: response}
  193. } else {
  194. c.Data["json"] = lib.JSONS{Code: 200, Msg: fmt.Sprintf("部分文件添加成功,成功%d个,失败%d个", successCount, len(failedFiles)), Data: response}
  195. }
  196. c.ServeJSON()
  197. return
  198. }
  199. // DeleteFileManager 删除文件(支持递归删除文件夹及其子文件)
  200. func (c *FileManagerController) DeleteFileManager() {
  201. T_path := c.GetString("path")
  202. if len(T_path) == 0 {
  203. c.Data["json"] = lib.JSONS{Code: 202, Msg: "文件路径不能为空"}
  204. c.ServeJSON()
  205. return
  206. }
  207. // 使用递归删除方法(基于路径)
  208. deletedCount, err := FileManager.Delete_FileManager_Recursive_ByPath(c.T_pid, T_path)
  209. if err != nil {
  210. c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("删除失败: %v", err)}
  211. c.ServeJSON()
  212. return
  213. }
  214. // 根据删除数量返回不同的成功消息
  215. var msg string
  216. if deletedCount > 1 {
  217. msg = fmt.Sprintf("删除成功,共删除 %d 个文件/文件夹", deletedCount)
  218. } else {
  219. msg = "删除成功"
  220. }
  221. c.Data["json"] = lib.JSONS{Code: 200, Msg: msg, Data: map[string]interface{}{"deletedCount": deletedCount}}
  222. c.ServeJSON()
  223. return
  224. }
  225. // CheckFileExists 检查文件列表是否存在
  226. func (c *FileManagerController) CheckFileExists() {
  227. // 获取路径列表参数
  228. pathsParam := c.GetString("paths")
  229. if len(pathsParam) == 0 {
  230. c.Data["json"] = lib.JSONS{Code: 202, Msg: "路径列表参数不能为空"}
  231. c.ServeJSON()
  232. return
  233. }
  234. // 解析路径列表(支持JSON数组格式)
  235. var paths []string
  236. if err := json.Unmarshal([]byte(pathsParam), &paths); err != nil {
  237. // 如果不是JSON格式,按逗号分割
  238. paths = strings.Split(pathsParam, ",")
  239. }
  240. // 存储已存在的路径信息
  241. var existingFiles []map[string]interface{}
  242. // 检查每个路径
  243. for _, path := range paths {
  244. path = strings.TrimSpace(path)
  245. if len(path) == 0 {
  246. continue
  247. }
  248. // 检查路径是否存在
  249. if exists := FileManager.Check_FileManager_Exists_ByPath(c.T_pid, path); exists {
  250. // 获取文件详细信息
  251. if file, err := FileManager.Read_FileManager_ByPath(c.T_pid, path); err == nil {
  252. // 构建返回格式
  253. fileInfo := map[string]interface{}{
  254. "name": file.T_name,
  255. "path": file.T_path,
  256. "size": file.T_size, // 使用实际文件大小
  257. "modTime": file.CreateTime.Format("2006-01-02 15:04:05"),
  258. "isDir": strings.HasSuffix(file.T_path, "/"),
  259. }
  260. existingFiles = append(existingFiles, fileInfo)
  261. }
  262. }
  263. }
  264. // 返回已存在的文件列表
  265. c.Data["json"] = lib.JSONS{Code: 200, Msg: "success", Data: existingFiles}
  266. c.ServeJSON()
  267. return
  268. }
  269. // GetFileManagerList 获取文件列表
  270. func (c *FileManagerController) GetFileManagerList() {
  271. page, _ := c.GetInt("page")
  272. if page < 1 {
  273. page = 1
  274. }
  275. page_z, _ := c.GetInt("page_z")
  276. if page_z < 1 || page_z > 1000 {
  277. page_z = conf.Page_size
  278. }
  279. // 获取查询参数
  280. path := c.GetString("path", "/")
  281. search := c.GetString("search", "") // 搜索关键词
  282. sortBy := c.GetString("sortBy", "name") // 排序字段
  283. sortOrder := c.GetString("sortOrder", "ascending") // 排序方向
  284. // 使用简化版查询方法(只查询当前路径直接子项)
  285. files, total := FileManager.Read_FileManager_List_Simple(
  286. c.T_pid,
  287. path,
  288. search,
  289. sortBy,
  290. sortOrder,
  291. page,
  292. page_z,
  293. )
  294. // 计算分页信息
  295. totalPages := int(math.Ceil(float64(total) / float64(page_z)))
  296. // 构建响应数据
  297. response := map[string]interface{}{
  298. "Data": files,
  299. "Num": total,
  300. "page": page,
  301. "Page_size": page_z,
  302. "totalPages": totalPages,
  303. "path": path,
  304. "sortBy": sortBy,
  305. "sortOrder": sortOrder,
  306. "breadcrumb": FileManager.Get_FileManager_Breadcrumb(path),
  307. }
  308. c.Data["json"] = lib.JSONS{Code: 200, Msg: "success", Data: response}
  309. c.ServeJSON()
  310. return
  311. }
  312. // ------------ 文件夹相关接口 ------------
  313. // AddFolder 创建文件夹
  314. func (c *FileManagerController) AddFolder() {
  315. T_name := c.GetString("T_name")
  316. if len(T_name) == 0 {
  317. c.Data["json"] = lib.JSONS{Code: 202, Msg: "文件夹名称不能为空"}
  318. c.ServeJSON()
  319. return
  320. }
  321. T_path := c.GetString("path", "/")
  322. if !strings.HasSuffix(T_path, "/") {
  323. T_path += "/"
  324. }
  325. // 自动创建父级路径中不存在的文件夹
  326. if T_path != "/" {
  327. err := FileManager.Auto_Create_Folders(c.T_pid, T_path, c.Admin_r.T_uuid)
  328. if err != nil {
  329. c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("创建父级路径失败: %v", err)}
  330. c.ServeJSON()
  331. return
  332. }
  333. }
  334. // 检查同级目录下是否存在同名文件夹
  335. if FileManager.Check_FileManager_Name_Exists(c.T_pid, T_path, T_name, 0) {
  336. c.Data["json"] = lib.JSONS{Code: 202, Msg: "该目录下已存在同名文件夹"}
  337. c.ServeJSON()
  338. return
  339. }
  340. // 构建文件夹完整路径
  341. folderPath := T_path + T_name + "/"
  342. // 创建文件夹
  343. id, err := FileManager.Add_FileManager_Folder(c.T_pid, T_name, folderPath, c.Admin_r.T_uuid)
  344. if err != nil {
  345. c.Data["json"] = lib.JSONS{Code: 202, Msg: "创建文件夹失败"}
  346. c.ServeJSON()
  347. return
  348. }
  349. c.Data["json"] = lib.JSONS{Code: 200, Msg: "创建成功", Data: map[string]interface{}{"id": id, "path": folderPath}}
  350. c.ServeJSON()
  351. return
  352. }
  353. // GetBreadcrumb 获取路径面包屑
  354. func (c *FileManagerController) GetBreadcrumb() {
  355. T_path := c.GetString("path", "/")
  356. breadcrumb := FileManager.Get_FileManager_Breadcrumb(T_path)
  357. c.Data["json"] = lib.JSONS{Code: 200, Msg: "success", Data: breadcrumb}
  358. c.ServeJSON()
  359. return
  360. }
  361. // RenameFile 重命名文件或文件夹
  362. func (c *FileManagerController) RenameFile() {
  363. // 支持两种参数格式:
  364. // 1. 传统的id + T_name格式
  365. // 2. 新的oldName + newName格式(参考API)
  366. oldName := c.GetString("oldName")
  367. newName := c.GetString("newName")
  368. path := c.GetString("path")
  369. // 如果使用新格式
  370. if len(oldName) > 0 && len(newName) > 0 {
  371. c.renameByPath(oldName, newName, path)
  372. return
  373. }
  374. }
  375. // renameByPath 基于路径的重命名方法
  376. func (c *FileManagerController) renameByPath(oldPath, newPath, parentPath string) {
  377. // 参数验证
  378. if len(oldPath) == 0 || len(newPath) == 0 {
  379. c.Data["json"] = lib.JSONS{Code: 202, Msg: "路径参数不能为空"}
  380. c.ServeJSON()
  381. return
  382. }
  383. // 从完整路径中提取文件名
  384. newName := filepath.Base(newPath)
  385. // 确保路径以/开头
  386. if !strings.HasPrefix(oldPath, "/") {
  387. oldPath = "/" + oldPath
  388. }
  389. if !strings.HasPrefix(newPath, "/") {
  390. newPath = "/" + newPath
  391. }
  392. // 查找要重命名的文件/文件夹
  393. file, err := FileManager.Read_FileManager_ByPath(c.T_pid, oldPath)
  394. if err != nil {
  395. // 如果是文件夹,尝试添加/后缀
  396. if !strings.HasSuffix(oldPath, "/") {
  397. file, err = FileManager.Read_FileManager_ByPath(c.T_pid, oldPath+"/")
  398. if err != nil {
  399. c.Data["json"] = lib.JSONS{Code: 202, Msg: "文件或文件夹不存在"}
  400. c.ServeJSON()
  401. return
  402. }
  403. oldPath += "/"
  404. newPath += "/"
  405. } else {
  406. c.Data["json"] = lib.JSONS{Code: 202, Msg: "文件或文件夹不存在"}
  407. c.ServeJSON()
  408. return
  409. }
  410. }
  411. // 验证权限
  412. if file.T_pid != c.T_pid {
  413. c.Data["json"] = lib.JSONS{Code: 202, Msg: "权限不足"}
  414. c.ServeJSON()
  415. return
  416. }
  417. // 检查新路径是否已存在
  418. exists := FileManager.Check_FileManager_Exists_ByPath(c.T_pid, newPath)
  419. if exists {
  420. c.Data["json"] = lib.JSONS{Code: 202, Msg: "目标路径已存在"}
  421. c.ServeJSON()
  422. return
  423. }
  424. // 执行重命名
  425. if strings.HasSuffix(oldPath, "/") { // 文件夹
  426. err = FileManager.Update_Folder_And_Children_Path(c.T_pid, oldPath, newPath, newName)
  427. if err != nil {
  428. c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("重命名文件夹失败: %v", err)}
  429. c.ServeJSON()
  430. return
  431. }
  432. } else { // 文件
  433. file.T_name = newName
  434. file.T_path = newPath
  435. success := FileManager.Update_FileManager(file, "T_name", "T_path", "UpdateTime")
  436. if !success {
  437. c.Data["json"] = lib.JSONS{Code: 202, Msg: "重命名失败"}
  438. c.ServeJSON()
  439. return
  440. }
  441. }
  442. c.Data["json"] = lib.JSONS{Code: 200, Msg: "重命名成功"}
  443. c.ServeJSON()
  444. return
  445. }
  446. // GetStorageInfo 获取公司存储使用情况
  447. func (c *FileManagerController) GetStorageInfo() {
  448. // 获取存储信息
  449. storageInfo, err := FileManager.Get_Company_Storage_Info(c.T_pid)
  450. if err != nil {
  451. c.Data["json"] = lib.JSONS{Code: 202, Msg: fmt.Sprintf("获取存储信息失败: %v", err)}
  452. c.ServeJSON()
  453. return
  454. }
  455. c.Data["json"] = lib.JSONS{Code: 200, Msg: "success", Data: storageInfo}
  456. c.ServeJSON()
  457. return
  458. }
  459. // GetUploadToken 获取七牛云上传Token
  460. func (c *FileManagerController) GetUploadToken() {
  461. // 获取文件后缀参数
  462. fileSuffix := c.GetString("suffix", "")
  463. // 生成上传Token
  464. uploadToken := lib.UploadToken(fileSuffix)
  465. c.Data["json"] = lib.JSONS{
  466. Code: 200,
  467. Msg: "success",
  468. Data: map[string]interface{}{
  469. "token": uploadToken,
  470. "domain": "", // 七牛云访问域名(如需要可从配置获取)
  471. },
  472. }
  473. c.ServeJSON()
  474. return
  475. }