♻️(frontend) refactor useConnectionObserver to track session time
Add session duration tracking and consolidate all disconnect events (including client-initiated) with timing data for comprehensive connection analytics.
This commit is contained in:
committed by
aleb_the_flash
parent
77d2365a61
commit
bbb6e4f317
@@ -1,17 +1,25 @@
|
||||
import { useRoomContext } from '@livekit/components-react'
|
||||
import { useEffect } from 'react'
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { DisconnectReason, RoomEvent } from 'livekit-client'
|
||||
import { useIsAnalyticsEnabled } from '@/features/analytics/hooks/useIsAnalyticsEnabled'
|
||||
import posthog from 'posthog-js'
|
||||
|
||||
export const useConnectionObserver = () => {
|
||||
const room = useRoomContext()
|
||||
const connectionStartTimeRef = useRef<number | null>(null)
|
||||
|
||||
const isAnalyticsEnabled = useIsAnalyticsEnabled()
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAnalyticsEnabled) return
|
||||
|
||||
const handleConnection = () => {
|
||||
// Preserve original connection timestamp across reconnections to measure
|
||||
// total session duration from first connect to final disconnect.
|
||||
if (connectionStartTimeRef.current != null) return
|
||||
connectionStartTimeRef.current = Date.now()
|
||||
}
|
||||
|
||||
const handleReconnect = () => {
|
||||
posthog.capture('reconnect-event')
|
||||
}
|
||||
@@ -19,16 +27,34 @@ export const useConnectionObserver = () => {
|
||||
const handleDisconnect = (
|
||||
disconnectReason: DisconnectReason | undefined
|
||||
) => {
|
||||
if (disconnectReason == DisconnectReason.CLIENT_INITIATED) return
|
||||
const connectionEndTime = Date.now()
|
||||
|
||||
posthog.capture('disconnect-event', {
|
||||
reason: disconnectReason && DisconnectReason[disconnectReason],
|
||||
// Calculate total session duration from first connection to final disconnect
|
||||
// This duration is sensitive to refreshing the page.
|
||||
sessionDuration: connectionStartTimeRef.current
|
||||
? connectionEndTime - connectionStartTimeRef.current
|
||||
: -1,
|
||||
reason: disconnectReason
|
||||
? DisconnectReason[disconnectReason]
|
||||
: 'UNKNOWN',
|
||||
})
|
||||
}
|
||||
|
||||
room.on(RoomEvent.Connected, handleConnection)
|
||||
room.on(RoomEvent.Disconnected, handleDisconnect)
|
||||
room.on(RoomEvent.Reconnecting, handleReconnect)
|
||||
|
||||
return () => {
|
||||
room.off(RoomEvent.Connected, handleConnection)
|
||||
room.off(RoomEvent.Disconnected, handleDisconnect)
|
||||
room.off(RoomEvent.Reconnecting, handleReconnect)
|
||||
}
|
||||
}, [room, isAnalyticsEnabled])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
connectionStartTimeRef.current = null
|
||||
}
|
||||
}, [])
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user