WhspBrd/internal/tui/messages.go
2025-08-21 13:05:55 +02:00

78 lines
2.2 KiB
Go

package tui
import (
"encoding/base64"
"encoding/json"
"log"
"os"
"path/filepath"
"strings"
"time"
)
type ChatMessage struct {
ID string `json:"id"`
Sender string `json:"sender"`
Receiver string `json:"receiver"`
Content string `json:"content"`
Timestamp string `json:"timestamp"`
}
type ChatData struct {
Messages []ChatMessage `json:"messages"`
}
func LoadContacts(path string) {
users = nil
contactsPath := filepath.Join(path, "users")
folders, err := os.ReadDir(contactsPath)
if err != nil {
log.Printf("Error reading contacts directory: %v", err)
return
}
// TODO: Instead of just using list create some more complex structure so i can load details about the user in it
for _, folder := range folders {
if folder.IsDir() {
users = append(users, folder.Name())
}
}
}
func LoadMessages(username string) {
chatFile := filepath.Join("configs", "servers", "default", "users", strings.ToLower(username), "messages.json")
data, err := os.ReadFile(chatFile)
if err != nil {
log.Printf("Error reading chat file: %v", err)
return
}
var chatData ChatData
if err := json.Unmarshal(data, &chatData); err != nil {
log.Printf("Error parsing JSON: %v", err)
return
}
for _, msg := range chatData.Messages {
decoded, err := base64.StdEncoding.DecodeString(msg.Content)
if err != nil {
log.Printf("Error decoding message: %v", err)
continue
}
if strings.HasSuffix(string(decoded), "\n") {
decoded = []byte(strings.TrimSuffix(string(decoded), "\n"))
}
t, _ := time.Parse(time.RFC3339, msg.Timestamp)
formattedTime := t.Format("2006-01-02 15:04")
// TODO: Move this part to the rendering chat file (./chat.go) and here i should only load all messages and related data to that
// TODO: And in the chat file i should get all data in nice structure and then just select what i need from that
if !strings.EqualFold(msg.Sender, username) {
messages = append(messages, "\t\t\t\t\t"+Colors.Text(Colors.Base02)+"You ("+formattedTime+"):"+Colors.Reset+"\n\t\t\t\t\t"+string(decoded))
} else {
messages = append(messages, "\t\t\t\t\t"+Colors.Text(Colors.Base05)+msg.Sender+" ("+formattedTime+"):\n"+Colors.Reset+"\t\t\t\t\t"+string(decoded))
}
}
}