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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
|
package api
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"task-dashboard/internal/models"
)
const (
todoistBaseURL = "https://api.todoist.com/rest/v2"
)
// TodoistClient handles interactions with the Todoist API
type TodoistClient struct {
apiKey string
baseURL string
httpClient *http.Client
}
// NewTodoistClient creates a new Todoist API client
func NewTodoistClient(apiKey string) *TodoistClient {
return &TodoistClient{
apiKey: apiKey,
baseURL: todoistBaseURL,
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
}
}
// todoistTaskResponse represents the API response structure
type todoistTaskResponse struct {
ID string `json:"id"`
Content string `json:"content"`
Description string `json:"description"`
ProjectID string `json:"project_id"`
Priority int `json:"priority"`
Labels []string `json:"labels"`
Due *struct {
Date string `json:"date"`
Datetime string `json:"datetime"`
} `json:"due"`
URL string `json:"url"`
CreatedAt string `json:"created_at"`
}
// todoistProjectResponse represents the project API response
type todoistProjectResponse struct {
ID string `json:"id"`
Name string `json:"name"`
}
// GetTasks fetches all active tasks from Todoist
func (c *TodoistClient) GetTasks(ctx context.Context) ([]models.Task, error) {
req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/tasks", nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch tasks: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("todoist API error (status %d): %s", resp.StatusCode, string(body))
}
var apiTasks []todoistTaskResponse
if err := json.NewDecoder(resp.Body).Decode(&apiTasks); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
// Fetch projects to get project names
projects, err := c.GetProjects(ctx)
projectMap := make(map[string]string)
if err == nil {
// Build map of project ID to name
for _, proj := range projects {
projectMap[proj.ID] = proj.Name
}
}
// Convert to our model
tasks := make([]models.Task, 0, len(apiTasks))
for _, apiTask := range apiTasks {
task := models.Task{
ID: apiTask.ID,
Content: apiTask.Content,
Description: apiTask.Description,
ProjectID: apiTask.ProjectID,
ProjectName: projectMap[apiTask.ProjectID],
Priority: apiTask.Priority,
Completed: false,
Labels: apiTask.Labels,
URL: apiTask.URL,
}
// Parse created_at
if createdAt, err := time.Parse(time.RFC3339, apiTask.CreatedAt); err == nil {
task.CreatedAt = createdAt
}
// Parse due date
if apiTask.Due != nil {
var dueDate time.Time
if apiTask.Due.Datetime != "" {
dueDate, err = time.Parse(time.RFC3339, apiTask.Due.Datetime)
} else if apiTask.Due.Date != "" {
dueDate, err = time.Parse("2006-01-02", apiTask.Due.Date)
}
if err == nil {
task.DueDate = &dueDate
}
}
tasks = append(tasks, task)
}
return tasks, nil
}
// GetProjects fetches all projects
func (c *TodoistClient) GetProjects(ctx context.Context) ([]models.Project, error) {
req, err := http.NewRequestWithContext(ctx, "GET", c.baseURL+"/projects", nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch projects: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("todoist API error (status %d): %s", resp.StatusCode, string(body))
}
var apiProjects []todoistProjectResponse
if err := json.NewDecoder(resp.Body).Decode(&apiProjects); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
// Convert to model
projects := make([]models.Project, 0, len(apiProjects))
for _, apiProj := range apiProjects {
projects = append(projects, models.Project{
ID: apiProj.ID,
Name: apiProj.Name,
})
}
return projects, nil
}
// CreateTask creates a new task in Todoist
func (c *TodoistClient) CreateTask(ctx context.Context, content, projectID string, dueDate *time.Time, priority int) (*models.Task, error) {
// Prepare request payload
payload := map[string]interface{}{
"content": content,
}
if projectID != "" {
payload["project_id"] = projectID
}
if dueDate != nil {
payload["due_date"] = dueDate.Format("2006-01-02")
}
if priority > 0 {
payload["priority"] = priority
}
jsonData, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
// Create POST request
req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/tasks", bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Header.Set("Content-Type", "application/json")
// Execute request
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to create task: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("todoist API error (status %d): %s", resp.StatusCode, string(body))
}
// Decode response
var apiTask todoistTaskResponse
if err := json.NewDecoder(resp.Body).Decode(&apiTask); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
// Convert to our model
task := &models.Task{
ID: apiTask.ID,
Content: apiTask.Content,
Description: apiTask.Description,
ProjectID: apiTask.ProjectID,
Priority: apiTask.Priority,
Completed: false,
Labels: apiTask.Labels,
URL: apiTask.URL,
}
// Parse created_at
if createdAt, err := time.Parse(time.RFC3339, apiTask.CreatedAt); err == nil {
task.CreatedAt = createdAt
}
// Parse due date
if apiTask.Due != nil {
var taskDueDate time.Time
if apiTask.Due.Datetime != "" {
taskDueDate, err = time.Parse(time.RFC3339, apiTask.Due.Datetime)
} else if apiTask.Due.Date != "" {
taskDueDate, err = time.Parse("2006-01-02", apiTask.Due.Date)
}
if err == nil {
task.DueDate = &taskDueDate
}
}
return task, nil
}
// CompleteTask marks a task as complete in Todoist
func (c *TodoistClient) CompleteTask(ctx context.Context, taskID string) error {
// Create POST request to close endpoint
url := fmt.Sprintf("%s/tasks/%s/close", c.baseURL, taskID)
req, err := http.NewRequestWithContext(ctx, "POST", url, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
// Execute request
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to complete task: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("todoist API error (status %d): %s", resp.StatusCode, string(body))
}
return nil
}
|