Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

9.1 KB
Raw Blame
import { MakeLogicType, actions, connect, defaults, kea, key, listeners, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'

import api, { ApiError } from 'lib/api'
import { dayjs } from 'lib/dayjs'
import { snapshotDataLogic } from 'scenes/session-recordings/player/snapshotDataLogic'
import { windowIdRegistryLogic } from 'scenes/session-recordings/player/windowIdRegistryLogic'
import { teamLogic } from 'scenes/teamLogic'

import { annotationsModel } from '~/models/annotationsModel'
import { SessionRecordingId, SessionRecordingType } from '~/types'

import type {
    AnnotationType,
    PersonType,
    RecordingSnapshot,
    SessionRecordingSnapshotSource,
    TeamPublicType,
    TeamType,
} from '../../../types'
import { ExportedSessionRecordingFileV2 } from '../file-playback/types'

export interface SessionRecordingMetaLogicProps {
    sessionRecordingId: SessionRecordingId
    blobV2PollingDisabled?: boolean
    playerKey?: string
    accessToken?: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sessionRecordingMetaLogicValues {
    annotations: AnnotationType[] // annotationsModel
    annotationsLoading: boolean // annotationsModel
    getWindowId: (uuid: string | undefined) => number | undefined // registryLogic
    uuidToIndex: Record<string, number> // registryLogic
    isLoadingSnapshots: boolean // snapshotLogic
    isRecordingDeleted: boolean // snapshotLogic
    recordingDeletedAt: number | null // snapshotLogic
    recordingDeletedBy: string | null // snapshotLogic
    snapshotSources: SessionRecordingSnapshotSource[] | null // snapshotLogic
    snapshotsLoaded: boolean // snapshotLogic
    snapshotsLoading: boolean // snapshotLogic
    currentTeam: TeamPublicType | TeamType | null // teamLogic
    isNotFound: boolean
    loadMetaError: boolean
    sessionPlayerMetaData: SessionRecordingType | null
    sessionPlayerMetaDataLoading: boolean
    trackedWindow: number | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sessionRecordingMetaLogicActions {
    registerWindowId: (uuid: string) => {
        uuid: string
    } // registryLogic
    loadSnapshotSources: (breakpointLength?: number | undefined) => {
        breakpointLength: number | undefined
    } // snapshotLogic
    loadSnapshots: () => {
        value: true
    } // snapshotLogic
    loadSnapshotsForSourceSuccess: (
        snapshotsForSource:
            | {
                  source: Pick<SessionRecordingSnapshotSource, 'blob_key' | 'source'>
                  sources?: undefined
              }
            | {
                  source?: undefined
                  sources: Pick<SessionRecordingSnapshotSource, 'blob_key' | 'source'>[]
              },
        payload?:
            | {
                  sources: Pick<SessionRecordingSnapshotSource, 'blob_key' | 'source'>[]
              }
            | undefined
    ) => {
        payload?: {
            sources: Pick<SessionRecordingSnapshotSource, 'blob_key' | 'source'>[]
        }
        snapshotsForSource:
            | {
                  source: Pick<SessionRecordingSnapshotSource, 'blob_key' | 'source'>
                  sources?: undefined
              }
            | {
                  source?: undefined
                  sources: Pick<SessionRecordingSnapshotSource, 'blob_key' | 'source'>[]
              }
    } // snapshotLogic
    setSnapshots: (snapshots: import('@common/replay-shared/src').RecordingSnapshot[]) => {
        snapshots: RecordingSnapshot[]
    } // snapshotLogic
    loadRecordingFromFile: (recording: ExportedSessionRecordingFileV2['data']) => {
        recording: {
            id: string
            person: PersonType | undefined
            snapshots: RecordingSnapshot[]
        }
    }
    loadRecordingMeta: () => {
        value: true
    }
    loadRecordingMetaFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadRecordingMetaSuccess: (
        sessionPlayerMetaData: SessionRecordingType | null,
        payload?: {
            value: true
        }
    ) => {
        sessionPlayerMetaData: SessionRecordingType | null
        payload?: {
            value: true
        }
    }
    maybeLoadRecordingMeta: () => {
        value: true
    }
    setTrackedWindow: (windowId: number | null) => {
        windowId: number | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sessionRecordingMetaLogicMeta {
    key: string
}

export type sessionRecordingMetaLogicType = MakeLogicType<
    sessionRecordingMetaLogicValues,
    sessionRecordingMetaLogicActions,
    SessionRecordingMetaLogicProps,
    sessionRecordingMetaLogicMeta
>

export const sessionRecordingMetaLogic = kea<sessionRecordingMetaLogicType>([
    path((key) => ['scenes', 'session-recordings', 'sessionRecordingMetaLogic', key]),
    props({} as SessionRecordingMetaLogicProps),
    key(({ sessionRecordingId }) => sessionRecordingId || 'no-session-recording-id'),
    connect(({ sessionRecordingId, blobV2PollingDisabled }: SessionRecordingMetaLogicProps) => {
        const snapshotLogic = snapshotDataLogic({
            sessionRecordingId,
            blobV2PollingDisabled,
        })
        const registryLogic = windowIdRegistryLogic({ sessionRecordingId })
        return {
            actions: [
                snapshotLogic,
                ['loadSnapshots', 'loadSnapshotSources', 'loadSnapshotsForSourceSuccess', 'setSnapshots'],
                registryLogic,
                ['registerWindowId'],
            ],
            values: [
                teamLogic,
                ['currentTeam'],
                annotationsModel,
                ['annotations', 'annotationsLoading'],
                snapshotLogic,
                [
                    'snapshotSources',
                    'snapshotsLoading',
                    'snapshotsLoaded',
                    'isLoadingSnapshots',
                    'isRecordingDeleted',
                    'recordingDeletedAt',
                    'recordingDeletedBy',
                ],
                registryLogic,
                ['uuidToIndex', 'getWindowId'],
            ],
        }
    }),
    defaults({
        sessionPlayerMetaData: null as SessionRecordingType | null,
    }),
    actions({
        loadRecordingMeta: true,
        loadRecordingFromFile: (recording: ExportedSessionRecordingFileV2['data']) => ({ recording }),
        maybeLoadRecordingMeta: true,
        setTrackedWindow: (windowId: number | null) => ({ windowId }),
    }),
    reducers(() => ({
        isNotFound: [
            false as boolean,
            {
                loadRecordingMeta: () => false,
                loadRecordingMetaSuccess: () => false,
                loadRecordingMetaFailure: (_, { errorObject }) =>
                    errorObject instanceof ApiError && errorObject.status === 404,
            },
        ],
        loadMetaError: [
            false as boolean,
            {
                loadRecordingMeta: () => false,
                loadRecordingMetaSuccess: () => false,
                loadRecordingMetaFailure: (_, { errorObject }) =>
                    !(errorObject instanceof ApiError && errorObject.status === 404),
            },
        ],
        trackedWindow: [
            null as number | null,
            {
                setTrackedWindow: (_, { windowId }) => windowId,
            },
        ],
    })),
    loaders(({ props }) => ({
        sessionPlayerMetaData: {
            loadRecordingMeta: async (_, breakpoint) => {
                if (!props.sessionRecordingId) {
                    return null
                }
                // Cancel orphaned loaders from StrictMode's unmounted logic
                await breakpoint(1)
                const headers: Record<string, string> = {}
                if (props.accessToken) {
                    headers.Authorization = `Bearer ${props.accessToken}`
                }
                const response = await api.recordings.get(props.sessionRecordingId, {}, headers)
                breakpoint()

                return response
            },
        },
    })),
    listeners(({ values, actions }) => ({
        loadRecordingFromFile: ({ recording }: { recording: ExportedSessionRecordingFileV2['data'] }) => {
            const { id, snapshots, person } = recording
            actions.setSnapshots(snapshots)
            actions.loadRecordingMetaSuccess({
                id,
                viewed: false,
                viewers: [],
                recording_duration: snapshots[snapshots.length - 1].timestamp - snapshots[0].timestamp,
                person: person || undefined,
                start_time: dayjs(snapshots[0].timestamp).toISOString(),
                end_time: dayjs(snapshots[snapshots.length - 1].timestamp).toISOString(),
                snapshot_source: 'unknown',
                expiry_time: undefined,
                recording_ttl: undefined,
            })
        },

        maybeLoadRecordingMeta: () => {
            if (!values.sessionPlayerMetaDataLoading) {
                actions.loadRecordingMeta()
            }
        },
    })),
])