sortfile.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package sortfile
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strconv"
  6. //"log"
  7. "os"
  8. "path/filepath"
  9. "sort"
  10. user "imuslab.com/arozos/mod/user"
  11. )
  12. type LargeFileScanner struct {
  13. userHandler *user.UserHandler
  14. }
  15. func NewLargeFileScanner(u *user.UserHandler) *LargeFileScanner {
  16. return &LargeFileScanner{
  17. userHandler: u,
  18. }
  19. }
  20. func (s *LargeFileScanner) HandleLargeFileList(w http.ResponseWriter, r *http.Request) {
  21. userinfo, err := s.userHandler.GetUserInfoFromRequest(w, r)
  22. if err != nil {
  23. sendErrorResponse(w, err.Error())
  24. return
  25. }
  26. //Check if limit is set. If yes, use the limit in return
  27. limit, err := mv(r, "number", false)
  28. if err != nil {
  29. limit = "20"
  30. }
  31. //Try convert the limit to integer
  32. limitInt, err := strconv.Atoi(limit)
  33. if err != nil {
  34. limitInt = 20
  35. }
  36. //Get all the fshandler for this user
  37. fsHandlers := userinfo.GetAllFileSystemHandler()
  38. type FileObject struct {
  39. Filename string
  40. Filepath string
  41. realpath string
  42. Size int64
  43. IsOwner bool
  44. }
  45. //Walk all filesystem handlers and buffer all files and their sizes
  46. fileList := []*FileObject{}
  47. for _, fsh := range fsHandlers {
  48. err := filepath.Walk(fsh.Path, func(path string, info os.FileInfo, err error) error {
  49. if info.IsDir() {
  50. return nil
  51. }
  52. //Push the current file into the filelist
  53. if info.Size() > 0 {
  54. vpath, _ := userinfo.RealPathToVirtualPath(path)
  55. fileList = append(fileList, &FileObject{
  56. Filename: filepath.Base(path),
  57. Filepath: vpath,
  58. realpath: path,
  59. Size: info.Size(),
  60. IsOwner: false,
  61. })
  62. }
  63. return nil
  64. })
  65. if err != nil {
  66. sendErrorResponse(w, "Failed to scan emulated storage device: "+fsh.Name)
  67. return
  68. }
  69. }
  70. //Sort the fileList
  71. sort.Slice(fileList, func(i, j int) bool {
  72. return fileList[i].Size > fileList[j].Size
  73. })
  74. //Set the max filecount to prevent slice bounds out of range
  75. if len(fileList) < limitInt {
  76. limitInt = len(fileList)
  77. }
  78. //Only check ownership of those requested
  79. for _, file := range fileList[:limitInt] {
  80. if userinfo.IsOwnerOfFile(file.realpath) {
  81. file.IsOwner = true
  82. } else {
  83. file.IsOwner = false
  84. }
  85. }
  86. //Format the results and return
  87. jsonString, _ := json.Marshal(fileList[:limitInt])
  88. sendJSONResponse(w, string(jsonString))
  89. }