This repository was archived by the owner on Nov 11, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
84 lines (70 loc) · 2.65 KB
/
Copy pathbackground.js
File metadata and controls
84 lines (70 loc) · 2.65 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
class BackgroundWorker {
constructor() {
}
run() {
trektor.browser.runtime.onMessage.addListener(async (msg) => {
switch (msg.action) {
case "track":
await this.track(...msg.args);
return;
case "addTask":
await this.addTask(...msg.args);
return;
default:
throw new Error(`unknown action: ${msg.action}`);
}
});
}
async track(cardId) {
const task = await this.addTask(cardId);
const card = await trektor.trelloGateway.getCard(cardId);
const cardName = this.stripStoryPointsAndTaskToken(card.name);
const response = await trektor.togglGateway.startTimeEntry(task.id, cardName);
return response.data;
}
async addTask(cardId) {
const card = await trektor.trelloGateway.getCard(cardId);
const taskPrefixes = card.labels
.map((label) => label.name.match(/(?<=#)[a-z0-9]+$/)?.[0])
.filter((prefix) => prefix !== undefined);
if (taskPrefixes.length === 0) {
throw new Error("Card has no valid project labels.");
}
if (taskPrefixes.length > 1) {
throw new Error("Card has multiple project labels.");
}
const taskPrefix = taskPrefixes[0];
let taskName = card.name.match(/(?<=#)[A-Za-z0-9_-]+/)?.[0];
if (taskName === undefined) {
taskName = `${taskPrefix}_${card.idShort}`;
await trektor.trelloGateway.updateCard(card.id, {
name: `${card.name} #${taskName}`,
});
}
const workspaces = await trektor.togglGateway.getWorkspaces();
if (workspaces.length === 0) {
throw new Error("Could not find any toggl workspaces.");
}
if (workspaces.length > 1) {
throw new Error("Found multiple toggl workspaces. Not sure how to deal with that...");
}
const allProjects = await trektor.togglGateway.getProjects(workspaces[0].id);
const projects = allProjects.filter((project) => project.name.endsWith(`(${taskPrefix})`));
if (projects.length === 0) {
throw new Error("Could not find any matching toggl project.");
}
if (projects.length > 1) {
throw new Error("Found multiple matching toggl projects. Not sure how to deal with that...");
}
const tasks = await trektor.togglGateway.getTasks(projects[0].id);
const task = tasks.find((task) => task.name === taskName);
if (task !== undefined) return task;
const response = await trektor.togglGateway.createTask(projects[0].id, taskName)
return response.data;
}
stripStoryPointsAndTaskToken(cardName) {
return cardName
.replace(/^(\s*\(\d+\))?\s*/, "") // story points, e.g. (3)
.replace(/\s*#[a-z0-9_]+\s*$/, ""); // task token, e.g. #orga_5417
}
}