80 lines
2.4 KiB
Go
80 lines
2.4 KiB
Go
package database
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"github.com/google/uuid"
|
|
"relay-server/helpers"
|
|
)
|
|
|
|
func CreateGroup(db *sql.DB, groupName string, userID uuid.UUID) (uuid.UUID, error) {
|
|
createConversationQuery := `
|
|
INSERT INTO Conversations (conversation_type, name)
|
|
VALUES ('group', $1)
|
|
RETURNING conversation_id AS group_id;
|
|
`
|
|
|
|
insertGroupAdminQuery := `
|
|
INSERT INTO GroupAdmins (conversation_id, user_id, granted_by, is_owner)
|
|
VALUES ($1, $2, $3, true)
|
|
RETURNING granted_at;
|
|
`
|
|
|
|
// Create conversation
|
|
var groupID uuid.UUID
|
|
err := db.QueryRow(createConversationQuery, groupName).Scan(&groupID)
|
|
if err != nil {
|
|
return uuid.Nil, helpers.NewError(helpers.ErrInternal, "Failed to create group", fmt.Errorf("failed to create group: %w", err))
|
|
}
|
|
|
|
// Insert group admin (make user that created the group an admin)
|
|
var grantedAt string
|
|
err = db.QueryRow(insertGroupAdminQuery, groupID, userID, userID).Scan(&grantedAt)
|
|
if err != nil {
|
|
return uuid.Nil, helpers.NewError(helpers.ErrInternal, "Failed to create group", fmt.Errorf("failed to insert group admin: %w", err))
|
|
}
|
|
|
|
// Add self as group member
|
|
_, err = AddMemberToGroup(db, userID, groupID)
|
|
if err != nil {
|
|
return uuid.Nil, err
|
|
}
|
|
|
|
// Insert group contact
|
|
_, err = InsertContactByID(db, userID, groupID)
|
|
if err != nil {
|
|
return groupID, helpers.NewError(helpers.ErrInternal, "Failed to create group contact", fmt.Errorf("failed to insert group contact: %w", err))
|
|
}
|
|
|
|
return groupID, nil
|
|
}
|
|
|
|
func AddMemberToGroup(db *sql.DB, userID uuid.UUID, groupID uuid.UUID) (uuid.UUID, error) {
|
|
query := `
|
|
INSERT INTO Memberships (conversation_id, user_id)
|
|
VALUES ($1, $2)
|
|
ON CONFLICT DO NOTHING
|
|
RETURNING user_id;
|
|
`
|
|
var memberID uuid.UUID
|
|
err := db.QueryRow(query, groupID, userID).Scan(&memberID)
|
|
if err != nil {
|
|
return uuid.Nil, helpers.NewError(helpers.ErrInternal, "Failed to add member to group", fmt.Errorf("failed to add member to group: %w", err))
|
|
}
|
|
return memberID, nil
|
|
}
|
|
|
|
func IsAdmin(db *sql.DB, userID uuid.UUID, conversationID uuid.UUID) (bool, error) {
|
|
query := `
|
|
SELECT COUNT(1) FROM GroupAdmins
|
|
WHERE user_id = $1
|
|
AND conversation_id = $2;
|
|
`
|
|
var count int
|
|
err := db.QueryRow(query, userID, conversationID).Scan(&count)
|
|
if err != nil {
|
|
return false, helpers.NewError(helpers.ErrInternal, "Failed to check admin status", fmt.Errorf("failed to check admin status: %w", err))
|
|
}
|
|
return count > 0, nil
|
|
}
|