Fallback to backup path if storage path is not defined or writable

This commit is contained in:
Michael Mayer 2020-12-04 11:37:31 +01:00
parent ca41189dda
commit b7876711ad
3 changed files with 37 additions and 5 deletions
internal/config
pkg/fs

View file

@ -275,17 +275,22 @@ func (c *Config) StoragePath() string {
storageDir := fs.Abs(dirName)
// Find existing directories.
if fs.PathExists(originalsDir) && !c.ReadOnly() {
if fs.PathWritable(originalsDir) && !c.ReadOnly() {
return originalsDir
} else if fs.PathExists(storageDir) && c.ReadOnly() {
} else if fs.PathWritable(storageDir) && c.ReadOnly() {
return storageDir
}
// Fallback to backup storage path.
if fs.PathWritable(c.params.BackupPath) {
return fs.Abs(filepath.Join(c.params.BackupPath, dirName))
}
// Use .photoprism in home directory?
if usr, _ := user.Current(); usr.HomeDir != "" {
p := fs.Abs(filepath.Join(usr.HomeDir, fs.HiddenPath, dirName))
if fs.PathExists(p) || c.ReadOnly() {
if fs.PathWritable(p) || c.ReadOnly() {
return p
}
}
@ -304,7 +309,7 @@ func (c *Config) StoragePath() string {
// BackupPath returns the backup storage path.
func (c *Config) BackupPath() string {
if fs.PathExists(c.params.BackupPath) {
if fs.PathWritable(c.params.BackupPath) {
return fs.Abs(c.params.BackupPath)
}

View file

@ -40,6 +40,8 @@ import (
"os/user"
"path/filepath"
"strings"
"github.com/photoprism/photoprism/pkg/rnd"
)
const IgnoreFile = ".ppignore"
@ -59,7 +61,7 @@ func FileExists(fileName string) bool {
return err == nil && !info.IsDir()
}
// PathExists returns true if path exists and is a directory or symlink.
// PathExists tests if a path exists, and is a directory or symlink.
func PathExists(path string) bool {
if path == "" {
return false
@ -76,6 +78,25 @@ func PathExists(path string) bool {
return m&os.ModeDir != 0 || m&os.ModeSymlink != 0
}
// PathWritable tests if a path exists and is writable.
func PathWritable(path string) bool {
if !PathExists(path) {
return false
}
tmpName := filepath.Join(path, "."+rnd.Token(8))
if f, err := os.Create(tmpName); err != nil {
return false
} else if err := f.Close(); err != nil {
return false
} else if err := os.Remove(tmpName); err != nil {
return false
}
return true
}
// Overwrite overwrites the file with data. Creates file if not present.
func Overwrite(fileName string, data []byte) bool {
f, err := os.Create(fileName)

View file

@ -20,6 +20,12 @@ func TestPathExists(t *testing.T) {
assert.False(t, PathExists("./testdata3ggdtgdg"))
}
func TestPathWritable(t *testing.T) {
assert.True(t, PathExists("./testdata"))
assert.False(t, PathExists("./testdata/test.jpg"))
assert.False(t, PathExists("./testdata3ggdtgdg"))
}
func TestOverwrite(t *testing.T) {
data := make([]byte, 3)
data[1] = 3