summaryrefslogtreecommitdiffci
path: root/internal
diff refs
from: back
to: back
| flip
diff options
context:
space:
mode:
Diffstat (limited to 'internal')
-rw-r--r--internal/mailer/mailer.go80
-rw-r--r--internal/router/api-v1-subs.go2
-rw-r--r--internal/router/lang-user-unsubscribe.go69
3 files changed, 17 insertions, 134 deletions
diff --git a/internal/mailer/mailer.go b/internal/mailer/mailer.go
index c146548..f51186e 100644
--- a/internal/mailer/mailer.go
+++ b/internal/mailer/mailer.go
@@ -6,7 +6,6 @@ import (
"encoding/base64"
"encoding/binary"
"fmt"
- "html/template"
"log/slog"
"slices"
"strconv"
@@ -25,7 +24,6 @@ import (
type Mailer struct {
verificationCodes *ristretto.Cache[uint64, string]
- unsubscribeCodes *ristretto.Cache[uint64, []byte]
db *sql.DB
tm *templatemanager.TemplateManager
mailClient *mail.Client
@@ -60,17 +58,7 @@ func NewMailer(db *sql.DB, clientHost string, mailHost string, publicName string
NumCounters: 10000,
MaxCost: 1 << 20, // 1 MB
BufferItems: 64,
- 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
+ TtlTickerDurationInSec: 3600,
})
if err != nil {
return nil, fmt.Errorf("fail to initialize cache for verification codes: %w", err)
@@ -97,7 +85,6 @@ func NewMailer(db *sql.DB, clientHost string, mailHost string, publicName string
return &Mailer{
verificationCodes: verificationCodes,
- unsubscribeCodes: unsubscribeCodes,
db: db,
clientHost: clientHost,
tm: tm,
@@ -188,24 +175,6 @@ 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()
@@ -355,7 +324,7 @@ func (m *Mailer) GetSubscriptions(userId string) (subscriptionType SubscriptionT
}
}
-func (m *Mailer) Subscribe(userIdHash []byte, subscriptionType SubscriptionType, tags ...string) error {
+func (m *Mailer) Subscribe(userId string, subscriptionType SubscriptionType, tags ...string) error {
tx, err := m.db.Begin()
if err != nil {
return fmt.Errorf("failed to initialize transaction with db: %s", err)
@@ -372,9 +341,11 @@ func (m *Mailer) Subscribe(userIdHash []byte, subscriptionType SubscriptionType,
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;`, userIdHash, tagsOutput); err != nil {
+ tags=excluded.tags;`, hash, tagsOutput); err != nil {
tx.Rollback()
return fmt.Errorf("failed to configure user-to-tags table in db for the user: %s", err)
}
@@ -400,10 +371,7 @@ func (m *Mailer) NewPost(post *b2.BlogPage) error {
}
var userId []byte
- usersToSend := make([]struct {
- userId []byte
- email string
- }, 0)
+ usersToSend := make([]string, 0)
var tagsString string
i := -1
@@ -430,20 +398,14 @@ rowLoop:
}
if tagsString == "_all" {
- usersToSend = append(usersToSend, struct {
- userId []byte
- email string
- }{userId, email})
+ usersToSend = append(usersToSend, email)
continue
}
pageTags := strings.Split(tagsString, ",")
for _, tag := range pageTags {
if _, found := slices.BinarySearch(post.Metadata.Tags, tag); found {
- usersToSend = append(usersToSend, struct {
- userId []byte
- email string
- }{userId, email})
+ usersToSend = append(usersToSend, email)
continue rowLoop
}
}
@@ -452,23 +414,15 @@ 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)
}
@@ -481,7 +435,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.email); err != nil {
+ if err := message.To(user); err != nil {
return fmt.Errorf("failed to set TO address: %w", err)
}
@@ -491,8 +445,6 @@ 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 72f16e0..8995ebe 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(Mailer.GetHash(id), subscriptionTypeEnum, specificTags); err != nil {
+ if err = Mailer.Subscribe(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
deleted file mode 100644
index a6ca89f..0000000
--- a/internal/router/lang-user-unsubscribe.go
+++ /dev/null
@@ -1,69 +0,0 @@
-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)
- }
-}