| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/attach" |
| 14 | "amadan.net/oficina/equipo/internal/wire" |
| 15 | "gorm.io/gorm" |
| 16 | ) |
| 17 | |
| 18 | // Attachment refusals, each with its own API code and words. |
| 19 | var ( |
| 20 | ErrAttachmentTooLarge = errors.New("chat: attachment too large") |
| 21 | ErrAttachmentType = errors.New("chat: attachment type") |
| 22 | ErrAttachmentHEIC = errors.New("chat: attachment heic") |
| 23 | ErrAttachmentLimit = errors.New("chat: too many unsent attachments") |
| 24 | ErrAttachmentPixels = errors.New("chat: attachment too many pixels") |
| 25 | ) |
| 26 | |
| 27 | // Unsent uploads are kept a day, and a person holds at most this many. |
| 28 | const ( |
| 29 | unsentFor = 24 * time.Hour |
| 30 | maxUnsent = 20 |
| 31 | ) |
| 32 | |
| 33 | // fileRecord is one uploaded attachment. MessageID is empty until it is |
| 34 | // sent; Position is its place among the message's attachments. |
| 35 | type fileRecord struct { |
| 36 | ID string `gorm:"primaryKey"` |
| 37 | Person string `gorm:"index:chat_attachment_person"` |
| 38 | MessageID string `gorm:"index:chat_attachment_message"` |
| 39 | Position int |
| 40 | Kind string |
| 41 | Name string |
| 42 | MediaType string |
| 43 | Size int64 |
| 44 | SHA256 string `gorm:"column:sha256"` |
| 45 | Width int |
| 46 | Height int |
| 47 | HasPreview bool |
| 48 | Revision int64 |
| 49 | CreatedAt time.Time |
| 50 | } |
| 51 | |
| 52 | func (fileRecord) TableName() string { return "chat_attachments" } |
| 53 | |
| 54 | // fileDataRecord holds the bytes apart, so listing attachments never |
| 55 | // loads them. Preview is an image's thumbnail, when it needs one. |
| 56 | type fileDataRecord struct { |
| 57 | ID string `gorm:"primaryKey"` |
| 58 | Data []byte |
| 59 | Preview []byte |
| 60 | } |
| 61 | |
| 62 | func (fileDataRecord) TableName() string { return "chat_attachment_data" } |
| 63 | |
| 64 | func fileView(r fileRecord) wire.MessageAttachment { |
| 65 | return wire.MessageAttachment{ID: r.ID, Revision: r.Revision, Kind: r.Kind, Name: r.Name, MediaType: r.MediaType, Size: r.Size, SHA256: r.SHA256, Width: r.Width, Height: r.Height, MessageID: r.MessageID, CreatedAt: r.CreatedAt} |
| 66 | } |
| 67 | |
| 68 | // Upload keeps one file for the person, on no message yet. The type is |
| 69 | // sniffed from the bytes, an image's location is stripped, and an image |
| 70 | // that needs one gets a thumbnail. |
| 71 | func (s *Store) Upload(ctx context.Context, person, name, declared string, data []byte) (out wire.MessageAttachment, err error) { |
| 72 | info, clean, err := attach.Inspect(name, declared, data) |
| 73 | switch { |
| 74 | case errors.Is(err, attach.ErrTooLarge): |
| 75 | return out, ErrAttachmentTooLarge |
| 76 | case errors.Is(err, attach.ErrHEIC): |
| 77 | return out, ErrAttachmentHEIC |
| 78 | case errors.Is(err, attach.ErrPixels): |
| 79 | return out, ErrAttachmentPixels |
| 80 | case err != nil: |
| 81 | return out, ErrAttachmentType |
| 82 | } |
| 83 | var preview []byte |
| 84 | if info.Kind == attach.KindImage { |
| 85 | if p, ok, err := attach.Preview(info.MediaType, clean); err == nil && ok { |
| 86 | preview = p |
| 87 | } |
| 88 | } |
| 89 | sum := sha256.Sum256(clean) |
| 90 | err = s.tx(ctx, func(t *txn) error { |
| 91 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 92 | return err |
| 93 | } |
| 94 | now := t.now() |
| 95 | // Unsent uploads past a day go; a person keeps at most maxUnsent. |
| 96 | if err := t.dropUnsent(person, now.Add(-unsentFor)); err != nil { |
| 97 | return err |
| 98 | } |
| 99 | var unsent int64 |
| 100 | if err := t.db.Model(&fileRecord{}).Where("person = ? AND message_id = ''", person).Count(&unsent).Error; err != nil { |
| 101 | return err |
| 102 | } |
| 103 | if unsent >= maxUnsent { |
| 104 | return ErrAttachmentLimit |
| 105 | } |
| 106 | r := fileRecord{ID: newID("at_"), Person: person, Kind: info.Kind, Name: info.Name, MediaType: info.MediaType, Size: int64(len(clean)), SHA256: hex.EncodeToString(sum[:]), Width: info.Width, Height: info.Height, HasPreview: preview != nil, Revision: 1, CreatedAt: now} |
| 107 | if err := t.db.Create(&r).Error; err != nil { |
| 108 | return err |
| 109 | } |
| 110 | if err := t.db.Create(&fileDataRecord{ID: r.ID, Data: clean, Preview: preview}).Error; err != nil { |
| 111 | return err |
| 112 | } |
| 113 | out = fileView(r) |
| 114 | return nil |
| 115 | }) |
| 116 | return out, err |
| 117 | } |
| 118 | |
| 119 | // ErrAttachmentSent: the upload is on a message already, so it stays |
| 120 | // (409 attachment_sent). |
| 121 | var ErrAttachmentSent = errors.New("chat: attachment sent") |
| 122 | |
| 123 | // auditAttachmentDelete is a deleted unsent upload, audited by id alone. |
| 124 | const auditAttachmentDelete = "attachment.delete" |
| 125 | |
| 126 | // DeleteUnsent deletes one of the person's own unsent uploads, its row |
| 127 | // and its bytes, in one transaction with the roster check, and audits |
| 128 | // it by id: the person removed it before sending, so it no longer counts |
| 129 | // against maxUnsent. An id that is not the person's, or no longer |
| 130 | // exists, is ErrNotFound; one on a message already is ErrAttachmentSent. |
| 131 | // A send racing it either links the file first (then this is |
| 132 | // ErrAttachmentSent) or finds it gone (ErrInvalid): linkFiles links only |
| 133 | // a row still unsent. |
| 134 | func (s *Store) DeleteUnsent(ctx context.Context, person, id string) error { |
| 135 | return s.tx(ctx, func(t *txn) error { |
| 136 | if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| 137 | return err |
| 138 | } |
| 139 | var r fileRecord |
| 140 | if err := t.db.Select("id", "message_id").Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 141 | return ErrNotFound |
| 142 | } else if err != nil { |
| 143 | return err |
| 144 | } |
| 145 | if r.MessageID != "" { |
| 146 | return ErrAttachmentSent |
| 147 | } |
| 148 | res := t.db.Where("id = ? AND person = ? AND message_id = ''", id, person).Delete(&fileRecord{}) |
| 149 | if res.Error != nil { |
| 150 | return res.Error |
| 151 | } |
| 152 | if res.RowsAffected != 1 { |
| 153 | return ErrNotFound |
| 154 | } |
| 155 | if err := t.db.Where("id = ?", id).Delete(&fileDataRecord{}).Error; err != nil { |
| 156 | return err |
| 157 | } |
| 158 | return s.authority.Audit(t.db, person, auditAttachmentDelete, id) |
| 159 | }) |
| 160 | } |
| 161 | |
| 162 | func (t *txn) dropUnsent(person string, before time.Time) error { |
| 163 | var ids []string |
| 164 | q := t.db.Model(&fileRecord{}).Where("message_id = '' AND created_at < ?", before) |
| 165 | if person != "" { |
| 166 | q = q.Where("person = ?", person) |
| 167 | } |
| 168 | if err := q.Pluck("id", &ids).Error; err != nil || len(ids) == 0 { |
| 169 | return err |
| 170 | } |
| 171 | if err := t.db.Where("id IN ?", ids).Delete(&fileDataRecord{}).Error; err != nil { |
| 172 | return err |
| 173 | } |
| 174 | return t.db.Where("id IN ?", ids).Delete(&fileRecord{}).Error |
| 175 | } |
| 176 | |
| 177 | // checkFiles validates a send's attachment ids: at most five, no repeats. |
| 178 | func checkFiles(ids []string) error { |
| 179 | if len(ids) > attach.MaxPerMessage { |
| 180 | return ErrInvalid |
| 181 | } |
| 182 | seen := map[string]bool{} |
| 183 | for _, id := range ids { |
| 184 | if !strings.HasPrefix(id, "at_") || len(id) > 64 || seen[id] { |
| 185 | return ErrInvalid |
| 186 | } |
| 187 | seen[id] = true |
| 188 | } |
| 189 | return nil |
| 190 | } |
| 191 | |
| 192 | // sendHash is the idempotency hash of a send: the text, and the |
| 193 | // attachment ids when there are any (so a plain message hashes as before). |
| 194 | func sendHash(text string, files []string) string { |
| 195 | if len(files) == 0 { |
| 196 | return bodyHash(text) |
| 197 | } |
| 198 | raw, _ := json.Marshal(struct { |
| 199 | Text string `json:"text"` |
| 200 | Files []string `json:"files"` |
| 201 | }{text, files}) |
| 202 | return bodyHash(string(raw)) |
| 203 | } |
| 204 | |
| 205 | // linkFiles puts the person's unsent uploads on message m, in order. An id |
| 206 | // that is not the person's, already sent, or past its day unsent (it is |
| 207 | // dropped with the next upload) refuses the whole send. |
| 208 | func (t *txn) linkFiles(m messageRecord, ids []string) error { |
| 209 | kept := t.now().Add(-unsentFor) |
| 210 | for i, id := range ids { |
| 211 | res := t.db.Model(&fileRecord{}).Where("id = ? AND person = ? AND message_id = '' AND created_at >= ?", id, m.Person, kept).Select("message_id", "position").Updates(&fileRecord{MessageID: m.ID, Position: i + 1}) |
| 212 | if res.Error != nil { |
| 213 | return res.Error |
| 214 | } |
| 215 | if res.RowsAffected != 1 { |
| 216 | return ErrInvalid |
| 217 | } |
| 218 | } |
| 219 | return nil |
| 220 | } |
| 221 | |
| 222 | // filesOf reads the attachments of messages, by message id. |
| 223 | func filesOf(tx *gorm.DB, ids []string) (map[string][]wire.MessageAttachment, error) { |
| 224 | out := map[string][]wire.MessageAttachment{} |
| 225 | if len(ids) == 0 { |
| 226 | return out, nil |
| 227 | } |
| 228 | var rows []fileRecord |
| 229 | if err := tx.Where("message_id IN ?", ids).Order("message_id, position").Find(&rows).Error; err != nil { |
| 230 | return nil, err |
| 231 | } |
| 232 | for _, r := range rows { |
| 233 | out[r.MessageID] = append(out[r.MessageID], fileView(r)) |
| 234 | } |
| 235 | return out, nil |
| 236 | } |
| 237 | |
| 238 | // withFiles fills in the attachments of person messages. |
| 239 | func withFiles(tx *gorm.DB, views []wire.Message) error { |
| 240 | var ids []string |
| 241 | for _, v := range views { |
| 242 | if v.Role == wire.RolePerson { |
| 243 | ids = append(ids, v.ID) |
| 244 | } |
| 245 | } |
| 246 | files, err := filesOf(tx, ids) |
| 247 | if err != nil { |
| 248 | return err |
| 249 | } |
| 250 | for i := range views { |
| 251 | views[i].Attachments = files[views[i].ID] |
| 252 | } |
| 253 | // An Assistant reply shows its turn's lookups. |
| 254 | return withLookups(tx, views) |
| 255 | } |
| 256 | |
| 257 | // AttachmentData is one attachment's bytes for its person: the original, |
| 258 | // or an image's thumbnail (the original when it needs none). |
| 259 | func (s *Store) AttachmentData(ctx context.Context, person, id string, preview bool) (meta wire.MessageAttachment, data []byte, err error) { |
| 260 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 261 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 262 | return err |
| 263 | } |
| 264 | var r fileRecord |
| 265 | if err := tx.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| 266 | return ErrNotFound |
| 267 | } else if err != nil { |
| 268 | return err |
| 269 | } |
| 270 | if preview && r.Kind != wire.AttachmentImage { |
| 271 | return ErrNotFound |
| 272 | } |
| 273 | var d fileDataRecord |
| 274 | if err := tx.Where("id = ?", id).First(&d).Error; err != nil { |
| 275 | return err |
| 276 | } |
| 277 | meta, data = fileView(r), d.Data |
| 278 | if preview && r.HasPreview { |
| 279 | meta.MediaType, data = attach.JPEG, d.Preview |
| 280 | } |
| 281 | return nil |
| 282 | }) |
| 283 | return meta, data, err |
| 284 | } |
| 285 | |
| 286 | // relayFiles writes the attachment frames for the files of a turn's |
| 287 | // messages, before its message frame. The command rows hold no bytes: |
| 288 | // Pending reads each chunk from chat_attachment_data as it sends. names |
| 289 | // are each message's file names, in order. |
| 290 | func (t *txn) relayFiles(person string, messages []string) ([]wire.AttachmentRef, map[string][]string, error) { |
| 291 | if len(messages) == 0 { |
| 292 | return nil, nil, nil |
| 293 | } |
| 294 | var rows []fileRecord |
| 295 | if err := t.db.Where("message_id IN ? AND person = ?", messages, person).Find(&rows).Error; err != nil { |
| 296 | return nil, nil, err |
| 297 | } |
| 298 | order := map[string]int{} |
| 299 | for i, id := range messages { |
| 300 | order[id] = i |
| 301 | } |
| 302 | slices.SortFunc(rows, func(a, b fileRecord) int { |
| 303 | if d := order[a.MessageID] - order[b.MessageID]; d != 0 { |
| 304 | return d |
| 305 | } |
| 306 | return a.Position - b.Position |
| 307 | }) |
| 308 | refs := make([]wire.AttachmentRef, 0, len(rows)) |
| 309 | names := map[string][]string{} |
| 310 | for _, r := range rows { |
| 311 | ref := wire.AttachmentRef{ID: r.ID, Kind: r.Kind, Name: r.Name, MediaType: r.MediaType, Size: r.Size, SHA256: r.SHA256} |
| 312 | count := attach.Chunks(r.Size) |
| 313 | for i := 0; i < count; i++ { |
| 314 | if err := t.command(person, wire.FrameAttachment, wire.AttachmentChunk{Person: person, AttachmentRef: ref, Index: i, Count: count}); err != nil { |
| 315 | return nil, nil, err |
| 316 | } |
| 317 | } |
| 318 | refs = append(refs, ref) |
| 319 | names[r.MessageID] = append(names[r.MessageID], r.Name) |
| 320 | } |
| 321 | return refs, names, nil |
| 322 | } |
| 323 | |
| 324 | // earlierFiles is what a turn's frame names as Earlier: the files of the |
| 325 | // person's own messages in lane sent since since, in turns already |
| 326 | // dispatched (so their bytes went to the runner), apart from exclude's |
| 327 | // messages; newest message first, each message's files in order, at most |
| 328 | // limit. more counts the rest. No bytes are sent again: the runner holds |
| 329 | // them, or no longer does, and says so. |
| 330 | func (t *txn) earlierFiles(person, lane string, exclude []string, since time.Time, limit int) (refs []wire.AttachmentRef, more int, err error) { |
| 331 | if len(exclude) == 0 { |
| 332 | exclude = []string{""} |
| 333 | } |
| 334 | q := t.db.Table("chat_attachments AS a").Joins("JOIN chat_messages AS m ON m.id = a.message_id"). |
| 335 | Where("a.person = ? AND m.person = ? AND m.role = ? AND coalesce(m.lane, '') = ? AND m.created_at >= ? AND m.id NOT IN ?", person, person, wire.RolePerson, lane, since, exclude). |
| 336 | Where("m.turn_id IN (SELECT id FROM chat_turns WHERE person = ? AND dispatched = ?)", person, true) |
| 337 | var total int64 |
| 338 | if err := q.Session(&gorm.Session{}).Count(&total).Error; err != nil { |
| 339 | return nil, 0, err |
| 340 | } |
| 341 | var rows []fileRecord |
| 342 | if err := q.Session(&gorm.Session{}).Select("a.*").Order("m.seq DESC, a.position").Limit(limit).Find(&rows).Error; err != nil { |
| 343 | return nil, 0, err |
| 344 | } |
| 345 | refs = make([]wire.AttachmentRef, 0, len(rows)) |
| 346 | for _, r := range rows { |
| 347 | refs = append(refs, wire.AttachmentRef{ID: r.ID, Kind: r.Kind, Name: r.Name, MediaType: r.MediaType, Size: r.Size, SHA256: r.SHA256}) |
| 348 | } |
| 349 | return refs, int(total) - len(refs), nil |
| 350 | } |
| 351 | |
| 352 | // sentFilesLine is a files-only person message as the tail shows it: |
| 353 | // the names of the files it carried. |
| 354 | func sentFilesLine(names []string) string { |
| 355 | return "(sent files: " + strings.Join(names, ", ") + ")" |
| 356 | } |
| 357 | |
| 358 | // hydrate fills an attachment frame's bytes from the stored file. |
| 359 | func hydrate(tx *gorm.DB, body string) (string, error) { |
| 360 | var c wire.AttachmentChunk |
| 361 | if err := json.Unmarshal([]byte(body), &c); err != nil { |
| 362 | return "", err |
| 363 | } |
| 364 | var data []byte |
| 365 | if err := tx.Raw("SELECT substr(data, ?, ?) FROM chat_attachment_data WHERE id = ?", c.Index*attach.ChunkBytes+1, attach.ChunkBytes, c.ID).Row().Scan(&data); err != nil { |
| 366 | return "", err |
| 367 | } |
| 368 | c.Data = data |
| 369 | raw, err := json.Marshal(c) |
| 370 | return string(raw), err |
| 371 | } |
| 372 | |