camcap.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "sync"
  10. "time"
  11. "strings"
  12. )
  13. // Camera represents a single camera
  14. type Camera struct {
  15. Host string `json:"host"`
  16. Port string `json:"port"`
  17. }
  18. // Config represents the full JSON config
  19. type Config struct {
  20. ImagesPath string `json:"images_path"`
  21. NtfyURL string `json:"ntfy_url"`
  22. PollIntervalMinutes int `json:"poll_interval_minutes"`
  23. Cameras map[string]Camera `json:"cameras"`
  24. }
  25. var config Config
  26. func main() {
  27. loadConfig()
  28. interval := time.Duration(config.PollIntervalMinutes) * time.Minute
  29. ticker := time.NewTicker(interval)
  30. defer ticker.Stop()
  31. // Run immediately at startup
  32. go pollImages()
  33. for range ticker.C {
  34. go pollImages()
  35. }
  36. select {} // keep program running
  37. }
  38. // loadConfig searches multiple locations for the JSON config
  39. func loadConfig() {
  40. paths := []string{
  41. "/usr/local/etc/camcap.json",
  42. "/usr/etc/camcap.json",
  43. "./camcap.json",
  44. }
  45. var configFile string
  46. for _, path := range paths {
  47. if _, err := os.Stat(path); err == nil {
  48. configFile = path
  49. break
  50. }
  51. }
  52. if configFile == "" {
  53. panic("No configuration file found in /usr/local/etc, /usr/etc, or current directory")
  54. }
  55. f, err := os.Open(configFile)
  56. if err != nil {
  57. panic(err)
  58. }
  59. defer f.Close()
  60. if err := json.NewDecoder(f).Decode(&config); err != nil {
  61. panic(err)
  62. }
  63. fmt.Println("Loaded config from:", configFile)
  64. }
  65. // pollImages downloads snapshots concurrently
  66. func pollImages() {
  67. fmt.Println("Starting image poll at", time.Now())
  68. var wg sync.WaitGroup
  69. errCh := make(chan error, len(config.Cameras))
  70. for title, cam := range config.Cameras {
  71. url := fmt.Sprintf("http://%s.service:%s/snapshot", cam.Host, cam.Port)
  72. wg.Add(1)
  73. go func(title, url string) {
  74. defer wg.Done()
  75. if err := downloadImageWithTitle(url, title); err != nil {
  76. errCh <- fmt.Errorf("%s: %v", title, err)
  77. } else {
  78. fmt.Println("Downloaded:", title)
  79. }
  80. }(title, url)
  81. }
  82. wg.Wait()
  83. close(errCh)
  84. for err := range errCh {
  85. fmt.Println("Error:", err)
  86. }
  87. fmt.Println("Finished image poll at", time.Now())
  88. }
  89. // downloadImageWithTitle saves the image to timestamped directories
  90. func downloadImageWithTitle(url, title string) error {
  91. today := time.Now()
  92. dir := filepath.Join(config.ImagesPath, title,
  93. fmt.Sprintf("%d", today.Year()),
  94. fmt.Sprintf("%02d", today.Month()),
  95. fmt.Sprintf("%02d", today.Day()))
  96. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  97. return err
  98. }
  99. timestamp := today.Format("20060102150405")
  100. fileName := fmt.Sprintf("%s-%s.jpg", title, timestamp)
  101. filePath := filepath.Join(dir, fileName)
  102. resp, err := http.Get(url)
  103. if err != nil {
  104. notifyError(fmt.Sprintf("Connection error for %s: %v", title, err))
  105. return err
  106. }
  107. defer resp.Body.Close()
  108. if resp.StatusCode != http.StatusOK {
  109. notifyError(fmt.Sprintf("HTTP error for %s: %s", title, resp.Status))
  110. return fmt.Errorf("bad status: %s", resp.Status)
  111. }
  112. out, err := os.Create(filePath)
  113. if err != nil {
  114. notifyError(fmt.Sprintf("File creation error for %s: %v", title, err))
  115. return err
  116. }
  117. defer out.Close()
  118. _, err = io.Copy(out, resp.Body)
  119. if err != nil {
  120. notifyError(fmt.Sprintf("File write error for %s: %v", title, err))
  121. }
  122. return err
  123. }
  124. // notifyError posts errors to ntfy
  125. func notifyError(message string) {
  126. resp, err := http.Post(config.NtfyURL, "text/plain", strings.NewReader(message))
  127. if err != nil {
  128. fmt.Println("Failed to send ntfy notification:", err)
  129. return
  130. }
  131. defer resp.Body.Close()
  132. fmt.Println("Sent ntfy error:", message)
  133. }