file_system.go 93 KB

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