file_system.go 76 KB

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