file_system.go 96 KB

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