-
Notifications
You must be signed in to change notification settings - Fork 0
/
room-reactions.ts
281 lines (247 loc) · 8.56 KB
/
room-reactions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import * as Ably from 'ably';
import { getChannel } from './channel.js';
import {
DiscontinuityEmitter,
DiscontinuityListener,
EmitsDiscontinuities,
HandlesDiscontinuity,
newDiscontinuityEmitter,
OnDiscontinuitySubscriptionResponse,
} from './discontinuity.js';
import { ErrorCodes } from './errors.js';
import { RoomReactionEvents } from './events.js';
import { Logger } from './logger.js';
import { Reaction, ReactionHeaders, ReactionMetadata } from './reaction.js';
import { parseReaction } from './reaction-parser.js';
import { addListenerToChannelWithoutAttach } from './realtime-extensions.js';
import { ContributesToRoomLifecycle } from './room-lifecycle-manager.js';
import EventEmitter from './utils/event-emitter.js';
/**
* Params for sending a room-level reactions. Only `type` is mandatory.
*/
export interface SendReactionParams {
/**
* The type of the reaction, for example an emoji or a short string such as
* "like".
*
* It is the only mandatory parameter to send a room-level reaction.
*/
type: string;
/**
* Optional metadata of the reaction.
*
* The metadata is a map of extra information that can be attached to the
* room reaction. It is not used by Ably and is sent as part of the realtime
* message payload. Example use cases are custom animations or other effects.
*
* Do not use metadata for authoritative information. There is no server-side
* validation. When reading the metadata treat it like user input.
*
*/
metadata?: ReactionMetadata;
/**
* Optional headers of the room reaction.
*
* The headers are a flat key-value map and are sent as part of the realtime
* message's `extras` inside the `headers` property. They can serve similar
* purposes as the metadata but they are read by Ably and can be used for
* features such as
* [subscription filters](https://faqs.ably.com/subscription-filters).
*
* Do not use the headers for authoritative information. There is no
* server-side validation. When reading the headers treat them like user
* input.
*
*/
headers?: ReactionHeaders;
}
/**
* The listener function type for room-level reactions.
*
* @param reaction The reaction that was received.
*/
export type RoomReactionListener = (reaction: Reaction) => void;
/**
* This interface is used to interact with room-level reactions in a chat room: subscribing to reactions and sending them.
*
* Get an instance via {@link Room.reactions}.
*/
export interface RoomReactions extends EmitsDiscontinuities {
/**
* Send a reaction to the room including some metadata.
*
* This method accepts parameters for a room-level reaction. It accepts an object
*
*
* @param params an object containing {type, headers, metadata} for the room
* reaction to be sent. Type is required, metadata and headers are optional.
* @returns The returned promise resolves when the reaction was sent. Note
* that it is possible to receive your own reaction via the reactions
* listener before this promise resolves.
*/
send(params: SendReactionParams): Promise<void>;
/**
* Subscribe to receive room-level reactions.
*
* @param listener The listener function to be called when a reaction is received.
* @returns A response object that allows you to control the subscription.
*/
subscribe(listener: RoomReactionListener): RoomReactionsSubscriptionResponse;
/**
* Unsubscribe all listeners from receiving room-level reaction events.
*/
unsubscribeAll(): void;
/**
* Returns an instance of the Ably realtime channel used for room-level reactions.
* Avoid using this directly unless special features that cannot otherwise be implemented are needed.
*
* @returns A promise of the Ably realtime channel.
*/
get channel(): Promise<Ably.RealtimeChannel>;
}
interface RoomReactionEventsMap {
[RoomReactionEvents.Reaction]: Reaction;
}
interface ReactionPayload {
type: string;
metadata?: ReactionMetadata;
}
/**
* A response object that allows you to control the subscription to room-level reactions.
*/
export interface RoomReactionsSubscriptionResponse {
/**
* Unsubscribe the listener registered with {@link RoomReactions.subscribe} from reaction events.
*/
unsubscribe: () => void;
}
/**
* @inheritDoc
*/
export class DefaultRoomReactions
extends EventEmitter<RoomReactionEventsMap>
implements RoomReactions, HandlesDiscontinuity, ContributesToRoomLifecycle
{
private readonly _channel: Promise<Ably.RealtimeChannel>;
private readonly _clientId: string;
private readonly _logger: Logger;
private readonly _discontinuityEmitter: DiscontinuityEmitter = newDiscontinuityEmitter();
/**
* Constructs a new `DefaultRoomReactions` instance.
* @param roomId The unique identifier of the room.
* @param realtime An instance of the Ably Realtime client.
* @param clientId The client ID of the user.
* @param logger An instance of the Logger.
* @param initAfter A promise that is awaited before creating any channels.
*/
constructor(roomId: string, realtime: Ably.Realtime, clientId: string, logger: Logger, initAfter: Promise<void>) {
super();
this._channel = initAfter.then(() => this._makeChannel(roomId, realtime));
// Catch this so it won't send unhandledrejection global event
this._channel.catch((error: unknown) => {
logger.debug('RoomReactions: channel initialization canceled', { roomId, error });
});
this._clientId = clientId;
this._logger = logger;
}
/**
* Creates the realtime channel for room reactions. Called after initAfter is resolved.
*/
private _makeChannel(roomId: string, realtime: Ably.Realtime): Ably.RealtimeChannel {
const channel = getChannel(`${roomId}::$chat::$reactions`, realtime);
addListenerToChannelWithoutAttach({
listener: this._forwarder.bind(this),
events: [RoomReactionEvents.Reaction],
channel: channel,
});
return channel;
}
/**
* @inheritDoc Reactions
*/
send(params: SendReactionParams): Promise<void> {
this._logger.trace('RoomReactions.send();', params);
const { type, metadata, headers } = params;
if (!type) {
return Promise.reject(new Ably.ErrorInfo('unable to send reaction; type not set and it is required', 40001, 400));
}
const payload: ReactionPayload = {
type: type,
metadata: metadata ?? {},
};
const realtimeMessage: Ably.Message = {
name: RoomReactionEvents.Reaction,
data: payload,
extras: {
headers: headers ?? {},
},
};
return this._channel.then((channel) => {
return channel.publish(realtimeMessage);
});
}
/**
* @inheritDoc Reactions
*/
subscribe(listener: RoomReactionListener): RoomReactionsSubscriptionResponse {
this._logger.trace(`RoomReactions.subscribe();`);
this.on(listener);
return {
unsubscribe: () => {
this._logger.trace('RoomReactions.unsubscribe();');
this.off(listener);
},
};
}
/**
* @inheritDoc Reactions
*/
unsubscribeAll() {
this._logger.trace(`RoomReactions.unsubscribeAll();`);
this.off();
}
// parses reactions from realtime channel into Reaction objects and forwards them to the EventEmitter
private _forwarder = (inbound: Ably.InboundMessage) => {
const reaction = this._parseNewReaction(inbound, this._clientId);
if (!reaction) {
// ignore non-reactions
return;
}
this.emit(RoomReactionEvents.Reaction, reaction);
};
get channel(): Promise<Ably.RealtimeChannel> {
return this._channel;
}
private _parseNewReaction(inbound: Ably.InboundMessage, clientId: string): Reaction | undefined {
try {
return parseReaction(inbound, clientId);
} catch (error: unknown) {
this._logger.error(`failed to parse incoming reaction;`, { inbound, error: error as Ably.ErrorInfo });
}
}
discontinuityDetected(reason?: Ably.ErrorInfo): void {
this._logger.warn('RoomReactions.discontinuityDetected();', { reason });
this._discontinuityEmitter.emit('discontinuity', reason);
}
onDiscontinuity(listener: DiscontinuityListener): OnDiscontinuitySubscriptionResponse {
this._logger.trace('RoomReactions.onDiscontinuity();');
this._discontinuityEmitter.on(listener);
return {
off: () => {
this._discontinuityEmitter.off(listener);
},
};
}
/**
* @inheritdoc ContributesToRoomLifecycle
*/
get attachmentErrorCode(): ErrorCodes {
return ErrorCodes.ReactionsAttachmentFailed;
}
/**
* @inheritdoc ContributesToRoomLifecycle
*/
get detachmentErrorCode(): ErrorCodes {
return ErrorCodes.ReactionsDetachmentFailed;
}
}