tier.go 14 KB

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