diff options
Diffstat (limited to 'internal')
| -rw-r--r-- | internal/mailer/mailer.go | 80 | ||||
| -rw-r--r-- | internal/router/api-v1-subs.go | 2 | ||||
| -rw-r--r-- | internal/router/lang-user-unsubscribe.go | 69 |
3 files changed, 134 insertions, 17 deletions
diff --git a/internal/mailer/mailer.go b/internal/mailer/mailer.go index f51186e..c146548 100644 --- a/internal/mailer/mailer.go +++ b/internal/mailer/mailer.go @@ -6,6 +6,7 @@ import ( "encoding/base64" "encoding/binary" "fmt" + "html/template" "log/slog" "slices" "strconv" @@ -24,6 +25,7 @@ import ( type Mailer struct { verificationCodes *ristretto.Cache[uint64, string] + unsubscribeCodes *ristretto.Cache[uint64, []byte] db *sql.DB tm *templatemanager.TemplateManager mailClient *mail.Client @@ -58,7 +60,17 @@ func NewMailer(db *sql.DB, clientHost string, mailHost string, publicName string NumCounters: 10000, MaxCost: 1 << 20, // 1 MB BufferItems: 64, - TtlTickerDurationInSec: 3600, + TtlTickerDurationInSec: 3600, // 1 hour + }) + if err != nil { + return nil, fmt.Errorf("fail to initialize cache for verification codes: %w", err) + } + + unsubscribeCodes, err := ristretto.NewCache(&ristretto.Config[uint64, []byte]{ + NumCounters: 10000, + MaxCost: 1 << 20, // 1 MB + BufferItems: 64, + TtlTickerDurationInSec: 86400, // 1 day }) if err != nil { return nil, fmt.Errorf("fail to initialize cache for verification codes: %w", err) @@ -85,6 +97,7 @@ func NewMailer(db *sql.DB, clientHost string, mailHost string, publicName string return &Mailer{ verificationCodes: verificationCodes, + unsubscribeCodes: unsubscribeCodes, db: db, clientHost: clientHost, tm: tm, @@ -175,6 +188,24 @@ func (m *Mailer) GetInfo(userIdHash []byte) (email string, lang string, err erro return } +func (m *Mailer) Unsubscribe(unsubscribeCodeString string) (clientError error, serverError error) { + unsubscribeCode, err := strconv.ParseUint(unsubscribeCodeString, 16, 64) + if err != nil { + return fmt.Errorf("invalid unsubscribe code: %s", err), nil + } + + userId, _ := m.unsubscribeCodes.Get(unsubscribeCode) + if len(userId) == 0 { + return fmt.Errorf("invalid unsubscribe code: have no information about it"), nil + } + + if err = m.Subscribe(userId, None); err != nil { + return nil, fmt.Errorf("failed to unsubscribe: %s", err) + } + + return nil, nil +} + func (m *Mailer) SendVerificationCode(userId string, address string, lang string) error { message := mail.NewMsg() @@ -324,7 +355,7 @@ func (m *Mailer) GetSubscriptions(userId string) (subscriptionType SubscriptionT } } -func (m *Mailer) Subscribe(userId string, subscriptionType SubscriptionType, tags ...string) error { +func (m *Mailer) Subscribe(userIdHash []byte, subscriptionType SubscriptionType, tags ...string) error { tx, err := m.db.Begin() if err != nil { return fmt.Errorf("failed to initialize transaction with db: %s", err) @@ -341,11 +372,9 @@ func (m *Mailer) Subscribe(userId string, subscriptionType SubscriptionType, tag tagsOutput = strings.Join(tags, ",") } - hash := m.GetHash(userId) - if _, err = tx.Exec(`INSERT INTO subscription_user_to_tags_table(user_id, tags) VALUES(?, ?) ON CONFLICT(user_id) DO UPDATE SET - tags=excluded.tags;`, hash, tagsOutput); err != nil { + tags=excluded.tags;`, userIdHash, tagsOutput); err != nil { tx.Rollback() return fmt.Errorf("failed to configure user-to-tags table in db for the user: %s", err) } @@ -371,7 +400,10 @@ func (m *Mailer) NewPost(post *b2.BlogPage) error { } var userId []byte - usersToSend := make([]string, 0) + usersToSend := make([]struct { + userId []byte + email string + }, 0) var tagsString string i := -1 @@ -398,14 +430,20 @@ rowLoop: } if tagsString == "_all" { - usersToSend = append(usersToSend, email) + usersToSend = append(usersToSend, struct { + userId []byte + email string + }{userId, email}) continue } pageTags := strings.Split(tagsString, ",") for _, tag := range pageTags { if _, found := slices.BinarySearch(post.Metadata.Tags, tag); found { - usersToSend = append(usersToSend, email) + usersToSend = append(usersToSend, struct { + userId []byte + email string + }{userId, email}) continue rowLoop } } @@ -414,15 +452,23 @@ rowLoop: tx.Commit() rows.Close() - msgBody, err := m.tm.Render("new-post", fiber.Map{ - "L": m.l[post.Lang], - "Lang": post.Lang, - "Post": post, - "ClientHost": m.clientHost, - }) - messages := make([]*mail.Msg, 0, len(usersToSend)) for _, user := range usersToSend { + unsubscribeCodeBytes := make([]byte, 8) + rand.Read(unsubscribeCodeBytes) + unsubscribeCode := binary.LittleEndian.Uint64(unsubscribeCodeBytes) + + unsubscribeFooter := strings.Replace(m.l[post.Lang].Mail.UnsubscribeFooter, "{}", fmt.Sprintf(`<a style="color: #273de1 !important;" href="https://%s/%s/user/unsubscribe?code=%X">`, m.clientHost, post.Lang, unsubscribeCode), 1) + unsubscribeFooter = strings.Replace(unsubscribeFooter, "{/}", "</a>", 1) + + msgBody, err := m.tm.Render("new-post", fiber.Map{ + "L": m.l[post.Lang], + "Lang": post.Lang, + "Post": post, + "ClientHost": m.clientHost, + "UnsubscribeFooter": template.HTML(unsubscribeFooter), + }) + if err != nil { return fmt.Errorf("failed to render message body: %w", err) } @@ -435,7 +481,7 @@ rowLoop: if err := message.FromFormat(m.publicName, m.mailAddress); err != nil { return fmt.Errorf("failed to set formatted FROM address: %w", err) } - if err := message.To(user); err != nil { + if err := message.To(user.email); err != nil { return fmt.Errorf("failed to set TO address: %w", err) } @@ -445,6 +491,8 @@ rowLoop: message.Subject(m.l[post.Lang].Mail.NewPost.Subject) message.SetBodyString(mail.TypeTextHTML, string(msgBody)) + m.unsubscribeCodes.Set(unsubscribeCode, user.userId, 40) + messages = append(messages, message) } diff --git a/internal/router/api-v1-subs.go b/internal/router/api-v1-subs.go index 8995ebe..72f16e0 100644 --- a/internal/router/api-v1-subs.go +++ b/internal/router/api-v1-subs.go @@ -58,7 +58,7 @@ func Api_V1_Subs_Put(l map[string]*locale.LocaleConfig) func(c *fiber.Ctx) error } specificTags := c.FormValue("tags_picked") - if err = Mailer.Subscribe(id, subscriptionTypeEnum, specificTags); err != nil { + if err = Mailer.Subscribe(Mailer.GetHash(id), subscriptionTypeEnum, specificTags); err != nil { return api_v1_email_sendStatusHtml(c, "subs-message", l, "Failed", fiber.StatusUnprocessableEntity, lang, l[lang].UserProfile.FailedToSubscribe, map[string]string{}) } diff --git a/internal/router/lang-user-unsubscribe.go b/internal/router/lang-user-unsubscribe.go new file mode 100644 index 0000000..a6ca89f --- /dev/null +++ b/internal/router/lang-user-unsubscribe.go @@ -0,0 +1,69 @@ +package router + +import ( + "fmt" + "html/template" + "log/slog" + + "github.com/SayaAndy/saya-today-web/config" + "github.com/SayaAndy/saya-today-web/locale" + "github.com/gofiber/fiber/v2" +) + +func init() { + assert(0, tm.Add("unsubscribe-page", "views/pages/unsubscribe-page.html")) +} + +func Lang_User_Unsubscribe(l map[string]*locale.LocaleConfig, langs []config.AvailableLanguageConfig) func(c *fiber.Ctx) error { + return func(c *fiber.Ctx) error { + lang := c.Params("lang") + for _, availableLang := range langs { + if availableLang.Name == lang { + goto langIsAvailable + } + } + return c.Status(fiber.ErrNotFound.Code).SendString(fmt.Sprintf("server does not support '%s' language", lang)) + + langIsAvailable: + var statusEmoji, statusText, statusColor string + var status int + + unsubscribeCode := c.FormValue("code") + if unsubscribeCode == "" { + statusColor = "0, 0, 255" + statusEmoji = "(╭ರ_•́)" + statusText = l[lang].UnsubscribePage.UnsetCode + status = fiber.ErrBadRequest.Code + } else if clientError, serverError := Mailer.Unsubscribe(unsubscribeCode); clientError != nil { + statusColor = "255, 0, 0" + statusEmoji = "(͠≖~≖ ͡ )" + statusText = l[lang].UnsubscribePage.InvalidCode + status = fiber.ErrBadRequest.Code + } else if serverError != nil { + statusColor = "255, 128, 0" + statusEmoji = "( ˶°ㅁ°) !!" + statusText = l[lang].UnsubscribePage.OnServerError + status = fiber.ErrInternalServerError.Code + } else { + statusColor = "0, 255, 0," + statusEmoji = "♡⸜(˶˃ ᵕ ˂˶)⸝♡" + statusText = l[lang].UnsubscribePage.Success + status = fiber.StatusOK + } + + content, err := tm.Render("unsubscribe-page", fiber.Map{ + "Lang": lang, + "L": l[lang], + "StatusEmoji": statusEmoji, + "StatusText": statusText, + "StatusColor": template.HTML(statusColor), + }) + if err != nil { + slog.Warn("failed to generate page", slog.String("page", "/"+lang+"/user/unsubscribe"), slog.String("error", err.Error())) + c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8) + return c.Status(fiber.ErrInternalServerError.Code).SendString("failed to generate page") + } + + return c.Type("html").Status(status).Send(content) + } +} |