- package Messages
-
- import (
- "encoding/base64"
- "encoding/json"
- "fmt"
- "net/http"
- "time"
-
- "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database"
- "git.tovijaeschke.xyz/tovi/Envelope/Backend/Service"
- "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util"
- )
-
- // TODO: Encrypt sender and conversationID metadata + add more
- type payload struct {
- Messages []rawMessageData `json:"messages"`
- Sender string `json:"sender"`
- ConversationID string `json:"conversation_id"`
- Tokens []string `json:"tokens"`
- }
-
- type rawMessageData struct {
- MessageData Database.MessageData `json:"message_data"`
- Messages Database.MessageList `json:"message"`
- }
-
- // CreateMessage sends a message
- func CreateMessage(w http.ResponseWriter, r *http.Request) {
- var (
- messagesData payload
- messageData rawMessageData
- message Database.Message
- t time.Time
- decodedFile []byte
- fileName string
- i int
- err error
- )
-
- err = json.NewDecoder(r.Body).Decode(&messagesData)
- if err != nil {
- http.Error(w, "Error", http.StatusInternalServerError)
- return
- }
-
- for _, messageData = range messagesData.Messages {
- if messageData.MessageData.Data == "" {
- decodedFile, err = base64.StdEncoding.DecodeString(messageData.MessageData.Attachment.Data)
- fileName, err = Util.WriteFile(decodedFile)
- messageData.MessageData.Attachment.FilePath = fileName
- }
-
- for i, message = range messageData.Messages {
- t, err = time.Parse(time.RFC3339, message.ExpiryRaw)
- if err == nil {
- err = messageData.Messages[i].Expiry.Scan(t)
- if err != nil {
- http.Error(w, "Error", http.StatusInternalServerError)
- return
- }
- }
- }
-
- err = (&messageData.MessageData).CreateMessageData()
- if err != nil {
- http.Error(w, "Error", http.StatusInternalServerError)
- return
- }
-
- err = (&messageData.Messages).CreateMessages()
- if err != nil {
- http.Error(w, "Error", http.StatusInternalServerError)
- return
- }
- }
-
- _ = Service.SendNotification(
- messagesData.Tokens,
- fmt.Sprintf(
- "%s sent a message",
- messagesData.Sender,
- ),
- map[string]string{
- "conversation_id": messagesData.ConversationID,
- },
- )
-
- w.WriteHeader(http.StatusNoContent)
- }
|