Repository navigation
Expand file tree
/
Copy pathplugin.js
More file actions
394 lines (341 loc) · 13.9 KB
/
Copy pathplugin.js
File metadata and controls
394 lines (341 loc) · 13.9 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// Notion Tasks - Super Productivity issue provider plugin
//
// Pulls pages from a Notion database whose date falls in the current week
// (Monday to Sunday, local time) and are not yet completed. Completing the task
// in Super Productivity checks the Notion "done" checkbox, and vice versa.
// See REDESIGN.md for the design and the reasoning behind it.
const NOTION_API = 'https://api.notion.com/v1';
const NOTION_VERSION = '2022-06-28';
const DEFAULT_DONE_PROPERTY = 'Completed';
const DEFAULT_DATE_PROPERTY = 'Date';
// Name of the sync value SP compares and pushes for the isDone mapping.
// Independent of the Notion property name, which is configurable.
const DONE_FIELD = 'isCompleted';
const MAX_RETRIES = 3;
const PAGE_SIZE = 100;
const SEARCH_LIMIT = 50;
// ===== CONFIG =====
function readConfig(config) {
return {
apiToken: String(config.apiToken || '').trim(),
databaseId: normalizeId(config.databaseId),
doneProperty: String(config.doneProperty || '').trim() || DEFAULT_DONE_PROPERTY,
dateProperty: String(config.dateProperty || '').trim() || DEFAULT_DATE_PROPERTY,
titleProperty: String(config.titleProperty || '').trim(),
};
}
// Accepts a raw ID or a pasted Notion URL and returns the 32-char ID.
function normalizeId(value) {
const str = String(value || '').trim();
const match = str.replace(/-/g, '').match(/[0-9a-f]{32}/i);
return match ? match[0] : str;
}
// ===== HTTP =====
// Retries with exponential backoff on Notion's rate limit (HTTP 429) and on
// network failures (status 0, e.g. a transient DNS lookup failure).
function isRetryable(error) {
return error?.status === 429 || error?.status === 0;
}
async function withRetry(operation) {
for (let attempt = 0; ; attempt++) {
try {
return await operation();
} catch (error) {
if (!isRetryable(error) || attempt >= MAX_RETRIES) {
throw error;
}
await new Promise((resolve) => setTimeout(resolve, 1000 * 2 ** attempt));
}
}
}
// Turns an HTTP error into a readable message, including Notion's own error
// code and message when the response body has them.
function describeError(error) {
const body = error?.error;
if (body && typeof body === 'object' && body.message) {
return `${error.status} ${body.code || ''}: ${body.message.replace(/\.$/, '')}`;
}
if (error?.status === 0) {
return 'Network error: could not reach api.notion.com';
}
if (error?.status) {
return `HTTP ${error.status} ${error.statusText || ''}`.trim();
}
if (error?.name === 'TimeoutError') {
return 'Request to Notion timed out';
}
return error?.message || String(error);
}
function reportError(context, error) {
const message = describeError(error);
PluginAPI.log.err(`[Notion Tasks] ${context}: ${message}`);
return message;
}
// Logs a readable message for a failed callback, then rethrows so SP's own
// error handling (snacks, retry on next poll) still applies.
async function logFailure(context, operation) {
try {
return await operation();
} catch (error) {
reportError(context, error);
throw error;
}
}
function getDatabase(cfg, http) {
return withRetry(() => http.get(`${NOTION_API}/databases/${cfg.databaseId}`));
}
// Queries the database and follows pagination until `limit` results or the end.
async function queryDatabase(cfg, http, body, limit = Infinity) {
const results = [];
let cursor;
do {
const page = await withRetry(() =>
http.post(`${NOTION_API}/databases/${cfg.databaseId}/query`, {
...body,
page_size: PAGE_SIZE,
...(cursor ? { start_cursor: cursor } : {}),
}),
);
results.push(...(page.results || []));
cursor = page.has_more ? page.next_cursor : null;
} while (cursor && results.length < limit);
return results.slice(0, limit);
}
// ===== SCHEMA =====
// Finds a property by name: exact match first, then case-insensitive, so
// "completed" in the config matches a Notion property called "Completed".
function findPropertyName(properties, name) {
if (!properties || !name) return undefined;
if (Object.prototype.hasOwnProperty.call(properties, name)) return name;
const wanted = name.trim().toLowerCase();
return Object.keys(properties).find((key) => key.trim().toLowerCase() === wanted);
}
// Resolves the configured property names to Notion's exact spelling and checks
// their types. Cached per database and configured names; testConnection refreshes it.
const schemaCache = new Map();
async function resolveSchema(cfg, http, { refresh = false } = {}) {
const cacheKey = [cfg.databaseId, cfg.doneProperty, cfg.dateProperty, cfg.titleProperty].join('|');
if (!refresh && schemaCache.has(cacheKey)) return schemaCache.get(cacheKey);
const db = await getDatabase(cfg, http);
const props = db.properties || {};
const done = findPropertyName(props, cfg.doneProperty);
const date = findPropertyName(props, cfg.dateProperty);
const title = cfg.titleProperty
? findPropertyName(props, cfg.titleProperty)
: Object.keys(props).find((key) => props[key].type === 'title');
const errors = [];
const check = (resolved, configured, type, label) => {
if (!resolved) {
errors.push(`no ${label} property named "${configured}"`);
} else if (props[resolved].type !== type) {
errors.push(`"${resolved}" is a ${props[resolved].type} property, not a ${type}`);
}
};
check(done, cfg.doneProperty, 'checkbox', 'checkbox');
check(date, cfg.dateProperty, 'date', 'date');
if (!title) errors.push(cfg.titleProperty ? `no title property named "${cfg.titleProperty}"` : 'database has no title property');
if (errors.length) throw new Error(`Notion database: ${errors.join('; ')}`);
const schema = { done, date, title };
schemaCache.set(cacheKey, schema);
return schema;
}
// ===== DATES =====
function toLocalDateString(date) {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
// Monday to Sunday of the current week, local time, as YYYY-MM-DD strings.
function getCurrentWeekRange(now = new Date()) {
const monday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const daysSinceMonday = (monday.getDay() + 6) % 7;
monday.setDate(monday.getDate() - daysSinceMonday);
const sunday = new Date(monday);
sunday.setDate(monday.getDate() + 6);
return { start: toLocalDateString(monday), end: toLocalDateString(sunday) };
}
// ===== MAPPING =====
function plainText(richText) {
return (richText || []).map((part) => part.plain_text || '').join('');
}
function getPageTitle(page) {
const titleProp = Object.values(page.properties || {}).find((prop) => prop.type === 'title');
return plainText(titleProp?.title) || 'Untitled';
}
// Maps a Notion page to the shape SP uses both for search results and issues.
// The id is used exactly as Notion returns it so SP's duplicate check works.
function mapPage(page, cfg) {
const props = page.properties || {};
const isCompleted = props[findPropertyName(props, cfg.doneProperty)]?.checkbox === true;
const date = props[findPropertyName(props, cfg.dateProperty)]?.date;
return {
id: page.id,
title: getPageTitle(page),
url: page.url,
state: isCompleted ? 'Completed' : 'Open',
status: isCompleted ? 'Completed' : 'Open',
date: date?.start || undefined,
lastUpdated: new Date(page.last_edited_time).getTime(),
[DONE_FIELD]: isCompleted,
};
}
function toPageUrl(pageId) {
return `https://www.notion.so/${String(pageId).replace(/-/g, '')}`;
}
// ===== PROVIDER =====
PluginAPI.registerIssueProvider({
configFields: [
{
key: 'apiToken',
type: 'password',
label: 'Notion integration token',
description: 'Internal integration secret (starts with "ntn_"). The integration needs access to the database.',
required: true,
},
{
key: 'apiTokenHelp',
type: 'link',
label: 'Create a Notion integration',
url: 'https://www.notion.so/profile/integrations',
},
{
key: 'databaseId',
type: 'input',
label: 'Database ID',
description: 'The 32-character ID from the database URL (before "?v="), or paste the whole URL.',
required: true,
},
{
key: 'doneProperty',
type: 'input',
label: 'Done checkbox property',
description: `Checkbox property that marks a task as done. Default: "${DEFAULT_DONE_PROPERTY}".`,
advanced: true,
},
{
key: 'dateProperty',
type: 'input',
label: 'Date property',
description: `Date property used to import this week's tasks. Default: "${DEFAULT_DATE_PROPERTY}".`,
advanced: true,
},
{
key: 'titleProperty',
type: 'input',
label: 'Title property',
description: "Leave empty to use the database's title property.",
advanced: true,
},
],
getHeaders(config) {
return {
Authorization: `Bearer ${readConfig(config).apiToken}`,
'Notion-Version': NOTION_VERSION,
'Content-Type': 'application/json',
};
},
// Throws on failure instead of returning false: SP's dialog then shows
// "Connection failed: <message>" rather than a bare "Connection failed".
async testConnection(config, http) {
const cfg = readConfig(config);
PluginAPI.log.log(`[Notion Tasks] Testing connection to database ${cfg.databaseId || '(empty)'}`);
let schema;
try {
schema = await resolveSchema(cfg, http, { refresh: true });
} catch (error) {
const message = reportError(`testConnection (database ${cfg.databaseId})`, error);
const hint = error?.status === 404
? '. Connect the integration to the database (••• → Connections) and use the ID of the database itself, not a page or linked view'
: '';
throw new Error(`${message}${hint}`);
}
PluginAPI.log.log(`[Notion Tasks] Connection OK (done: "${schema.done}", date: "${schema.date}", title: "${schema.title}")`);
return true;
},
// Automatic import: this week's pages that are not completed.
async getNewIssuesForBacklog(config, http) {
const cfg = readConfig(config);
const week = getCurrentWeekRange();
const pages = await logFailure('import', async () => {
const schema = await resolveSchema(cfg, http);
return queryDatabase(cfg, http, {
filter: {
and: [
{ property: schema.date, date: { on_or_after: week.start } },
{ property: schema.date, date: { on_or_before: week.end } },
{ property: schema.done, checkbox: { equals: false } },
],
},
sorts: [{ property: schema.date, direction: 'ascending' }],
});
});
return pages.map((page) => mapPage(page, cfg));
},
// Manual search: the whole database, so older tasks can be added by hand.
async searchIssues(searchTerm, config, http) {
const cfg = readConfig(config);
const term = String(searchTerm || '').trim();
const body = { sorts: [{ timestamp: 'last_edited_time', direction: 'descending' }] };
const pages = await logFailure('search', async () => {
if (term) {
const schema = await resolveSchema(cfg, http);
body.filter = { property: schema.title, title: { contains: term } };
}
return queryDatabase(cfg, http, body, SEARCH_LIMIT);
});
return pages.map((page) => mapPage(page, cfg));
},
async getById(issueId, config, http) {
const cfg = readConfig(config);
const page = await logFailure(`getById ${issueId}`, () =>
withRetry(() => http.get(`${NOTION_API}/pages/${issueId}`)),
);
return mapPage(page, cfg);
},
getIssueLink(issueId) {
return toPageUrl(issueId);
},
issueDisplay: [
{ field: 'title', label: 'Task', type: 'link', linkField: 'url' },
{ field: 'state', label: 'Status', type: 'text' },
{ field: 'date', label: 'Date', type: 'text', hideEmpty: true },
],
fieldMappings: [
{
taskField: 'isDone',
issueField: DONE_FIELD,
defaultDirection: 'both',
toIssueValue: (taskValue) => !!taskValue,
toTaskValue: (issueValue) => issueValue === true,
},
{
taskField: 'title',
issueField: 'title',
defaultDirection: 'pullOnly',
toIssueValue: (taskValue) => String(taskValue ?? ''),
toTaskValue: (issueValue) => String(issueValue ?? ''),
},
],
extractSyncValues(issue) {
return {
[DONE_FIELD]: issue[DONE_FIELD],
title: issue.title,
};
},
// Only the done checkbox is ever written to Notion.
async updateIssue(id, changes, config, http) {
if (!Object.prototype.hasOwnProperty.call(changes, DONE_FIELD)) return;
const cfg = readConfig(config);
await logFailure(`updateIssue ${id}`, async () => {
const schema = await resolveSchema(cfg, http);
return withRetry(() =>
http.patch(`${NOTION_API}/pages/${id}`, {
properties: {
[schema.done]: { checkbox: !!changes[DONE_FIELD] },
},
}),
);
});
},
});