share.go 21 KB

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