tier.go 14 KB

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