aboutsummaryrefslogtreecommitdiffstats
path: root/config/triggers.go
blob: 7b461e706bb7f059c816627fb7dca034ec8e2418 (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
package config

import (
	"errors"
	"fmt"

	"github.com/go-ini/ini"
	"github.com/google/shlex"

	"git.sr.ht/~rjarry/aerc/lib/format"
	"git.sr.ht/~rjarry/aerc/log"
	"git.sr.ht/~rjarry/aerc/models"
)

type TriggersConfig struct {
	NewEmail       string `ini:"new-email"`
	ExecuteCommand func(command []string) error
}

var Triggers = &TriggersConfig{}

func parseTriggers(file *ini.File) error {
	triggers, err := file.GetSection("triggers")
	if err != nil {
		goto out
	}
	if err := triggers.MapTo(&Triggers); err != nil {
		return err
	}
out:
	log.Debugf("aerc.conf: [triggers] %#v", Triggers)
	return nil
}

func (trig *TriggersConfig) ExecTrigger(triggerCmd string,
	triggerFmt func(string) (string, error),
) error {
	if len(triggerCmd) == 0 {
		return errors.New("Trigger command empty")
	}
	triggerCmdParts, err := shlex.Split(triggerCmd)
	if err != nil {
		return err
	}

	var command []string
	for _, part := range triggerCmdParts {
		formattedPart, err := triggerFmt(part)
		if err != nil {
			return err
		}
		command = append(command, formattedPart)
	}
	return trig.ExecuteCommand(command)
}

func (trig *TriggersConfig) ExecNewEmail(
	account *AccountConfig, msg *models.MessageInfo,
) {
	err := trig.ExecTrigger(trig.NewEmail,
		func(part string) (string, error) {
			formatstr, args, err := format.ParseMessageFormat(
				part, Ui.TimestampFormat,
				Ui.ThisDayTimeFormat,
				Ui.ThisWeekTimeFormat,
				Ui.ThisYearTimeFormat,
				Ui.IconAttachment,
				format.Ctx{
					FromAddress: account.From,
					AccountName: account.Name,
					MsgInfo:     msg,
				},
			)
			if err != nil {
				return "", err
			}
			return fmt.Sprintf(formatstr, args...), nil
		})
	if err != nil {
		log.Errorf("failed to run new-email trigger: %v", err)
	}
}