file_system.go 105 KB

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