generated from silverbulletmd/silverbullet-plug-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodoist.ts
98 lines (76 loc) · 2.55 KB
/
todoist.ts
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
import type { QueryProviderEvent } from "$sb/app_event.ts";
import { applyQuery, evalQueryExpression, liftAttributeFilter } from "$sb/lib/query.ts";
import { evalQueryExpression } from "$sb/lib/query_expression.ts";
import { TodoistApi } from 'todoist';
import { readSecrets } from "$sb/lib/secrets_page.ts";
import { editor } from "$sb/syscalls.ts";
const projectIdMap = {};
async function getProjectIdMap(): Promise<object> {
if (Object.keys(projectIdMap).length) {
return projectIdMap;
}
const [token] = await readSecrets(["todoistToken"]);
const api = await new TodoistApi(token);
const projectList = await api.getProjects();
for (let i = 0; i < projectList.length; i++) {
projectIdMap[projectList[i].id] = projectList[i].name;
}
return projectIdMap;
}
export async function getTasks({ query }: QueryProviderEvent): Promise<any[]> {
const [token] = await readSecrets(["todoistToken"]);
const api = await new TodoistApi(token);
const filterString = liftAttributeFilter(query.filter, "filter");
if (!filterString) {
throw Error("No 'filter' specified, this is mandatory");
}
const filter: string = evalQueryExpression(filterString, {});
const tasks = await api.getTasks({filter: filter});
const projectMap = await getProjectIdMap();
for (let i = 0; i < tasks.length; i++) {
if (projectMap[tasks[i].projectId]) {
tasks[i].projectName = projectMap[tasks[i].projectId];
}
else {
tasks[i].projectName = "None";
}
}
const result = applyQuery(
query,
tasks.map((p) => flattenObject(p)),
);
return result;
}
export async function addInboxTask() {
const [token] = await readSecrets(["todoistToken"]);
const api = await new TodoistApi(token);
// If there is selected text then prefill in the prompt
let text = await editor.getText();
const selection = await editor.getSelection();
if (selection.from !== selection.to) {
text = text.substring(selection.from, selection.to);
}
else {
text = "";
}
const task = await editor.prompt("Add to Todoist Inbox:", text);
if (!task) {
return;
}
const result = await api.addTask({ content: task });
await editor.flashNotification("New task added to Todoist Inbox");
}
function flattenObject(obj: any, prefix = ""): any {
let result: any = {};
for (let [key, value] of Object.entries(obj)) {
if (prefix) {
key = prefix + "_" + key;
}
if (value && typeof value === "object") {
result = { ...result, ...flattenObject(value, key) };
} else {
result[key] = value;
}
}
return result;
}