stuve-it-backend/messages/main.go

149 lines
4.9 KiB
Go

package messages
import (
"fmt"
"git.stuve.uni-ulm.de/stuve-it/stuve-it-backend/logger"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase"
"github.com/pocketbase/pocketbase/core"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/tools/mailer"
"github.com/pocketbase/pocketbase/tools/template"
"net/mail"
)
// sendEmailNotification sends an email notification to the user
func sendEmailNotification(app *pocketbase.PocketBase, registry *template.Registry, user *models.Record, message *models.Record) {
// check if user and message are set and user is not the sender
if user == nil || message == nil || user.GetId() == message.GetString("sender") {
return
}
// don't send email notification if user has muted email notifications and message is not an announcement
if user.GetBool("muteEmailNotifications") && !message.GetBool("isAnnouncement") {
return
}
// get user email
userEmail := user.GetString("email")
// check if user has a valid email
if len(userEmail) == 0 {
logger.LogErrorF("Error sending email notification to user with username '%s': no valid email", user.GetString("username"))
return
}
// get link to chat and message type (announcement or message)
var actionUrl string
var messageType string
if message.GetBool("isAnnouncement") {
actionUrl = app.Settings().Meta.AppUrl + "/chat/announcements"
messageType = "Ankündigung"
} else {
actionUrl = app.Settings().Meta.AppUrl + "/chat/" + message.GetString("eventList")
messageType = "Nachricht"
}
// render email template
html, err := registry.LoadFiles(
"html/emailNotification.html",
).Render(map[string]any{
"ACTION_URL": actionUrl,
"APP_URL": app.Settings().Meta.AppUrl,
"MESSAGE_TYPE": messageType,
})
if err != nil {
logger.LogErrorF("Error rendering email notification to user with username '%s': %v", user.GetString("username"), err)
return
}
// send email
email := &mailer.Message{
From: mail.Address{
Address: app.Settings().Meta.SenderAddress,
Name: app.Settings().Meta.SenderName,
},
To: []mail.Address{{Address: userEmail}},
Subject: "[StuVe IT] Neue " + messageType,
HTML: html,
}
if err := app.NewMailClient().Send(email); err != nil {
logger.LogErrorF("Error sending email notification to user with username '%s': %v", user.GetString("username"), err)
}
}
// InitMessages initializes the messages email notifier
//
// the function sends an email notification to all recipients of a message after the message has been created
func InitMessages(app *pocketbase.PocketBase, e *core.ServeEvent) error {
logger.LogInfoF("Adding messages email notifier")
registry := template.NewRegistry()
app.OnModelAfterCreate("messages").Add(func(e *core.ModelEvent) error {
// get created message record
createdMessageRecord, err := app.Dao().FindRecordById("messages", e.Model.GetId())
if err != nil {
return err
}
// expand the createdMessageRecord to get recipient user and send email notification if recipient is set
if errs := app.Dao().ExpandRecord(createdMessageRecord, []string{"recipients", "eventList"}, nil); len(errs) > 0 {
// return new error with all errors
return fmt.Errorf("error expanding created message record: %v", errs)
}
recipients := createdMessageRecord.ExpandedAll("recipients")
for _, recipient := range recipients {
sendEmailNotification(app, registry, recipient, createdMessageRecord)
}
// get eventList entries to notify and event admins
eventList := createdMessageRecord.ExpandedOne("eventList")
if eventList != nil {
// get all eventListSlotEntries for the eventList
listEntryRecords, err := app.Dao().FindRecordsByFilter(
"eventListSlotEntries",
"eventListsSlot.eventList.id={:listId}",
"",
-1,
0,
dbx.Params{"listId": eventList.GetId()},
)
if err != nil {
logger.LogErrorF("Error getting eventListSlotEntries for EmailNotifier: %v", err)
}
// send messages to all eventListSlotEntries
for _, record := range listEntryRecords {
// expand the createdMessageRecord to get the user
if errs := app.Dao().ExpandRecord(record, []string{"user"}, nil); len(errs) > 0 {
logger.LogErrorF("Error expanding user for EmailNotifier: %v", errs)
}
sendEmailNotification(app, registry, record.ExpandedOne("user"), createdMessageRecord)
}
// get event and eventAdmins
if errs := app.Dao().ExpandRecord(eventList, []string{"event"}, nil); len(errs) > 0 {
logger.LogErrorF("Error expanding event for EmailNotifier: %v", errs)
}
event := eventList.ExpandedOne("event")
if errs := app.Dao().ExpandRecord(event, []string{"eventAdmins"}, nil); len(errs) > 0 {
logger.LogErrorF("Error expanding eventAdmins for EmailNotifier: %v", errs)
}
eventAdmins := event.ExpandedAll("eventAdmins")
// send messages to all eventAdmins
for _, record := range eventAdmins {
sendEmailNotification(app, registry, record, createdMessageRecord)
}
}
return nil
})
return nil
}