share.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  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. fs "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 := fs.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 := fs.GetDirctorySize(shareOption.FileRealPath, false)
  244. //Build the filelist of the root folder
  245. rawFilelist, _ := fs.WGlob(filepath.Clean(shareOption.FileRealPath) + "/*")
  246. rootVisableFiles := []File{}
  247. for _, file := range rawFilelist {
  248. if filepath.Base(file)[:1] != "." {
  249. //Not hidden folder.
  250. fileSize := fs.GetFileSize(file)
  251. if fs.IsDir(file) {
  252. fileSize, _ = fs.GetDirctorySize(file, false)
  253. }
  254. rootVisableFiles = append(rootVisableFiles, File{
  255. Filename: filepath.Base(file),
  256. RelPath: "/",
  257. Filesize: fs.GetFileDisplaySize(fileSize, 2),
  258. IsDir: fs.IsDir(file),
  259. })
  260. }
  261. }
  262. js, _ := json.Marshal(rootVisableFiles)
  263. //Get modification time
  264. fmodtime, _ := fs.GetModTime(shareOption.FileRealPath)
  265. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  266. t := fasttemplate.New(string(content), "{{", "}}")
  267. s := t.ExecuteString(map[string]interface{}{
  268. "hostname": s.options.HostName,
  269. "reqid": id,
  270. "mime": "application/x-directory",
  271. "size": fs.GetFileDisplaySize(fsize, 2),
  272. "filecount": strconv.Itoa(fcount),
  273. "modtime": timeString,
  274. "downloadurl": "/share?id=" + id + "&download=true",
  275. "filename": filepath.Base(shareOption.FileRealPath),
  276. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  277. "filelist": js,
  278. })
  279. w.Write([]byte(s))
  280. return
  281. }
  282. } else {
  283. if directDownload == true {
  284. //Serve the file directly
  285. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(shareOption.FileRealPath)), "+", "%20"))
  286. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  287. http.ServeFile(w, r, shareOption.FileRealPath)
  288. } else if directServe == true {
  289. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  290. http.ServeFile(w, r, shareOption.FileRealPath)
  291. } else {
  292. //Serve the download page
  293. content, err := ioutil.ReadFile("./system/share/downloadPage.html")
  294. if err != nil {
  295. http.NotFound(w, r)
  296. return
  297. }
  298. //Get file mime type
  299. mime, ext, err := fs.GetMime(shareOption.FileRealPath)
  300. if err != nil {
  301. mime = "Unknown"
  302. }
  303. //Load the preview template
  304. templateRoot := "./system/share/"
  305. previewTemplate := filepath.Join(templateRoot, "defaultTemplate.html")
  306. if ext == ".mp4" || ext == ".webm" {
  307. previewTemplate = filepath.Join(templateRoot, "video.html")
  308. } else if ext == ".mp3" || ext == ".wav" || ext == ".flac" || ext == ".ogg" {
  309. previewTemplate = filepath.Join(templateRoot, "audio.html")
  310. } else if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".webp" {
  311. previewTemplate = filepath.Join(templateRoot, "image.html")
  312. } else if ext == ".pdf" {
  313. previewTemplate = filepath.Join(templateRoot, "iframe.html")
  314. } else {
  315. //Format do not support preview. Use the default.html
  316. previewTemplate = filepath.Join(templateRoot, "default.html")
  317. }
  318. tp, err := ioutil.ReadFile(previewTemplate)
  319. if err != nil {
  320. tp = []byte("")
  321. }
  322. //Merge two templates
  323. content = []byte(strings.ReplaceAll(string(content), "{{previewer}}", string(tp)))
  324. //Get file size
  325. fsize := fs.GetFileSize(shareOption.FileRealPath)
  326. //Get modification time
  327. fmodtime, _ := fs.GetModTime(shareOption.FileRealPath)
  328. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  329. t := fasttemplate.New(string(content), "{{", "}}")
  330. s := t.ExecuteString(map[string]interface{}{
  331. "hostname": s.options.HostName,
  332. "reqid": id,
  333. "mime": mime,
  334. "ext": ext,
  335. "size": fs.GetFileDisplaySize(fsize, 2),
  336. "modtime": timeString,
  337. "downloadurl": "/share?id=" + id + "&download=true",
  338. "preview_url": "/share?id=" + id + "&serve=true",
  339. "filename": filepath.Base(shareOption.FileRealPath),
  340. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  341. })
  342. w.Write([]byte(s))
  343. return
  344. }
  345. }
  346. } else {
  347. //This share not exists
  348. if err != nil {
  349. //Template not found. Just send a 404 Not Found
  350. http.NotFound(w, r)
  351. return
  352. }
  353. if directDownload == true {
  354. //Send 404 header
  355. http.NotFound(w, r)
  356. return
  357. } else {
  358. //Send not found page
  359. content, err := ioutil.ReadFile("./system/share/notfound.html")
  360. if err != nil {
  361. http.NotFound(w, r)
  362. return
  363. }
  364. t := fasttemplate.New(string(content), "{{", "}}")
  365. s := t.ExecuteString(map[string]interface{}{
  366. "hostname": s.options.HostName,
  367. "reqid": id,
  368. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  369. })
  370. w.Write([]byte(s))
  371. return
  372. }
  373. }
  374. }
  375. //Create new share from the given path
  376. func (s *Manager) HandleCreateNewShare(w http.ResponseWriter, r *http.Request) {
  377. //Get the vpath from paramters
  378. vpath, err := mv(r, "path", true)
  379. if err != nil {
  380. sendErrorResponse(w, "Invalid path given")
  381. return
  382. }
  383. //Get userinfo
  384. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  385. if err != nil {
  386. sendErrorResponse(w, "User not logged in")
  387. return
  388. }
  389. share, err := s.CreateNewShare(userinfo, vpath)
  390. if err != nil {
  391. sendErrorResponse(w, err.Error())
  392. return
  393. }
  394. js, _ := json.Marshal(share)
  395. sendJSONResponse(w, string(js))
  396. }
  397. // Handle Share Edit.
  398. // For allowing groups / users, use the following syntax
  399. // groups:group1,group2,group3
  400. // users:user1,user2,user3
  401. // For basic modes, use the following keywords
  402. // anyone / signedin / samegroup
  403. // anyone: Anyone who has the link
  404. // signedin: Anyone logged in to this system
  405. // samegroup: The requesting user has the same (or more) user group as the share owner
  406. func (s *Manager) HandleEditShare(w http.ResponseWriter, r *http.Request) {
  407. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  408. if err != nil {
  409. sendErrorResponse(w, "User not logged in")
  410. return
  411. }
  412. uuid, err := mv(r, "uuid", true)
  413. if err != nil {
  414. sendErrorResponse(w, "Invalid path given")
  415. return
  416. }
  417. shareMode, _ := mv(r, "mode", true)
  418. if shareMode == "" {
  419. shareMode = "signedin"
  420. }
  421. //Check if share exists
  422. so := s.GetShareObjectFromUUID(uuid)
  423. if so == nil {
  424. //This share url not exists
  425. sendErrorResponse(w, "Share UUID not exists")
  426. return
  427. }
  428. //Check if the user has permission to edit this share
  429. if so.Owner != userinfo.Username && userinfo.IsAdmin() == false {
  430. //This file is not shared by this user and this user is not admin. Block this request
  431. sendErrorResponse(w, "Permission denied")
  432. return
  433. }
  434. //Validate and extract the storage mode
  435. ok, sharetype, settings := validateShareModes(shareMode)
  436. if !ok {
  437. sendErrorResponse(w, "Invalid share setting")
  438. return
  439. }
  440. //Analysis the sharetype
  441. if sharetype == "anyone" || sharetype == "signedin" || sharetype == "samegroup" {
  442. //Basic types.
  443. so.Permission = sharetype
  444. if sharetype == "samegroup" {
  445. //Write user groups into accessible (Must be all match inorder to allow access)
  446. userpg := []string{}
  447. for _, pg := range userinfo.PermissionGroup {
  448. userpg = append(userpg, pg.Name)
  449. }
  450. so.Accessibles = userpg
  451. }
  452. //Write changes to database
  453. s.options.Database.Write("share", uuid, so)
  454. } else if sharetype == "groups" || sharetype == "users" {
  455. //Username or group is listed = ok
  456. so.Permission = sharetype
  457. so.Accessibles = settings
  458. //Write changes to database
  459. s.options.Database.Write("share", uuid, so)
  460. }
  461. sendOK(w)
  462. }
  463. func (s *Manager) HandleDeleteShare(w http.ResponseWriter, r *http.Request) {
  464. //Get the vpath from paramters
  465. vpath, err := mv(r, "path", true)
  466. if err != nil {
  467. sendErrorResponse(w, "Invalid path given")
  468. return
  469. }
  470. //Get userinfo
  471. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  472. if err != nil {
  473. sendErrorResponse(w, "User not logged in")
  474. return
  475. }
  476. //Delete the share setting
  477. err = s.DeleteShare(userinfo, vpath)
  478. if err != nil {
  479. sendErrorResponse(w, err.Error())
  480. } else {
  481. sendOK(w)
  482. }
  483. }
  484. //Craete a new file or folder share
  485. func (s *Manager) CreateNewShare(userinfo *user.User, vpath string) (*ShareOption, error) {
  486. //Translate the vpath to realpath
  487. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  488. if err != nil {
  489. return nil, errors.New("Unable to find the file on disk")
  490. }
  491. rpath = filepath.ToSlash(filepath.Clean(rpath))
  492. //Check if source file exists
  493. if !fileExists(rpath) {
  494. return nil, errors.New("Unable to find the file on disk")
  495. }
  496. //Check if the share already exists. If yes, use the previous link
  497. val, ok := s.fileToUrlMap.Load(rpath)
  498. if ok {
  499. //Exists. Send back the old share url
  500. ShareOption := val.(*ShareOption)
  501. return ShareOption, nil
  502. } else {
  503. //Create new link for this file
  504. shareUUID := uuid.NewV4().String()
  505. //user groups when share
  506. groups := []string{}
  507. for _, pg := range userinfo.GetUserPermissionGroup() {
  508. groups = append(groups, pg.Name)
  509. }
  510. //Create a share object
  511. shareOption := ShareOption{
  512. UUID: shareUUID,
  513. FileRealPath: rpath,
  514. Owner: userinfo.Username,
  515. Accessibles: groups,
  516. Permission: "anyone",
  517. AllowLivePreview: true,
  518. }
  519. //Store results on two map to make sure O(1) Lookup time
  520. s.fileToUrlMap.Store(rpath, &shareOption)
  521. s.urlToFileMap.Store(shareUUID, &shareOption)
  522. //Write object to database
  523. s.options.Database.Write("share", shareUUID, shareOption)
  524. return &shareOption, nil
  525. }
  526. }
  527. //Delete the share on this vpath
  528. func (s *Manager) DeleteShare(userinfo *user.User, vpath string) error {
  529. //Translate the vpath to realpath
  530. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  531. if err != nil {
  532. return errors.New("Unable to find the file on disk")
  533. }
  534. //Check if the share already exists. If yes, use the previous link
  535. val, ok := s.fileToUrlMap.Load(rpath)
  536. if ok {
  537. //Exists. Send back the old share url
  538. uuid := val.(*ShareOption).UUID
  539. //Remove this from the database
  540. err = s.options.Database.Delete("share", uuid)
  541. if err != nil {
  542. return err
  543. }
  544. //Remove this form the current sync map
  545. s.urlToFileMap.Delete(uuid)
  546. s.fileToUrlMap.Delete(rpath)
  547. return nil
  548. } else {
  549. //Already deleted from buffered record.
  550. return nil
  551. }
  552. }
  553. func (s *Manager) GetShareUUIDFromPath(rpath string) string {
  554. targetShareObject := s.GetShareObjectFromRealPath(rpath)
  555. if (targetShareObject) != nil {
  556. return targetShareObject.UUID
  557. }
  558. return ""
  559. }
  560. func (s *Manager) GetShareObjectFromRealPath(rpath string) *ShareOption {
  561. rpath = filepath.ToSlash(filepath.Clean(rpath))
  562. var targetShareOption *ShareOption
  563. s.fileToUrlMap.Range(func(k, v interface{}) bool {
  564. filePath := k.(string)
  565. shareObject := v.(*ShareOption)
  566. if filepath.ToSlash(filepath.Clean(filePath)) == rpath {
  567. targetShareOption = shareObject
  568. }
  569. return true
  570. })
  571. return targetShareOption
  572. }
  573. func (s *Manager) GetShareObjectFromUUID(uuid string) *ShareOption {
  574. var targetShareOption *ShareOption
  575. s.urlToFileMap.Range(func(k, v interface{}) bool {
  576. thisUuid := k.(string)
  577. shareObject := v.(*ShareOption)
  578. if thisUuid == uuid {
  579. targetShareOption = shareObject
  580. }
  581. return true
  582. })
  583. return targetShareOption
  584. }
  585. func (s *Manager) FileIsShared(rpath string) bool {
  586. shareUUID := s.GetShareUUIDFromPath(rpath)
  587. return shareUUID != ""
  588. }
  589. /*
  590. Validate Share Mode string
  591. will return
  592. 1. bool => Is valid
  593. 2. permission type: {basic / groups / users}
  594. 3. mode string
  595. */
  596. func validateShareModes(mode string) (bool, string, []string) {
  597. // user:a,b,c,d
  598. validModes := []string{"anyone", "signedin", "samegroup"}
  599. if inArray(validModes, mode) {
  600. //Standard modes
  601. return true, mode, []string{}
  602. } else if len(mode) > 7 && mode[:7] == "groups:" {
  603. //Handle custom group case like groups:a,b,c,d
  604. groupList := mode[7:]
  605. if len(groupList) > 0 {
  606. groups := strings.Split(groupList, ",")
  607. return true, "groups", groups
  608. } else {
  609. //Invalid configuration
  610. return false, "groups", []string{}
  611. }
  612. } else if len(mode) > 6 && mode[:6] == "users:" {
  613. //Handle custom usersname like users:a,b,c,d
  614. userList := mode[6:]
  615. if len(userList) > 0 {
  616. users := strings.Split(userList, ",")
  617. return true, "users", users
  618. } else {
  619. //Invalid configuration
  620. return false, "users", []string{}
  621. }
  622. }
  623. return false, "", []string{}
  624. }
  625. func (s *Manager) RemoveShareByRealpath(rpath string) error {
  626. _, ok := s.fileToUrlMap.Load(rpath)
  627. if ok {
  628. s.fileToUrlMap.Delete(rpath)
  629. } else {
  630. return errors.New("Share with given realpath not exists")
  631. }
  632. return nil
  633. }
  634. func (s *Manager) RemoveShareByUUID(uuid string) error {
  635. _, ok := s.urlToFileMap.Load(uuid)
  636. if ok {
  637. s.urlToFileMap.Delete(uuid)
  638. } else {
  639. return errors.New("Share with given uuid not exists")
  640. }
  641. return nil
  642. }
  643. //Check and clear shares that its pointinf files no longe exists
  644. func (s *Manager) ValidateAndClearShares() {
  645. //Iterate through all shares within the system
  646. s.fileToUrlMap.Range(func(k, v interface{}) bool {
  647. thisRealPath := k.(string)
  648. if !fileExists(thisRealPath) {
  649. //This share source file don't exists anymore. Remove it
  650. thisFileShareOption := v.(*ShareOption)
  651. //Delete this task from both sync map
  652. s.RemoveShareByRealpath(thisRealPath)
  653. s.RemoveShareByUUID(thisFileShareOption.UUID)
  654. //Remove share from database
  655. s.options.Database.Delete("share", thisFileShareOption.UUID)
  656. log.Println("*Share* Removing share to file: " + thisRealPath + " as it no longer exists")
  657. }
  658. return true
  659. })
  660. }