file_system.go 94 KB

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