file_system.go 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468
  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. //Handle the main share function
  151. http.HandleFunc("/share", shareManager.HandleShareAccess)
  152. /*
  153. Nighly Tasks
  154. These functions allow file system to clear and maintain
  155. the arozos file system when no one is using the system
  156. */
  157. //Clear tmp folder if files is placed here too long
  158. RegisterNightlyTask(system_fs_clearOldTmpFiles)
  159. //Clear shares that its parent file no longer exists in the system
  160. shareManager.ValidateAndClearShares()
  161. RegisterNightlyTask(shareManager.ValidateAndClearShares)
  162. }
  163. /*
  164. File Search
  165. Handle file search in wildcard and recursive search
  166. */
  167. func system_fs_handleFileSearch(w http.ResponseWriter, r *http.Request) {
  168. //Get the user information
  169. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  170. if err != nil {
  171. sendErrorResponse(w, "User not logged in")
  172. return
  173. }
  174. //Get the search target root path
  175. vpath, err := mv(r, "path", true)
  176. if err != nil {
  177. sendErrorResponse(w, "Invalid vpath given")
  178. return
  179. }
  180. keyword, err := mv(r, "keyword", true)
  181. if err != nil {
  182. sendErrorResponse(w, "Invalid keyword given")
  183. return
  184. }
  185. //Check if case sensitive is enabled
  186. casesensitve, _ := mv(r, "casesensitive", true)
  187. //Translate the vpath to realpath
  188. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  189. if err != nil {
  190. sendErrorResponse(w, "Invalid path given")
  191. return
  192. }
  193. //Check if the search mode is recursive keyword or wildcard
  194. if len(keyword) > 1 && keyword[:1] == "/" {
  195. //Wildcard
  196. wildcard := keyword[1:]
  197. matchingFiles, err := filepath.Glob(filepath.Join(rpath, wildcard))
  198. if err != nil {
  199. sendErrorResponse(w, err.Error())
  200. return
  201. }
  202. //Prepare result struct
  203. results := []fs.FileData{}
  204. //Process the matching files. Do not allow directory escape
  205. srcAbs, _ := filepath.Abs(rpath)
  206. srcAbs = filepath.ToSlash(srcAbs)
  207. escaped := false
  208. for _, matchedFile := range matchingFiles {
  209. absMatch, _ := filepath.Abs(matchedFile)
  210. absMatch = filepath.ToSlash(absMatch)
  211. if !strings.Contains(absMatch, srcAbs) {
  212. escaped = true
  213. }
  214. thisVpath, _ := userinfo.RealPathToVirtualPath(matchedFile)
  215. results = append(results, fs.GetFileDataFromPath(thisVpath, matchedFile, 2))
  216. }
  217. if escaped {
  218. sendErrorResponse(w, "Search keywords contain escape character!")
  219. return
  220. }
  221. //OK. Tidy up the results
  222. js, _ := json.Marshal(results)
  223. sendJSONResponse(w, string(js))
  224. } else {
  225. //Recursive keyword
  226. results := []fs.FileData{}
  227. var err error = nil
  228. if casesensitve == "true" {
  229. //Require case sensitive match
  230. err = filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  231. if strings.Contains(filepath.Base(path), keyword) {
  232. //This is a matching file
  233. if !fs.IsInsideHiddenFolder(path) {
  234. thisVpath, _ := userinfo.RealPathToVirtualPath(path)
  235. results = append(results, fs.GetFileDataFromPath(thisVpath, path, 2))
  236. }
  237. }
  238. return nil
  239. })
  240. } else {
  241. //Require general match
  242. keywordLower := strings.ToLower(keyword)
  243. err = filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  244. if strings.Contains(strings.ToLower(filepath.Base(path)), keywordLower) {
  245. //This is a matching file
  246. if !fs.IsInsideHiddenFolder(path) {
  247. thisVpath, _ := userinfo.RealPathToVirtualPath(path)
  248. results = append(results, fs.GetFileDataFromPath(thisVpath, path, 2))
  249. }
  250. }
  251. return nil
  252. })
  253. }
  254. if err != nil {
  255. sendErrorResponse(w, err.Error())
  256. return
  257. }
  258. //OK. Tidy up the results
  259. js, _ := json.Marshal(results)
  260. sendJSONResponse(w, string(js))
  261. }
  262. }
  263. /*
  264. Handle low-memory upload operations
  265. This function is specailly designed to work with low memory devices
  266. (e.g. ZeroPi / Orange Pi Zero with 512MB RAM)
  267. */
  268. func system_fs_handleLowMemoryUpload(w http.ResponseWriter, r *http.Request) {
  269. //Get user info
  270. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  271. if err != nil {
  272. w.WriteHeader(http.StatusUnauthorized)
  273. w.Write([]byte("401 - Unauthorized"))
  274. return
  275. }
  276. //Get filename and upload path
  277. filename, err := mv(r, "filename", false)
  278. if filename == "" || err != nil {
  279. w.WriteHeader(http.StatusInternalServerError)
  280. w.Write([]byte("500 - Invalid filename given"))
  281. return
  282. }
  283. //Get upload target directory
  284. uploadTarget, err := mv(r, "path", false)
  285. if uploadTarget == "" || err != nil {
  286. w.WriteHeader(http.StatusInternalServerError)
  287. w.Write([]byte("500 - Invalid path given"))
  288. return
  289. }
  290. //Check if the user can write to this folder
  291. if !userinfo.CanWrite(uploadTarget) {
  292. //No permission
  293. w.WriteHeader(http.StatusForbidden)
  294. w.Write([]byte("403 - Access Denied"))
  295. return
  296. }
  297. //Translate the upload target directory
  298. realUploadPath, err := userinfo.VirtualPathToRealPath(uploadTarget)
  299. if err != nil {
  300. w.WriteHeader(http.StatusInternalServerError)
  301. w.Write([]byte("500 - Path translation failed"))
  302. return
  303. }
  304. //Generate an UUID for this upload
  305. uploadUUID := uuid.NewV4().String()
  306. uploadFolder := filepath.Join(*tmp_directory, "uploads", uploadUUID)
  307. os.MkdirAll(uploadFolder, 0700)
  308. targetUploadLocation := filepath.Join(realUploadPath, filename)
  309. if !fileExists(realUploadPath) {
  310. os.MkdirAll(realUploadPath, 0755)
  311. }
  312. //Start websocket connection
  313. var upgrader = websocket.Upgrader{}
  314. c, err := upgrader.Upgrade(w, r, nil)
  315. defer c.Close()
  316. //Handle WebSocket upload
  317. blockCounter := 0
  318. chunkName := []string{}
  319. lastChunkArrivalTime := time.Now().Unix()
  320. //Setup a timeout listener, check if connection still active every 1 minute
  321. ticker := time.NewTicker(60 * time.Second)
  322. done := make(chan bool)
  323. go func() {
  324. for {
  325. select {
  326. case <-done:
  327. return
  328. case <-ticker.C:
  329. if time.Now().Unix()-lastChunkArrivalTime > 300 {
  330. //Already 5 minutes without new data arraival. Stop connection
  331. log.Println("Upload WebSocket connection timeout. Disconnecting.")
  332. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  333. time.Sleep(1 * time.Second)
  334. c.Close()
  335. return
  336. }
  337. }
  338. }
  339. }()
  340. totalFileSize := int64(0)
  341. for {
  342. mt, message, err := c.ReadMessage()
  343. if err != nil {
  344. //Connection closed by client. Clear the tmp folder and exit
  345. log.Println("Upload terminated by client. Cleaning tmp folder.")
  346. //Clear the tmp folder
  347. time.Sleep(1 * time.Second)
  348. os.RemoveAll(uploadFolder)
  349. return
  350. }
  351. //The mt should be 2 = binary for file upload and 1 for control syntax
  352. if mt == 1 {
  353. msg := strings.TrimSpace(string(message))
  354. if msg == "done" {
  355. //Start the merging process
  356. log.Println(userinfo.Username + " uploaded a file: " + filepath.Base(targetUploadLocation))
  357. break
  358. } else {
  359. //Unknown operations
  360. }
  361. } else if mt == 2 {
  362. //File block. Save it to tmp folder
  363. chunkFilepath := filepath.Join(uploadFolder, "upld_"+strconv.Itoa(blockCounter))
  364. chunkName = append(chunkName, chunkFilepath)
  365. ioutil.WriteFile(chunkFilepath, message, 0700)
  366. //Update the last upload chunk time
  367. lastChunkArrivalTime = time.Now().Unix()
  368. //Check if the file size is too big
  369. totalFileSize += fs.GetFileSize(chunkFilepath)
  370. if totalFileSize > max_upload_size {
  371. //File too big
  372. c.WriteMessage(1, []byte(`{\"error\":\"File size too large.\"}`))
  373. //Close the connection
  374. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  375. time.Sleep(1 * time.Second)
  376. c.Close()
  377. //Clear the tmp files
  378. os.RemoveAll(uploadFolder)
  379. return
  380. }
  381. blockCounter++
  382. //Request client to send the next chunk
  383. c.WriteMessage(1, []byte("next"))
  384. }
  385. //log.Println("recv:", len(message), "type", mt)
  386. }
  387. //Merge the file
  388. out, err := os.OpenFile(targetUploadLocation, os.O_CREATE|os.O_WRONLY, 0755)
  389. if err != nil {
  390. log.Println("Failed to open file:", err)
  391. c.WriteMessage(1, []byte(`{\"error\":\"Failed to open destination file\"}`))
  392. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  393. time.Sleep(1 * time.Second)
  394. c.Close()
  395. return
  396. }
  397. defer out.Close()
  398. for _, filesrc := range chunkName {
  399. srcChunkReader, err := os.Open(filesrc)
  400. if err != nil {
  401. log.Println("Failed to open Source Chunk", filesrc, " with error ", err.Error())
  402. c.WriteMessage(1, []byte(`{\"error\":\"Failed to open Source Chunk\"}`))
  403. return
  404. }
  405. io.Copy(out, srcChunkReader)
  406. srcChunkReader.Close()
  407. }
  408. //Set owner of the new uploaded file
  409. userinfo.SetOwnerOfFile(targetUploadLocation)
  410. //Return complete signal
  411. c.WriteMessage(1, []byte("OK"))
  412. //Stop the timeout listner
  413. done <- true
  414. //Clear the tmp folder
  415. time.Sleep(1 * time.Second)
  416. err = os.RemoveAll(uploadFolder)
  417. if err != nil {
  418. log.Println(err)
  419. }
  420. //Close WebSocket connection after finished
  421. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  422. time.Sleep(1 * time.Second)
  423. c.Close()
  424. }
  425. /*
  426. Handle FORM POST based upload
  427. This function is design for general SBCs or computers with more than 1GB of RAM
  428. (e.g. Raspberry Pi 4 / Linux Server)
  429. */
  430. func system_fs_handleUpload(w http.ResponseWriter, r *http.Request) {
  431. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  432. if err != nil {
  433. sendErrorResponse(w, "User not logged in")
  434. return
  435. }
  436. username := userinfo.Username
  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: " + 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(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 := 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. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1144. if err != nil {
  1145. sendErrorResponse(w, "User not logged in")
  1146. return
  1147. }
  1148. operation, _ := mv(r, "opr", true)
  1149. vsrcFiles, _ := mv(r, "src", true)
  1150. vdestFile, _ := mv(r, "dest", true)
  1151. vnfilenames, _ := mv(r, "new", true) //Only use when rename or create new file / folder
  1152. //Check if operation valid.
  1153. if operation == "" {
  1154. //Undefined operations.
  1155. sendErrorResponse(w, "Undefined operations paramter: Missing 'opr' in request header.")
  1156. return
  1157. }
  1158. //As the user can pass in multiple source files at the same time, parse sourceFiles from json string
  1159. var sourceFiles []string
  1160. //This line is required in order to allow passing of special charaters
  1161. decodedSourceFiles := system_fs_specialURIDecode(vsrcFiles)
  1162. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  1163. if err != nil {
  1164. sendErrorResponse(w, "Source file JSON parse error.")
  1165. return
  1166. }
  1167. //Check if new filenames are also valid. If yes, translate it into string array
  1168. var newFilenames []string
  1169. if vnfilenames != "" {
  1170. vnfilenames, _ := url.QueryUnescape(vnfilenames)
  1171. err = json.Unmarshal([]byte(vnfilenames), &newFilenames)
  1172. if err != nil {
  1173. sendErrorResponse(w, "Unable to parse JSON for new filenames")
  1174. return
  1175. }
  1176. }
  1177. if operation == "zip" {
  1178. //Zip operation. Parse the real filepath list
  1179. rsrcFiles := []string{}
  1180. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1181. for _, vsrcFile := range sourceFiles {
  1182. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1183. if fileExists(rsrcFile) {
  1184. rsrcFiles = append(rsrcFiles, rsrcFile)
  1185. }
  1186. }
  1187. zipFilename := rdestFile
  1188. if fs.IsDir(rdestFile) {
  1189. //Append the filename to it
  1190. if len(rsrcFiles) == 1 {
  1191. zipFilename = filepath.Join(rdestFile, strings.TrimSuffix(filepath.Base(rsrcFiles[0]), filepath.Ext(filepath.Base(rsrcFiles[0])))+".zip")
  1192. } else if len(rsrcFiles) > 1 {
  1193. zipFilename = filepath.Join(rdestFile, filepath.Base(filepath.Dir(rsrcFiles[0]))+".zip")
  1194. }
  1195. }
  1196. //Create a zip file at target location
  1197. err := fs.ArozZipFile(rsrcFiles, zipFilename, false)
  1198. if err != nil {
  1199. sendErrorResponse(w, err.Error())
  1200. return
  1201. }
  1202. } else {
  1203. //For operations that is handled file by file
  1204. for i, vsrcFile := range sourceFiles {
  1205. //Convert the virtual path to realpath on disk
  1206. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1207. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1208. //Check if the source file exists
  1209. if !fileExists(rsrcFile) {
  1210. /*
  1211. Special edge case handler:
  1212. There might be edge case that files are stored in URIEncoded methods
  1213. e.g. abc def.mp3 --> abc%20cdf.mp3
  1214. In this case, this logic statement should be able to handle this
  1215. */
  1216. edgeCaseFilename := filepath.Join(filepath.Dir(rsrcFile), system_fs_specialURIEncode(filepath.Base(rsrcFile)))
  1217. if fileExists(edgeCaseFilename) {
  1218. rsrcFile = edgeCaseFilename
  1219. } else {
  1220. sendErrorResponse(w, "Source file not exists.")
  1221. return
  1222. }
  1223. }
  1224. if operation == "rename" {
  1225. //Check if the usage is correct.
  1226. if vdestFile != "" {
  1227. sendErrorResponse(w, "Rename only accept 'src' and 'new'. Please use move if you want to move a file.")
  1228. return
  1229. }
  1230. //Check if new name paramter is passed in.
  1231. if len(newFilenames) == 0 {
  1232. sendErrorResponse(w, "Missing paramter (JSON string): 'new'")
  1233. return
  1234. }
  1235. //Check if the source filenames and new filenanmes match
  1236. if len(newFilenames) != len(sourceFiles) {
  1237. sendErrorResponse(w, "New filenames do not match with source filename's length.")
  1238. return
  1239. }
  1240. //Check if the target dir is not readonly
  1241. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1242. if accmode == "readonly" {
  1243. sendErrorResponse(w, "This directory is Read Only.")
  1244. return
  1245. } else if accmode == "denied" {
  1246. sendErrorResponse(w, "Access Denied")
  1247. return
  1248. }
  1249. thisFilename := newFilenames[i]
  1250. //Check if the name already exists. If yes, return false
  1251. if fileExists(filepath.Dir(rsrcFile) + "/" + thisFilename) {
  1252. sendErrorResponse(w, "File already exists")
  1253. return
  1254. }
  1255. //Everything is ok. Rename the file.
  1256. targetNewName := filepath.Dir(rsrcFile) + "/" + thisFilename
  1257. err = os.Rename(rsrcFile, targetNewName)
  1258. if err != nil {
  1259. sendErrorResponse(w, err.Error())
  1260. return
  1261. }
  1262. } else if operation == "move" {
  1263. //File move operation. Check if the source file / dir and target directory exists
  1264. /*
  1265. Example usage from file explorer
  1266. $.ajax({
  1267. type: 'POST',
  1268. url: `/system/file_system/fileOpr`,
  1269. data: {opr: "move" ,src: JSON.stringify(fileList), dest: targetDir},
  1270. success: function(data){
  1271. if (data.error !== undefined){
  1272. msgbox("remove",data.error);
  1273. }else{
  1274. //OK, do something
  1275. }
  1276. }
  1277. });
  1278. */
  1279. if !fileExists(rsrcFile) {
  1280. sendErrorResponse(w, "Source file not exists")
  1281. return
  1282. }
  1283. //Check if the source file is read only.
  1284. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1285. if accmode == "readonly" {
  1286. sendErrorResponse(w, "This source file is Read Only.")
  1287. return
  1288. } else if accmode == "denied" {
  1289. sendErrorResponse(w, "Access Denied")
  1290. return
  1291. }
  1292. if rdestFile == "" {
  1293. sendErrorResponse(w, "Undefined dest location.")
  1294. return
  1295. }
  1296. //Get exists overwrite mode
  1297. existsOpr, _ := mv(r, "existsresp", true)
  1298. //Check if use fast move instead
  1299. //Check if the source and destination folder are under the same root. If yes, use os.Rename for faster move operations
  1300. underSameRoot := false
  1301. //Check if the two files are under the same user root path
  1302. srcAbs, _ := filepath.Abs(rsrcFile)
  1303. destAbs, _ := filepath.Abs(rdestFile)
  1304. //Check other storage path and see if they are under the same root
  1305. for _, rootPath := range userinfo.GetAllFileSystemHandler() {
  1306. thisRoot := rootPath.Path
  1307. thisRootAbs, err := filepath.Abs(thisRoot)
  1308. if err != nil {
  1309. continue
  1310. }
  1311. if strings.Contains(srcAbs, thisRootAbs) && strings.Contains(destAbs, thisRootAbs) {
  1312. underSameRoot = true
  1313. }
  1314. }
  1315. //Updates 19-10-2020: Added ownership management to file move and copy
  1316. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1317. err = fs.FileMove(rsrcFile, rdestFile, existsOpr, underSameRoot, nil)
  1318. if err != nil {
  1319. sendErrorResponse(w, err.Error())
  1320. //Restore the ownership if remove failed
  1321. userinfo.SetOwnerOfFile(rsrcFile)
  1322. return
  1323. }
  1324. //Set user to own the new file
  1325. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1326. } else if operation == "copy" {
  1327. //Copy file. See move example and change 'opr' to 'copy'
  1328. if !fileExists(rsrcFile) {
  1329. sendErrorResponse(w, "Source file not exists")
  1330. return
  1331. }
  1332. //Check if the desintation is read only.
  1333. if !userinfo.CanWrite(vdestFile) {
  1334. sendErrorResponse(w, "Access Denied.")
  1335. return
  1336. }
  1337. if !fileExists(rdestFile) {
  1338. if fileExists(filepath.Dir(rdestFile)) {
  1339. //User pass in the whole path for the folder. Report error usecase.
  1340. sendErrorResponse(w, "Dest location should be an existing folder instead of the full path of the copied file.")
  1341. return
  1342. }
  1343. sendErrorResponse(w, "Dest folder not found")
  1344. return
  1345. }
  1346. existsOpr, _ := mv(r, "existsresp", true)
  1347. //Check if the user have space for the extra file
  1348. if !userinfo.StorageQuota.HaveSpace(fs.GetFileSize(rdestFile)) {
  1349. sendErrorResponse(w, "Storage Quota Full")
  1350. return
  1351. }
  1352. err = fs.FileCopy(rsrcFile, rdestFile, existsOpr, nil)
  1353. if err != nil {
  1354. sendErrorResponse(w, err.Error())
  1355. return
  1356. }
  1357. //Set user to own this file
  1358. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1359. } else if operation == "delete" {
  1360. //Delete the file permanently
  1361. if !fileExists(rsrcFile) {
  1362. //Check if it is a non escapted file instead
  1363. sendErrorResponse(w, "Source file not exists")
  1364. return
  1365. }
  1366. //Check if the desintation is read only.
  1367. /*
  1368. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1369. if accmode == "readonly" {
  1370. sendErrorResponse(w, "This directory is Read Only.")
  1371. return
  1372. } else if accmode == "denied" {
  1373. sendErrorResponse(w, "Access Denied")
  1374. return
  1375. }
  1376. */
  1377. if !userinfo.CanWrite(vsrcFile) {
  1378. sendErrorResponse(w, "Access Denied.")
  1379. return
  1380. }
  1381. //Check if the user own this file
  1382. isOwner := userinfo.IsOwnerOfFile(rsrcFile)
  1383. if isOwner {
  1384. //This user own this system. Remove this file from his quota
  1385. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1386. }
  1387. //Check if this file has any cached files. If yes, remove it
  1388. if fileExists(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg") {
  1389. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg")
  1390. }
  1391. //Clear the cache folder if there is no files inside
  1392. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1393. if len(fc) == 0 {
  1394. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1395. }
  1396. os.RemoveAll(rsrcFile)
  1397. } else if operation == "recycle" {
  1398. //Put it into a subfolder named trash and allow it to to be removed later
  1399. if !fileExists(rsrcFile) {
  1400. //Check if it is a non escapted file instead
  1401. sendErrorResponse(w, "Source file not exists")
  1402. return
  1403. }
  1404. //Check if the upload target is read only.
  1405. //Updates 20 Jan 2021: Replace with CanWrite handler
  1406. /*
  1407. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1408. if accmode == "readonly" {
  1409. sendErrorResponse(w, "This directory is Read Only.")
  1410. return
  1411. } else if accmode == "denied" {
  1412. sendErrorResponse(w, "Access Denied")
  1413. return
  1414. }*/
  1415. if !userinfo.CanWrite(vsrcFile) {
  1416. sendErrorResponse(w, "Access Denied.")
  1417. return
  1418. }
  1419. //Check if this file has any cached files. If yes, remove it
  1420. if fileExists(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg") {
  1421. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/" + filepath.Base(rsrcFile) + ".jpg")
  1422. }
  1423. //Clear the cache folder if there is no files inside
  1424. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1425. if len(fc) == 0 {
  1426. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1427. }
  1428. //Create a trash directory for this folder
  1429. trashDir := filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.trash/"
  1430. os.MkdirAll(trashDir, 0755)
  1431. hidden.HideFile(trashDir)
  1432. os.Rename(rsrcFile, trashDir+filepath.Base(rsrcFile)+"."+Int64ToString(GetUnixTime()))
  1433. } else if operation == "unzip" {
  1434. //Unzip the file to destination
  1435. //Check if the user can write to the target dest file
  1436. if userinfo.CanWrite(string(vdestFile)) == false {
  1437. sendErrorResponse(w, "Access Denied.")
  1438. return
  1439. }
  1440. //Make the rdest directory if not exists
  1441. if !fileExists(rdestFile) {
  1442. err = os.MkdirAll(rdestFile, 0755)
  1443. if err != nil {
  1444. sendErrorResponse(w, err.Error())
  1445. return
  1446. }
  1447. }
  1448. //OK! Unzip to destination
  1449. err := fs.Unzip(rsrcFile, rdestFile)
  1450. if err != nil {
  1451. sendErrorResponse(w, err.Error())
  1452. return
  1453. }
  1454. } else {
  1455. sendErrorResponse(w, "Unknown file opeartion given.")
  1456. return
  1457. }
  1458. }
  1459. }
  1460. sendJSONResponse(w, "\"OK\"")
  1461. return
  1462. }
  1463. //Allow systems to store key value pairs in the database as preferences.
  1464. func system_fs_handleUserPreference(w http.ResponseWriter, r *http.Request) {
  1465. username, err := authAgent.GetUserName(w, r)
  1466. if err != nil {
  1467. sendErrorResponse(w, "User not logged in")
  1468. return
  1469. }
  1470. key, _ := mv(r, "key", false)
  1471. value, _ := mv(r, "value", false)
  1472. remove, _ := mv(r, "remove", false)
  1473. if key != "" && value == "" && remove == "" {
  1474. //Get mode. Read the prefernece with given key
  1475. result := ""
  1476. err := sysdb.Read("fs", "pref/"+key+"/"+username, &result)
  1477. if err != nil {
  1478. sendJSONResponse(w, "{\"error\":\"Key not found.\"}")
  1479. return
  1480. }
  1481. sendTextResponse(w, result)
  1482. } else if key != "" && value == "" && remove == "true" {
  1483. //Remove mode. Delete this key from sysdb
  1484. err := sysdb.Delete("fs", "pref/"+key+"/"+username)
  1485. if err != nil {
  1486. sendErrorResponse(w, err.Error())
  1487. }
  1488. sendOK(w)
  1489. } else if key != "" && value != "" {
  1490. //Set mode. Set the preference with given key
  1491. if len(value) > 1024 {
  1492. //Size too big. Reject storage
  1493. sendErrorResponse(w, "Preference value too long. Preference value can only store maximum 1024 characters.")
  1494. return
  1495. }
  1496. sysdb.Write("fs", "pref/"+key+"/"+username, value)
  1497. sendOK(w)
  1498. }
  1499. }
  1500. func system_fs_removeUserPreferences(username string) {
  1501. entries, err := sysdb.ListTable("fs")
  1502. if err != nil {
  1503. return
  1504. }
  1505. for _, keypairs := range entries {
  1506. if strings.Contains(string(keypairs[0]), "pref/") && strings.Contains(string(keypairs[0]), "/"+username) {
  1507. //Remove this preference
  1508. sysdb.Delete("fs", string(keypairs[0]))
  1509. }
  1510. }
  1511. }
  1512. func system_fs_listDrives(w http.ResponseWriter, r *http.Request) {
  1513. if authAgent.CheckAuth(r) == false {
  1514. sendErrorResponse(w, "User not logged in")
  1515. return
  1516. }
  1517. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1518. type driveInfo struct {
  1519. Drivepath string
  1520. DriveFreeSpace uint64
  1521. DriveTotalSpace uint64
  1522. DriveAvailSpace uint64
  1523. }
  1524. var drives []driveInfo
  1525. if runtime.GOOS == "windows" {
  1526. //Under windows
  1527. for _, drive := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
  1528. f, err := os.Open(string(drive) + ":\\")
  1529. if err == nil {
  1530. thisdrive := new(driveInfo)
  1531. thisdrive.Drivepath = string(drive) + ":\\"
  1532. free, total, avail := storage.GetDriveCapacity(string(drive) + ":\\")
  1533. thisdrive.DriveFreeSpace = free
  1534. thisdrive.DriveTotalSpace = total
  1535. thisdrive.DriveAvailSpace = avail
  1536. drives = append(drives, *thisdrive)
  1537. f.Close()
  1538. }
  1539. }
  1540. } else {
  1541. //Under linux environment
  1542. //Append all the virtual directories root as root instead
  1543. storageDevices := []string{}
  1544. for _, fshandler := range userinfo.GetAllFileSystemHandler() {
  1545. storageDevices = append(storageDevices, fshandler.Path)
  1546. }
  1547. //List all storage information of each devices
  1548. for _, dev := range storageDevices {
  1549. thisdrive := new(driveInfo)
  1550. thisdrive.Drivepath = filepath.Base(dev)
  1551. free, total, avail := storage.GetDriveCapacity(string(dev))
  1552. thisdrive.DriveFreeSpace = free
  1553. thisdrive.DriveTotalSpace = total
  1554. thisdrive.DriveAvailSpace = avail
  1555. drives = append(drives, *thisdrive)
  1556. }
  1557. }
  1558. jsonString, _ := json.Marshal(drives)
  1559. sendJSONResponse(w, string(jsonString))
  1560. }
  1561. func system_fs_listRoot(w http.ResponseWriter, r *http.Request) {
  1562. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1563. if err != nil {
  1564. sendErrorResponse(w, err.Error())
  1565. return
  1566. }
  1567. username := userinfo.Username
  1568. userRoot, _ := mv(r, "user", false)
  1569. if userRoot == "true" {
  1570. type fileObject struct {
  1571. Filename string
  1572. Filepath string
  1573. IsDir bool
  1574. }
  1575. //List the root media folders under user:/
  1576. filesInUserRoot := []fileObject{}
  1577. filesInRoot, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(*root_directory)) + "/users/" + username + "/*")
  1578. for _, file := range filesInRoot {
  1579. thisFile := new(fileObject)
  1580. thisFile.Filename = filepath.Base(file)
  1581. thisFile.Filepath, _ = userinfo.RealPathToVirtualPath(file)
  1582. thisFile.IsDir = IsDir(file)
  1583. filesInUserRoot = append(filesInUserRoot, *thisFile)
  1584. }
  1585. jsonString, _ := json.Marshal(filesInUserRoot)
  1586. sendJSONResponse(w, string(jsonString))
  1587. } else {
  1588. type rootObject struct {
  1589. RootName string
  1590. RootPath string
  1591. }
  1592. var roots []rootObject
  1593. for _, store := range userinfo.GetAllFileSystemHandler() {
  1594. var thisDevice = new(rootObject)
  1595. thisDevice.RootName = store.Name
  1596. thisDevice.RootPath = store.UUID + ":/"
  1597. roots = append(roots, *thisDevice)
  1598. }
  1599. jsonString, _ := json.Marshal(roots)
  1600. sendJSONResponse(w, string(jsonString))
  1601. }
  1602. }
  1603. /*
  1604. Special Glob for handling path with [ or ] inside.
  1605. You can also pass in normal path for globing if you are not sure.
  1606. */
  1607. func system_fs_specialGlob(path string) ([]string, error) {
  1608. files, err := filepath.Glob(path)
  1609. if err != nil {
  1610. return []string{}, err
  1611. }
  1612. if strings.Contains(path, "[") == true || strings.Contains(path, "]") == true {
  1613. if len(files) == 0 {
  1614. //Handle reverse check. Replace all [ and ] with *
  1615. newSearchPath := strings.ReplaceAll(path, "[", "?")
  1616. newSearchPath = strings.ReplaceAll(newSearchPath, "]", "?")
  1617. //Scan with all the similar structure except [ and ]
  1618. tmpFilelist, _ := filepath.Glob(newSearchPath)
  1619. for _, file := range tmpFilelist {
  1620. file = filepath.ToSlash(file)
  1621. if strings.Contains(file, filepath.ToSlash(filepath.Dir(path))) {
  1622. files = append(files, file)
  1623. }
  1624. }
  1625. }
  1626. }
  1627. //Convert all filepaths to slash
  1628. for i := 0; i < len(files); i++ {
  1629. files[i] = filepath.ToSlash(files[i])
  1630. }
  1631. return files, nil
  1632. }
  1633. func system_fs_specialURIDecode(inputPath string) string {
  1634. inputPath = strings.ReplaceAll(inputPath, "+", "{{plus_sign}}")
  1635. inputPath, _ = url.QueryUnescape(inputPath)
  1636. inputPath = strings.ReplaceAll(inputPath, "{{plus_sign}}", "+")
  1637. return inputPath
  1638. }
  1639. func system_fs_specialURIEncode(inputPath string) string {
  1640. inputPath = strings.ReplaceAll(inputPath, " ", "{{space_sign}}")
  1641. inputPath, _ = url.QueryUnescape(inputPath)
  1642. inputPath = strings.ReplaceAll(inputPath, "{{space_sign}}", "%20")
  1643. return inputPath
  1644. }
  1645. func system_fs_matchFileExt(inputFilename string, extArray []string) bool {
  1646. inputExt := filepath.Ext(inputFilename)
  1647. if stringInSlice(inputExt, extArray) {
  1648. return true
  1649. }
  1650. return false
  1651. }
  1652. //Handle file properties request
  1653. func system_fs_getFileProperties(w http.ResponseWriter, r *http.Request) {
  1654. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1655. if err != nil {
  1656. sendErrorResponse(w, err.Error())
  1657. return
  1658. }
  1659. vpath, err := mv(r, "path", true)
  1660. if err != nil {
  1661. sendErrorResponse(w, "path not defined")
  1662. return
  1663. }
  1664. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  1665. if err != nil {
  1666. sendErrorResponse(w, err.Error())
  1667. return
  1668. }
  1669. fileStat, err := os.Stat(rpath)
  1670. if err != nil {
  1671. sendErrorResponse(w, err.Error())
  1672. return
  1673. }
  1674. type fileProperties struct {
  1675. VirtualPath string
  1676. StoragePath string
  1677. Basename string
  1678. VirtualDirname string
  1679. StorageDirname string
  1680. Ext string
  1681. MimeType string
  1682. Filesize int64
  1683. Permission string
  1684. LastModTime string
  1685. LastModUnix int64
  1686. IsDirectory bool
  1687. Owner string
  1688. }
  1689. mime := "text/directory"
  1690. if !fileStat.IsDir() {
  1691. m, _, err := fs.GetMime(rpath)
  1692. if err != nil {
  1693. mime = ""
  1694. }
  1695. mime = m
  1696. }
  1697. filesize := fileStat.Size()
  1698. //Get file overall size if this is folder
  1699. if fileStat.IsDir() {
  1700. var size int64
  1701. filepath.Walk(rpath, func(_ string, info os.FileInfo, err error) error {
  1702. if err != nil {
  1703. return err
  1704. }
  1705. if !info.IsDir() {
  1706. size += info.Size()
  1707. }
  1708. return err
  1709. })
  1710. filesize = size
  1711. }
  1712. //Get file owner
  1713. owner := userinfo.GetFileOwner(rpath)
  1714. if owner == "" {
  1715. owner = "Unknown"
  1716. }
  1717. result := fileProperties{
  1718. VirtualPath: vpath,
  1719. StoragePath: filepath.Clean(rpath),
  1720. Basename: filepath.Base(rpath),
  1721. VirtualDirname: filepath.ToSlash(filepath.Dir(vpath)),
  1722. StorageDirname: filepath.ToSlash(filepath.Dir(rpath)),
  1723. Ext: filepath.Ext(rpath),
  1724. MimeType: mime,
  1725. Filesize: filesize,
  1726. Permission: fileStat.Mode().Perm().String(),
  1727. LastModTime: timeToString(fileStat.ModTime()),
  1728. LastModUnix: fileStat.ModTime().Unix(),
  1729. IsDirectory: fileStat.IsDir(),
  1730. Owner: owner,
  1731. }
  1732. jsonString, _ := json.Marshal(result)
  1733. sendJSONResponse(w, string(jsonString))
  1734. }
  1735. /*
  1736. List directory in the given path
  1737. Usage: Pass in dir like the following examples:
  1738. AOR:/Desktop <= Open /user/{username}/Desktop
  1739. S1:/ <= Open {uuid=S1}/
  1740. */
  1741. func system_fs_handleList(w http.ResponseWriter, r *http.Request) {
  1742. currentDir, _ := mv(r, "dir", true)
  1743. //Commented this line to handle dirname that contains "+" sign
  1744. //currentDir, _ = url.QueryUnescape(currentDir)
  1745. sortMode, _ := mv(r, "sort", true)
  1746. showHidden, _ := mv(r, "showHidden", true)
  1747. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1748. if err != nil {
  1749. //user not logged in. Redirect to login page.
  1750. sendErrorResponse(w, "User not logged in")
  1751. return
  1752. }
  1753. if currentDir == "" {
  1754. sendErrorResponse(w, "Invalid dir given.")
  1755. return
  1756. }
  1757. //Pad a slash at the end of currentDir if not exists
  1758. if currentDir[len(currentDir)-1:] != "/" {
  1759. currentDir = currentDir + "/"
  1760. }
  1761. //Convert the virutal path to realpath
  1762. realpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1763. if err != nil {
  1764. sendErrorResponse(w, "Error. Unable to parse path. "+err.Error())
  1765. return
  1766. }
  1767. if !fileExists(realpath) {
  1768. userRoot, _ := userinfo.VirtualPathToRealPath("user:/")
  1769. if filepath.Clean(realpath) == filepath.Clean(userRoot) {
  1770. //Initiate user folder (Initiaed in user object)
  1771. userinfo.GetHomeDirectory()
  1772. } else {
  1773. //Folder not exists
  1774. sendJSONResponse(w, "{\"error\":\"Folder not exists\"}")
  1775. return
  1776. }
  1777. }
  1778. if sortMode == "" {
  1779. sortMode = "default"
  1780. }
  1781. //Check for really special exception in where the path contains [ or ] which cannot be handled via Golang Glob function
  1782. files, _ := system_fs_specialGlob(filepath.Clean(realpath) + "/*")
  1783. var parsedFilelist []fs.FileData
  1784. for _, v := range files {
  1785. if showHidden != "true" && filepath.Base(v)[:1] == "." {
  1786. //Skipping hidden files
  1787. continue
  1788. }
  1789. rawsize := fs.GetFileSize(v)
  1790. modtime, _ := fs.GetModTime(v)
  1791. thisFile := fs.FileData{
  1792. Filename: filepath.Base(v),
  1793. Filepath: currentDir + filepath.Base(v),
  1794. Realpath: v,
  1795. IsDir: IsDir(v),
  1796. Filesize: rawsize,
  1797. Displaysize: fs.GetFileDisplaySize(rawsize, 2),
  1798. ModTime: modtime,
  1799. IsShared: shareManager.FileIsShared(v),
  1800. }
  1801. parsedFilelist = append(parsedFilelist, thisFile)
  1802. }
  1803. //Sort the filelist
  1804. if sortMode == "default" {
  1805. //Sort by name, convert filename to window sorting methods
  1806. sort.Slice(parsedFilelist, func(i, j int) bool {
  1807. return strings.ToLower(parsedFilelist[i].Filename) < strings.ToLower(parsedFilelist[j].Filename)
  1808. })
  1809. } else if sortMode == "reverse" {
  1810. //Sort by reverse name
  1811. sort.Slice(parsedFilelist, func(i, j int) bool {
  1812. return strings.ToLower(parsedFilelist[i].Filename) > strings.ToLower(parsedFilelist[j].Filename)
  1813. })
  1814. } else if sortMode == "smallToLarge" {
  1815. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize < parsedFilelist[j].Filesize })
  1816. } else if sortMode == "largeToSmall" {
  1817. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize > parsedFilelist[j].Filesize })
  1818. } else if sortMode == "mostRecent" {
  1819. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime > parsedFilelist[j].ModTime })
  1820. } else if sortMode == "leastRecent" {
  1821. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime < parsedFilelist[j].ModTime })
  1822. }
  1823. jsonString, _ := json.Marshal(parsedFilelist)
  1824. sendJSONResponse(w, string(jsonString))
  1825. }
  1826. //Handle getting a hash from a given contents in the given path
  1827. func system_fs_handleDirHash(w http.ResponseWriter, r *http.Request) {
  1828. currentDir, err := mv(r, "dir", true)
  1829. if err != nil {
  1830. sendErrorResponse(w, "Invalid dir given")
  1831. return
  1832. }
  1833. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1834. if err != nil {
  1835. sendErrorResponse(w, "User not logged in")
  1836. return
  1837. }
  1838. rpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1839. if err != nil {
  1840. sendErrorResponse(w, "Invalid dir given")
  1841. return
  1842. }
  1843. //Get a list of files in this directory
  1844. currentDir = filepath.ToSlash(filepath.Clean(rpath)) + "/"
  1845. filesInDir, err := system_fs_specialGlob(currentDir + "*")
  1846. if err != nil {
  1847. sendErrorResponse(w, err.Error())
  1848. return
  1849. }
  1850. filenames := []string{}
  1851. for _, file := range filesInDir {
  1852. if len(filepath.Base(file)) > 0 && string([]rune(filepath.Base(file))[0]) != "." {
  1853. //Ignore hidden files
  1854. filenames = append(filenames, filepath.Base(file))
  1855. }
  1856. }
  1857. sort.Strings(filenames)
  1858. //Build a hash base on the filelist
  1859. h := sha256.New()
  1860. h.Write([]byte(strings.Join(filenames, ",")))
  1861. sendTextResponse(w, hex.EncodeToString((h.Sum(nil))))
  1862. }
  1863. /*
  1864. File zipping and unzipping functions
  1865. */
  1866. //Handle all zip related API
  1867. func system_fs_zipHandler(w http.ResponseWriter, r *http.Request) {
  1868. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1869. if err != nil {
  1870. sendErrorResponse(w, err.Error())
  1871. return
  1872. }
  1873. opr, err := mv(r, "opr", true)
  1874. if err != nil {
  1875. sendErrorResponse(w, "Invalid opr or opr not defined")
  1876. return
  1877. }
  1878. vsrc, _ := mv(r, "src", true)
  1879. if vsrc == "" {
  1880. sendErrorResponse(w, "Invalid src paramter")
  1881. return
  1882. }
  1883. vdest, _ := mv(r, "dest", true)
  1884. rdest := ""
  1885. //Convert source path from JSON string to object
  1886. virtualSourcePaths := []string{}
  1887. err = json.Unmarshal([]byte(vsrc), &virtualSourcePaths)
  1888. if err != nil {
  1889. sendErrorResponse(w, err.Error())
  1890. return
  1891. }
  1892. //Check each of the path
  1893. realSourcePaths := []string{}
  1894. for _, vpath := range virtualSourcePaths {
  1895. thisrpath, err := userinfo.VirtualPathToRealPath(vpath)
  1896. if err != nil || !fileExists(thisrpath) {
  1897. sendErrorResponse(w, "File not exists: "+vpath)
  1898. return
  1899. }
  1900. realSourcePaths = append(realSourcePaths, thisrpath)
  1901. }
  1902. ///Convert dest to real if given
  1903. if vdest != "" {
  1904. realdest, _ := userinfo.VirtualPathToRealPath(vdest)
  1905. rdest = realdest
  1906. }
  1907. //This function will be deprecate soon in ArozOS 1.120
  1908. log.Println("*DEPRECATE* zipHandler will be deprecating soon! Please use fileOpr endpoint")
  1909. if opr == "zip" {
  1910. //Check if destination location exists
  1911. if rdest == "" || !fileExists(filepath.Dir(rdest)) {
  1912. sendErrorResponse(w, "Invalid dest location")
  1913. return
  1914. }
  1915. //OK. Create the zip at the desired location
  1916. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  1917. if err != nil {
  1918. sendErrorResponse(w, err.Error())
  1919. return
  1920. }
  1921. sendOK(w)
  1922. } else if opr == "tmpzip" {
  1923. //Zip to tmp folder
  1924. userTmpFolder, _ := userinfo.VirtualPathToRealPath("tmp:/")
  1925. filename := Int64ToString(GetUnixTime()) + ".zip"
  1926. rdest := filepath.ToSlash(filepath.Clean(userTmpFolder)) + "/" + filename
  1927. log.Println(realSourcePaths, rdest)
  1928. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  1929. if err != nil {
  1930. sendErrorResponse(w, err.Error())
  1931. return
  1932. }
  1933. //Send the tmp filename to the user
  1934. sendTextResponse(w, "tmp:/"+filename)
  1935. } else if opr == "inspect" {
  1936. } else if opr == "unzip" {
  1937. }
  1938. }
  1939. //Translate path from and to virtual and realpath
  1940. func system_fs_handlePathTranslate(w http.ResponseWriter, r *http.Request) {
  1941. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1942. if err != nil {
  1943. sendErrorResponse(w, err.Error())
  1944. return
  1945. }
  1946. path, err := mv(r, "path", false)
  1947. if err != nil {
  1948. sendErrorResponse(w, "Invalid path given")
  1949. return
  1950. }
  1951. rpath, err := userinfo.VirtualPathToRealPath(path)
  1952. if err != nil {
  1953. //Try to convert it to virtualPath
  1954. vpath, err := userinfo.RealPathToVirtualPath(path)
  1955. if err != nil {
  1956. sendErrorResponse(w, "Unknown path given")
  1957. } else {
  1958. jsonstring, _ := json.Marshal(vpath)
  1959. sendJSONResponse(w, string(jsonstring))
  1960. }
  1961. } else {
  1962. abrpath, _ := filepath.Abs(rpath)
  1963. jsonstring, _ := json.Marshal([]string{rpath, filepath.ToSlash(abrpath)})
  1964. sendJSONResponse(w, string(jsonstring))
  1965. }
  1966. }
  1967. //Handle cache rendering with websocket pipeline
  1968. func system_fs_handleCacheRender(w http.ResponseWriter, r *http.Request) {
  1969. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1970. vpath, err := mv(r, "folder", false)
  1971. if err != nil {
  1972. sendErrorResponse(w, "Invalid folder paramter")
  1973. return
  1974. }
  1975. //Convert vpath to realpath
  1976. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  1977. if err != nil {
  1978. sendErrorResponse(w, err.Error())
  1979. return
  1980. }
  1981. //Perform cache rendering
  1982. thumbRenderHandler.HandleLoadCache(w, r, rpath)
  1983. }
  1984. //Handle file thumbnail caching
  1985. func system_fs_handleFolderCache(w http.ResponseWriter, r *http.Request) {
  1986. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1987. vfolderpath, err := mv(r, "folder", false)
  1988. if err != nil {
  1989. sendErrorResponse(w, "folder not defined")
  1990. return
  1991. }
  1992. rpath, err := userinfo.VirtualPathToRealPath(vfolderpath)
  1993. if err != nil {
  1994. sendErrorResponse(w, err.Error())
  1995. return
  1996. }
  1997. thumbRenderHandler.BuildCacheForFolder(rpath)
  1998. sendOK(w)
  1999. }
  2000. //Handle setting and loading of file permission on Linux
  2001. func system_fs_handleFilePermission(w http.ResponseWriter, r *http.Request) {
  2002. file, err := mv(r, "file", true)
  2003. if err != nil {
  2004. sendErrorResponse(w, "Invalid file")
  2005. return
  2006. }
  2007. //Translate the file to real path
  2008. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2009. if err != nil {
  2010. sendErrorResponse(w, "User not logged in")
  2011. return
  2012. }
  2013. rpath, err := userinfo.VirtualPathToRealPath(file)
  2014. if err != nil {
  2015. sendErrorResponse(w, err.Error())
  2016. return
  2017. }
  2018. newMode, _ := mv(r, "mode", true)
  2019. if newMode == "" {
  2020. //Read the file mode
  2021. //Check if the file exists
  2022. if !fileExists(rpath) {
  2023. sendErrorResponse(w, "File not exists!")
  2024. return
  2025. }
  2026. //Read the file permission
  2027. filePermission, err := fsp.GetFilePermissions(rpath)
  2028. if err != nil {
  2029. sendErrorResponse(w, err.Error())
  2030. return
  2031. }
  2032. //Send the file permission to client
  2033. js, _ := json.Marshal(filePermission)
  2034. sendJSONResponse(w, string(js))
  2035. } else {
  2036. //Set the file mode
  2037. //Check if the file exists
  2038. if !fileExists(rpath) {
  2039. sendErrorResponse(w, "File not exists!")
  2040. return
  2041. }
  2042. //Check if windows. If yes, ignore this request
  2043. if runtime.GOOS == "windows" {
  2044. sendErrorResponse(w, "Windows host not supported")
  2045. return
  2046. }
  2047. //Check if this user has permission to change the file permission
  2048. //Aka user must be 1. This is his own folder or 2. Admin
  2049. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(file)
  2050. if fsh.Hierarchy == "user" {
  2051. //Always ok as this is owned by the user
  2052. } else if fsh.Hierarchy == "public" {
  2053. //Require admin
  2054. if userinfo.IsAdmin() == false {
  2055. sendErrorResponse(w, "Permission Denied")
  2056. return
  2057. }
  2058. } else {
  2059. //Not implemeneted. Require admin
  2060. if userinfo.IsAdmin() == false {
  2061. sendErrorResponse(w, "Permission Denied")
  2062. return
  2063. }
  2064. }
  2065. //Be noted that if the system is not running in sudo mode,
  2066. //File permission change might not works.
  2067. err := fsp.SetFilePermisson(rpath, newMode)
  2068. if err != nil {
  2069. sendErrorResponse(w, err.Error())
  2070. return
  2071. } else {
  2072. sendOK(w)
  2073. }
  2074. }
  2075. }
  2076. //Check if the given filepath is and must inside the given directory path.
  2077. //You can pass both as relative
  2078. func system_fs_checkFileInDirectory(filesourcepath string, directory string) bool {
  2079. filepathAbs, err := filepath.Abs(filesourcepath)
  2080. if err != nil {
  2081. return false
  2082. }
  2083. directoryAbs, err := filepath.Abs(directory)
  2084. if err != nil {
  2085. return false
  2086. }
  2087. //Check if the filepathabs contain directoryAbs
  2088. if strings.Contains(filepathAbs, directoryAbs) {
  2089. return true
  2090. } else {
  2091. return false
  2092. }
  2093. }
  2094. //Clear the old files inside the tmp file
  2095. func system_fs_clearOldTmpFiles() {
  2096. filesToBeDelete := []string{}
  2097. tmpAbs, _ := filepath.Abs(*tmp_directory)
  2098. filepath.Walk(*tmp_directory, func(path string, info os.FileInfo, err error) error {
  2099. if filepath.Base(path) != "aofs.db" && filepath.Base(path) != "aofs.db.lock" {
  2100. //Check if root folders. Do not delete root folders
  2101. parentAbs, _ := filepath.Abs(filepath.Dir(path))
  2102. if tmpAbs == parentAbs {
  2103. //Root folder. Do not remove
  2104. return nil
  2105. }
  2106. //Get its modification time
  2107. modTime, err := fs.GetModTime(path)
  2108. if err != nil {
  2109. return nil
  2110. }
  2111. //Check if mod time is more than 24 hours ago
  2112. if time.Now().Unix()-modTime > int64(*maxTempFileKeepTime) {
  2113. //Delete OK
  2114. filesToBeDelete = append(filesToBeDelete, path)
  2115. }
  2116. }
  2117. return nil
  2118. })
  2119. //Remove all files from the delete list
  2120. for _, fileToBeDelete := range filesToBeDelete {
  2121. os.RemoveAll(fileToBeDelete)
  2122. }
  2123. }