file_system.go 97 KB

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