349 lines
12 KiB
Go
349 lines
12 KiB
Go
package database
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/google/uuid"
|
|
"log"
|
|
"relay-server/helpers"
|
|
"relay-server/model"
|
|
)
|
|
|
|
func DeleteContact(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (string, error) {
|
|
// Check conversation type
|
|
var conversationType string
|
|
err := db.QueryRow(
|
|
"SELECT conversation_type FROM Conversations WHERE conversation_id = $1",
|
|
conversationID,
|
|
).Scan(&conversationType)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return "no conversation found for this id", nil
|
|
}
|
|
return "", fmt.Errorf("error checking conversation type: %w", err)
|
|
}
|
|
|
|
if conversationType == "group" {
|
|
// Delete from Contacts
|
|
res, err := db.Exec(
|
|
"DELETE FROM Contacts WHERE conversation_id = $1 AND user_id = $2",
|
|
conversationID,
|
|
userID,
|
|
)
|
|
if err != nil {
|
|
return "", fmt.Errorf("error deleting contact: %w", err)
|
|
}
|
|
|
|
rowsAffected, err := res.RowsAffected()
|
|
if err != nil {
|
|
return "", fmt.Errorf("error checking contact deletion: %w", err)
|
|
}
|
|
if rowsAffected == 0 {
|
|
return fmt.Sprintf("no matching contact found with conversation id: %s, user id: %s", conversationID, userID), nil
|
|
}
|
|
|
|
// Delete from Memberships
|
|
res, err = db.Exec(
|
|
"DELETE FROM Memberships WHERE conversation_id = $1 AND user_id = $2",
|
|
conversationID,
|
|
userID,
|
|
)
|
|
if err != nil {
|
|
return "", fmt.Errorf("error deleting membership: %w", err)
|
|
}
|
|
|
|
rowsAffected, err = res.RowsAffected()
|
|
if err != nil {
|
|
return "", fmt.Errorf("error checking membership deletion: %w", err)
|
|
}
|
|
if rowsAffected == 0 {
|
|
return "", fmt.Errorf("no matching membership found with conversation id: %s, user id: %s", conversationID, userID)
|
|
}
|
|
} else {
|
|
// Handle direct conversation
|
|
res, err := db.Exec(
|
|
"DELETE FROM Contacts WHERE user_id = $1 AND conversation_id = $2",
|
|
userID,
|
|
conversationID,
|
|
)
|
|
if err != nil {
|
|
return "", fmt.Errorf("error deleting contact: %w", err)
|
|
}
|
|
|
|
rowsAffected, err := res.RowsAffected()
|
|
if err != nil {
|
|
return "", fmt.Errorf("error checking contact deletion: %w", err)
|
|
}
|
|
if rowsAffected == 0 {
|
|
return fmt.Sprintf("no matching contact found with user id: %s, conversation id: %s", userID, conversationID), nil
|
|
}
|
|
|
|
fmt.Printf("Successfully deleted contact for user %s in conversation %s", userID, conversationID)
|
|
}
|
|
|
|
return "", nil
|
|
}
|
|
|
|
func InsertContact(db *sql.DB, userID uuid.UUID, contactID uuid.UUID, contactUsername string) (*model.Contact, error) {
|
|
isSelfContact := userID == contactID
|
|
var contact model.Contact
|
|
var conversationID uuid.UUID
|
|
|
|
if isSelfContact {
|
|
findSelfConversationQuery := `
|
|
SELECT c.conversation_id
|
|
FROM Conversations c
|
|
JOIN Memberships m ON c.conversation_id = m.conversation_id
|
|
WHERE c.conversation_type = 'direct'
|
|
AND m.user_id = $1
|
|
AND (
|
|
SELECT COUNT(*)
|
|
FROM Memberships
|
|
WHERE conversation_id = c.conversation_id
|
|
) = 1
|
|
LIMIT 1;
|
|
`
|
|
|
|
err := db.QueryRow(findSelfConversationQuery, userID).Scan(&conversationID)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
conversationID = uuid.Nil
|
|
}
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error finding existing conversation: %w", err))
|
|
}
|
|
|
|
// if conversation for themselves don't exist
|
|
if conversationID == uuid.Nil {
|
|
createConversationQuery := `
|
|
INSERT INTO Conversations (conversation_type)
|
|
VALUES ('direct')
|
|
RETURNING conversation_id;
|
|
`
|
|
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
|
|
if err != nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "Internal server error", fmt.Errorf("error creating conversation for self-contact: %w", err))
|
|
}
|
|
|
|
createMembershipQuery := `
|
|
INSERT INTO Memberships (conversation_id, user_id)
|
|
VALUES ($1, $2)
|
|
ON CONFLICT (conversation_id, user_id) DO NOTHING;
|
|
`
|
|
_, err = db.Exec(createMembershipQuery, conversationID, userID)
|
|
|
|
} else {
|
|
// For regular contacts, check if a conversation already exists between the two users
|
|
findConversationQuery := `
|
|
SELECT c.conversation_id
|
|
FROM Conversations c
|
|
JOIN Memberships m1 ON c.conversation_id = m1.conversation_id
|
|
JOIN Memberships m2 ON c.conversation_id = m2.conversation_id
|
|
WHERE c.conversation_type = 'direct'
|
|
AND (
|
|
(m1.user_id = $1 AND m2.user_id = $2)
|
|
OR
|
|
(m1.user_id = $2 AND m2.user_id = $1)
|
|
)
|
|
LIMIT 1;
|
|
`
|
|
err := db.QueryRow(findConversationQuery, userID, contactID).Scan(&conversationID)
|
|
if err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
conversationID = uuid.Nil
|
|
}
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error finding existing conversation: %w", err))
|
|
}
|
|
if conversationID != uuid.Nil {
|
|
// Create a new conversation between user and contact
|
|
createConversationQuery := `
|
|
INSERT INTO Conversations (conversation_type)
|
|
VALUES ('direct')
|
|
RETURNING conversation_id;
|
|
`
|
|
err := db.QueryRow(createConversationQuery).Scan(&conversationID)
|
|
if err != nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating conversation: %w", err))
|
|
}
|
|
|
|
createMembershipQuery := `
|
|
INSERT INTO Memberships (conversation_id, user_id)
|
|
VALUES ($1, $2), ($1, $3)
|
|
ON CONFLICT (conversation_id, user_id) DO NOTHING;
|
|
`
|
|
|
|
res, err := db.Exec(createMembershipQuery, conversationID, userID, contactID)
|
|
if err != nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating membership: %w", err))
|
|
}
|
|
rowsAffected, err := res.RowsAffected()
|
|
if err != nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error checking membership creation: %w", err))
|
|
}
|
|
if rowsAffected == 0 {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error creating membership %w", err))
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
insertedContact, err := InsertContactByID(db, contactID, conversationID)
|
|
if err != nil || insertedContact.UserID == uuid.Nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err)
|
|
}
|
|
|
|
latestMessage, err := GetLatestMessage(db, conversationID)
|
|
if err != nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", err)
|
|
}
|
|
|
|
contact = model.Contact{
|
|
ID: insertedContact.ID,
|
|
ConversationID: insertedContact.ConversationID,
|
|
UserID: insertedContact.UserID,
|
|
Username: contactUsername,
|
|
Type: "direct",
|
|
LastMessageID: latestMessage.LastMessageID,
|
|
LastMessage: latestMessage.LastMessage,
|
|
LastMessageTime: latestMessage.LastMessageTime,
|
|
LastMessageSender: latestMessage.LastMessageSender,
|
|
}
|
|
return &contact, nil
|
|
}
|
|
|
|
func InsertContactByID(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (*model.Contact, error) {
|
|
// First check if contact already exists
|
|
checkQuery := `
|
|
SELECT contact_id, conversation_id, user_id
|
|
FROM Contacts
|
|
WHERE user_id = $1 AND conversation_id = $2
|
|
`
|
|
var contact model.Contact
|
|
err := db.QueryRow(checkQuery, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
|
|
if err == nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("contact already exists"))
|
|
} else if !errors.Is(err, sql.ErrNoRows) {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error checking contact existence: %w", err))
|
|
}
|
|
|
|
insertQuery := `
|
|
INSERT INTO Contacts (user_id, conversation_id)
|
|
VALUES($1, $2)
|
|
RETURNING contact_id, conversation_id, user_id
|
|
`
|
|
|
|
err = db.QueryRow(insertQuery, userID, conversationID).Scan(&contact.ID, &contact.ConversationID, &contact.UserID)
|
|
if err != nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error inserting contact: %w", err))
|
|
}
|
|
fmt.Printf("Successfully inserted contact by id: %v", conversationID)
|
|
|
|
return &contact, nil
|
|
}
|
|
|
|
func GetLatestMessage(db *sql.DB, conversationId uuid.UUID) (*model.Contact, error) {
|
|
var latestMessage model.Contact
|
|
|
|
query := `
|
|
SELECT DISTINCT ON (m.conversation_id)
|
|
m.message_id AS last_message_id,
|
|
m.content AS last_message,
|
|
m.sent_at AS last_message_time,
|
|
a.username AS last_message_sender
|
|
FROM Messages m
|
|
JOIN Accounts a ON m.user_id = a.user_id
|
|
WHERE m.conversation_id = $1
|
|
ORDER BY m.conversation_id, m.sent_at DESC
|
|
LIMIT 1;
|
|
`
|
|
|
|
err := db.QueryRow(query, conversationId).Scan(&latestMessage.LastMessageID, &latestMessage.LastMessage, &latestMessage.LastMessageTime, &latestMessage.LastMessageSender)
|
|
if err != nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting latest message: %w", err))
|
|
}
|
|
return &latestMessage, nil
|
|
}
|
|
|
|
func GetContacts(db *sql.DB, userID uuid.UUID) ([]*model.Contact, error) {
|
|
contactsQuery := `
|
|
WITH DirectContacts AS (
|
|
SELECT DISTINCT ON (c.conversation_id)
|
|
c.contact_id AS id,
|
|
a.user_id AS user_id,
|
|
a.username AS username,
|
|
conv.last_active,
|
|
c.conversation_id,
|
|
conv.conversation_type AS type,
|
|
requesting_member.last_read_message_id
|
|
FROM Contacts c
|
|
JOIN Conversations conv ON c.conversation_id = conv.conversation_id
|
|
JOIN Memberships requesting_member
|
|
ON requesting_member.conversation_id = conv.conversation_id
|
|
AND requesting_member.user_id = $1
|
|
JOIN Memberships other_member
|
|
ON other_member.conversation_id = conv.conversation_id
|
|
JOIN Accounts a ON a.user_id = other_member.user_id
|
|
WHERE c.user_id = $1
|
|
AND conv.conversation_type = 'direct'
|
|
AND (
|
|
a.user_id != $1
|
|
OR (SELECT COUNT(*) FROM Memberships WHERE conversation_id = c.conversation_id) = 1
|
|
)
|
|
),
|
|
GroupContacts AS (
|
|
SELECT DISTINCT ON (c.conversation_id)
|
|
c.contact_id AS id,
|
|
NULL::uuid AS user_id,
|
|
conv.name AS username,
|
|
conv.last_active,
|
|
c.conversation_id,
|
|
conv.conversation_type AS type,
|
|
m.last_read_message_id
|
|
FROM Contacts c
|
|
JOIN Conversations conv ON c.conversation_id = conv.conversation_id
|
|
JOIN Memberships m
|
|
ON m.conversation_id = conv.conversation_id
|
|
AND m.user_id = $1
|
|
WHERE c.user_id = $1
|
|
AND conv.conversation_type = 'group'
|
|
)
|
|
SELECT * FROM DirectContacts
|
|
UNION ALL
|
|
SELECT * FROM GroupContacts
|
|
ORDER BY last_active DESC NULLS LAST;
|
|
`
|
|
|
|
rows, err := db.Query(contactsQuery, userID)
|
|
if err != nil {
|
|
log.Println("Failed to get contacts:", err)
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting contacts: %w", err))
|
|
}
|
|
|
|
var contacts []*model.Contact
|
|
for rows.Next() {
|
|
contact := &model.Contact{}
|
|
err := rows.Scan(&contact.ID, &contact.UserID, &contact.Username, &contact.ConversationID, &contact.Type)
|
|
if err != nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error scanning contact: %w", err))
|
|
}
|
|
|
|
latestMessage, err := GetLatestMessage(db, contact.ConversationID)
|
|
if err != nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error getting latest message: %w", err))
|
|
}
|
|
|
|
contact.LastMessageID = latestMessage.LastMessageID
|
|
contact.LastMessage = latestMessage.LastMessage
|
|
contact.LastMessageTime = latestMessage.LastMessageTime
|
|
contact.LastMessageSender = latestMessage.LastMessageSender
|
|
|
|
contacts = append(contacts, contact)
|
|
}
|
|
|
|
if err = rows.Err(); err != nil {
|
|
return nil, helpers.NewError(helpers.ErrInternal, "internal server error", fmt.Errorf("error iterating over contacts: %w", err))
|
|
}
|
|
|
|
return contacts, nil
|
|
}
|