file_system.go 94 KB

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