file_system.go 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530
  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 = []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. //Validate the token
  815. tokenValid := CSRFTokenManager.HandleTokenValidation(w, r)
  816. if !tokenValid {
  817. http.Error(w, "Invalid CSRF token", 401)
  818. return
  819. }
  820. fileType, _ := mv(r, "type", true) //File creation type, {file, folder}
  821. vsrc, _ := mv(r, "src", true) //Virtual file source folder, do not include filename
  822. filename, _ := mv(r, "filename", true) //Filename for the new file
  823. if fileType == "" && filename == "" {
  824. //List all the supported new filetype
  825. if !fileExists("system/newitem/") {
  826. os.MkdirAll("system/newitem/", 0755)
  827. }
  828. type newItemObject struct {
  829. Desc string
  830. Ext string
  831. }
  832. var newItemList []newItemObject
  833. newItemTemplate, _ := filepath.Glob("system/newitem/*")
  834. for _, file := range newItemTemplate {
  835. thisItem := new(newItemObject)
  836. thisItem.Desc = strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
  837. thisItem.Ext = filepath.Ext(file)[1:]
  838. newItemList = append(newItemList, *thisItem)
  839. }
  840. jsonString, err := json.Marshal(newItemList)
  841. if err != nil {
  842. log.Println("*File System* Unable to parse JSON string for new item list!")
  843. sendErrorResponse(w, "Unable to parse new item list. See server log for more information.")
  844. return
  845. }
  846. sendJSONResponse(w, string(jsonString))
  847. return
  848. } else if fileType != "" && filename != "" {
  849. if vsrc == "" {
  850. sendErrorResponse(w, "Missing paramter: 'src'")
  851. return
  852. }
  853. //Translate the path to realpath
  854. rpath, err := userinfo.VirtualPathToRealPath(vsrc)
  855. if err != nil {
  856. sendErrorResponse(w, "Invalid path given.")
  857. return
  858. }
  859. //Check if directory is readonly
  860. accmode := userinfo.GetPathAccessPermission(vsrc)
  861. if accmode == "readonly" {
  862. sendErrorResponse(w, "This directory is Read Only.")
  863. return
  864. } else if accmode == "denied" {
  865. sendErrorResponse(w, "Access Denied")
  866. return
  867. }
  868. //Check if the file already exists. If yes, fix its filename.
  869. newfilePath := filepath.ToSlash(filepath.Join(rpath, filename))
  870. if fileType == "file" {
  871. for fileExists(newfilePath) {
  872. sendErrorResponse(w, "Given filename already exists.")
  873. return
  874. }
  875. ext := filepath.Ext(filename)
  876. if ext == "" {
  877. //This is a file with no extension.
  878. f, err := os.Create(newfilePath)
  879. if err != nil {
  880. log.Println("*File System* " + err.Error())
  881. sendErrorResponse(w, err.Error())
  882. return
  883. }
  884. f.Close()
  885. } else {
  886. templateFile, _ := filepath.Glob("system/newitem/*" + ext)
  887. if len(templateFile) == 0 {
  888. //This file extension is not in template
  889. f, err := os.Create(newfilePath)
  890. if err != nil {
  891. log.Println("*File System* " + err.Error())
  892. sendErrorResponse(w, err.Error())
  893. return
  894. }
  895. f.Close()
  896. } else {
  897. //Copy file from templateFile[0] to current dir with the given name
  898. input, _ := ioutil.ReadFile(templateFile[0])
  899. err := ioutil.WriteFile(newfilePath, input, 0755)
  900. if err != nil {
  901. log.Println("*File System* " + err.Error())
  902. sendErrorResponse(w, err.Error())
  903. return
  904. }
  905. }
  906. }
  907. } else if fileType == "folder" {
  908. if fileExists(newfilePath) {
  909. sendErrorResponse(w, "Given folder already exists.")
  910. return
  911. }
  912. //Create the folder at target location
  913. err := os.Mkdir(newfilePath, 0755)
  914. if err != nil {
  915. sendErrorResponse(w, err.Error())
  916. return
  917. }
  918. }
  919. sendJSONResponse(w, "\"OK\"")
  920. } else {
  921. sendErrorResponse(w, "Missing paramter(s).")
  922. return
  923. }
  924. }
  925. /*
  926. Handle file operations via WebSocket
  927. This handler only handle zip, unzip, copy and move. Not other operations.
  928. For other operations, please use the legacy handleOpr endpoint
  929. */
  930. func system_fs_handleWebSocketOpr(w http.ResponseWriter, r *http.Request) {
  931. //Get and check user permission
  932. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  933. if err != nil {
  934. sendErrorResponse(w, "User not logged in")
  935. return
  936. }
  937. operation, _ := mv(r, "opr", false) //Accept copy and move
  938. vsrcFiles, _ := mv(r, "src", false)
  939. vdestFile, _ := mv(r, "dest", false)
  940. existsOpr, _ := mv(r, "existsresp", false)
  941. if existsOpr == "" {
  942. existsOpr = "keep"
  943. }
  944. //Decode the source file list
  945. var sourceFiles []string
  946. tmp := []string{}
  947. decodedSourceFiles, _ := url.QueryUnescape(vsrcFiles)
  948. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  949. if err != nil {
  950. log.Println("Source file JSON parse error.", err.Error())
  951. sendErrorResponse(w, "Source file JSON parse error.")
  952. return
  953. }
  954. //Bugged char filtering
  955. for _, src := range sourceFiles {
  956. tmp = append(tmp, strings.ReplaceAll(src, "{{plug_sign}}", "+"))
  957. }
  958. sourceFiles = tmp
  959. vdestFile = strings.ReplaceAll(vdestFile, "{{plug_sign}}", "+")
  960. //Decode the target position
  961. escapedVdest, _ := url.QueryUnescape(vdestFile)
  962. vdestFile = escapedVdest
  963. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  964. //Permission checking
  965. if !userinfo.CanWrite(vdestFile) {
  966. log.Println(vdestFile)
  967. w.WriteHeader(http.StatusForbidden)
  968. w.Write([]byte("403 - Access Denied"))
  969. return
  970. }
  971. //Check if opr is suported
  972. if operation == "move" || operation == "copy" || operation == "zip" || operation == "unzip" {
  973. } else {
  974. log.Println("This file operation is not supported on WebSocket file operations endpoint. Please use the legacy endpoint instead. Received: ", operation)
  975. w.WriteHeader(http.StatusInternalServerError)
  976. w.Write([]byte("500 - Not supported operation"))
  977. return
  978. }
  979. //Upgrade to websocket
  980. var upgrader = websocket.Upgrader{}
  981. c, err := upgrader.Upgrade(w, r, nil)
  982. if err != nil {
  983. w.WriteHeader(http.StatusInternalServerError)
  984. w.Write([]byte("500 - " + err.Error()))
  985. log.Print("Websocket Upgrade Error:", err.Error())
  986. return
  987. }
  988. type ProgressUpdate struct {
  989. LatestFile string
  990. Progress int
  991. Error string
  992. }
  993. if operation == "zip" {
  994. //Zip files
  995. outputFilename := filepath.Join(rdestFile, filepath.Base(rdestFile)) + ".zip"
  996. if len(sourceFiles) == 1 {
  997. //Use the basename of the source file as zip file name
  998. outputFilename = filepath.Join(rdestFile, filepath.Base(sourceFiles[0])) + ".zip"
  999. }
  1000. //Translate source Files into real paths
  1001. realSourceFiles := []string{}
  1002. for _, vsrcs := range sourceFiles {
  1003. rsrc, err := userinfo.VirtualPathToRealPath(vsrcs)
  1004. if err != nil {
  1005. stopStatus := ProgressUpdate{
  1006. LatestFile: filepath.Base(rsrc),
  1007. Progress: -1,
  1008. Error: "File not exists",
  1009. }
  1010. js, _ := json.Marshal(stopStatus)
  1011. c.WriteMessage(1, js)
  1012. c.Close()
  1013. }
  1014. realSourceFiles = append(realSourceFiles, rsrc)
  1015. }
  1016. //Create the zip file
  1017. fs.ArozZipFileWithProgress(realSourceFiles, outputFilename, false, func(currentFilename string, _ int, _ int, progress float64) {
  1018. currentStatus := ProgressUpdate{
  1019. LatestFile: currentFilename,
  1020. Progress: int(math.Ceil(progress)),
  1021. Error: "",
  1022. }
  1023. js, _ := json.Marshal(currentStatus)
  1024. c.WriteMessage(1, js)
  1025. })
  1026. } else if operation == "unzip" {
  1027. //Check if the target destination exists and writable
  1028. if !userinfo.CanWrite(vdestFile) {
  1029. stopStatus := ProgressUpdate{
  1030. LatestFile: filepath.Base(vdestFile),
  1031. Progress: -1,
  1032. Error: "Access Denied: No Write Permission",
  1033. }
  1034. js, _ := json.Marshal(stopStatus)
  1035. c.WriteMessage(1, js)
  1036. c.Close()
  1037. }
  1038. //Create the destination folder
  1039. os.MkdirAll(rdestFile, 0755)
  1040. //Convert the src files into realpaths
  1041. realSourceFiles := []string{}
  1042. for _, vsrcs := range sourceFiles {
  1043. rsrc, err := userinfo.VirtualPathToRealPath(vsrcs)
  1044. if err != nil {
  1045. stopStatus := ProgressUpdate{
  1046. LatestFile: filepath.Base(rsrc),
  1047. Progress: -1,
  1048. Error: "File not exists",
  1049. }
  1050. js, _ := json.Marshal(stopStatus)
  1051. c.WriteMessage(1, js)
  1052. c.Close()
  1053. }
  1054. realSourceFiles = append(realSourceFiles, rsrc)
  1055. }
  1056. //Unzip the files
  1057. fs.ArozUnzipFileWithProgress(realSourceFiles, rdestFile, func(currentFile string, filecount int, totalfile int, progress float64) {
  1058. //Generate the status update struct
  1059. currentStatus := ProgressUpdate{
  1060. LatestFile: filepath.Base(currentFile),
  1061. Progress: int(math.Ceil(progress)),
  1062. Error: "",
  1063. }
  1064. js, _ := json.Marshal(currentStatus)
  1065. c.WriteMessage(1, js)
  1066. })
  1067. } else {
  1068. //Other operations that allow multiple source files to handle one by one
  1069. for i := 0; i < len(sourceFiles); i++ {
  1070. vsrcFile := sourceFiles[i]
  1071. rsrcFile, _ := userinfo.VirtualPathToRealPath(vsrcFile)
  1072. //c.WriteMessage(1, message)
  1073. if !fileExists(rsrcFile) {
  1074. //This source file not exists. Report Error and Stop
  1075. stopStatus := ProgressUpdate{
  1076. LatestFile: filepath.Base(rsrcFile),
  1077. Progress: -1,
  1078. Error: "File not exists",
  1079. }
  1080. js, _ := json.Marshal(stopStatus)
  1081. c.WriteMessage(1, js)
  1082. c.Close()
  1083. return
  1084. }
  1085. if operation == "move" {
  1086. err := fs.FileMove(rsrcFile, rdestFile, existsOpr, false, func(progress int, currentFile string) {
  1087. //Multply child progress to parent progress
  1088. blockRatio := float64(100) / float64(len(sourceFiles))
  1089. overallRatio := blockRatio*float64(i) + blockRatio*(float64(progress)/float64(100))
  1090. //Construct return struct
  1091. currentStatus := ProgressUpdate{
  1092. LatestFile: filepath.Base(currentFile),
  1093. Progress: int(overallRatio),
  1094. Error: "",
  1095. }
  1096. js, _ := json.Marshal(currentStatus)
  1097. c.WriteMessage(1, js)
  1098. })
  1099. //Handle move starting error
  1100. if err != nil {
  1101. stopStatus := ProgressUpdate{
  1102. LatestFile: filepath.Base(rsrcFile),
  1103. Progress: -1,
  1104. Error: err.Error(),
  1105. }
  1106. js, _ := json.Marshal(stopStatus)
  1107. c.WriteMessage(1, js)
  1108. c.Close()
  1109. return
  1110. }
  1111. } else if operation == "copy" {
  1112. err := fs.FileCopy(rsrcFile, rdestFile, existsOpr, func(progress int, currentFile string) {
  1113. //Multply child progress to parent progress
  1114. blockRatio := float64(100) / float64(len(sourceFiles))
  1115. overallRatio := blockRatio*float64(i) + blockRatio*(float64(progress)/float64(100))
  1116. //Construct return struct
  1117. currentStatus := ProgressUpdate{
  1118. LatestFile: filepath.Base(currentFile),
  1119. Progress: int(overallRatio),
  1120. Error: "",
  1121. }
  1122. js, _ := json.Marshal(currentStatus)
  1123. c.WriteMessage(1, js)
  1124. })
  1125. //Handle Copy starting error
  1126. if err != nil {
  1127. stopStatus := ProgressUpdate{
  1128. LatestFile: filepath.Base(rsrcFile),
  1129. Progress: -1,
  1130. Error: err.Error(),
  1131. }
  1132. js, _ := json.Marshal(stopStatus)
  1133. c.WriteMessage(1, js)
  1134. c.Close()
  1135. return
  1136. }
  1137. }
  1138. }
  1139. }
  1140. //Close WebSocket connection after finished
  1141. time.Sleep(1 * time.Second)
  1142. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  1143. c.Close()
  1144. }
  1145. /*
  1146. Handle file operations
  1147. Support {move, copy, delete, recycle, rename}
  1148. */
  1149. //Handle file operations.
  1150. func system_fs_handleOpr(w http.ResponseWriter, r *http.Request) {
  1151. //Check if user logged in
  1152. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1153. if err != nil {
  1154. sendErrorResponse(w, "User not logged in")
  1155. return
  1156. }
  1157. //Validate the token
  1158. tokenValid := CSRFTokenManager.HandleTokenValidation(w, r)
  1159. if !tokenValid {
  1160. http.Error(w, "Invalid CSRF token", 401)
  1161. return
  1162. }
  1163. operation, _ := mv(r, "opr", true)
  1164. vsrcFiles, _ := mv(r, "src", true)
  1165. vdestFile, _ := mv(r, "dest", true)
  1166. vnfilenames, _ := mv(r, "new", true) //Only use when rename or create new file / folder
  1167. //Check if operation valid.
  1168. if operation == "" {
  1169. //Undefined operations.
  1170. sendErrorResponse(w, "Undefined operations paramter: Missing 'opr' in request header.")
  1171. return
  1172. }
  1173. //As the user can pass in multiple source files at the same time, parse sourceFiles from json string
  1174. var sourceFiles []string
  1175. //This line is required in order to allow passing of special charaters
  1176. decodedSourceFiles := system_fs_specialURIDecode(vsrcFiles)
  1177. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  1178. if err != nil {
  1179. sendErrorResponse(w, "Source file JSON parse error.")
  1180. return
  1181. }
  1182. //Check if new filenames are also valid. If yes, translate it into string array
  1183. var newFilenames []string
  1184. if vnfilenames != "" {
  1185. vnfilenames, _ := url.QueryUnescape(vnfilenames)
  1186. err = json.Unmarshal([]byte(vnfilenames), &newFilenames)
  1187. if err != nil {
  1188. sendErrorResponse(w, "Unable to parse JSON for new filenames")
  1189. return
  1190. }
  1191. }
  1192. if operation == "zip" {
  1193. //Zip operation. Parse the real filepath list
  1194. rsrcFiles := []string{}
  1195. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1196. for _, vsrcFile := range sourceFiles {
  1197. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1198. if fileExists(rsrcFile) {
  1199. rsrcFiles = append(rsrcFiles, rsrcFile)
  1200. }
  1201. }
  1202. zipFilename := rdestFile
  1203. if fs.IsDir(rdestFile) {
  1204. //Append the filename to it
  1205. if len(rsrcFiles) == 1 {
  1206. zipFilename = filepath.Join(rdestFile, strings.TrimSuffix(filepath.Base(rsrcFiles[0]), filepath.Ext(filepath.Base(rsrcFiles[0])))+".zip")
  1207. } else if len(rsrcFiles) > 1 {
  1208. zipFilename = filepath.Join(rdestFile, filepath.Base(filepath.Dir(rsrcFiles[0]))+".zip")
  1209. }
  1210. }
  1211. //Create a zip file at target location
  1212. err := fs.ArozZipFile(rsrcFiles, zipFilename, false)
  1213. if err != nil {
  1214. sendErrorResponse(w, err.Error())
  1215. return
  1216. }
  1217. } else {
  1218. //For operations that is handled file by file
  1219. for i, vsrcFile := range sourceFiles {
  1220. //Convert the virtual path to realpath on disk
  1221. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1222. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1223. //Check if the source file exists
  1224. if !fileExists(rsrcFile) {
  1225. /*
  1226. Special edge case handler:
  1227. There might be edge case that files are stored in URIEncoded methods
  1228. e.g. abc def.mp3 --> abc%20cdf.mp3
  1229. In this case, this logic statement should be able to handle this
  1230. */
  1231. edgeCaseFilename := filepath.Join(filepath.Dir(rsrcFile), system_fs_specialURIEncode(filepath.Base(rsrcFile)))
  1232. if fileExists(edgeCaseFilename) {
  1233. rsrcFile = edgeCaseFilename
  1234. } else {
  1235. sendErrorResponse(w, "Source file not exists.")
  1236. return
  1237. }
  1238. }
  1239. if operation == "rename" {
  1240. //Check if the usage is correct.
  1241. if vdestFile != "" {
  1242. sendErrorResponse(w, "Rename only accept 'src' and 'new'. Please use move if you want to move a file.")
  1243. return
  1244. }
  1245. //Check if new name paramter is passed in.
  1246. if len(newFilenames) == 0 {
  1247. sendErrorResponse(w, "Missing paramter (JSON string): 'new'")
  1248. return
  1249. }
  1250. //Check if the source filenames and new filenanmes match
  1251. if len(newFilenames) != len(sourceFiles) {
  1252. sendErrorResponse(w, "New filenames do not match with source filename's length.")
  1253. return
  1254. }
  1255. //Check if the target dir is not readonly
  1256. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1257. if accmode == "readonly" {
  1258. sendErrorResponse(w, "This directory is Read Only.")
  1259. return
  1260. } else if accmode == "denied" {
  1261. sendErrorResponse(w, "Access Denied")
  1262. return
  1263. }
  1264. thisFilename := newFilenames[i]
  1265. //Check if the name already exists. If yes, return false
  1266. if fileExists(filepath.Dir(rsrcFile) + "/" + thisFilename) {
  1267. sendErrorResponse(w, "File already exists")
  1268. return
  1269. }
  1270. //Everything is ok. Rename the file.
  1271. targetNewName := filepath.Dir(rsrcFile) + "/" + thisFilename
  1272. err = os.Rename(rsrcFile, targetNewName)
  1273. if err != nil {
  1274. sendErrorResponse(w, err.Error())
  1275. return
  1276. }
  1277. } else if operation == "move" {
  1278. //File move operation. Check if the source file / dir and target directory exists
  1279. /*
  1280. Example usage from file explorer
  1281. $.ajax({
  1282. type: 'POST',
  1283. url: `/system/file_system/fileOpr`,
  1284. data: {opr: "move" ,src: JSON.stringify(fileList), dest: targetDir},
  1285. success: function(data){
  1286. if (data.error !== undefined){
  1287. msgbox("remove",data.error);
  1288. }else{
  1289. //OK, do something
  1290. }
  1291. }
  1292. });
  1293. */
  1294. if !fileExists(rsrcFile) {
  1295. sendErrorResponse(w, "Source file not exists")
  1296. return
  1297. }
  1298. //Check if the source file is read only.
  1299. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1300. if accmode == "readonly" {
  1301. sendErrorResponse(w, "This source file is Read Only.")
  1302. return
  1303. } else if accmode == "denied" {
  1304. sendErrorResponse(w, "Access Denied")
  1305. return
  1306. }
  1307. if rdestFile == "" {
  1308. sendErrorResponse(w, "Undefined dest location.")
  1309. return
  1310. }
  1311. //Get exists overwrite mode
  1312. existsOpr, _ := mv(r, "existsresp", true)
  1313. //Check if use fast move instead
  1314. //Check if the source and destination folder are under the same root. If yes, use os.Rename for faster move operations
  1315. underSameRoot := false
  1316. //Check if the two files are under the same user root path
  1317. srcAbs, _ := filepath.Abs(rsrcFile)
  1318. destAbs, _ := filepath.Abs(rdestFile)
  1319. //Check other storage path and see if they are under the same root
  1320. for _, rootPath := range userinfo.GetAllFileSystemHandler() {
  1321. thisRoot := rootPath.Path
  1322. thisRootAbs, err := filepath.Abs(thisRoot)
  1323. if err != nil {
  1324. continue
  1325. }
  1326. if strings.Contains(srcAbs, thisRootAbs) && strings.Contains(destAbs, thisRootAbs) {
  1327. underSameRoot = true
  1328. }
  1329. }
  1330. //Updates 19-10-2020: Added ownership management to file move and copy
  1331. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1332. err = fs.FileMove(rsrcFile, rdestFile, existsOpr, underSameRoot, nil)
  1333. if err != nil {
  1334. sendErrorResponse(w, err.Error())
  1335. //Restore the ownership if remove failed
  1336. userinfo.SetOwnerOfFile(rsrcFile)
  1337. return
  1338. }
  1339. //Set user to own the new file
  1340. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1341. } else if operation == "copy" {
  1342. //Copy file. See move example and change 'opr' to 'copy'
  1343. if !fileExists(rsrcFile) {
  1344. sendErrorResponse(w, "Source file not exists")
  1345. return
  1346. }
  1347. //Check if the desintation is read only.
  1348. if !userinfo.CanWrite(vdestFile) {
  1349. sendErrorResponse(w, "Access Denied.")
  1350. return
  1351. }
  1352. if !fileExists(rdestFile) {
  1353. if fileExists(filepath.Dir(rdestFile)) {
  1354. //User pass in the whole path for the folder. Report error usecase.
  1355. sendErrorResponse(w, "Dest location should be an existing folder instead of the full path of the copied file.")
  1356. return
  1357. }
  1358. sendErrorResponse(w, "Dest folder not found")
  1359. return
  1360. }
  1361. existsOpr, _ := mv(r, "existsresp", true)
  1362. //Check if the user have space for the extra file
  1363. if !userinfo.StorageQuota.HaveSpace(fs.GetFileSize(rdestFile)) {
  1364. sendErrorResponse(w, "Storage Quota Full")
  1365. return
  1366. }
  1367. err = fs.FileCopy(rsrcFile, rdestFile, existsOpr, nil)
  1368. if err != nil {
  1369. sendErrorResponse(w, err.Error())
  1370. return
  1371. }
  1372. //Set user to own this file
  1373. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1374. } else if operation == "delete" {
  1375. //Delete the file permanently
  1376. if !fileExists(rsrcFile) {
  1377. //Check if it is a non escapted file instead
  1378. sendErrorResponse(w, "Source file not exists")
  1379. return
  1380. }
  1381. //Check if the desintation is read only.
  1382. /*
  1383. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1384. if accmode == "readonly" {
  1385. sendErrorResponse(w, "This directory is Read Only.")
  1386. return
  1387. } else if accmode == "denied" {
  1388. sendErrorResponse(w, "Access Denied")
  1389. return
  1390. }
  1391. */
  1392. if !userinfo.CanWrite(vsrcFile) {
  1393. sendErrorResponse(w, "Access Denied.")
  1394. return
  1395. }
  1396. //Check if the user own this file
  1397. isOwner := userinfo.IsOwnerOfFile(rsrcFile)
  1398. if isOwner {
  1399. //This user own this system. Remove this file from his quota
  1400. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1401. }
  1402. //Check if this file has any cached files. If yes, remove it
  1403. if fileExists(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg") {
  1404. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg")
  1405. }
  1406. //Clear the cache folder if there is no files inside
  1407. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1408. if len(fc) == 0 {
  1409. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1410. }
  1411. os.RemoveAll(rsrcFile)
  1412. } else if operation == "recycle" {
  1413. //Put it into a subfolder named trash and allow it to to be removed later
  1414. if !fileExists(rsrcFile) {
  1415. //Check if it is a non escapted file instead
  1416. sendErrorResponse(w, "Source file not exists")
  1417. return
  1418. }
  1419. //Check if the upload target is read only.
  1420. //Updates 20 Jan 2021: Replace with CanWrite handler
  1421. /*
  1422. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1423. if accmode == "readonly" {
  1424. sendErrorResponse(w, "This directory is Read Only.")
  1425. return
  1426. } else if accmode == "denied" {
  1427. sendErrorResponse(w, "Access Denied")
  1428. return
  1429. }*/
  1430. if !userinfo.CanWrite(vsrcFile) {
  1431. sendErrorResponse(w, "Access Denied.")
  1432. return
  1433. }
  1434. //Check if this file has any cached files. If yes, remove it
  1435. if fileExists(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg") {
  1436. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg")
  1437. }
  1438. //Clear the cache folder if there is no files inside
  1439. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1440. if len(fc) == 0 {
  1441. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1442. }
  1443. //Create a trash directory for this folder
  1444. trashDir := filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.trash/"
  1445. os.MkdirAll(trashDir, 0755)
  1446. hidden.HideFile(trashDir)
  1447. os.Rename(rsrcFile, trashDir+filepath.Base(rsrcFile)+"."+Int64ToString(GetUnixTime()))
  1448. } else if operation == "unzip" {
  1449. //Unzip the file to destination
  1450. //Check if the user can write to the target dest file
  1451. if userinfo.CanWrite(string(vdestFile)) == false {
  1452. sendErrorResponse(w, "Access Denied.")
  1453. return
  1454. }
  1455. //Make the rdest directory if not exists
  1456. if !fileExists(rdestFile) {
  1457. err = os.MkdirAll(rdestFile, 0755)
  1458. if err != nil {
  1459. sendErrorResponse(w, err.Error())
  1460. return
  1461. }
  1462. }
  1463. //OK! Unzip to destination
  1464. err := fs.Unzip(rsrcFile, rdestFile)
  1465. if err != nil {
  1466. sendErrorResponse(w, err.Error())
  1467. return
  1468. }
  1469. } else {
  1470. sendErrorResponse(w, "Unknown file opeartion given.")
  1471. return
  1472. }
  1473. }
  1474. }
  1475. sendJSONResponse(w, "\"OK\"")
  1476. return
  1477. }
  1478. //Allow systems to store key value pairs in the database as preferences.
  1479. func system_fs_handleUserPreference(w http.ResponseWriter, r *http.Request) {
  1480. username, err := authAgent.GetUserName(w, r)
  1481. if err != nil {
  1482. sendErrorResponse(w, "User not logged in")
  1483. return
  1484. }
  1485. key, _ := mv(r, "key", false)
  1486. value, _ := mv(r, "value", false)
  1487. remove, _ := mv(r, "remove", false)
  1488. if key != "" && value == "" && remove == "" {
  1489. //Get mode. Read the prefernece with given key
  1490. result := ""
  1491. err := sysdb.Read("fs", "pref/"+key+"/"+username, &result)
  1492. if err != nil {
  1493. sendJSONResponse(w, "{\"error\":\"Key not found.\"}")
  1494. return
  1495. }
  1496. sendTextResponse(w, result)
  1497. } else if key != "" && value == "" && remove == "true" {
  1498. //Remove mode. Delete this key from sysdb
  1499. err := sysdb.Delete("fs", "pref/"+key+"/"+username)
  1500. if err != nil {
  1501. sendErrorResponse(w, err.Error())
  1502. }
  1503. sendOK(w)
  1504. } else if key != "" && value != "" {
  1505. //Set mode. Set the preference with given key
  1506. if len(value) > 1024 {
  1507. //Size too big. Reject storage
  1508. sendErrorResponse(w, "Preference value too long. Preference value can only store maximum 1024 characters.")
  1509. return
  1510. }
  1511. sysdb.Write("fs", "pref/"+key+"/"+username, value)
  1512. sendOK(w)
  1513. }
  1514. }
  1515. func system_fs_removeUserPreferences(username string) {
  1516. entries, err := sysdb.ListTable("fs")
  1517. if err != nil {
  1518. return
  1519. }
  1520. for _, keypairs := range entries {
  1521. if strings.Contains(string(keypairs[0]), "pref/") && strings.Contains(string(keypairs[0]), "/"+username) {
  1522. //Remove this preference
  1523. sysdb.Delete("fs", string(keypairs[0]))
  1524. }
  1525. }
  1526. }
  1527. func system_fs_listDrives(w http.ResponseWriter, r *http.Request) {
  1528. if authAgent.CheckAuth(r) == false {
  1529. sendErrorResponse(w, "User not logged in")
  1530. return
  1531. }
  1532. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1533. type driveInfo struct {
  1534. Drivepath string
  1535. DriveFreeSpace uint64
  1536. DriveTotalSpace uint64
  1537. DriveAvailSpace uint64
  1538. }
  1539. var drives []driveInfo
  1540. if runtime.GOOS == "windows" {
  1541. //Under windows
  1542. for _, drive := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
  1543. f, err := os.Open(string(drive) + ":\\")
  1544. if err == nil {
  1545. thisdrive := new(driveInfo)
  1546. thisdrive.Drivepath = string(drive) + ":\\"
  1547. free, total, avail := storage.GetDriveCapacity(string(drive) + ":\\")
  1548. thisdrive.DriveFreeSpace = free
  1549. thisdrive.DriveTotalSpace = total
  1550. thisdrive.DriveAvailSpace = avail
  1551. drives = append(drives, *thisdrive)
  1552. f.Close()
  1553. }
  1554. }
  1555. } else {
  1556. //Under linux environment
  1557. //Append all the virtual directories root as root instead
  1558. storageDevices := []string{}
  1559. for _, fshandler := range userinfo.GetAllFileSystemHandler() {
  1560. storageDevices = append(storageDevices, fshandler.Path)
  1561. }
  1562. //List all storage information of each devices
  1563. for _, dev := range storageDevices {
  1564. thisdrive := new(driveInfo)
  1565. thisdrive.Drivepath = filepath.Base(dev)
  1566. free, total, avail := storage.GetDriveCapacity(string(dev))
  1567. thisdrive.DriveFreeSpace = free
  1568. thisdrive.DriveTotalSpace = total
  1569. thisdrive.DriveAvailSpace = avail
  1570. drives = append(drives, *thisdrive)
  1571. }
  1572. }
  1573. jsonString, _ := json.Marshal(drives)
  1574. sendJSONResponse(w, string(jsonString))
  1575. }
  1576. func system_fs_listRoot(w http.ResponseWriter, r *http.Request) {
  1577. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1578. if err != nil {
  1579. sendErrorResponse(w, err.Error())
  1580. return
  1581. }
  1582. username := userinfo.Username
  1583. userRoot, _ := mv(r, "user", false)
  1584. if userRoot == "true" {
  1585. type fileObject struct {
  1586. Filename string
  1587. Filepath string
  1588. IsDir bool
  1589. }
  1590. //List the root media folders under user:/
  1591. filesInUserRoot := []fileObject{}
  1592. filesInRoot, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(*root_directory)) + "/users/" + username + "/*")
  1593. for _, file := range filesInRoot {
  1594. thisFile := new(fileObject)
  1595. thisFile.Filename = filepath.Base(file)
  1596. thisFile.Filepath, _ = userinfo.RealPathToVirtualPath(file)
  1597. thisFile.IsDir = IsDir(file)
  1598. filesInUserRoot = append(filesInUserRoot, *thisFile)
  1599. }
  1600. jsonString, _ := json.Marshal(filesInUserRoot)
  1601. sendJSONResponse(w, string(jsonString))
  1602. } else {
  1603. type rootObject struct {
  1604. rootID string //The vroot id
  1605. RootName string //The name of this vroot
  1606. RootPath string //The path of this vroot
  1607. RootBackups bool //If there are backup for this vroot
  1608. }
  1609. roots := []*rootObject{}
  1610. backupRoots := []string{}
  1611. for _, store := range userinfo.GetAllFileSystemHandler() {
  1612. if store.Hierarchy == "user" || store.Hierarchy == "public" {
  1613. //Normal drives
  1614. var thisDevice = new(rootObject)
  1615. thisDevice.RootName = store.Name
  1616. thisDevice.RootPath = store.UUID + ":/"
  1617. thisDevice.rootID = store.UUID
  1618. roots = append(roots, thisDevice)
  1619. } else if store.Hierarchy == "backup" {
  1620. //Backup drive.
  1621. backupRoots = append(backupRoots, store.HierarchyConfig.(hybridBackup.BackupTask).ParentUID)
  1622. }
  1623. }
  1624. //Update root configs for backup roots
  1625. for _, backupRoot := range backupRoots {
  1626. //For this backup root, check if the parent root mounted
  1627. for _, root := range roots {
  1628. if root.rootID == backupRoot {
  1629. //Parent root mounted. Label the parent root as "have backup"
  1630. root.RootBackups = true
  1631. }
  1632. }
  1633. }
  1634. jsonString, _ := json.Marshal(roots)
  1635. sendJSONResponse(w, string(jsonString))
  1636. }
  1637. }
  1638. /*
  1639. Special Glob for handling path with [ or ] inside.
  1640. You can also pass in normal path for globing if you are not sure.
  1641. */
  1642. func system_fs_specialGlob(path string) ([]string, error) {
  1643. //Quick fix for foldername containing -] issue
  1644. path = strings.ReplaceAll(path, "[", "[[]")
  1645. files, err := filepath.Glob(path)
  1646. if err != nil {
  1647. return []string{}, err
  1648. }
  1649. if strings.Contains(path, "[") == true || strings.Contains(path, "]") == true {
  1650. if len(files) == 0 {
  1651. //Handle reverse check. Replace all [ and ] with *
  1652. newSearchPath := strings.ReplaceAll(path, "[", "?")
  1653. newSearchPath = strings.ReplaceAll(newSearchPath, "]", "?")
  1654. //Scan with all the similar structure except [ and ]
  1655. tmpFilelist, _ := filepath.Glob(newSearchPath)
  1656. for _, file := range tmpFilelist {
  1657. file = filepath.ToSlash(file)
  1658. if strings.Contains(file, filepath.ToSlash(filepath.Dir(path))) {
  1659. files = append(files, file)
  1660. }
  1661. }
  1662. }
  1663. }
  1664. //Convert all filepaths to slash
  1665. for i := 0; i < len(files); i++ {
  1666. files[i] = filepath.ToSlash(files[i])
  1667. }
  1668. return files, nil
  1669. }
  1670. func system_fs_specialURIDecode(inputPath string) string {
  1671. inputPath = strings.ReplaceAll(inputPath, "+", "{{plus_sign}}")
  1672. inputPath, _ = url.QueryUnescape(inputPath)
  1673. inputPath = strings.ReplaceAll(inputPath, "{{plus_sign}}", "+")
  1674. return inputPath
  1675. }
  1676. func system_fs_specialURIEncode(inputPath string) string {
  1677. inputPath = strings.ReplaceAll(inputPath, " ", "{{space_sign}}")
  1678. inputPath, _ = url.QueryUnescape(inputPath)
  1679. inputPath = strings.ReplaceAll(inputPath, "{{space_sign}}", "%20")
  1680. return inputPath
  1681. }
  1682. func system_fs_matchFileExt(inputFilename string, extArray []string) bool {
  1683. inputExt := filepath.Ext(inputFilename)
  1684. if stringInSlice(inputExt, extArray) {
  1685. return true
  1686. }
  1687. return false
  1688. }
  1689. //Handle file properties request
  1690. func system_fs_getFileProperties(w http.ResponseWriter, r *http.Request) {
  1691. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1692. if err != nil {
  1693. sendErrorResponse(w, err.Error())
  1694. return
  1695. }
  1696. vpath, err := mv(r, "path", true)
  1697. if err != nil {
  1698. sendErrorResponse(w, "path not defined")
  1699. return
  1700. }
  1701. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  1702. if err != nil {
  1703. sendErrorResponse(w, err.Error())
  1704. return
  1705. }
  1706. fileStat, err := os.Stat(rpath)
  1707. if err != nil {
  1708. sendErrorResponse(w, err.Error())
  1709. return
  1710. }
  1711. type fileProperties struct {
  1712. VirtualPath string
  1713. StoragePath string
  1714. Basename string
  1715. VirtualDirname string
  1716. StorageDirname string
  1717. Ext string
  1718. MimeType string
  1719. Filesize int64
  1720. Permission string
  1721. LastModTime string
  1722. LastModUnix int64
  1723. IsDirectory bool
  1724. Owner string
  1725. }
  1726. mime := "text/directory"
  1727. if !fileStat.IsDir() {
  1728. m, _, err := fs.GetMime(rpath)
  1729. if err != nil {
  1730. mime = ""
  1731. }
  1732. mime = m
  1733. }
  1734. filesize := fileStat.Size()
  1735. //Get file overall size if this is folder
  1736. if fileStat.IsDir() {
  1737. var size int64
  1738. filepath.Walk(rpath, func(_ string, info os.FileInfo, err error) error {
  1739. if err != nil {
  1740. return err
  1741. }
  1742. if !info.IsDir() {
  1743. size += info.Size()
  1744. }
  1745. return err
  1746. })
  1747. filesize = size
  1748. }
  1749. //Get file owner
  1750. owner := userinfo.GetFileOwner(rpath)
  1751. if owner == "" {
  1752. owner = "Unknown"
  1753. }
  1754. result := fileProperties{
  1755. VirtualPath: vpath,
  1756. StoragePath: filepath.Clean(rpath),
  1757. Basename: filepath.Base(rpath),
  1758. VirtualDirname: filepath.ToSlash(filepath.Dir(vpath)),
  1759. StorageDirname: filepath.ToSlash(filepath.Dir(rpath)),
  1760. Ext: filepath.Ext(rpath),
  1761. MimeType: mime,
  1762. Filesize: filesize,
  1763. Permission: fileStat.Mode().Perm().String(),
  1764. LastModTime: timeToString(fileStat.ModTime()),
  1765. LastModUnix: fileStat.ModTime().Unix(),
  1766. IsDirectory: fileStat.IsDir(),
  1767. Owner: owner,
  1768. }
  1769. jsonString, _ := json.Marshal(result)
  1770. sendJSONResponse(w, string(jsonString))
  1771. }
  1772. /*
  1773. List directory in the given path
  1774. Usage: Pass in dir like the following examples:
  1775. AOR:/Desktop <= Open /user/{username}/Desktop
  1776. S1:/ <= Open {uuid=S1}/
  1777. */
  1778. func system_fs_handleList(w http.ResponseWriter, r *http.Request) {
  1779. currentDir, _ := mv(r, "dir", true)
  1780. //Commented this line to handle dirname that contains "+" sign
  1781. //currentDir, _ = url.QueryUnescape(currentDir)
  1782. sortMode, _ := mv(r, "sort", true)
  1783. showHidden, _ := mv(r, "showHidden", true)
  1784. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1785. if err != nil {
  1786. //user not logged in. Redirect to login page.
  1787. sendErrorResponse(w, "User not logged in")
  1788. return
  1789. }
  1790. if currentDir == "" {
  1791. sendErrorResponse(w, "Invalid dir given.")
  1792. return
  1793. }
  1794. //Pad a slash at the end of currentDir if not exists
  1795. if currentDir[len(currentDir)-1:] != "/" {
  1796. currentDir = currentDir + "/"
  1797. }
  1798. //Convert the virutal path to realpath
  1799. realpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1800. if err != nil {
  1801. sendErrorResponse(w, "Error. Unable to parse path. "+err.Error())
  1802. return
  1803. }
  1804. if !fileExists(realpath) {
  1805. userRoot, _ := userinfo.VirtualPathToRealPath("user:/")
  1806. if filepath.Clean(realpath) == filepath.Clean(userRoot) {
  1807. //Initiate user folder (Initiaed in user object)
  1808. userinfo.GetHomeDirectory()
  1809. } else {
  1810. //Folder not exists
  1811. log.Println("[File Explorer] Requested path: ", realpath, " does not exists!")
  1812. sendErrorResponse(w, "Folder not exists")
  1813. return
  1814. }
  1815. }
  1816. if sortMode == "" {
  1817. sortMode = "default"
  1818. }
  1819. //Check for really special exception in where the path contains [ or ] which cannot be handled via Golang Glob function
  1820. files, _ := system_fs_specialGlob(filepath.Clean(realpath) + "/*")
  1821. var parsedFilelist []fs.FileData
  1822. var shortCutInfo *shortcut.ShortcutData = nil
  1823. for _, v := range files {
  1824. //Check if it is hidden file
  1825. isHidden, _ := hidden.IsHidden(v, false)
  1826. if showHidden != "true" && isHidden {
  1827. //Skipping hidden files
  1828. continue
  1829. }
  1830. //Check if this is an aodb file
  1831. if filepath.Base(v) == "aofs.db" || filepath.Base(v) == "aofs.db.lock" {
  1832. //Database file (reserved)
  1833. continue
  1834. }
  1835. //Check if it is shortcut file. If yes, render a shortcut data struct
  1836. if filepath.Ext(v) == ".shortcut" {
  1837. //This is a shortcut file
  1838. shorcutData, err := shortcut.ReadShortcut(v)
  1839. if err == nil {
  1840. shortCutInfo = shorcutData
  1841. }
  1842. }
  1843. rawsize := fs.GetFileSize(v)
  1844. modtime, _ := fs.GetModTime(v)
  1845. thisFile := fs.FileData{
  1846. Filename: filepath.Base(v),
  1847. Filepath: currentDir + filepath.Base(v),
  1848. Realpath: v,
  1849. IsDir: IsDir(v),
  1850. Filesize: rawsize,
  1851. Displaysize: fs.GetFileDisplaySize(rawsize, 2),
  1852. ModTime: modtime,
  1853. IsShared: shareManager.FileIsShared(v),
  1854. Shortcut: shortCutInfo,
  1855. }
  1856. parsedFilelist = append(parsedFilelist, thisFile)
  1857. }
  1858. //Sort the filelist
  1859. if sortMode == "default" {
  1860. //Sort by name, convert filename to window sorting methods
  1861. sort.Slice(parsedFilelist, func(i, j int) bool {
  1862. return strings.ToLower(parsedFilelist[i].Filename) < strings.ToLower(parsedFilelist[j].Filename)
  1863. })
  1864. } else if sortMode == "reverse" {
  1865. //Sort by reverse name
  1866. sort.Slice(parsedFilelist, func(i, j int) bool {
  1867. return strings.ToLower(parsedFilelist[i].Filename) > strings.ToLower(parsedFilelist[j].Filename)
  1868. })
  1869. } else if sortMode == "smallToLarge" {
  1870. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize < parsedFilelist[j].Filesize })
  1871. } else if sortMode == "largeToSmall" {
  1872. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize > parsedFilelist[j].Filesize })
  1873. } else if sortMode == "mostRecent" {
  1874. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime > parsedFilelist[j].ModTime })
  1875. } else if sortMode == "leastRecent" {
  1876. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime < parsedFilelist[j].ModTime })
  1877. }
  1878. jsonString, _ := json.Marshal(parsedFilelist)
  1879. sendJSONResponse(w, string(jsonString))
  1880. }
  1881. //Handle getting a hash from a given contents in the given path
  1882. func system_fs_handleDirHash(w http.ResponseWriter, r *http.Request) {
  1883. currentDir, err := mv(r, "dir", true)
  1884. if err != nil {
  1885. sendErrorResponse(w, "Invalid dir given")
  1886. return
  1887. }
  1888. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1889. if err != nil {
  1890. sendErrorResponse(w, "User not logged in")
  1891. return
  1892. }
  1893. rpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1894. if err != nil {
  1895. sendErrorResponse(w, "Invalid dir given")
  1896. return
  1897. }
  1898. //Get a list of files in this directory
  1899. currentDir = filepath.ToSlash(filepath.Clean(rpath)) + "/"
  1900. filesInDir, err := system_fs_specialGlob(currentDir + "*")
  1901. if err != nil {
  1902. sendErrorResponse(w, err.Error())
  1903. return
  1904. }
  1905. filenames := []string{}
  1906. for _, file := range filesInDir {
  1907. if len(filepath.Base(file)) > 0 && string([]rune(filepath.Base(file))[0]) != "." {
  1908. //Ignore hidden files
  1909. filenames = append(filenames, filepath.Base(file))
  1910. }
  1911. }
  1912. sort.Strings(filenames)
  1913. //Build a hash base on the filelist
  1914. h := sha256.New()
  1915. h.Write([]byte(strings.Join(filenames, ",")))
  1916. sendTextResponse(w, hex.EncodeToString((h.Sum(nil))))
  1917. }
  1918. /*
  1919. File zipping and unzipping functions
  1920. */
  1921. //Handle all zip related API
  1922. func system_fs_zipHandler(w http.ResponseWriter, r *http.Request) {
  1923. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1924. if err != nil {
  1925. sendErrorResponse(w, err.Error())
  1926. return
  1927. }
  1928. opr, err := mv(r, "opr", true)
  1929. if err != nil {
  1930. sendErrorResponse(w, "Invalid opr or opr not defined")
  1931. return
  1932. }
  1933. vsrc, _ := mv(r, "src", true)
  1934. if vsrc == "" {
  1935. sendErrorResponse(w, "Invalid src paramter")
  1936. return
  1937. }
  1938. vdest, _ := mv(r, "dest", true)
  1939. rdest := ""
  1940. //Convert source path from JSON string to object
  1941. virtualSourcePaths := []string{}
  1942. err = json.Unmarshal([]byte(vsrc), &virtualSourcePaths)
  1943. if err != nil {
  1944. sendErrorResponse(w, err.Error())
  1945. return
  1946. }
  1947. //Check each of the path
  1948. realSourcePaths := []string{}
  1949. for _, vpath := range virtualSourcePaths {
  1950. thisrpath, err := userinfo.VirtualPathToRealPath(vpath)
  1951. if err != nil || !fileExists(thisrpath) {
  1952. sendErrorResponse(w, "File not exists: "+vpath)
  1953. return
  1954. }
  1955. realSourcePaths = append(realSourcePaths, thisrpath)
  1956. }
  1957. ///Convert dest to real if given
  1958. if vdest != "" {
  1959. realdest, _ := userinfo.VirtualPathToRealPath(vdest)
  1960. rdest = realdest
  1961. }
  1962. //This function will be deprecate soon in ArozOS 1.120
  1963. log.Println("*DEPRECATE* zipHandler will be deprecating soon! Please use fileOpr endpoint")
  1964. if opr == "zip" {
  1965. //Check if destination location exists
  1966. if rdest == "" || !fileExists(filepath.Dir(rdest)) {
  1967. sendErrorResponse(w, "Invalid dest location")
  1968. return
  1969. }
  1970. //OK. Create the zip at the desired location
  1971. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  1972. if err != nil {
  1973. sendErrorResponse(w, err.Error())
  1974. return
  1975. }
  1976. sendOK(w)
  1977. } else if opr == "tmpzip" {
  1978. //Zip to tmp folder
  1979. userTmpFolder, _ := userinfo.VirtualPathToRealPath("tmp:/")
  1980. filename := Int64ToString(GetUnixTime()) + ".zip"
  1981. rdest := filepath.ToSlash(filepath.Clean(userTmpFolder)) + "/" + filename
  1982. log.Println(realSourcePaths, rdest)
  1983. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  1984. if err != nil {
  1985. sendErrorResponse(w, err.Error())
  1986. return
  1987. }
  1988. //Send the tmp filename to the user
  1989. sendTextResponse(w, "tmp:/"+filename)
  1990. } else if opr == "inspect" {
  1991. } else if opr == "unzip" {
  1992. }
  1993. }
  1994. //Translate path from and to virtual and realpath
  1995. func system_fs_handlePathTranslate(w http.ResponseWriter, r *http.Request) {
  1996. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1997. if err != nil {
  1998. sendErrorResponse(w, err.Error())
  1999. return
  2000. }
  2001. path, err := mv(r, "path", false)
  2002. if err != nil {
  2003. sendErrorResponse(w, "Invalid path given")
  2004. return
  2005. }
  2006. rpath, err := userinfo.VirtualPathToRealPath(path)
  2007. if err != nil {
  2008. //Try to convert it to virtualPath
  2009. vpath, err := userinfo.RealPathToVirtualPath(path)
  2010. if err != nil {
  2011. sendErrorResponse(w, "Unknown path given")
  2012. } else {
  2013. jsonstring, _ := json.Marshal(vpath)
  2014. sendJSONResponse(w, string(jsonstring))
  2015. }
  2016. } else {
  2017. abrpath, _ := filepath.Abs(rpath)
  2018. jsonstring, _ := json.Marshal([]string{rpath, filepath.ToSlash(abrpath)})
  2019. sendJSONResponse(w, string(jsonstring))
  2020. }
  2021. }
  2022. //Handle cache rendering with websocket pipeline
  2023. func system_fs_handleCacheRender(w http.ResponseWriter, r *http.Request) {
  2024. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2025. vpath, err := mv(r, "folder", false)
  2026. if err != nil {
  2027. sendErrorResponse(w, "Invalid folder paramter")
  2028. return
  2029. }
  2030. //Convert vpath to realpath
  2031. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  2032. if err != nil {
  2033. sendErrorResponse(w, err.Error())
  2034. return
  2035. }
  2036. //Perform cache rendering
  2037. thumbRenderHandler.HandleLoadCache(w, r, rpath)
  2038. }
  2039. //Handle file thumbnail caching
  2040. func system_fs_handleFolderCache(w http.ResponseWriter, r *http.Request) {
  2041. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2042. vfolderpath, err := mv(r, "folder", false)
  2043. if err != nil {
  2044. sendErrorResponse(w, "folder not defined")
  2045. return
  2046. }
  2047. rpath, err := userinfo.VirtualPathToRealPath(vfolderpath)
  2048. if err != nil {
  2049. sendErrorResponse(w, err.Error())
  2050. return
  2051. }
  2052. thumbRenderHandler.BuildCacheForFolder(rpath)
  2053. sendOK(w)
  2054. }
  2055. //Handle setting and loading of file permission on Linux
  2056. func system_fs_handleFilePermission(w http.ResponseWriter, r *http.Request) {
  2057. file, err := mv(r, "file", true)
  2058. if err != nil {
  2059. sendErrorResponse(w, "Invalid file")
  2060. return
  2061. }
  2062. //Translate the file to real path
  2063. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2064. if err != nil {
  2065. sendErrorResponse(w, "User not logged in")
  2066. return
  2067. }
  2068. rpath, err := userinfo.VirtualPathToRealPath(file)
  2069. if err != nil {
  2070. sendErrorResponse(w, err.Error())
  2071. return
  2072. }
  2073. newMode, _ := mv(r, "mode", true)
  2074. if newMode == "" {
  2075. //Read the file mode
  2076. //Check if the file exists
  2077. if !fileExists(rpath) {
  2078. sendErrorResponse(w, "File not exists!")
  2079. return
  2080. }
  2081. //Read the file permission
  2082. filePermission, err := fsp.GetFilePermissions(rpath)
  2083. if err != nil {
  2084. sendErrorResponse(w, err.Error())
  2085. return
  2086. }
  2087. //Send the file permission to client
  2088. js, _ := json.Marshal(filePermission)
  2089. sendJSONResponse(w, string(js))
  2090. } else {
  2091. //Set the file mode
  2092. //Check if the file exists
  2093. if !fileExists(rpath) {
  2094. sendErrorResponse(w, "File not exists!")
  2095. return
  2096. }
  2097. //Check if windows. If yes, ignore this request
  2098. if runtime.GOOS == "windows" {
  2099. sendErrorResponse(w, "Windows host not supported")
  2100. return
  2101. }
  2102. //Check if this user has permission to change the file permission
  2103. //Aka user must be 1. This is his own folder or 2. Admin
  2104. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(file)
  2105. if fsh.Hierarchy == "user" {
  2106. //Always ok as this is owned by the user
  2107. } else if fsh.Hierarchy == "public" {
  2108. //Require admin
  2109. if userinfo.IsAdmin() == false {
  2110. sendErrorResponse(w, "Permission Denied")
  2111. return
  2112. }
  2113. } else {
  2114. //Not implemeneted. Require admin
  2115. if userinfo.IsAdmin() == false {
  2116. sendErrorResponse(w, "Permission Denied")
  2117. return
  2118. }
  2119. }
  2120. //Be noted that if the system is not running in sudo mode,
  2121. //File permission change might not works.
  2122. err := fsp.SetFilePermisson(rpath, newMode)
  2123. if err != nil {
  2124. sendErrorResponse(w, err.Error())
  2125. return
  2126. } else {
  2127. sendOK(w)
  2128. }
  2129. }
  2130. }
  2131. //Check if the given filepath is and must inside the given directory path.
  2132. //You can pass both as relative
  2133. func system_fs_checkFileInDirectory(filesourcepath string, directory string) bool {
  2134. filepathAbs, err := filepath.Abs(filesourcepath)
  2135. if err != nil {
  2136. return false
  2137. }
  2138. directoryAbs, err := filepath.Abs(directory)
  2139. if err != nil {
  2140. return false
  2141. }
  2142. //Check if the filepathabs contain directoryAbs
  2143. if strings.Contains(filepathAbs, directoryAbs) {
  2144. return true
  2145. } else {
  2146. return false
  2147. }
  2148. }
  2149. //Clear the old files inside the tmp file
  2150. func system_fs_clearOldTmpFiles() {
  2151. filesToBeDelete := []string{}
  2152. tmpAbs, _ := filepath.Abs(*tmp_directory)
  2153. filepath.Walk(*tmp_directory, func(path string, info os.FileInfo, err error) error {
  2154. if filepath.Base(path) != "aofs.db" && filepath.Base(path) != "aofs.db.lock" {
  2155. //Check if root folders. Do not delete root folders
  2156. parentAbs, _ := filepath.Abs(filepath.Dir(path))
  2157. if tmpAbs == parentAbs {
  2158. //Root folder. Do not remove
  2159. return nil
  2160. }
  2161. //Get its modification time
  2162. modTime, err := fs.GetModTime(path)
  2163. if err != nil {
  2164. return nil
  2165. }
  2166. //Check if mod time is more than 24 hours ago
  2167. if time.Now().Unix()-modTime > int64(*maxTempFileKeepTime) {
  2168. //Delete OK
  2169. filesToBeDelete = append(filesToBeDelete, path)
  2170. }
  2171. }
  2172. return nil
  2173. })
  2174. //Remove all files from the delete list
  2175. for _, fileToBeDelete := range filesToBeDelete {
  2176. os.RemoveAll(fileToBeDelete)
  2177. }
  2178. }