Skip to content

Commit

Permalink
add: support apply filter to existing emails
Browse files Browse the repository at this point in the history
  • Loading branch information
nasa9084 committed Jun 29, 2020
1 parent 719ddfd commit 32f20dd
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
10 changes: 9 additions & 1 deletion commands/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ func init() {
}

type ApplyCommand struct {
Target string `short:"f" long:"filename" required:"yes"`
Target string `short:"f" long:"filename" required:"yes"`
ApplyToExistingEmails bool `short:"e" long:"apply-to-existing"`
}

func (cmd *ApplyCommand) Execute([]string) error {
Expand Down Expand Up @@ -95,6 +96,13 @@ func (cmd *ApplyCommand) applyFilter(data []byte) error {
if err := c.CreateFilter(ctx, filter); err != nil {
return err
}

if cmd.ApplyToExistingEmails {
log.Printf("Apply filter %s to existing emails", filter.String())
if err := c.ApplyLabelToExistingEmail(ctx, filter); err != nil {
return err
}
}
}

return nil
Expand Down
1 change: 1 addition & 0 deletions commands/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (

var oauthScope = []string{
gmail.GmailLabelsScope,
gmail.GmailModifyScope,
gmail.GmailSettingsBasicScope,
}

Expand Down
49 changes: 49 additions & 0 deletions gmail/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,55 @@ func (c *Client) DeleteFilterByID(ctx context.Context, id string) error {
return nil
}

func (c *Client) ApplyLabelToExistingEmail(ctx context.Context, filter Filter) error {
if filter.Action.AddLabel == "" {
return nil
}

gf, err := c.convertFilterToGmail(filter)
if err != nil {
return err
}

if err := c.svc.Users.Messages.List("me").Q(filter.Criteria.String()).MaxResults(999).Pages(
ctx,
func(msgsResp *gmail.ListMessagesResponse) error {
if len(msgsResp.Messages) == 0 {
return nil
}

messageIDs := make([]string, 0, len(msgsResp.Messages))

for _, msg := range msgsResp.Messages {
messageIDs = append(messageIDs, msg.Id)
}

var begin int
for begin < len(messageIDs) {
end := begin + 1000
if len(messageIDs) < end {
end = len(messageIDs)
}
batchModifyMessagesRequest := &gmail.BatchModifyMessagesRequest{
AddLabelIds: gf.Action.AddLabelIds,
RemoveLabelIds: gf.Action.RemoveLabelIds,
Ids: messageIDs[begin:end],
}

if err := c.svc.Users.Messages.BatchModify("me", batchModifyMessagesRequest).Context(ctx).Do(); err != nil {
return err
}
begin = end
}
return nil
},
); err != nil {
return err
}

return nil
}

func (c *Client) convertFilterFromGmail(gf *gmail.Filter) Filter {
var f Filter
f.id = gf.Id
Expand Down

0 comments on commit 32f20dd

Please sign in to comment.