file_system.go 101 KB

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