Spaces:
Running
Running
Download server/state/camera.ts from evalstate/mcp-webcam: direct link, hf CLI and curl.
- Browser
- Download file 6.74 kB
-
https://huggingface.co/spaces/evalstate/mcp-webcam/resolve/main/server/state/camera.ts
- Command line
-
hf download hf://spaces/evalstate/mcp-webcam/server/state/camera.ts
-
curl -L -o camera.ts https://huggingface.co/spaces/evalstate/mcp-webcam/resolve/main/server/state/camera.ts
6.74 kB
| import { randomUUID } from 'node:crypto'; | |
| import type * as T from '../../shared/api-types.js'; | |
| import type { CameraBridgeApi } from '../contracts.js'; | |
| interface TabRecord { | |
| tabId: string; | |
| connectedAt: string; | |
| send: (m: T.FeedMessage) => void; | |
| userAgent?: string; | |
| frozen?: boolean; | |
| deviceLabel?: string; | |
| width?: number; | |
| height?: number; | |
| pendingCaptures: number; | |
| } | |
| interface PendingCapture { | |
| requestId: string; | |
| tabId: string; | |
| timer: ReturnType<typeof setTimeout>; | |
| resolve: (result: { mimeType: string; base64: string; dataUrl: string }) => void; | |
| reject: (err: Error) => void; | |
| } | |
| export interface CameraBridgeOptions { | |
| onTabJoined?: (tabId: string) => void; | |
| onTabLeft?: (tabId: string) => void; | |
| onChange?: () => void; | |
| } | |
| const DATA_URL_RE = /^data:([^;,]+);base64,(.+)$/s; | |
| const ALLOWED_IMAGE_MIMES = new Set(['image/jpeg', 'image/png', 'image/webp']); | |
| export function parseImageDataUrl(dataUrl: string): { mimeType: string; base64: string; dataUrl: string } { | |
| const match = DATA_URL_RE.exec(dataUrl.trim()); | |
| if (!match) { | |
| throw new Error('Invalid image data URL'); | |
| } | |
| const mimeType = match[1].trim().toLowerCase(); | |
| const base64 = match[2].trim(); | |
| if (!ALLOWED_IMAGE_MIMES.has(mimeType) || base64.length === 0) { | |
| throw new Error('Invalid image data URL (allowed MIME types: image/jpeg, image/png, image/webp)'); | |
| } | |
| return { mimeType, base64, dataUrl: dataUrl.trim() }; | |
| } | |
| export function createCameraBridge(opts: CameraBridgeOptions = {}): CameraBridgeApi { | |
| const tabs = new Map<string, TabRecord>(); | |
| const pending = new Map<string, PendingCapture>(); | |
| let primaryTabId: string | null = null; | |
| function ensurePrimary(): void { | |
| if (primaryTabId !== null && tabs.has(primaryTabId)) return; | |
| const first = tabs.keys().next(); | |
| primaryTabId = first.done ? null : first.value; | |
| } | |
| function getPrimaryTab(): TabRecord | undefined { | |
| ensurePrimary(); | |
| return primaryTabId ? tabs.get(primaryTabId) : undefined; | |
| } | |
| function clearPendingForTab(tabId: string): void { | |
| for (const [reqId, entry] of pending) { | |
| if (entry.tabId === tabId) { | |
| clearTimeout(entry.timer); | |
| pending.delete(reqId); | |
| entry.reject(new Error('Camera tab disconnected before completing capture')); | |
| } | |
| } | |
| } | |
| return { | |
| addTab(tabId: string, send: (m: T.FeedMessage) => void, userAgent?: string): () => void { | |
| const existing = tabs.get(tabId); | |
| const record: TabRecord = { | |
| tabId, | |
| connectedAt: existing?.connectedAt ?? new Date().toISOString(), | |
| send, | |
| userAgent, | |
| frozen: existing?.frozen, | |
| deviceLabel: existing?.deviceLabel, | |
| width: existing?.width, | |
| height: existing?.height, | |
| pendingCaptures: existing?.pendingCaptures ?? 0, | |
| }; | |
| tabs.set(tabId, record); | |
| if (primaryTabId === null) { | |
| primaryTabId = tabId; | |
| } | |
| opts.onTabJoined?.(tabId); | |
| opts.onChange?.(); | |
| let removed = false; | |
| return () => { | |
| if (removed) return; | |
| removed = true; | |
| // Only remove if this exact record is still active (handles reconnect with same tabId) | |
| if (tabs.get(tabId) !== record) return; | |
| tabs.delete(tabId); | |
| clearPendingForTab(tabId); | |
| if (primaryTabId === tabId) { | |
| primaryTabId = null; | |
| ensurePrimary(); | |
| } | |
| opts.onTabLeft?.(tabId); | |
| opts.onChange?.(); | |
| }; | |
| }, | |
| setPrimary(tabId: string): boolean { | |
| if (!tabs.has(tabId)) return false; | |
| primaryTabId = tabId; | |
| opts.onChange?.(); | |
| return true; | |
| }, | |
| setStatus(tabId: string, s: Partial<T.CameraTabView>): void { | |
| const tab = tabs.get(tabId); | |
| if (!tab) return; | |
| if (s.frozen !== undefined) tab.frozen = s.frozen; | |
| if (s.deviceLabel !== undefined) tab.deviceLabel = s.deviceLabel; | |
| if (s.width !== undefined) tab.width = s.width; | |
| if (s.height !== undefined) tab.height = s.height; | |
| opts.onChange?.(); | |
| }, | |
| hasCamera(): boolean { | |
| return tabs.size > 0; | |
| }, | |
| requestCapture( | |
| kind: 'webcam' | 'screen', | |
| reason: string, | |
| timeoutMs: number, | |
| ): Promise<{ mimeType: string; base64: string; dataUrl: string }> { | |
| const tab = getPrimaryTab(); | |
| if (!tab) { | |
| return Promise.reject(new Error('No camera tab connected')); | |
| } | |
| const requestId = randomUUID(); | |
| tab.pendingCaptures += 1; | |
| opts.onChange?.(); | |
| return new Promise((resolve, reject) => { | |
| const timer = setTimeout(() => { | |
| const entry = pending.get(requestId); | |
| if (!entry) return; | |
| pending.delete(requestId); | |
| const t = tabs.get(entry.tabId); | |
| if (t && t.pendingCaptures > 0) { | |
| t.pendingCaptures -= 1; | |
| } | |
| opts.onChange?.(); | |
| reject(new Error(`Capture timed out after ${timeoutMs}ms`)); | |
| }, timeoutMs); | |
| timer.unref?.(); | |
| pending.set(requestId, { | |
| requestId, | |
| tabId: tab.tabId, | |
| timer, | |
| resolve, | |
| reject, | |
| }); | |
| try { | |
| tab.send({ type: 'capture', requestId, kind, reason }); | |
| } catch (err) { | |
| clearTimeout(timer); | |
| pending.delete(requestId); | |
| if (tab.pendingCaptures > 0) tab.pendingCaptures -= 1; | |
| opts.onChange?.(); | |
| reject(err instanceof Error ? err : new Error(String(err))); | |
| } | |
| }); | |
| }, | |
| resolveCapture(requestId: string, r: T.CaptureResultRequest): boolean { | |
| const entry = pending.get(requestId); | |
| if (!entry) return false; | |
| clearTimeout(entry.timer); | |
| pending.delete(requestId); | |
| const tab = tabs.get(entry.tabId); | |
| if (tab && tab.pendingCaptures > 0) { | |
| tab.pendingCaptures -= 1; | |
| } | |
| opts.onChange?.(); | |
| if (r.error) { | |
| entry.reject(new Error(r.error)); | |
| return true; | |
| } | |
| if (!r.image) { | |
| entry.reject(new Error('Capture response missing image data')); | |
| return true; | |
| } | |
| try { | |
| const parsed = parseImageDataUrl(r.image); | |
| entry.resolve(parsed); | |
| } catch (err) { | |
| entry.reject(err instanceof Error ? err : new Error(String(err))); | |
| } | |
| return true; | |
| }, | |
| views(): T.CameraTabView[] { | |
| ensurePrimary(); | |
| return Array.from(tabs.values()).map((tab) => ({ | |
| tabId: tab.tabId, | |
| connectedAt: tab.connectedAt, | |
| primary: tab.tabId === primaryTabId, | |
| userAgent: tab.userAgent, | |
| frozen: tab.frozen, | |
| deviceLabel: tab.deviceLabel, | |
| width: tab.width, | |
| height: tab.height, | |
| pendingCaptures: tab.pendingCaptures, | |
| })); | |
| }, | |
| }; | |
| } | |