UNPKG

@amityco/ts-sdk-react-native

Version:

Amity Social Cloud Typescript SDK

66 lines (55 loc) 1.81 kB
import { getActiveClient } from '~/client/api/activeClient'; import { createEventSubscriber } from '~/core/events'; import { pullFromCache, upsertInCache } from '~/cache/api'; type CallbackFn = ( channel: Amity.StaticInternalChannel, member: Amity.Membership<'channel'>, ) => void; const callbacks: CallbackFn[] = []; let mainDisposer: (() => void) | null = null; const dispose = (cb: CallbackFn) => { const index = callbacks.indexOf(cb); if (index > -1) { callbacks.splice(index, 1); } if (callbacks.length === 0) { mainDisposer?.(); } }; export const onChannelSetUserMuted = ( callback: (channel: Amity.StaticInternalChannel, member: Amity.Membership<'channel'>) => void, ): Amity.Unsubscriber => { if (callbacks.length === 0) { const client = getActiveClient(); const filter = async (payload: Amity.ChannelSetUserMutedPayload) => { payload.userIds.forEach(userId => // If muteTimeout > now => user is muted // Otherwise => user is unmuted upsertInCache(['channelUsers', 'get', `${payload.channelId}#${userId}`], { isMuted: Date.parse(payload.muteTimeout) > Date.now(), }), ); const channel = pullFromCache<Amity.StaticInternalChannel>([ 'channel', 'get', payload.channelId, ])?.data; const channelUser = pullFromCache<Amity.Membership<'channel'>>([ 'channelUsers', 'get', `${payload.channelId}#${payload.userIds[0]}`, ])?.data; if (channel && channelUser) { callbacks.forEach(cb => cb(channel, channelUser)); } }; mainDisposer = createEventSubscriber( client, 'onChannelUserMute', 'channel.setMutedUsers', filter, ); } callbacks.push(callback); return () => dispose(callback); };