为双端群聊增加端到端加密附件
This commit is contained in:
1 parent
5988ad6ed6
commit
a95a007768
21 files changed
+405
-84
No files matched your search
@@ -0,0 +1,58 @@
|
||||
package groups
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
var ErrAttachment = errors.New("group attachment unavailable or already used")
|
||||
|
||||
func (s *Store) UploadAttachment(ctx context.Context, group, user, device, epoch, id string, ciphertext []byte) error {
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if err = lockSendingEpoch(ctx, tx, group, user, device, epoch); err != nil {
|
||||
return err
|
||||
}
|
||||
inserted, err := tx.Exec(ctx, `
|
||||
INSERT INTO group_attachments(group_id,id,epoch_id,sender_device,ciphertext)
|
||||
VALUES($1,$2,$3,$4,$5) ON CONFLICT(group_id,id) DO NOTHING
|
||||
`, group, id, epoch, device, ciphertext)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if inserted.RowsAffected() == 0 {
|
||||
var matches bool
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT ciphertext=$5 FROM group_attachments WHERE group_id=$1 AND id=$2 AND epoch_id=$3 AND sender_device=$4
|
||||
`, group, id, epoch, device, ciphertext).Scan(&matches)
|
||||
if errors.Is(err, pgx.ErrNoRows) || err == nil && !matches {
|
||||
return ErrAttachment
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) DownloadAttachment(ctx context.Context, group, user, device, id string) ([]byte, error) {
|
||||
var ciphertext []byte
|
||||
err := s.db.QueryRow(ctx, `
|
||||
SELECT a.ciphertext FROM group_attachments a
|
||||
JOIN group_messages x ON x.group_id=a.group_id AND x.attachment_id=a.id
|
||||
JOIN group_epochs g ON g.group_id=a.group_id AND g.id=a.epoch_id
|
||||
JOIN group_epoch_devices e ON e.group_id=g.group_id AND e.epoch_id=g.id AND e.device_id=$3
|
||||
JOIN group_members m ON m.group_id=g.group_id AND m.user_id=$2 AND m.state='active'
|
||||
JOIN devices d ON d.id=e.device_id AND d.user_id=m.user_id AND d.revoked_at IS NULL
|
||||
WHERE a.group_id=$1 AND a.id=$4 AND g.membership_version>=m.joined_version
|
||||
`, group, user, device, id).Scan(&ciphertext)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return ciphertext, err
|
||||
}
|
||||
Reference in new issue
Block a user