74 lines
1.7 KiB
Go
74 lines
1.7 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) {
|
|
contactsPath := filepath.Join(path, "users")
|
|
folders, err := os.ReadDir(contactsPath)
|
|
if err != nil {
|
|
log.Printf("Error reading contacts directory: %v", err)
|
|
return
|
|
}
|
|
|
|
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")
|
|
|
|
if !strings.EqualFold(msg.Sender, username) {
|
|
messages = append(messages, "\t\t\t\tYou ("+formattedTime+"):\n\t\t\t\t"+string(decoded))
|
|
} else {
|
|
messages = append(messages, "\t\t\t\t"+msg.Sender+" ("+formattedTime+"):\n\t\t\t\t"+string(decoded))
|
|
}
|
|
}
|
|
}
|