aboutsummaryrefslogtreecommitdiffstats
path: root/worker/imap/extensions/xgmext/search.go
blob: 42a4f2ca7b521d11c18abb2a0046be8b5d7618d9 (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
package xgmext

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

type threadIDSearch struct {
	Charset   string
	ThreadIDs []string
}

// NewThreadIDSearch return an imap.Command to search UIDs for the provided
// thread IDs using the X-GM-EXT-1 (Gmail extension)
func NewThreadIDSearch(threadIDs []string) *threadIDSearch {
	return &threadIDSearch{
		Charset:   "UTF-8",
		ThreadIDs: threadIDs,
	}
}

func (cmd *threadIDSearch) Command() *imap.Command {
	const threadSearchKey = "X-GM-THRID"

	var args []interface{}
	if cmd.Charset != "" {
		args = append(args, imap.RawString("CHARSET"))
		args = append(args, imap.RawString(cmd.Charset))
	}

	// we want to produce a search query that looks like this:
	// SEARCH CHARSET UTF-8 OR OR X-GM-THRID 1771431779961568536 \
	// X-GM-THRID 1765355745646219617 X-GM-THRID 1771500774375286796
	for i := 0; i < len(cmd.ThreadIDs)-1; i++ {
		args = append(args, imap.RawString("OR"))
	}

	for _, thrid := range cmd.ThreadIDs {
		args = append(args, imap.RawString(threadSearchKey))
		args = append(args, imap.RawString(thrid))
	}

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

type rawSearch struct {
	Charset string
	Search  string
}

func NewRawSearch(search string) *rawSearch {
	return &rawSearch{
		Charset: "UTF-8",
		Search:  search,
	}
}

func (cmd *rawSearch) Command() *imap.Command {
	const key = "X-GM-RAW"

	var args []interface{}
	if cmd.Charset != "" {
		args = append(args, imap.RawString("CHARSET"))
		args = append(args, imap.RawString(cmd.Charset))
	}

	args = append(args, imap.RawString(key))
	args = append(args, imap.RawString(cmd.Search))

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