subscribe_linux.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package cmd
  2. import (
  3. "fmt"
  4. "github.com/urfave/cli/v2"
  5. "heckel.io/ntfy/client"
  6. "heckel.io/ntfy/util"
  7. "log"
  8. "os"
  9. "os/exec"
  10. "os/user"
  11. "path/filepath"
  12. )
  13. const (
  14. defaultClientRootConfigFile = "/etc/ntfy/client.yml"
  15. defaultClientUserConfigFileRelative = "ntfy/client.yml"
  16. defaultClientConfigFileDescriptionSuffix = `The default config file for all client commands is /etc/ntfy/client.yml (if root user),
  17. or ~/.config/ntfy/client.yml for all other users.`
  18. )
  19. func runCommandInternal(c *cli.Context, command string, m *client.Message) error {
  20. scriptFile, err := createTmpScript(command)
  21. if err != nil {
  22. return err
  23. }
  24. defer os.Remove(scriptFile)
  25. verbose := c.Bool("verbose")
  26. if verbose {
  27. log.Printf("[%s] Executing: %s (for message: %s)", util.ShortTopicURL(m.TopicURL), command, m.Raw)
  28. }
  29. cmd := exec.Command("sh", "-c", scriptFile)
  30. cmd.Stdin = c.App.Reader
  31. cmd.Stdout = c.App.Writer
  32. cmd.Stderr = c.App.ErrWriter
  33. cmd.Env = envVars(m)
  34. return cmd.Run()
  35. }
  36. func createTmpScript(command string) (string, error) {
  37. scriptFile := fmt.Sprintf("%s/ntfy-subscribe-%s.sh.tmp", os.TempDir(), util.RandomString(10))
  38. script := fmt.Sprintf("#!/bin/sh\n%s", command)
  39. if err := os.WriteFile(scriptFile, []byte(script), 0700); err != nil {
  40. return "", err
  41. }
  42. return scriptFile, nil
  43. }
  44. func defaultConfigFile() string {
  45. u, _ := user.Current()
  46. configFile := defaultClientRootConfigFile
  47. if u.Uid != "0" {
  48. homeDir, _ := os.UserConfigDir()
  49. return filepath.Join(homeDir, defaultClientUserConfigFileRelative)
  50. }
  51. return configFile
  52. }