file_system.go 68 KB

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