From df7a0ae1c0fc177cba2eae8cc73fe21d2afdd229 Mon Sep 17 00:00:00 2001 From: SayaAndy Date: Fri, 24 Oct 2025 20:40:00 +0700 Subject: feat: allow to unsubscribe from an email --- internal/mailer/mailer.go | 80 +++++++++++++++++++++++++------- internal/router/api-v1-subs.go | 2 +- internal/router/lang-user-unsubscribe.go | 69 +++++++++++++++++++++++++++ locale/localization.en.yaml | 8 +++- locale/localization.go | 23 ++++++--- locale/localization.ru.yaml | 8 +++- main.go | 1 + views/messages/new-post.html | 4 +- views/pages/unsubscribe-page.html | 30 ++++++++++++ 9 files changed, 197 insertions(+), 28 deletions(-) create mode 100644 internal/router/lang-user-unsubscribe.go create mode 100644 views/pages/unsubscribe-page.html 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(``, m.clientHost, post.Lang, unsubscribeCode), 1) + unsubscribeFooter = strings.Replace(unsubscribeFooter, "{/}", "", 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) + } +} diff --git a/locale/localization.en.yaml b/locale/localization.en.yaml index 8981c49..c7f2df8 100644 --- a/locale/localization.en.yaml +++ b/locale/localization.en.yaml @@ -22,11 +22,17 @@ HomePage: Hymn2: "We've been expecting you!" Hymn3: 'You bring such joy in Sayasite!' Hymn4: 'No matter where you roam, know our love is true!~' +UnsubscribePage: + Header: 'Cancelling the Subscription' + UnsetCode: 'Your cancel code is not set. You just having a walk around the site?' + InvalidCode: "Your cancel code could not be verified. Maybe, the code expired after a day. Or maybe, you've already unsubscribed." + OnServerError: "We couldn't unsubscribe you, the problem is on our side! We will solve this problem as soon as possible." + Success: 'Cancelled your subscription successfully! We do hope we will engage you again someday.' Metadata: Published: 'Published' Action: 'Took place on' Mail: - UnsubscribeFooter: 'If this letter got you in a bad mood, you can unsubscribe from my blog by this link.' + UnsubscribeFooter: 'If this letter got you in a bad mood, you can unsubscribe from my blog by {}this link{/}.' VerifyEmail: Subject: 'Verification Link for SAYA.TODAY is waiting for you!' Welcome: 'Greetings!' diff --git a/locale/localization.go b/locale/localization.go index b3a1613..c6467c4 100644 --- a/locale/localization.go +++ b/locale/localization.go @@ -8,13 +8,14 @@ import ( ) type LocaleConfig struct { - TagsLabel string `yaml:"TagsLabel" json:"TagsLabel"` - BlogSearch BlogSearchConfig `yaml:"BlogSearch" json:"BlogSearch"` - GlobalMap GlobalMapConfig `yaml:"GlobalMap" json:"GlobalMap"` - HomePage HomePageConfig `yaml:"HomePage" json:"HomePage"` - Metadata MetadataConfig `yaml:"Metadata" json:"Metadata"` - Mail MailConfig `yaml:"Mail" json:"Mail"` - UserProfile UserProfileConfig `yaml:"UserProfile" json:"UserProfile"` + TagsLabel string `yaml:"TagsLabel" json:"TagsLabel"` + BlogSearch BlogSearchConfig `yaml:"BlogSearch" json:"BlogSearch"` + GlobalMap GlobalMapConfig `yaml:"GlobalMap" json:"GlobalMap"` + HomePage HomePageConfig `yaml:"HomePage" json:"HomePage"` + UnsubscribePage UnsubscribePageConfig `yaml:"UnsubscribePage" json:"UnsubscribePage"` + Metadata MetadataConfig `yaml:"Metadata" json:"Metadata"` + Mail MailConfig `yaml:"Mail" json:"Mail"` + UserProfile UserProfileConfig `yaml:"UserProfile" json:"UserProfile"` } type BlogSearchConfig struct { @@ -46,6 +47,14 @@ type HomePageConfig struct { Hymn4 string `yaml:"Hymn4" json:"Hymn4"` } +type UnsubscribePageConfig struct { + Header string `yaml:"Header" json:"Header"` + UnsetCode string `yaml:"UnsetCode" json:"UnsetCode"` + InvalidCode string `yaml:"InvalidCode" json:"InvalidCode"` + OnServerError string `yaml:"OnServerError" json:"OnServerError"` + Success string `yaml:"Success" json:"Success"` +} + type MetadataConfig struct { Action string `yaml:"Action" json:"Action"` Published string `yaml:"Published" json:"Published"` diff --git a/locale/localization.ru.yaml b/locale/localization.ru.yaml index c09ad16..5df82da 100644 --- a/locale/localization.ru.yaml +++ b/locale/localization.ru.yaml @@ -22,11 +22,17 @@ HomePage: Hymn2: 'Мы Вас столько ждали!' Hymn3: 'Столько радости от Вас на Саясайте!' Hymn4: 'Где бы Вы не были, знайте, -- наша любовь крепка!' +UnsubscribePage: + Header: 'Отписка' + UnsetCode: 'Код для отписки не проставлен. Вы случайно не заблудились?' + InvalidCode: 'Код для отписки не подтверждён. Может, истекло время в сутки для кода. А может, вы уже успели отписаться.' + OnServerError: 'Мы не смогли вас отписать, проблема на нашей стороне! В скором времени займёмся проблемой.' + Success: 'Вы отписались от рассылки! Надеюсь, мы ещё сможем вас заинтересовать.' Metadata: Published: 'Опубликовано' Action: 'Время действия' Mail: - UnsubscribeFooter: 'Если данное письмо пришло вам случайно, либо вы хотите отписаться, можете перейти по этой ссылке.' + UnsubscribeFooter: 'Если данное письмо пришло вам случайно, либо вы хотите отписаться, можете перейти по {}этой ссылке{/}.' VerifyEmail: Subject: 'Ссылка для верификации для подтверждения вашей почты SAYA.TODAY' Welcome: 'Приветствую!' diff --git a/main.go b/main.go index 8f9f619..9d80cee 100644 --- a/main.go +++ b/main.go @@ -170,6 +170,7 @@ func main() { app.Get("/:lang", router.Api_V1_GeneralPage(localization, availableLanguages)) app.Get("/:lang/map", router.Lang_Map(localization, availableLanguages, b2Client)) app.Get("/:lang/user", router.Api_V1_GeneralPage(localization, availableLanguages)) + app.Get("/:lang/user/unsubscribe", router.Lang_User_Unsubscribe(localization, availableLanguages)) app.Get("/:lang/blog", router.Api_V1_GeneralPage(localization, availableLanguages)) app.Get("/:lang/blog/:title", router.Api_V1_GeneralPage(localization, availableLanguages)) diff --git a/views/messages/new-post.html b/views/messages/new-post.html index 7b3082a..f1338f7 100644 --- a/views/messages/new-post.html +++ b/views/messages/new-post.html @@ -3,7 +3,7 @@ - + @@ -15,5 +15,5 @@ {{ end }} {{ define "footer" }} -

{{ .L.Mail.UnsubscribeFooter }}

+

{{ .UnsubscribeFooter }}

{{ end }} diff --git a/views/pages/unsubscribe-page.html b/views/pages/unsubscribe-page.html new file mode 100644 index 0000000..3876818 --- /dev/null +++ b/views/pages/unsubscribe-page.html @@ -0,0 +1,30 @@ + + + + + + {{ .L.UnsubscribePage.Header }} // SAYA TODAY + + + + + +
+ +
+

{{ .StatusEmoji }}

+
+ +
+

{{ .StatusText }}

+
+ +
+ + + + -- cgit v1.3.1+13
{{ .Post.Metadata.Title }}{{ .Post.Metadata.Title }}
{{ .Post.Metadata.ShortDescription }}