github.com/jstaf/onedriver@v0.14.2-0.20240420231225-f07678f9e6ef/ui/onedriver.go (about) 1 package ui 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 "os" 8 "path/filepath" 9 "strings" 10 "time" 11 12 "github.com/jstaf/onedriver/fs/graph" 13 "github.com/rs/zerolog/log" 14 ) 15 16 // onedriver specific utility functions 17 18 // PollUntilAvail will block until the mountpoint is available or a timeout is reached. 19 // If timeout is -1, default timeout is 120s. 20 func PollUntilAvail(mountpoint string, timeout int) bool { 21 if timeout == -1 { 22 timeout = 120 23 } 24 for i := 1; i < timeout*10; i++ { 25 _, err := os.Stat(filepath.Join(mountpoint, ".xdg-volume-info")) 26 if err == nil { 27 return true 28 } 29 time.Sleep(100 * time.Millisecond) 30 } 31 return false 32 } 33 34 // MountpointIsValid returns if the mountpoint exists and nothing is in it. 35 func MountpointIsValid(mountpoint string) bool { 36 dirents, err := ioutil.ReadDir(mountpoint) 37 if err != nil { 38 return false 39 } 40 return len(dirents) == 0 41 } 42 43 func GetAccountName(cacheDir, instance string) (string, error) { 44 tokenFile := fmt.Sprintf("%s/%s/auth_tokens.json", cacheDir, instance) 45 46 var auth graph.Auth 47 data, err := ioutil.ReadFile(tokenFile) 48 if err != nil { 49 return "", err 50 } 51 err = json.Unmarshal(data, &auth) 52 if err != nil { 53 return "", err 54 } 55 return auth.Account, nil 56 } 57 58 // GetKnownMounts returns the currently known mountpoints and returns their escaped name 59 func GetKnownMounts(cacheDir string) []string { 60 mounts := make([]string, 0) 61 62 if cacheDir == "" { 63 userCacheDir, _ := os.UserCacheDir() 64 cacheDir = filepath.Join(userCacheDir, "onedriver") 65 } 66 os.MkdirAll(cacheDir, 0700) 67 dirents, err := ioutil.ReadDir(cacheDir) 68 69 if err != nil { 70 log.Error().Err(err).Msg("Could not fetch known mountpoints.") 71 return mounts 72 } 73 74 for _, dirent := range dirents { 75 _, err := os.Stat(filepath.Join(cacheDir, dirent.Name(), "auth_tokens.json")) 76 if err == nil { 77 mounts = append(mounts, dirent.Name()) 78 } 79 } 80 return mounts 81 } 82 83 // EscapeHome replaces the user's absolute home directory with "~" 84 func EscapeHome(path string) string { 85 homedir, _ := os.UserHomeDir() 86 if strings.HasPrefix(path, homedir) { 87 return strings.Replace(path, homedir, "~", 1) 88 } 89 return path 90 } 91 92 // UnescapeHome replaces the "~" in a path with the absolute path. 93 func UnescapeHome(path string) string { 94 if strings.HasPrefix(path, "~/") { 95 homedir, _ := os.UserHomeDir() 96 return filepath.Join(homedir, path[2:]) 97 } 98 return path 99 }