tier.go 13 KB

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