From: Thomas Karpiniec Date: Mon, 26 Feb 2024 03:13:59 +0000 (+1100) Subject: Initial git commit X-Git-Url: https://code.octet-stream.net/photosorter/commitdiff_plain Initial git commit --- a42c5786fafc88cf7067dde24964aca256fc2186 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4c3d884 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +photosorter diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0f93d67 --- /dev/null +++ b/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2023 Thomas Karpiniec + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b366187 --- /dev/null +++ b/README.md @@ -0,0 +1,36 @@ +# photosorter + +A personal tool for monitoring for new photos synced from a phone via SyncThing and placing them into the real photos directory automatically. + +Each photo's modification time is used to determine the year it was taken and it is copied to `${target}/${year}/${filename}`. + +A cache of seen files is maintained in `~/.cache` so that files which are deleted from the target directory are not re-copied. + +## Usage + +Compile: + +``` +go build +``` + +Install the binary in a location such as `/usr/local/bin/photosorter`. + +Copy the provided systemd template `photosorter.service` to `~/.config/systemd/user/` and edit the source path (`-s`) and target path (`-t`) to match your needs. + +Activate the service: + +``` +systemctl --user enable photosorter +systemctl --user start photosorter +``` + +Watch output with: + +``` +journalctl --user-unit photosorter -f +``` + +## Licence + +MIT diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..11427c7 --- /dev/null +++ b/go.mod @@ -0,0 +1,7 @@ +module github.com/thombles/photosorter + +go 1.21.1 + +require github.com/fsnotify/fsnotify v1.6.0 + +require golang.org/x/sys v0.0.0-20220908164124-27713097b956 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..60d7d6e --- /dev/null +++ b/go.sum @@ -0,0 +1,4 @@ +github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= +github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +golang.org/x/sys v0.0.0-20220908164124-27713097b956 h1:XeJjHH1KiLpKGb6lvMiksZ9l0fVUh+AmGcm0nOMEBOY= +golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/photosorter.go b/photosorter.go new file mode 100644 index 0000000..ec7223c --- /dev/null +++ b/photosorter.go @@ -0,0 +1,174 @@ +package main + +import ( + "bufio" + "errors" + "flag" + "log" + "os" + "os/signal" + "path" + "strconv" + "strings" + "syscall" + "time" + + "github.com/fsnotify/fsnotify" +) + +var sourcePath string +var targetPath string + +func getSeenPath() string { + cacheDir, err := os.UserCacheDir() + if err != nil { + log.Fatal(err, "No cache directory available") + } + return path.Join(cacheDir, "photosorter", "seen") +} + +func prepareStateDir() { + parent := path.Dir(getSeenPath()) + log.Println("Storing seen cache in:", parent) + os.MkdirAll(parent, 0700) +} + +func getSeen() map[string]bool { + seenFiles := make(map[string]bool) + file, err := os.Open(getSeenPath()) + if err != nil { + return seenFiles + } + defer file.Close() + scanner := bufio.NewScanner(file) + for scanner.Scan() { + seenFiles[scanner.Text()] = true + } + return seenFiles +} + +func setSeen(seenFiles map[string]bool) { + file, err := os.Create(getSeenPath()) + if err != nil { + return + } + defer file.Close() + w := bufio.NewWriter(file) + for key := range seenFiles { + w.WriteString(key) + w.WriteString("\n") + } + w.Flush() +} + +func processFile(name string, modified time.Time) { + sourceFile := path.Join(sourcePath, name) + targetDir := path.Join(targetPath, strconv.Itoa(modified.Year())) + targetFile := path.Join(targetDir, name) + if _, err := os.Stat(targetFile); errors.Is(err, os.ErrNotExist) { + log.Println("Copying src:", sourceFile, "target:", targetFile) + r, err := os.Open(sourceFile) + if err != nil { + return + } + defer r.Close() + os.MkdirAll(targetDir, 0700) + w, err := os.Create(targetFile) + if err != nil { + return + } + defer w.Close() + _, err = w.ReadFrom(r) + if err != nil { + // Try to clean up for next time + os.Remove(targetFile) + } + } else { + log.Println("Skipping because it exists, src:", sourceFile, "target:", targetFile) + } +} + +func doSort() { + log.Println("Starting sort...") + didProcess := false + seenFiles := getSeen() + newSeenFiles := make(map[string]bool) + files, err := os.ReadDir(sourcePath) + if err != nil { + log.Fatal(err) + } + for _, file := range files { + if strings.HasPrefix(file.Name(), ".") { + continue + } + if !file.Type().IsRegular() { + continue + } + info, err := file.Info() + if err != nil { + continue + } + newSeenFiles[file.Name()] = true + if seenFiles[file.Name()] { + continue + } + processFile(file.Name(), info.ModTime()) + didProcess = true + } + setSeen(newSeenFiles) + if didProcess { + log.Println("Sort complete") + } else { + log.Println("Sort complete (no changes)") + } +} + +func sortWorker(changeTimes chan time.Time) { + // Handle signals cleanly so we avoid stopping mid-execution + stopping := make(chan os.Signal) + signal.Notify(stopping, syscall.SIGTERM, syscall.SIGHUP) + + // Initial sort to catch any changes before startup + lastRun := time.Now() + doSort() + for { + select { + case <-stopping: + log.Println("Stopping due to signal") + os.Exit(0) + case t := <-changeTimes: + if t.After(lastRun) { + log.Println("Source directory did change") + lastRun = time.Now() + doSort() + } + } + } +} + +func watcher(changeTimes chan time.Time) { + w, err := fsnotify.NewWatcher() + if err != nil { + log.Fatal(err) + } + defer w.Close() + w.Add(sourcePath) + for range w.Events { + changeTimes <- time.Now() + } +} + +func main() { + const req = "REQUIRED" + flag.StringVar(&sourcePath, "s", req, "source directory where photos are uploaded") + flag.StringVar(&targetPath, "t", req, "target directory in which year directories are created") + flag.Parse() + if sourcePath == req || targetPath == req { + log.Println("Source and Target paths must both be provided") + os.Exit(1) + } + prepareStateDir() + changeTimes := make(chan time.Time, 1024) + go sortWorker(changeTimes) + watcher(changeTimes) +} diff --git a/photosorter.service b/photosorter.service new file mode 100644 index 0000000..a4d6045 --- /dev/null +++ b/photosorter.service @@ -0,0 +1,8 @@ +[Unit] +Description=Camera Photo Sorter + +[Service] +ExecStart=/usr/local/bin/photosorter -s /home/USER/sync/Camera -t /home/USER/photos + +[Install] +WantedBy=default.target