Home Reference Source

src/users-new/Presence.ts

import {Observable, concat, defer} from 'rxjs';
import {filter, first, map, mergeMap, shareReplay} from 'rxjs/operators';

import {PresenceService} from '../wac-proxy/wac-stack/presence/PresenceService';

import {PresenceState} from './PresenceState';

/**
 * Allows retrieving and updating presence related information othe the current user.
 * An instance of this class must be obtained using {@link Session.getPresence}.
 */
export class Presence {
	/**
	 * Allows access to the current presence information.
	 */
	readonly state$: Observable<PresenceState>;

	constructor(
		private presenceService: PresenceService,
		private ownId: string,
	) {
		this.presenceService = presenceService;
		this.ownId = ownId;

		const initial$ = defer(() => this.presenceService.subscribeToPresence$(this.ownId));
		const updates$ = defer(() => this.presenceService.event$).pipe(
			map(event => event.body),
			filter(presence => presence.address === this.ownId),
		);
		this.state$ = concat(initial$, updates$).pipe(
			map(presenceDto => ({
				online: presenceDto.online,
				activity: presenceDto.activity,
				mood: presenceDto.mood,
				note: presenceDto.note,
				avatar: presenceDto.avatar,
				displayName: presenceDto.displayName,
			})),
			shareReplay(1),
		);
	}

	/**
	 * Allows updating current user presence information
	 */
	update(presence: Partial<PresenceState>): Observable<void> {
		return this.state$.pipe(
			first(),
			mergeMap(currentState => this.presenceService.update$(this.ownId, {...currentState, ...presence})),
			map(() => undefined),
		);
	}
}