file_system.go 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689
  1. package main
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "io"
  8. "io/ioutil"
  9. "log"
  10. "math"
  11. "mime/multipart"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "path/filepath"
  16. "runtime"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/gorilla/websocket"
  22. uuid "github.com/satori/go.uuid"
  23. "imuslab.com/arozos/mod/compatibility"
  24. "imuslab.com/arozos/mod/disk/hybridBackup"
  25. fs "imuslab.com/arozos/mod/filesystem"
  26. fsp "imuslab.com/arozos/mod/filesystem/fspermission"
  27. hidden "imuslab.com/arozos/mod/filesystem/hidden"
  28. metadata "imuslab.com/arozos/mod/filesystem/metadata"
  29. "imuslab.com/arozos/mod/filesystem/shortcut"
  30. module "imuslab.com/arozos/mod/modules"
  31. prout "imuslab.com/arozos/mod/prouter"
  32. "imuslab.com/arozos/mod/share"
  33. storage "imuslab.com/arozos/mod/storage"
  34. user "imuslab.com/arozos/mod/user"
  35. )
  36. var (
  37. thumbRenderHandler *metadata.RenderHandler
  38. shareManager *share.Manager
  39. )
  40. type trashedFile struct {
  41. Filename string
  42. Filepath string
  43. FileExt string
  44. IsDir bool
  45. Filesize int64
  46. RemoveTimestamp int64
  47. RemoveDate string
  48. OriginalPath string
  49. OriginalFilename string
  50. }
  51. func FileSystemInit() {
  52. router := prout.NewModuleRouter(prout.RouterOption{
  53. ModuleName: "File Manager",
  54. AdminOnly: false,
  55. UserHandler: userHandler,
  56. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  57. sendErrorResponse(w, "Permission Denied")
  58. },
  59. })
  60. //Upload related functions
  61. router.HandleFunc("/system/file_system/upload", system_fs_handleUpload)
  62. router.HandleFunc("/system/file_system/lowmemUpload", system_fs_handleLowMemoryUpload)
  63. //Other file operations
  64. router.HandleFunc("/system/file_system/validateFileOpr", system_fs_validateFileOpr)
  65. router.HandleFunc("/system/file_system/fileOpr", system_fs_handleOpr)
  66. router.HandleFunc("/system/file_system/ws/fileOpr", system_fs_handleWebSocketOpr)
  67. router.HandleFunc("/system/file_system/listDir", system_fs_handleList)
  68. router.HandleFunc("/system/file_system/listDirHash", system_fs_handleDirHash)
  69. router.HandleFunc("/system/file_system/listRoots", system_fs_listRoot)
  70. router.HandleFunc("/system/file_system/listDrives", system_fs_listDrives)
  71. router.HandleFunc("/system/file_system/newItem", system_fs_handleNewObjects)
  72. router.HandleFunc("/system/file_system/preference", system_fs_handleUserPreference)
  73. router.HandleFunc("/system/file_system/listTrash", system_fs_scanTrashBin)
  74. router.HandleFunc("/system/file_system/ws/listTrash", system_fs_WebSocketScanTrashBin)
  75. router.HandleFunc("/system/file_system/clearTrash", system_fs_clearTrashBin)
  76. router.HandleFunc("/system/file_system/restoreTrash", system_fs_restoreFile)
  77. router.HandleFunc("/system/file_system/zipHandler", system_fs_zipHandler)
  78. router.HandleFunc("/system/file_system/getProperties", system_fs_getFileProperties)
  79. router.HandleFunc("/system/file_system/pathTranslate", system_fs_handlePathTranslate)
  80. router.HandleFunc("/system/file_system/handleFilePermission", system_fs_handleFilePermission)
  81. router.HandleFunc("/system/file_system/search", system_fs_handleFileSearch)
  82. //Thumbnail caching functions
  83. router.HandleFunc("/system/file_system/handleFolderCache", system_fs_handleFolderCache)
  84. router.HandleFunc("/system/file_system/handleCacheRender", system_fs_handleCacheRender)
  85. router.HandleFunc("/system/file_system/loadThumbnail", system_fs_handleThumbnailLoad)
  86. //Directory specific config
  87. router.HandleFunc("/system/file_system/sortMode", system_fs_handleFolderSortModePreference)
  88. //Register the module
  89. moduleHandler.RegisterModule(module.ModuleInfo{
  90. Name: "File Manager",
  91. Group: "System Tools",
  92. IconPath: "SystemAO/file_system/img/small_icon.png",
  93. Version: "1.0",
  94. StartDir: "SystemAO/file_system/file_explorer.html",
  95. SupportFW: true,
  96. InitFWSize: []int{1080, 580},
  97. LaunchFWDir: "SystemAO/file_system/file_explorer.html",
  98. SupportEmb: false,
  99. })
  100. //Register the Trashbin module
  101. moduleHandler.RegisterModule(module.ModuleInfo{
  102. Name: "Trash Bin",
  103. Group: "System Tools",
  104. IconPath: "SystemAO/file_system/trashbin_img/small_icon.png",
  105. Version: "1.0",
  106. StartDir: "SystemAO/file_system/trashbin.html",
  107. SupportFW: true,
  108. InitFWSize: []int{1080, 580},
  109. LaunchFWDir: "SystemAO/file_system/trashbin.html",
  110. SupportEmb: false,
  111. SupportedExt: []string{"*"},
  112. })
  113. //Register the Zip Extractor module
  114. moduleHandler.RegisterModule(module.ModuleInfo{
  115. Name: "Zip Extractor",
  116. Group: "System Tools",
  117. IconPath: "SystemAO/file_system/img/zip_extractor.png",
  118. Version: "1.0",
  119. SupportFW: false,
  120. LaunchEmb: "SystemAO/file_system/zip_extractor.html",
  121. SupportEmb: true,
  122. InitEmbSize: []int{260, 120},
  123. SupportedExt: []string{".zip"},
  124. })
  125. //Create user root if not exists
  126. err := os.MkdirAll(*root_directory+"users/", 0755)
  127. if err != nil {
  128. log.Println("Failed to create system storage root.")
  129. panic(err)
  130. }
  131. //Create database table if not exists
  132. err = sysdb.NewTable("fs")
  133. if err != nil {
  134. log.Println("Failed to create table for file system")
  135. panic(err)
  136. }
  137. //Create new table for sort preference
  138. err = sysdb.NewTable("fs-sortpref")
  139. if err != nil {
  140. log.Println("Failed to create table for file system")
  141. panic(err)
  142. }
  143. //Create a RenderHandler for caching thumbnails
  144. thumbRenderHandler = metadata.NewRenderHandler()
  145. /*
  146. Share Related Registering
  147. This section of functions create and register the file share service
  148. for the arozos
  149. */
  150. //Create a share manager to handle user file sharae
  151. shareManager = share.NewShareManager(share.Options{
  152. AuthAgent: authAgent,
  153. Database: sysdb,
  154. UserHandler: userHandler,
  155. HostName: *host_name,
  156. TmpFolder: *tmp_directory,
  157. })
  158. //Share related functions
  159. router.HandleFunc("/system/file_system/share/new", shareManager.HandleCreateNewShare)
  160. router.HandleFunc("/system/file_system/share/delete", shareManager.HandleDeleteShare)
  161. router.HandleFunc("/system/file_system/share/edit", shareManager.HandleEditShare)
  162. router.HandleFunc("/system/file_system/share/checkShared", shareManager.HandleShareCheck)
  163. //Handle the main share function
  164. //Share function is now routed by the main router
  165. //http.HandleFunc("/share", shareManager.HandleShareAccess)
  166. /*
  167. Nighly Tasks
  168. These functions allow file system to clear and maintain
  169. the arozos file system when no one is using the system
  170. */
  171. //Clear tmp folder if files is placed here too long
  172. nightlyManager.RegisterNightlyTask(system_fs_clearOldTmpFiles)
  173. //Clear shares that its parent file no longer exists in the system
  174. shareManager.ValidateAndClearShares()
  175. nightlyManager.RegisterNightlyTask(shareManager.ValidateAndClearShares)
  176. }
  177. /*
  178. File Search
  179. Handle file search in wildcard and recursive search
  180. */
  181. func system_fs_handleFileSearch(w http.ResponseWriter, r *http.Request) {
  182. //Get the user information
  183. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  184. if err != nil {
  185. sendErrorResponse(w, "User not logged in")
  186. return
  187. }
  188. //Get the search target root path
  189. vpath, err := mv(r, "path", true)
  190. if err != nil {
  191. sendErrorResponse(w, "Invalid vpath given")
  192. return
  193. }
  194. keyword, err := mv(r, "keyword", true)
  195. if err != nil {
  196. sendErrorResponse(w, "Invalid keyword given")
  197. return
  198. }
  199. //Check if case sensitive is enabled
  200. casesensitve, _ := mv(r, "casesensitive", true)
  201. //Translate the vpath to realpath
  202. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  203. if err != nil {
  204. sendErrorResponse(w, "Invalid path given")
  205. return
  206. }
  207. //Check if the search mode is recursive keyword or wildcard
  208. if len(keyword) > 1 && keyword[:1] == "/" {
  209. //Wildcard
  210. wildcard := keyword[1:]
  211. matchingFiles, err := filepath.Glob(filepath.Join(rpath, wildcard))
  212. if err != nil {
  213. sendErrorResponse(w, err.Error())
  214. return
  215. }
  216. //Prepare result struct
  217. results := []fs.FileData{}
  218. //Process the matching files. Do not allow directory escape
  219. srcAbs, _ := filepath.Abs(rpath)
  220. srcAbs = filepath.ToSlash(srcAbs)
  221. escaped := false
  222. for _, matchedFile := range matchingFiles {
  223. absMatch, _ := filepath.Abs(matchedFile)
  224. absMatch = filepath.ToSlash(absMatch)
  225. if !strings.Contains(absMatch, srcAbs) {
  226. escaped = true
  227. }
  228. thisVpath, _ := userinfo.RealPathToVirtualPath(matchedFile)
  229. results = append(results, fs.GetFileDataFromPath(thisVpath, matchedFile, 2))
  230. }
  231. if escaped {
  232. sendErrorResponse(w, "Search keywords contain escape character!")
  233. return
  234. }
  235. //OK. Tidy up the results
  236. js, _ := json.Marshal(results)
  237. sendJSONResponse(w, string(js))
  238. } else {
  239. //Recursive keyword
  240. results := []fs.FileData{}
  241. var err error = nil
  242. if casesensitve == "true" {
  243. //Require case sensitive match
  244. err = filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  245. if strings.Contains(filepath.Base(path), keyword) {
  246. //This is a matching file
  247. if !fs.IsInsideHiddenFolder(path) {
  248. thisVpath, _ := userinfo.RealPathToVirtualPath(path)
  249. results = append(results, fs.GetFileDataFromPath(thisVpath, path, 2))
  250. }
  251. }
  252. return nil
  253. })
  254. } else {
  255. //Require general match
  256. keywordLower := strings.ToLower(keyword)
  257. err = filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  258. if strings.Contains(strings.ToLower(filepath.Base(path)), keywordLower) {
  259. //This is a matching file
  260. if !fs.IsInsideHiddenFolder(path) {
  261. thisVpath, _ := userinfo.RealPathToVirtualPath(path)
  262. results = append(results, fs.GetFileDataFromPath(thisVpath, path, 2))
  263. }
  264. }
  265. return nil
  266. })
  267. }
  268. if err != nil {
  269. sendErrorResponse(w, err.Error())
  270. return
  271. }
  272. //OK. Tidy up the results
  273. js, _ := json.Marshal(results)
  274. sendJSONResponse(w, string(js))
  275. }
  276. }
  277. /*
  278. Handle low-memory upload operations
  279. This function is specailly designed to work with low memory devices
  280. (e.g. ZeroPi / Orange Pi Zero with 512MB RAM)
  281. */
  282. func system_fs_handleLowMemoryUpload(w http.ResponseWriter, r *http.Request) {
  283. //Get user info
  284. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  285. if err != nil {
  286. w.WriteHeader(http.StatusUnauthorized)
  287. w.Write([]byte("401 - Unauthorized"))
  288. return
  289. }
  290. //Get filename and upload path
  291. filename, err := mv(r, "filename", false)
  292. if filename == "" || err != nil {
  293. w.WriteHeader(http.StatusInternalServerError)
  294. w.Write([]byte("500 - Invalid filename given"))
  295. return
  296. }
  297. //Get upload target directory
  298. uploadTarget, err := mv(r, "path", false)
  299. if uploadTarget == "" || err != nil {
  300. w.WriteHeader(http.StatusInternalServerError)
  301. w.Write([]byte("500 - Invalid path given"))
  302. return
  303. }
  304. //Check if the user can write to this folder
  305. if !userinfo.CanWrite(uploadTarget) {
  306. //No permission
  307. w.WriteHeader(http.StatusForbidden)
  308. w.Write([]byte("403 - Access Denied"))
  309. return
  310. }
  311. //Translate the upload target directory
  312. realUploadPath, err := userinfo.VirtualPathToRealPath(uploadTarget)
  313. if err != nil {
  314. w.WriteHeader(http.StatusInternalServerError)
  315. w.Write([]byte("500 - Path translation failed"))
  316. return
  317. }
  318. //Generate an UUID for this upload
  319. uploadUUID := uuid.NewV4().String()
  320. uploadFolder := filepath.Join(*tmp_directory, "uploads", uploadUUID)
  321. os.MkdirAll(uploadFolder, 0700)
  322. targetUploadLocation := filepath.Join(realUploadPath, filename)
  323. if !fileExists(realUploadPath) {
  324. os.MkdirAll(realUploadPath, 0755)
  325. }
  326. //Start websocket connection
  327. var upgrader = websocket.Upgrader{}
  328. c, err := upgrader.Upgrade(w, r, nil)
  329. if err != nil {
  330. log.Println("Failed to upgrade websocket connection: ", err.Error())
  331. w.WriteHeader(http.StatusInternalServerError)
  332. w.Write([]byte("500 WebSocket upgrade failed"))
  333. return
  334. }
  335. defer c.Close()
  336. //Handle WebSocket upload
  337. blockCounter := 0
  338. chunkName := []string{}
  339. lastChunkArrivalTime := time.Now().Unix()
  340. //Setup a timeout listener, check if connection still active every 1 minute
  341. ticker := time.NewTicker(60 * time.Second)
  342. done := make(chan bool)
  343. go func() {
  344. for {
  345. select {
  346. case <-done:
  347. return
  348. case <-ticker.C:
  349. if time.Now().Unix()-lastChunkArrivalTime > 300 {
  350. //Already 5 minutes without new data arraival. Stop connection
  351. log.Println("Upload WebSocket connection timeout. Disconnecting.")
  352. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  353. time.Sleep(1 * time.Second)
  354. c.Close()
  355. return
  356. }
  357. }
  358. }
  359. }()
  360. totalFileSize := int64(0)
  361. for {
  362. mt, message, err := c.ReadMessage()
  363. if err != nil {
  364. //Connection closed by client. Clear the tmp folder and exit
  365. log.Println("Upload terminated by client. Cleaning tmp folder.")
  366. //Clear the tmp folder
  367. time.Sleep(1 * time.Second)
  368. os.RemoveAll(uploadFolder)
  369. return
  370. }
  371. //The mt should be 2 = binary for file upload and 1 for control syntax
  372. if mt == 1 {
  373. msg := strings.TrimSpace(string(message))
  374. if msg == "done" {
  375. //Start the merging process
  376. log.Println(userinfo.Username + " uploaded a file: " + filepath.Base(targetUploadLocation))
  377. break
  378. } else {
  379. //Unknown operations
  380. }
  381. } else if mt == 2 {
  382. //File block. Save it to tmp folder
  383. chunkFilepath := filepath.Join(uploadFolder, "upld_"+strconv.Itoa(blockCounter))
  384. chunkName = append(chunkName, chunkFilepath)
  385. ioutil.WriteFile(chunkFilepath, message, 0700)
  386. //Update the last upload chunk time
  387. lastChunkArrivalTime = time.Now().Unix()
  388. //Check if the file size is too big
  389. totalFileSize += fs.GetFileSize(chunkFilepath)
  390. if totalFileSize > max_upload_size {
  391. //File too big
  392. c.WriteMessage(1, []byte(`{\"error\":\"File size too large.\"}`))
  393. //Close the connection
  394. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  395. time.Sleep(1 * time.Second)
  396. c.Close()
  397. //Clear the tmp files
  398. os.RemoveAll(uploadFolder)
  399. return
  400. }
  401. blockCounter++
  402. //Request client to send the next chunk
  403. c.WriteMessage(1, []byte("next"))
  404. }
  405. //log.Println("recv:", len(message), "type", mt)
  406. }
  407. //Merge the file
  408. out, err := os.OpenFile(targetUploadLocation, os.O_CREATE|os.O_WRONLY, 0755)
  409. if err != nil {
  410. log.Println("Failed to open file:", err)
  411. c.WriteMessage(1, []byte(`{\"error\":\"Failed to open destination file\"}`))
  412. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  413. time.Sleep(1 * time.Second)
  414. c.Close()
  415. return
  416. }
  417. for _, filesrc := range chunkName {
  418. srcChunkReader, err := os.Open(filesrc)
  419. if err != nil {
  420. log.Println("Failed to open Source Chunk", filesrc, " with error ", err.Error())
  421. c.WriteMessage(1, []byte(`{\"error\":\"Failed to open Source Chunk\"}`))
  422. return
  423. }
  424. io.Copy(out, srcChunkReader)
  425. srcChunkReader.Close()
  426. }
  427. out.Close()
  428. //Check if the size fit in user quota
  429. fi, err := os.Stat(targetUploadLocation)
  430. if err != nil {
  431. // Could not obtain stat, handle error
  432. log.Println("Failed to validate uploaded file: ", targetUploadLocation, ". Error Message: ", err.Error())
  433. c.WriteMessage(1, []byte(`{\"error\":\"Failed to validate uploaded file\"}`))
  434. return
  435. }
  436. if !userinfo.StorageQuota.HaveSpace(fi.Size()) {
  437. c.WriteMessage(1, []byte(`{\"error\":\"User Storage Quota Exceeded\"}`))
  438. return
  439. }
  440. //Set owner of the new uploaded file
  441. userinfo.SetOwnerOfFile(targetUploadLocation)
  442. //Return complete signal
  443. c.WriteMessage(1, []byte("OK"))
  444. //Stop the timeout listner
  445. done <- true
  446. //Clear the tmp folder
  447. time.Sleep(300 * time.Millisecond)
  448. err = os.RemoveAll(uploadFolder)
  449. if err != nil {
  450. log.Println(err)
  451. }
  452. //Close WebSocket connection after finished
  453. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  454. time.Sleep(300 * time.Second)
  455. c.Close()
  456. }
  457. /*
  458. Handle FORM POST based upload
  459. This function is design for general SBCs or computers with more than 2GB of RAM
  460. (e.g. Raspberry Pi 4 / Linux Server)
  461. */
  462. func system_fs_handleUpload(w http.ResponseWriter, r *http.Request) {
  463. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  464. if err != nil {
  465. sendErrorResponse(w, "User not logged in")
  466. return
  467. }
  468. //Limit the max upload size to the user defined size
  469. if max_upload_size != 0 {
  470. r.Body = http.MaxBytesReader(w, r.Body, max_upload_size)
  471. }
  472. //Check if this is running under demo mode. If yes, reject upload
  473. if *demo_mode {
  474. sendErrorResponse(w, "You cannot upload in demo mode")
  475. return
  476. }
  477. err = r.ParseMultipartForm(int64(*upload_buf) << 20)
  478. if err != nil {
  479. //Filesize too big
  480. log.Println(err)
  481. sendErrorResponse(w, "File too large")
  482. return
  483. }
  484. file, handler, err := r.FormFile("file")
  485. if err != nil {
  486. log.Println("Error Retrieving File from upload by user: " + userinfo.Username)
  487. sendErrorResponse(w, "Unable to parse file from upload")
  488. return
  489. }
  490. //Get upload target directory
  491. uploadTarget, _ := mv(r, "path", true)
  492. if uploadTarget == "" {
  493. sendErrorResponse(w, "Upload target cannot be empty.")
  494. return
  495. }
  496. //Translate the upload target directory
  497. realUploadPath, err := userinfo.VirtualPathToRealPath(uploadTarget)
  498. if err != nil {
  499. sendErrorResponse(w, "Upload target is invalid or permission denied.")
  500. return
  501. }
  502. storeFilename := handler.Filename //Filename of the uploaded file
  503. //Update for Firefox 94.0.2 (x64) -> Now firefox put its relative path inside Content-Disposition -> filename
  504. //Skip this handler logic if Firefox version is in between 84.0.2 to 94.0.2
  505. bypassMetaCheck := compatibility.FirefoxBrowserVersionForBypassUploadMetaHeaderCheck(r.UserAgent())
  506. if !bypassMetaCheck && strings.Contains(handler.Header["Content-Disposition"][0], "filename=") && strings.Contains(handler.Header["Content-Disposition"][0], "/") {
  507. //This is a firefox MIME Header for file inside folder. Look for the actual filename
  508. headerFields := strings.Split(handler.Header["Content-Disposition"][0], "; ")
  509. possibleRelativePathname := ""
  510. for _, hf := range headerFields {
  511. if strings.Contains(hf, "filename=") && len(hf) > 11 {
  512. //Found. Overwrite original filename with the latest one
  513. possibleRelativePathname = hf[10 : len(hf)-1]
  514. storeFilename = possibleRelativePathname
  515. break
  516. }
  517. }
  518. }
  519. destFilepath := filepath.ToSlash(filepath.Clean(realUploadPath)) + "/" + storeFilename
  520. if !fileExists(filepath.Dir(destFilepath)) {
  521. os.MkdirAll(filepath.Dir(destFilepath), 0775)
  522. }
  523. //Check if the upload target is read only.
  524. accmode := userinfo.GetPathAccessPermission(uploadTarget)
  525. if accmode == "readonly" {
  526. sendErrorResponse(w, "The upload target is Read Only.")
  527. return
  528. } else if accmode == "denied" {
  529. sendErrorResponse(w, "Access Denied")
  530. return
  531. }
  532. //Check for storage quota
  533. uploadFileSize := handler.Size
  534. if !userinfo.StorageQuota.HaveSpace(uploadFileSize) {
  535. sendErrorResponse(w, "User Storage Quota Exceeded")
  536. return
  537. }
  538. //Prepare the file to be created (uploaded)
  539. destination, err := os.Create(destFilepath)
  540. if err != nil {
  541. sendErrorResponse(w, err.Error())
  542. return
  543. }
  544. defer destination.Close()
  545. defer file.Close()
  546. //Move the file to destination file location
  547. if *enable_asyncFileUpload {
  548. //Use Async upload method
  549. go func(r *http.Request, file multipart.File, destination *os.File, userinfo *user.User) {
  550. //Do the file copying using a buffered reader
  551. buf := make([]byte, *file_opr_buff)
  552. for {
  553. n, err := file.Read(buf)
  554. if err != nil && err != io.EOF {
  555. log.Println(err.Error())
  556. return
  557. }
  558. if n == 0 {
  559. break
  560. }
  561. if _, err := destination.Write(buf[:n]); err != nil {
  562. log.Println(err.Error())
  563. return
  564. }
  565. }
  566. //Clear up buffered files
  567. r.MultipartForm.RemoveAll()
  568. //Set the ownership of file
  569. userinfo.SetOwnerOfFile(destFilepath)
  570. //Perform a GC afterward
  571. runtime.GC()
  572. }(r, file, destination, userinfo)
  573. } else {
  574. //Use blocking upload and move method
  575. buf := make([]byte, *file_opr_buff)
  576. for {
  577. n, err := file.Read(buf)
  578. if err != nil && err != io.EOF {
  579. log.Println(err.Error())
  580. return
  581. }
  582. if n == 0 {
  583. break
  584. }
  585. if _, err := destination.Write(buf[:n]); err != nil {
  586. log.Println(err.Error())
  587. return
  588. }
  589. }
  590. //Clear up buffered files
  591. r.MultipartForm.RemoveAll()
  592. //Set the ownership of file
  593. userinfo.SetOwnerOfFile(destFilepath)
  594. }
  595. //Finish up the upload
  596. /*
  597. fmt.Printf("Uploaded File: %+v\n", handler.Filename)
  598. fmt.Printf("File Size: %+v\n", handler.Size)
  599. fmt.Printf("MIME Header: %+v\n", handler.Header)
  600. fmt.Println("Upload target: " + realUploadPath)
  601. */
  602. //Fnish upload. Fix the tmp filename
  603. log.Println(userinfo.Username + " uploaded a file: " + handler.Filename)
  604. //Do upload finishing stuff
  605. //Perform a GC
  606. runtime.GC()
  607. //Completed
  608. sendOK(w)
  609. return
  610. }
  611. //Validate if the copy and target process will involve file overwriting problem.
  612. func system_fs_validateFileOpr(w http.ResponseWriter, r *http.Request) {
  613. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  614. if err != nil {
  615. sendErrorResponse(w, err.Error())
  616. return
  617. }
  618. vsrcFiles, _ := mv(r, "src", true)
  619. vdestFile, _ := mv(r, "dest", true)
  620. var duplicateFiles []string = []string{}
  621. //Loop through all files are see if there are duplication during copy and paste
  622. sourceFiles := []string{}
  623. decodedSourceFiles, _ := url.QueryUnescape(vsrcFiles)
  624. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  625. if err != nil {
  626. sendErrorResponse(w, "Source file JSON parse error.")
  627. return
  628. }
  629. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  630. for _, file := range sourceFiles {
  631. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(file))
  632. if fileExists(filepath.Join(rdestFile, filepath.Base(rsrcFile))) {
  633. //File exists already.
  634. vpath, _ := userinfo.RealPathToVirtualPath(rsrcFile)
  635. duplicateFiles = append(duplicateFiles, vpath)
  636. }
  637. }
  638. jsonString, _ := json.Marshal(duplicateFiles)
  639. sendJSONResponse(w, string(jsonString))
  640. return
  641. }
  642. //Scan all directory and get trash file and send back results with WebSocket
  643. func system_fs_WebSocketScanTrashBin(w http.ResponseWriter, r *http.Request) {
  644. //Get and check user permission
  645. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  646. if err != nil {
  647. sendErrorResponse(w, "User not logged in")
  648. return
  649. }
  650. //Upgrade to websocket
  651. var upgrader = websocket.Upgrader{}
  652. c, err := upgrader.Upgrade(w, r, nil)
  653. if err != nil {
  654. w.WriteHeader(http.StatusInternalServerError)
  655. w.Write([]byte("500 - " + err.Error()))
  656. log.Print("Websocket Upgrade Error:", err.Error())
  657. return
  658. }
  659. //Start Scanning
  660. scanningRoots := []string{}
  661. //Get all roots to scan
  662. for _, storage := range userinfo.GetAllFileSystemHandler() {
  663. if storage.Hierarchy == "backup" {
  664. //Skip this fsh
  665. continue
  666. }
  667. if storage.Hierarchy == "user" {
  668. storageRoot := filepath.ToSlash(filepath.Join(storage.Path, "users", userinfo.Username))
  669. scanningRoots = append(scanningRoots, storageRoot)
  670. } else {
  671. storageRoot := storage.Path
  672. scanningRoots = append(scanningRoots, storageRoot)
  673. }
  674. }
  675. for _, rootPath := range scanningRoots {
  676. err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
  677. oneLevelUpper := filepath.Base(filepath.Dir(path))
  678. if oneLevelUpper == ".trash" {
  679. //This is a trashbin dir.
  680. file := path
  681. //Parse the trashFile struct
  682. timestamp := filepath.Ext(file)[1:]
  683. originalName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(filepath.Base(file)))
  684. originalExt := filepath.Ext(filepath.Base(originalName))
  685. virtualFilepath, _ := userinfo.RealPathToVirtualPath(file)
  686. virtualOrgPath, _ := userinfo.RealPathToVirtualPath(filepath.Dir(filepath.Dir(file)))
  687. rawsize := fs.GetFileSize(file)
  688. timestampInt64, _ := StringToInt64(timestamp)
  689. removeTimeDate := time.Unix(timestampInt64, 0)
  690. if IsDir(file) {
  691. originalExt = ""
  692. }
  693. thisTrashFileObject := trashedFile{
  694. Filename: filepath.Base(file),
  695. Filepath: virtualFilepath,
  696. FileExt: originalExt,
  697. IsDir: IsDir(file),
  698. Filesize: int64(rawsize),
  699. RemoveTimestamp: timestampInt64,
  700. RemoveDate: timeToString(removeTimeDate),
  701. OriginalPath: virtualOrgPath,
  702. OriginalFilename: originalName,
  703. }
  704. //Send out the result as JSON string
  705. js, _ := json.Marshal(thisTrashFileObject)
  706. err := c.WriteMessage(1, js)
  707. if err != nil {
  708. //Connection already closed
  709. return err
  710. }
  711. }
  712. return nil
  713. })
  714. if err != nil {
  715. //Scan or client connection error (Connection closed?)
  716. return
  717. }
  718. }
  719. //Close connection after finished
  720. c.Close()
  721. }
  722. //Scan all the directory and get trash files within the system
  723. func system_fs_scanTrashBin(w http.ResponseWriter, r *http.Request) {
  724. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  725. if err != nil {
  726. sendErrorResponse(w, err.Error())
  727. return
  728. }
  729. username := userinfo.Username
  730. results := []trashedFile{}
  731. files, err := system_fs_listTrash(username)
  732. if err != nil {
  733. sendErrorResponse(w, err.Error())
  734. return
  735. }
  736. //Get information of each files and process it into results
  737. for _, file := range files {
  738. timestamp := filepath.Ext(file)[1:]
  739. originalName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(filepath.Base(file)))
  740. originalExt := filepath.Ext(filepath.Base(originalName))
  741. virtualFilepath, _ := userinfo.RealPathToVirtualPath(file)
  742. virtualOrgPath, _ := userinfo.RealPathToVirtualPath(filepath.Dir(filepath.Dir(file)))
  743. rawsize := fs.GetFileSize(file)
  744. timestampInt64, _ := StringToInt64(timestamp)
  745. removeTimeDate := time.Unix(timestampInt64, 0)
  746. if IsDir(file) {
  747. originalExt = ""
  748. }
  749. results = append(results, trashedFile{
  750. Filename: filepath.Base(file),
  751. Filepath: virtualFilepath,
  752. FileExt: originalExt,
  753. IsDir: IsDir(file),
  754. Filesize: int64(rawsize),
  755. RemoveTimestamp: timestampInt64,
  756. RemoveDate: timeToString(removeTimeDate),
  757. OriginalPath: virtualOrgPath,
  758. OriginalFilename: originalName,
  759. })
  760. }
  761. //Sort the results by date, latest on top
  762. sort.Slice(results[:], func(i, j int) bool {
  763. return results[i].RemoveTimestamp > results[j].RemoveTimestamp
  764. })
  765. //Format and return the json results
  766. jsonString, _ := json.Marshal(results)
  767. sendJSONResponse(w, string(jsonString))
  768. }
  769. //Restore a trashed file to its parent dir
  770. func system_fs_restoreFile(w http.ResponseWriter, r *http.Request) {
  771. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  772. if err != nil {
  773. sendErrorResponse(w, err.Error())
  774. return
  775. }
  776. targetTrashedFile, err := mv(r, "src", true)
  777. if err != nil {
  778. sendErrorResponse(w, "Invalid src given")
  779. return
  780. }
  781. //Translate it to realpath
  782. realpath, _ := userinfo.VirtualPathToRealPath(targetTrashedFile)
  783. if !fileExists(realpath) {
  784. sendErrorResponse(w, "File not exists")
  785. return
  786. }
  787. //Check if this is really a trashed file
  788. if filepath.Base(filepath.Dir(realpath)) != ".trash" {
  789. sendErrorResponse(w, "File not in trashbin")
  790. return
  791. }
  792. //OK to proceed.
  793. targetPath := filepath.ToSlash(filepath.Dir(filepath.Dir(realpath))) + "/" + strings.TrimSuffix(filepath.Base(realpath), filepath.Ext(filepath.Base(realpath)))
  794. //log.Println(targetPath);
  795. os.Rename(realpath, targetPath)
  796. //Check if the parent dir has no more fileds. If yes, remove it
  797. filescounter, _ := filepath.Glob(filepath.Dir(realpath) + "/*")
  798. if len(filescounter) == 0 {
  799. os.Remove(filepath.Dir(realpath))
  800. }
  801. sendOK(w)
  802. }
  803. //Clear all trashed file in the system
  804. func system_fs_clearTrashBin(w http.ResponseWriter, r *http.Request) {
  805. u, err := userHandler.GetUserInfoFromRequest(w, r)
  806. if err != nil {
  807. sendErrorResponse(w, "User not logged in")
  808. return
  809. }
  810. username := u.Username
  811. fileList, err := system_fs_listTrash(username)
  812. if err != nil {
  813. sendErrorResponse(w, "Unable to clear trash: "+err.Error())
  814. return
  815. }
  816. //Get list success. Remove each of them.
  817. for _, file := range fileList {
  818. isOwner := u.IsOwnerOfFile(file)
  819. if isOwner {
  820. //This user own this system. Remove this file from his quota
  821. u.RemoveOwnershipFromFile(file)
  822. }
  823. os.RemoveAll(file)
  824. //Check if its parent directory have no files. If yes, remove the dir itself as well.
  825. filesInThisTrashBin, _ := filepath.Glob(filepath.Dir(file) + "/*")
  826. if len(filesInThisTrashBin) == 0 {
  827. os.Remove(filepath.Dir(file))
  828. }
  829. }
  830. sendOK(w)
  831. }
  832. //Get all trash in a string list
  833. func system_fs_listTrash(username string) ([]string, error) {
  834. userinfo, _ := userHandler.GetUserInfoFromUsername(username)
  835. scanningRoots := []string{}
  836. //Get all roots to scan
  837. for _, storage := range userinfo.GetAllFileSystemHandler() {
  838. if storage.Hierarchy == "backup" {
  839. //Skip this fsh
  840. continue
  841. }
  842. if storage.Hierarchy == "user" {
  843. storageRoot := filepath.ToSlash(filepath.Join(storage.Path, "users", userinfo.Username))
  844. scanningRoots = append(scanningRoots, storageRoot)
  845. } else {
  846. storageRoot := storage.Path
  847. scanningRoots = append(scanningRoots, storageRoot)
  848. }
  849. }
  850. files := []string{}
  851. for _, rootPath := range scanningRoots {
  852. err := filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
  853. oneLevelUpper := filepath.Base(filepath.Dir(path))
  854. if oneLevelUpper == ".trash" {
  855. //This is a trashbin dir.
  856. files = append(files, path)
  857. }
  858. return nil
  859. })
  860. if err != nil {
  861. return []string{}, errors.New("Failed to scan file system.")
  862. }
  863. }
  864. return files, nil
  865. }
  866. /*
  867. Handle new file or folder functions
  868. Required information
  869. @type {folder / file}
  870. @ext {any that is listed in the template folder}
  871. if no paramter is passed in, default listing all the supported template file
  872. */
  873. func system_fs_handleNewObjects(w http.ResponseWriter, r *http.Request) {
  874. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  875. if err != nil {
  876. sendErrorResponse(w, "User not logged in")
  877. return
  878. }
  879. //Validate the token
  880. tokenValid := CSRFTokenManager.HandleTokenValidation(w, r)
  881. if !tokenValid {
  882. http.Error(w, "Invalid CSRF token", 401)
  883. return
  884. }
  885. fileType, _ := mv(r, "type", true) //File creation type, {file, folder}
  886. vsrc, _ := mv(r, "src", true) //Virtual file source folder, do not include filename
  887. filename, _ := mv(r, "filename", true) //Filename for the new file
  888. if fileType == "" && filename == "" {
  889. //List all the supported new filetype
  890. if !fileExists("system/newitem/") {
  891. os.MkdirAll("system/newitem/", 0755)
  892. }
  893. type newItemObject struct {
  894. Desc string
  895. Ext string
  896. }
  897. var newItemList []newItemObject
  898. newItemTemplate, _ := filepath.Glob("system/newitem/*")
  899. for _, file := range newItemTemplate {
  900. thisItem := new(newItemObject)
  901. thisItem.Desc = strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
  902. thisItem.Ext = filepath.Ext(file)[1:]
  903. newItemList = append(newItemList, *thisItem)
  904. }
  905. jsonString, err := json.Marshal(newItemList)
  906. if err != nil {
  907. log.Println("*File System* Unable to parse JSON string for new item list!")
  908. sendErrorResponse(w, "Unable to parse new item list. See server log for more information.")
  909. return
  910. }
  911. sendJSONResponse(w, string(jsonString))
  912. return
  913. } else if fileType != "" && filename != "" {
  914. if vsrc == "" {
  915. sendErrorResponse(w, "Missing paramter: 'src'")
  916. return
  917. }
  918. //Translate the path to realpath
  919. rpath, err := userinfo.VirtualPathToRealPath(vsrc)
  920. if err != nil {
  921. sendErrorResponse(w, "Invalid path given.")
  922. return
  923. }
  924. //Check if directory is readonly
  925. accmode := userinfo.GetPathAccessPermission(vsrc)
  926. if accmode == "readonly" {
  927. sendErrorResponse(w, "This directory is Read Only.")
  928. return
  929. } else if accmode == "denied" {
  930. sendErrorResponse(w, "Access Denied")
  931. return
  932. }
  933. //Check if the file already exists. If yes, fix its filename.
  934. newfilePath := filepath.ToSlash(filepath.Join(rpath, filename))
  935. if fileType == "file" {
  936. for fileExists(newfilePath) {
  937. sendErrorResponse(w, "Given filename already exists.")
  938. return
  939. }
  940. ext := filepath.Ext(filename)
  941. if ext == "" {
  942. //This is a file with no extension.
  943. f, err := os.Create(newfilePath)
  944. if err != nil {
  945. log.Println("*File System* " + err.Error())
  946. sendErrorResponse(w, err.Error())
  947. return
  948. }
  949. f.Close()
  950. } else {
  951. templateFile, _ := filepath.Glob("system/newitem/*" + ext)
  952. if len(templateFile) == 0 {
  953. //This file extension is not in template
  954. f, err := os.Create(newfilePath)
  955. if err != nil {
  956. log.Println("*File System* " + err.Error())
  957. sendErrorResponse(w, err.Error())
  958. return
  959. }
  960. f.Close()
  961. } else {
  962. //Copy file from templateFile[0] to current dir with the given name
  963. input, _ := ioutil.ReadFile(templateFile[0])
  964. err := ioutil.WriteFile(newfilePath, input, 0755)
  965. if err != nil {
  966. log.Println("*File System* " + err.Error())
  967. sendErrorResponse(w, err.Error())
  968. return
  969. }
  970. }
  971. }
  972. } else if fileType == "folder" {
  973. if fileExists(newfilePath) {
  974. sendErrorResponse(w, "Given folder already exists.")
  975. return
  976. }
  977. //Create the folder at target location
  978. err := os.Mkdir(newfilePath, 0755)
  979. if err != nil {
  980. sendErrorResponse(w, err.Error())
  981. return
  982. }
  983. }
  984. sendJSONResponse(w, "\"OK\"")
  985. } else {
  986. sendErrorResponse(w, "Missing paramter(s).")
  987. return
  988. }
  989. }
  990. /*
  991. Handle file operations via WebSocket
  992. This handler only handle zip, unzip, copy and move. Not other operations.
  993. For other operations, please use the legacy handleOpr endpoint
  994. */
  995. func system_fs_handleWebSocketOpr(w http.ResponseWriter, r *http.Request) {
  996. //Get and check user permission
  997. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  998. if err != nil {
  999. sendErrorResponse(w, "User not logged in")
  1000. return
  1001. }
  1002. operation, _ := mv(r, "opr", false) //Accept copy and move
  1003. vsrcFiles, _ := mv(r, "src", false)
  1004. vdestFile, _ := mv(r, "dest", false)
  1005. existsOpr, _ := mv(r, "existsresp", false)
  1006. if existsOpr == "" {
  1007. existsOpr = "keep"
  1008. }
  1009. //Decode the source file list
  1010. var sourceFiles []string
  1011. tmp := []string{}
  1012. decodedSourceFiles, _ := url.QueryUnescape(vsrcFiles)
  1013. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  1014. if err != nil {
  1015. log.Println("Source file JSON parse error.", err.Error())
  1016. sendErrorResponse(w, "Source file JSON parse error.")
  1017. return
  1018. }
  1019. //Bugged char filtering
  1020. for _, src := range sourceFiles {
  1021. tmp = append(tmp, strings.ReplaceAll(src, "{{plug_sign}}", "+"))
  1022. }
  1023. sourceFiles = tmp
  1024. vdestFile = strings.ReplaceAll(vdestFile, "{{plug_sign}}", "+")
  1025. //Decode the target position
  1026. escapedVdest, _ := url.QueryUnescape(vdestFile)
  1027. vdestFile = escapedVdest
  1028. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1029. //Permission checking
  1030. if !userinfo.CanWrite(vdestFile) {
  1031. log.Println("Access denied for " + userinfo.Username + " try to access " + vdestFile)
  1032. w.WriteHeader(http.StatusForbidden)
  1033. w.Write([]byte("403 - Access Denied"))
  1034. return
  1035. }
  1036. //Check if opr is suported
  1037. if operation == "move" || operation == "copy" || operation == "zip" || operation == "unzip" {
  1038. } else {
  1039. log.Println("This file operation is not supported on WebSocket file operations endpoint. Please use the legacy endpoint instead. Received: ", operation)
  1040. w.WriteHeader(http.StatusInternalServerError)
  1041. w.Write([]byte("500 - Not supported operation"))
  1042. return
  1043. }
  1044. //Upgrade to websocket
  1045. var upgrader = websocket.Upgrader{}
  1046. c, err := upgrader.Upgrade(w, r, nil)
  1047. if err != nil {
  1048. w.WriteHeader(http.StatusInternalServerError)
  1049. w.Write([]byte("500 - " + err.Error()))
  1050. log.Print("Websocket Upgrade Error:", err.Error())
  1051. return
  1052. }
  1053. type ProgressUpdate struct {
  1054. LatestFile string
  1055. Progress int
  1056. Error string
  1057. }
  1058. if operation == "zip" {
  1059. //Zip files
  1060. outputFilename := filepath.Join(rdestFile, filepath.Base(rdestFile)) + ".zip"
  1061. if len(sourceFiles) == 1 {
  1062. //Use the basename of the source file as zip file name
  1063. outputFilename = filepath.Join(rdestFile, filepath.Base(sourceFiles[0])) + ".zip"
  1064. }
  1065. //Translate source Files into real paths
  1066. realSourceFiles := []string{}
  1067. for _, vsrcs := range sourceFiles {
  1068. rsrc, err := userinfo.VirtualPathToRealPath(vsrcs)
  1069. if err != nil {
  1070. stopStatus := ProgressUpdate{
  1071. LatestFile: filepath.Base(rsrc),
  1072. Progress: -1,
  1073. Error: "File not exists",
  1074. }
  1075. js, _ := json.Marshal(stopStatus)
  1076. c.WriteMessage(1, js)
  1077. c.Close()
  1078. }
  1079. realSourceFiles = append(realSourceFiles, rsrc)
  1080. }
  1081. //Create the zip file
  1082. fs.ArozZipFileWithProgress(realSourceFiles, outputFilename, false, func(currentFilename string, _ int, _ int, progress float64) {
  1083. currentStatus := ProgressUpdate{
  1084. LatestFile: currentFilename,
  1085. Progress: int(math.Ceil(progress)),
  1086. Error: "",
  1087. }
  1088. js, _ := json.Marshal(currentStatus)
  1089. c.WriteMessage(1, js)
  1090. })
  1091. } else if operation == "unzip" {
  1092. //Check if the target destination exists and writable
  1093. if !userinfo.CanWrite(vdestFile) {
  1094. stopStatus := ProgressUpdate{
  1095. LatestFile: filepath.Base(vdestFile),
  1096. Progress: -1,
  1097. Error: "Access Denied: No Write Permission",
  1098. }
  1099. js, _ := json.Marshal(stopStatus)
  1100. c.WriteMessage(1, js)
  1101. c.Close()
  1102. }
  1103. //Create the destination folder
  1104. os.MkdirAll(rdestFile, 0755)
  1105. //Convert the src files into realpaths
  1106. realSourceFiles := []string{}
  1107. for _, vsrcs := range sourceFiles {
  1108. rsrc, err := userinfo.VirtualPathToRealPath(vsrcs)
  1109. if err != nil {
  1110. stopStatus := ProgressUpdate{
  1111. LatestFile: filepath.Base(rsrc),
  1112. Progress: -1,
  1113. Error: "File not exists",
  1114. }
  1115. js, _ := json.Marshal(stopStatus)
  1116. c.WriteMessage(1, js)
  1117. c.Close()
  1118. }
  1119. realSourceFiles = append(realSourceFiles, rsrc)
  1120. }
  1121. //Unzip the files
  1122. fs.ArozUnzipFileWithProgress(realSourceFiles, rdestFile, func(currentFile string, filecount int, totalfile int, progress float64) {
  1123. //Generate the status update struct
  1124. currentStatus := ProgressUpdate{
  1125. LatestFile: filepath.Base(currentFile),
  1126. Progress: int(math.Ceil(progress)),
  1127. Error: "",
  1128. }
  1129. js, _ := json.Marshal(currentStatus)
  1130. c.WriteMessage(1, js)
  1131. })
  1132. } else {
  1133. //Other operations that allow multiple source files to handle one by one
  1134. for i := 0; i < len(sourceFiles); i++ {
  1135. vsrcFile := sourceFiles[i]
  1136. rsrcFile, _ := userinfo.VirtualPathToRealPath(vsrcFile)
  1137. //c.WriteMessage(1, message)
  1138. if !fileExists(rsrcFile) {
  1139. //This source file not exists. Report Error and Stop
  1140. stopStatus := ProgressUpdate{
  1141. LatestFile: filepath.Base(rsrcFile),
  1142. Progress: -1,
  1143. Error: "File not exists",
  1144. }
  1145. js, _ := json.Marshal(stopStatus)
  1146. c.WriteMessage(1, js)
  1147. c.Close()
  1148. return
  1149. }
  1150. if operation == "move" {
  1151. err := fs.FileMove(rsrcFile, rdestFile, existsOpr, false, func(progress int, currentFile string) {
  1152. //Multply child progress to parent progress
  1153. blockRatio := float64(100) / float64(len(sourceFiles))
  1154. overallRatio := blockRatio*float64(i) + blockRatio*(float64(progress)/float64(100))
  1155. //Construct return struct
  1156. currentStatus := ProgressUpdate{
  1157. LatestFile: filepath.Base(currentFile),
  1158. Progress: int(overallRatio),
  1159. Error: "",
  1160. }
  1161. js, _ := json.Marshal(currentStatus)
  1162. c.WriteMessage(1, js)
  1163. })
  1164. //Handle move starting error
  1165. if err != nil {
  1166. stopStatus := ProgressUpdate{
  1167. LatestFile: filepath.Base(rsrcFile),
  1168. Progress: -1,
  1169. Error: err.Error(),
  1170. }
  1171. js, _ := json.Marshal(stopStatus)
  1172. c.WriteMessage(1, js)
  1173. c.Close()
  1174. return
  1175. }
  1176. //Remove the cache for the original file
  1177. metadata.RemoveCache(rsrcFile)
  1178. } else if operation == "copy" {
  1179. err := fs.FileCopy(rsrcFile, rdestFile, existsOpr, func(progress int, currentFile string) {
  1180. //Multply child progress to parent progress
  1181. blockRatio := float64(100) / float64(len(sourceFiles))
  1182. overallRatio := blockRatio*float64(i) + blockRatio*(float64(progress)/float64(100))
  1183. //Construct return struct
  1184. currentStatus := ProgressUpdate{
  1185. LatestFile: filepath.Base(currentFile),
  1186. Progress: int(overallRatio),
  1187. Error: "",
  1188. }
  1189. js, _ := json.Marshal(currentStatus)
  1190. c.WriteMessage(1, js)
  1191. })
  1192. //Handle Copy starting error
  1193. if err != nil {
  1194. stopStatus := ProgressUpdate{
  1195. LatestFile: filepath.Base(rsrcFile),
  1196. Progress: -1,
  1197. Error: err.Error(),
  1198. }
  1199. js, _ := json.Marshal(stopStatus)
  1200. c.WriteMessage(1, js)
  1201. c.Close()
  1202. return
  1203. }
  1204. }
  1205. }
  1206. }
  1207. //Close WebSocket connection after finished
  1208. time.Sleep(1 * time.Second)
  1209. c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
  1210. c.Close()
  1211. }
  1212. /*
  1213. Handle file operations
  1214. Support {move, copy, delete, recycle, rename}
  1215. */
  1216. //Handle file operations.
  1217. func system_fs_handleOpr(w http.ResponseWriter, r *http.Request) {
  1218. //Check if user logged in
  1219. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1220. if err != nil {
  1221. sendErrorResponse(w, "User not logged in")
  1222. return
  1223. }
  1224. //Validate the token
  1225. tokenValid := CSRFTokenManager.HandleTokenValidation(w, r)
  1226. if !tokenValid {
  1227. http.Error(w, "Invalid CSRF token", 401)
  1228. return
  1229. }
  1230. operation, _ := mv(r, "opr", true)
  1231. vsrcFiles, _ := mv(r, "src", true)
  1232. vdestFile, _ := mv(r, "dest", true)
  1233. vnfilenames, _ := mv(r, "new", true) //Only use when rename or create new file / folder
  1234. //Check if operation valid.
  1235. if operation == "" {
  1236. //Undefined operations.
  1237. sendErrorResponse(w, "Undefined operations paramter: Missing 'opr' in request header.")
  1238. return
  1239. }
  1240. //As the user can pass in multiple source files at the same time, parse sourceFiles from json string
  1241. var sourceFiles []string
  1242. //This line is required in order to allow passing of special charaters
  1243. decodedSourceFiles := system_fs_specialURIDecode(vsrcFiles)
  1244. err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
  1245. if err != nil {
  1246. sendErrorResponse(w, "Source file JSON parse error.")
  1247. return
  1248. }
  1249. //Check if new filenames are also valid. If yes, translate it into string array
  1250. var newFilenames []string
  1251. if vnfilenames != "" {
  1252. vnfilenames, _ := url.QueryUnescape(vnfilenames)
  1253. err = json.Unmarshal([]byte(vnfilenames), &newFilenames)
  1254. if err != nil {
  1255. sendErrorResponse(w, "Unable to parse JSON for new filenames")
  1256. return
  1257. }
  1258. }
  1259. if operation == "zip" {
  1260. //Zip operation. Parse the real filepath list
  1261. rsrcFiles := []string{}
  1262. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1263. for _, vsrcFile := range sourceFiles {
  1264. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1265. if fileExists(rsrcFile) {
  1266. rsrcFiles = append(rsrcFiles, rsrcFile)
  1267. }
  1268. }
  1269. zipFilename := rdestFile
  1270. if fs.IsDir(rdestFile) {
  1271. //Append the filename to it
  1272. if len(rsrcFiles) == 1 {
  1273. zipFilename = filepath.Join(rdestFile, strings.TrimSuffix(filepath.Base(rsrcFiles[0]), filepath.Ext(filepath.Base(rsrcFiles[0])))+".zip")
  1274. } else if len(rsrcFiles) > 1 {
  1275. zipFilename = filepath.Join(rdestFile, filepath.Base(filepath.Dir(rsrcFiles[0]))+".zip")
  1276. }
  1277. }
  1278. //Create a zip file at target location
  1279. err := fs.ArozZipFile(rsrcFiles, zipFilename, false)
  1280. if err != nil {
  1281. sendErrorResponse(w, err.Error())
  1282. return
  1283. }
  1284. } else {
  1285. //For operations that is handled file by file
  1286. for i, vsrcFile := range sourceFiles {
  1287. //Convert the virtual path to realpath on disk
  1288. rsrcFile, _ := userinfo.VirtualPathToRealPath(string(vsrcFile))
  1289. rdestFile, _ := userinfo.VirtualPathToRealPath(vdestFile)
  1290. //Check if the source file exists
  1291. if !fileExists(rsrcFile) {
  1292. /*
  1293. Special edge case handler:
  1294. There might be edge case that files are stored in URIEncoded methods
  1295. e.g. abc def.mp3 --> abc%20cdf.mp3
  1296. In this case, this logic statement should be able to handle this
  1297. */
  1298. edgeCaseFilename := filepath.Join(filepath.Dir(rsrcFile), system_fs_specialURIEncode(filepath.Base(rsrcFile)))
  1299. if fileExists(edgeCaseFilename) {
  1300. rsrcFile = edgeCaseFilename
  1301. } else {
  1302. sendErrorResponse(w, "Source file not exists.")
  1303. return
  1304. }
  1305. }
  1306. if operation == "rename" {
  1307. //Check if the usage is correct.
  1308. if vdestFile != "" {
  1309. sendErrorResponse(w, "Rename only accept 'src' and 'new'. Please use move if you want to move a file.")
  1310. return
  1311. }
  1312. //Check if new name paramter is passed in.
  1313. if len(newFilenames) == 0 {
  1314. sendErrorResponse(w, "Missing paramter (JSON string): 'new'")
  1315. return
  1316. }
  1317. //Check if the source filenames and new filenanmes match
  1318. if len(newFilenames) != len(sourceFiles) {
  1319. sendErrorResponse(w, "New filenames do not match with source filename's length.")
  1320. return
  1321. }
  1322. //Check if the target dir is not readonly
  1323. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1324. if accmode == "readonly" {
  1325. sendErrorResponse(w, "This directory is Read Only.")
  1326. return
  1327. } else if accmode == "denied" {
  1328. sendErrorResponse(w, "Access Denied")
  1329. return
  1330. }
  1331. thisFilename := newFilenames[i]
  1332. //Check if the name already exists. If yes, return false
  1333. if fileExists(filepath.Dir(rsrcFile) + "/" + thisFilename) {
  1334. sendErrorResponse(w, "File already exists")
  1335. return
  1336. }
  1337. //Everything is ok. Rename the file.
  1338. targetNewName := filepath.Dir(rsrcFile) + "/" + thisFilename
  1339. err = os.Rename(rsrcFile, targetNewName)
  1340. if err != nil {
  1341. sendErrorResponse(w, err.Error())
  1342. return
  1343. }
  1344. //Remove the cache for the original file
  1345. metadata.RemoveCache(rsrcFile)
  1346. } else if operation == "move" {
  1347. //File move operation. Check if the source file / dir and target directory exists
  1348. /*
  1349. Example usage from file explorer
  1350. $.ajax({
  1351. type: 'POST',
  1352. url: `/system/file_system/fileOpr`,
  1353. data: {opr: "move" ,src: JSON.stringify(fileList), dest: targetDir},
  1354. success: function(data){
  1355. if (data.error !== undefined){
  1356. msgbox("remove",data.error);
  1357. }else{
  1358. //OK, do something
  1359. }
  1360. }
  1361. });
  1362. */
  1363. if !fileExists(rsrcFile) {
  1364. sendErrorResponse(w, "Source file not exists")
  1365. return
  1366. }
  1367. //Check if the source file is read only.
  1368. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1369. if accmode == "readonly" {
  1370. sendErrorResponse(w, "This source file is Read Only.")
  1371. return
  1372. } else if accmode == "denied" {
  1373. sendErrorResponse(w, "Access Denied")
  1374. return
  1375. }
  1376. if rdestFile == "" {
  1377. sendErrorResponse(w, "Undefined dest location.")
  1378. return
  1379. }
  1380. //Get exists overwrite mode
  1381. existsOpr, _ := mv(r, "existsresp", true)
  1382. //Check if use fast move instead
  1383. //Check if the source and destination folder are under the same root. If yes, use os.Rename for faster move operations
  1384. underSameRoot := false
  1385. //Check if the two files are under the same user root path
  1386. srcAbs, _ := filepath.Abs(rsrcFile)
  1387. destAbs, _ := filepath.Abs(rdestFile)
  1388. //Check other storage path and see if they are under the same root
  1389. for _, rootPath := range userinfo.GetAllFileSystemHandler() {
  1390. thisRoot := rootPath.Path
  1391. thisRootAbs, err := filepath.Abs(thisRoot)
  1392. if err != nil {
  1393. continue
  1394. }
  1395. if strings.Contains(srcAbs, thisRootAbs) && strings.Contains(destAbs, thisRootAbs) {
  1396. underSameRoot = true
  1397. }
  1398. }
  1399. //Updates 19-10-2020: Added ownership management to file move and copy
  1400. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1401. err = fs.FileMove(rsrcFile, rdestFile, existsOpr, underSameRoot, nil)
  1402. if err != nil {
  1403. sendErrorResponse(w, err.Error())
  1404. //Restore the ownership if remove failed
  1405. userinfo.SetOwnerOfFile(rsrcFile)
  1406. return
  1407. }
  1408. //Set user to own the new file
  1409. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1410. //Remove cache for the original file
  1411. metadata.RemoveCache(rsrcFile)
  1412. } else if operation == "copy" {
  1413. //Copy file. See move example and change 'opr' to 'copy'
  1414. if !fileExists(rsrcFile) {
  1415. sendErrorResponse(w, "Source file not exists")
  1416. return
  1417. }
  1418. //Check if the desintation is read only.
  1419. if !userinfo.CanWrite(vdestFile) {
  1420. sendErrorResponse(w, "Access Denied.")
  1421. return
  1422. }
  1423. if !fileExists(rdestFile) {
  1424. if fileExists(filepath.Dir(rdestFile)) {
  1425. //User pass in the whole path for the folder. Report error usecase.
  1426. sendErrorResponse(w, "Dest location should be an existing folder instead of the full path of the copied file.")
  1427. return
  1428. }
  1429. sendErrorResponse(w, "Dest folder not found")
  1430. return
  1431. }
  1432. existsOpr, _ := mv(r, "existsresp", true)
  1433. //Check if the user have space for the extra file
  1434. if !userinfo.StorageQuota.HaveSpace(fs.GetFileSize(rdestFile)) {
  1435. sendErrorResponse(w, "Storage Quota Full")
  1436. return
  1437. }
  1438. err = fs.FileCopy(rsrcFile, rdestFile, existsOpr, nil)
  1439. if err != nil {
  1440. sendErrorResponse(w, err.Error())
  1441. return
  1442. }
  1443. //Set user to own this file
  1444. userinfo.SetOwnerOfFile(filepath.ToSlash(filepath.Clean(rdestFile)) + "/" + filepath.Base(rsrcFile))
  1445. } else if operation == "delete" {
  1446. //Delete the file permanently
  1447. if !fileExists(rsrcFile) {
  1448. //Check if it is a non escapted file instead
  1449. sendErrorResponse(w, "Source file not exists")
  1450. return
  1451. }
  1452. if !userinfo.CanWrite(vsrcFile) {
  1453. sendErrorResponse(w, "Access Denied.")
  1454. return
  1455. }
  1456. //Check if the user own this file
  1457. isOwner := userinfo.IsOwnerOfFile(rsrcFile)
  1458. if isOwner {
  1459. //This user own this system. Remove this file from his quota
  1460. userinfo.RemoveOwnershipFromFile(rsrcFile)
  1461. }
  1462. //Check if this file has any cached files. If yes, remove it
  1463. metadata.RemoveCache(rsrcFile)
  1464. //Clear the cache folder if there is no files inside
  1465. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1466. if len(fc) == 0 {
  1467. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1468. }
  1469. os.RemoveAll(rsrcFile)
  1470. } else if operation == "recycle" {
  1471. //Put it into a subfolder named trash and allow it to to be removed later
  1472. if !fileExists(rsrcFile) {
  1473. //Check if it is a non escapted file instead
  1474. sendErrorResponse(w, "Source file not exists")
  1475. return
  1476. }
  1477. //Check if the upload target is read only.
  1478. //Updates 20 Jan 2021: Replace with CanWrite handler
  1479. /*
  1480. accmode := userinfo.GetPathAccessPermission(string(vsrcFile))
  1481. if accmode == "readonly" {
  1482. sendErrorResponse(w, "This directory is Read Only.")
  1483. return
  1484. } else if accmode == "denied" {
  1485. sendErrorResponse(w, "Access Denied")
  1486. return
  1487. }*/
  1488. if !userinfo.CanWrite(vsrcFile) {
  1489. sendErrorResponse(w, "Access Denied.")
  1490. return
  1491. }
  1492. //Check if this file has any cached files. If yes, remove it
  1493. metadata.RemoveCache(rsrcFile)
  1494. //Clear the cache folder if there is no files inside
  1495. fc, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/*")
  1496. if len(fc) == 0 {
  1497. os.Remove(filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.cache/")
  1498. }
  1499. //Create a trash directory for this folder
  1500. trashDir := filepath.ToSlash(filepath.Dir(rsrcFile)) + "/.trash/"
  1501. os.MkdirAll(trashDir, 0755)
  1502. hidden.HideFile(trashDir)
  1503. os.Rename(rsrcFile, trashDir+filepath.Base(rsrcFile)+"."+Int64ToString(GetUnixTime()))
  1504. } else if operation == "unzip" {
  1505. //Unzip the file to destination
  1506. //Check if the user can write to the target dest file
  1507. if userinfo.CanWrite(string(vdestFile)) == false {
  1508. sendErrorResponse(w, "Access Denied.")
  1509. return
  1510. }
  1511. //Make the rdest directory if not exists
  1512. if !fileExists(rdestFile) {
  1513. err = os.MkdirAll(rdestFile, 0755)
  1514. if err != nil {
  1515. sendErrorResponse(w, err.Error())
  1516. return
  1517. }
  1518. }
  1519. //OK! Unzip to destination
  1520. err := fs.Unzip(rsrcFile, rdestFile)
  1521. if err != nil {
  1522. sendErrorResponse(w, err.Error())
  1523. return
  1524. }
  1525. } else {
  1526. sendErrorResponse(w, "Unknown file opeartion given.")
  1527. return
  1528. }
  1529. }
  1530. }
  1531. sendJSONResponse(w, "\"OK\"")
  1532. return
  1533. }
  1534. //Allow systems to store key value pairs in the database as preferences.
  1535. func system_fs_handleUserPreference(w http.ResponseWriter, r *http.Request) {
  1536. username, err := authAgent.GetUserName(w, r)
  1537. if err != nil {
  1538. sendErrorResponse(w, "User not logged in")
  1539. return
  1540. }
  1541. key, _ := mv(r, "key", false)
  1542. value, _ := mv(r, "value", false)
  1543. remove, _ := mv(r, "remove", false)
  1544. if key != "" && value == "" && remove == "" {
  1545. //Get mode. Read the prefernece with given key
  1546. result := ""
  1547. err := sysdb.Read("fs", "pref/"+key+"/"+username, &result)
  1548. if err != nil {
  1549. sendJSONResponse(w, "{\"error\":\"Key not found.\"}")
  1550. return
  1551. }
  1552. sendTextResponse(w, result)
  1553. } else if key != "" && value == "" && remove == "true" {
  1554. //Remove mode. Delete this key from sysdb
  1555. err := sysdb.Delete("fs", "pref/"+key+"/"+username)
  1556. if err != nil {
  1557. sendErrorResponse(w, err.Error())
  1558. }
  1559. sendOK(w)
  1560. } else if key != "" && value != "" {
  1561. //Set mode. Set the preference with given key
  1562. if len(value) > 1024 {
  1563. //Size too big. Reject storage
  1564. sendErrorResponse(w, "Preference value too long. Preference value can only store maximum 1024 characters.")
  1565. return
  1566. }
  1567. sysdb.Write("fs", "pref/"+key+"/"+username, value)
  1568. sendOK(w)
  1569. }
  1570. }
  1571. func system_fs_removeUserPreferences(username string) {
  1572. entries, err := sysdb.ListTable("fs")
  1573. if err != nil {
  1574. return
  1575. }
  1576. for _, keypairs := range entries {
  1577. if strings.Contains(string(keypairs[0]), "pref/") && strings.Contains(string(keypairs[0]), "/"+username) {
  1578. //Remove this preference
  1579. sysdb.Delete("fs", string(keypairs[0]))
  1580. }
  1581. }
  1582. }
  1583. func system_fs_listDrives(w http.ResponseWriter, r *http.Request) {
  1584. if authAgent.CheckAuth(r) == false {
  1585. sendErrorResponse(w, "User not logged in")
  1586. return
  1587. }
  1588. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  1589. type driveInfo struct {
  1590. Drivepath string
  1591. DriveFreeSpace uint64
  1592. DriveTotalSpace uint64
  1593. DriveAvailSpace uint64
  1594. }
  1595. var drives []driveInfo
  1596. if runtime.GOOS == "windows" {
  1597. //Under windows
  1598. for _, drive := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
  1599. f, err := os.Open(string(drive) + ":\\")
  1600. if err == nil {
  1601. thisdrive := new(driveInfo)
  1602. thisdrive.Drivepath = string(drive) + ":\\"
  1603. free, total, avail := storage.GetDriveCapacity(string(drive) + ":\\")
  1604. thisdrive.DriveFreeSpace = free
  1605. thisdrive.DriveTotalSpace = total
  1606. thisdrive.DriveAvailSpace = avail
  1607. drives = append(drives, *thisdrive)
  1608. f.Close()
  1609. }
  1610. }
  1611. } else {
  1612. //Under linux environment
  1613. //Append all the virtual directories root as root instead
  1614. storageDevices := []string{}
  1615. for _, fshandler := range userinfo.GetAllFileSystemHandler() {
  1616. storageDevices = append(storageDevices, fshandler.Path)
  1617. }
  1618. //List all storage information of each devices
  1619. for _, dev := range storageDevices {
  1620. thisdrive := new(driveInfo)
  1621. thisdrive.Drivepath = filepath.Base(dev)
  1622. free, total, avail := storage.GetDriveCapacity(string(dev))
  1623. thisdrive.DriveFreeSpace = free
  1624. thisdrive.DriveTotalSpace = total
  1625. thisdrive.DriveAvailSpace = avail
  1626. drives = append(drives, *thisdrive)
  1627. }
  1628. }
  1629. jsonString, _ := json.Marshal(drives)
  1630. sendJSONResponse(w, string(jsonString))
  1631. }
  1632. func system_fs_listRoot(w http.ResponseWriter, r *http.Request) {
  1633. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1634. if err != nil {
  1635. sendErrorResponse(w, err.Error())
  1636. return
  1637. }
  1638. username := userinfo.Username
  1639. userRoot, _ := mv(r, "user", false)
  1640. if userRoot == "true" {
  1641. type fileObject struct {
  1642. Filename string
  1643. Filepath string
  1644. IsDir bool
  1645. }
  1646. //List the root media folders under user:/
  1647. filesInUserRoot := []fileObject{}
  1648. filesInRoot, _ := filepath.Glob(filepath.ToSlash(filepath.Clean(*root_directory)) + "/users/" + username + "/*")
  1649. for _, file := range filesInRoot {
  1650. thisFile := new(fileObject)
  1651. thisFile.Filename = filepath.Base(file)
  1652. thisFile.Filepath, _ = userinfo.RealPathToVirtualPath(file)
  1653. thisFile.IsDir = IsDir(file)
  1654. filesInUserRoot = append(filesInUserRoot, *thisFile)
  1655. }
  1656. jsonString, _ := json.Marshal(filesInUserRoot)
  1657. sendJSONResponse(w, string(jsonString))
  1658. } else {
  1659. type rootObject struct {
  1660. rootID string //The vroot id
  1661. RootName string //The name of this vroot
  1662. RootPath string //The path of this vroot
  1663. RootBackups bool //If there are backup for this vroot
  1664. }
  1665. roots := []*rootObject{}
  1666. backupRoots := []string{}
  1667. for _, store := range userinfo.GetAllFileSystemHandler() {
  1668. if store.Hierarchy == "user" || store.Hierarchy == "public" {
  1669. //Normal drives
  1670. var thisDevice = new(rootObject)
  1671. thisDevice.RootName = store.Name
  1672. thisDevice.RootPath = store.UUID + ":/"
  1673. thisDevice.rootID = store.UUID
  1674. roots = append(roots, thisDevice)
  1675. } else if store.Hierarchy == "backup" {
  1676. //Backup drive.
  1677. backupRoots = append(backupRoots, store.HierarchyConfig.(hybridBackup.BackupTask).ParentUID)
  1678. }
  1679. }
  1680. //Update root configs for backup roots
  1681. for _, backupRoot := range backupRoots {
  1682. //For this backup root, check if the parent root mounted
  1683. for _, root := range roots {
  1684. if root.rootID == backupRoot {
  1685. //Parent root mounted. Label the parent root as "have backup"
  1686. root.RootBackups = true
  1687. }
  1688. }
  1689. }
  1690. jsonString, _ := json.Marshal(roots)
  1691. sendJSONResponse(w, string(jsonString))
  1692. }
  1693. }
  1694. /*
  1695. Special Glob for handling path with [ or ] inside.
  1696. You can also pass in normal path for globing if you are not sure.
  1697. */
  1698. func system_fs_specialGlob(path string) ([]string, error) {
  1699. //Quick fix for foldername containing -] issue
  1700. path = strings.ReplaceAll(path, "[", "[[]")
  1701. files, err := filepath.Glob(path)
  1702. if err != nil {
  1703. return []string{}, err
  1704. }
  1705. if strings.Contains(path, "[") == true || strings.Contains(path, "]") == true {
  1706. if len(files) == 0 {
  1707. //Handle reverse check. Replace all [ and ] with *
  1708. newSearchPath := strings.ReplaceAll(path, "[", "?")
  1709. newSearchPath = strings.ReplaceAll(newSearchPath, "]", "?")
  1710. //Scan with all the similar structure except [ and ]
  1711. tmpFilelist, _ := filepath.Glob(newSearchPath)
  1712. for _, file := range tmpFilelist {
  1713. file = filepath.ToSlash(file)
  1714. if strings.Contains(file, filepath.ToSlash(filepath.Dir(path))) {
  1715. files = append(files, file)
  1716. }
  1717. }
  1718. }
  1719. }
  1720. //Convert all filepaths to slash
  1721. for i := 0; i < len(files); i++ {
  1722. files[i] = filepath.ToSlash(files[i])
  1723. }
  1724. return files, nil
  1725. }
  1726. func system_fs_specialURIDecode(inputPath string) string {
  1727. inputPath = strings.ReplaceAll(inputPath, "+", "{{plus_sign}}")
  1728. inputPath, _ = url.QueryUnescape(inputPath)
  1729. inputPath = strings.ReplaceAll(inputPath, "{{plus_sign}}", "+")
  1730. return inputPath
  1731. }
  1732. func system_fs_specialURIEncode(inputPath string) string {
  1733. inputPath = strings.ReplaceAll(inputPath, " ", "{{space_sign}}")
  1734. inputPath, _ = url.QueryUnescape(inputPath)
  1735. inputPath = strings.ReplaceAll(inputPath, "{{space_sign}}", "%20")
  1736. return inputPath
  1737. }
  1738. func system_fs_matchFileExt(inputFilename string, extArray []string) bool {
  1739. inputExt := filepath.Ext(inputFilename)
  1740. if stringInSlice(inputExt, extArray) {
  1741. return true
  1742. }
  1743. return false
  1744. }
  1745. //Handle file properties request
  1746. func system_fs_getFileProperties(w http.ResponseWriter, r *http.Request) {
  1747. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1748. if err != nil {
  1749. sendErrorResponse(w, err.Error())
  1750. return
  1751. }
  1752. vpath, err := mv(r, "path", true)
  1753. if err != nil {
  1754. sendErrorResponse(w, "path not defined")
  1755. return
  1756. }
  1757. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  1758. if err != nil {
  1759. sendErrorResponse(w, err.Error())
  1760. return
  1761. }
  1762. fileStat, err := os.Stat(rpath)
  1763. if err != nil {
  1764. sendErrorResponse(w, err.Error())
  1765. return
  1766. }
  1767. type fileProperties struct {
  1768. VirtualPath string
  1769. StoragePath string
  1770. Basename string
  1771. VirtualDirname string
  1772. StorageDirname string
  1773. Ext string
  1774. MimeType string
  1775. Filesize int64
  1776. Permission string
  1777. LastModTime string
  1778. LastModUnix int64
  1779. IsDirectory bool
  1780. Owner string
  1781. }
  1782. mime := "text/directory"
  1783. if !fileStat.IsDir() {
  1784. m, _, err := fs.GetMime(rpath)
  1785. if err != nil {
  1786. mime = ""
  1787. }
  1788. mime = m
  1789. }
  1790. filesize := fileStat.Size()
  1791. //Get file overall size if this is folder
  1792. if fileStat.IsDir() {
  1793. var size int64
  1794. filepath.Walk(rpath, func(_ string, info os.FileInfo, err error) error {
  1795. if err != nil {
  1796. return err
  1797. }
  1798. if !info.IsDir() {
  1799. size += info.Size()
  1800. }
  1801. return err
  1802. })
  1803. filesize = size
  1804. }
  1805. //Get file owner
  1806. owner := userinfo.GetFileOwner(rpath)
  1807. if owner == "" {
  1808. owner = "Unknown"
  1809. }
  1810. result := fileProperties{
  1811. VirtualPath: vpath,
  1812. StoragePath: filepath.Clean(rpath),
  1813. Basename: filepath.Base(rpath),
  1814. VirtualDirname: filepath.ToSlash(filepath.Dir(vpath)),
  1815. StorageDirname: filepath.ToSlash(filepath.Dir(rpath)),
  1816. Ext: filepath.Ext(rpath),
  1817. MimeType: mime,
  1818. Filesize: filesize,
  1819. Permission: fileStat.Mode().Perm().String(),
  1820. LastModTime: timeToString(fileStat.ModTime()),
  1821. LastModUnix: fileStat.ModTime().Unix(),
  1822. IsDirectory: fileStat.IsDir(),
  1823. Owner: owner,
  1824. }
  1825. jsonString, _ := json.Marshal(result)
  1826. sendJSONResponse(w, string(jsonString))
  1827. }
  1828. /*
  1829. List directory in the given path
  1830. Usage: Pass in dir like the following examples:
  1831. AOR:/Desktop <= Open /user/{username}/Desktop
  1832. S1:/ <= Open {uuid=S1}/
  1833. */
  1834. func system_fs_handleList(w http.ResponseWriter, r *http.Request) {
  1835. currentDir, _ := mv(r, "dir", true)
  1836. //Commented this line to handle dirname that contains "+" sign
  1837. //currentDir, _ = url.QueryUnescape(currentDir)
  1838. sortMode, _ := mv(r, "sort", true)
  1839. showHidden, _ := mv(r, "showHidden", true)
  1840. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1841. if err != nil {
  1842. //user not logged in. Redirect to login page.
  1843. sendErrorResponse(w, "User not logged in")
  1844. return
  1845. }
  1846. if currentDir == "" {
  1847. sendErrorResponse(w, "Invalid dir given.")
  1848. return
  1849. }
  1850. //Pad a slash at the end of currentDir if not exists
  1851. if currentDir[len(currentDir)-1:] != "/" {
  1852. currentDir = currentDir + "/"
  1853. }
  1854. //Convert the virutal path to realpath
  1855. realpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1856. if err != nil {
  1857. sendErrorResponse(w, "Error. Unable to parse path. "+err.Error())
  1858. return
  1859. }
  1860. if !fileExists(realpath) {
  1861. userRoot, _ := userinfo.VirtualPathToRealPath("user:/")
  1862. if filepath.Clean(realpath) == filepath.Clean(userRoot) {
  1863. //Initiate user folder (Initiaed in user object)
  1864. userinfo.GetHomeDirectory()
  1865. } else if !strings.Contains(filepath.ToSlash(filepath.Clean(currentDir)), "/") {
  1866. //User root not created. Create the root folder
  1867. os.MkdirAll(filepath.Clean(realpath), 0775)
  1868. } else {
  1869. //Folder not exists
  1870. log.Println("[File Explorer] Requested path: ", realpath, " does not exists!")
  1871. sendErrorResponse(w, "Folder not exists")
  1872. return
  1873. }
  1874. }
  1875. if sortMode == "" {
  1876. sortMode = "default"
  1877. }
  1878. //Check for really special exception in where the path contains [ or ] which cannot be handled via Golang Glob function
  1879. files, _ := system_fs_specialGlob(filepath.Clean(realpath) + "/*")
  1880. var parsedFilelist []fs.FileData
  1881. var shortCutInfo *shortcut.ShortcutData = nil
  1882. for _, v := range files {
  1883. //Check if it is hidden file
  1884. isHidden, _ := hidden.IsHidden(v, false)
  1885. if showHidden != "true" && isHidden {
  1886. //Skipping hidden files
  1887. continue
  1888. }
  1889. //Check if this is an aodb file
  1890. if filepath.Base(v) == "aofs.db" || filepath.Base(v) == "aofs.db.lock" {
  1891. //Database file (reserved)
  1892. continue
  1893. }
  1894. //Check if it is shortcut file. If yes, render a shortcut data struct
  1895. if filepath.Ext(v) == ".shortcut" {
  1896. //This is a shortcut file
  1897. shorcutData, err := shortcut.ReadShortcut(v)
  1898. if err == nil {
  1899. shortCutInfo = shorcutData
  1900. }
  1901. }
  1902. rawsize := fs.GetFileSize(v)
  1903. modtime, _ := fs.GetModTime(v)
  1904. thisFile := fs.FileData{
  1905. Filename: filepath.Base(v),
  1906. Filepath: currentDir + filepath.Base(v),
  1907. Realpath: v,
  1908. IsDir: IsDir(v),
  1909. Filesize: rawsize,
  1910. Displaysize: fs.GetFileDisplaySize(rawsize, 2),
  1911. ModTime: modtime,
  1912. IsShared: shareManager.FileIsShared(v),
  1913. Shortcut: shortCutInfo,
  1914. }
  1915. parsedFilelist = append(parsedFilelist, thisFile)
  1916. }
  1917. //Sort the filelist
  1918. if sortMode == "default" {
  1919. //Sort by name, convert filename to window sorting methods
  1920. sort.Slice(parsedFilelist, func(i, j int) bool {
  1921. return strings.ToLower(parsedFilelist[i].Filename) < strings.ToLower(parsedFilelist[j].Filename)
  1922. })
  1923. } else if sortMode == "reverse" {
  1924. //Sort by reverse name
  1925. sort.Slice(parsedFilelist, func(i, j int) bool {
  1926. return strings.ToLower(parsedFilelist[i].Filename) > strings.ToLower(parsedFilelist[j].Filename)
  1927. })
  1928. } else if sortMode == "smallToLarge" {
  1929. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize < parsedFilelist[j].Filesize })
  1930. } else if sortMode == "largeToSmall" {
  1931. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].Filesize > parsedFilelist[j].Filesize })
  1932. } else if sortMode == "mostRecent" {
  1933. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime > parsedFilelist[j].ModTime })
  1934. } else if sortMode == "leastRecent" {
  1935. sort.Slice(parsedFilelist, func(i, j int) bool { return parsedFilelist[i].ModTime < parsedFilelist[j].ModTime })
  1936. }
  1937. jsonString, _ := json.Marshal(parsedFilelist)
  1938. sendJSONResponse(w, string(jsonString))
  1939. }
  1940. //Handle getting a hash from a given contents in the given path
  1941. func system_fs_handleDirHash(w http.ResponseWriter, r *http.Request) {
  1942. currentDir, err := mv(r, "dir", true)
  1943. if err != nil {
  1944. sendErrorResponse(w, "Invalid dir given")
  1945. return
  1946. }
  1947. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1948. if err != nil {
  1949. sendErrorResponse(w, "User not logged in")
  1950. return
  1951. }
  1952. rpath, err := userinfo.VirtualPathToRealPath(currentDir)
  1953. if err != nil {
  1954. sendErrorResponse(w, "Invalid dir given")
  1955. return
  1956. }
  1957. //Get a list of files in this directory
  1958. currentDir = filepath.ToSlash(filepath.Clean(rpath)) + "/"
  1959. filesInDir, err := system_fs_specialGlob(currentDir + "*")
  1960. if err != nil {
  1961. sendErrorResponse(w, err.Error())
  1962. return
  1963. }
  1964. filenames := []string{}
  1965. for _, file := range filesInDir {
  1966. if len(filepath.Base(file)) > 0 && string([]rune(filepath.Base(file))[0]) != "." {
  1967. //Ignore hidden files
  1968. filenames = append(filenames, filepath.Base(file))
  1969. }
  1970. }
  1971. sort.Strings(filenames)
  1972. //Build a hash base on the filelist
  1973. h := sha256.New()
  1974. h.Write([]byte(strings.Join(filenames, ",")))
  1975. sendTextResponse(w, hex.EncodeToString((h.Sum(nil))))
  1976. }
  1977. /*
  1978. File zipping and unzipping functions
  1979. */
  1980. //Handle all zip related API
  1981. func system_fs_zipHandler(w http.ResponseWriter, r *http.Request) {
  1982. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  1983. if err != nil {
  1984. sendErrorResponse(w, err.Error())
  1985. return
  1986. }
  1987. opr, err := mv(r, "opr", true)
  1988. if err != nil {
  1989. sendErrorResponse(w, "Invalid opr or opr not defined")
  1990. return
  1991. }
  1992. vsrc, _ := mv(r, "src", true)
  1993. if vsrc == "" {
  1994. sendErrorResponse(w, "Invalid src paramter")
  1995. return
  1996. }
  1997. vdest, _ := mv(r, "dest", true)
  1998. rdest := ""
  1999. //Convert source path from JSON string to object
  2000. virtualSourcePaths := []string{}
  2001. err = json.Unmarshal([]byte(vsrc), &virtualSourcePaths)
  2002. if err != nil {
  2003. sendErrorResponse(w, err.Error())
  2004. return
  2005. }
  2006. //Check each of the path
  2007. realSourcePaths := []string{}
  2008. for _, vpath := range virtualSourcePaths {
  2009. thisrpath, err := userinfo.VirtualPathToRealPath(vpath)
  2010. if err != nil || !fileExists(thisrpath) {
  2011. sendErrorResponse(w, "File not exists: "+vpath)
  2012. return
  2013. }
  2014. realSourcePaths = append(realSourcePaths, thisrpath)
  2015. }
  2016. ///Convert dest to real if given
  2017. if vdest != "" {
  2018. realdest, _ := userinfo.VirtualPathToRealPath(vdest)
  2019. rdest = realdest
  2020. }
  2021. //This function will be deprecate soon in ArozOS 1.120
  2022. log.Println("*DEPRECATE* zipHandler will be deprecating soon! Please use fileOpr endpoint")
  2023. if opr == "zip" {
  2024. //Check if destination location exists
  2025. if rdest == "" || !fileExists(filepath.Dir(rdest)) {
  2026. sendErrorResponse(w, "Invalid dest location")
  2027. return
  2028. }
  2029. //OK. Create the zip at the desired location
  2030. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  2031. if err != nil {
  2032. sendErrorResponse(w, err.Error())
  2033. return
  2034. }
  2035. sendOK(w)
  2036. } else if opr == "tmpzip" {
  2037. //Zip to tmp folder
  2038. userTmpFolder, _ := userinfo.VirtualPathToRealPath("tmp:/")
  2039. filename := Int64ToString(GetUnixTime()) + ".zip"
  2040. rdest := filepath.ToSlash(filepath.Clean(userTmpFolder)) + "/" + filename
  2041. log.Println(realSourcePaths, rdest)
  2042. err := fs.ArozZipFile(realSourcePaths, rdest, false)
  2043. if err != nil {
  2044. sendErrorResponse(w, err.Error())
  2045. return
  2046. }
  2047. //Send the tmp filename to the user
  2048. sendTextResponse(w, "tmp:/"+filename)
  2049. } else if opr == "inspect" {
  2050. } else if opr == "unzip" {
  2051. }
  2052. }
  2053. //Translate path from and to virtual and realpath
  2054. func system_fs_handlePathTranslate(w http.ResponseWriter, r *http.Request) {
  2055. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2056. if err != nil {
  2057. sendErrorResponse(w, err.Error())
  2058. return
  2059. }
  2060. path, err := mv(r, "path", false)
  2061. if err != nil {
  2062. sendErrorResponse(w, "Invalid path given")
  2063. return
  2064. }
  2065. rpath, err := userinfo.VirtualPathToRealPath(path)
  2066. if err != nil {
  2067. //Try to convert it to virtualPath
  2068. vpath, err := userinfo.RealPathToVirtualPath(path)
  2069. if err != nil {
  2070. sendErrorResponse(w, "Unknown path given")
  2071. } else {
  2072. jsonstring, _ := json.Marshal(vpath)
  2073. sendJSONResponse(w, string(jsonstring))
  2074. }
  2075. } else {
  2076. abrpath, _ := filepath.Abs(rpath)
  2077. jsonstring, _ := json.Marshal([]string{rpath, filepath.ToSlash(abrpath)})
  2078. sendJSONResponse(w, string(jsonstring))
  2079. }
  2080. }
  2081. //Handle cache rendering with websocket pipeline
  2082. func system_fs_handleCacheRender(w http.ResponseWriter, r *http.Request) {
  2083. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2084. vpath, err := mv(r, "folder", false)
  2085. if err != nil {
  2086. sendErrorResponse(w, "Invalid folder paramter")
  2087. return
  2088. }
  2089. //Convert vpath to realpath
  2090. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  2091. if err != nil {
  2092. sendErrorResponse(w, err.Error())
  2093. return
  2094. }
  2095. //Get folder sort mode
  2096. sortMode := "default"
  2097. folder := filepath.ToSlash(filepath.Clean(vpath))
  2098. if sysdb.KeyExists("fs-sortpref", userinfo.Username+"/"+folder) {
  2099. sysdb.Read("fs-sortpref", userinfo.Username+"/"+folder, &sortMode)
  2100. }
  2101. //Perform cache rendering
  2102. thumbRenderHandler.HandleLoadCache(w, r, rpath, sortMode)
  2103. }
  2104. //Handle loading of one thumbnail
  2105. func system_fs_handleThumbnailLoad(w http.ResponseWriter, r *http.Request) {
  2106. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2107. vpath, err := mv(r, "vpath", false)
  2108. if err != nil {
  2109. sendErrorResponse(w, "vpath not defined")
  2110. return
  2111. }
  2112. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  2113. if err != nil {
  2114. sendErrorResponse(w, err.Error())
  2115. return
  2116. }
  2117. byteMode, _ := mv(r, "bytes", false)
  2118. if byteMode == "true" {
  2119. thumbnailBytes, err := thumbRenderHandler.LoadCacheAsBytes(rpath, false)
  2120. if err != nil {
  2121. sendErrorResponse(w, err.Error())
  2122. return
  2123. }
  2124. filetype := http.DetectContentType(thumbnailBytes)
  2125. w.Header().Add("Content-Type", filetype)
  2126. w.Write(thumbnailBytes)
  2127. } else {
  2128. thumbnailPath, err := thumbRenderHandler.LoadCache(rpath, false)
  2129. if err != nil {
  2130. sendErrorResponse(w, err.Error())
  2131. return
  2132. }
  2133. js, _ := json.Marshal(thumbnailPath)
  2134. sendJSONResponse(w, string(js))
  2135. }
  2136. }
  2137. //Handle file thumbnail caching
  2138. func system_fs_handleFolderCache(w http.ResponseWriter, r *http.Request) {
  2139. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  2140. vfolderpath, err := mv(r, "folder", false)
  2141. if err != nil {
  2142. sendErrorResponse(w, "folder not defined")
  2143. return
  2144. }
  2145. rpath, err := userinfo.VirtualPathToRealPath(vfolderpath)
  2146. if err != nil {
  2147. sendErrorResponse(w, err.Error())
  2148. return
  2149. }
  2150. thumbRenderHandler.BuildCacheForFolder(rpath)
  2151. sendOK(w)
  2152. }
  2153. //Handle the get and set of sort mode of a particular folder
  2154. func system_fs_handleFolderSortModePreference(w http.ResponseWriter, r *http.Request) {
  2155. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2156. if err != nil {
  2157. sendErrorResponse(w, "User not logged in")
  2158. return
  2159. }
  2160. folder, err := mv(r, "folder", true)
  2161. if err != nil {
  2162. sendErrorResponse(w, "Invalid folder given")
  2163. return
  2164. }
  2165. opr, _ := mv(r, "opr", true)
  2166. folder = filepath.ToSlash(filepath.Clean(folder))
  2167. if opr == "" || opr == "get" {
  2168. sortMode := "default"
  2169. if sysdb.KeyExists("fs-sortpref", userinfo.Username+"/"+folder) {
  2170. sysdb.Read("fs-sortpref", userinfo.Username+"/"+folder, &sortMode)
  2171. }
  2172. js, _ := json.Marshal(sortMode)
  2173. sendJSONResponse(w, string(js))
  2174. } else if opr == "set" {
  2175. sortMode, err := mv(r, "mode", true)
  2176. if err != nil {
  2177. sendErrorResponse(w, "Invalid sort mode given")
  2178. return
  2179. }
  2180. if !stringInSlice(sortMode, []string{"default", "reverse", "smallToLarge", "largeToSmall", "mostRecent", "leastRecent"}) {
  2181. sendErrorResponse(w, "Not supported sort mode: "+sortMode)
  2182. return
  2183. }
  2184. sysdb.Write("fs-sortpref", userinfo.Username+"/"+folder, sortMode)
  2185. sendOK(w)
  2186. } else {
  2187. sendErrorResponse(w, "Invalid opr mode")
  2188. return
  2189. }
  2190. }
  2191. //Handle setting and loading of file permission on Linux
  2192. func system_fs_handleFilePermission(w http.ResponseWriter, r *http.Request) {
  2193. file, err := mv(r, "file", true)
  2194. if err != nil {
  2195. sendErrorResponse(w, "Invalid file")
  2196. return
  2197. }
  2198. //Translate the file to real path
  2199. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  2200. if err != nil {
  2201. sendErrorResponse(w, "User not logged in")
  2202. return
  2203. }
  2204. rpath, err := userinfo.VirtualPathToRealPath(file)
  2205. if err != nil {
  2206. sendErrorResponse(w, err.Error())
  2207. return
  2208. }
  2209. newMode, _ := mv(r, "mode", true)
  2210. if newMode == "" {
  2211. //Read the file mode
  2212. //Check if the file exists
  2213. if !fileExists(rpath) {
  2214. sendErrorResponse(w, "File not exists!")
  2215. return
  2216. }
  2217. //Read the file permission
  2218. filePermission, err := fsp.GetFilePermissions(rpath)
  2219. if err != nil {
  2220. sendErrorResponse(w, err.Error())
  2221. return
  2222. }
  2223. //Send the file permission to client
  2224. js, _ := json.Marshal(filePermission)
  2225. sendJSONResponse(w, string(js))
  2226. } else {
  2227. //Set the file mode
  2228. //Check if the file exists
  2229. if !fileExists(rpath) {
  2230. sendErrorResponse(w, "File not exists!")
  2231. return
  2232. }
  2233. //Check if windows. If yes, ignore this request
  2234. if runtime.GOOS == "windows" {
  2235. sendErrorResponse(w, "Windows host not supported")
  2236. return
  2237. }
  2238. //Check if this user has permission to change the file permission
  2239. //Aka user must be 1. This is his own folder or 2. Admin
  2240. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(file)
  2241. if fsh.Hierarchy == "user" {
  2242. //Always ok as this is owned by the user
  2243. } else if fsh.Hierarchy == "public" {
  2244. //Require admin
  2245. if userinfo.IsAdmin() == false {
  2246. sendErrorResponse(w, "Permission Denied")
  2247. return
  2248. }
  2249. } else {
  2250. //Not implemeneted. Require admin
  2251. if userinfo.IsAdmin() == false {
  2252. sendErrorResponse(w, "Permission Denied")
  2253. return
  2254. }
  2255. }
  2256. //Be noted that if the system is not running in sudo mode,
  2257. //File permission change might not works.
  2258. err := fsp.SetFilePermisson(rpath, newMode)
  2259. if err != nil {
  2260. sendErrorResponse(w, err.Error())
  2261. return
  2262. } else {
  2263. sendOK(w)
  2264. }
  2265. }
  2266. }
  2267. //Check if the given filepath is and must inside the given directory path.
  2268. //You can pass both as relative
  2269. func system_fs_checkFileInDirectory(filesourcepath string, directory string) bool {
  2270. filepathAbs, err := filepath.Abs(filesourcepath)
  2271. if err != nil {
  2272. return false
  2273. }
  2274. directoryAbs, err := filepath.Abs(directory)
  2275. if err != nil {
  2276. return false
  2277. }
  2278. //Check if the filepathabs contain directoryAbs
  2279. if strings.Contains(filepathAbs, directoryAbs) {
  2280. return true
  2281. } else {
  2282. return false
  2283. }
  2284. }
  2285. //Clear the old files inside the tmp file
  2286. func system_fs_clearOldTmpFiles() {
  2287. filesToBeDelete := []string{}
  2288. tmpAbs, _ := filepath.Abs(*tmp_directory)
  2289. filepath.Walk(*tmp_directory, func(path string, info os.FileInfo, err error) error {
  2290. if filepath.Base(path) != "aofs.db" && filepath.Base(path) != "aofs.db.lock" {
  2291. //Check if root folders. Do not delete root folders
  2292. parentAbs, _ := filepath.Abs(filepath.Dir(path))
  2293. if tmpAbs == parentAbs {
  2294. //Root folder. Do not remove
  2295. return nil
  2296. }
  2297. //Get its modification time
  2298. modTime, err := fs.GetModTime(path)
  2299. if err != nil {
  2300. return nil
  2301. }
  2302. //Check if mod time is more than 24 hours ago
  2303. if time.Now().Unix()-modTime > int64(*maxTempFileKeepTime) {
  2304. //Delete OK
  2305. filesToBeDelete = append(filesToBeDelete, path)
  2306. }
  2307. }
  2308. return nil
  2309. })
  2310. //Remove all files from the delete list
  2311. for _, fileToBeDelete := range filesToBeDelete {
  2312. os.RemoveAll(fileToBeDelete)
  2313. }
  2314. }