tier.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. //go:build !noserver
  2. package cmd
  3. import (
  4. "errors"
  5. "fmt"
  6. "github.com/urfave/cli/v2"
  7. "heckel.io/ntfy/user"
  8. "heckel.io/ntfy/util"
  9. "time"
  10. )
  11. func init() {
  12. commands = append(commands, cmdTier)
  13. }
  14. const (
  15. defaultMessageLimit = 5000
  16. defaultMessageExpiryDuration = 12 * time.Hour
  17. defaultEmailLimit = 20
  18. defaultReservationLimit = 3
  19. defaultAttachmentFileSizeLimit = "15M"
  20. defaultAttachmentTotalSizeLimit = "100M"
  21. defaultAttachmentExpiryDuration = 6 * time.Hour
  22. defaultAttachmentBandwidthLimit = "1G"
  23. )
  24. var (
  25. flagsTier = append([]cli.Flag{}, flagsUser...)
  26. )
  27. var cmdTier = &cli.Command{
  28. Name: "tier",
  29. Usage: "Manage/show tiers",
  30. UsageText: "ntfy tier [list|add|change|remove] ...",
  31. Flags: flagsTier,
  32. Before: initConfigFileInputSourceFunc("config", flagsUser, initLogFunc),
  33. Category: categoryServer,
  34. Subcommands: []*cli.Command{
  35. {
  36. Name: "add",
  37. Aliases: []string{"a"},
  38. Usage: "Adds a new tier",
  39. UsageText: "ntfy tier add [OPTIONS] CODE",
  40. Action: execTierAdd,
  41. Flags: []cli.Flag{
  42. &cli.StringFlag{Name: "name", Usage: "tier name"},
  43. &cli.Int64Flag{Name: "message-limit", Value: defaultMessageLimit, Usage: "daily message limit"},
  44. &cli.DurationFlag{Name: "message-expiry-duration", Value: defaultMessageExpiryDuration, Usage: "duration after which messages are deleted"},
  45. &cli.Int64Flag{Name: "email-limit", Value: defaultEmailLimit, Usage: "daily email limit"},
  46. &cli.Int64Flag{Name: "reservation-limit", Value: defaultReservationLimit, Usage: "topic reservation limit"},
  47. &cli.StringFlag{Name: "attachment-file-size-limit", Value: defaultAttachmentFileSizeLimit, Usage: "per-attachment file size limit"},
  48. &cli.StringFlag{Name: "attachment-total-size-limit", Value: defaultAttachmentTotalSizeLimit, Usage: "total size limit of attachments for the user"},
  49. &cli.DurationFlag{Name: "attachment-expiry-duration", Value: defaultAttachmentExpiryDuration, Usage: "duration after which attachments are deleted"},
  50. &cli.StringFlag{Name: "attachment-bandwidth-limit", Value: defaultAttachmentBandwidthLimit, Usage: "daily bandwidth limit for attachment uploads/downloads"},
  51. &cli.StringFlag{Name: "stripe-price-id", Usage: "Stripe price ID for paid tiers (e.g. price_12345)"},
  52. &cli.BoolFlag{Name: "ignore-exists", Usage: "if the tier already exists, perform no action and exit"},
  53. },
  54. Description: `Add a new tier to the ntfy user database.
  55. Tiers can be used to grant users higher limits, such as daily message limits, attachment size, or
  56. make it possible for users to reserve topics.
  57. This is a server-only command. It directly reads from user.db as defined in the server config
  58. file server.yml. The command only works if 'auth-file' is properly defined.
  59. Examples:
  60. ntfy tier add pro # Add tier with code "pro", using the defaults
  61. ntfy tier add \ # Add a tier with custom limits
  62. --name="Pro" \
  63. --message-limit=10000 \
  64. --message-expiry-duration=24h \
  65. --email-limit=50 \
  66. --reservation-limit=10 \
  67. --attachment-file-size-limit=100M \
  68. --attachment-total-size-limit=1G \
  69. --attachment-expiry-duration=12h \
  70. --attachment-bandwidth-limit=5G \
  71. pro
  72. `,
  73. },
  74. {
  75. Name: "change",
  76. Aliases: []string{"ch"},
  77. Usage: "Change a tier",
  78. UsageText: "ntfy tier change [OPTIONS] CODE",
  79. Action: execTierChange,
  80. Flags: []cli.Flag{
  81. &cli.StringFlag{Name: "name", Usage: "tier name"},
  82. &cli.Int64Flag{Name: "message-limit", Usage: "daily message limit"},
  83. &cli.DurationFlag{Name: "message-expiry-duration", Usage: "duration after which messages are deleted"},
  84. &cli.Int64Flag{Name: "email-limit", Usage: "daily email limit"},
  85. &cli.Int64Flag{Name: "reservation-limit", Usage: "topic reservation limit"},
  86. &cli.StringFlag{Name: "attachment-file-size-limit", Usage: "per-attachment file size limit"},
  87. &cli.StringFlag{Name: "attachment-total-size-limit", Usage: "total size limit of attachments for the user"},
  88. &cli.DurationFlag{Name: "attachment-expiry-duration", Usage: "duration after which attachments are deleted"},
  89. &cli.StringFlag{Name: "attachment-bandwidth-limit", Usage: "daily bandwidth limit for attachment uploads/downloads"},
  90. &cli.StringFlag{Name: "stripe-price-id", Usage: "Stripe price ID for paid tiers (e.g. price_12345)"},
  91. },
  92. Description: `Updates a tier to change the limits.
  93. After updating a tier, you may have to restart the ntfy server to apply them
  94. to all visitors.
  95. This is a server-only command. It directly reads from user.db as defined in the server config
  96. file server.yml. The command only works if 'auth-file' is properly defined.
  97. Examples:
  98. ntfy tier change --name="Pro" pro # Update the name of an existing tier
  99. ntfy tier change \ # Update multiple limits and fields
  100. --message-expiry-duration=24h \
  101. --stripe-price-id=price_1234 \
  102. pro
  103. `,
  104. },
  105. {
  106. Name: "remove",
  107. Aliases: []string{"del", "rm"},
  108. Usage: "Removes a tier",
  109. UsageText: "ntfy tier remove CODE",
  110. Action: execTierDel,
  111. Description: `Remove a tier from the ntfy user database.
  112. You cannot remove a tier if there are users associated with a tier. Use "ntfy user change-tier"
  113. to remove or switch their tier first.
  114. This is a server-only command. It directly reads from user.db as defined in the server config
  115. file server.yml. The command only works if 'auth-file' is properly defined.
  116. Example:
  117. ntfy tier del pro
  118. `,
  119. },
  120. {
  121. Name: "list",
  122. Aliases: []string{"l"},
  123. Usage: "Shows a list of tiers",
  124. Action: execTierList,
  125. Description: `Shows a list of all configured tiers.
  126. This is a server-only command. It directly reads from user.db as defined in the server config
  127. file server.yml. The command only works if 'auth-file' is properly defined.
  128. `,
  129. },
  130. },
  131. Description: `Manage tiers of the ntfy server.
  132. The command allows you to add/remove/change tiers in the ntfy user database. Tiers are used
  133. to grant users higher limits, such as daily message limits, attachment size, or make it
  134. possible for users to reserve topics.
  135. This is a server-only command. It directly manages the user.db as defined in the server config
  136. file server.yml. The command only works if 'auth-file' is properly defined.
  137. Examples:
  138. ntfy tier add pro # Add tier with code "pro", using the defaults
  139. ntfy tier change --name="Pro" pro # Update the name of an existing tier
  140. ntfy tier del pro # Delete an existing tier
  141. `,
  142. }
  143. func execTierAdd(c *cli.Context) error {
  144. code := c.Args().Get(0)
  145. if code == "" {
  146. return errors.New("tier code expected, type 'ntfy tier add --help' for help")
  147. } else if !user.AllowedTier(code) {
  148. return errors.New("tier code must consist only of numbers and letters")
  149. }
  150. manager, err := createUserManager(c)
  151. if err != nil {
  152. return err
  153. }
  154. if tier, _ := manager.Tier(code); tier != nil {
  155. if c.Bool("ignore-exists") {
  156. fmt.Fprintf(c.App.ErrWriter, "tier %s already exists (exited successfully)\n", code)
  157. return nil
  158. }
  159. return fmt.Errorf("tier %s already exists", code)
  160. }
  161. name := c.String("name")
  162. if name == "" {
  163. name = code
  164. }
  165. attachmentFileSizeLimit, err := util.ParseSize(c.String("attachment-file-size-limit"))
  166. if err != nil {
  167. return err
  168. }
  169. attachmentTotalSizeLimit, err := util.ParseSize(c.String("attachment-total-size-limit"))
  170. if err != nil {
  171. return err
  172. }
  173. attachmentBandwidthLimit, err := util.ParseSize(c.String("attachment-bandwidth-limit"))
  174. if err != nil {
  175. return err
  176. }
  177. tier := &user.Tier{
  178. ID: "", // Generated
  179. Code: code,
  180. Name: name,
  181. MessageLimit: c.Int64("message-limit"),
  182. MessageExpiryDuration: c.Duration("message-expiry-duration"),
  183. EmailLimit: c.Int64("email-limit"),
  184. ReservationLimit: c.Int64("reservation-limit"),
  185. AttachmentFileSizeLimit: attachmentFileSizeLimit,
  186. AttachmentTotalSizeLimit: attachmentTotalSizeLimit,
  187. AttachmentExpiryDuration: c.Duration("attachment-expiry-duration"),
  188. AttachmentBandwidthLimit: attachmentBandwidthLimit,
  189. StripePriceID: c.String("stripe-price-id"),
  190. }
  191. if err := manager.AddTier(tier); err != nil {
  192. return err
  193. }
  194. tier, err = manager.Tier(code)
  195. if err != nil {
  196. return err
  197. }
  198. fmt.Fprintf(c.App.ErrWriter, "tier added\n\n")
  199. printTier(c, tier)
  200. return nil
  201. }
  202. func execTierChange(c *cli.Context) error {
  203. code := c.Args().Get(0)
  204. if code == "" {
  205. return errors.New("tier code expected, type 'ntfy tier change --help' for help")
  206. } else if !user.AllowedTier(code) {
  207. return errors.New("tier code must consist only of numbers and letters")
  208. }
  209. manager, err := createUserManager(c)
  210. if err != nil {
  211. return err
  212. }
  213. tier, err := manager.Tier(code)
  214. if err == user.ErrTierNotFound {
  215. return fmt.Errorf("tier %s does not exist", code)
  216. } else if err != nil {
  217. return err
  218. }
  219. if c.IsSet("name") {
  220. tier.Name = c.String("name")
  221. }
  222. if c.IsSet("message-limit") {
  223. tier.MessageLimit = c.Int64("message-limit")
  224. }
  225. if c.IsSet("message-expiry-duration") {
  226. tier.MessageExpiryDuration = c.Duration("message-expiry-duration")
  227. }
  228. if c.IsSet("email-limit") {
  229. tier.EmailLimit = c.Int64("email-limit")
  230. }
  231. if c.IsSet("reservation-limit") {
  232. tier.ReservationLimit = c.Int64("reservation-limit")
  233. }
  234. if c.IsSet("attachment-file-size-limit") {
  235. tier.AttachmentFileSizeLimit, err = util.ParseSize(c.String("attachment-file-size-limit"))
  236. if err != nil {
  237. return err
  238. }
  239. }
  240. if c.IsSet("attachment-total-size-limit") {
  241. tier.AttachmentTotalSizeLimit, err = util.ParseSize(c.String("attachment-total-size-limit"))
  242. if err != nil {
  243. return err
  244. }
  245. }
  246. if c.IsSet("attachment-expiry-duration") {
  247. tier.AttachmentExpiryDuration = c.Duration("attachment-expiry-duration")
  248. }
  249. if c.IsSet("attachment-bandwidth-limit") {
  250. tier.AttachmentBandwidthLimit, err = util.ParseSize(c.String("attachment-bandwidth-limit"))
  251. if err != nil {
  252. return err
  253. }
  254. }
  255. if c.IsSet("stripe-price-id") {
  256. tier.StripePriceID = c.String("stripe-price-id")
  257. }
  258. if err := manager.UpdateTier(tier); err != nil {
  259. return err
  260. }
  261. fmt.Fprintf(c.App.ErrWriter, "tier updated\n\n")
  262. printTier(c, tier)
  263. return nil
  264. }
  265. func execTierDel(c *cli.Context) error {
  266. code := c.Args().Get(0)
  267. if code == "" {
  268. return errors.New("tier code expected, type 'ntfy tier del --help' for help")
  269. }
  270. manager, err := createUserManager(c)
  271. if err != nil {
  272. return err
  273. }
  274. if _, err := manager.Tier(code); err == user.ErrTierNotFound {
  275. return fmt.Errorf("tier %s does not exist", code)
  276. }
  277. if err := manager.RemoveTier(code); err != nil {
  278. return err
  279. }
  280. fmt.Fprintf(c.App.ErrWriter, "tier %s removed\n", code)
  281. return nil
  282. }
  283. func execTierList(c *cli.Context) error {
  284. manager, err := createUserManager(c)
  285. if err != nil {
  286. return err
  287. }
  288. tiers, err := manager.Tiers()
  289. if err != nil {
  290. return err
  291. }
  292. for _, tier := range tiers {
  293. printTier(c, tier)
  294. }
  295. return nil
  296. }
  297. func printTier(c *cli.Context, tier *user.Tier) {
  298. stripePriceID := tier.StripePriceID
  299. if stripePriceID == "" {
  300. stripePriceID = "(none)"
  301. }
  302. fmt.Fprintf(c.App.ErrWriter, "tier %s (id: %s)\n", tier.Code, tier.ID)
  303. fmt.Fprintf(c.App.ErrWriter, "- Name: %s\n", tier.Name)
  304. fmt.Fprintf(c.App.ErrWriter, "- Message limit: %d\n", tier.MessageLimit)
  305. fmt.Fprintf(c.App.ErrWriter, "- Message expiry duration: %s (%d seconds)\n", tier.MessageExpiryDuration.String(), int64(tier.MessageExpiryDuration.Seconds()))
  306. fmt.Fprintf(c.App.ErrWriter, "- Email limit: %d\n", tier.EmailLimit)
  307. fmt.Fprintf(c.App.ErrWriter, "- Reservation limit: %d\n", tier.ReservationLimit)
  308. fmt.Fprintf(c.App.ErrWriter, "- Attachment file size limit: %s\n", util.FormatSize(tier.AttachmentFileSizeLimit))
  309. fmt.Fprintf(c.App.ErrWriter, "- Attachment total size limit: %s\n", util.FormatSize(tier.AttachmentTotalSizeLimit))
  310. fmt.Fprintf(c.App.ErrWriter, "- Attachment expiry duration: %s (%d seconds)\n", tier.AttachmentExpiryDuration.String(), int64(tier.AttachmentExpiryDuration.Seconds()))
  311. fmt.Fprintf(c.App.ErrWriter, "- Attachment daily bandwidth limit: %s\n", util.FormatSize(tier.AttachmentBandwidthLimit))
  312. fmt.Fprintf(c.App.ErrWriter, "- Stripe price: %s\n", stripePriceID)
  313. }