Skip to content
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

feat: add call duration in the call state #1528

Open
wants to merge 19 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 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,7 @@ 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. |
| `duration$` | `duration` | The duration since the start of the call 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
54 changes: 54 additions & 0 deletions packages/client/src/store/CallState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ export class CallState {
private callStatsReportSubject = new BehaviorSubject<
CallStatsReport | undefined
>(undefined);
private durationSubject = 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 +286,12 @@ export class CallState {
*/
thumbnails$: Observable<ThumbnailResponse | undefined>;

/**
* Will provide the count of seconds since the call started.
*/
duration$: Observable<number>;
durationInterval: NodeJS.Timeout | undefined;

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

/**
Expand Down Expand Up @@ -390,6 +397,8 @@ export class CallState {
this.participantCount$ = duc(this.participantCountSubject);
this.recording$ = duc(this.recordingSubject);
this.transcribing$ = duc(this.transcribingSubject);
this.duration$ = duc(this.durationSubject);
this.durationInterval = undefined;

this.eventHandlers = {
// these events are not updating the call state:
Expand Down Expand Up @@ -464,6 +473,16 @@ export class CallState {
};
}

/**
* Runs the cleanup tasks.
*/
dispose = () => {
if (this.durationInterval) {
clearInterval(this.durationInterval);
this.durationInterval = 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 +534,23 @@ export class CallState {
return this.setCurrentValue(this.participantCountSubject, count);
};

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

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

/**
* The time the call session actually started.
* Useful for displaying the call duration.
Expand Down Expand Up @@ -1064,6 +1100,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 +1207,23 @@ export class CallState {
this.setAnonymousParticipantCount(session.anonymous_participant_count || 0);
};

private updateDuration = (session: CallSessionResponse | undefined) => {
if (session?.live_started_at && !this.durationInterval) {
const startedAt = new Date(session.live_started_at).getTime();
const elapsedSeconds = Math.floor((Date.now() - startedAt) / 1000);
this.setDuration(elapsedSeconds);
this.durationInterval = setInterval(
() => this.setDuration((prev) => prev + 1),
1000,
);
}

if (session?.ended_at && this.durationInterval) {
clearInterval(this.durationInterval);
this.durationInterval = undefined;
}
};

private updateFromSessionParticipantCountUpdate = (
event: CallSessionParticipantCountsUpdatedEvent,
) => {
Expand Down
10 changes: 10 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,16 @@ export const useParticipantCount = () => {
return useObservableValue(participantCount$);
};

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

/**
* 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,7 @@ 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. |
| `useCallDuration` | The call duration since the start of the call in seconds. |
kristian-mkd marked this conversation as resolved.
Show resolved Hide resolved
| `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 +206,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
39 changes: 18 additions & 21 deletions sample-apps/react/react-dogfood/components/ActiveCallHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,26 +38,24 @@ const LatencyIndicator = () => {
);
};

const Elapsed = ({ startedAt }: { startedAt: string | undefined }) => {
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 [elapsed, setElapsed] = useState<string>();
const startedAtDate = useMemo(
() => (startedAt ? new Date(startedAt).getTime() : Date.now()),
[startedAt],
);
const { useCallDuration } = useCallStateHooks();
const duration = useCallDuration();

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]);
setElapsed(formatTime(duration));
}, [duration]);
kristian-mkd marked this conversation as resolved.
Show resolved Hide resolved

return (
<div className="rd__header__elapsed">
Expand All @@ -72,9 +70,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 +106,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