share.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. package share
  2. /*
  3. Arozos File Share Manager
  4. author: tobychui
  5. This module handle file share request and other stuffs
  6. */
  7. import (
  8. "encoding/json"
  9. "errors"
  10. "io/ioutil"
  11. "log"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "path/filepath"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/valyala/fasttemplate"
  21. uuid "github.com/satori/go.uuid"
  22. "imuslab.com/arozos/mod/auth"
  23. "imuslab.com/arozos/mod/database"
  24. filesystem "imuslab.com/arozos/mod/filesystem"
  25. "imuslab.com/arozos/mod/user"
  26. )
  27. type Options struct {
  28. AuthAgent *auth.AuthAgent
  29. Database *database.Database
  30. UserHandler *user.UserHandler
  31. HostName string
  32. TmpFolder string
  33. }
  34. type ShareOption struct {
  35. UUID string
  36. FileRealPath string
  37. Owner string
  38. Accessibles []string //Use to store username or group names if permission is groups or users
  39. Permission string //Access permission, allow {anyone / signedin / samegroup / groups / users}
  40. AllowLivePreview bool
  41. }
  42. type Manager struct {
  43. fileToUrlMap *sync.Map
  44. urlToFileMap *sync.Map
  45. options Options
  46. }
  47. //Create a new Share Manager
  48. func NewShareManager(options Options) *Manager {
  49. //Create the share table if not exists
  50. db := options.Database
  51. db.NewTable("share")
  52. fileToUrlMap := sync.Map{}
  53. urlToFileMap := sync.Map{}
  54. //Load the old share links
  55. entries, _ := db.ListTable("share")
  56. for _, keypairs := range entries {
  57. shareObject := new(ShareOption)
  58. json.Unmarshal(keypairs[1], &shareObject)
  59. if shareObject != nil {
  60. //Append this to the maps
  61. fileToUrlMap.Store(shareObject.FileRealPath, shareObject)
  62. urlToFileMap.Store(shareObject.UUID, shareObject)
  63. }
  64. }
  65. //Return a new manager object
  66. return &Manager{
  67. options: options,
  68. fileToUrlMap: &fileToUrlMap,
  69. urlToFileMap: &urlToFileMap,
  70. }
  71. }
  72. //Main function for handle share. Must be called with http.HandleFunc (No auth)
  73. func (s *Manager) HandleShareAccess(w http.ResponseWriter, r *http.Request) {
  74. id, err := mv(r, "id", false)
  75. if err != nil {
  76. http.NotFound(w, r)
  77. return
  78. }
  79. directDownload := false
  80. directServe := false
  81. download, _ := mv(r, "download", false)
  82. if download == "true" {
  83. directDownload = true
  84. }
  85. serve, _ := mv(r, "serve", false)
  86. if serve == "true" {
  87. directServe = true
  88. }
  89. relpath, _ := mv(r, "rel", false)
  90. //Check if id exists
  91. val, ok := s.urlToFileMap.Load(id)
  92. if ok {
  93. //Parse the option structure
  94. shareOption := val.(*ShareOption)
  95. //Check for permission
  96. if shareOption.Permission == "anyone" {
  97. //OK to proceed
  98. } else if shareOption.Permission == "signedin" {
  99. if s.options.AuthAgent.CheckAuth(r) == false {
  100. //Redirect to login page
  101. if directDownload || directServe {
  102. w.WriteHeader(http.StatusUnauthorized)
  103. w.Write([]byte("401 - Unauthorized"))
  104. } else {
  105. http.Redirect(w, r, "/login.system?redirect=/share?id="+id, 307)
  106. }
  107. return
  108. } else {
  109. //Ok to proccedd
  110. }
  111. } else if shareOption.Permission == "samegroup" {
  112. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  113. if err != nil {
  114. if directDownload || directServe {
  115. w.WriteHeader(http.StatusUnauthorized)
  116. w.Write([]byte("401 - Unauthorized"))
  117. } else {
  118. http.Redirect(w, r, "/login.system?redirect=/share?id="+id, 307)
  119. }
  120. return
  121. }
  122. //Check if all the user groups are inside the share owner groups
  123. valid := true
  124. thisUsersGroupByName := []string{}
  125. for _, pg := range thisuserinfo.PermissionGroup {
  126. thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
  127. }
  128. for _, allowedpg := range shareOption.Accessibles {
  129. if inArray(thisUsersGroupByName, allowedpg) {
  130. //This required group is inside this user's group. OK
  131. } else {
  132. //This required group is not inside user's group. Reject
  133. valid = false
  134. }
  135. }
  136. if !valid {
  137. //Serve permission denied page
  138. if directDownload || directServe {
  139. w.WriteHeader(http.StatusForbidden)
  140. w.Write([]byte("401 - Forbidden"))
  141. } else {
  142. w.Write([]byte("Permission Denied page WIP"))
  143. }
  144. return
  145. }
  146. } else if shareOption.Permission == "users" {
  147. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  148. if err != nil {
  149. //User not logged in. Redirect to login page
  150. if directDownload || directServe {
  151. w.WriteHeader(http.StatusUnauthorized)
  152. w.Write([]byte("401 - Unauthorized"))
  153. } else {
  154. http.Redirect(w, r, "/login.system?redirect=/share?id="+id, 307)
  155. }
  156. return
  157. }
  158. //Check if username in the allowed user list
  159. if !inArray(shareOption.Accessibles, thisuserinfo.Username) {
  160. //Serve permission denied page
  161. //Serve permission denied page
  162. if directDownload || directServe {
  163. w.WriteHeader(http.StatusForbidden)
  164. w.Write([]byte("401 - Forbidden"))
  165. } else {
  166. w.Write([]byte("Permission Denied page WIP"))
  167. }
  168. return
  169. }
  170. } else if shareOption.Permission == "groups" {
  171. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  172. if err != nil {
  173. //User not logged in. Redirect to login page
  174. if directDownload || directServe {
  175. w.WriteHeader(http.StatusUnauthorized)
  176. w.Write([]byte("401 - Unauthorized"))
  177. } else {
  178. http.Redirect(w, r, "/login.system?redirect=/share?id="+id, 307)
  179. }
  180. return
  181. }
  182. allowAccess := false
  183. thisUsersGroupByName := []string{}
  184. for _, pg := range thisuserinfo.PermissionGroup {
  185. thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
  186. }
  187. for _, thisUserPg := range thisUsersGroupByName {
  188. if inArray(shareOption.Accessibles, thisUserPg) {
  189. allowAccess = true
  190. }
  191. }
  192. if !allowAccess {
  193. //Serve permission denied page
  194. if directDownload || directServe {
  195. w.WriteHeader(http.StatusForbidden)
  196. w.Write([]byte("401 - Forbidden"))
  197. } else {
  198. w.Write([]byte("Permission Denied page WIP"))
  199. }
  200. return
  201. }
  202. } else {
  203. //Unsupported mode. Show notfound
  204. http.NotFound(w, r)
  205. return
  206. }
  207. //Serve the download page
  208. if isDir(shareOption.FileRealPath) {
  209. type File struct {
  210. Filename string
  211. RelPath string
  212. Filesize string
  213. IsDir bool
  214. }
  215. if directDownload == true {
  216. if relpath != "" {
  217. //User specified a specific file within the directory. Escape the relpath
  218. targetFilepath := filepath.Join(shareOption.FileRealPath, relpath)
  219. //Check if file exists
  220. if !fileExists(targetFilepath) {
  221. http.NotFound(w, r)
  222. return
  223. }
  224. //Validate the absolute path to prevent path escape
  225. absroot, _ := filepath.Abs(shareOption.FileRealPath)
  226. abstarget, _ := filepath.Abs(targetFilepath)
  227. if len(abstarget) <= len(absroot) || abstarget[:len(absroot)] != absroot {
  228. //Directory escape detected
  229. w.WriteHeader(http.StatusBadRequest)
  230. w.Write([]byte("400 - Bad Request: Invalid relative path"))
  231. return
  232. }
  233. //Serve the target file
  234. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(targetFilepath)), "+", "%20"))
  235. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  236. http.ServeFile(w, r, targetFilepath)
  237. sendOK(w)
  238. } else {
  239. //Download this folder as zip
  240. //Build the filelist to download
  241. //Create a zip using ArOZ Zipper, tmp zip files are located under tmp/share-cache/*.zip
  242. tmpFolder := s.options.TmpFolder
  243. tmpFolder = filepath.Join(tmpFolder, "share-cache")
  244. os.MkdirAll(tmpFolder, 0755)
  245. targetZipFilename := filepath.Join(tmpFolder, filepath.Base(shareOption.FileRealPath)) + ".zip"
  246. //Build a filelist
  247. err := filesystem.ArozZipFile([]string{shareOption.FileRealPath}, targetZipFilename, false)
  248. if err != nil {
  249. //Failed to create zip file
  250. w.WriteHeader(http.StatusInternalServerError)
  251. w.Write([]byte("500 - Internal Server Error: Zip file creation failed"))
  252. log.Println("Failed to create zip file for share download: " + err.Error())
  253. return
  254. }
  255. //Serve thje zip file
  256. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(shareOption.FileRealPath)), "+", "%20")+".zip")
  257. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  258. http.ServeFile(w, r, targetZipFilename)
  259. }
  260. } else {
  261. //Show download page. Do not allow serving
  262. content, err := ioutil.ReadFile("./system/share/downloadPageFolder.html")
  263. if err != nil {
  264. http.NotFound(w, r)
  265. return
  266. }
  267. //Get file size
  268. fsize, fcount := filesystem.GetDirctorySize(shareOption.FileRealPath, false)
  269. //Build the tree list of the folder
  270. treeList := map[string][]File{}
  271. err = filepath.Walk(filepath.Clean(shareOption.FileRealPath), func(file string, info os.FileInfo, err error) error {
  272. if err != nil {
  273. //If error skip this
  274. return nil
  275. }
  276. if filepath.Base(file)[:1] != "." {
  277. fileSize := filesystem.GetFileSize(file)
  278. if filesystem.IsDir(file) {
  279. fileSize, _ = filesystem.GetDirctorySize(file, false)
  280. }
  281. relPath, err := filepath.Rel(shareOption.FileRealPath, file)
  282. if err != nil {
  283. relPath = ""
  284. }
  285. relPath = filepath.ToSlash(filepath.Clean(relPath))
  286. relDir := filepath.ToSlash(filepath.Dir(relPath))
  287. if relPath == "." {
  288. //The root file object. Skip this
  289. return nil
  290. }
  291. treeList[relDir] = append(treeList[relDir], File{
  292. Filename: filepath.Base(file),
  293. RelPath: filepath.ToSlash(relPath),
  294. Filesize: filesystem.GetFileDisplaySize(fileSize, 2),
  295. IsDir: filesystem.IsDir(file),
  296. })
  297. }
  298. return nil
  299. })
  300. tl, _ := json.Marshal(treeList)
  301. //Get modification time
  302. fmodtime, _ := filesystem.GetModTime(shareOption.FileRealPath)
  303. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  304. t := fasttemplate.New(string(content), "{{", "}}")
  305. s := t.ExecuteString(map[string]interface{}{
  306. "hostname": s.options.HostName,
  307. "reqid": id,
  308. "mime": "application/x-directory",
  309. "size": filesystem.GetFileDisplaySize(fsize, 2),
  310. "filecount": strconv.Itoa(fcount),
  311. "modtime": timeString,
  312. "downloadurl": "./share?id=" + id + "&download=true",
  313. "filename": filepath.Base(shareOption.FileRealPath),
  314. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  315. "treelist": tl,
  316. "downloaduuid": id,
  317. })
  318. w.Write([]byte(s))
  319. return
  320. }
  321. } else {
  322. if directDownload == true {
  323. //Serve the file directly
  324. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(shareOption.FileRealPath)), "+", "%20"))
  325. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  326. http.ServeFile(w, r, shareOption.FileRealPath)
  327. } else if directServe == true {
  328. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  329. http.ServeFile(w, r, shareOption.FileRealPath)
  330. } else {
  331. //Serve the download page
  332. content, err := ioutil.ReadFile("./system/share/downloadPage.html")
  333. if err != nil {
  334. http.NotFound(w, r)
  335. return
  336. }
  337. //Get file mime type
  338. mime, ext, err := filesystem.GetMime(shareOption.FileRealPath)
  339. if err != nil {
  340. mime = "Unknown"
  341. }
  342. //Load the preview template
  343. templateRoot := "./system/share/"
  344. previewTemplate := filepath.Join(templateRoot, "defaultTemplate.html")
  345. if ext == ".mp4" || ext == ".webm" {
  346. previewTemplate = filepath.Join(templateRoot, "video.html")
  347. } else if ext == ".mp3" || ext == ".wav" || ext == ".flac" || ext == ".ogg" {
  348. previewTemplate = filepath.Join(templateRoot, "audio.html")
  349. } else if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".webp" {
  350. previewTemplate = filepath.Join(templateRoot, "image.html")
  351. } else if ext == ".pdf" {
  352. previewTemplate = filepath.Join(templateRoot, "iframe.html")
  353. } else {
  354. //Format do not support preview. Use the default.html
  355. previewTemplate = filepath.Join(templateRoot, "default.html")
  356. }
  357. tp, err := ioutil.ReadFile(previewTemplate)
  358. if err != nil {
  359. tp = []byte("")
  360. }
  361. //Merge two templates
  362. content = []byte(strings.ReplaceAll(string(content), "{{previewer}}", string(tp)))
  363. //Get file size
  364. fsize := filesystem.GetFileSize(shareOption.FileRealPath)
  365. //Get modification time
  366. fmodtime, _ := filesystem.GetModTime(shareOption.FileRealPath)
  367. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  368. t := fasttemplate.New(string(content), "{{", "}}")
  369. s := t.ExecuteString(map[string]interface{}{
  370. "hostname": s.options.HostName,
  371. "reqid": id,
  372. "mime": mime,
  373. "ext": ext,
  374. "size": filesystem.GetFileDisplaySize(fsize, 2),
  375. "modtime": timeString,
  376. "downloadurl": "/share?id=" + id + "&download=true",
  377. "preview_url": "/share?id=" + id + "&serve=true",
  378. "filename": filepath.Base(shareOption.FileRealPath),
  379. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  380. })
  381. w.Write([]byte(s))
  382. return
  383. }
  384. }
  385. } else {
  386. //This share not exists
  387. if err != nil {
  388. //Template not found. Just send a 404 Not Found
  389. http.NotFound(w, r)
  390. return
  391. }
  392. if directDownload == true {
  393. //Send 404 header
  394. http.NotFound(w, r)
  395. return
  396. } else {
  397. //Send not found page
  398. content, err := ioutil.ReadFile("./system/share/notfound.html")
  399. if err != nil {
  400. http.NotFound(w, r)
  401. return
  402. }
  403. t := fasttemplate.New(string(content), "{{", "}}")
  404. s := t.ExecuteString(map[string]interface{}{
  405. "hostname": s.options.HostName,
  406. "reqid": id,
  407. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  408. })
  409. w.Write([]byte(s))
  410. return
  411. }
  412. }
  413. }
  414. //Create new share from the given path
  415. func (s *Manager) HandleCreateNewShare(w http.ResponseWriter, r *http.Request) {
  416. //Get the vpath from paramters
  417. vpath, err := mv(r, "path", true)
  418. if err != nil {
  419. sendErrorResponse(w, "Invalid path given")
  420. return
  421. }
  422. //Get userinfo
  423. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  424. if err != nil {
  425. sendErrorResponse(w, "User not logged in")
  426. return
  427. }
  428. share, err := s.CreateNewShare(userinfo, vpath)
  429. if err != nil {
  430. sendErrorResponse(w, err.Error())
  431. return
  432. }
  433. js, _ := json.Marshal(share)
  434. sendJSONResponse(w, string(js))
  435. }
  436. // Handle Share Edit.
  437. // For allowing groups / users, use the following syntax
  438. // groups:group1,group2,group3
  439. // users:user1,user2,user3
  440. // For basic modes, use the following keywords
  441. // anyone / signedin / samegroup
  442. // anyone: Anyone who has the link
  443. // signedin: Anyone logged in to this system
  444. // samegroup: The requesting user has the same (or more) user group as the share owner
  445. func (s *Manager) HandleEditShare(w http.ResponseWriter, r *http.Request) {
  446. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  447. if err != nil {
  448. sendErrorResponse(w, "User not logged in")
  449. return
  450. }
  451. uuid, err := mv(r, "uuid", true)
  452. if err != nil {
  453. sendErrorResponse(w, "Invalid path given")
  454. return
  455. }
  456. shareMode, _ := mv(r, "mode", true)
  457. if shareMode == "" {
  458. shareMode = "signedin"
  459. }
  460. //Check if share exists
  461. so := s.GetShareObjectFromUUID(uuid)
  462. if so == nil {
  463. //This share url not exists
  464. sendErrorResponse(w, "Share UUID not exists")
  465. return
  466. }
  467. //Check if the user has permission to edit this share
  468. if so.Owner != userinfo.Username && userinfo.IsAdmin() == false {
  469. //This file is not shared by this user and this user is not admin. Block this request
  470. sendErrorResponse(w, "Permission denied")
  471. return
  472. }
  473. //Validate and extract the storage mode
  474. ok, sharetype, settings := validateShareModes(shareMode)
  475. if !ok {
  476. sendErrorResponse(w, "Invalid share setting")
  477. return
  478. }
  479. //Analysis the sharetype
  480. if sharetype == "anyone" || sharetype == "signedin" || sharetype == "samegroup" {
  481. //Basic types.
  482. so.Permission = sharetype
  483. if sharetype == "samegroup" {
  484. //Write user groups into accessible (Must be all match inorder to allow access)
  485. userpg := []string{}
  486. for _, pg := range userinfo.PermissionGroup {
  487. userpg = append(userpg, pg.Name)
  488. }
  489. so.Accessibles = userpg
  490. }
  491. //Write changes to database
  492. s.options.Database.Write("share", uuid, so)
  493. } else if sharetype == "groups" || sharetype == "users" {
  494. //Username or group is listed = ok
  495. so.Permission = sharetype
  496. so.Accessibles = settings
  497. //Write changes to database
  498. s.options.Database.Write("share", uuid, so)
  499. }
  500. sendOK(w)
  501. }
  502. func (s *Manager) HandleDeleteShare(w http.ResponseWriter, r *http.Request) {
  503. //Get the vpath from paramters
  504. vpath, err := mv(r, "path", true)
  505. if err != nil {
  506. sendErrorResponse(w, "Invalid path given")
  507. return
  508. }
  509. //Get userinfo
  510. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  511. if err != nil {
  512. sendErrorResponse(w, "User not logged in")
  513. return
  514. }
  515. //Delete the share setting
  516. err = s.DeleteShare(userinfo, vpath)
  517. if err != nil {
  518. sendErrorResponse(w, err.Error())
  519. } else {
  520. sendOK(w)
  521. }
  522. }
  523. //Craete a new file or folder share
  524. func (s *Manager) CreateNewShare(userinfo *user.User, vpath string) (*ShareOption, error) {
  525. //Translate the vpath to realpath
  526. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  527. if err != nil {
  528. return nil, errors.New("Unable to find the file on disk")
  529. }
  530. rpath = filepath.ToSlash(filepath.Clean(rpath))
  531. //Check if source file exists
  532. if !fileExists(rpath) {
  533. return nil, errors.New("Unable to find the file on disk")
  534. }
  535. //Check if the share already exists. If yes, use the previous link
  536. val, ok := s.fileToUrlMap.Load(rpath)
  537. if ok {
  538. //Exists. Send back the old share url
  539. ShareOption := val.(*ShareOption)
  540. return ShareOption, nil
  541. } else {
  542. //Create new link for this file
  543. shareUUID := uuid.NewV4().String()
  544. //user groups when share
  545. groups := []string{}
  546. for _, pg := range userinfo.GetUserPermissionGroup() {
  547. groups = append(groups, pg.Name)
  548. }
  549. //Create a share object
  550. shareOption := ShareOption{
  551. UUID: shareUUID,
  552. FileRealPath: rpath,
  553. Owner: userinfo.Username,
  554. Accessibles: groups,
  555. Permission: "anyone",
  556. AllowLivePreview: true,
  557. }
  558. //Store results on two map to make sure O(1) Lookup time
  559. s.fileToUrlMap.Store(rpath, &shareOption)
  560. s.urlToFileMap.Store(shareUUID, &shareOption)
  561. //Write object to database
  562. s.options.Database.Write("share", shareUUID, shareOption)
  563. return &shareOption, nil
  564. }
  565. }
  566. //Delete the share on this vpath
  567. func (s *Manager) DeleteShare(userinfo *user.User, vpath string) error {
  568. //Translate the vpath to realpath
  569. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  570. if err != nil {
  571. return errors.New("Unable to find the file on disk")
  572. }
  573. //Check if the share already exists. If yes, use the previous link
  574. val, ok := s.fileToUrlMap.Load(rpath)
  575. if ok {
  576. //Exists. Send back the old share url
  577. uuid := val.(*ShareOption).UUID
  578. //Remove this from the database
  579. err = s.options.Database.Delete("share", uuid)
  580. if err != nil {
  581. return err
  582. }
  583. //Remove this form the current sync map
  584. s.urlToFileMap.Delete(uuid)
  585. s.fileToUrlMap.Delete(rpath)
  586. return nil
  587. } else {
  588. //Already deleted from buffered record.
  589. return nil
  590. }
  591. }
  592. func (s *Manager) GetShareUUIDFromPath(rpath string) string {
  593. targetShareObject := s.GetShareObjectFromRealPath(rpath)
  594. if (targetShareObject) != nil {
  595. return targetShareObject.UUID
  596. }
  597. return ""
  598. }
  599. func (s *Manager) GetShareObjectFromRealPath(rpath string) *ShareOption {
  600. rpath = filepath.ToSlash(filepath.Clean(rpath))
  601. var targetShareOption *ShareOption
  602. s.fileToUrlMap.Range(func(k, v interface{}) bool {
  603. filePath := k.(string)
  604. shareObject := v.(*ShareOption)
  605. if filepath.ToSlash(filepath.Clean(filePath)) == rpath {
  606. targetShareOption = shareObject
  607. }
  608. return true
  609. })
  610. return targetShareOption
  611. }
  612. func (s *Manager) GetShareObjectFromUUID(uuid string) *ShareOption {
  613. var targetShareOption *ShareOption
  614. s.urlToFileMap.Range(func(k, v interface{}) bool {
  615. thisUuid := k.(string)
  616. shareObject := v.(*ShareOption)
  617. if thisUuid == uuid {
  618. targetShareOption = shareObject
  619. }
  620. return true
  621. })
  622. return targetShareOption
  623. }
  624. func (s *Manager) FileIsShared(rpath string) bool {
  625. shareUUID := s.GetShareUUIDFromPath(rpath)
  626. return shareUUID != ""
  627. }
  628. /*
  629. Validate Share Mode string
  630. will return
  631. 1. bool => Is valid
  632. 2. permission type: {basic / groups / users}
  633. 3. mode string
  634. */
  635. func validateShareModes(mode string) (bool, string, []string) {
  636. // user:a,b,c,d
  637. validModes := []string{"anyone", "signedin", "samegroup"}
  638. if inArray(validModes, mode) {
  639. //Standard modes
  640. return true, mode, []string{}
  641. } else if len(mode) > 7 && mode[:7] == "groups:" {
  642. //Handle custom group case like groups:a,b,c,d
  643. groupList := mode[7:]
  644. if len(groupList) > 0 {
  645. groups := strings.Split(groupList, ",")
  646. return true, "groups", groups
  647. } else {
  648. //Invalid configuration
  649. return false, "groups", []string{}
  650. }
  651. } else if len(mode) > 6 && mode[:6] == "users:" {
  652. //Handle custom usersname like users:a,b,c,d
  653. userList := mode[6:]
  654. if len(userList) > 0 {
  655. users := strings.Split(userList, ",")
  656. return true, "users", users
  657. } else {
  658. //Invalid configuration
  659. return false, "users", []string{}
  660. }
  661. }
  662. return false, "", []string{}
  663. }
  664. func (s *Manager) RemoveShareByRealpath(rpath string) error {
  665. _, ok := s.fileToUrlMap.Load(rpath)
  666. if ok {
  667. s.fileToUrlMap.Delete(rpath)
  668. } else {
  669. return errors.New("Share with given realpath not exists")
  670. }
  671. return nil
  672. }
  673. func (s *Manager) RemoveShareByUUID(uuid string) error {
  674. _, ok := s.urlToFileMap.Load(uuid)
  675. if ok {
  676. s.urlToFileMap.Delete(uuid)
  677. } else {
  678. return errors.New("Share with given uuid not exists")
  679. }
  680. return nil
  681. }
  682. //Check and clear shares that its pointinf files no longe exists
  683. func (s *Manager) ValidateAndClearShares() {
  684. //Iterate through all shares within the system
  685. s.fileToUrlMap.Range(func(k, v interface{}) bool {
  686. thisRealPath := k.(string)
  687. if !fileExists(thisRealPath) {
  688. //This share source file don't exists anymore. Remove it
  689. thisFileShareOption := v.(*ShareOption)
  690. //Delete this task from both sync map
  691. s.RemoveShareByRealpath(thisRealPath)
  692. s.RemoveShareByUUID(thisFileShareOption.UUID)
  693. //Remove share from database
  694. s.options.Database.Delete("share", thisFileShareOption.UUID)
  695. log.Println("*Share* Removing share to file: " + thisRealPath + " as it no longer exists")
  696. }
  697. return true
  698. })
  699. }