file_system.go 94 KB

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