aboutsummaryrefslogtreecommitdiffstats
path: root/worker/notmuch/eventhandlers.go
blob: a8a396c9bd6f28854daf380ea7050e876ab179d3 (plain) (blame)
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
//go:build notmuch
// +build notmuch

package notmuch

import (
	"context"
	"fmt"
	"path/filepath"
	"strconv"

	"git.sr.ht/~rjarry/aerc/log"
	"git.sr.ht/~rjarry/aerc/worker/types"
)

func (w *worker) handleNotmuchEvent() error {
	err := w.db.Connect()
	if err != nil {
		return err
	}
	defer w.db.Close()
	err = w.updateDirCounts()
	if err != nil {
		return err
	}
	err = w.updateChangedMessages()
	if err != nil {
		return err
	}
	w.emitLabelList()
	return nil
}

func (w *worker) updateDirCounts() error {
	if w.store != nil {
		folders, err := w.store.FolderMap()
		if err != nil {
			w.w.Errorf("failed listing directories: %v", err)
			return err
		}
		for name := range folders {
			folder := filepath.Join(w.maildirAccountPath, name)
			query := fmt.Sprintf("folder:%s", strconv.Quote(folder))
			w.w.PostMessage(&types.DirectoryInfo{
				Info:    w.getDirectoryInfo(name, query),
				Refetch: w.query == query,
			}, nil)
		}
	}

	for name, query := range w.nameQueryMap {
		w.w.PostMessage(&types.DirectoryInfo{
			Info:    w.getDirectoryInfo(name, query),
			Refetch: w.query == query,
		}, nil)
	}

	return nil
}

func (w *worker) updateChangedMessages() error {
	newState := w.db.State()
	if newState == w.state {
		return nil
	}
	w.w.Logger.Debugf("State change: %d to %d", w.state, newState)
	query := fmt.Sprintf("%s lastmod:%d..%d", w.query, w.state, newState)
	uids, err := w.uidsFromQuery(context.TODO(), query)
	if err != nil {
		return fmt.Errorf("Couldn't get updates messages: %w", err)
	}
	for _, uid := range uids {
		m, err := w.msgFromUid(uid)
		if err != nil {
			log.Errorf("%s", err)
			continue
		}
		err = w.emitMessageInfo(m, nil)
		if err != nil {
			log.Errorf("%s", err)
		}
	}
	w.state = newState
	return nil
}