file_system.go 93 KB

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