drive.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. package share
  2. /*
  3. Shared with me
  4. Builds the root of the share:/ drive (mod/filesystem/abstractions/sharefs):
  5. the files and folders other users shared with someone, each under a name
  6. that is unique on that drive, so the File Manager can browse them like a
  7. folder instead of opening each share link on its own page.
  8. Only shares that name the user as a recipient count: an invited user, one
  9. of the user's groups, or a same group share whose groups the user is in.
  10. "Anyone with the link" and "signed-in users with the link" shares are left
  11. out. Their audience is whoever was handed the link, so listing them on
  12. every account would publish links their owners only meant to pass around.
  13. Password protected shares are left out too: the drive cannot ask for the
  14. password, and handing the files over without it would defeat the point.
  15. All of these still open from their link as before.
  16. */
  17. import (
  18. "net/http"
  19. "path"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. filesystem "imuslab.com/arozos/mod/filesystem"
  26. "imuslab.com/arozos/mod/filesystem/abstractions/sharefs"
  27. "imuslab.com/arozos/mod/share/shareEntry"
  28. "imuslab.com/arozos/mod/utils"
  29. )
  30. // SharedDriveUUID is the virtual root id of the drive, "share:/"
  31. const SharedDriveUUID = "share"
  32. // How long a user's drive root is reused before it is built again. Every
  33. // file operation on the drive resolves its path against the root, so this
  34. // keeps a folder listing from rebuilding it once per file.
  35. const sharedDriveCacheTTL = 2 * time.Second
  36. // sharedEntry is one item of a user's drive root before it is tied to the
  37. // drive the file lives on
  38. type sharedEntry struct {
  39. Name string
  40. Shares []*shareEntry.ShareOption //Shares of the same file, oldest first
  41. }
  42. func (e *sharedEntry) first() *shareEntry.ShareOption {
  43. return e.Shares[0]
  44. }
  45. // permissions merges what the shares of one file allow: the user could use
  46. // any of their links, so the most generous of them applies.
  47. func (e *sharedEntry) permissions() (canBrowse bool, canDownload bool, canUpload bool) {
  48. for _, so := range e.Shares {
  49. canBrowse = canBrowse || (so.IsFolder && so.ShowFileList)
  50. canDownload = canDownload || so.AllowDownload
  51. canUpload = canUpload || so.CanUpload()
  52. }
  53. return
  54. }
  55. // isAddressedTo reports whether a share names the user as a recipient, see
  56. // the note at the top of this file
  57. func isAddressedTo(so *shareEntry.ShareOption, username string, groups []string) bool {
  58. if so.Owner == username {
  59. return false
  60. }
  61. switch so.Permission {
  62. case shareEntry.PermissionUsers:
  63. return utils.StringInArray(so.Accessibles, username)
  64. case shareEntry.PermissionGroups:
  65. for _, group := range groups {
  66. if utils.StringInArray(so.Accessibles, group) {
  67. return true
  68. }
  69. }
  70. case shareEntry.PermissionSameGroup:
  71. //The same rule the share link applies: every group the owner was in
  72. //when sharing. A share that recorded no groups is not addressed to
  73. //anybody in particular.
  74. if len(so.Accessibles) == 0 {
  75. return false
  76. }
  77. for _, group := range so.Accessibles {
  78. if !utils.StringInArray(groups, group) {
  79. return false
  80. }
  81. }
  82. return true
  83. }
  84. return false
  85. }
  86. // itemBaseName is the name a shared file or folder would like to have on the
  87. // drive: its own name, or for a whole shared drive the drive's id
  88. func itemBaseName(so *shareEntry.ShareOption) string {
  89. vrootID, subpath, err := filesystem.GetIDFromVirtualPath(so.FileVirtualPath)
  90. if err != nil {
  91. return so.UUID
  92. }
  93. name := path.Base(path.Clean("/" + strings.ReplaceAll(subpath, "\\", "/")))
  94. if name == "/" || name == "." || name == "" {
  95. return vrootID
  96. }
  97. return name
  98. }
  99. // nameWithSuffix puts a suffix after a name, before the extension of a file:
  100. // "report.pdf" -> "report (bob).pdf", "Photos" -> "Photos (bob)"
  101. func nameWithSuffix(name string, suffix string, isDir bool) string {
  102. ext := ""
  103. if !isDir {
  104. ext = path.Ext(name)
  105. if ext == name {
  106. //A dot file such as ".bashrc" has no extension to keep
  107. ext = ""
  108. }
  109. }
  110. return strings.TrimSuffix(name, ext) + " (" + suffix + ")" + ext
  111. }
  112. /*
  113. sharedWith lists what is shared with a user as the entries of the drive root.
  114. Shares of the same file are merged into one entry. Every entry gets a name
  115. unique on the drive, compared without case so two entries never differ only
  116. in case: the file's own name for the oldest share of that name, then the
  117. owner's name added for the next, then a counter. Names only depend on the
  118. shares, never on whether the file is reachable right now, so a drive that is
  119. offline for a moment does not rename everything after it.
  120. */
  121. func sharedWith(all []*shareEntry.ShareOption, username string, groups []string, now time.Time) []*sharedEntry {
  122. addressed := []*shareEntry.ShareOption{}
  123. for _, so := range all {
  124. if so.IsExpired(now) || so.HasPassword() || !isAddressedTo(so, username, groups) {
  125. continue
  126. }
  127. addressed = append(addressed, so)
  128. }
  129. sort.SliceStable(addressed, func(i, j int) bool {
  130. if addressed[i].CreatedAt != addressed[j].CreatedAt {
  131. return addressed[i].CreatedAt < addressed[j].CreatedAt
  132. }
  133. return addressed[i].UUID < addressed[j].UUID
  134. })
  135. entries := []*sharedEntry{}
  136. byPath := map[string]*sharedEntry{}
  137. for _, so := range addressed {
  138. if entry, ok := byPath[so.PathHash]; ok {
  139. entry.Shares = append(entry.Shares, so)
  140. continue
  141. }
  142. entry := &sharedEntry{Shares: []*shareEntry.ShareOption{so}}
  143. byPath[so.PathHash] = entry
  144. entries = append(entries, entry)
  145. }
  146. taken := map[string]bool{}
  147. for _, entry := range entries {
  148. so := entry.first()
  149. base := itemBaseName(so)
  150. name := base
  151. for n := 1; taken[strings.ToLower(name)]; n++ {
  152. suffix := so.Owner
  153. if n > 1 {
  154. suffix += " " + strconv.Itoa(n)
  155. }
  156. name = nameWithSuffix(base, suffix, so.IsFolder)
  157. }
  158. taken[strings.ToLower(name)] = true
  159. entry.Name = name
  160. }
  161. return entries
  162. }
  163. /*
  164. Drive root, as the sharefs.Resolver of the share:/ drive
  165. */
  166. type sharedDriveCacheEntry struct {
  167. items []*sharefs.Item
  168. builtAt time.Time
  169. }
  170. type sharedDriveCache struct {
  171. mu sync.Mutex
  172. users map[string]sharedDriveCacheEntry
  173. }
  174. func (c *sharedDriveCache) get(username string, now time.Time) ([]*sharefs.Item, bool) {
  175. c.mu.Lock()
  176. defer c.mu.Unlock()
  177. entry, ok := c.users[username]
  178. if !ok || now.Sub(entry.builtAt) > sharedDriveCacheTTL {
  179. return nil, false
  180. }
  181. return entry.items, true
  182. }
  183. func (c *sharedDriveCache) put(username string, items []*sharefs.Item, now time.Time) {
  184. c.mu.Lock()
  185. defer c.mu.Unlock()
  186. if c.users == nil {
  187. c.users = map[string]sharedDriveCacheEntry{}
  188. }
  189. c.users[username] = sharedDriveCacheEntry{items: items, builtAt: now}
  190. }
  191. // clear drops every user's root, after a share was created, changed or removed
  192. func (c *sharedDriveCache) clear() {
  193. c.mu.Lock()
  194. defer c.mu.Unlock()
  195. c.users = nil
  196. }
  197. // Items lists what is shared with a user, for the share:/ drive
  198. func (s *Manager) Items(username string) []*sharefs.Item {
  199. now := time.Now()
  200. if items, ok := s.driveCache.get(username, now); ok {
  201. return items
  202. }
  203. items := s.buildSharedDriveItems(username, now)
  204. s.driveCache.put(username, items, now)
  205. return items
  206. }
  207. // buildSharedDriveItems ties each entry shared with the user to the drive
  208. // its file lives on. An entry whose owner or drive cannot be resolved right
  209. // now is left out; its name stays reserved, see sharedWith.
  210. func (s *Manager) buildSharedDriveItems(username string, now time.Time) []*sharefs.Item {
  211. items := []*sharefs.Item{}
  212. if s.options.UserHandler == nil || s.options.ShareEntryTable == nil {
  213. return items
  214. }
  215. if !s.options.UserHandler.GetAuthAgent().UserExists(username) {
  216. return items
  217. }
  218. groups := []string{}
  219. if pgs, err := s.options.UserHandler.GetPermissionHandler().GetUsersPermissionGroup(username); err == nil {
  220. for _, pg := range pgs {
  221. groups = append(groups, pg.Name)
  222. }
  223. }
  224. for _, entry := range sharedWith(s.options.ShareEntryTable.ListAllShares(), username, groups, now) {
  225. so := entry.first()
  226. owner, err := s.options.UserHandler.GetUserInfoFromUsername(so.Owner)
  227. if err != nil {
  228. continue
  229. }
  230. fsh, err := owner.GetFileSystemHandlerFromVirtualPath(so.FileVirtualPath)
  231. if err != nil || fsh == nil || fsh.FileSystemAbstraction == nil || fsh.Closed || IsSharedDrive(fsh) {
  232. continue
  233. }
  234. root, err := fsh.FileSystemAbstraction.VirtualPathToRealPath(so.FileVirtualPath, owner.Username)
  235. if err != nil {
  236. continue
  237. }
  238. shareIDs := []string{}
  239. for _, share := range entry.Shares {
  240. shareIDs = append(shareIDs, share.UUID)
  241. }
  242. canBrowse, canDownload, canUpload := entry.permissions()
  243. items = append(items, &sharefs.Item{
  244. Name: entry.Name,
  245. Owner: so.Owner,
  246. ShareIDs: shareIDs,
  247. IsDir: so.IsFolder,
  248. CanBrowse: canBrowse,
  249. CanDownload: canDownload,
  250. CanUpload: canUpload,
  251. Fsh: fsh,
  252. Root: root,
  253. })
  254. }
  255. return items
  256. }
  257. // IsSharedDrive reports whether a file system handler is the share:/ drive
  258. func IsSharedDrive(fsh *filesystem.FileSystemHandler) bool {
  259. if fsh == nil {
  260. return false
  261. }
  262. _, ok := fsh.FileSystemAbstraction.(*sharefs.ShareFileSystem)
  263. return ok
  264. }
  265. /*
  266. API
  267. */
  268. // SharedItemInfo is the client facing view of an item on the share:/ drive.
  269. // It says what the item allows, never where the file really lives.
  270. type SharedItemInfo struct {
  271. Name string //Name at the drive root
  272. Path string //Its virtual path, share:/<Name>
  273. Owner string
  274. IsFolder bool
  275. CanBrowse bool
  276. CanDownload bool
  277. CanUpload bool
  278. ShareUUID string //The oldest share granting access, for its link page
  279. }
  280. // HandleListSharedWithMe lists the root of the user's share:/ drive with
  281. // what each item allows, which the File Manager uses to offer only the file
  282. // operations that can work on it.
  283. func (s *Manager) HandleListSharedWithMe(w http.ResponseWriter, r *http.Request) {
  284. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  285. if err != nil {
  286. utils.SendErrorResponse(w, "User not logged in")
  287. return
  288. }
  289. results := []*SharedItemInfo{}
  290. for _, item := range s.Items(userinfo.Username) {
  291. shareUUID := ""
  292. if len(item.ShareIDs) > 0 {
  293. shareUUID = item.ShareIDs[0]
  294. }
  295. results = append(results, &SharedItemInfo{
  296. Name: item.Name,
  297. Path: SharedDriveUUID + ":/" + item.Name,
  298. Owner: item.Owner,
  299. IsFolder: item.IsDir,
  300. CanBrowse: item.CanBrowse,
  301. CanDownload: item.CanDownload,
  302. CanUpload: item.CanUpload,
  303. ShareUUID: shareUUID,
  304. })
  305. }
  306. sendJSON(w, results)
  307. }