shareEntry.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. package shareEntry
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "sync"
  11. uuid "github.com/satori/go.uuid"
  12. "imuslab.com/arozos/mod/database"
  13. "imuslab.com/arozos/mod/filesystem"
  14. fs "imuslab.com/arozos/mod/filesystem"
  15. )
  16. /*
  17. Share Entry
  18. This module is designed to isolate the entry operatiosn with the
  19. handle operations so as to reduce the complexity of recursive import
  20. during development
  21. */
  22. type ShareEntryTable struct {
  23. FileToUrlMap *sync.Map
  24. UrlToFileMap *sync.Map
  25. Database *database.Database
  26. }
  27. type ShareOption struct {
  28. UUID string
  29. PathHash string //Path Hash, the key for loading a share from vpath and fsh specific config
  30. FileVirtualPath string
  31. FileRealPath string
  32. Owner string
  33. Accessibles []string //Use to store username or group names if permission is groups or users
  34. Permission string //Access permission, allow {anyone / signedin / samegroup / groups / users}
  35. AllowLivePreview bool
  36. }
  37. func NewShareEntryTable(db *database.Database) *ShareEntryTable {
  38. //Create the share table if not exists
  39. db.NewTable("share")
  40. FileToUrlMap := sync.Map{}
  41. UrlToFileMap := sync.Map{}
  42. //Load the old share links
  43. entries, _ := db.ListTable("share")
  44. for _, keypairs := range entries {
  45. shareObject := new(ShareOption)
  46. json.Unmarshal(keypairs[1], &shareObject)
  47. if shareObject != nil {
  48. //Append this to the maps
  49. FileToUrlMap.Store(shareObject.PathHash, shareObject)
  50. UrlToFileMap.Store(shareObject.UUID, shareObject)
  51. }
  52. }
  53. return &ShareEntryTable{
  54. FileToUrlMap: &FileToUrlMap,
  55. UrlToFileMap: &UrlToFileMap,
  56. Database: db,
  57. }
  58. }
  59. func (s *ShareEntryTable) CreateNewShare(srcFsh *filesystem.FileSystemHandler, vpath string, username string, usergroups []string) (*ShareOption, error) {
  60. rpath, err := srcFsh.FileSystemAbstraction.VirtualPathToRealPath(vpath, username)
  61. if err != nil {
  62. return nil, errors.New("Unable to translate path given")
  63. }
  64. rpath = filepath.ToSlash(filepath.Clean(rpath))
  65. //Check if source file exists
  66. if !srcFsh.FileSystemAbstraction.FileExists(rpath) {
  67. return nil, errors.New("Unable to find the file on disk")
  68. }
  69. sharePathHash := GetPathHash(srcFsh, vpath, username)
  70. //Check if the share already exists. If yes, use the previous link
  71. val, ok := s.FileToUrlMap.Load(sharePathHash)
  72. if ok {
  73. //Exists. Send back the old share url
  74. ShareOption := val.(*ShareOption)
  75. return ShareOption, nil
  76. } else {
  77. //Create new link for this file
  78. shareUUID := uuid.NewV4().String()
  79. //Create a share object
  80. shareOption := ShareOption{
  81. UUID: shareUUID,
  82. PathHash: sharePathHash,
  83. FileVirtualPath: vpath,
  84. FileRealPath: rpath,
  85. Owner: username,
  86. Accessibles: usergroups,
  87. Permission: "anyone",
  88. AllowLivePreview: true,
  89. }
  90. //Store results on two map to make sure O(1) Lookup time
  91. s.FileToUrlMap.Store(sharePathHash, &shareOption)
  92. s.UrlToFileMap.Store(shareUUID, &shareOption)
  93. //Write object to database
  94. s.Database.Write("share", shareUUID, shareOption)
  95. return &shareOption, nil
  96. }
  97. }
  98. //Delete the share on this vpath
  99. func (s *ShareEntryTable) DeleteShareByPathHash(pathhash string) error {
  100. //Check if the share already exists. If yes, use the previous link
  101. val, ok := s.FileToUrlMap.Load(pathhash)
  102. if ok {
  103. //Exists. Send back the old share url
  104. uuid := val.(*ShareOption).UUID
  105. //Remove this from the database
  106. err := s.Database.Delete("share", uuid)
  107. if err != nil {
  108. return err
  109. }
  110. //Remove this form the current sync map
  111. s.UrlToFileMap.Delete(uuid)
  112. s.FileToUrlMap.Delete(pathhash)
  113. return nil
  114. } else {
  115. //Already deleted from buffered record.
  116. return nil
  117. }
  118. }
  119. func (s *ShareEntryTable) GetShareUUIDFromPathHash(pathhash string) string {
  120. shareObject := s.GetShareObjectFromPathHash(pathhash)
  121. if shareObject == nil {
  122. return ""
  123. } else {
  124. return shareObject.UUID
  125. }
  126. }
  127. func (s *ShareEntryTable) GetShareObjectFromPathHash(pathhash string) *ShareOption {
  128. var targetShareOption *ShareOption = nil
  129. s.FileToUrlMap.Range(func(k, v interface{}) bool {
  130. thisPathhash := k.(string)
  131. shareObject := v.(*ShareOption)
  132. if thisPathhash == pathhash {
  133. targetShareOption = shareObject
  134. }
  135. return true
  136. })
  137. return targetShareOption
  138. }
  139. func (s *ShareEntryTable) GetShareObjectFromUUID(uuid string) *ShareOption {
  140. var targetShareOption *ShareOption
  141. s.UrlToFileMap.Range(func(k, v interface{}) bool {
  142. thisUuid := k.(string)
  143. shareObject := v.(*ShareOption)
  144. if thisUuid == uuid {
  145. targetShareOption = shareObject
  146. }
  147. return true
  148. })
  149. return targetShareOption
  150. }
  151. func (s *ShareEntryTable) FileIsShared(pathhash string) bool {
  152. shareUUID := s.GetShareUUIDFromPathHash(pathhash)
  153. return shareUUID != ""
  154. }
  155. func (s *ShareEntryTable) RemoveShareByPathHash(pathhash string) error {
  156. so, ok := s.FileToUrlMap.Load(pathhash)
  157. if ok {
  158. shareUUID := so.(*ShareOption).UUID
  159. s.UrlToFileMap.Delete(shareUUID)
  160. s.FileToUrlMap.Delete(pathhash)
  161. s.Database.Delete("share", shareUUID)
  162. } else {
  163. return errors.New("Share with given realpath not exists")
  164. }
  165. return nil
  166. }
  167. func (s *ShareEntryTable) RemoveShareByUUID(uuid string) error {
  168. so, ok := s.UrlToFileMap.Load(uuid)
  169. if ok {
  170. shareOption := so.(*ShareOption)
  171. s.FileToUrlMap.Delete(shareOption.PathHash)
  172. s.UrlToFileMap.Delete(uuid)
  173. s.Database.Delete("share", uuid)
  174. } else {
  175. return errors.New("Share with given uuid not exists")
  176. }
  177. return nil
  178. }
  179. func (s *ShareEntryTable) ResolveShareOptionFromShareSubpath(subpath string) (*ShareOption, error) {
  180. subpathElements := strings.Split(filepath.ToSlash(filepath.Clean(subpath))[1:], "/")
  181. if len(subpathElements) >= 1 {
  182. shareObject := s.GetShareObjectFromUUID(subpathElements[0])
  183. if shareObject == nil {
  184. return nil, errors.New("Invalid subpath")
  185. } else {
  186. return shareObject, nil
  187. }
  188. } else {
  189. return nil, errors.New("Invalid subpath")
  190. }
  191. }
  192. func (s *ShareEntryTable) ResolveShareVrootPath(subpath string, username string, usergroup []string) (string, error) {
  193. //Get a list of accessible files from this user
  194. subpathElements := strings.Split(filepath.ToSlash(filepath.Clean(subpath))[1:], "/")
  195. if len(subpathElements) == 0 {
  196. //Requesting root folder.
  197. return "", errors.New("This virtual file system router do not support root listing")
  198. }
  199. //Analysis the subpath elements
  200. if len(subpathElements) == 1 {
  201. return "", errors.New("Redirect: parent")
  202. } else if len(subpathElements) == 2 {
  203. //ID only or ID with the target filename
  204. shareObject := s.GetShareObjectFromUUID(subpathElements[0])
  205. if shareObject == nil {
  206. return "", errors.New("Share file not found")
  207. }
  208. return shareObject.FileRealPath, nil
  209. } else if len(subpathElements) > 2 {
  210. //Loading folder / files inside folder type shares
  211. shareObject := s.GetShareObjectFromUUID(subpathElements[0])
  212. folderSubpaths := append([]string{shareObject.FileRealPath}, subpathElements[2:]...)
  213. targetFolder := filepath.Join(folderSubpaths...)
  214. return targetFolder, nil
  215. }
  216. return "", errors.New("Not implemented")
  217. }
  218. func (s *ShareEntryTable) Walk(subpath string, username string, usergroup []string, fastWalkFunction func(fs.FileData) error) error {
  219. //Resolve the subpath
  220. if subpath == "" {
  221. //List root as a collections of shares
  222. rootFileList := s.ListRootForUser(username, usergroup)
  223. for _, fileInRoot := range rootFileList {
  224. if fs.IsDir(fileInRoot.Realpath) {
  225. //Walk it
  226. err := filepath.Walk(fileInRoot.Realpath, func(path string, info os.FileInfo, err error) error {
  227. relPath, err := filepath.Rel(fileInRoot.Realpath, path)
  228. if err != nil {
  229. return err
  230. }
  231. thisVpath := filepath.ToSlash(filepath.Join(fileInRoot.Filepath, relPath))
  232. thisFd := fs.GetFileDataFromPath(thisVpath, path, 2)
  233. err = fastWalkFunction(thisFd)
  234. if err != nil {
  235. return err
  236. }
  237. return nil
  238. })
  239. return err
  240. } else {
  241. //Normal files
  242. err := fastWalkFunction(fileInRoot)
  243. if err != nil {
  244. return err
  245. }
  246. }
  247. }
  248. } else {
  249. //List realpath of the system
  250. rpath, err := s.ResolveShareVrootPath(subpath, username, usergroup)
  251. if err != nil {
  252. return err
  253. }
  254. vpath := "share:/" + subpath
  255. err = filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
  256. relPath, err := filepath.Rel(rpath, path)
  257. if err != nil {
  258. return err
  259. }
  260. thisVpath := filepath.ToSlash(filepath.Join(vpath, relPath))
  261. thisFd := fs.GetFileDataFromPath(thisVpath, rpath, 2)
  262. err = fastWalkFunction(thisFd)
  263. if err != nil {
  264. return err
  265. }
  266. return nil
  267. })
  268. return err
  269. }
  270. return nil
  271. }
  272. func (s *ShareEntryTable) ListRootForUser(username string, usergroup []string) []fs.FileData {
  273. //Iterate through all shares in the system to see which of the share is user accessible
  274. userAccessiableShare := []*ShareOption{}
  275. s.FileToUrlMap.Range(func(fp, so interface{}) bool {
  276. fileRealpath := fp.(string)
  277. thisShareOption := so.(*ShareOption)
  278. if fs.FileExists(fileRealpath) {
  279. if thisShareOption.IsAccessibleBy(username, usergroup) {
  280. userAccessiableShare = append(userAccessiableShare, thisShareOption)
  281. }
  282. }
  283. return true
  284. })
  285. results := []fs.FileData{}
  286. for _, thisShareObject := range userAccessiableShare {
  287. rpath := thisShareObject.FileRealPath
  288. thisFile := fs.GetFileDataFromPath("share:/"+thisShareObject.UUID+"/"+filepath.Base(rpath), rpath, 2)
  289. if thisShareObject.Owner == username {
  290. thisFile.IsShared = true
  291. }
  292. results = append(results, thisFile)
  293. }
  294. return results
  295. }
  296. func GetPathHash(fsh *filesystem.FileSystemHandler, vpath string, username string) string {
  297. fshAbs := fsh.FileSystemAbstraction
  298. rpath := ""
  299. if strings.Contains(vpath, ":/") {
  300. rpath, _ = fshAbs.VirtualPathToRealPath(vpath, username)
  301. rpath = filepath.ToSlash(rpath)
  302. } else {
  303. //Passed in realpath as vpath.
  304. rpath = vpath
  305. }
  306. hash := md5.Sum([]byte(fsh.UUID + "_" + rpath))
  307. return hex.EncodeToString(hash[:])
  308. }