summaryrefslogtreecommitdiff
path: root/main.go
blob: 097f7bd531ab82f88c363bbf78316a0cba94c28d (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
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
// This program creates tasks in Todoist, based on time specificiations in the
// cron format. It takes one argument (the path to the input file) and requires
// that your Todoist developer token be set in the TODOIST_TOKEN environment
// variable.
//
// The input file must be a text file where each line is either empty, a comment
// (starting with #), or a cron specification followed by the name of the task.
// Note that the cron specification must be provided as five whitespace
// separated fields; this program doesn't currently support all the features of
// robfig/cron (e.g. '@monthly').
//
// The input file is checked for changes each minute, and the program creates
// Todoist tasks when their cron run time occurs.
package main

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"time"

	"github.com/cenkalti/backoff/v5"
	"github.com/robfig/cron/v3"
)

type InputLine struct {
	RawSchedule, RawTask string
}

type TaskAddingJob struct {
	Schedule cron.Schedule
	Task     cron.Job
	EntryID  cron.EntryID // this doesn't fit super well, but we'll figure that out soon I guess
	Delete   bool
}

type Task struct {
	Name string
}

func (t Task) Run() {
	_, err := backoff.Retry(
		context.Background(),
		func() (bool, error) { return true, createTask(t.Name) },
	)
	if err != nil {
		log.Printf("Failed to create task '%s': %s", t.Name, err)
	}
}

var jobsFromInput = map[InputLine]TaskAddingJob{}
var todoistToken string
var httpClient = http.Client{
	Timeout: 10 * time.Second,
}

func main() {
	if err := setToken(); err != nil {
		log.Fatalf("setting token: %s", err)
	}

	p, err := inputFilePath()
	if err != nil {
		log.Fatalf("getting input file: %s", err)
	}
	log.Printf("Started watching '%s'", p)

	c := cron.New()
	c.Start()

	for {
		err = readInput(p)
		if err != nil {
			log.Printf("Error reading input: %s", err)
			goto SLEEP
		}

		for inputLine, taskAddingJob := range jobsFromInput {
			if jobsFromInput[inputLine].EntryID == 0 {
				taskAddingJob.EntryID = c.Schedule(
					jobsFromInput[inputLine].Schedule,
					jobsFromInput[inputLine].Task,
				)
				jobsFromInput[inputLine] = taskAddingJob

				log.Printf(
					"Added '%s' with recurrence '%s'",
					inputLine.RawTask,
					inputLine.RawSchedule,
				)
			} else if taskAddingJob.Delete {
				c.Remove(taskAddingJob.EntryID)
				delete(jobsFromInput, inputLine)
				log.Printf("Removed '%s'", inputLine.RawTask)
			}
		}

	SLEEP:
		time.Sleep(time.Minute)
	}

}

func setToken() error {
	token := os.Getenv("TODOIST_TOKEN")
	if token == "" {
		return fmt.Errorf("TODOIST_TOKEN env var must be present and non-empty")
	}
	todoistToken = token

	return nil
}

func inputFilePath() (string, error) {
	args := os.Args
	if len(args) != 2 {
		return "", fmt.Errorf("expected one argument (input file path), got %d", len(args)-1)
	}
	p := filepath.Clean(args[1])

	// While we're here, check that the input path actually exists and
	// is stat-able.
	if _, err := os.Stat(p); err != nil {
		return "", fmt.Errorf("cannot stat input file: %w", err)
	}

	return p, nil
}

var inputFileRe = regexp.MustCompile(`([^\s]+\s+[^\s]+\s+[^\s]+\s+[^\s]+\s+[^\s]+)\s+(.*)`)

func readInput(p string) error {
	f, err := os.Open(p)
	if err != nil {
		return fmt.Errorf("opening '%s': %w", p, err)
	}
	defer f.Close()

	previousInput := map[InputLine]struct{}{}
	for k := range jobsFromInput {
		previousInput[k] = struct{}{}
	}
	currentInput := map[InputLine]struct{}{}

	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		line := strings.TrimSpace(scanner.Text())
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}

		matches := inputFileRe.FindStringSubmatch(line)
		if matches == nil || len(matches) != 1+2 {
			log.Printf("failed to parse input line: '%s'", line)
			continue
		}

		inputLine := InputLine{
			RawSchedule: matches[1],
			RawTask:     matches[2],
		}

		currentInput[inputLine] = struct{}{}
		if _, ok := previousInput[inputLine]; ok {
			continue
		}

		schedule, err := cron.ParseStandard(inputLine.RawSchedule)
		if err != nil {
			log.Printf(
				"Failed to add '%s' with recurrence '%s': %s",
				inputLine.RawTask,
				inputLine.RawSchedule,
				err,
			)
			continue
		}

		jobsFromInput[inputLine] = TaskAddingJob{
			Schedule: schedule,
			Task:     Task{Name: inputLine.RawTask},
		}
	}
	if err := scanner.Err(); err != nil {
		return fmt.Errorf("scanning: %w", err)
	}

	// Mark stuff that we previously saw, but is now missing, for pruning.
	for k := range previousInput {
		if _, ok := currentInput[k]; !ok {
			v := jobsFromInput[k]
			v.Delete = true
			jobsFromInput[k] = v
		}
	}

	return nil
}

func createTask(task string) error {
	jsonBody := []byte(fmt.Sprintf(`{"content": %s}`, strconv.Quote(task)))
	req, err := http.NewRequest(
		http.MethodPost,
		"https://api.todoist.com/api/v1/tasks",
		bytes.NewBuffer(jsonBody),
	)
	if err != nil {
		return fmt.Errorf("creating request: %w", err)
	}
	req.Header.Add("Authorization", "Bearer "+todoistToken)
	req.Header.Set("Content-Type", "application/json")

	resp, err := httpClient.Do(req)
	if err != nil {
		return fmt.Errorf("doing request: %w", err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		bodyBytes, err := io.ReadAll(resp.Body)
		if err != nil {
			return fmt.Errorf("reading body when preparing error message (HTTP status was %d): %w", resp.StatusCode, err)
		}
		return fmt.Errorf("expected 200, got status code %d: body was %s", resp.StatusCode, strconv.Quote(string(bodyBytes)))
	}

	log.Printf("Created task '%s'", task)
	return nil
}