all repos — emessage @ b974eee156c9035918b86852896e7b4d45738145

The EMessage email client

mailaccount.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
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
package main

import (
	"errors"
	"time"
	"sync"
	"strconv"
	
	"github.com/emersion/go-imap/v2"
	"github.com/emersion/go-imap/v2/imapclient"
	"github.com/emersion/go-sasl"
	"github.com/emersion/go-smtp"
	"github.com/zalando/go-keyring"
	"gorm.io/gorm"
)

var ImapSyncMutex sync.Mutex

type MailAccountConnection struct {
	gorm.Model
	Email        string `gorm:"uniqueIndex"`
	ImapServer   string
	ImapPort     int
	ImapUsername string
	SmtpServer   string
	SmtpPort     int
	SmtpUsername string
	Password     string             `gorm:"-:all"`
	ImapClient   *imapclient.Client `gorm:"-:all"`
	SmtpClient   *smtp.Client       `gorm:"-:all"`
	SmtpSasl     *sasl.Client       `gorm:"-:all"`
}

var (
	mailConnections = make(map[string]MailAccountConnection)
	AppMailbox      = "APPLICATION.machinetelecom.emessage"
	SourceMailboxes = []string{"INBOX", "Sent", "Spam", "Junk"}
)

func (app *App) GetMailConnections() ([]MailAccountConnection, error) {
	userContact := app.GetUserContact()
	connections := make([]MailAccountConnection, len(userContact.Emails))
	for index, email := range userContact.Emails {
		if err := app.DB.
			Where("email = ?", email.Value).
			First(&connections[index]).
			Error; err != nil {
			connections[index].Email = email.Value
			connections[index].ImapUsername = email.Value
			connections[index].ImapPort = 993
			connections[index].SmtpUsername = email.Value
			connections[index].SmtpPort = 465
			continue
		}
		mailPassword, err := keyring.Get(
			app.GetMailPasswordKeyringService(),
			email.Value,
		)
		if err != nil {
			continue
		}
		connections[index].Password = mailPassword

		if connections[index].Email != "" &&
			connections[index].ImapServer != "" &&
			connections[index].ImapPort != 0 &&
			connections[index].ImapUsername != "" &&
			connections[index].SmtpServer != "" &&
			connections[index].SmtpPort != 0 &&
			connections[index].SmtpUsername != "" &&
			connections[index].Password != "" {
			mailConnections[email.Value] = connections[index]
		}
	}

	return connections, nil
}

func (app *App) GetActiveMailEmails() []string {
	emails := make([]string, 0)
	for email := range mailConnections {
		emails = append(emails, email)
	}
	return emails
}

func (app *App) SaveMailConnection(conn MailAccountConnection) error {
	keyring.Set(
		app.GetMailPasswordKeyringService(),
		conn.Email,
		conn.Password,
	)
	return app.DB.Save(&conn).Error
}

func RemoveMailConnection(address string) {
	if conn, ok := mailConnections[address]; ok {
		if conn.ImapClient != nil {
			conn.ImapClient.Close()
		}
		if conn.SmtpClient != nil {
			conn.SmtpClient.Close()
		}
		delete(mailConnections, address)
	}
}

func (app *App) EstablishMailConnections() {
	ImapSyncMutex.Lock()
	defer ImapSyncMutex.Unlock()
	_, _ = app.GetMailConnections()
	for key, conn := range mailConnections {
		app.Log("Attempting to connect to %s...", conn.Email).
				Stdout().
				StatusLine()
		var err error

		if conn.ImapClient != nil {
			conn.ImapClient.Close()
		}
		switch conn.ImapPort {
		case 143:
			conn.ImapClient, err = imapclient.DialStartTLS(
				conn.ImapServer+":"+strconv.Itoa(conn.ImapPort),
				nil,
			)
			break
		case 993:
			conn.ImapClient, err = imapclient.DialTLS(
				conn.ImapServer+":"+strconv.Itoa(conn.ImapPort),
				nil,
			)
			break
		default:
			conn.ImapClient, err = imapclient.DialTLS(
				conn.ImapServer+":"+strconv.Itoa(conn.ImapPort),
				nil,
			)
			break
		}
		if err != nil {
			RemoveMailConnection(conn.Email)
			app.Log(err.Error()).
				Stdout()
			continue
		}

		if err := conn.ImapClient.Login(conn.ImapUsername, conn.Password).Wait(); err != nil {
			RemoveMailConnection(conn.Email)
			app.Log(err.Error()).
				Stdout()
			continue
		}

		go app.keepIMAPAlive(key)

		if conn.SmtpClient != nil {
			conn.SmtpClient.Close()
		}
		switch conn.SmtpPort {
		case 25:
			conn.SmtpClient, err = smtp.Dial(conn.SmtpServer + ":" + strconv.Itoa(conn.SmtpPort))
			break
		case 587:
			conn.SmtpClient, err = smtp.DialStartTLS(
				conn.SmtpServer+":"+strconv.Itoa(conn.SmtpPort),
				nil,
			)
			break
		case 465:
			conn.SmtpClient, err = smtp.DialTLS(
				conn.SmtpServer+":"+strconv.Itoa(conn.SmtpPort),
				nil,
			)
			break
		default:
			conn.SmtpClient, err = smtp.DialTLS(
				conn.SmtpServer+":"+strconv.Itoa(conn.SmtpPort),
				nil,
			)
			break
		}
		if err != nil {
			RemoveMailConnection(conn.Email)
			app.Log(err.Error()).
				Stdout()
			continue
		}

		auth := sasl.NewPlainClient("", conn.SmtpUsername, conn.Password)
		if err := conn.SmtpClient.Auth(auth); err != nil {
			RemoveMailConnection(conn.Email)
			app.Log(err.Error()).
				Stdout()
			continue
		}
		conn.SmtpSasl = &auth

		mailConnections[key] = conn
		app.Log("Successfully connected %s!", conn.Email).
			Stdout().
			StatusLine()
	}
	app.EnsureAppMailboxExists()
	go func () {
		if err := app.syncMessages(); err != nil {
			app.Log("Sync Error: %s", err.Error()).
				Stdout().
				StatusLine()
		}
	}()
}

func CloseMailConnections() {
	for key, _ := range mailConnections {
		RemoveMailConnection(key)
	}
}

func (conn *MailAccountConnection) EnsureMailboxExists(mailboxName string) error {
	if conn.ImapClient == nil {
		return errors.New("IMAP client is nil")
	}
	_, err := conn.ImapClient.Status(mailboxName, &imap.StatusOptions{UIDValidity: true}).Wait()
	if err != nil {
		if err := conn.ImapClient.Create(mailboxName, nil).Wait(); err != nil {
			return err
		}
	}
	return nil
}

func (app *App) EnsureAppMailboxExists() {
	for email, conn := range mailConnections {
		if err := conn.EnsureMailboxExists(AppMailbox); err != nil {
			app.Log("Failed to ensure app mailbox for %s: %v", email, err).
				Stdout().
				StatusLine()
		}
	}
}

func (app *App) organizeMailboxesForAccount(conn MailAccountConnection) error {
	for _, mailbox := range SourceMailboxes {
		if _, err := conn.ImapClient.Select(mailbox, nil).Wait(); err != nil {
			continue
		}

		criteria := &imap.SearchCriteria{
			Header: []imap.SearchCriteriaHeaderField{{
				Key:   "FE-Application",
				Value: "emessage",
			}},
		}
		searchData, err := conn.ImapClient.UIDSearch(criteria, nil).Wait()
		if err != nil {
			return err
		}
		uids := searchData.AllUIDs()
		if len(uids) == 0 {
			continue
		}

		uidSet := imap.UIDSetNum(uids...)
		if _, err := conn.ImapClient.Move(uidSet, AppMailbox).Wait(); err != nil {
			return err
		}
	}

	return nil
}
func (app *App) syncMailbox(email EmailAddress, conn MailAccountConnection) error {
	if err := app.organizeMailboxesForAccount(conn); err != nil {
		return err
	}

	messages, err := app.fetchFilteredMessages(conn)
	if err != nil {
		return err
	}
	if len(messages) == 0 {
		return nil
	}

	app.Log("Found %d messages...", len(messages)).Stdout().StatusLine()

	var maxUID uint32
	for _, buf := range messages {
		msg, err := app.parseMessage(buf)
		if err != nil {
			continue
		}
		app.Log("Processing %s...", msg.ServerMessageID).Stdout()

		recipients := collectRecipients(&msg)

		conv, err := app.findOrCreateConversation(recipients, email)
		if err != nil {
			app.Log(err.Error()).
				Stdout()
			continue
		}

		msg.ConversationID = conv.ID

		sender, err := app.resolveSender(msg.From)
		if err != nil {
			app.Log(err.Error()).
				Stdout().
				StatusLine()
			continue
		}
		msg.SenderID = sender.ID

		if err := app.DB.Create(&msg).Error; err != nil {
			app.Log(err.Error()).
				Stdout().
				StatusLine()
			continue
		}

		if !msg.Seen {
			app.DB.Model(&conv).Update("IsUnread", true)
		}

		if msg.UID > maxUID {
			maxUID = msg.UID
		}
	}

	if maxUID > 0 {
		if err := app.setLastSynced(email, maxUID); err != nil {
			return err
		}
	}

	return nil
}

func (app *App) syncMessages() error {
	if !ImapSyncMutex.TryLock() {
		return nil
	}
	defer ImapSyncMutex.Unlock()
	app.Log("Syncing...").
		Stdout().
		StatusLine()
	for emailStr, conn := range mailConnections {
		var emailAddr EmailAddress
		if err := app.DB.Where("value = ?", emailStr).First(&emailAddr).Error; err != nil {
			app.Log("Email %s not found in DB: %v", emailStr, err).
				Stdout().
				StatusLine()
			continue
		}

		if err := app.syncMailbox(emailAddr, conn); err != nil {
			app.Log("Mailbox Error: %s: %v", emailStr, err).
				Stdout().
				StatusLine()
			continue
		}
	}
	app.Log("Syncing done.").
		Stdout().
		StatusLine()
	
	go func() {
		budget := 10
		for {
			amount, err := app.PopulateMissingMessageContents(budget)
			if err != nil || amount < budget {
				break
			}
			time.Sleep(20 * time.Millisecond)
		}
	}()

	
	
	return nil
}

func (app *App) keepIMAPAlive(conn string) {
    for {
        select {
        case <-time.After(5 * time.Minute):
            if connection, ok := mailConnections[conn]; ok {
				ImapSyncMutex.Lock()
                err := connection.ImapClient.Noop().Wait()
				ImapSyncMutex.Unlock()
                if err != nil {
                    app.Log("IMAP Noop failed: %v", err).Stdout()
					go app.EstablishMailConnections()
                    return
                }
            }
        }
    }
}