file_system.go 105 KB

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