file_system.go 105 KB

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