file_system.go 95 KB

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