file_system.go 95 KB

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