all repos — emessage @ 6b4a23ef0a41620ece7bf9728e8507ff40439692

The EMessage email client

conversation.go (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
package main

import (
	"errors"
	"fmt"
	"sort"
	"strings"
	"time"

	"github.com/emersion/go-imap/v2"
	"github.com/emersion/go-imap/v2/imapclient"
	"gorm.io/gorm"
)

type Conversation struct {
	gorm.Model
	Subject           string
	IsUnread          bool
	ServerRecipientID uint
	ServerRecipient   EmailAddress
	DisplayImageID    uint
	DisplayImage      DisplayImage
	Recipients        []EmailAddress `gorm:"many2many:conversation_email_addresses;"`
	Messages          []Message
}

func (app *App) NewConversation() (conv Conversation) {
	conv.Recipients = []EmailAddress{{}}
	return conv
}

func (app *App) GetConversationPreviewSubject(conv Conversation) string {
	if len(conv.Recipients) > 1 {
		return strings.Join(app.GetRecipientDisplay(conv.Recipients[1:]), ", ")
	} else {
		return "New Message"
	}
}

func (app *App) GetConversationPreviewText(conv Conversation) string {
	var msg Message
	err := app.DB.
		Where("conversation_id = ?", conv.ID).
		Order("created_at DESC").
		Preload("MessageContents").
		First(&msg).Error
	if err != nil {
		return ""
	}

	if len(msg.MessageContents) > 0 {
		s := string(msg.MessageContents[0].Content)
		runes := []rune(s)
		if len(runes) > 100 {
			s = string(runes[:100]) + "..."
		}
		return s
	}
	return ""
}

func (app *App) GetConversationPreviewTime(conv Conversation) string {
	var msg Message
	err := app.DB.
		Where("conversation_id = ?", conv.ID).
		Order("created_at DESC").
		First(&msg).Error
	if err != nil {
		return ""
	}

	return relativeTime(msg.Date)
}

func relativeTime(t time.Time) string {
	now := time.Now().Local()
	t = t.Local()
	nowDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	tDay := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())

	days := int(nowDay.Sub(tDay).Hours() / 24)

	switch {
	case days == 0:
		return t.Format("3:04 PM")
	case days == 1:
		return "yesterday"
	case days < 7:
		return fmt.Sprintf("%d days ago", days)
	case days < 28:
		weeks := days / 7
		if weeks == 1 {
			return "1 week ago"
		}
		return fmt.Sprintf("%d weeks ago", weeks)
	case days < 365:
		months := days / 28
		if months == 1 {
			return "1 month ago"
		}
		return fmt.Sprintf("%d months ago", months)
	default:
		years := days / 365
		if years == 1 {
			return "1 year ago"
		}
		return fmt.Sprintf("%d years ago", years)
	}
}

func (app *App) GetAllConversations() ([]Conversation, error) {
	var conversations []Conversation
	err := app.DB.
		Preload("Recipients").
		Preload("ServerRecipient").
		Order("updated_at DESC").
		Find(&conversations).Error
	return conversations, err
}

type MailMessageStandard struct {
	From            string
	To              string
	Subject         string
	Date            time.Time
	ServerMessageID string `gorm:"unique"`
	UID             uint32
	Seen            bool
	Answered        bool
	Deleted         bool
	EmailID         string
	ThreadID        string
}

type Message struct {
	gorm.Model
	MailMessageStandard
	ConversationID  uint
	Conversation    Conversation
	SenderID        uint
	Sender          EmailAddress
	Hidden          bool
	Internal        bool
	Headers         []MailHeader
	MessageContents []MessageContent
}

type MailHeader struct {
	gorm.Model
	MessageID uint
	Key       string
	Value     string
}

type MessageContent struct {
	gorm.Model
	MessageID uint
	MIMEType  string
	Content   []byte
}

type LastSynced struct {
	gorm.Model
	EmailAddressID uint
	EmailAddress   EmailAddress
	UID            uint32
}

func (app *App) getLastSynced(email EmailAddress) (LastSynced, error) {
	var last LastSynced
	app.Log("Getting last synced for %s.", email.Value).
		Stdout().
		StatusLine()
	defer app.Log("Last synced for %s is %d.", email.Value, last.UID).
		Stdout()
	err := app.DB.Where("email_address_id = ?", email.ID).
		First(&last).
		Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return LastSynced{}, nil
	}
	return last, err
}

func (app *App) setLastSynced(email EmailAddress, uid uint32) error {
	var last LastSynced
	app.Log("Setting last synced for %s to %d.", email.Value, uid).
		Stdout()
	result := app.DB.Where(LastSynced{EmailAddressID: email.ID}).
		Assign(LastSynced{UID: uid}).
		FirstOrCreate(&last)
	return result.Error
}

func (app *App) fetchFilteredMessages(conn MailAccountConnection) ([]*imapclient.FetchMessageBuffer, error) {
	var emailAddr EmailAddress
	if err := app.DB.Where("value = ?", conn.Email).First(&emailAddr).Error; err != nil {
		return nil, err
	}

	lastSynced, err := app.getLastSynced(emailAddr)
	if err != nil {
		return nil, err
	}

	selectData, err := conn.ImapClient.Select(AppMailbox, nil).Wait()
	if err != nil {
		return nil, err
	}

	startUID := uint32(1)
	if lastSynced.UID > 0 {
		startUID = lastSynced.UID + 1
	}
	endUID := uint32(0)
	if selectData.UIDNext > 1 {
		endUID = uint32(selectData.UIDNext) - 1
	}

	if startUID > endUID {
		return []*imapclient.FetchMessageBuffer{}, nil
	}

	uidRange := []imap.UIDRange{{
		Start: imap.UID(startUID),
		Stop:  imap.UID(endUID),
	}}

	criteria := &imap.SearchCriteria{
		Header: []imap.SearchCriteriaHeaderField{{
			Key:   "FE-Application",
			Value: "emessage",
		}},
		UID: []imap.UIDSet{uidRange},
	}

	searchData, err := conn.ImapClient.UIDSearch(criteria, nil).Wait()
	if err != nil {
		return nil, err
	}
	uids := searchData.AllUIDs()
	if len(uids) == 0 {
		return nil, nil
	}

	fetchOptions := &imap.FetchOptions{
		UID:          true,
		Envelope:     true,
		Flags:        true,
		InternalDate: true,
	}
	uidSet := imap.UIDSetNum(uids...)
	fetchCmd := conn.ImapClient.Fetch(uidSet, fetchOptions)
	defer fetchCmd.Close()

	var results []*imapclient.FetchMessageBuffer
	for {
		msg := fetchCmd.Next()
		if msg == nil {
			break
		}
		buf, err := msg.Collect()
		if err != nil {
			return nil, err
		}
		results = append(results, buf)
	}
	return results, nil
}

func (app *App) findOrCreateConversation(recipients []string, serverRecipient EmailAddress) (*Conversation, error) {
	emailIDs := make([]uint, len(recipients))
	for i, r := range recipients {
		addr, err := app.GetOrCreateEmailAddress(r)
		if err != nil {
			return nil, err
		}
		emailIDs[i] = addr.ID
	}
	sort.Slice(emailIDs, func(i, j int) bool { return emailIDs[i] < emailIDs[j] })

	sql := `
		SELECT cea.conversation_id
		FROM conversation_email_addresses cea
		JOIN (
			SELECT conversation_id
			FROM conversation_email_addresses
			GROUP BY conversation_id
			HAVING COUNT(DISTINCT email_address_id) = ?
		) total ON total.conversation_id = cea.conversation_id
		WHERE cea.email_address_id IN ?
		GROUP BY cea.conversation_id
		HAVING COUNT(DISTINCT cea.email_address_id) = ?
		LIMIT 1
	`
	var convID uint
	err := app.DB.Raw(sql, len(emailIDs), emailIDs, len(emailIDs)).Scan(&convID).Error
	if err != nil {
		return nil, err
	}

	if convID != 0 {
		var conv Conversation
		if err := app.DB.Preload("Recipients").Preload("ServerRecipient").First(&conv, convID).Error; err != nil {
			return nil, err
		}
		return &conv, nil
	}

	emailRecipients := make([]EmailAddress, 0, len(emailIDs))
	for _, id := range emailIDs {
		var addr EmailAddress
		if err := app.DB.First(&addr, id).Error; err != nil {
			return nil, err
		}
		emailRecipients = append(emailRecipients, addr)
	}

	containsServer := false
	for _, addr := range emailRecipients {
		if addr.ID == serverRecipient.ID {
			containsServer = true
			break
		}
	}
	if !containsServer {
		emailRecipients = append(emailRecipients, serverRecipient)
	}

	conv := Conversation{
		ServerRecipientID: serverRecipient.ID,
		ServerRecipient:   serverRecipient,
		Recipients:        emailRecipients,
		Messages:          []Message{},
	}

	if err := app.DB.Create(&conv).Error; err != nil {
		return nil, err
	}

	if err := app.DB.Preload("Recipients").Preload("ServerRecipient").First(&conv, conv.ID).Error; err != nil {
		return nil, err
	}
	return &conv, nil
}

type PaginatedMessages struct {
	Messages []Message `json:"messages"`
	Total    int64     `json:"total"`
}

func (app *App) GetMessagesFromConversation(conv Conversation, page, pageSize int) (*PaginatedMessages, error) {
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 20
	}

	convID := conv.ID
	var total int64
	if err := app.DB.Model(&Message{}).
		Where("conversation_id = ?", convID).
		Count(&total).Error; err != nil {
		return nil, err
	}

	offset := (page - 1) * pageSize
	var messages []Message
	err := app.DB.
		Where("conversation_id = ?", convID).
		Preload("Headers").
		Preload("MessageContents").
		Preload("Sender").
		Order("date DESC, id ASC").
		Offset(offset).
		Limit(pageSize).
		Find(&messages).Error
	if err != nil {
		return nil, err
	}

	return &PaginatedMessages{
		Messages: messages,
		Total:    total,
	}, nil
}