app.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Package cmd provides the ntfy CLI application
  2. package cmd
  3. import (
  4. "fmt"
  5. "github.com/urfave/cli/v2"
  6. "github.com/urfave/cli/v2/altsrc"
  7. "heckel.io/ntfy/client"
  8. "heckel.io/ntfy/util"
  9. "log"
  10. "os"
  11. "strings"
  12. )
  13. // New creates a new CLI application
  14. func New() *cli.App {
  15. return &cli.App{
  16. Name: "ntfy",
  17. Usage: "Simple pub-sub notification service",
  18. UsageText: "ntfy [OPTION..]",
  19. HideVersion: true,
  20. UseShortOptionHandling: true,
  21. Reader: os.Stdin,
  22. Writer: os.Stdout,
  23. ErrWriter: os.Stderr,
  24. Action: execMainApp,
  25. Before: initConfigFileInputSource("config", flagsServe), // DEPRECATED, see deprecation notice
  26. Flags: flagsServe, // DEPRECATED, see deprecation notice
  27. Commands: []*cli.Command{
  28. cmdServe,
  29. cmdPublish,
  30. cmdSubscribe,
  31. },
  32. }
  33. }
  34. func execMainApp(c *cli.Context) error {
  35. log.Printf("\x1b[1;33mDeprecation notice: Please run the server using 'ntfy serve'; see 'ntfy -h' for help.\x1b[0m")
  36. log.Printf("\x1b[1;33mThis way of running the server will be removed March 2022. See https://ntfy.sh/docs/deprecations/ for details.\x1b[0m")
  37. return execServe(c)
  38. }
  39. // initConfigFileInputSource is like altsrc.InitInputSourceWithContext and altsrc.NewYamlSourceFromFlagFunc, but checks
  40. // if the config flag is exists and only loads it if it does. If the flag is set and the file exists, it fails.
  41. func initConfigFileInputSource(configFlag string, flags []cli.Flag) cli.BeforeFunc {
  42. return func(context *cli.Context) error {
  43. configFile := context.String(configFlag)
  44. if context.IsSet(configFlag) && !util.FileExists(configFile) {
  45. return fmt.Errorf("config file %s does not exist", configFile)
  46. } else if !context.IsSet(configFlag) && !util.FileExists(configFile) {
  47. return nil
  48. }
  49. inputSource, err := altsrc.NewYamlSourceFromFile(configFile)
  50. if err != nil {
  51. return err
  52. }
  53. return altsrc.ApplyInputSourceValues(context, inputSource, flags)
  54. }
  55. }
  56. func expandTopicURL(s string) string {
  57. if strings.HasPrefix(s, "http://") || strings.HasPrefix(s, "https://") {
  58. return s
  59. } else if strings.Contains(s, "/") {
  60. return fmt.Sprintf("https://%s", s)
  61. }
  62. return fmt.Sprintf("%s/%s", client.DefaultBaseURL, s)
  63. }
  64. func collapseTopicURL(s string) string {
  65. return strings.TrimPrefix(strings.TrimPrefix(s, "https://"), "http://")
  66. }