file_system.go 104 KB

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