48d3c6f857
- add files_metadata and files_metadata_connections tables with CRUD helpers - add FileMetadata type and Sha256Hash typedef; replace Media struct - add minio upload, presigned download URL, and key generation - fix bucket existence check to use FileStorageBucketName instead of hardcoded "main" - fix files_metadata_connections table name and trailing comma in DDL - fix column name original -> name in files_metadata schema - add canonical MIME-to-extension map with .unk fallback - add FileDownloadLinkTtl constant (24h)
300 lines
8.7 KiB
Go
300 lines
8.7 KiB
Go
package postgresql
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"go-socket/packages/cache"
|
|
"go-socket/packages/convertions"
|
|
"go-socket/packages/types"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
var dbConn *pgxpool.Pool
|
|
|
|
func PgInit(ctx context.Context) {
|
|
var err error
|
|
dbConn, err = pgxpool.New(ctx, "postgres://master:secret@localhost:5432") // TODO change to env in production
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
_, err = dbConn.Exec(ctx, `CREATE EXTENSION IF NOT EXISTS "pgcrypto";`)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
_, err = dbConn.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
name TEXT UNIQUE NOT NULL,
|
|
pass_hash TEXT NOT NULL,
|
|
pronouns TEXT DEFAULT NULL,
|
|
rgba BIGINT NOT NULL DEFAULT 0 CHECK (rgba BETWEEN 0 AND 4294967295),
|
|
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
|
)
|
|
`)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
_, err = dbConn.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS user_connections (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
requestor_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
recipient_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
state SMALLINT NOT NULL DEFAULT 0,
|
|
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
|
)
|
|
`)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
_, err = dbConn.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS direct_messages (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
receiver_id UUID NOT NULL REFERENCES user_connections(id) ON DELETE CASCADE,
|
|
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
content TEXT NOT NULL
|
|
)
|
|
`)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
_, err = dbConn.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS files_metadata (
|
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
uploader_id UUID NOT NULL REFERENCES users(id),
|
|
name TEXT,
|
|
hash TEXT NOT NULL,
|
|
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
|
)
|
|
`)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
_, err = dbConn.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS files_metadata_connections (
|
|
file_metadata_id UUID NOT NULL REFERENCES files_metadata(id) ON DELETE CASCADE,
|
|
connection_id UUID NOT NULL REFERENCES user_connections(id) ON DELETE CASCADE
|
|
)
|
|
`)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func PgUserSave(ctx context.Context, user *types.User) error {
|
|
err := dbConn.QueryRow(ctx, `
|
|
INSERT INTO users (name, pass_hash, pronouns, rgba, created_at)
|
|
VALUES ($1, $2, $3, $4, $5)
|
|
RETURNING id
|
|
`, user.Name, user.PasswordHash, user.Pronouns, convertions.RgbaToUint32(user.Color), user.CreatedAt).
|
|
Scan(&user.Id)
|
|
return err
|
|
}
|
|
|
|
func PgUserDelete(ctx context.Context, id uuid.UUID) error {
|
|
_, err := dbConn.Exec(ctx, `
|
|
DELETE FROM users WHERE id = $1
|
|
`, id)
|
|
return err
|
|
}
|
|
|
|
func PgUserGetStandardInfoByName(ctx context.Context, user *types.User) error {
|
|
var rgba int64
|
|
err := dbConn.QueryRow(ctx, `
|
|
SELECT id, name, pass_hash, COALESCE(pronouns, ''), rgba, created_at FROM users WHERE name = $1
|
|
`, user.Name).Scan(&user.Id, &user.Name, &user.PasswordHash, &user.Pronouns, &rgba, &user.CreatedAt)
|
|
if err == nil {
|
|
user.Color = convertions.Uint32ToRgba(uint32(rgba))
|
|
}
|
|
return err
|
|
}
|
|
|
|
func PgUserGetById(ctx context.Context, user *types.User) error {
|
|
var rgba int64
|
|
err := dbConn.QueryRow(ctx, `
|
|
SELECT name, pass_hash, COALESCE(pronouns, ''), rgba, created_at FROM users WHERE id = $1
|
|
`, user.Id).Scan(&user.Name, &user.PasswordHash, &user.Pronouns, &rgba, &user.CreatedAt)
|
|
if err == nil {
|
|
user.Color = convertions.Uint32ToRgba(uint32(rgba))
|
|
}
|
|
return err
|
|
}
|
|
|
|
func PgUserSetColor(ctx context.Context, user *types.User) error {
|
|
_, err := dbConn.Exec(ctx, `
|
|
UPDATE users SET rgba = $1 WHERE id = $2
|
|
`, convertions.RgbaToUint32(user.Color), user.Id)
|
|
return err
|
|
}
|
|
|
|
func PgUserSetPronouns(ctx context.Context, user *types.User) error {
|
|
_, err := dbConn.Exec(ctx, `
|
|
UPDATE users SET pronouns = $1 WHERE id = $2
|
|
`, user.Pronouns, user.Id)
|
|
return err
|
|
}
|
|
|
|
func PgGetWholeUser(ctx context.Context, user *types.User) error {
|
|
if err := PgUserGetById(ctx, user); err != nil {
|
|
return err
|
|
}
|
|
if err := PgConnectionsGetBelongingToUser(ctx, user); err != nil {
|
|
return err
|
|
}
|
|
|
|
cache.CacheSaveUser(user)
|
|
return nil
|
|
}
|
|
|
|
func PgConnectionSave(ctx context.Context, conn *types.Connection) error {
|
|
return dbConn.QueryRow(ctx, `
|
|
INSERT INTO user_connections (requestor_id, recipient_id, state, created_at) VALUES ($1, $2, $3, $4)
|
|
RETURNING id
|
|
`, conn.RequestorId, conn.RecipientId, conn.State, conn.CreatedAt).Scan(&conn.Id)
|
|
}
|
|
|
|
func PgConnectionDelete(ctx context.Context, conn *types.Connection) error {
|
|
_, err := dbConn.Exec(ctx, `
|
|
DELETE FROM user_connections WHERE id = $1
|
|
`, conn.Id)
|
|
return err
|
|
}
|
|
|
|
func PgConnectionsGetBelongingToUser(ctx context.Context, user *types.User) error {
|
|
rows, err := dbConn.Query(ctx, `
|
|
SELECT id, requestor_id, recipient_id, state, created_at
|
|
FROM user_connections
|
|
WHERE requestor_id = $1 OR recipient_id = $1
|
|
`, user.Id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer rows.Close()
|
|
|
|
if user.Connections == nil {
|
|
user.Connections = make(map[uuid.UUID]*types.Connection)
|
|
}
|
|
|
|
for rows.Next() {
|
|
conn := &types.Connection{}
|
|
if err = rows.Scan(&conn.Id, &conn.RequestorId, &conn.RecipientId, &conn.State, &conn.CreatedAt); err != nil {
|
|
return fmt.Errorf("scanning connection row: %w", err)
|
|
}
|
|
user.Connections[conn.Id] = conn
|
|
}
|
|
return rows.Err()
|
|
}
|
|
|
|
func PgConnectionUpdateState(ctx context.Context, conn *types.Connection) error {
|
|
_, err := dbConn.Exec(ctx, `
|
|
UPDATE user_connections SET state = $1 WHERE id = $2
|
|
`, conn.State, conn.Id)
|
|
return err
|
|
}
|
|
|
|
func PgConnectionMessageSave(ctx context.Context, message *types.Message) error {
|
|
if message.Id != (uuid.UUID{}) {
|
|
_, err := dbConn.Exec(ctx, `
|
|
INSERT INTO direct_messages (id, sender_id, receiver_id, created_at, content) VALUES ($1, $2, $3, $4, $5)
|
|
`, message.Id, message.Sender, message.Receiver, message.CreatedAt, message.Content)
|
|
return err
|
|
}
|
|
return dbConn.QueryRow(ctx, `
|
|
INSERT INTO direct_messages (sender_id, receiver_id, created_at, content) VALUES ($1, $2, $3, $4)
|
|
RETURNING id
|
|
`, message.Sender, message.Receiver, message.CreatedAt, message.Content).Scan(&message.Id)
|
|
}
|
|
|
|
func PgConnectionGetMessagesBefore(ctx context.Context, before time.Time, connection uuid.UUID, cap uint32) ([]*types.Message, error) {
|
|
rows, err := dbConn.Query(ctx, `
|
|
SELECT id, sender_id, receiver_id, created_at, content
|
|
FROM (
|
|
SELECT id, sender_id, receiver_id, created_at, content
|
|
FROM direct_messages
|
|
WHERE receiver_id = $1
|
|
AND created_at < $2
|
|
ORDER BY created_at DESC
|
|
LIMIT $3
|
|
) sub
|
|
ORDER BY created_at ASC
|
|
`, connection, before, cap)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
messages := make([]*types.Message, 0, cap)
|
|
for rows.Next() {
|
|
msg := &types.Message{}
|
|
if err = rows.Scan(&msg.Id, &msg.Sender, &msg.Receiver, &msg.CreatedAt, &msg.Content); err != nil {
|
|
return nil, err
|
|
}
|
|
messages = append(messages, msg)
|
|
}
|
|
return messages, rows.Err()
|
|
}
|
|
|
|
func PgFileMetadataSave(ctx context.Context, metadata *types.FileMetadata) error {
|
|
_, err := dbConn.Exec(ctx, `
|
|
INSERT INTO files_metadata (id, uploader_id, name, hash, created_at) VALUES ($1, $2, $3, $4, $5)
|
|
`, metadata.Id, metadata.UploaderId, metadata.Name, metadata.Hash, metadata.CreatedAt)
|
|
return err
|
|
}
|
|
|
|
func PgFileMetadataGet(ctx context.Context, metadata *types.FileMetadata) error {
|
|
return dbConn.QueryRow(ctx, `
|
|
SELECT uploader_id, name, hash, created_at FROM files_metadata WHERE id = $1
|
|
`, metadata.Id).Scan(&metadata.UploaderId, &metadata.Name, &metadata.Hash, &metadata.CreatedAt)
|
|
}
|
|
|
|
func PgFileMetadataDelete(ctx context.Context, metadataId *uuid.UUID) error {
|
|
_, err := dbConn.Exec(ctx, `
|
|
DELETE FROM files_metadata WHERE id = $1
|
|
`, metadataId)
|
|
return err
|
|
}
|
|
|
|
func PgFileConnectionsAdd(ctx context.Context, metadataId *uuid.UUID, connectionId *uuid.UUID) error {
|
|
_, err := dbConn.Exec(ctx, `
|
|
INSERT INTO files_metadata_connections (file_metadata_id, connection_id) VALUES ($1, $2)
|
|
`, metadataId, connectionId)
|
|
return err
|
|
}
|
|
|
|
func PgFileConnectionsGet(ctx context.Context, metadata *types.FileMetadata) error {
|
|
rows, err := dbConn.Query(ctx, `
|
|
SELECT connection_id FROM files_metadata_connections WHERE file_metadata_id = $1
|
|
`, metadata.Id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer rows.Close()
|
|
|
|
for rows.Next() {
|
|
connectionId := uuid.UUID{}
|
|
if err = rows.Scan(&connectionId); err != nil {
|
|
return err
|
|
}
|
|
metadata.Connections = append(metadata.Connections, connectionId)
|
|
}
|
|
return rows.Err()
|
|
}
|
|
|
|
func PgFileMetadataHashExists(ctx context.Context, hash *types.Sha256Hash) (bool, error) {
|
|
var exists bool
|
|
err := dbConn.QueryRow(ctx, `
|
|
SELECT EXISTS (SELECT FROM files_metadata WHERE hash = $1)
|
|
`, hash).Scan(&exists)
|
|
return exists, err
|
|
}
|