123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364 |
- package shareEntry
- import (
- "crypto/md5"
- "encoding/hex"
- "encoding/json"
- "errors"
- "os"
- "path/filepath"
- "strings"
- "sync"
- uuid "github.com/satori/go.uuid"
- "imuslab.com/arozos/mod/database"
- "imuslab.com/arozos/mod/filesystem"
- fs "imuslab.com/arozos/mod/filesystem"
- )
- /*
- Share Entry
- This module is designed to isolate the entry operatiosn with the
- handle operations so as to reduce the complexity of recursive import
- during development
- */
- type ShareEntryTable struct {
- FileToUrlMap *sync.Map
- UrlToFileMap *sync.Map
- Database *database.Database
- }
- type ShareOption struct {
- UUID string
- PathHash string //Path Hash, the key for loading a share from vpath and fsh specific config
- FileVirtualPath string
- FileRealPath string
- Owner string
- Accessibles []string //Use to store username or group names if permission is groups or users
- Permission string //Access permission, allow {anyone / signedin / samegroup / groups / users}
- AllowLivePreview bool
- }
- func NewShareEntryTable(db *database.Database) *ShareEntryTable {
- //Create the share table if not exists
- db.NewTable("share")
- FileToUrlMap := sync.Map{}
- UrlToFileMap := sync.Map{}
- //Load the old share links
- entries, _ := db.ListTable("share")
- for _, keypairs := range entries {
- shareObject := new(ShareOption)
- json.Unmarshal(keypairs[1], &shareObject)
- if shareObject != nil {
- //Append this to the maps
- FileToUrlMap.Store(shareObject.PathHash, shareObject)
- UrlToFileMap.Store(shareObject.UUID, shareObject)
- }
- }
- return &ShareEntryTable{
- FileToUrlMap: &FileToUrlMap,
- UrlToFileMap: &UrlToFileMap,
- Database: db,
- }
- }
- func (s *ShareEntryTable) CreateNewShare(srcFsh *filesystem.FileSystemHandler, vpath string, username string, usergroups []string) (*ShareOption, error) {
- rpath, err := srcFsh.FileSystemAbstraction.VirtualPathToRealPath(vpath, username)
- if err != nil {
- return nil, errors.New("Unable to translate path given")
- }
- rpath = filepath.ToSlash(filepath.Clean(rpath))
- //Check if source file exists
- if !srcFsh.FileSystemAbstraction.FileExists(rpath) {
- return nil, errors.New("Unable to find the file on disk")
- }
- sharePathHash := GetPathHash(srcFsh, vpath, username)
- //Check if the share already exists. If yes, use the previous link
- val, ok := s.FileToUrlMap.Load(sharePathHash)
- if ok {
- //Exists. Send back the old share url
- ShareOption := val.(*ShareOption)
- return ShareOption, nil
- } else {
- //Create new link for this file
- shareUUID := uuid.NewV4().String()
- //Create a share object
- shareOption := ShareOption{
- UUID: shareUUID,
- PathHash: sharePathHash,
- FileVirtualPath: vpath,
- FileRealPath: rpath,
- Owner: username,
- Accessibles: usergroups,
- Permission: "anyone",
- AllowLivePreview: true,
- }
- //Store results on two map to make sure O(1) Lookup time
- s.FileToUrlMap.Store(sharePathHash, &shareOption)
- s.UrlToFileMap.Store(shareUUID, &shareOption)
- //Write object to database
- s.Database.Write("share", shareUUID, shareOption)
- return &shareOption, nil
- }
- }
- //Delete the share on this vpath
- func (s *ShareEntryTable) DeleteShareByPathHash(pathhash string) error {
- //Check if the share already exists. If yes, use the previous link
- val, ok := s.FileToUrlMap.Load(pathhash)
- if ok {
- //Exists. Send back the old share url
- uuid := val.(*ShareOption).UUID
- //Remove this from the database
- err := s.Database.Delete("share", uuid)
- if err != nil {
- return err
- }
- //Remove this form the current sync map
- s.UrlToFileMap.Delete(uuid)
- s.FileToUrlMap.Delete(pathhash)
- return nil
- } else {
- //Already deleted from buffered record.
- return nil
- }
- }
- func (s *ShareEntryTable) GetShareUUIDFromPathHash(pathhash string) string {
- shareObject := s.GetShareObjectFromPathHash(pathhash)
- if shareObject == nil {
- return ""
- } else {
- return shareObject.UUID
- }
- }
- func (s *ShareEntryTable) GetShareObjectFromPathHash(pathhash string) *ShareOption {
- var targetShareOption *ShareOption = nil
- s.FileToUrlMap.Range(func(k, v interface{}) bool {
- thisPathhash := k.(string)
- shareObject := v.(*ShareOption)
- if thisPathhash == pathhash {
- targetShareOption = shareObject
- }
- return true
- })
- return targetShareOption
- }
- func (s *ShareEntryTable) GetShareObjectFromUUID(uuid string) *ShareOption {
- var targetShareOption *ShareOption
- s.UrlToFileMap.Range(func(k, v interface{}) bool {
- thisUuid := k.(string)
- shareObject := v.(*ShareOption)
- if thisUuid == uuid {
- targetShareOption = shareObject
- }
- return true
- })
- return targetShareOption
- }
- func (s *ShareEntryTable) FileIsShared(pathhash string) bool {
- shareUUID := s.GetShareUUIDFromPathHash(pathhash)
- return shareUUID != ""
- }
- func (s *ShareEntryTable) RemoveShareByPathHash(pathhash string) error {
- so, ok := s.FileToUrlMap.Load(pathhash)
- if ok {
- shareUUID := so.(*ShareOption).UUID
- s.UrlToFileMap.Delete(shareUUID)
- s.FileToUrlMap.Delete(pathhash)
- s.Database.Delete("share", shareUUID)
- } else {
- return errors.New("Share with given realpath not exists")
- }
- return nil
- }
- func (s *ShareEntryTable) RemoveShareByUUID(uuid string) error {
- so, ok := s.UrlToFileMap.Load(uuid)
- if ok {
- shareOption := so.(*ShareOption)
- s.FileToUrlMap.Delete(shareOption.PathHash)
- s.UrlToFileMap.Delete(uuid)
- s.Database.Delete("share", uuid)
- } else {
- return errors.New("Share with given uuid not exists")
- }
- return nil
- }
- func (s *ShareEntryTable) ResolveShareOptionFromShareSubpath(subpath string) (*ShareOption, error) {
- subpathElements := strings.Split(filepath.ToSlash(filepath.Clean(subpath))[1:], "/")
- if len(subpathElements) >= 1 {
- shareObject := s.GetShareObjectFromUUID(subpathElements[0])
- if shareObject == nil {
- return nil, errors.New("Invalid subpath")
- } else {
- return shareObject, nil
- }
- } else {
- return nil, errors.New("Invalid subpath")
- }
- }
- func (s *ShareEntryTable) ResolveShareVrootPath(subpath string, username string, usergroup []string) (string, error) {
- //Get a list of accessible files from this user
- subpathElements := strings.Split(filepath.ToSlash(filepath.Clean(subpath))[1:], "/")
- if len(subpathElements) == 0 {
- //Requesting root folder.
- return "", errors.New("This virtual file system router do not support root listing")
- }
- //Analysis the subpath elements
- if len(subpathElements) == 1 {
- return "", errors.New("Redirect: parent")
- } else if len(subpathElements) == 2 {
- //ID only or ID with the target filename
- shareObject := s.GetShareObjectFromUUID(subpathElements[0])
- if shareObject == nil {
- return "", errors.New("Share file not found")
- }
- return shareObject.FileRealPath, nil
- } else if len(subpathElements) > 2 {
- //Loading folder / files inside folder type shares
- shareObject := s.GetShareObjectFromUUID(subpathElements[0])
- folderSubpaths := append([]string{shareObject.FileRealPath}, subpathElements[2:]...)
- targetFolder := filepath.Join(folderSubpaths...)
- return targetFolder, nil
- }
- return "", errors.New("Not implemented")
- }
- func (s *ShareEntryTable) Walk(subpath string, username string, usergroup []string, fastWalkFunction func(fs.FileData) error) error {
- //Resolve the subpath
- if subpath == "" {
- //List root as a collections of shares
- rootFileList := s.ListRootForUser(username, usergroup)
- for _, fileInRoot := range rootFileList {
- if fs.IsDir(fileInRoot.Realpath) {
- //Walk it
- err := filepath.Walk(fileInRoot.Realpath, func(path string, info os.FileInfo, err error) error {
- relPath, err := filepath.Rel(fileInRoot.Realpath, path)
- if err != nil {
- return err
- }
- thisVpath := filepath.ToSlash(filepath.Join(fileInRoot.Filepath, relPath))
- thisFd := fs.GetFileDataFromPath(thisVpath, path, 2)
- err = fastWalkFunction(thisFd)
- if err != nil {
- return err
- }
- return nil
- })
- return err
- } else {
- //Normal files
- err := fastWalkFunction(fileInRoot)
- if err != nil {
- return err
- }
- }
- }
- } else {
- //List realpath of the system
- rpath, err := s.ResolveShareVrootPath(subpath, username, usergroup)
- if err != nil {
- return err
- }
- vpath := "share:/" + subpath
- err = filepath.Walk(rpath, func(path string, info os.FileInfo, err error) error {
- relPath, err := filepath.Rel(rpath, path)
- if err != nil {
- return err
- }
- thisVpath := filepath.ToSlash(filepath.Join(vpath, relPath))
- thisFd := fs.GetFileDataFromPath(thisVpath, rpath, 2)
- err = fastWalkFunction(thisFd)
- if err != nil {
- return err
- }
- return nil
- })
- return err
- }
- return nil
- }
- func (s *ShareEntryTable) ListRootForUser(username string, usergroup []string) []fs.FileData {
- //Iterate through all shares in the system to see which of the share is user accessible
- userAccessiableShare := []*ShareOption{}
- s.FileToUrlMap.Range(func(fp, so interface{}) bool {
- fileRealpath := fp.(string)
- thisShareOption := so.(*ShareOption)
- if fs.FileExists(fileRealpath) {
- if thisShareOption.IsAccessibleBy(username, usergroup) {
- userAccessiableShare = append(userAccessiableShare, thisShareOption)
- }
- }
- return true
- })
- results := []fs.FileData{}
- for _, thisShareObject := range userAccessiableShare {
- rpath := thisShareObject.FileRealPath
- thisFile := fs.GetFileDataFromPath("share:/"+thisShareObject.UUID+"/"+filepath.Base(rpath), rpath, 2)
- if thisShareObject.Owner == username {
- thisFile.IsShared = true
- }
- results = append(results, thisFile)
- }
- return results
- }
- func GetPathHash(fsh *filesystem.FileSystemHandler, vpath string, username string) string {
- fshAbs := fsh.FileSystemAbstraction
- rpath := ""
- if strings.Contains(vpath, ":/") {
- rpath, _ = fshAbs.VirtualPathToRealPath(vpath, username)
- rpath = filepath.ToSlash(rpath)
- } else {
- //Passed in realpath as vpath.
- rpath = vpath
- }
- hash := md5.Sum([]byte(fsh.UUID + "_" + rpath))
- return hex.EncodeToString(hash[:])
- }
|