Files
XHChat/server/internal/delivery/attachments.go
T

56 lines
1.5 KiB
Go

package delivery
import (
"bytes"
"context"
"errors"
"github.com/jackc/pgx/v5"
)
const AttachmentLimit = 8<<20 + 16
func (s *Store) UploadAttachment(ctx context.Context, sender, recipient, id string, ciphertext []byte) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
if err = authorizeDelivery(ctx, tx, sender, recipient); err != nil {
return err
}
result, err := tx.Exec(ctx, `
INSERT INTO device_attachments(id,sender_device,recipient_device,ciphertext)
VALUES($1,$2,$3,$4) ON CONFLICT(id) DO NOTHING
`, id, sender, recipient, ciphertext)
if err != nil {
return err
}
if result.RowsAffected() == 0 {
var stored []byte
err = tx.QueryRow(ctx, `
SELECT ciphertext FROM device_attachments WHERE id=$1 AND sender_device=$2 AND recipient_device=$3
`, id, sender, recipient).Scan(&stored)
if errors.Is(err, pgx.ErrNoRows) || err == nil && !bytes.Equal(stored, ciphertext) {
return ErrConflict
}
if err != nil {
return err
}
}
return tx.Commit(ctx)
}
func (s *Store) DownloadAttachment(ctx context.Context, device, id string) ([]byte, error) {
var ciphertext []byte
err := s.db.QueryRow(ctx, `
SELECT attachment.ciphertext FROM device_attachments attachment JOIN devices d ON d.id=$2
WHERE attachment.id=$1 AND d.revoked_at IS NULL
AND d.id IN (attachment.sender_device,attachment.recipient_device)
`, id, device).Scan(&ciphertext)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrUnavailable
}
return ciphertext, err
}