file_system.go 74 KB

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