file_system.go 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517
  1. package main
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "math"
  11. "mime/multipart"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "path/filepath"
  16. "runtime"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/gorilla/websocket"
  22. uuid "github.com/satori/go.uuid"
  23. "imuslab.com/arozos/mod/disk/hybridBackup"
  24. fs "imuslab.com/arozos/mod/filesystem"
  25. fsp "imuslab.com/arozos/mod/filesystem/fspermission"
  26. hidden "imuslab.com/arozos/mod/filesystem/hidden"
  27. metadata "imuslab.com/arozos/mod/filesystem/metadata"
  28. "imuslab.com/arozos/mod/filesystem/shortcut"
  29. module "imuslab.com/arozos/mod/modules"
  30. prout "imuslab.com/arozos/mod/prouter"
  31. "imuslab.com/arozos/mod/share"
  32. storage "imuslab.com/arozos/mod/storage"
  33. user "imuslab.com/arozos/mod/user"
  34. )
  35. var (
  36. thumbRenderHandler *metadata.RenderHandler
  37. shareManager *share.Manager
  38. )
  39. type trashedFile struct {
  40. Filename string
  41. Filepath string
  42. FileExt string
  43. IsDir bool
  44. Filesize int64
  45. RemoveTimestamp int64
  46. RemoveDate string
  47. OriginalPath string
  48. OriginalFilename string
  49. }
  50. func FileSystemInit() {
  51. router := prout.NewModuleRouter(prout.RouterOption{
  52. ModuleName: "File Manager",
  53. AdminOnly: false,
  54. UserHandler: userHandler,
  55. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  56. sendErrorResponse(w, "Permission Denied")
  57. },
  58. })
  59. //Upload related functions
  60. router.HandleFunc("/system/file_system/upload", system_fs_handleUpload)
  61. router.HandleFunc("/system/file_system/lowmemUpload", system_fs_handleLowMemoryUpload)
  62. //Other file operations
  63. router.HandleFunc("/system/file_system/validateFileOpr", system_fs_validateFileOpr)
  64. router.HandleFunc("/system/file_system/fileOpr", system_fs_handleOpr)
  65. router.HandleFunc("/system/file_system/ws/fileOpr", system_fs_handleWebSocketOpr)
  66. router.HandleFunc("/system/file_system/listDir", system_fs_handleList)
  67. router.HandleFunc("/system/file_system/listDirHash", system_fs_handleDirHash)
  68. router.HandleFunc("/system/file_system/listRoots", system_fs_listRoot)
  69. router.HandleFunc("/system/file_system/listDrives", system_fs_listDrives)
  70. router.HandleFunc("/system/file_system/newItem", system_fs_handleNewObjects)
  71. router.HandleFunc("/system/file_system/preference", system_fs_handleUserPreference)
  72. router.HandleFunc("/system/file_system/listTrash", system_fs_scanTrashBin)
  73. router.HandleFunc("/system/file_system/ws/listTrash", system_fs_WebSocketScanTrashBin)
  74. router.HandleFunc("/system/file_system/clearTrash", system_fs_clearTrashBin)
  75. router.HandleFunc("/system/file_system/restoreTrash", system_fs_restoreFile)
  76. router.HandleFunc("/system/file_system/zipHandler", system_fs_zipHandler)
  77. router.HandleFunc("/system/file_system/getProperties", system_fs_getFileProperties)
  78. router.HandleFunc("/system/file_system/pathTranslate", system_fs_handlePathTranslate)
  79. router.HandleFunc("/system/file_system/handleFilePermission", system_fs_handleFilePermission)
  80. router.HandleFunc("/system/file_system/search", system_fs_handleFileSearch)
  81. //Thumbnail caching functions
  82. router.HandleFunc("/system/file_system/handleFolderCache", system_fs_handleFolderCache)
  83. router.HandleFunc("/system/file_system/handleCacheRender", system_fs_handleCacheRender)
  84. //Register the module
  85. moduleHandler.RegisterModule(module.ModuleInfo{
  86. Name: "File Manager",
  87. Group: "System Tools",
  88. IconPath: "SystemAO/file_system/img/small_icon.png",
  89. Version: "1.0",
  90. StartDir: "SystemAO/file_system/file_explorer.html",
  91. SupportFW: true,
  92. InitFWSize: []int{1080, 580},
  93. LaunchFWDir: "SystemAO/file_system/file_explorer.html",
  94. SupportEmb: false,
  95. })
  96. //Register the Trashbin module
  97. moduleHandler.RegisterModule(module.ModuleInfo{
  98. Name: "Trash Bin",
  99. Group: "System Tools",
  100. IconPath: "SystemAO/file_system/trashbin_img/small_icon.png",
  101. Version: "1.0",
  102. StartDir: "SystemAO/file_system/trashbin.html",
  103. SupportFW: true,
  104. InitFWSize: []int{1080, 580},
  105. LaunchFWDir: "SystemAO/file_system/trashbin.html",
  106. SupportEmb: false,
  107. SupportedExt: []string{"*"},
  108. })
  109. //Register the Zip Extractor module
  110. moduleHandler.RegisterModule(module.ModuleInfo{
  111. Name: "Zip Extractor",
  112. Group: "System Tools",
  113. IconPath: "SystemAO/file_system/img/zip_extractor.png",
  114. Version: "1.0",
  115. SupportFW: false,
  116. LaunchEmb: "SystemAO/file_system/zip_extractor.html",
  117. SupportEmb: true,
  118. InitEmbSize: []int{260, 120},
  119. SupportedExt: []string{".zip"},
  120. })
  121. //Create user root if not exists
  122. err := os.MkdirAll(*root_directory+"users/", 0755)
  123. if err != nil {
  124. log.Println("Failed to create system storage root.")
  125. panic(err)
  126. }
  127. //Create database table if not exists
  128. err = sysdb.NewTable("fs")
  129. if err != nil {
  130. log.Println("Failed to create table for file system")
  131. panic(err)
  132. }
  133. //Create a RenderHandler for caching thumbnails
  134. thumbRenderHandler = metadata.NewRenderHandler()
  135. /*
  136. Share Related Registering
  137. This section of functions create and register the file share service
  138. for the arozos
  139. */
  140. //Create a share manager to handle user file sharae
  141. shareManager = share.NewShareManager(share.Options{
  142. AuthAgent: authAgent,
  143. Database: sysdb,
  144. UserHandler: userHandler,
  145. HostName: *host_name,
  146. TmpFolder: *tmp_directory,
  147. })
  148. //Share related functions
  149. router.HandleFunc("/system/file_system/share/new", shareManager.HandleCreateNewShare)
  150. router.HandleFunc("/system/file_system/share/delete", shareManager.HandleDeleteShare)
  151. router.HandleFunc("/system/file_system/share/edit", shareManager.HandleEditShare)
  152. router.HandleFunc("/system/file_system/share/checkShared", shareManager.HandleShareCheck)
  153. //Handle the main share function
  154. http.HandleFunc("/share", shareManager.HandleShareAccess)
  155. /*
  156. Nighly Tasks
  157. These functions allow file system to clear and maintain
  158. the arozos file system when no one is using the system
  159. */
  160. //Clear tmp folder if files is placed here too long
  161. nightlyManager.RegisterNightlyTask(system_fs_clearOldTmpFiles)
  162. //Clear shares that its parent file no longer exists in the system
  163. shareManager.ValidateAndClearShares()
  164. nightlyManager.RegisterNightlyTask(shareManager.ValidateAndClearShares)
  165. }
  166. /*
  167. File Search
  168. Handle file search in wildcard and recursive search
  169. */
  170. func system_fs_handleFileSearch(w http.ResponseWriter, r *http.Request) {
  171. //Get the user information
  172. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  173. if err != nil {
  174. sendErrorResponse(w, "User not logged in")
  175. return
  176. }
  177. //Get the search target root path
  178. vpath, err := mv(r, "path", true)
  179. if err != nil {
  180. sendErrorResponse(w, "Invalid vpath given")
  181. return
  182. }
  183. keyword, err := mv(r, "keyword", true)
  184. if err != nil {
  185. sendErrorResponse(w, "Invalid keyword given")
  186. return
  187. }
  188. //Check if case sensitive is enabled
  189. casesensitve, _ := mv(r, "casesensitive", true)
  190. //Translate the vpath to realpath
  191. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  192. if err != nil {
  193. sendErrorResponse(w, "Invalid path given")
  194. return
  195. }
  196. //Check if the search mode is recursive keyword or wildcard
  197. if len(keyword) > 1 && keyword[:1] == "/" {
  198. //Wildcard
  199. wildcard := keyword[1:]
  200. matchingFiles, err := filepath.Glob(filepath.Join(rpath, wildcard))
  201. if err != nil {
  202. sendErrorResponse(w, err.Error())
  203. return
  204. }
  205. //Prepare result struct
  206. results := []fs.FileData{}
  207. //Process the matching files. Do not allow directory escape
  208. srcAbs, _ := filepath.Abs(rpath)
  209. srcAbs = filepath.ToSlash(srcAbs)
  210. escaped := false
  211. for _, matchedFile := range matchingFiles {
  212. absMatch, _ := filepath.Abs(matchedFile)
  213. absMatch = filepath.ToSlash(absMatch)
  214. if !strings.Contains(absMatch, srcAbs) {
  215. escaped = true
  216. }
  217. thisVpath, _ := userinfo.RealPathToVirtualPath(matchedFile)
  218. results = append(results, fs.GetFileDataFromPath(thisVpath, matchedFile, 2))
  219. }
  220. if escaped {
  221. sendErrorResponse(w, "Search keywords contain escape character!")
  222. return
  223. }
  224. //OK. Tidy up the results
  225. js, _ := json.Marshal(results)
  226. sendJSONResponse(w, string(js))
  227. } else {
  228. //Recursive keyword
  229. results := []fs.FileData{}
  230. var err error = nil
  231. if casesensitve == "true" {
  232. //Require case sensitive match
  233. err = filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  234. if strings.Contains(filepath.Base(path), keyword) {
  235. //This is a matching file
  236. if !fs.IsInsideHiddenFolder(path) {
  237. thisVpath, _ := userinfo.RealPathToVirtualPath(path)
  238. results = append(results, fs.GetFileDataFromPath(thisVpath, path, 2))
  239. }
  240. }
  241. return nil
  242. })
  243. } else {
  244. //Require general match
  245. keywordLower := strings.ToLower(keyword)
  246. err = filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  247. if strings.Contains(strings.ToLower(filepath.Base(path)), keywordLower) {
  248. //This is a matching file
  249. if !fs.IsInsideHiddenFolder(path) {
  250. thisVpath, _ := userinfo.RealPathToVirtualPath(path)
  251. results = append(results, fs.GetFileDataFromPath(thisVpath, path, 2))
  252. }
  253. }
  254. return nil
  255. })
  256. }
  257. if err != nil {
  258. sendErrorResponse(w, err.Error())
  259. return
  260. }
  261. //OK. Tidy up the results
  262. js, _ := json.Marshal(results)
  263. sendJSONResponse(w, string(js))
  264. }
  265. }
  266. /*
  267. Handle low-memory upload operations
  268. This function is specailly designed to work with low memory devices
  269. (e.g. ZeroPi / Orange Pi Zero with 512MB RAM)
  270. */
  271. func system_fs_handleLowMemoryUpload(w http.ResponseWriter, r *http.Request) {
  272. //Get user info
  273. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  274. if err != nil {
  275. w.WriteHeader(http.StatusUnauthorized)
  276. w.Write([]byte("401 - Unauthorized"))
  277. return
  278. }
  279. //Get filename and upload path
  280. filename, err := mv(r, "filename", false)
  281. if filename == "" || err != nil {
  282. w.WriteHeader(http.StatusInternalServerError)
  283. w.Write([]byte("500 - Invalid filename given"))
  284. return
  285. }
  286. //Get upload target directory
  287. uploadTarget, err := mv(r, "path", false)
  288. if uploadTarget == "" || err != nil {
  289. w.WriteHeader(http.StatusInternalServerError)
  290. w.Write([]byte("500 - Invalid path given"))
  291. return
  292. }
  293. //Check if the user can write to this folder
  294. if !userinfo.CanWrite(uploadTarget) {
  295. //No permission
  296. w.WriteHeader(http.StatusForbidden)
  297. w.Write([]byte("403 - Access Denied"))
  298. return
  299. }
  300. //Translate the upload target directory
  301. realUploadPath, err := userinfo.VirtualPathToRealPath(uploadTarget)
  302. if err != nil {
  303. w.WriteHeader(http.StatusInternalServerError)
  304. w.Write([]byte("500 - Path translation failed"))
  305. return
  306. }
  307. //Generate an UUID for this upload
  308. uploadUUID := uuid.NewV4().String()
  309. uploadFolder := filepath.Join(*tmp_directory, "uploads", uploadUUID)
  310. os.MkdirAll(uploadFolder, 0700)
  311. targetUploadLocation := filepath.Join(realUploadPath, filename)
  312. if !fileExists(realUploadPath) {
  313. os.MkdirAll(realUploadPath, 0755)
  314. }
  315. //Start websocket connection
  316. var upgrader = websocket.Upgrader{}
  317. c, err := upgrader.Upgrade(w, r, nil)
  318. defer c.Close()
  319. //Handle WebSocket upload
  320. blockCounter := 0
  321. chunkName := []string{}
  322. lastChunkArrivalTime := time.Now().Unix()
  323. //Setup a timeout listener, check if connection still active every 1 minute
  324. ticker := time.NewTicker(60 * time.Second)
  325. done := make(chan bool)
  326. go func() {
  327. for {
  328. select {
  329. case <-done:
  330. return
  331. case <-ticker.C:
  332. if time.Now().Unix()-lastChunkArrivalTime > 300 {
  333. //Already 5 minutes without new data arraival. Stop connection
  334. log.Println("Upload WebSocket connection timeout. Disconnecting.")
  335. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  336. time.Sleep(1 * time.Second)
  337. c.Close()
  338. return
  339. }
  340. }
  341. }
  342. }()
  343. totalFileSize := int64(0)
  344. for {
  345. mt, message, err := c.ReadMessage()
  346. if err != nil {
  347. //Connection closed by client. Clear the tmp folder and exit
  348. log.Println("Upload terminated by client. Cleaning tmp folder.")
  349. //Clear the tmp folder
  350. time.Sleep(1 * time.Second)
  351. os.RemoveAll(uploadFolder)
  352. return
  353. }
  354. //The mt should be 2 = binary for file upload and 1 for control syntax
  355. if mt == 1 {
  356. msg := strings.TrimSpace(string(message))
  357. if msg == "done" {
  358. //Start the merging process
  359. log.Println(userinfo.Username + " uploaded a file: " + filepath.Base(targetUploadLocation))
  360. break
  361. } else {
  362. //Unknown operations
  363. }
  364. } else if mt == 2 {
  365. //File block. Save it to tmp folder
  366. chunkFilepath := filepath.Join(uploadFolder, "upld_"+strconv.Itoa(blockCounter))
  367. chunkName = append(chunkName, chunkFilepath)
  368. ioutil.WriteFile(chunkFilepath, message, 0700)
  369. //Update the last upload chunk time
  370. lastChunkArrivalTime = time.Now().Unix()
  371. //Check if the file size is too big
  372. totalFileSize += fs.GetFileSize(chunkFilepath)
  373. if totalFileSize > max_upload_size {
  374. //File too big
  375. c.WriteMessage(1, []byte(`{\"error\":\"File size too large.\"}`))
  376. //Close the connection
  377. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  378. time.Sleep(1 * time.Second)
  379. c.Close()
  380. //Clear the tmp files
  381. os.RemoveAll(uploadFolder)
  382. return
  383. }
  384. blockCounter++
  385. //Request client to send the next chunk
  386. c.WriteMessage(1, []byte("next"))
  387. }
  388. //log.Println("recv:", len(message), "type", mt)
  389. }
  390. //Merge the file
  391. out, err := os.OpenFile(targetUploadLocation, os.O_CREATE|os.O_WRONLY, 0755)
  392. if err != nil {
  393. log.Println("Failed to open file:", err)
  394. c.WriteMessage(1, []byte(`{\"error\":\"Failed to open destination file\"}`))
  395. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  396. time.Sleep(1 * time.Second)
  397. c.Close()
  398. return
  399. }
  400. defer out.Close()
  401. for _, filesrc := range chunkName {
  402. srcChunkReader, err := os.Open(filesrc)
  403. if err != nil {
  404. log.Println("Failed to open Source Chunk", filesrc, " with error ", err.Error())
  405. c.WriteMessage(1, []byte(`{\"error\":\"Failed to open Source Chunk\"}`))
  406. return
  407. }
  408. io.Copy(out, srcChunkReader)
  409. srcChunkReader.Close()
  410. }
  411. //Set owner of the new uploaded file
  412. userinfo.SetOwnerOfFile(targetUploadLocation)
  413. //Return complete signal
  414. c.WriteMessage(1, []byte("OK"))
  415. //Stop the timeout listner
  416. done <- true
  417. //Clear the tmp folder
  418. time.Sleep(1 * time.Second)
  419. err = os.RemoveAll(uploadFolder)
  420. if err != nil {
  421. log.Println(err)
  422. }
  423. //Close WebSocket connection after finished
  424. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  425. time.Sleep(1 * time.Second)
  426. c.Close()
  427. }
  428. /*
  429. Handle FORM POST based upload
  430. This function is design for general SBCs or computers with more than 2GB of RAM
  431. (e.g. Raspberry Pi 4 / Linux Server)
  432. */
  433. func system_fs_handleUpload(w http.ResponseWriter, r *http.Request) {
  434. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  435. if err != nil {
  436. sendErrorResponse(w, "User not logged in")
  437. return
  438. }
  439. //Limit the max upload size to the user defined size
  440. if max_upload_size != 0 {
  441. r.Body = http.MaxBytesReader(w, r.Body, max_upload_size)
  442. }
  443. //Check if this is running under demo mode. If yes, reject upload
  444. if *demo_mode {
  445. sendErrorResponse(w, "You cannot upload in demo mode")
  446. return
  447. }
  448. err = r.ParseMultipartForm(int64(*upload_buf) << 20)
  449. if err != nil {
  450. //Filesize too big
  451. log.Println(err)
  452. sendErrorResponse(w, "File too large")
  453. return
  454. }
  455. file, handler, err := r.FormFile("file")
  456. if err != nil {
  457. log.Println("Error Retrieving File from upload by user: " + userinfo.Username)
  458. sendErrorResponse(w, "Unable to parse file from upload")
  459. return
  460. }
  461. //Get upload target directory
  462. uploadTarget, _ := mv(r, "path", true)
  463. if uploadTarget == "" {
  464. sendErrorResponse(w, "Upload target cannot be empty.")
  465. return
  466. }
  467. //Translate the upload target directory
  468. realUploadPath, err := userinfo.VirtualPathToRealPath(uploadTarget)
  469. if err != nil {
  470. sendErrorResponse(w, "Upload target is invalid or permission denied.")
  471. return
  472. }
  473. storeFilename := handler.Filename //Filename of the uploaded file
  474. destFilepath := filepath.ToSlash(filepath.Clean(realUploadPath)) + "/" + storeFilename
  475. if !fileExists(filepath.Dir(destFilepath)) {
  476. os.MkdirAll(filepath.Dir(destFilepath), 0755)
  477. }
  478. //Check if the upload target is read only.
  479. accmode := userinfo.GetPathAccessPermission(uploadTarget)
  480. if accmode == "readonly" {
  481. sendErrorResponse(w, "The upload target is Read Only.")
  482. return
  483. } else if accmode == "denied" {
  484. sendErrorResponse(w, "Access Denied")
  485. return
  486. }
  487. //Check for storage quota
  488. uploadFileSize := handler.Size
  489. if !userinfo.StorageQuota.HaveSpace(uploadFileSize) {
  490. sendErrorResponse(w, "Storage Quota Full")
  491. return
  492. }
  493. //Prepare the file to be created (uploaded)
  494. destination, err := os.Create(destFilepath)
  495. if err != nil {
  496. sendErrorResponse(w, err.Error())
  497. return
  498. }
  499. defer destination.Close()
  500. defer file.Close()
  501. //Move the file to destination file location
  502. if *enable_asyncFileUpload {
  503. //Use Async upload method
  504. go func(r *http.Request, file multipart.File, destination *os.File, userinfo *user.User) {
  505. //Do the file copying using a buffered reader
  506. buf := make([]byte, *file_opr_buff)
  507. for {
  508. n, err := file.Read(buf)
  509. if err != nil && err != io.EOF {
  510. log.Println(err.Error())
  511. return
  512. }
  513. if n == 0 {
  514. break
  515. }
  516. if _, err := destination.Write(buf[:n]); err != nil {
  517. log.Println(err.Error())
  518. return
  519. }
  520. }
  521. //Clear up buffered files
  522. r.MultipartForm.RemoveAll()
  523. //Set the ownership of file
  524. userinfo.SetOwnerOfFile(destFilepath)
  525. //Perform a GC afterward
  526. runtime.GC()
  527. }(r, file, destination, userinfo)
  528. } else {
  529. //Use blocking upload and move method
  530. buf := make([]byte, *file_opr_buff)
  531. for {
  532. n, err := file.Read(buf)
  533. if err != nil && err != io.EOF {
  534. log.Println(err.Error())
  535. return
  536. }
  537. if n == 0 {
  538. break
  539. }
  540. if _, err := destination.Write(buf[:n]); err != nil {
  541. log.Println(err.Error())
  542. return
  543. }
  544. }
  545. //Clear up buffered files
  546. r.MultipartForm.RemoveAll()
  547. //Set the ownership of file
  548. userinfo.SetOwnerOfFile(destFilepath)
  549. }
  550. //Finish up the upload
  551. //fmt.Printf("Uploaded File: %+v\n", handler.Filename)
  552. //fmt.Printf("File Size: %+v\n", handler.Size)
  553. //fmt.Printf("MIME Header: %+v\n", handler.Header)
  554. //fmt.Println("Upload target: " + realUploadPath)
  555. //Fnish upload. Fix the tmp filename
  556. log.Println(userinfo.Username + " uploaded a file: " + handler.Filename)
  557. //Do upload finishing stuff
  558. //Perform a GC
  559. runtime.GC()
  560. //Completed
  561. sendOK(w)
  562. return
  563. }
  564. //Validate if the copy and target process will involve file overwriting problem.
  565. func system_fs_validateFileOpr(w http.ResponseWriter, r *http.Request) {
  566. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  567. if err != nil {
  568. sendErrorResponse(w, err.Error())
  569. return
  570. }
  571. vsrcFiles, _ := mv(r, "src", true)
  572. vdestFile, _ := mv(r, "dest", true)
  573. var duplicateFiles []string
  574. //Loop through all files are see if there are duplication during copy and paste
  575. sourceFiles := []string{}
  576. decodedSourceFiles, _ := url.QueryUnescape(vsrcFiles)
  577. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  578. if err != nil {
  579. sendErrorResponse(w, "Source file JSON parse error.")
  580. return
  581. }
  582. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  583. for _, file := range sourceFiles {
  584. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(file))
  585. if fileExists(rdestFile + filepath.Base(rsrcFile)) {
  586. //File exists already.
  587. vpath, _ := userinfo.RealPathToVirtualPath(rsrcFile)
  588. duplicateFiles = append(duplicateFiles, vpath)
  589. }
  590. }
  591. jsonString, _ := json.Marshal(duplicateFiles)
  592. sendJSONResponse(w, string(jsonString))
  593. return
  594. }
  595. //Scan all directory and get trash file and send back results with WebSocket
  596. func system_fs_WebSocketScanTrashBin(w http.ResponseWriter, r *http.Request) {
  597. //Get and check user permission
  598. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  599. if err != nil {
  600. sendErrorResponse(w, "User not logged in")
  601. return
  602. }
  603. //Upgrade to websocket
  604. var upgrader = websocket.Upgrader{}
  605. c, err := upgrader.Upgrade(w, r, nil)
  606. if err != nil {
  607. w.WriteHeader(http.StatusInternalServerError)
  608. w.Write([]byte("500 - " + err.Error()))
  609. log.Print("Websocket Upgrade Error:", err.Error())
  610. return
  611. }
  612. //Start Scanning
  613. scanningRoots := []string{}
  614. //Get all roots to scan
  615. for _, storage := range userinfo.GetAllFileSystemHandler() {
  616. storageRoot := storage.Path
  617. scanningRoots = append(scanningRoots, storageRoot)
  618. }
  619. for _, rootPath := range scanningRoots {
  620. err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
  621. oneLevelUpper := filepath.Base(filepath.Dir(path))
  622. if oneLevelUpper == ".trash" {
  623. //This is a trashbin dir.
  624. file := path
  625. //Parse the trashFile struct
  626. timestamp := filepath.Ext(file)[1:]
  627. originalName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(filepath.Base(file)))
  628. originalExt := filepath.Ext(filepath.Base(originalName))
  629. virtualFilepath, _ := userinfo.RealPathToVirtualPath(file)
  630. virtualOrgPath, _ := userinfo.RealPathToVirtualPath(filepath.Dir(filepath.Dir(file)))
  631. rawsize := fs.GetFileSize(file)
  632. timestampInt64, _ := StringToInt64(timestamp)
  633. removeTimeDate := time.Unix(timestampInt64, 0)
  634. if IsDir(file) {
  635. originalExt = ""
  636. }
  637. thisTrashFileObject := trashedFile{
  638. Filename: filepath.Base(file),
  639. Filepath: virtualFilepath,
  640. FileExt: originalExt,
  641. IsDir: IsDir(file),
  642. Filesize: int64(rawsize),
  643. RemoveTimestamp: timestampInt64,
  644. RemoveDate: timeToString(removeTimeDate),
  645. OriginalPath: virtualOrgPath,
  646. OriginalFilename: originalName,
  647. }
  648. //Send out the result as JSON string
  649. js, _ := json.Marshal(thisTrashFileObject)
  650. err := c.WriteMessage(1, js)
  651. if err != nil {
  652. //Connection already closed
  653. return err
  654. }
  655. }
  656. return nil
  657. })
  658. if err != nil {
  659. //Scan or client connection error (Connection closed?)
  660. return
  661. }
  662. }
  663. //Close connection after finished
  664. c.Close()
  665. }
  666. //Scan all the directory and get trash files within the system
  667. func system_fs_scanTrashBin(w http.ResponseWriter, r *http.Request) {
  668. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  669. if err != nil {
  670. sendErrorResponse(w, err.Error())
  671. return
  672. }
  673. username := userinfo.Username
  674. results := []trashedFile{}
  675. files, err := system_fs_listTrash(username)
  676. if err != nil {
  677. sendErrorResponse(w, err.Error())
  678. return
  679. }
  680. //Get information of each files and process it into results
  681. for _, file := range files {
  682. timestamp := filepath.Ext(file)[1:]
  683. originalName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(filepath.Base(file)))
  684. originalExt := filepath.Ext(filepath.Base(originalName))
  685. virtualFilepath, _ := userinfo.RealPathToVirtualPath(file)
  686. virtualOrgPath, _ := userinfo.RealPathToVirtualPath(filepath.Dir(filepath.Dir(file)))
  687. rawsize := fs.GetFileSize(file)
  688. timestampInt64, _ := StringToInt64(timestamp)
  689. removeTimeDate := time.Unix(timestampInt64, 0)
  690. if IsDir(file) {
  691. originalExt = ""
  692. }
  693. results = append(results, trashedFile{
  694. Filename: filepath.Base(file),
  695. Filepath: virtualFilepath,
  696. FileExt: originalExt,
  697. IsDir: IsDir(file),
  698. Filesize: int64(rawsize),
  699. RemoveTimestamp: timestampInt64,
  700. RemoveDate: timeToString(removeTimeDate),
  701. OriginalPath: virtualOrgPath,
  702. OriginalFilename: originalName,
  703. })
  704. }
  705. //Sort the results by date, latest on top
  706. sort.Slice(results[:], func(i, j int) bool {
  707. return results[i].RemoveTimestamp > results[j].RemoveTimestamp
  708. })
  709. //Format and return the json results
  710. jsonString, _ := json.Marshal(results)
  711. sendJSONResponse(w, string(jsonString))
  712. }
  713. //Restore a trashed file to its parent dir
  714. func system_fs_restoreFile(w http.ResponseWriter, r *http.Request) {
  715. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  716. if err != nil {
  717. sendErrorResponse(w, err.Error())
  718. return
  719. }
  720. targetTrashedFile, err := mv(r, "src", true)
  721. if err != nil {
  722. sendErrorResponse(w, "Invalid src given")
  723. return
  724. }
  725. //Translate it to realpath
  726. realpath, _ := userinfo.VirtualPathToRealPath(targetTrashedFile)
  727. if !fileExists(realpath) {
  728. sendErrorResponse(w, "File not exists")
  729. return
  730. }
  731. //Check if this is really a trashed file
  732. if filepath.Base(filepath.Dir(realpath)) != ".trash" {
  733. sendErrorResponse(w, "File not in trashbin")
  734. return
  735. }
  736. //OK to proceed.
  737. targetPath := filepath.ToSlash(filepath.Dir(filepath.Dir(realpath))) + "/" + strings.TrimSuffix(filepath.Base(realpath), filepath.Ext(filepath.Base(realpath)))
  738. //log.Println(targetPath);
  739. os.Rename(realpath, targetPath)
  740. //Check if the parent dir has no more fileds. If yes, remove it
  741. filescounter, _ := filepath.Glob(filepath.Dir(realpath) + "/*")
  742. if len(filescounter) == 0 {
  743. os.Remove(filepath.Dir(realpath))
  744. }
  745. sendOK(w)
  746. }
  747. //Clear all trashed file in the system
  748. func system_fs_clearTrashBin(w http.ResponseWriter, r *http.Request) {
  749. u, err := userHandler.GetUserInfoFromRequest(w, r)
  750. if err != nil {
  751. sendErrorResponse(w, "User not logged in")
  752. return
  753. }
  754. username := u.Username
  755. fileList, err := system_fs_listTrash(username)
  756. if err != nil {
  757. sendErrorResponse(w, "Unable to clear trash: "+err.Error())
  758. return
  759. }
  760. //Get list success. Remove each of them.
  761. for _, file := range fileList {
  762. isOwner := u.IsOwnerOfFile(file)
  763. if isOwner {
  764. //This user own this system. Remove this file from his quota
  765. u.RemoveOwnershipFromFile(file)
  766. }
  767. os.RemoveAll(file)
  768. //Check if its parent directory have no files. If yes, remove the dir itself as well.
  769. filesInThisTrashBin, _ := filepath.Glob(filepath.Dir(file) + "/*")
  770. if len(filesInThisTrashBin) == 0 {
  771. os.Remove(filepath.Dir(file))
  772. }
  773. }
  774. sendOK(w)
  775. }
  776. //Get all trash in a string list
  777. func system_fs_listTrash(username string) ([]string, error) {
  778. userinfo, _ := userHandler.GetUserInfoFromUsername(username)
  779. scanningRoots := []string{}
  780. //Get all roots to scan
  781. for _, storage := range userinfo.GetAllFileSystemHandler() {
  782. storageRoot := storage.Path
  783. scanningRoots = append(scanningRoots, storageRoot)
  784. }
  785. files := []string{}
  786. for _, rootPath := range scanningRoots {
  787. err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
  788. oneLevelUpper := filepath.Base(filepath.Dir(path))
  789. if oneLevelUpper == ".trash" {
  790. //This is a trashbin dir.
  791. files = append(files, path)
  792. }
  793. return nil
  794. })
  795. if err != nil {
  796. return []string{}, errors.New("Failed to scan file system.")
  797. }
  798. }
  799. return files, nil
  800. }
  801. /*
  802. Handle new file or folder functions
  803. Required information
  804. @type {folder / file}
  805. @ext {any that is listed in the template folder}
  806. if no paramter is passed in, default listing all the supported template file
  807. */
  808. func system_fs_handleNewObjects(w http.ResponseWriter, r *http.Request) {
  809. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  810. if err != nil {
  811. sendErrorResponse(w, "User not logged in")
  812. return
  813. }
  814. fileType, _ := mv(r, "type", true) //File creation type, {file, folder}
  815. vsrc, _ := mv(r, "src", true) //Virtual file source folder, do not include filename
  816. filename, _ := mv(r, "filename", true) //Filename for the new file
  817. if fileType == "" && filename == "" {
  818. //List all the supported new filetype
  819. if !fileExists("system/newitem/") {
  820. os.MkdirAll("system/newitem/", 0755)
  821. }
  822. type newItemObject struct {
  823. Desc string
  824. Ext string
  825. }
  826. var newItemList []newItemObject
  827. newItemTemplate, _ := filepath.Glob("system/newitem/*")
  828. for _, file := range newItemTemplate {
  829. thisItem := new(newItemObject)
  830. thisItem.Desc = strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
  831. thisItem.Ext = filepath.Ext(file)[1:]
  832. newItemList = append(newItemList, *thisItem)
  833. }
  834. jsonString, err := json.Marshal(newItemList)
  835. if err != nil {
  836. log.Println("*File System* Unable to parse JSON string for new item list!")
  837. sendErrorResponse(w, "Unable to parse new item list. See server log for more information.")
  838. return
  839. }
  840. sendJSONResponse(w, string(jsonString))
  841. return
  842. } else if fileType != "" && filename != "" {
  843. if vsrc == "" {
  844. sendErrorResponse(w, "Missing paramter: 'src'")
  845. return
  846. }
  847. //Translate the path to realpath
  848. rpath, err := userinfo.VirtualPathToRealPath(vsrc)
  849. if err != nil {
  850. sendErrorResponse(w, "Invalid path given.")
  851. return
  852. }
  853. //Check if directory is readonly
  854. accmode := userinfo.GetPathAccessPermission(vsrc)
  855. if accmode == "readonly" {
  856. sendErrorResponse(w, "This directory is Read Only.")
  857. return
  858. } else if accmode == "denied" {
  859. sendErrorResponse(w, "Access Denied")
  860. return
  861. }
  862. //Check if the file already exists. If yes, fix its filename.
  863. newfilePath := filepath.ToSlash(filepath.Join(rpath, filename))
  864. if fileType == "file" {
  865. for fileExists(newfilePath) {
  866. sendErrorResponse(w, "Given filename already exists.")
  867. return
  868. }
  869. ext := filepath.Ext(filename)
  870. if ext == "" {
  871. //This is a file with no extension.
  872. f, err := os.Create(newfilePath)
  873. if err != nil {
  874. log.Println("*File System* " + err.Error())
  875. sendErrorResponse(w, err.Error())
  876. return
  877. }
  878. f.Close()
  879. } else {
  880. templateFile, _ := filepath.Glob("system/newitem/*" + ext)
  881. if len(templateFile) == 0 {
  882. //This file extension is not in template
  883. f, err := os.Create(newfilePath)
  884. if err != nil {
  885. log.Println("*File System* " + err.Error())
  886. sendErrorResponse(w, err.Error())
  887. return
  888. }
  889. f.Close()
  890. } else {
  891. //Copy file from templateFile[0] to current dir with the given name
  892. input, _ := ioutil.ReadFile(templateFile[0])
  893. err := ioutil.WriteFile(newfilePath, input, 0755)
  894. if err != nil {
  895. log.Println("*File System* " + err.Error())
  896. sendErrorResponse(w, err.Error())
  897. return
  898. }
  899. }
  900. }
  901. } else if fileType == "folder" {
  902. if fileExists(newfilePath) {
  903. sendErrorResponse(w, "Given folder already exists.")
  904. return
  905. }
  906. //Create the folder at target location
  907. err := os.Mkdir(newfilePath, 0755)
  908. if err != nil {
  909. sendErrorResponse(w, err.Error())
  910. return
  911. }
  912. }
  913. sendJSONResponse(w, "\"OK\"")
  914. } else {
  915. sendErrorResponse(w, "Missing paramter(s).")
  916. return
  917. }
  918. }
  919. /*
  920. Handle file operations via WebSocket
  921. This handler only handle zip, unzip, copy and move. Not other operations.
  922. For other operations, please use the legacy handleOpr endpoint
  923. */
  924. func system_fs_handleWebSocketOpr(w http.ResponseWriter, r *http.Request) {
  925. //Get and check user permission
  926. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  927. if err != nil {
  928. sendErrorResponse(w, "User not logged in")
  929. return
  930. }
  931. operation, _ := mv(r, "opr", false) //Accept copy and move
  932. vsrcFiles, _ := mv(r, "src", false)
  933. vdestFile, _ := mv(r, "dest", false)
  934. existsOpr, _ := mv(r, "existsresp", false)
  935. if existsOpr == "" {
  936. existsOpr = "keep"
  937. }
  938. //Decode the source file list
  939. var sourceFiles []string
  940. tmp := []string{}
  941. decodedSourceFiles, _ := url.QueryUnescape(vsrcFiles)
  942. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  943. if err != nil {
  944. log.Println("Source file JSON parse error.", err.Error())
  945. sendErrorResponse(w, "Source file JSON parse error.")
  946. return
  947. }
  948. //Bugged char filtering
  949. for _, src := range sourceFiles {
  950. tmp = append(tmp, strings.ReplaceAll(src, "{{plug_sign}}", "+"))
  951. }
  952. sourceFiles = tmp
  953. vdestFile = strings.ReplaceAll(vdestFile, "{{plug_sign}}", "+")
  954. //Decode the target position
  955. escapedVdest, _ := url.QueryUnescape(vdestFile)
  956. vdestFile = escapedVdest
  957. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  958. //Permission checking
  959. if !userinfo.CanWrite(vdestFile) {
  960. log.Println(vdestFile)
  961. w.WriteHeader(http.StatusForbidden)
  962. w.Write([]byte("403 - Access Denied"))
  963. return
  964. }
  965. //Check if opr is suported
  966. if operation == "move" || operation == "copy" || operation == "zip" || operation == "unzip" {
  967. } else {
  968. log.Println("This file operation is not supported on WebSocket file operations endpoint. Please use the legacy endpoint instead. Received: ", operation)
  969. w.WriteHeader(http.StatusInternalServerError)
  970. w.Write([]byte("500 - Not supported operation"))
  971. return
  972. }
  973. //Upgrade to websocket
  974. var upgrader = websocket.Upgrader{}
  975. c, err := upgrader.Upgrade(w, r, nil)
  976. if err != nil {
  977. w.WriteHeader(http.StatusInternalServerError)
  978. w.Write([]byte("500 - " + err.Error()))
  979. log.Print("Websocket Upgrade Error:", err.Error())
  980. return
  981. }
  982. type ProgressUpdate struct {
  983. LatestFile string
  984. Progress int
  985. Error string
  986. }
  987. if operation == "zip" {
  988. //Zip files
  989. outputFilename := filepath.Join(rdestFile, filepath.Base(rdestFile)) + ".zip"
  990. if len(sourceFiles) == 1 {
  991. //Use the basename of the source file as zip file name
  992. outputFilename = filepath.Join(rdestFile, filepath.Base(sourceFiles[0])) + ".zip"
  993. }
  994. //Translate source Files into real paths
  995. realSourceFiles := []string{}
  996. for _, vsrcs := range sourceFiles {
  997. rsrc, err := userinfo.VirtualPathToRealPath(vsrcs)
  998. if err != nil {
  999. stopStatus := ProgressUpdate{
  1000. LatestFile: filepath.Base(rsrc),
  1001. Progress: -1,
  1002. Error: "File not exists",
  1003. }
  1004. js, _ := json.Marshal(stopStatus)
  1005. c.WriteMessage(1, js)
  1006. c.Close()
  1007. }
  1008. realSourceFiles = append(realSourceFiles, rsrc)
  1009. }
  1010. //Create the zip file
  1011. fs.ArozZipFileWithProgress(realSourceFiles, outputFilename, false, func(currentFilename string, _ int, _ int, progress float64) {
  1012. currentStatus := ProgressUpdate{
  1013. LatestFile: currentFilename,
  1014. Progress: int(math.Ceil(progress)),
  1015. Error: "",
  1016. }
  1017. js, _ := json.Marshal(currentStatus)
  1018. c.WriteMessage(1, js)
  1019. })
  1020. } else if operation == "unzip" {
  1021. //Check if the target destination exists and writable
  1022. if !userinfo.CanWrite(vdestFile) {
  1023. stopStatus := ProgressUpdate{
  1024. LatestFile: filepath.Base(vdestFile),
  1025. Progress: -1,
  1026. Error: "Access Denied: No Write Permission",
  1027. }
  1028. js, _ := json.Marshal(stopStatus)
  1029. c.WriteMessage(1, js)
  1030. c.Close()
  1031. }
  1032. //Create the destination folder
  1033. os.MkdirAll(rdestFile, 0755)
  1034. //Convert the src files into realpaths
  1035. realSourceFiles := []string{}
  1036. for _, vsrcs := range sourceFiles {
  1037. rsrc, err := userinfo.VirtualPathToRealPath(vsrcs)
  1038. if err != nil {
  1039. stopStatus := ProgressUpdate{
  1040. LatestFile: filepath.Base(rsrc),
  1041. Progress: -1,
  1042. Error: "File not exists",
  1043. }
  1044. js, _ := json.Marshal(stopStatus)
  1045. c.WriteMessage(1, js)
  1046. c.Close()
  1047. }
  1048. realSourceFiles = append(realSourceFiles, rsrc)
  1049. }
  1050. //Unzip the files
  1051. fs.ArozUnzipFileWithProgress(realSourceFiles, rdestFile, func(currentFile string, filecount int, totalfile int, progress float64) {
  1052. //Generate the status update struct
  1053. currentStatus := ProgressUpdate{
  1054. LatestFile: filepath.Base(currentFile),
  1055. Progress: int(math.Ceil(progress)),
  1056. Error: "",
  1057. }
  1058. js, _ := json.Marshal(currentStatus)
  1059. c.WriteMessage(1, js)
  1060. })
  1061. } else {
  1062. //Other operations that allow multiple source files to handle one by one
  1063. for i := 0; i < len(sourceFiles); i++ {
  1064. vsrcFile := sourceFiles[i]
  1065. rsrcFile, _ := userinfo.VirtualPathToRealPath(vsrcFile)
  1066. //c.WriteMessage(1, message)
  1067. if !fileExists(rsrcFile) {
  1068. //This source file not exists. Report Error and Stop
  1069. stopStatus := ProgressUpdate{
  1070. LatestFile: filepath.Base(rsrcFile),
  1071. Progress: -1,
  1072. Error: "File not exists",
  1073. }
  1074. js, _ := json.Marshal(stopStatus)
  1075. c.WriteMessage(1, js)
  1076. c.Close()
  1077. return
  1078. }
  1079. if operation == "move" {
  1080. err := fs.FileMove(rsrcFile, rdestFile, existsOpr, false, func(progress int, currentFile string) {
  1081. //Multply child progress to parent progress
  1082. blockRatio := float64(100) / float64(len(sourceFiles))
  1083. overallRatio := blockRatio*float64(i) + blockRatio*(float64(progress)/float64(100))
  1084. //Construct return struct
  1085. currentStatus := ProgressUpdate{
  1086. LatestFile: filepath.Base(currentFile),
  1087. Progress: int(overallRatio),
  1088. Error: "",
  1089. }
  1090. js, _ := json.Marshal(currentStatus)
  1091. c.WriteMessage(1, js)
  1092. })
  1093. //Handle move starting error
  1094. if err != nil {
  1095. stopStatus := ProgressUpdate{
  1096. LatestFile: filepath.Base(rsrcFile),
  1097. Progress: -1,
  1098. Error: err.Error(),
  1099. }
  1100. js, _ := json.Marshal(stopStatus)
  1101. c.WriteMessage(1, js)
  1102. c.Close()
  1103. return
  1104. }
  1105. } else if operation == "copy" {
  1106. err := fs.FileCopy(rsrcFile, rdestFile, existsOpr, func(progress int, currentFile string) {
  1107. //Multply child progress to parent progress
  1108. blockRatio := float64(100) / float64(len(sourceFiles))
  1109. overallRatio := blockRatio*float64(i) + blockRatio*(float64(progress)/float64(100))
  1110. //Construct return struct
  1111. currentStatus := ProgressUpdate{
  1112. LatestFile: filepath.Base(currentFile),
  1113. Progress: int(overallRatio),
  1114. Error: "",
  1115. }
  1116. js, _ := json.Marshal(currentStatus)
  1117. c.WriteMessage(1, js)
  1118. })
  1119. //Handle Copy starting error
  1120. if err != nil {
  1121. stopStatus := ProgressUpdate{
  1122. LatestFile: filepath.Base(rsrcFile),
  1123. Progress: -1,
  1124. Error: err.Error(),
  1125. }
  1126. js, _ := json.Marshal(stopStatus)
  1127. c.WriteMessage(1, js)
  1128. c.Close()
  1129. return
  1130. }
  1131. }
  1132. }
  1133. }
  1134. //Close WebSocket connection after finished
  1135. time.Sleep(1 * time.Second)
  1136. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  1137. c.Close()
  1138. }
  1139. /*
  1140. Handle file operations
  1141. Support {move, copy, delete, recycle, rename}
  1142. */
  1143. //Handle file operations.
  1144. func system_fs_handleOpr(w http.ResponseWriter, r *http.Request) {
  1145. //Check if user logged in
  1146. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1147. if err != nil {
  1148. sendErrorResponse(w, "User not logged in")
  1149. return
  1150. }
  1151. //Validate the token
  1152. tokenValid := CSRFTokenManager.HandleTokenValidation(w, r)
  1153. if !tokenValid {
  1154. http.Error(w, "Invalid CSRF token", 401)
  1155. return
  1156. }
  1157. operation, _ := mv(r, "opr", true)
  1158. vsrcFiles, _ := mv(r, "src", true)
  1159. vdestFile, _ := mv(r, "dest", true)
  1160. vnfilenames, _ := mv(r, "new", true) //Only use when rename or create new file / folder
  1161. //Check if operation valid.
  1162. if operation == "" {
  1163. //Undefined operations.
  1164. sendErrorResponse(w, "Undefined operations paramter: Missing 'opr' in request header.")
  1165. return
  1166. }
  1167. //As the user can pass in multiple source files at the same time, parse sourceFiles from json string
  1168. var sourceFiles []string
  1169. //This line is required in order to allow passing of special charaters
  1170. decodedSourceFiles := system_fs_specialURIDecode(vsrcFiles)
  1171. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  1172. if err != nil {
  1173. sendErrorResponse(w, "Source file JSON parse error.")
  1174. return
  1175. }
  1176. //Check if new filenames are also valid. If yes, translate it into string array
  1177. var newFilenames []string
  1178. if vnfilenames != "" {
  1179. vnfilenames, _ := url.QueryUnescape(vnfilenames)
  1180. err = json.Unmarshal([]byte(vnfilenames), &newFilenames)
  1181. if err != nil {
  1182. sendErrorResponse(w, "Unable to parse JSON for new filenames")
  1183. return
  1184. }
  1185. }
  1186. if operation == "zip" {
  1187. //Zip operation. Parse the real filepath list
  1188. rsrcFiles := []string{}
  1189. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1190. for _, vsrcFile := range sourceFiles {
  1191. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1192. if fileExists(rsrcFile) {
  1193. rsrcFiles = append(rsrcFiles, rsrcFile)
  1194. }
  1195. }
  1196. zipFilename := rdestFile
  1197. if fs.IsDir(rdestFile) {
  1198. //Append the filename to it
  1199. if len(rsrcFiles) == 1 {
  1200. zipFilename = filepath.Join(rdestFile, strings.TrimSuffix(filepath.Base(rsrcFiles[0]), filepath.Ext(filepath.Base(rsrcFiles[0])))+".zip")
  1201. } else if len(rsrcFiles) > 1 {
  1202. zipFilename = filepath.Join(rdestFile, filepath.Base(filepath.Dir(rsrcFiles[0]))+".zip")
  1203. }
  1204. }
  1205. //Create a zip file at target location
  1206. err := fs.ArozZipFile(rsrcFiles, zipFilename, false)
  1207. if err != nil {
  1208. sendErrorResponse(w, err.Error())
  1209. return
  1210. }
  1211. } else {
  1212. //For operations that is handled file by file
  1213. for i, vsrcFile := range sourceFiles {
  1214. //Convert the virtual path to realpath on disk
  1215. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1216. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1217. //Check if the source file exists
  1218. if !fileExists(rsrcFile) {
  1219. /*
  1220. Special edge case handler:
  1221. There might be edge case that files are stored in URIEncoded methods
  1222. e.g. abc def.mp3 --> abc%20cdf.mp3
  1223. In this case, this logic statement should be able to handle this
  1224. */
  1225. edgeCaseFilename := filepath.Join(filepath.Dir(rsrcFile), system_fs_specialURIEncode(filepath.Base(rsrcFile)))
  1226. if fileExists(edgeCaseFilename) {
  1227. rsrcFile = edgeCaseFilename
  1228. } else {
  1229. sendErrorResponse(w, "Source file not exists.")
  1230. return
  1231. }
  1232. }
  1233. if operation == "rename" {
  1234. //Check if the usage is correct.
  1235. if vdestFile != "" {
  1236. sendErrorResponse(w, "Rename only accept 'src' and 'new'. Please use move if you want to move a file.")
  1237. return
  1238. }
  1239. //Check if new name paramter is passed in.
  1240. if len(newFilenames) == 0 {
  1241. sendErrorResponse(w, "Missing paramter (JSON string): 'new'")
  1242. return
  1243. }
  1244. //Check if the source filenames and new filenanmes match
  1245. if len(newFilenames) != len(sourceFiles) {
  1246. sendErrorResponse(w, "New filenames do not match with source filename's length.")
  1247. return
  1248. }
  1249. //Check if the target dir is not readonly
  1250. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1251. if accmode == "readonly" {
  1252. sendErrorResponse(w, "This directory is Read Only.")
  1253. return
  1254. } else if accmode == "denied" {
  1255. sendErrorResponse(w, "Access Denied")
  1256. return
  1257. }
  1258. thisFilename := newFilenames[i]
  1259. //Check if the name already exists. If yes, return false
  1260. if fileExists(filepath.Dir(rsrcFile) + "/" + thisFilename) {
  1261. sendErrorResponse(w, "File already exists")
  1262. return
  1263. }
  1264. //Everything is ok. Rename the file.
  1265. targetNewName := filepath.Dir(rsrcFile) + "/" + thisFilename
  1266. err = os.Rename(rsrcFile, targetNewName)
  1267. if err != nil {
  1268. sendErrorResponse(w, err.Error())
  1269. return
  1270. }
  1271. } else if operation == "move" {
  1272. //File move operation. Check if the source file / dir and target directory exists
  1273. /*
  1274. Example usage from file explorer
  1275. $.ajax({
  1276. type: 'POST',
  1277. url: `/system/file_system/fileOpr`,
  1278. data: {opr: "move" ,src: JSON.stringify(fileList), dest: targetDir},
  1279. success: function(data){
  1280. if (data.error !== undefined){
  1281. msgbox("remove",data.error);
  1282. }else{
  1283. //OK, do something
  1284. }
  1285. }
  1286. });
  1287. */
  1288. if !fileExists(rsrcFile) {
  1289. sendErrorResponse(w, "Source file not exists")
  1290. return
  1291. }
  1292. //Check if the source file is read only.
  1293. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1294. if accmode == "readonly" {
  1295. sendErrorResponse(w, "This source file is Read Only.")
  1296. return
  1297. } else if accmode == "denied" {
  1298. sendErrorResponse(w, "Access Denied")
  1299. return
  1300. }
  1301. if rdestFile == "" {
  1302. sendErrorResponse(w, "Undefined dest location.")
  1303. return
  1304. }
  1305. //Get exists overwrite mode
  1306. existsOpr, _ := mv(r, "existsresp", true)
  1307. //Check if use fast move instead
  1308. //Check if the source and destination folder are under the same root. If yes, use os.Rename for faster move operations
  1309. underSameRoot := false
  1310. //Check if the two files are under the same user root path
  1311. srcAbs, _ := filepath.Abs(rsrcFile)
  1312. destAbs, _ := filepath.Abs(rdestFile)
  1313. //Check other storage path and see if they are under the same root
  1314. for _, rootPath := range userinfo.GetAllFileSystemHandler() {
  1315. thisRoot := rootPath.Path
  1316. thisRootAbs, err := filepath.Abs(thisRoot)
  1317. if err != nil {
  1318. continue
  1319. }
  1320. if strings.Contains(srcAbs, thisRootAbs) && strings.Contains(destAbs, thisRootAbs) {
  1321. underSameRoot = true
  1322. }
  1323. }
  1324. //Updates 19-10-2020: Added ownership management to file move and copy
  1325. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1326. err = fs.FileMove(rsrcFile, rdestFile, existsOpr, underSameRoot, nil)
  1327. if err != nil {
  1328. sendErrorResponse(w, err.Error())
  1329. //Restore the ownership if remove failed
  1330. userinfo.SetOwnerOfFile(rsrcFile)
  1331. return
  1332. }
  1333. //Set user to own the new file
  1334. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1335. } else if operation == "copy" {
  1336. //Copy file. See move example and change 'opr' to 'copy'
  1337. if !fileExists(rsrcFile) {
  1338. sendErrorResponse(w, "Source file not exists")
  1339. return
  1340. }
  1341. //Check if the desintation is read only.
  1342. if !userinfo.CanWrite(vdestFile) {
  1343. sendErrorResponse(w, "Access Denied.")
  1344. return
  1345. }
  1346. if !fileExists(rdestFile) {
  1347. if fileExists(filepath.Dir(rdestFile)) {
  1348. //User pass in the whole path for the folder. Report error usecase.
  1349. sendErrorResponse(w, "Dest location should be an existing folder instead of the full path of the copied file.")
  1350. return
  1351. }
  1352. sendErrorResponse(w, "Dest folder not found")
  1353. return
  1354. }
  1355. existsOpr, _ := mv(r, "existsresp", true)
  1356. //Check if the user have space for the extra file
  1357. if !userinfo.StorageQuota.HaveSpace(fs.GetFileSize(rdestFile)) {
  1358. sendErrorResponse(w, "Storage Quota Full")
  1359. return
  1360. }
  1361. err = fs.FileCopy(rsrcFile, rdestFile, existsOpr, nil)
  1362. if err != nil {
  1363. sendErrorResponse(w, err.Error())
  1364. return
  1365. }
  1366. //Set user to own this file
  1367. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1368. } else if operation == "delete" {
  1369. //Delete the file permanently
  1370. if !fileExists(rsrcFile) {
  1371. //Check if it is a non escapted file instead
  1372. sendErrorResponse(w, "Source file not exists")
  1373. return
  1374. }
  1375. //Check if the desintation is read only.
  1376. /*
  1377. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1378. if accmode == "readonly" {
  1379. sendErrorResponse(w, "This directory is Read Only.")
  1380. return
  1381. } else if accmode == "denied" {
  1382. sendErrorResponse(w, "Access Denied")
  1383. return
  1384. }
  1385. */
  1386. if !userinfo.CanWrite(vsrcFile) {
  1387. sendErrorResponse(w, "Access Denied.")
  1388. return
  1389. }
  1390. //Check if the user own this file
  1391. isOwner := userinfo.IsOwnerOfFile(rsrcFile)
  1392. if isOwner {
  1393. //This user own this system. Remove this file from his quota
  1394. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1395. }
  1396. //Check if this file has any cached files. If yes, remove it
  1397. if fileExists(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg") {
  1398. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg")
  1399. }
  1400. //Clear the cache folder if there is no files inside
  1401. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1402. if len(fc) == 0 {
  1403. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1404. }
  1405. os.RemoveAll(rsrcFile)
  1406. } else if operation == "recycle" {
  1407. //Put it into a subfolder named trash and allow it to to be removed later
  1408. if !fileExists(rsrcFile) {
  1409. //Check if it is a non escapted file instead
  1410. sendErrorResponse(w, "Source file not exists")
  1411. return
  1412. }
  1413. //Check if the upload target is read only.
  1414. //Updates 20 Jan 2021: Replace with CanWrite handler
  1415. /*
  1416. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1417. if accmode == "readonly" {
  1418. sendErrorResponse(w, "This directory is Read Only.")
  1419. return
  1420. } else if accmode == "denied" {
  1421. sendErrorResponse(w, "Access Denied")
  1422. return
  1423. }*/
  1424. if !userinfo.CanWrite(vsrcFile) {
  1425. sendErrorResponse(w, "Access Denied.")
  1426. return
  1427. }
  1428. //Check if this file has any cached files. If yes, remove it
  1429. if fileExists(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg") {
  1430. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg")
  1431. }
  1432. //Clear the cache folder if there is no files inside
  1433. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1434. if len(fc) == 0 {
  1435. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1436. }
  1437. //Create a trash directory for this folder
  1438. trashDir := filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.trash/"
  1439. os.MkdirAll(trashDir, 0755)
  1440. hidden.HideFile(trashDir)
  1441. os.Rename(rsrcFile, trashDir+filepath.Base(rsrcFile)+"."+Int64ToString(GetUnixTime()))
  1442. } else if operation == "unzip" {
  1443. //Unzip the file to destination
  1444. //Check if the user can write to the target dest file
  1445. if userinfo.CanWrite(string(vdestFile)) == false {
  1446. sendErrorResponse(w, "Access Denied.")
  1447. return
  1448. }
  1449. //Make the rdest directory if not exists
  1450. if !fileExists(rdestFile) {
  1451. err = os.MkdirAll(rdestFile, 0755)
  1452. if err != nil {
  1453. sendErrorResponse(w, err.Error())
  1454. return
  1455. }
  1456. }
  1457. //OK! Unzip to destination
  1458. err := fs.Unzip(rsrcFile, rdestFile)
  1459. if err != nil {
  1460. sendErrorResponse(w, err.Error())
  1461. return
  1462. }
  1463. } else {
  1464. sendErrorResponse(w, "Unknown file opeartion given.")
  1465. return
  1466. }
  1467. }
  1468. }
  1469. sendJSONResponse(w, "\"OK\"")
  1470. return
  1471. }
  1472. //Allow systems to store key value pairs in the database as preferences.
  1473. func system_fs_handleUserPreference(w http.ResponseWriter, r *http.Request) {
  1474. username, err := authAgent.GetUserName(w, r)
  1475. if err != nil {
  1476. sendErrorResponse(w, "User not logged in")
  1477. return
  1478. }
  1479. key, _ := mv(r, "key", false)
  1480. value, _ := mv(r, "value", false)
  1481. remove, _ := mv(r, "remove", false)
  1482. if key != "" && value == "" && remove == "" {
  1483. //Get mode. Read the prefernece with given key
  1484. result := ""
  1485. err := sysdb.Read("fs", "pref/"+key+"/"+username, &result)
  1486. if err != nil {
  1487. sendJSONResponse(w, "{\"error\":\"Key not found.\"}")
  1488. return
  1489. }
  1490. sendTextResponse(w, result)
  1491. } else if key != "" && value == "" && remove == "true" {
  1492. //Remove mode. Delete this key from sysdb
  1493. err := sysdb.Delete("fs", "pref/"+key+"/"+username)
  1494. if err != nil {
  1495. sendErrorResponse(w, err.Error())
  1496. }
  1497. sendOK(w)
  1498. } else if key != "" && value != "" {
  1499. //Set mode. Set the preference with given key
  1500. if len(value) > 1024 {
  1501. //Size too big. Reject storage
  1502. sendErrorResponse(w, "Preference value too long. Preference value can only store maximum 1024 characters.")
  1503. return
  1504. }
  1505. sysdb.Write("fs", "pref/"+key+"/"+username, value)
  1506. sendOK(w)
  1507. }
  1508. }
  1509. func system_fs_removeUserPreferences(username string) {
  1510. entries, err := sysdb.ListTable("fs")
  1511. if err != nil {
  1512. return
  1513. }
  1514. for _, keypairs := range entries {
  1515. if strings.Contains(string(keypairs[0]), "pref/") && strings.Contains(string(keypairs[0]), "/"+username) {
  1516. //Remove this preference
  1517. sysdb.Delete("fs", string(keypairs[0]))
  1518. }
  1519. }
  1520. }
  1521. func system_fs_listDrives(w http.ResponseWriter, r *http.Request) {
  1522. if authAgent.CheckAuth(r) == false {
  1523. sendErrorResponse(w, "User not logged in")
  1524. return
  1525. }
  1526. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1527. type driveInfo struct {
  1528. Drivepath string
  1529. DriveFreeSpace uint64
  1530. DriveTotalSpace uint64
  1531. DriveAvailSpace uint64
  1532. }
  1533. var drives []driveInfo
  1534. if runtime.GOOS == "windows" {
  1535. //Under windows
  1536. for _, drive := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
  1537. f, err := os.Open(string(drive) + ":\\")
  1538. if err == nil {
  1539. thisdrive := new(driveInfo)
  1540. thisdrive.Drivepath = string(drive) + ":\\"
  1541. free, total, avail := storage.GetDriveCapacity(string(drive) + ":\\")
  1542. thisdrive.DriveFreeSpace = free
  1543. thisdrive.DriveTotalSpace = total
  1544. thisdrive.DriveAvailSpace = avail
  1545. drives = append(drives, *thisdrive)
  1546. f.Close()
  1547. }
  1548. }
  1549. } else {
  1550. //Under linux environment
  1551. //Append all the virtual directories root as root instead
  1552. storageDevices := []string{}
  1553. for _, fshandler := range userinfo.GetAllFileSystemHandler() {
  1554. storageDevices = append(storageDevices, fshandler.Path)
  1555. }
  1556. //List all storage information of each devices
  1557. for _, dev := range storageDevices {
  1558. thisdrive := new(driveInfo)
  1559. thisdrive.Drivepath = filepath.Base(dev)
  1560. free, total, avail := storage.GetDriveCapacity(string(dev))
  1561. thisdrive.DriveFreeSpace = free
  1562. thisdrive.DriveTotalSpace = total
  1563. thisdrive.DriveAvailSpace = avail
  1564. drives = append(drives, *thisdrive)
  1565. }
  1566. }
  1567. jsonString, _ := json.Marshal(drives)
  1568. sendJSONResponse(w, string(jsonString))
  1569. }
  1570. func system_fs_listRoot(w http.ResponseWriter, r *http.Request) {
  1571. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1572. if err != nil {
  1573. sendErrorResponse(w, err.Error())
  1574. return
  1575. }
  1576. username := userinfo.Username
  1577. userRoot, _ := mv(r, "user", false)
  1578. if userRoot == "true" {
  1579. type fileObject struct {
  1580. Filename string
  1581. Filepath string
  1582. IsDir bool
  1583. }
  1584. //List the root media folders under user:/
  1585. filesInUserRoot := []fileObject{}
  1586. filesInRoot, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(*root_directory)) + "/users/" + username + "/*")
  1587. for _, file := range filesInRoot {
  1588. thisFile := new(fileObject)
  1589. thisFile.Filename = filepath.Base(file)
  1590. thisFile.Filepath, _ = userinfo.RealPathToVirtualPath(file)
  1591. thisFile.IsDir = IsDir(file)
  1592. filesInUserRoot = append(filesInUserRoot, *thisFile)
  1593. }
  1594. jsonString, _ := json.Marshal(filesInUserRoot)
  1595. sendJSONResponse(w, string(jsonString))
  1596. } else {
  1597. type rootObject struct {
  1598. rootID string //The vroot id
  1599. RootName string //The name of this vroot
  1600. RootPath string //The path of this vroot
  1601. RootBackups bool //If there are backup for this vroot
  1602. }
  1603. roots := []*rootObject{}
  1604. backupRoots := []string{}
  1605. for _, store := range userinfo.GetAllFileSystemHandler() {
  1606. if store.Hierarchy == "user" || store.Hierarchy == "public" {
  1607. //Normal drives
  1608. var thisDevice = new(rootObject)
  1609. thisDevice.RootName = store.Name
  1610. thisDevice.RootPath = store.UUID + ":/"
  1611. thisDevice.rootID = store.UUID
  1612. roots = append(roots, thisDevice)
  1613. } else if store.Hierarchy == "backup" {
  1614. //Backup drive.
  1615. backupRoots = append(backupRoots, store.HierarchyConfig.(hybridBackup.BackupTask).ParentUID)
  1616. }
  1617. }
  1618. //Update root configs for backup roots
  1619. for _, backupRoot := range backupRoots {
  1620. //For this backup root, check if the parent root mounted
  1621. for _, root := range roots {
  1622. if root.rootID == backupRoot {
  1623. //Parent root mounted. Label the parent root as "have backup"
  1624. root.RootBackups = true
  1625. }
  1626. }
  1627. }
  1628. jsonString, _ := json.Marshal(roots)
  1629. sendJSONResponse(w, string(jsonString))
  1630. }
  1631. }
  1632. /*
  1633. Special Glob for handling path with [ or ] inside.
  1634. You can also pass in normal path for globing if you are not sure.
  1635. */
  1636. func system_fs_specialGlob(path string) ([]string, error) {
  1637. //Quick fix for foldername containing -] issue
  1638. path = strings.ReplaceAll(path, "[", "[[]")
  1639. files, err := filepath.Glob(path)
  1640. if err != nil {
  1641. return []string{}, err
  1642. }
  1643. if strings.Contains(path, "[") == true || strings.Contains(path, "]") == true {
  1644. if len(files) == 0 {
  1645. //Handle reverse check. Replace all [ and ] with *
  1646. newSearchPath := strings.ReplaceAll(path, "[", "?")
  1647. newSearchPath = strings.ReplaceAll(newSearchPath, "]", "?")
  1648. //Scan with all the similar structure except [ and ]
  1649. tmpFilelist, _ := filepath.Glob(newSearchPath)
  1650. for _, file := range tmpFilelist {
  1651. file = filepath.ToSlash(file)
  1652. if strings.Contains(file, filepath.ToSlash(filepath.Dir(path))) {
  1653. files = append(files, file)
  1654. }
  1655. }
  1656. }
  1657. }
  1658. //Convert all filepaths to slash
  1659. for i := 0; i < len(files); i++ {
  1660. files[i] = filepath.ToSlash(files[i])
  1661. }
  1662. return files, nil
  1663. }
  1664. func system_fs_specialURIDecode(inputPath string) string {
  1665. inputPath = strings.ReplaceAll(inputPath, "+", "{{plus_sign}}")
  1666. inputPath, _ = url.QueryUnescape(inputPath)
  1667. inputPath = strings.ReplaceAll(inputPath, "{{plus_sign}}", "+")
  1668. return inputPath
  1669. }
  1670. func system_fs_specialURIEncode(inputPath string) string {
  1671. inputPath = strings.ReplaceAll(inputPath, " ", "{{space_sign}}")
  1672. inputPath, _ = url.QueryUnescape(inputPath)
  1673. inputPath = strings.ReplaceAll(inputPath, "{{space_sign}}", "%20")
  1674. return inputPath
  1675. }
  1676. func system_fs_matchFileExt(inputFilename string, extArray []string) bool {
  1677. inputExt := filepath.Ext(inputFilename)
  1678. if stringInSlice(inputExt, extArray) {
  1679. return true
  1680. }
  1681. return false
  1682. }
  1683. //Handle file properties request
  1684. func system_fs_getFileProperties(w http.ResponseWriter, r *http.Request) {
  1685. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1686. if err != nil {
  1687. sendErrorResponse(w, err.Error())
  1688. return
  1689. }
  1690. vpath, err := mv(r, "path", true)
  1691. if err != nil {
  1692. sendErrorResponse(w, "path not defined")
  1693. return
  1694. }
  1695. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  1696. if err != nil {
  1697. sendErrorResponse(w, err.Error())
  1698. return
  1699. }
  1700. fileStat, err := os.Stat(rpath)
  1701. if err != nil {
  1702. sendErrorResponse(w, err.Error())
  1703. return
  1704. }
  1705. type fileProperties struct {
  1706. VirtualPath string
  1707. StoragePath string
  1708. Basename string
  1709. VirtualDirname string
  1710. StorageDirname string
  1711. Ext string
  1712. MimeType string
  1713. Filesize int64
  1714. Permission string
  1715. LastModTime string
  1716. LastModUnix int64
  1717. IsDirectory bool
  1718. Owner string
  1719. }
  1720. mime := "text/directory"
  1721. if !fileStat.IsDir() {
  1722. m, _, err := fs.GetMime(rpath)
  1723. if err != nil {
  1724. mime = ""
  1725. }
  1726. mime = m
  1727. }
  1728. filesize := fileStat.Size()
  1729. //Get file overall size if this is folder
  1730. if fileStat.IsDir() {
  1731. var size int64
  1732. filepath.Walk(rpath, func(_ string, info os.FileInfo, err error) error {
  1733. if err != nil {
  1734. return err
  1735. }
  1736. if !info.IsDir() {
  1737. size += info.Size()
  1738. }
  1739. return err
  1740. })
  1741. filesize = size
  1742. }
  1743. //Get file owner
  1744. owner := userinfo.GetFileOwner(rpath)
  1745. if owner == "" {
  1746. owner = "Unknown"
  1747. }
  1748. result := fileProperties{
  1749. VirtualPath: vpath,
  1750. StoragePath: filepath.Clean(rpath),
  1751. Basename: filepath.Base(rpath),
  1752. VirtualDirname: filepath.ToSlash(filepath.Dir(vpath)),
  1753. StorageDirname: filepath.ToSlash(filepath.Dir(rpath)),
  1754. Ext: filepath.Ext(rpath),
  1755. MimeType: mime,
  1756. Filesize: filesize,
  1757. Permission: fileStat.Mode().Perm().String(),
  1758. LastModTime: timeToString(fileStat.ModTime()),
  1759. LastModUnix: fileStat.ModTime().Unix(),
  1760. IsDirectory: fileStat.IsDir(),
  1761. Owner: owner,
  1762. }
  1763. jsonString, _ := json.Marshal(result)
  1764. sendJSONResponse(w, string(jsonString))
  1765. }
  1766. /*
  1767. List directory in the given path
  1768. Usage: Pass in dir like the following examples:
  1769. AOR:/Desktop <= Open /user/{username}/Desktop
  1770. S1:/ <= Open {uuid=S1}/
  1771. */
  1772. func system_fs_handleList(w http.ResponseWriter, r *http.Request) {
  1773. currentDir, _ := mv(r, "dir", true)
  1774. //Commented this line to handle dirname that contains "+" sign
  1775. //currentDir, _ = url.QueryUnescape(currentDir)
  1776. sortMode, _ := mv(r, "sort", true)
  1777. showHidden, _ := mv(r, "showHidden", true)
  1778. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1779. if err != nil {
  1780. //user not logged in. Redirect to login page.
  1781. sendErrorResponse(w, "User not logged in")
  1782. return
  1783. }
  1784. if currentDir == "" {
  1785. sendErrorResponse(w, "Invalid dir given.")
  1786. return
  1787. }
  1788. //Pad a slash at the end of currentDir if not exists
  1789. if currentDir[len(currentDir)-1:] != "/" {
  1790. currentDir = currentDir + "/"
  1791. }
  1792. //Convert the virutal path to realpath
  1793. realpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1794. if err != nil {
  1795. sendErrorResponse(w, "Error. Unable to parse path. "+err.Error())
  1796. return
  1797. }
  1798. if !fileExists(realpath) {
  1799. userRoot, _ := userinfo.VirtualPathToRealPath("user:/")
  1800. if filepath.Clean(realpath) == filepath.Clean(userRoot) {
  1801. //Initiate user folder (Initiaed in user object)
  1802. userinfo.GetHomeDirectory()
  1803. } else {
  1804. //Folder not exists
  1805. log.Println("[File Explorer] Requested path: ", realpath, " does not exists!")
  1806. sendJSONResponse(w, "{\"error\":\"Folder not exists\"}")
  1807. return
  1808. }
  1809. }
  1810. if sortMode == "" {
  1811. sortMode = "default"
  1812. }
  1813. //Check for really special exception in where the path contains [ or ] which cannot be handled via Golang Glob function
  1814. files, _ := system_fs_specialGlob(filepath.Clean(realpath) + "/*")
  1815. var parsedFilelist []fs.FileData
  1816. var shortCutInfo *shortcut.ShortcutData = nil
  1817. for _, v := range files {
  1818. //Check if it is hidden file
  1819. isHidden, _ := hidden.IsHidden(v, false)
  1820. if showHidden != "true" && isHidden {
  1821. //Skipping hidden files
  1822. continue
  1823. }
  1824. //Check if it is shortcut file. If yes, render a shortcut data struct
  1825. if filepath.Ext(v) == ".shortcut" {
  1826. //This is a shortcut file
  1827. shorcutData, err := shortcut.ReadShortcut(v)
  1828. if err == nil {
  1829. shortCutInfo = shorcutData
  1830. }
  1831. }
  1832. rawsize := fs.GetFileSize(v)
  1833. modtime, _ := fs.GetModTime(v)
  1834. thisFile := fs.FileData{
  1835. Filename: filepath.Base(v),
  1836. Filepath: currentDir + filepath.Base(v),
  1837. Realpath: v,
  1838. IsDir: IsDir(v),
  1839. Filesize: rawsize,
  1840. Displaysize: fs.GetFileDisplaySize(rawsize, 2),
  1841. ModTime: modtime,
  1842. IsShared: shareManager.FileIsShared(v),
  1843. Shortcut: shortCutInfo,
  1844. }
  1845. parsedFilelist = append(parsedFilelist, thisFile)
  1846. }
  1847. //Sort the filelist
  1848. if sortMode == "default" {
  1849. //Sort by name, convert filename to window sorting methods
  1850. sort.Slice(parsedFilelist, func(i, j int) bool {
  1851. return strings.ToLower(parsedFilelist[i].Filename) < strings.ToLower(parsedFilelist[j].Filename)
  1852. })
  1853. } else if sortMode == "reverse" {
  1854. //Sort by reverse name
  1855. sort.Slice(parsedFilelist, func(i, j int) bool {
  1856. return strings.ToLower(parsedFilelist[i].Filename) > strings.ToLower(parsedFilelist[j].Filename)
  1857. })
  1858. } else if sortMode == "smallToLarge" {
  1859. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize < parsedFilelist[j].Filesize })
  1860. } else if sortMode == "largeToSmall" {
  1861. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize > parsedFilelist[j].Filesize })
  1862. } else if sortMode == "mostRecent" {
  1863. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime > parsedFilelist[j].ModTime })
  1864. } else if sortMode == "leastRecent" {
  1865. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime < parsedFilelist[j].ModTime })
  1866. }
  1867. jsonString, _ := json.Marshal(parsedFilelist)
  1868. sendJSONResponse(w, string(jsonString))
  1869. }
  1870. //Handle getting a hash from a given contents in the given path
  1871. func system_fs_handleDirHash(w http.ResponseWriter, r *http.Request) {
  1872. currentDir, err := mv(r, "dir", true)
  1873. if err != nil {
  1874. sendErrorResponse(w, "Invalid dir given")
  1875. return
  1876. }
  1877. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1878. if err != nil {
  1879. sendErrorResponse(w, "User not logged in")
  1880. return
  1881. }
  1882. rpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1883. if err != nil {
  1884. sendErrorResponse(w, "Invalid dir given")
  1885. return
  1886. }
  1887. //Get a list of files in this directory
  1888. currentDir = filepath.ToSlash(filepath.Clean(rpath)) + "/"
  1889. filesInDir, err := system_fs_specialGlob(currentDir + "*")
  1890. if err != nil {
  1891. sendErrorResponse(w, err.Error())
  1892. return
  1893. }
  1894. filenames := []string{}
  1895. for _, file := range filesInDir {
  1896. if len(filepath.Base(file)) > 0 && string([]rune(filepath.Base(file))[0]) != "." {
  1897. //Ignore hidden files
  1898. filenames = append(filenames, filepath.Base(file))
  1899. }
  1900. }
  1901. sort.Strings(filenames)
  1902. //Build a hash base on the filelist
  1903. h := sha256.New()
  1904. h.Write([]byte(strings.Join(filenames, ",")))
  1905. sendTextResponse(w, hex.EncodeToString((h.Sum(nil))))
  1906. }
  1907. /*
  1908. File zipping and unzipping functions
  1909. */
  1910. //Handle all zip related API
  1911. func system_fs_zipHandler(w http.ResponseWriter, r *http.Request) {
  1912. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1913. if err != nil {
  1914. sendErrorResponse(w, err.Error())
  1915. return
  1916. }
  1917. opr, err := mv(r, "opr", true)
  1918. if err != nil {
  1919. sendErrorResponse(w, "Invalid opr or opr not defined")
  1920. return
  1921. }
  1922. vsrc, _ := mv(r, "src", true)
  1923. if vsrc == "" {
  1924. sendErrorResponse(w, "Invalid src paramter")
  1925. return
  1926. }
  1927. vdest, _ := mv(r, "dest", true)
  1928. rdest := ""
  1929. //Convert source path from JSON string to object
  1930. virtualSourcePaths := []string{}
  1931. err = json.Unmarshal([]byte(vsrc), &virtualSourcePaths)
  1932. if err != nil {
  1933. sendErrorResponse(w, err.Error())
  1934. return
  1935. }
  1936. //Check each of the path
  1937. realSourcePaths := []string{}
  1938. for _, vpath := range virtualSourcePaths {
  1939. thisrpath, err := userinfo.VirtualPathToRealPath(vpath)
  1940. if err != nil || !fileExists(thisrpath) {
  1941. sendErrorResponse(w, "File not exists: "+vpath)
  1942. return
  1943. }
  1944. realSourcePaths = append(realSourcePaths, thisrpath)
  1945. }
  1946. ///Convert dest to real if given
  1947. if vdest != "" {
  1948. realdest, _ := userinfo.VirtualPathToRealPath(vdest)
  1949. rdest = realdest
  1950. }
  1951. //This function will be deprecate soon in ArozOS 1.120
  1952. log.Println("*DEPRECATE* zipHandler will be deprecating soon! Please use fileOpr endpoint")
  1953. if opr == "zip" {
  1954. //Check if destination location exists
  1955. if rdest == "" || !fileExists(filepath.Dir(rdest)) {
  1956. sendErrorResponse(w, "Invalid dest location")
  1957. return
  1958. }
  1959. //OK. Create the zip at the desired location
  1960. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  1961. if err != nil {
  1962. sendErrorResponse(w, err.Error())
  1963. return
  1964. }
  1965. sendOK(w)
  1966. } else if opr == "tmpzip" {
  1967. //Zip to tmp folder
  1968. userTmpFolder, _ := userinfo.VirtualPathToRealPath("tmp:/")
  1969. filename := Int64ToString(GetUnixTime()) + ".zip"
  1970. rdest := filepath.ToSlash(filepath.Clean(userTmpFolder)) + "/" + filename
  1971. log.Println(realSourcePaths, rdest)
  1972. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  1973. if err != nil {
  1974. sendErrorResponse(w, err.Error())
  1975. return
  1976. }
  1977. //Send the tmp filename to the user
  1978. sendTextResponse(w, "tmp:/"+filename)
  1979. } else if opr == "inspect" {
  1980. } else if opr == "unzip" {
  1981. }
  1982. }
  1983. //Translate path from and to virtual and realpath
  1984. func system_fs_handlePathTranslate(w http.ResponseWriter, r *http.Request) {
  1985. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1986. if err != nil {
  1987. sendErrorResponse(w, err.Error())
  1988. return
  1989. }
  1990. path, err := mv(r, "path", false)
  1991. if err != nil {
  1992. sendErrorResponse(w, "Invalid path given")
  1993. return
  1994. }
  1995. rpath, err := userinfo.VirtualPathToRealPath(path)
  1996. if err != nil {
  1997. //Try to convert it to virtualPath
  1998. vpath, err := userinfo.RealPathToVirtualPath(path)
  1999. if err != nil {
  2000. sendErrorResponse(w, "Unknown path given")
  2001. } else {
  2002. jsonstring, _ := json.Marshal(vpath)
  2003. sendJSONResponse(w, string(jsonstring))
  2004. }
  2005. } else {
  2006. abrpath, _ := filepath.Abs(rpath)
  2007. jsonstring, _ := json.Marshal([]string{rpath, filepath.ToSlash(abrpath)})
  2008. sendJSONResponse(w, string(jsonstring))
  2009. }
  2010. }
  2011. //Handle cache rendering with websocket pipeline
  2012. func system_fs_handleCacheRender(w http.ResponseWriter, r *http.Request) {
  2013. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2014. vpath, err := mv(r, "folder", false)
  2015. if err != nil {
  2016. sendErrorResponse(w, "Invalid folder paramter")
  2017. return
  2018. }
  2019. //Convert vpath to realpath
  2020. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  2021. if err != nil {
  2022. sendErrorResponse(w, err.Error())
  2023. return
  2024. }
  2025. //Perform cache rendering
  2026. thumbRenderHandler.HandleLoadCache(w, r, rpath)
  2027. }
  2028. //Handle file thumbnail caching
  2029. func system_fs_handleFolderCache(w http.ResponseWriter, r *http.Request) {
  2030. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2031. vfolderpath, err := mv(r, "folder", false)
  2032. if err != nil {
  2033. sendErrorResponse(w, "folder not defined")
  2034. return
  2035. }
  2036. rpath, err := userinfo.VirtualPathToRealPath(vfolderpath)
  2037. if err != nil {
  2038. sendErrorResponse(w, err.Error())
  2039. return
  2040. }
  2041. thumbRenderHandler.BuildCacheForFolder(rpath)
  2042. sendOK(w)
  2043. }
  2044. //Handle setting and loading of file permission on Linux
  2045. func system_fs_handleFilePermission(w http.ResponseWriter, r *http.Request) {
  2046. file, err := mv(r, "file", true)
  2047. if err != nil {
  2048. sendErrorResponse(w, "Invalid file")
  2049. return
  2050. }
  2051. //Translate the file to real path
  2052. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2053. if err != nil {
  2054. sendErrorResponse(w, "User not logged in")
  2055. return
  2056. }
  2057. rpath, err := userinfo.VirtualPathToRealPath(file)
  2058. if err != nil {
  2059. sendErrorResponse(w, err.Error())
  2060. return
  2061. }
  2062. newMode, _ := mv(r, "mode", true)
  2063. if newMode == "" {
  2064. //Read the file mode
  2065. //Check if the file exists
  2066. if !fileExists(rpath) {
  2067. sendErrorResponse(w, "File not exists!")
  2068. return
  2069. }
  2070. //Read the file permission
  2071. filePermission, err := fsp.GetFilePermissions(rpath)
  2072. if err != nil {
  2073. sendErrorResponse(w, err.Error())
  2074. return
  2075. }
  2076. //Send the file permission to client
  2077. js, _ := json.Marshal(filePermission)
  2078. sendJSONResponse(w, string(js))
  2079. } else {
  2080. //Set the file mode
  2081. //Check if the file exists
  2082. if !fileExists(rpath) {
  2083. sendErrorResponse(w, "File not exists!")
  2084. return
  2085. }
  2086. //Check if windows. If yes, ignore this request
  2087. if runtime.GOOS == "windows" {
  2088. sendErrorResponse(w, "Windows host not supported")
  2089. return
  2090. }
  2091. //Check if this user has permission to change the file permission
  2092. //Aka user must be 1. This is his own folder or 2. Admin
  2093. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(file)
  2094. if fsh.Hierarchy == "user" {
  2095. //Always ok as this is owned by the user
  2096. } else if fsh.Hierarchy == "public" {
  2097. //Require admin
  2098. if userinfo.IsAdmin() == false {
  2099. sendErrorResponse(w, "Permission Denied")
  2100. return
  2101. }
  2102. } else {
  2103. //Not implemeneted. Require admin
  2104. if userinfo.IsAdmin() == false {
  2105. sendErrorResponse(w, "Permission Denied")
  2106. return
  2107. }
  2108. }
  2109. //Be noted that if the system is not running in sudo mode,
  2110. //File permission change might not works.
  2111. err := fsp.SetFilePermisson(rpath, newMode)
  2112. if err != nil {
  2113. sendErrorResponse(w, err.Error())
  2114. return
  2115. } else {
  2116. sendOK(w)
  2117. }
  2118. }
  2119. }
  2120. //Check if the given filepath is and must inside the given directory path.
  2121. //You can pass both as relative
  2122. func system_fs_checkFileInDirectory(filesourcepath string, directory string) bool {
  2123. filepathAbs, err := filepath.Abs(filesourcepath)
  2124. if err != nil {
  2125. return false
  2126. }
  2127. directoryAbs, err := filepath.Abs(directory)
  2128. if err != nil {
  2129. return false
  2130. }
  2131. //Check if the filepathabs contain directoryAbs
  2132. if strings.Contains(filepathAbs, directoryAbs) {
  2133. return true
  2134. } else {
  2135. return false
  2136. }
  2137. }
  2138. //Clear the old files inside the tmp file
  2139. func system_fs_clearOldTmpFiles() {
  2140. filesToBeDelete := []string{}
  2141. tmpAbs, _ := filepath.Abs(*tmp_directory)
  2142. filepath.Walk(*tmp_directory, func(path string, info os.FileInfo, err error) error {
  2143. if filepath.Base(path) != "aofs.db" && filepath.Base(path) != "aofs.db.lock" {
  2144. //Check if root folders. Do not delete root folders
  2145. parentAbs, _ := filepath.Abs(filepath.Dir(path))
  2146. if tmpAbs == parentAbs {
  2147. //Root folder. Do not remove
  2148. return nil
  2149. }
  2150. //Get its modification time
  2151. modTime, err := fs.GetModTime(path)
  2152. if err != nil {
  2153. return nil
  2154. }
  2155. //Check if mod time is more than 24 hours ago
  2156. if time.Now().Unix()-modTime > int64(*maxTempFileKeepTime) {
  2157. //Delete OK
  2158. filesToBeDelete = append(filesToBeDelete, path)
  2159. }
  2160. }
  2161. return nil
  2162. })
  2163. //Remove all files from the delete list
  2164. for _, fileToBeDelete := range filesToBeDelete {
  2165. os.RemoveAll(fileToBeDelete)
  2166. }
  2167. }