file_system.go 74 KB

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