file_system.go 94 KB

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