file_system.go 98 KB

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