mediasfu-shared 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +228 -0
  3. package/dist/index.cjs +7707 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.ts +7285 -0
  6. package/dist/index.js +7690 -0
  7. package/dist/index.js.map +1 -0
  8. package/package.json +78 -0
  9. package/src/ProducerClient/producerClientEmits/createDeviceClient.ts +68 -0
  10. package/src/consumers/addVideosGrid.ts +18 -0
  11. package/src/consumers/autoAdjust.ts +100 -0
  12. package/src/consumers/calculateRowsAndColumns.ts +51 -0
  13. package/src/consumers/changeVids.ts +753 -0
  14. package/src/consumers/checkGrid.ts +100 -0
  15. package/src/consumers/checkPermission.ts +89 -0
  16. package/src/consumers/checkScreenShare.ts +114 -0
  17. package/src/consumers/closeAndResize.ts +401 -0
  18. package/src/consumers/compareActiveNames.ts +122 -0
  19. package/src/consumers/compareScreenStates.ts +117 -0
  20. package/src/consumers/connectIps.ts +175 -0
  21. package/src/consumers/connectLocalIps.ts +103 -0
  22. package/src/consumers/connectRecvTransport.ts +158 -0
  23. package/src/consumers/connectSendTransport.ts +150 -0
  24. package/src/consumers/connectSendTransportAudio.ts +161 -0
  25. package/src/consumers/connectSendTransportScreen.ts +169 -0
  26. package/src/consumers/connectSendTransportVideo.ts +149 -0
  27. package/src/consumers/consumerResume.ts +25 -0
  28. package/src/consumers/controlMedia.ts +118 -0
  29. package/src/consumers/createSendTransport.ts +312 -0
  30. package/src/consumers/disconnectSendTransportAudio.ts +170 -0
  31. package/src/consumers/disconnectSendTransportScreen.ts +130 -0
  32. package/src/consumers/disconnectSendTransportVideo.ts +161 -0
  33. package/src/consumers/dispStreams.ts +694 -0
  34. package/src/consumers/generatePageContent.ts +118 -0
  35. package/src/consumers/getEstimate.ts +124 -0
  36. package/src/consumers/getPipedProducersAlt.ts +96 -0
  37. package/src/consumers/getProducersPiped.ts +89 -0
  38. package/src/consumers/getVideos.ts +107 -0
  39. package/src/consumers/mixStreams.ts +97 -0
  40. package/src/consumers/onScreenChanges.ts +106 -0
  41. package/src/consumers/prepopulateUserMedia.ts +18 -0
  42. package/src/consumers/processConsumerTransports.ts +157 -0
  43. package/src/consumers/processConsumerTransportsAudio.ts +121 -0
  44. package/src/consumers/rePort.ts +123 -0
  45. package/src/consumers/reUpdateInter.ts +289 -0
  46. package/src/consumers/readjust.ts +170 -0
  47. package/src/consumers/receiveAllPipedTransports.ts +77 -0
  48. package/src/consumers/receiveRoomMessages.ts +55 -0
  49. package/src/consumers/reorderStreams.ts +246 -0
  50. package/src/consumers/requestScreenShare.ts +103 -0
  51. package/src/consumers/resumePauseAudioStreams.ts +174 -0
  52. package/src/consumers/resumePauseStreams.ts +110 -0
  53. package/src/consumers/resumeSendTransportAudio.ts +143 -0
  54. package/src/consumers/signalNewConsumerTransport.ts +179 -0
  55. package/src/consumers/socketReceiveMethods/joinConsumeRoom.ts +130 -0
  56. package/src/consumers/socketReceiveMethods/newPipeProducer.ts +138 -0
  57. package/src/consumers/socketReceiveMethods/producerClosed.ts +102 -0
  58. package/src/consumers/startShareScreen.ts +124 -0
  59. package/src/consumers/stopShareScreen.ts +241 -0
  60. package/src/consumers/streamSuccessAudio.ts +297 -0
  61. package/src/consumers/streamSuccessAudioSwitch.ts +315 -0
  62. package/src/consumers/streamSuccessScreen.ts +255 -0
  63. package/src/consumers/streamSuccessVideo.ts +373 -0
  64. package/src/consumers/switchUserAudio.ts +140 -0
  65. package/src/consumers/switchUserVideo.ts +201 -0
  66. package/src/consumers/switchUserVideoAlt.ts +331 -0
  67. package/src/consumers/trigger.ts +250 -0
  68. package/src/consumers/updateMiniCardsGrid.ts +150 -0
  69. package/src/consumers/updateParticipantAudioDecibels.ts +56 -0
  70. package/src/index.ts +119 -0
  71. package/src/methods/background/launchBackground.ts +16 -0
  72. package/src/methods/breakoutRooms/breakoutRoomUpdated.ts +161 -0
  73. package/src/methods/breakoutRooms/handleStartBreakout.ts +96 -0
  74. package/src/methods/breakoutRooms/handleStopBreakout.ts +72 -0
  75. package/src/methods/breakoutRooms/index.ts +4 -0
  76. package/src/methods/breakoutRooms/launchBreakoutRooms.ts +31 -0
  77. package/src/methods/coHost/launchCoHost.ts +28 -0
  78. package/src/methods/coHostMethods/index.ts +2 -0
  79. package/src/methods/coHostMethods/modifyCoHostSettings.ts +94 -0
  80. package/src/methods/displaySettings/index.ts +1 -0
  81. package/src/methods/displaySettings/launchDisplaySettings.ts +31 -0
  82. package/src/methods/displaySettings/modifyDisplaySettings.ts +242 -0
  83. package/src/methods/exit/confirmExit.ts +60 -0
  84. package/src/methods/exit/index.ts +2 -0
  85. package/src/methods/exit/launchConfirmExit.ts +29 -0
  86. package/src/methods/index.ts +5 -0
  87. package/src/methods/mediaSettings/launchMediaSettings.ts +61 -0
  88. package/src/methods/menu/launchMenuModal.ts +28 -0
  89. package/src/methods/message/index.ts +1 -0
  90. package/src/methods/message/launchMessages.ts +27 -0
  91. package/src/methods/message/sendMessage.ts +175 -0
  92. package/src/methods/participants/index.ts +3 -0
  93. package/src/methods/participants/launchParticipants.ts +25 -0
  94. package/src/methods/participants/messageParticipants.ts +78 -0
  95. package/src/methods/participants/muteParticipants.ts +79 -0
  96. package/src/methods/participants/removeParticipants.ts +97 -0
  97. package/src/methods/polls/handleCreatePoll.ts +66 -0
  98. package/src/methods/polls/handleEndPoll.ts +64 -0
  99. package/src/methods/polls/handleVotePoll.ts +76 -0
  100. package/src/methods/polls/index.ts +3 -0
  101. package/src/methods/polls/launchPoll.ts +25 -0
  102. package/src/methods/prejoin/handleCreateRoom.ts +441 -0
  103. package/src/methods/prejoin/handleJoinRoom.ts +153 -0
  104. package/src/methods/prejoin/index.ts +14 -0
  105. package/src/methods/recording/checkPauseState.ts +57 -0
  106. package/src/methods/recording/checkResumeState.ts +42 -0
  107. package/src/methods/recording/confirmRecording.ts +241 -0
  108. package/src/methods/recording/launchRecording.ts +114 -0
  109. package/src/methods/recording/recordPauseTimer.ts +52 -0
  110. package/src/methods/recording/recordResumeTimer.ts +92 -0
  111. package/src/methods/recording/recordStartTimer.ts +106 -0
  112. package/src/methods/recording/recordUpdateTimer.ts +49 -0
  113. package/src/methods/recording/startRecording.ts +268 -0
  114. package/src/methods/recording/stopRecording.ts +124 -0
  115. package/src/methods/recording/updateRecording.ts +245 -0
  116. package/src/methods/requests/index.ts +1 -0
  117. package/src/methods/requests/launchRequests.ts +25 -0
  118. package/src/methods/requests/respondToRequests.ts +108 -0
  119. package/src/methods/settings/index.ts +2 -0
  120. package/src/methods/settings/launchSettings.ts +25 -0
  121. package/src/methods/settings/modifySettings.ts +99 -0
  122. package/src/methods/stream/clickVideo.ts +337 -0
  123. package/src/methods/stream/index.ts +3 -0
  124. package/src/methods/stream/switchAudio.ts +73 -0
  125. package/src/methods/stream/switchVideo.ts +148 -0
  126. package/src/methods/stream/switchVideoAlt.ts +152 -0
  127. package/src/methods/utils/checkLimitsAndMakeRequest.ts +103 -0
  128. package/src/methods/utils/validateAlphanumeric.ts +41 -0
  129. package/src/methods/waiting/index.ts +1 -0
  130. package/src/methods/waiting/launchWaiting.ts +26 -0
  131. package/src/methods/waiting/respondToWaiting.ts +82 -0
  132. package/src/methods/welcome/handleWelcomeRequest.ts +189 -0
  133. package/src/methods/welcome/index.ts +5 -0
  134. package/src/methods/whiteboard/handleStartWhiteboard.ts +65 -0
  135. package/src/methods/whiteboard/handleStopWhiteboard.ts +48 -0
  136. package/src/methods/whiteboard/index.ts +4 -0
  137. package/src/methods/whiteboard/launchConfigureWhiteboard.ts +29 -0
  138. package/src/producers/producerEmits/joinConRoom.ts +153 -0
  139. package/src/sockets/SocketManager.ts +232 -0
  140. package/src/types/shared-base-types.ts +752 -0
  141. package/src/types/types.ts +84 -0
@@ -0,0 +1,143 @@
1
+ import type { Producer } from 'mediasoup-client/lib/types';
2
+ import { PrepopulateUserMediaParameters, PrepopulateUserMediaType } from "../types/types";
3
+
4
+ export interface ResumeSendTransportAudioParameters extends PrepopulateUserMediaParameters {
5
+ audioProducer: Producer | null;
6
+ localAudioProducer?: Producer | null;
7
+ islevel: string;
8
+ hostLabel: string;
9
+ lock_screen: boolean;
10
+ shared: boolean;
11
+ videoAlreadyOn: boolean;
12
+ updateAudioProducer: (audioProducer: Producer | null) => void;
13
+ updateLocalAudioProducer?: (localAudioProducer: Producer | null) => void;
14
+ updateUpdateMainWindow: (updateMainWindow: boolean) => void;
15
+
16
+ // mediasfu functions
17
+ prepopulateUserMedia: PrepopulateUserMediaType;
18
+ prepopulateLocalUserMedia?: PrepopulateUserMediaType;
19
+ [key: string]: any;
20
+ }
21
+
22
+ export interface ResumeSendTransportAudioOptions {
23
+ parameters: ResumeSendTransportAudioParameters;
24
+ }
25
+
26
+ // Export the type definition for the function
27
+ export type ResumeSendTransportAudioType = (options: ResumeSendTransportAudioOptions) => Promise<void>;
28
+
29
+ const resumeLocalSendTransportAudio = async ({
30
+ parameters,
31
+ }: ResumeSendTransportAudioOptions): Promise<void> => {
32
+ try {
33
+ const {
34
+ localAudioProducer,
35
+ updateLocalAudioProducer,
36
+ } = parameters;
37
+
38
+ // Resume local audio producer
39
+ if (localAudioProducer) {
40
+ localAudioProducer.resume();
41
+ updateLocalAudioProducer?.(localAudioProducer);
42
+ }
43
+ } catch (error) {
44
+ console.error("Error resuming local audio send transport:", error);
45
+ throw error; // Re-throw to propagate the error
46
+ }
47
+ };
48
+
49
+ /**
50
+ * Resumes the send transport for audio and updates the UI and audio producer state accordingly.
51
+ *
52
+ * This function supports both a primary and a local audio producer, delegating the local logic to a separate function.
53
+ *
54
+ * @param {ResumeSendTransportAudioOptions} options - The options for resuming the send transport.
55
+ * @param {ResumeSendTransportAudioParameters} options.parameters - The parameters for resuming the send transport.
56
+ * @param {Producer} options.parameters.audioProducer - The primary audio producer to resume.
57
+ * @param {Producer} [options.parameters.localAudioProducer] - The local audio producer to resume.
58
+ * @param {string} options.parameters.islevel - The level of the audio producer.
59
+ * @param {string} options.parameters.hostLabel - The label for the host.
60
+ * @param {boolean} options.parameters.lock_screen - Indicates if the screen is locked.
61
+ * @param {boolean} options.parameters.shared - Indicates if the screen is shared.
62
+ * @param {boolean} options.parameters.videoAlreadyOn - Indicates if the video is already on.
63
+ * @param {Function} options.parameters.updateAudioProducer - Function to update the audio producer state.
64
+ * @param {Function} [options.parameters.updateLocalAudioProducer] - Function to update the local audio producer state.
65
+ * @param {Function} options.parameters.updateUpdateMainWindow - Function to update the main window.
66
+ * @param {Function} options.parameters.prepopulateUserMedia - Function to prepopulate user media.
67
+ * @returns {Promise<void>} A promise that resolves when the send transport is resumed and the UI is updated.
68
+ *
69
+ * @throws {Error} Throws an error if there is an issue during the process of resuming the audio send transport.
70
+ *
71
+ * @example
72
+ * ```typescript
73
+ * await resumeSendTransportAudio({
74
+ * parameters: {
75
+ * audioProducer: producer,
76
+ * localAudioProducer: localProducer,
77
+ * islevel: '1',
78
+ * hostLabel: 'Host',
79
+ * lock_screen: false,
80
+ * shared: false,
81
+ * updateAudioProducer: updateProducerFunction,
82
+ * updateLocalAudioProducer: updateLocalProducerFunction,
83
+ * videoAlreadyOn: false,
84
+ * updateUpdateMainWindow: updateWindowFunction,
85
+ * prepopulateUserMedia: prepopulateFunction,
86
+ * prepopulateLocalUserMedia: prepopulateLocalFunction,
87
+ * },
88
+ * });
89
+ * ```
90
+ */
91
+
92
+ export const resumeSendTransportAudio: ResumeSendTransportAudioType = async ({
93
+ parameters,
94
+ }: ResumeSendTransportAudioOptions): Promise<void> => {
95
+ try {
96
+ const {
97
+ audioProducer,
98
+ islevel,
99
+ hostLabel,
100
+ lock_screen,
101
+ shared,
102
+ updateAudioProducer,
103
+ videoAlreadyOn,
104
+ updateUpdateMainWindow,
105
+
106
+ //mediasfu functions
107
+ prepopulateUserMedia,
108
+ } = parameters;
109
+
110
+ // Resume send transport for audio
111
+ audioProducer!.resume();
112
+
113
+ // Update UI for primary producer
114
+ if (!videoAlreadyOn && islevel === "2") {
115
+ if (!lock_screen && !shared) {
116
+ let updatedMainWindow = true;
117
+ updateUpdateMainWindow(updatedMainWindow);
118
+ await prepopulateUserMedia({ name: hostLabel, parameters });
119
+ updatedMainWindow = false;
120
+ updateUpdateMainWindow(updatedMainWindow);
121
+ }
122
+ }
123
+
124
+ // Update audio producer state
125
+ updateAudioProducer(audioProducer);
126
+
127
+ // Attempt to handle local audio producer if primary fails
128
+ try {
129
+ await resumeLocalSendTransportAudio({ parameters });
130
+ } catch (localError) {
131
+ console.error(
132
+ "local audio send transport resuming failed:",
133
+ localError
134
+ );
135
+ }
136
+ } catch (error: any) {
137
+ // Handle errors during the process of resuming the audio send transport
138
+ throw new Error(
139
+ `Error during resuming audio send transport: ${error.message}`
140
+ );
141
+
142
+ }
143
+ };
@@ -0,0 +1,179 @@
1
+ import { Socket } from "socket.io-client";
2
+ import { ReorderStreamsParameters, ReorderStreamsType, ConnectRecvTransportType,
3
+ ConnectRecvTransportParameters, CreateWebRTCTransportResponse } from "../types/types";
4
+ import type { Device, DtlsParameters } from 'mediasoup-client/lib/types';
5
+
6
+ export interface SignalNewConsumerTransportParameters extends ReorderStreamsParameters, ConnectRecvTransportParameters {
7
+ device: Device | null;
8
+ consumingTransports: string[];
9
+ lock_screen: boolean;
10
+ updateConsumingTransports: (transports: string[]) => void;
11
+ connectRecvTransport: ConnectRecvTransportType;
12
+ reorderStreams: ReorderStreamsType;
13
+ getUpdatedAllParams: () => SignalNewConsumerTransportParameters;
14
+ [key: string]: any;
15
+ }
16
+
17
+ export interface SignalNewConsumerTransportOptions {
18
+ remoteProducerId: string;
19
+ islevel: string;
20
+ nsock: Socket;
21
+ parameters: SignalNewConsumerTransportParameters;
22
+ }
23
+
24
+ // Export the type definition for the function
25
+ export type SignalNewConsumerTransportType = (options: SignalNewConsumerTransportOptions) => Promise<string[] | void>;
26
+
27
+ /**
28
+ * Signals the creation of a new consumer transport.
29
+ *
30
+ * @param {SignalNewConsumerTransportOptions} options - The options for signaling a new consumer transport.
31
+ * @param {string} options.remoteProducerId - The ID of the remote producer.
32
+ * @param {string} options.islevel - Indicates the level of the consumer.
33
+ * @param {Socket} options.nsock - The socket instance for communication.
34
+ * @param {SignalNewConsumerTransportParameters} options.parameters - The parameters for the transport.
35
+ *
36
+ * @returns {Promise<string[] | void>} A promise that resolves to an array of consuming transports or void.
37
+ *
38
+ * @throws Will throw an error if the signaling process fails.
39
+ *
40
+ * @example
41
+ * const options = {
42
+ * remoteProducerId: 'producer-id',
43
+ * islevel: '1',
44
+ * nsock: socketInstance,
45
+ * parameters: {
46
+ * device: mediaDevice,
47
+ * consumingTransports: [],
48
+ * lock_screen: false,
49
+ * updateConsumingTransports: updateFunction,
50
+ * connectRecvTransport: connectFunction,
51
+ * reorderStreams: reorderFunction,
52
+ * getUpdatedAllParams: getUpdatedParamsFunction,
53
+ * },
54
+ * };
55
+ *
56
+ * signalNewConsumerTransport(options)
57
+ * .then(consumingTransports => {
58
+ * console.log('Consuming Transports:', consumingTransports);
59
+ * })
60
+ * .catch(error => {
61
+ * console.error('Error signaling new consumer transport:', error);
62
+ * });
63
+ */
64
+
65
+ export const signalNewConsumerTransport = async ({
66
+ remoteProducerId,
67
+ islevel,
68
+ nsock,
69
+ parameters,
70
+ }: SignalNewConsumerTransportOptions): Promise<string[] | void> => {
71
+ try {
72
+ let {
73
+ device,
74
+ consumingTransports,
75
+ lock_screen,
76
+ updateConsumingTransports,
77
+ connectRecvTransport,
78
+ reorderStreams,
79
+ } = parameters;
80
+
81
+ // Get updated parameters
82
+ const updatedParams = parameters.getUpdatedAllParams();
83
+ device = updatedParams.device;
84
+ consumingTransports = updatedParams.consumingTransports;
85
+
86
+ // Check if already consuming
87
+ if (consumingTransports.includes(remoteProducerId)) {
88
+ return consumingTransports;
89
+ }
90
+
91
+ // Add remote producer ID to consumingTransports array
92
+ consumingTransports.push(remoteProducerId);
93
+ updateConsumingTransports(consumingTransports);
94
+
95
+ // Emit createWebRtcTransport event to signal a new consumer
96
+ nsock.emit(
97
+ "createWebRtcTransport",
98
+ { consumer: true, islevel },
99
+ async ({ params }: { params: CreateWebRTCTransportResponse }) => {
100
+ if (params.error) {
101
+ // Handle error
102
+ return;
103
+ }
104
+
105
+ try {
106
+ // Create a new receiving transport using the received parameters
107
+ const consumerTransport = device!.createRecvTransport({ ...params });
108
+
109
+ // Handle 'connect' event for the consumer transport
110
+ consumerTransport.on(
111
+ "connect",
112
+ async (
113
+ { dtlsParameters }: { dtlsParameters: DtlsParameters },
114
+ callback: () => void,
115
+ errback: (error: any) => void
116
+ ) => {
117
+ try {
118
+ // Emit transport-recv-connect event to signal connection
119
+ nsock.emit("transport-recv-connect", {
120
+ dtlsParameters,
121
+ serverConsumerTransportId: params.id,
122
+ });
123
+ callback();
124
+ } catch (error) {
125
+ errback(error);
126
+ }
127
+ }
128
+ );
129
+
130
+ // Listen for connection state change
131
+ consumerTransport.on("connectionstatechange", async (state: string) => {
132
+ switch (state) {
133
+ case "connecting":
134
+ // Handle connecting state
135
+ break;
136
+
137
+ case "connected":
138
+ // Handle connected state
139
+ break;
140
+
141
+ case "failed":
142
+ // Handle failed state
143
+ consumerTransport.close();
144
+
145
+ // Reorder streams based on conditions
146
+ if (lock_screen) {
147
+ await reorderStreams({ add: true, parameters });
148
+ } else {
149
+ await reorderStreams({ add: false, parameters });
150
+ }
151
+ break;
152
+
153
+ default:
154
+ break;
155
+ }
156
+ });
157
+
158
+ // Connect the receiving transport
159
+ await connectRecvTransport({
160
+ consumerTransport,
161
+ remoteProducerId,
162
+ serverConsumerTransportId: params.id,
163
+ nsock,
164
+ parameters,
165
+ });
166
+ } catch (error) {
167
+ console.log(error, "createRecvTransport error");
168
+ // Handle error
169
+ return;
170
+ }
171
+ }
172
+ );
173
+ } catch (error) {
174
+ console.log(error, "signalNewConsumerTransport error");
175
+ // Handle error
176
+ return;
177
+ }
178
+ };
179
+
@@ -0,0 +1,130 @@
1
+ import { joinConRoom } from '../../producers/producerEmits/joinConRoom';
2
+ import type { Device, RtpCapabilities } from 'mediasoup-client/lib/types';
3
+ import { Socket } from 'socket.io-client';
4
+ import { ReceiveAllPipedTransportsParameters, ReceiveAllPipedTransportsType, CreateDeviceClientType } from '../../types/types';
5
+
6
+
7
+ export interface JoinConsumeRoomParameters extends ReceiveAllPipedTransportsParameters {
8
+ roomName: string;
9
+ islevel: string;
10
+ member: string;
11
+ device: Device | null;
12
+ updateDevice: (device: Device | null) => void;
13
+
14
+ // Mediasfu functions
15
+ receiveAllPipedTransports: ReceiveAllPipedTransportsType;
16
+ createDeviceClient: CreateDeviceClientType;
17
+ getUpdatedAllParams: () => JoinConsumeRoomParameters;
18
+ [key: string]: any;
19
+ }
20
+ export interface JoinConsumeRoomOptions {
21
+ remote_sock: Socket;
22
+ apiToken: string;
23
+ apiUserName: string;
24
+ parameters: JoinConsumeRoomParameters;
25
+ }
26
+
27
+ interface JoinConsumeRoomResponse {
28
+ success: boolean;
29
+ rtpCapabilities?: RtpCapabilities | null;
30
+ }
31
+
32
+ // Export the type definition for the function
33
+ export type JoinConsumeRoomType = (options: JoinConsumeRoomOptions) => Promise<JoinConsumeRoomResponse>;
34
+
35
+ /**
36
+ * Joins a consumption room by sending a request to the server, handling device setup, and managing piped transports.
37
+ *
38
+ * @function
39
+ * @async
40
+ * @param {Object} options - The configuration options.
41
+ * @param {Socket} options.remote_sock - The remote socket for communication.
42
+ * @param {string} options.apiToken - The API token for authentication.
43
+ * @param {string} options.apiUserName - The API username for authentication.
44
+ * @param {JoinConsumeRoomParameters} options.parameters - Additional parameters including room details and Mediasoup configurations.
45
+ * @returns {Promise<JoinConsumeRoomResponse>} - An object indicating the success of joining the room and optional RTP capabilities.
46
+ * @throws {Error} Throws an error if joining the room or setup fails.
47
+ *
48
+ * @example
49
+ * import { joinConsumeRoom } from 'mediasfu-reactjs';
50
+ * import { io } from 'socket.io-client';
51
+ *
52
+ * const apiToken = 'your-api-token';
53
+ * const apiUserName = 'your-api-username';
54
+ * const remote_sock = io("http://localhost:3000");
55
+ *
56
+ * const parameters = {
57
+ * roomName: 'room-name',
58
+ * islevel: '2',
59
+ * member: 'user-id',
60
+ * device: null,
61
+ * updateDevice: (device) => console.log('Device updated:', device),
62
+ * receiveAllPipedTransports: (params) => console.log('Receiving all piped transports:', params),
63
+ * createDeviceClient: async (params) => { // Device client setup logic },
64
+ * getUpdatedAllParams: () => console.log('Getting updated parameters'),
65
+ * };
66
+ *
67
+ * async function init() {
68
+ * try {
69
+ * const data = await joinConsumeRoom({
70
+ * remote_sock,
71
+ * apiToken,
72
+ * apiUserName,
73
+ * parameters,
74
+ * });
75
+ * console.log('Joined room:', data);
76
+ * } catch (error) {
77
+ * console.error('Error joining room:', error);
78
+ * }
79
+ * }
80
+ * init();
81
+ * // Expected output: { success: true, rtpCapabilities: { ... } }
82
+ */
83
+
84
+
85
+ export const joinConsumeRoom = async ({
86
+ remote_sock,
87
+ apiToken,
88
+ apiUserName,
89
+ parameters,
90
+ }: JoinConsumeRoomOptions): Promise<JoinConsumeRoomResponse> => {
91
+ const {
92
+ roomName,
93
+ islevel,
94
+ member,
95
+ device,
96
+ updateDevice,
97
+
98
+ // Mediasfu functions
99
+ receiveAllPipedTransports,
100
+ createDeviceClient,
101
+ } = parameters;
102
+
103
+ try {
104
+ // Join the consumption room
105
+ const data: JoinConsumeRoomResponse = await joinConRoom({ socket: remote_sock, roomName, islevel, member, sec: apiToken, apiUserName });
106
+
107
+ if (data && data.success) {
108
+ // Setup media device if not already set
109
+ if (!device) {
110
+ if (data.rtpCapabilities) {
111
+ const device_: Device | null = await createDeviceClient({
112
+ rtpCapabilities: data.rtpCapabilities,
113
+ });
114
+
115
+ if (device_) {
116
+ updateDevice(device_);
117
+ }
118
+ }
119
+ }
120
+
121
+ // Receive all piped transports
122
+ await receiveAllPipedTransports({ nsock: remote_sock, parameters });
123
+ }
124
+
125
+ return data;
126
+ } catch (error) {
127
+ console.error('Error in joinConsumeRoom:', error);
128
+ throw new Error('Failed to join the consumption room or set up necessary components.');
129
+ }
130
+ };
@@ -0,0 +1,138 @@
1
+ import { Socket } from 'socket.io-client';
2
+ import { signalNewConsumerTransport } from '../signalNewConsumerTransport';
3
+ import { ReorderStreamsParameters, ReorderStreamsType, SignalNewConsumerTransportParameters, ConnectRecvTransportParameters, ConnectRecvTransportType, ShowAlert } from '../../types/types';
4
+ import type { Device } from 'mediasoup-client/lib/types';
5
+ export interface NewPipeProducerParameters extends ReorderStreamsParameters, SignalNewConsumerTransportParameters, ConnectRecvTransportParameters {
6
+
7
+ first_round: boolean;
8
+ shareScreenStarted: boolean;
9
+ shared: boolean;
10
+ landScaped: boolean;
11
+ showAlert?: ShowAlert;
12
+ isWideScreen: boolean;
13
+ updateFirst_round: (firstRound: boolean) => void;
14
+ updateLandScaped: (landScaped: boolean) => void;
15
+ device: Device | null;
16
+ consumingTransports: string[];
17
+ lock_screen: boolean;
18
+ updateConsumingTransports: (transports: string[]) => void;
19
+
20
+ // mediasfu functions
21
+ connectRecvTransport: ConnectRecvTransportType;
22
+ reorderStreams: ReorderStreamsType;
23
+ getUpdatedAllParams: () => NewPipeProducerParameters;
24
+ [key: string]: any;
25
+
26
+ }
27
+
28
+ export interface NewPipeProducerOptions {
29
+ producerId: string;
30
+ islevel: string;
31
+ nsock: Socket;
32
+ parameters: NewPipeProducerParameters;
33
+ }
34
+
35
+ // Export the type definition for the function
36
+ export type NewPipeProducerType = (options: NewPipeProducerOptions) => Promise<void>;
37
+
38
+
39
+ /**
40
+ * Handles the creation of a new pipe producer by signaling for a new consumer transport and updating the necessary parameters.
41
+ *
42
+ * @function
43
+ * @async
44
+ * @param {NewPipeProducerOptions} options - The options for the new pipe producer.
45
+ * @param {string} options.producerId - The ID of the producer to be consumed.
46
+ * @param {string} options.islevel - The level status of the participant.
47
+ * @param {Socket} options.nsock - The socket instance for real-time communication.
48
+ * @param {NewPipeProducerParameters} options.parameters - Additional parameters required for the producer.
49
+ * @param {boolean} options.parameters.shareScreenStarted - Indicates if screen sharing has started.
50
+ * @param {boolean} options.parameters.shared - Indicates if sharing is active.
51
+ * @param {boolean} options.parameters.landScaped - Indicates if the device is in landscape mode.
52
+ * @param {ShowAlert} options.parameters.showAlert - Function to show alerts to the user.
53
+ * @param {boolean} options.parameters.isWideScreen - Indicates if the device is a widescreen.
54
+ * @param {Function} options.parameters.updateFirst_round - Function to update the first round status.
55
+ * @param {Function} options.parameters.updateLandScaped - Function to update the landscape status.
56
+ * @returns {Promise<void>} A promise that resolves when the operation is complete.
57
+ * @throws {Error} Will throw an error if the operation fails to signal the new consumer transport.
58
+ *
59
+ * @example
60
+ * import { newPipeProducer } from 'mediasfu-reactjs';
61
+ * import { io } from 'socket.io-client';
62
+ *
63
+ * const parameters = {
64
+ * shareScreenStarted: true,
65
+ * shared: true,
66
+ * landScaped: false,
67
+ * showAlert: (alert) => console.log(alert.message),
68
+ * isWideScreen: false,
69
+ * updateFirst_round: (firstRound) => console.log('First round updated:', firstRound),
70
+ * updateLandScaped: (landScaped) => console.log('Landscape status updated:', landScaped),
71
+ * };
72
+ *
73
+ * const producerId = 'producer-123';
74
+ * const islevel = '2';
75
+ * const nsock = io("http://localhost:3000");
76
+ *
77
+ * async function init() {
78
+ * try {
79
+ * await newPipeProducer({
80
+ * producerId,
81
+ * islevel,
82
+ * nsock,
83
+ * parameters,
84
+ * });
85
+ * console.log('New pipe producer created successfully');
86
+ * } catch (error) {
87
+ * console.error('Error creating new pipe producer:', error);
88
+ * }
89
+ * }
90
+ *
91
+ * init();
92
+ */
93
+
94
+ export const newPipeProducer = async ({
95
+ producerId,
96
+ islevel,
97
+ nsock,
98
+ parameters,
99
+ }: NewPipeProducerOptions): Promise<void> => {
100
+ const {
101
+ shareScreenStarted,
102
+ shared,
103
+ landScaped,
104
+ showAlert,
105
+ isWideScreen,
106
+ updateFirst_round,
107
+ updateLandScaped,
108
+ } = parameters;
109
+
110
+ // Signal new consumer transport
111
+ await signalNewConsumerTransport({
112
+ remoteProducerId: producerId,
113
+ islevel,
114
+ nsock,
115
+ parameters
116
+ });
117
+
118
+ // Modify first_round and landscape status
119
+ let updatedFirstRound = false;
120
+
121
+ if (shareScreenStarted || shared) {
122
+ if (!isWideScreen) {
123
+ if (!landScaped) {
124
+ if (showAlert) {
125
+ showAlert({
126
+ message: 'Please rotate your device to landscape mode for better experience',
127
+ type: 'success',
128
+ duration: 3000,
129
+ });
130
+ }
131
+ updateLandScaped(true);
132
+ }
133
+ }
134
+
135
+ updatedFirstRound = true;
136
+ updateFirst_round(updatedFirstRound);
137
+ }
138
+ };
@@ -0,0 +1,102 @@
1
+ import { Transport, CloseAndResizeParameters, CloseAndResizeType } from '../../types/types';
2
+
3
+ export interface ProducerClosedParameters extends CloseAndResizeParameters {
4
+ consumerTransports: Transport[];
5
+ screenId?: string;
6
+ updateConsumerTransports: (transports: Transport[]) => void;
7
+
8
+ // mediasfu functions
9
+ closeAndResize: CloseAndResizeType;
10
+ getUpdatedAllParams: () => ProducerClosedParameters;
11
+ [key: string]: any;
12
+
13
+ }
14
+
15
+ export interface ProducerClosedOptions {
16
+ remoteProducerId: string;
17
+ parameters: ProducerClosedParameters;
18
+ }
19
+
20
+ // Export the type definition for the function
21
+ export type ProducerClosedType = (options: ProducerClosedOptions) => Promise<void>;
22
+
23
+ /**
24
+ * Handles the closure of a producer identified by its remote producer ID.
25
+ * This function will clean up the consumer transports and resize the video outputs.
26
+ *
27
+ * @function
28
+ * @async
29
+ * @param {ProducerClosedOptions} options - The options for closing the producer.
30
+ * @param {string} options.remoteProducerId - The ID of the remote producer to close.
31
+ * @param {ProducerClosedParameters} options.parameters - Additional parameters for the operation.
32
+ * @param {Transport[]} options.parameters.consumerTransports - The list of consumer transports associated with the producer.
33
+ * @param {Function} options.parameters.closeAndResize - Function to handle the closing and resizing of video streams.
34
+ * @param {string} [options.parameters.screenId] - The ID of the screen producer (if applicable).
35
+ * @param {Function} options.parameters.updateConsumerTransports - Function to update the state of consumer transports.
36
+ * @returns {Promise<void>} A promise that resolves when the producer has been successfully closed.
37
+ * @throws Will throw an error if there is an issue closing the consumer transport or the producer.
38
+ *
39
+ * @example
40
+ * import { producerClosed } from 'mediasfu-reactjs';
41
+ *
42
+ * const options = {
43
+ * remoteProducerId: 'producerId',
44
+ * parameters: {
45
+ * consumerTransports: [], // Array of consumer transports
46
+ * closeAndResize: (params) => console.log('Close and resize called', params),
47
+ * screenId: 'screenId',
48
+ * updateConsumerTransports: (transports) => console.log('Updated transports:', transports),
49
+ * },
50
+ * };
51
+ *
52
+ * producerClosed(options)
53
+ * .then(() => {
54
+ * console.log('Producer closed successfully');
55
+ * })
56
+ * .catch((error) => {
57
+ * console.error('Error closing producer:', error);
58
+ * });
59
+ */
60
+ export const producerClosed = async ({
61
+ remoteProducerId,
62
+ parameters,
63
+ }: ProducerClosedOptions): Promise<void> => {
64
+ let { consumerTransports, closeAndResize, screenId, updateConsumerTransports } = parameters;
65
+
66
+ // Handle producer closed
67
+ const producerToClose = consumerTransports.find(
68
+ (transportData: any) => transportData.producerId === remoteProducerId
69
+ );
70
+
71
+ if (!producerToClose) {
72
+ return;
73
+ }
74
+
75
+ // Check if the ID of the producer to close is the same as the screenId
76
+ let kind: string = producerToClose.consumer.kind;
77
+
78
+ if (producerToClose.producerId === screenId) {
79
+ kind = 'screenshare';
80
+ }
81
+
82
+ try {
83
+ await producerToClose.consumerTransport.close();
84
+ } catch (error) {
85
+ console.error('Error closing consumer transport:', error);
86
+ }
87
+
88
+ try {
89
+ producerToClose.consumer.close();
90
+ } catch (error) {
91
+ console.error('Error closing consumer:', error);
92
+ }
93
+
94
+ // Filter out the closed producer
95
+ consumerTransports = consumerTransports.filter(
96
+ (transportData: any) => transportData.producerId !== remoteProducerId
97
+ );
98
+ updateConsumerTransports(consumerTransports);
99
+
100
+ // Close and resize the videos
101
+ await closeAndResize({ producerId: remoteProducerId, kind, parameters });
102
+ };