All files / src/services session-sync-service.ts

69.78% Statements 127/182
65% Branches 13/20
87.5% Functions 7/8
69.78% Lines 127/182

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 1831x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x                                                                 1x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 14x 14x 14x 14x 14x                 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x             1x 1x 14x 14x 14x 14x 14x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x   2x 1x 1x 1x 1x 1x 1x 1x 1x 2x     2x 14x 14x 14x 14x 14x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 1x 1x 1x 2x     2x 14x  
import { getSupabase } from '../auth/supabaseClient';
import { RealtimeChannel } from '@supabase/supabase-js';
 
export class SessionSyncService {
    private channel?: RealtimeChannel;
    private sessionId?: string;
    private onParticipantChangeCallback?: (participants: any[]) => void;
    
    /**
     * Join a session and announce your presence
     */
    async joinSession(sessionId: string, githubUsername: string, peerNumber: number) {
        const supabase = getSupabase();
        this.sessionId = sessionId;
        
        try {
            // Get current user
            const { data: { user } } = await supabase.auth.getUser();
            if (!user) {
                console.error('[SessionSync] No authenticated user');
                return;
            }

            // Insert/update participant record
            const { error } = await supabase
                .from('session_participants')
                .upsert({
                    session_id: sessionId,
                    user_id: user.id,
                    github_username: githubUsername,
                    peer_number: peerNumber,
                    joined_at: new Date().toISOString(),
                    left_at: null
                }, { 
                    onConflict: 'session_id,peer_number'
                });
        

            if (error) {
                console.error('[SessionSync] Failed to announce presence:', error);
                return;
            }

            console.log('[SessionSync] Successfully announced presence:', githubUsername);

            // Subscribe to changes
            this.subscribeToSession(sessionId);
        } catch (err) {
            console.error('[SessionSync] Error joining session:', err);
        }
    }
 
    /**
     * Subscribe to participant changes for this session
     */
    private subscribeToSession(sessionId: string) {
        const supabase = getSupabase();
 
        this.channel = supabase
            .channel(`session_${sessionId}`)
            .on(
                'postgres_changes',
                {
                    event: '*',
                    schema: 'public',
                    table: 'session_participants',
                    filter: `session_id=eq.${sessionId}`
                },
                (payload) => {
                    console.log('[SessionSync] Participant change:', payload);
                    this.handleParticipantChange(payload);
                }
            )
            .subscribe((status) => {
                console.log('[SessionSync] Subscription status:', status);
            });
    }
 
    /**
     * Handle participant changes from Supabase
     */
    private async handleParticipantChange(payload: any) {
        console.log('[SessionSync] New/updated participant:', payload.new);
        
        // Reload all participants and notify callback
        if (this.sessionId && this.onParticipantChangeCallback) {
            const participants = await this.getParticipants(this.sessionId);
            this.onParticipantChangeCallback(participants);
        }
    }
 
    /**
     * Set callback for participant changes
     */
    setOnParticipantChange(callback: (participants: any[]) => void) {
        this.onParticipantChangeCallback = callback;
    }
 
    /**
     * Get all current participants in the session
     */
    async getParticipants(sessionId: string): Promise<any[]> {
        const supabase = getSupabase();
 
        const { data, error } = await supabase
            .from('session_participants')
            .select('*')
            .eq('session_id', sessionId)
            .is('left_at', null)
            .order('joined_at', { ascending: true });

        if (error) {
            console.error('[SessionSync] Failed to get participants:', error);
            return [];
        }

        return data || [];
    }
 
    /**
     * Leave the session - deletes the participant record
     */
    async leaveSession() {
        if (!this.sessionId) return;
 
        const supabase = getSupabase();
 
        try {
            const { data: { user } } = await supabase.auth.getUser();
            if (!user) return;
 
            // Delete the participant record
            const { error } = await supabase
                .from('session_participants')
                .delete()
                .eq('session_id', this.sessionId)
                .eq('user_id', user.id);
 
            if (error) {
                console.error('[SessionSync] Error deleting participant record:', error);
            } else {
                console.log('[SessionSync] Successfully left session and removed from participants');
            }
 
            // Unsubscribe
            if (this.channel) {
                await this.channel.unsubscribe();
                this.channel = undefined;
            }
        } catch (err) {
            console.error('[SessionSync] Error leaving session:', err);
        }
    }
 
    /**
     * Cleanup all participants for a session (host ending session)
     */
    async cleanupSession(sessionId: string) {
        const supabase = getSupabase();
 
        try {
            const { error } = await supabase
                .from('session_participants')
                .delete()
                .eq('session_id', sessionId);
 
            if (error) {
                console.error('[SessionSync] Error cleaning up session:', error);
            } else {
                console.log('[SessionSync] Successfully cleaned up all participants for session:', sessionId);
            }
 
            // Unsubscribe if this was our session
            if (this.sessionId === sessionId && this.channel) {
                await this.channel.unsubscribe();
                this.channel = undefined;
            }
        } catch (err) {
            console.error('[SessionSync] Error cleaning up session:', err);
        }
    }
}