Initial commit
This commit is contained in:
119
src/notion.ts
Normal file
119
src/notion.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
const NOTION_BASE = "https://api.notion.com/v1";
|
||||
|
||||
export interface NotionProject {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
function headers(token: string) {
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Notion-Version": "2022-06-28",
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
}
|
||||
|
||||
const BOOK_COLOR: Record<string, string> = {
|
||||
green: "📗", blue: "📘", orange: "📙", red: "📕",
|
||||
yellow: "📒", pink: "📔", purple: "📓",
|
||||
};
|
||||
|
||||
const COLOR_CIRCLE: Record<string, string> = {
|
||||
green: "🟢", blue: "🔵", red: "🔴", orange: "🟠",
|
||||
yellow: "🟡", purple: "🟣", pink: "🩷", brown: "🟤",
|
||||
gray: "⚫", lightgray: "⬜", default: "⬜",
|
||||
};
|
||||
|
||||
const ICON_NAME: Record<string, string> = {
|
||||
graduate: "🎓", science: "🔬", gears: "⚙️", comment: "💬",
|
||||
building: "🏢", chart: "📊", code: "💻", document: "📄",
|
||||
flag: "🚩", globe: "🌐", home: "🏠", link: "🔗",
|
||||
music: "🎵", person: "👤", phone: "📞", pin: "📌",
|
||||
rocket: "🚀", star: "⭐", tag: "🏷️", target: "🎯",
|
||||
};
|
||||
|
||||
function notionIconToEmoji(page: any): string {
|
||||
const icon = page?.icon;
|
||||
if (!icon) return "";
|
||||
if (icon.type === "emoji") return icon.emoji as string;
|
||||
if (icon.type === "icon") {
|
||||
const { name, color } = icon.icon ?? {};
|
||||
if (name === "book") return BOOK_COLOR[color] ?? "📚";
|
||||
if (name === "skip-forward") return `⏭ ${COLOR_CIRCLE[color] ?? ""}`.trimEnd();
|
||||
return ICON_NAME[name] ?? "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export async function fetchProjects(token: string, dbId: string): Promise<NotionProject[]> {
|
||||
const resp = await fetch(`${NOTION_BASE}/databases/${dbId}/query`, {
|
||||
method: "POST",
|
||||
headers: headers(token),
|
||||
body: JSON.stringify({
|
||||
page_size: 100,
|
||||
sorts: [{ property: "Project name", direction: "ascending" }],
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) throw new Error(`Notion error ${resp.status}: ${await resp.text()}`);
|
||||
|
||||
const data = (await resp.json()) as { results: unknown[] };
|
||||
return data.results.map((page: any) => {
|
||||
const titleArr: any[] = page.properties?.["Project name"]?.title ?? [];
|
||||
const title = titleArr.map((t: any) => t.plain_text).join("").trim() || "Untitled";
|
||||
const emoji = notionIconToEmoji(page);
|
||||
return {
|
||||
id: page.id as string,
|
||||
name: emoji ? `${emoji} ${title}` : title,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function startTimer(
|
||||
token: string,
|
||||
timingDbId: string,
|
||||
projectId: string,
|
||||
projectName: string,
|
||||
userId: string,
|
||||
): Promise<string> {
|
||||
const now = new Date().toISOString();
|
||||
const date = new Date().toLocaleDateString("en-GB");
|
||||
|
||||
const resp = await fetch(`${NOTION_BASE}/pages`, {
|
||||
method: "POST",
|
||||
headers: headers(token),
|
||||
body: JSON.stringify({
|
||||
parent: { database_id: timingDbId },
|
||||
icon: { type: "emoji", emoji: "⏱️" },
|
||||
properties: {
|
||||
Name: { title: [{ text: { content: "Timer Task" } }] },
|
||||
"Start Time": { date: { start: now } },
|
||||
Projects: { relation: [{ id: projectId }] },
|
||||
Status: { status: { name: "Running" } },
|
||||
Responsible: { people: [{ object: "user", id: userId }] },
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) throw new Error(`Failed to start timer: ${await resp.text()}`);
|
||||
|
||||
const data = (await resp.json()) as { id: string };
|
||||
return data.id;
|
||||
}
|
||||
|
||||
export async function stopTimer(token: string, entryId: string): Promise<void> {
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const resp = await fetch(`${NOTION_BASE}/pages/${entryId}`, {
|
||||
method: "PATCH",
|
||||
headers: headers(token),
|
||||
body: JSON.stringify({
|
||||
properties: {
|
||||
"End Time": { date: { start: now } },
|
||||
Status: { status: { name: "Stopped" } },
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!resp.ok) throw new Error(`Failed to stop timer: ${await resp.text()}`);
|
||||
}
|
||||
145
src/plugin.ts
Normal file
145
src/plugin.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import streamDeck, {
|
||||
action,
|
||||
KeyDownEvent,
|
||||
PropertyInspectorDidAppearEvent,
|
||||
SingletonAction,
|
||||
WillAppearEvent,
|
||||
} from "@elgato/streamdeck";
|
||||
import { fetchProjects, startTimer, stopTimer } from "./notion.js";
|
||||
|
||||
interface GlobalSettings {
|
||||
notionToken: string;
|
||||
timingDbId: string;
|
||||
projectsDbId: string;
|
||||
userId: string;
|
||||
}
|
||||
|
||||
interface TimerSettings {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
activeEntryId: string | null;
|
||||
}
|
||||
|
||||
const HARDCODED = {
|
||||
timingDbId: "2ec93117da3a80799ee2cf91244ee264",
|
||||
projectsDbId: "cd65c760-0f0a-4d6e-a262-d572c9e31585",
|
||||
};
|
||||
|
||||
async function getGlobal(): Promise<GlobalSettings> {
|
||||
const stored = await streamDeck.settings.getGlobalSettings<GlobalSettings>();
|
||||
return { ...stored, ...HARDCODED };
|
||||
}
|
||||
|
||||
function isConfigured(g: GlobalSettings): boolean {
|
||||
return !!(g.notionToken && g.userId);
|
||||
}
|
||||
|
||||
// Strip leading emoji characters so the button title shows just the project name
|
||||
function buttonTitle(projectName: string): string {
|
||||
return projectName.replace(/^[\p{Extended_Pictographic}\uFE0F\s]+/u, "").trim();
|
||||
}
|
||||
|
||||
@action({ UUID: "com.pdma.notion-timer.toggle" })
|
||||
class TimerToggle extends SingletonAction<TimerSettings> {
|
||||
private settingsCache = new Map<string, TimerSettings>();
|
||||
|
||||
async onWillAppear(ev: WillAppearEvent<TimerSettings>): Promise<void> {
|
||||
this.settingsCache.set(ev.action.id, ev.payload.settings);
|
||||
const { activeEntryId, projectName } = ev.payload.settings;
|
||||
const title = buttonTitle(projectName || "");
|
||||
if (activeEntryId) {
|
||||
await Promise.all([ev.action.setState(1), ev.action.setTitle(`⏱ ${title}`)]);
|
||||
} else {
|
||||
await Promise.all([ev.action.setState(0), ev.action.setTitle(title)]);
|
||||
}
|
||||
}
|
||||
|
||||
async onPropertyInspectorDidAppear(ev: PropertyInspectorDidAppearEvent<TimerSettings>): Promise<void> {
|
||||
try {
|
||||
const global = await getGlobal();
|
||||
if (!isConfigured(global)) {
|
||||
await streamDeck.ui.sendToPropertyInspector({ event: "projects", data: [], error: "Configure Notion credentials in plugin settings first." });
|
||||
return;
|
||||
}
|
||||
const projects = await fetchProjects(global.notionToken, global.projectsDbId);
|
||||
await streamDeck.ui.sendToPropertyInspector({ event: "projects", data: projects });
|
||||
} catch (err) {
|
||||
streamDeck.logger.error("Failed to fetch projects:", err);
|
||||
await streamDeck.ui.sendToPropertyInspector({ event: "projects", data: [], error: String(err) });
|
||||
}
|
||||
}
|
||||
|
||||
async onKeyDown(ev: KeyDownEvent<TimerSettings>): Promise<void> {
|
||||
this.settingsCache.set(ev.action.id, ev.payload.settings);
|
||||
const global = await getGlobal();
|
||||
const { projectId, projectName, activeEntryId } = ev.payload.settings;
|
||||
const title = buttonTitle(projectName || "");
|
||||
|
||||
if (!isConfigured(global)) {
|
||||
await ev.action.showAlert();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!projectId) {
|
||||
await ev.action.showAlert();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (activeEntryId) {
|
||||
await stopTimer(global.notionToken, activeEntryId);
|
||||
const stopped = { ...ev.payload.settings, activeEntryId: null };
|
||||
await ev.action.setSettings(stopped);
|
||||
this.settingsCache.set(ev.action.id, stopped);
|
||||
await ev.action.setState(0);
|
||||
await ev.action.setTitle(title);
|
||||
await ev.action.showOk();
|
||||
} else {
|
||||
// Stop any other running timer first
|
||||
for (const other of this.actions) {
|
||||
if (other.id === ev.action.id) continue;
|
||||
const otherSettings = this.settingsCache.get(other.id);
|
||||
if (otherSettings?.activeEntryId) {
|
||||
await stopTimer(global.notionToken, otherSettings.activeEntryId);
|
||||
const stopped = { ...otherSettings, activeEntryId: null };
|
||||
await other.setSettings(stopped);
|
||||
this.settingsCache.set(other.id, stopped);
|
||||
await other.setState(0);
|
||||
await other.setTitle(buttonTitle(otherSettings.projectName || ""));
|
||||
}
|
||||
}
|
||||
|
||||
const entryId = await startTimer(
|
||||
global.notionToken,
|
||||
global.timingDbId,
|
||||
projectId,
|
||||
projectName,
|
||||
global.userId,
|
||||
);
|
||||
const started = { ...ev.payload.settings, activeEntryId: entryId };
|
||||
await ev.action.setSettings(started);
|
||||
this.settingsCache.set(ev.action.id, started);
|
||||
await ev.action.setState(1);
|
||||
await ev.action.setTitle(`⏱ ${title}`);
|
||||
await ev.action.showOk();
|
||||
}
|
||||
} catch (err) {
|
||||
streamDeck.logger.error("Timer toggle failed:", err);
|
||||
await ev.action.showAlert();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const timerAction = new TimerToggle();
|
||||
streamDeck.actions.registerAction(timerAction);
|
||||
|
||||
// v2 requires using streamDeck.ui.onSendToPlugin — the SingletonAction method does not fire
|
||||
streamDeck.ui.onSendToPlugin<{ event: string; settings?: TimerSettings }>(async (ev) => {
|
||||
if (ev.payload.event === "saveSettings" && ev.payload.settings) {
|
||||
await ev.action.setSettings(ev.payload.settings);
|
||||
const title = buttonTitle(ev.payload.settings.projectName || "");
|
||||
if (title) await ev.action.setTitle(title);
|
||||
}
|
||||
});
|
||||
|
||||
streamDeck.connect();
|
||||
Reference in New Issue
Block a user