aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/emersion/go-imap/commands/search.go
blob: 72f026c6412f6c9634a12a12dc1d4866b4e35e6c (plain)
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
package commands

import (
	"errors"
	"io"
	"strings"

	"github.com/emersion/go-imap"
)

// Search is a SEARCH command, as defined in RFC 3501 section 6.4.4.
type Search struct {
	Charset  string
	Criteria *imap.SearchCriteria
}

func (cmd *Search) Command() *imap.Command {
	var args []interface{}
	if cmd.Charset != "" {
		args = append(args, imap.RawString("CHARSET"), imap.RawString(cmd.Charset))
	}
	args = append(args, cmd.Criteria.Format()...)

	return &imap.Command{
		Name:      "SEARCH",
		Arguments: args,
	}
}

func (cmd *Search) Parse(fields []interface{}) error {
	if len(fields) == 0 {
		return errors.New("Missing search criteria")
	}

	// Parse charset
	if f, ok := fields[0].(string); ok && strings.EqualFold(f, "CHARSET") {
		if len(fields) < 2 {
			return errors.New("Missing CHARSET value")
		}
		if cmd.Charset, ok = fields[1].(string); !ok {
			return errors.New("Charset must be a string")
		}
		fields = fields[2:]
	}

	var charsetReader func(io.Reader) io.Reader
	charset := strings.ToLower(cmd.Charset)
	if charset != "utf-8" && charset != "us-ascii" && charset != "" {
		charsetReader = func(r io.Reader) io.Reader {
			r, _ = imap.CharsetReader(charset, r)
			return r
		}
	}

	cmd.Criteria = new(imap.SearchCriteria)
	return cmd.Criteria.ParseWithCharset(fields, charsetReader)
}