Debian Codegraph @

cmd/tier.go

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