share.go 21 KB

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