/** * Node.js Screenshare Bot * Uses Playwright for browser automation and LiveKit for WebRTC streaming */ import { chromium, type Browser, type Page } from 'playwright'; import { Room, RoomEvent, type RemoteParticipant, VideoSource, VideoFrame, VideoBufferType, LocalVideoTrack, TrackSource, TrackPublishOptions } from '@livekit/rtc-node'; import { createClient, type SupabaseClient, type RealtimeChannel } from '@supabase/supabase-js'; import sharp from 'sharp'; import type { BotConfig, BotStatus, SlideCommand } from './types'; export class ScreenshareBot { private browser: Browser | null = null; private page: Page | null = null; private room: Room | null = null; private supabaseClient: SupabaseClient | null = null; private realtimeChannel: RealtimeChannel | null = null; private captureInterval: NodeJS.Timeout | null = null; private videoSource: VideoSource | null = null; private videoTrack: LocalVideoTrack | null = null; private config: BotConfig; private status: BotStatus['status'] = 'spawning'; private isRunning = false; constructor(config: BotConfig) { this.config = config; } /** * Start the bot: launch browser, connect to LiveKit, start streaming */ async start(): Promise { try { console.log(`[Bot ${this.config.botId}] Starting...`); this.status = 'spawning'; // 1. Launch Playwright browser await this.launchBrowser(); // 2. Navigate to deck URL await this.navigateToDeck(); // 3. Connect to LiveKit room await this.connectToLiveKit(); // 4. Start screenshot capture and streaming await this.startCapture(); // 5. Subscribe to Supabase slide control (will be added later) await this.setupSlideControl(); this.status = 'running'; this.isRunning = true; console.log(`[Bot ${this.config.botId}] Successfully started and streaming`); } catch (error) { this.status = 'error'; console.error(`[Bot ${this.config.botId}] Start failed:`, error); await this.stop(); throw error; } } /** * Launch headless Chromium browser */ private async launchBrowser(): Promise { console.log(`[Bot ${this.config.botId}] Launching browser...`); this.browser = await chromium.launch({ headless: true, args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-accelerated-2d-canvas', '--no-first-run', '--no-zygote', '--disable-gpu' ] }); this.page = await this.browser.newPage({ viewport: { width: 1920, height: 1080 } }); console.log(`[Bot ${this.config.botId}] Browser launched`); } /** * Navigate to the slidev deck URL */ private async navigateToDeck(): Promise { if (!this.page) { throw new Error('Page not initialized'); } console.log(`[Bot ${this.config.botId}] Navigating to deck: ${this.config.deckUrl}`); await this.page.goto(this.config.deckUrl, { waitUntil: 'networkidle', timeout: 30000 }); // Wait for slidev to load await this.page.waitForTimeout(2000); console.log(`[Bot ${this.config.botId}] Deck loaded`); } /** * Connect to LiveKit room with screenshare token */ private async connectToLiveKit(): Promise { console.log(`[Bot ${this.config.botId}] Connecting to LiveKit room: ${this.config.roomName}`); this.room = new Room(); // Set up room event handlers this.room.on(RoomEvent.Connected, () => { console.log(`[Bot ${this.config.botId}] Connected to LiveKit room`); }); this.room.on(RoomEvent.Disconnected, () => { console.log(`[Bot ${this.config.botId}] Disconnected from LiveKit room`); this.isRunning = false; }); this.room.on(RoomEvent.ParticipantConnected, (participant: RemoteParticipant) => { console.log(`[Bot ${this.config.botId}] Participant joined: ${participant.identity}`); }); // Connect to room await this.room.connect(this.config.livekitUrl, this.config.screenshareToken); console.log(`[Bot ${this.config.botId}] Successfully connected to LiveKit`); // Create video source and track for screenshare this.videoSource = new VideoSource(1920, 1080); this.videoTrack = LocalVideoTrack.createVideoTrack('screenshare', this.videoSource); // Publish track with screenshare source type const publishOptions = new TrackPublishOptions({ source: TrackSource.SOURCE_SCREENSHARE }); await this.room.localParticipant?.publishTrack(this.videoTrack, publishOptions); console.log(`[Bot ${this.config.botId}] Video track published`); } /** * Start screenshot capture loop and stream to LiveKit */ private async startCapture(): Promise { if (!this.page || !this.room) { throw new Error('Page or Room not initialized'); } console.log(`[Bot ${this.config.botId}] Starting screenshot capture at 30fps...`); const FPS = 30; const INTERVAL_MS = 1000 / FPS; // Capture and publish frames to LiveKit this.captureInterval = setInterval(() => { void (async () => { try { if (!this.isRunning || !this.page || !this.videoSource) { return; } // Capture screenshot with explicit timeout const pngBuffer = await this.page.screenshot({ type: 'png', fullPage: false, timeout: 20000, // 20 second timeout to allow Slidev deck to fully render animations: 'disabled' // Don't wait for animations to complete }); // Decode PNG to raw RGBA buffer using sharp const { data, info } = await sharp(pngBuffer) .ensureAlpha() .raw() .toBuffer({ resolveWithObject: true }); // Create VideoFrame and publish to LiveKit const frame = new VideoFrame( data, info.width, info.height, VideoBufferType.RGBA ); // Capture frame with microsecond timestamp const timestampUs = BigInt(Date.now() * 1000); this.videoSource.captureFrame(frame, timestampUs); } catch (error) { console.error(`[Bot ${this.config.botId}] Frame capture/publish error:`, error); // Don't throw - continue with next frame } })(); }, INTERVAL_MS); console.log(`[Bot ${this.config.botId}] Capture loop started`); } /** * Set up Supabase Realtime listener for slide control commands */ private async setupSlideControl(): Promise { const supabaseUrl = process.env.SUPABASE_URL; const supabaseKey = process.env.SUPABASE_SERVICE_KEY; if (!supabaseUrl || !supabaseKey) { console.warn(`[Bot ${this.config.botId}] Supabase not configured, skipping slide control`); return; } console.log(`[Bot ${this.config.botId}] Setting up Supabase slide control...`); this.supabaseClient = createClient(supabaseUrl, supabaseKey); // Subscribe to slide control channel for this session this.realtimeChannel = this.supabaseClient .channel(`slide_control:${this.config.sessionId}`) .on('broadcast', { event: 'slide_command' }, (payload: { payload: SlideCommand }) => { void (async () => { const command = payload.payload; console.log(`[Bot ${this.config.botId}] Received slide command:`, command); await this.handleSlideCommand(command); })(); }) .subscribe(); console.log(`[Bot ${this.config.botId}] Subscribed to slide control channel`); } /** * Handle slide navigation commands */ private async handleSlideCommand(command: SlideCommand): Promise { if (!this.page) { console.warn(`[Bot ${this.config.botId}] Cannot handle command - page not initialized`); return; } try { switch (command.action) { case 'next': await this.page.keyboard.press('ArrowRight'); console.log(`[Bot ${this.config.botId}] Navigated to next slide`); break; case 'prev': await this.page.keyboard.press('ArrowLeft'); console.log(`[Bot ${this.config.botId}] Navigated to previous slide`); break; case 'goto': if (command.slide_number !== undefined) { // In slidev, you can press a number then Enter to go to that slide await this.page.keyboard.type(command.slide_number.toString()); await this.page.keyboard.press('Enter'); console.log(`[Bot ${this.config.botId}] Jumped to slide ${command.slide_number}`); } break; default: console.warn(`[Bot ${this.config.botId}] Unknown command:`, command.action); } } catch (error) { console.error(`[Bot ${this.config.botId}] Error handling slide command:`, error); } } /** * Stop the bot and clean up resources */ async stop(): Promise { console.log(`[Bot ${this.config.botId}] Stopping...`); this.isRunning = false; this.status = 'stopping'; try { // Stop capture loop if (this.captureInterval) { clearInterval(this.captureInterval); this.captureInterval = null; } // Unsubscribe from Supabase if (this.realtimeChannel) { await this.realtimeChannel.unsubscribe(); this.realtimeChannel = null; } // Unpublish and clean up video track if (this.videoTrack && this.room) { try { await this.room.localParticipant?.unpublishTrack(this.videoTrack.sid); this.videoTrack = null; this.videoSource = null; } catch (error) { console.error(`[Bot ${this.config.botId}] Error unpublishing video track:`, error); } } // Disconnect from LiveKit if (this.room) { await this.room.disconnect(); this.room = null; } // Close browser if (this.browser) { await this.browser.close(); this.browser = null; this.page = null; } this.status = 'stopped'; console.log(`[Bot ${this.config.botId}] Stopped successfully`); } catch (error) { console.error(`[Bot ${this.config.botId}] Error during stop:`, error); this.status = 'error'; throw error; } } /** * Get current bot status */ getStatus(): BotStatus { return { botId: this.config.botId, status: this.status, roomName: this.config.roomName, sessionId: this.config.sessionId, createdAt: new Date().toISOString() }; } }