Fixes chicken-and-egg setup flow where new users couldn't populate the name dropdown because isConfigured required userId to already exist. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
213 lines
7.6 KiB
TypeScript
213 lines
7.6 KiB
TypeScript
const CURRENT_VERSION = "1.0.10";
|
|
const GITEA_BASE = "https://gitea.pdmarf.co.uk/pdm/stream_deck_notion_timer/raw/branch/master";
|
|
const SIGNING_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
|
MCowBQYDK2VwAyEAN7ko8TUpuPzPAJuKAZCRjV0c4ZSlou5d9pUAF6o12b4=
|
|
-----END PUBLIC KEY-----`;
|
|
|
|
function isNewerVersion(remote: string, current: string): boolean {
|
|
const parse = (v: string) => v.split(".").map(Number);
|
|
const [rMaj, rMin, rPat] = parse(remote);
|
|
const [cMaj, cMin, cPat] = parse(current);
|
|
if (rMaj !== cMaj) return rMaj > cMaj;
|
|
if (rMin !== cMin) return rMin > cMin;
|
|
return rPat > cPat;
|
|
}
|
|
|
|
function fetchWithTimeout(url: string): Promise<Response> {
|
|
const controller = new AbortController();
|
|
const timer = setTimeout(() => controller.abort(), 10_000);
|
|
return fetch(url, { signal: controller.signal }).finally(() => clearTimeout(timer));
|
|
}
|
|
|
|
async function checkForUpdates(): Promise<void> {
|
|
try {
|
|
const resp = await fetchWithTimeout(`${GITEA_BASE}/version.json`);
|
|
if (!resp.ok) return;
|
|
const { version } = await resp.json() as { version: string };
|
|
if (!/^\d+\.\d+\.\d+$/.test(version)) return;
|
|
if (!isNewerVersion(version, CURRENT_VERSION)) return;
|
|
|
|
const [pluginResp, sigResp] = await Promise.all([
|
|
fetchWithTimeout(`${GITEA_BASE}/com.pdma.notion-timer.sdPlugin/bin/plugin.js`),
|
|
fetchWithTimeout(`${GITEA_BASE}/com.pdma.notion-timer.sdPlugin/bin/plugin.js.sig`),
|
|
]);
|
|
if (!pluginResp.ok || !sigResp.ok) return;
|
|
|
|
const newCode = await pluginResp.text();
|
|
const sigBytes = Buffer.from(await sigResp.arrayBuffer());
|
|
|
|
const { verify } = await import("node:crypto");
|
|
const valid = verify(null, Buffer.from(newCode), SIGNING_PUBLIC_KEY, sigBytes);
|
|
if (!valid) {
|
|
streamDeck.logger.error("Update rejected: signature verification failed");
|
|
return;
|
|
}
|
|
|
|
const fs = await import("fs");
|
|
fs.writeFileSync(__filename, newCode);
|
|
streamDeck.logger.info(`Updated to ${version}, restarting…`);
|
|
process.exit(0);
|
|
} catch (err) {
|
|
streamDeck.logger.error(`Update check failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
}
|
|
}
|
|
|
|
import streamDeck, {
|
|
action,
|
|
KeyDownEvent,
|
|
PropertyInspectorDidAppearEvent,
|
|
SingletonAction,
|
|
WillAppearEvent,
|
|
} from "@elgato/streamdeck";
|
|
import { fetchProjects, fetchUsers, 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 onWillDisappear(ev: WillAppearEvent<TimerSettings>): Promise<void> {
|
|
this.settingsCache.delete(ev.action.id);
|
|
}
|
|
|
|
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 (!global.notionToken) {
|
|
await streamDeck.ui.sendToPropertyInspector({ event: "projects", data: [], error: "Enter your Notion API token above.", version: CURRENT_VERSION });
|
|
return;
|
|
}
|
|
const [projects, usersResult] = await Promise.all([
|
|
fetchProjects(global.notionToken, global.projectsDbId),
|
|
fetchUsers(global.notionToken).catch((err) => {
|
|
streamDeck.logger.error("Failed to fetch users:", err);
|
|
return [];
|
|
}),
|
|
]);
|
|
await streamDeck.ui.sendToPropertyInspector({ event: "projects", data: projects, users: usersResult, version: CURRENT_VERSION });
|
|
} catch (err) {
|
|
streamDeck.logger.error("Failed to fetch projects:", err);
|
|
await streamDeck.ui.sendToPropertyInspector({ event: "projects", data: [], error: String(err), version: CURRENT_VERSION });
|
|
}
|
|
}
|
|
|
|
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();
|
|
|
|
// Check for updates 10 seconds after startup to avoid disrupting initial connection
|
|
setTimeout(() => checkForUpdates(), 10_000);
|