aboutsummaryrefslogtreecommitdiffstats
path: root/worker/imap/search.go
blob: 77a1899087606013c8ebecbfe3eb041dd3c6052c (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
86
87
88
89
90
91
92
93
94
95
package imap

import (
	"errors"
	"strings"

	"github.com/emersion/go-imap"

	"git.sr.ht/~rjarry/aerc/log"
	"git.sr.ht/~rjarry/aerc/worker/lib"
	"git.sr.ht/~sircmpwn/getopt"
)

func parseSearch(args []string) (*imap.SearchCriteria, error) {
	criteria := imap.NewSearchCriteria()
	if len(args) == 0 {
		return criteria, nil
	}

	opts, optind, err := getopt.Getopts(args, "rubax:X:t:H:f:c:d:")
	if err != nil {
		return nil, err
	}
	body := false
	text := false
	for _, opt := range opts {
		switch opt.Option {
		case 'r':
			criteria.WithFlags = append(criteria.WithFlags, imap.SeenFlag)
		case 'u':
			criteria.WithoutFlags = append(criteria.WithoutFlags, imap.SeenFlag)
		case 'x':
			if f, err := getParsedFlag(opt.Value); err == nil {
				criteria.WithFlags = append(criteria.WithFlags, f)
			}
		case 'X':
			if f, err := getParsedFlag(opt.Value); err == nil {
				criteria.WithoutFlags = append(criteria.WithoutFlags, f)
			}
		case 'H':
			if strings.Contains(opt.Value, ": ") {
				HeaderValue := strings.SplitN(opt.Value, ": ", 2)
				criteria.Header.Add(HeaderValue[0], HeaderValue[1])
			} else {
				log.Errorf("Header is not given properly, must be given in format `Header: Value`")
				continue
			}
		case 'f':
			criteria.Header.Add("From", opt.Value)
		case 't':
			criteria.Header.Add("To", opt.Value)
		case 'c':
			criteria.Header.Add("Cc", opt.Value)
		case 'b':
			body = true
		case 'a':
			text = true
		case 'd':
			start, end, err := lib.ParseDateRange(opt.Value)
			if err != nil {
				log.Errorf("failed to parse start date: %v", err)
				continue
			}
			if !start.IsZero() {
				criteria.SentSince = start
			}
			if !end.IsZero() {
				criteria.SentBefore = end
			}
		}
	}
	switch {
	case text:
		criteria.Text = args[optind:]
	case body:
		criteria.Body = args[optind:]
	default:
		for _, arg := range args[optind:] {
			criteria.Header.Add("Subject", arg)
		}
	}
	return criteria, nil
}

func getParsedFlag(name string) (string, error) {
	switch strings.ToLower(name) {
	case "seen":
		return imap.SeenFlag, nil
	case "flagged":
		return imap.FlaggedFlag, nil
	case "answered":
		return imap.AnsweredFlag, nil
	}
	return imap.FlaggedFlag, errors.New("Flag not suppored")
}