Skip to content

feat: add call duration in the call state #1528

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ Here is an excerpt of the call state properties:
| `createdBy$` | `createdBy` | The user who created the call. |
| `custom$` | `custom` | Custom data attached to the call. |
| `dominantSpeaker$` | `dominantSpeaker` | The participant that is the current dominant speaker of the call. |
| `sessionDuration$` | `sessionDuration` | The duration since the start of the call session in seconds. |
| `liveDuration$` | `liveDuration` | The duration since the start of the call livestream in seconds. |
| `egress$` | `egress` | The egress data of the call (for broadcasting and livestreaming). |
| `endedAt$` | `endedAt` | The time the call was ended. |
| `endedBy$` | `endedBy` | The user who ended the call. |
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/Call.ts
Original file line number Diff line number Diff line change
Expand Up @@ -550,6 +550,7 @@ export class Call {
this.dynascaleManager.setSfuClient(undefined);

this.state.setCallingState(CallingState.LEFT);
this.state.dispose();

// Call all leave call hooks, e.g. to clean up global event handlers
this.leaveCallHooks.forEach((hook) => hook());
Expand Down
105 changes: 105 additions & 0 deletions packages/client/src/store/CallState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ export class CallState {
private callStatsReportSubject = new BehaviorSubject<
CallStatsReport | undefined
>(undefined);
private liveDurationSubject = new BehaviorSubject<number>(0);
private sessionDurationSubject = new BehaviorSubject<number>(0);

// These are tracks that were delivered to the Subscriber's onTrack event
// that we couldn't associate with a participant yet.
Expand Down Expand Up @@ -285,6 +287,18 @@ export class CallState {
*/
thumbnails$: Observable<ThumbnailResponse | undefined>;

/**
* Will provide the count of seconds since the session started.
*/
sessionDuration$: Observable<number>;
sessionDurationInterval: NodeJS.Timeout | undefined;

/**
* Will provide the count of seconds since the livestream started.
*/
liveDuration$: Observable<number>;
liveDurationInterval: NodeJS.Timeout | undefined;

readonly logger = getLogger(['CallState']);

/**
Expand Down Expand Up @@ -390,6 +404,10 @@ export class CallState {
this.participantCount$ = duc(this.participantCountSubject);
this.recording$ = duc(this.recordingSubject);
this.transcribing$ = duc(this.transcribingSubject);
this.sessionDuration$ = duc(this.sessionDurationSubject);
this.sessionDurationInterval = undefined;
this.liveDuration$ = duc(this.liveDurationSubject);
this.liveDurationInterval = undefined;

this.eventHandlers = {
// these events are not updating the call state:
Expand Down Expand Up @@ -424,6 +442,8 @@ export class CallState {
'call.hls_broadcasting_started': this.updateFromHLSBroadcastStarted,
'call.hls_broadcasting_stopped': this.updateFromHLSBroadcastStopped,
'call.live_started': (e) => this.updateFromCallResponse(e.call),
// TODO: uncomment this when it is added on the backend side
// 'call.live_ended': (e) => this.updateFromCallResponse(e.call),
'call.member_added': this.updateFromMemberAdded,
'call.member_removed': this.updateFromMemberRemoved,
'call.member_updated_permission': this.updateMembers,
Expand Down Expand Up @@ -464,6 +484,20 @@ export class CallState {
};
}

/**
* Runs the cleanup tasks.
*/
dispose = () => {
if (this.sessionDurationInterval) {
clearInterval(this.sessionDurationInterval);
this.sessionDurationInterval = undefined;
}
if (this.liveDurationInterval) {
clearInterval(this.liveDurationInterval);
this.liveDurationInterval = undefined;
}
};

/**
* Sets the list of criteria that are used to sort the participants.
* To disable sorting, you can pass `noopComparator()`.
Expand Down Expand Up @@ -515,6 +549,40 @@ export class CallState {
return this.setCurrentValue(this.participantCountSubject, count);
};

/**
* The number of seconds since the start of the call session.
*/
get sessionDuration() {
return this.getCurrentValue(this.sessionDuration$);
}

/**
* Sets the number of seconds since the start of the call session.
*
* @internal
* @param sessionDuration the duration of the call session in seconds.
*/
setSessionDuration = (duration: Patch<number>) => {
return this.setCurrentValue(this.sessionDurationSubject, duration);
};

/**
* The number of seconds since the start of the livestream.
*/
get liveDuration() {
return this.getCurrentValue(this.liveDuration$);
}

/**
* Sets the number of seconds since the start of the livestream.
*
* @internal
* @param liveDuration the duration of the livestream in seconds.
*/
setLiveDuration = (duration: Patch<number>) => {
return this.setCurrentValue(this.liveDurationSubject, duration);
};

/**
* The time the call session actually started.
* Useful for displaying the call duration.
Expand Down Expand Up @@ -1064,6 +1132,7 @@ export class CallState {
this.setCurrentValue(this.recordingSubject, call.recording);
const s = this.setCurrentValue(this.sessionSubject, call.session);
this.updateParticipantCountFromSession(s);
this.updateDuration(s);
this.setCurrentValue(this.settingsSubject, call.settings);
this.setCurrentValue(this.transcribingSubject, call.transcribing);
this.setCurrentValue(this.thumbnailsSubject, call.thumbnails);
Expand Down Expand Up @@ -1170,6 +1239,42 @@ export class CallState {
this.setAnonymousParticipantCount(session.anonymous_participant_count || 0);
};

startDurationInterval = (
startTime: string,
setDurationCallback: (seconds: Patch<number>) => number,
) => {
const startedAt = new Date(startTime).getTime();
const elapsedSeconds = Math.floor((Date.now() - startedAt) / 1000);
setDurationCallback(elapsedSeconds);
return setInterval(() => setDurationCallback((prev) => prev + 1), 1000);
};

private updateDuration = (session: CallSessionResponse | undefined) => {
// session duration
if (session?.started_at && !this.sessionDurationInterval) {
this.sessionDurationInterval = this.startDurationInterval(
session.started_at,
this.setSessionDuration,
);
}
if (session?.ended_at && this.sessionDurationInterval) {
clearInterval(this.sessionDurationInterval);
this.sessionDurationInterval = undefined;
}

// livestream duration
if (session?.live_started_at && !this.liveDurationInterval) {
this.liveDurationInterval = this.startDurationInterval(
session.live_started_at,
this.setLiveDuration,
);
}
if (session?.live_ended_at && this.liveDurationInterval) {
clearInterval(this.liveDurationInterval);
this.liveDurationInterval = undefined;
}
};

private updateFromSessionParticipantCountUpdate = (
event: CallSessionParticipantCountsUpdatedEvent,
) => {
Expand Down
20 changes: 20 additions & 0 deletions packages/react-bindings/src/hooks/callStateHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,26 @@ export const useParticipantCount = () => {
return useObservableValue(participantCount$);
};

/**
* Returns the duration of the call session in seconds.
*
* @category Call State
*/
export const useCallSessionDuration = () => {
const { sessionDuration$ } = useCallState();
return useObservableValue(sessionDuration$);
};

/**
* Returns the duration of the livestream seconds.
*
* @category Call State
*/
export const useCallLiveDuration = () => {
const { liveDuration$ } = useCallState();
return useObservableValue(liveDuration$);
};

/**
* Returns the approximate anonymous participant count of the active call.
* The regular participants are not included in this count. It is computed on the server.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ Here is an excerpt of the available call state hooks:
| `useCallCreatedAt` | The time the call was created. |
| `useCallCreatedBy` | The user that created the call. |
| `useCallCustomData` | The custom data attached to the call. |
| `useCallSessionDuration` | The duration since the start of the call session in seconds. |
| `useCallLiveDuration` | The duration since the start of the call livestream in seconds. |
| `useCallEgress` | The egress information of the call. |
| `useCallEndedBy` | The user that ended the call. |
| `useCallIngress` | The ingress information of the call. |
Expand Down Expand Up @@ -205,7 +207,7 @@ const hosts = participants.filter((p) => p.roles.includes('host'));

// participants that publish video and audio
const videoParticipants = participants.filter(
(p) => hasVideo(p) && hasAudio(p),
(p) => hasVideo(p) && hasAudio(p)
);
```

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ Here is an excerpt of the available call state hooks:
| `useCallCreatedAt` | The time the call was created. |
| `useCallCreatedBy` | The user that created the call. |
| `useCallCustomData` | The custom data attached to the call. |
| `useCallSessionDuration` | The duration since the start of the call session in seconds. |
| `useCallLiveDuration` | The duration since the start of the call livestream in seconds. |
| `useCallEgress` | The egress information of the call. |
| `useCallEndedBy` | The user that ended the call. |
| `useCallIngress` | The ingress information of the call. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,7 @@ const UnMemoizedChannelHeader = (props: ChannelHeaderProps) => {
>
<MenuIcon />
</button>
<Avatar
image={displayImage}
name={displayTitle}
/>
<Avatar image={displayImage} name={displayTitle} />
<div className="str-chat__header-livestream-left str-chat__channel-header-end">
<p className="str-chat__header-livestream-left--title str-chat__channel-header-title">
{displayTitle}{' '}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,7 @@ const QuickDialButton = <SCG extends ExtendableGenerics = DefaultGenerics>({
away: !user.online,
})}
>
<Avatar
image={user.image as string}
name={user.name}
user={user}
/>
<Avatar image={user.image as string} name={user.name} user={user} />
</button>
);
};
40 changes: 16 additions & 24 deletions sample-apps/react/react-dogfood/components/ActiveCallHeader.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { useEffect, useMemo, useState } from 'react';
import {
CallingState,
CancelCallConfirmButton,
Expand Down Expand Up @@ -38,26 +37,20 @@ const LatencyIndicator = () => {
);
};

const Elapsed = ({ startedAt }: { startedAt: string | undefined }) => {
const [elapsed, setElapsed] = useState<string>();
const startedAtDate = useMemo(
() => (startedAt ? new Date(startedAt).getTime() : Date.now()),
[startedAt],
);
useEffect(() => {
const interval = setInterval(() => {
const elapsedSeconds = (Date.now() - startedAtDate) / 1000;
const date = new Date(0);
date.setSeconds(elapsedSeconds);
const format = date.toISOString(); // '1970-01-01T00:00:35.000Z'
const hours = format.substring(11, 13);
const minutes = format.substring(14, 16);
const seconds = format.substring(17, 19);
const time = `${hours !== '00' ? hours + ':' : ''}${minutes}:${seconds}`;
setElapsed(time);
}, 1000);
return () => clearInterval(interval);
}, [startedAtDate]);
const formatTime = (timeInSeconds: number) => {
const date = new Date(0);
date.setSeconds(timeInSeconds);
const format = date.toISOString(); // '1970-01-01T00:00:35.000Z'
const hours = format.substring(11, 13);
const minutes = format.substring(14, 16);
const seconds = format.substring(17, 19);
return `${hours !== '00' ? hours + ':' : ''}${minutes}:${seconds}`;
};

const Elapsed = () => {
const { useCallSessionDuration } = useCallStateHooks();
const sessionDuration = useCallSessionDuration();
const elapsed = formatTime(sessionDuration);

return (
<div className="rd__header__elapsed">
Expand All @@ -72,9 +65,8 @@ export const ActiveCallHeader = ({
selectedLayout,
onMenuItemClick,
}: { onLeave: () => void } & LayoutSelectorProps) => {
const { useCallCallingState, useCallSession } = useCallStateHooks();
const { useCallCallingState } = useCallStateHooks();
const callingState = useCallCallingState();
const session = useCallSession();
const isOffline = callingState === CallingState.OFFLINE;
const isMigrating = callingState === CallingState.MIGRATING;
const isJoining = callingState === CallingState.JOINING;
Expand Down Expand Up @@ -109,7 +101,7 @@ export const ActiveCallHeader = ({
</div>

<div className="rd__call-header__controls-group">
<Elapsed startedAt={session?.started_at} />
<Elapsed />
<LatencyIndicator />
</div>
<div className="rd__call-header__leave">
Expand Down
Loading