2019-08-28 06:39:07 +02:00
|
|
|
package imap
|
|
|
|
|
|
|
|
import (
|
2020-07-24 10:36:19 +02:00
|
|
|
"errors"
|
|
|
|
"strings"
|
|
|
|
|
2019-08-28 06:39:07 +02:00
|
|
|
"github.com/emersion/go-imap"
|
2019-09-09 22:37:45 +02:00
|
|
|
|
|
|
|
"git.sr.ht/~sircmpwn/getopt"
|
2019-08-28 06:39:07 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func parseSearch(args []string) (*imap.SearchCriteria, error) {
|
|
|
|
criteria := imap.NewSearchCriteria()
|
2022-07-05 21:48:40 +02:00
|
|
|
if len(args) == 0 {
|
|
|
|
return criteria, nil
|
|
|
|
}
|
2019-08-28 06:39:07 +02:00
|
|
|
|
2020-07-24 10:36:19 +02:00
|
|
|
opts, optind, err := getopt.Getopts(args, "rubax:X:t:H:f:c:")
|
2019-08-28 06:39:07 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-09-09 22:37:45 +02:00
|
|
|
body := false
|
|
|
|
text := false
|
2019-08-28 06:39:07 +02:00
|
|
|
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)
|
2020-07-24 10:36:19 +02:00
|
|
|
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)
|
|
|
|
}
|
2019-08-28 06:39:07 +02:00
|
|
|
case 'H':
|
|
|
|
// TODO
|
2019-09-09 22:37:45 +02:00
|
|
|
case 'f':
|
|
|
|
criteria.Header.Add("From", opt.Value)
|
2019-09-20 18:26:17 +02:00
|
|
|
case 't':
|
|
|
|
criteria.Header.Add("To", opt.Value)
|
|
|
|
case 'c':
|
|
|
|
criteria.Header.Add("Cc", opt.Value)
|
2019-09-09 22:37:45 +02:00
|
|
|
case 'b':
|
|
|
|
body = true
|
2019-09-20 18:26:17 +02:00
|
|
|
case 'a':
|
2019-09-09 22:37:45 +02:00
|
|
|
text = true
|
2019-08-28 06:39:07 +02:00
|
|
|
}
|
|
|
|
}
|
2022-07-31 14:32:48 +02:00
|
|
|
switch {
|
|
|
|
case text:
|
2019-09-09 22:37:45 +02:00
|
|
|
criteria.Text = args[optind:]
|
2022-07-31 14:32:48 +02:00
|
|
|
case body:
|
2019-09-09 22:37:45 +02:00
|
|
|
criteria.Body = args[optind:]
|
2022-07-31 14:32:48 +02:00
|
|
|
default:
|
2019-09-09 22:37:45 +02:00
|
|
|
for _, arg := range args[optind:] {
|
|
|
|
criteria.Header.Add("Subject", arg)
|
|
|
|
}
|
2019-08-28 06:39:07 +02:00
|
|
|
}
|
|
|
|
return criteria, nil
|
|
|
|
}
|
2020-07-24 10:36:19 +02:00
|
|
|
|
|
|
|
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")
|
|
|
|
}
|