file_system.go 95 KB

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