file_system.go 94 KB

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