file_system.go 93 KB

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