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,122 @@
1
+ import { TriggerType, TriggerParameters } from '../types/types';
2
+
3
+ export interface CompareActiveNamesParameters extends TriggerParameters {
4
+ activeNames: string[];
5
+ prevActiveNames: string[];
6
+ updateActiveNames: (activeNames: string[]) => void;
7
+ updatePrevActiveNames: (prevActiveNames: string[]) => void;
8
+
9
+ // mediasfu functions
10
+ trigger: TriggerType;
11
+ getUpdatedAllParams: () => CompareActiveNamesParameters;
12
+ [key: string]: any;
13
+ }
14
+
15
+ export interface CompareActiveNamesOptions {
16
+ restart?: boolean;
17
+ parameters: CompareActiveNamesParameters;
18
+ }
19
+
20
+ // Export the type definition for the function
21
+ export type CompareActiveNamesType = (options: CompareActiveNamesOptions) => Promise<void>;
22
+
23
+ /**
24
+ * Compares the current active names with the previous active names and triggers an action if there are changes.
25
+ *
26
+ * @param {CompareActiveNamesOptions} options - The options for comparing active names.
27
+ * @param {boolean} [options.restart=false] - Whether to restart the comparison.
28
+ * @param {CompareActiveNamesParameters} options.parameters - The parameters for the comparison.
29
+ * @param {Function} options.parameters.getUpdatedAllParams - Function to get updated parameters.
30
+ * @param {string[]} options.parameters.activeNames - The current active names.
31
+ * @param {string[]} options.parameters.prevActiveNames - The previous active names.
32
+ * @param {Function} options.parameters.updatePrevActiveNames - Function to update the previous active names.
33
+ * @param {Function} options.parameters.trigger - Function to trigger an action when names change.
34
+ *
35
+ * @returns {Promise<void>} A promise that resolves when the comparison is complete.
36
+ *
37
+ * @throws Will log an error message if an error occurs during the comparison.
38
+ *
39
+ * @example
40
+ * const options = {
41
+ * restart: false,
42
+ * parameters: {
43
+ * getUpdatedAllParams: getUpdatedAllParamsFunction,
44
+ * activeNames: ['name1', 'name2'],
45
+ * prevActiveNames: ['name1'],
46
+ * updatePrevActiveNames: updatePrevActiveNamesFunction,
47
+ * trigger: triggerFunction,
48
+ * },
49
+ * };
50
+ *
51
+ * compareActiveNames(options)
52
+ * .then(() => {
53
+ * console.log('Active names compared successfully');
54
+ * });
55
+ */
56
+
57
+ export async function compareActiveNames({
58
+ restart = false,
59
+ parameters,
60
+ }: CompareActiveNamesOptions): Promise<void> {
61
+ try {
62
+ const { getUpdatedAllParams } = parameters;
63
+ parameters = getUpdatedAllParams();
64
+
65
+ const {
66
+ activeNames,
67
+ prevActiveNames,
68
+ updatePrevActiveNames,
69
+
70
+ //mediasfu functions
71
+ trigger,
72
+ } = parameters;
73
+
74
+ // Restart the comparison if needed
75
+ if (restart) {
76
+ await trigger({ ref_ActiveNames: activeNames, parameters });
77
+ return;
78
+ }
79
+
80
+ // Array to track changes in activeNames
81
+ const nameChanged: boolean[] = [];
82
+
83
+ // Compare each name in activeNames
84
+ for (let i = 0; i < activeNames.length; i++) {
85
+ const currentName = activeNames[i];
86
+
87
+ // Check if the name is present in prevActiveNames
88
+ const hasNameChanged = !prevActiveNames.includes(currentName);
89
+
90
+ if (hasNameChanged) {
91
+ nameChanged.push(true);
92
+ await trigger({ ref_ActiveNames: activeNames, parameters });
93
+ break;
94
+ }
95
+ }
96
+
97
+ // Count the number of `true` in nameChanged
98
+ const count = nameChanged.filter((value) => value === true).length;
99
+
100
+ if (count < 1) {
101
+ // Check for new names in prevActiveNames
102
+ for (let i = 0; i < prevActiveNames.length; i++) {
103
+ const currentName = prevActiveNames[i];
104
+
105
+ // Check if the name is present in activeNames
106
+ const hasNameChanged = !activeNames.includes(currentName);
107
+
108
+ // Signal change if the name is new
109
+ if (hasNameChanged) {
110
+ await trigger({ ref_ActiveNames: activeNames, parameters });
111
+ break;
112
+ }
113
+ }
114
+ }
115
+
116
+ // Update prevActiveNames with current activeNames
117
+ updatePrevActiveNames([...activeNames]);
118
+ } catch (error) {
119
+ console.log("compareActiveNames error", error);
120
+ // throw error; (Optional: Keep or remove depending on your error handling strategy)
121
+ }
122
+ }
@@ -0,0 +1,117 @@
1
+ import { ScreenState, TriggerType, TriggerParameters } from '../types/types';
2
+
3
+ export interface CompareScreenStatesParameters extends TriggerParameters {
4
+ recordingDisplayType: 'video' | 'media' | 'all';
5
+ recordingVideoOptimized: boolean;
6
+ screenStates: ScreenState[];
7
+ prevScreenStates: ScreenState[];
8
+ activeNames: string[];
9
+
10
+ // mediasfu functions
11
+ trigger: TriggerType;
12
+ getUpdatedAllParams: () => CompareScreenStatesParameters;
13
+ [key: string]: any;
14
+ }
15
+
16
+ export interface CompareScreenStatesOptions {
17
+ restart?: boolean;
18
+ parameters: CompareScreenStatesParameters;
19
+ }
20
+
21
+ // Export the type definition for the function
22
+ export type CompareScreenStatesType = (options: CompareScreenStatesOptions) => Promise<void>;
23
+
24
+ /**
25
+ * Compares the current screen states with the previous screen states and triggers actions based on changes.
26
+ *
27
+ * @param {CompareScreenStatesOptions} options - The options for comparing screen states.
28
+ * @param {boolean} [options.restart=false] - Whether to restart the comparison process.
29
+ * @param {CompareScreenStatesParameters} options.parameters - The parameters for the comparison.
30
+ * @param {Function} options.parameters.getUpdatedAllParams - Function to get updated parameters.
31
+ * @param {string} options.parameters.recordingDisplayType - The type of display being recorded.
32
+ * @param {boolean} options.parameters.recordingVideoOptimized - Whether the recording is optimized for video.
33
+ * @param {Array<ScreenState>} options.parameters.screenStates - The current screen states.
34
+ * @param {Array<ScreenState>} options.parameters.prevScreenStates - The previous screen states.
35
+ * @param {Array<string>} options.parameters.activeNames - The active names in the current context.
36
+ * @param {Function} options.parameters.trigger - Function to trigger actions based on changes.
37
+ *
38
+ * @returns {Promise<void>} A promise that resolves when the comparison and any triggered actions are complete.
39
+ *
40
+ * @throws Will log an error message if an error occurs during the comparison process.
41
+ *
42
+ * @example
43
+ * const options = {
44
+ * restart: false,
45
+ * parameters: {
46
+ * getUpdatedAllParams: getUpdatedAllParamsFunction,
47
+ * recordingDisplayType: 'video',
48
+ * recordingVideoOptimized: true,
49
+ * screenStates: [{ key1: 'value1' }, { key2: 'value2' }],
50
+ * prevScreenStates: [{ key1: 'value1' }, { key2: 'value2' }],
51
+ * activeNames: ['name1', 'name2'],
52
+ * trigger: triggerFunction,
53
+ * },
54
+ * };
55
+ *
56
+ * compareScreenStates(options)
57
+ * .then(() => {
58
+ * console.log('Screen states compared successfully');
59
+ * });
60
+ */
61
+
62
+ export async function compareScreenStates({
63
+ restart = false,
64
+ parameters,
65
+ }: CompareScreenStatesOptions): Promise<void> {
66
+ try {
67
+ const { getUpdatedAllParams } = parameters;
68
+ parameters = getUpdatedAllParams();
69
+
70
+ const {
71
+ recordingDisplayType,
72
+ recordingVideoOptimized,
73
+ screenStates,
74
+ prevScreenStates,
75
+ activeNames,
76
+
77
+ //mediasfu functions
78
+ trigger,
79
+ } = parameters;
80
+
81
+ // Restart the comparison if needed
82
+ if (restart) {
83
+ // Perform necessary actions on restart
84
+ return;
85
+ }
86
+
87
+ // Compare each key-value pair in the screenStates objects
88
+ for (let i = 0; i < screenStates.length; i++) {
89
+ const currentScreenState = screenStates[i];
90
+ const prevScreenState = prevScreenStates[i];
91
+
92
+ // Check if any value has changed
93
+ const hasChanged = (Object.keys(currentScreenState) as (keyof ScreenState)[]).some(
94
+ (key) => currentScreenState[key] !== prevScreenState[key]
95
+ );
96
+
97
+ // Signal change if any value has changed
98
+ if (hasChanged) {
99
+ // Perform actions or trigger events based on the change
100
+ if (recordingDisplayType === 'video') {
101
+ if (recordingVideoOptimized) {
102
+ await trigger({
103
+ ref_ActiveNames: activeNames,
104
+ parameters,
105
+ });
106
+ break;
107
+ }
108
+ }
109
+ await trigger({ ref_ActiveNames: activeNames, parameters });
110
+ break;
111
+ }
112
+ }
113
+ } catch (error) {
114
+ console.log('compareScreenStates error', error);
115
+ // Optionally re-throw the error for further handling
116
+ }
117
+ }
@@ -0,0 +1,175 @@
1
+
2
+ import { connectSocket } from "../../src/sockets/SocketManager";
3
+ import { newPipeProducer } from "./socketReceiveMethods/newPipeProducer";
4
+ import { producerClosed } from "./socketReceiveMethods/producerClosed";
5
+ import { joinConsumeRoom } from "./socketReceiveMethods/joinConsumeRoom";
6
+ import type { Device } from 'mediasoup-client/lib/types';
7
+ import {
8
+ ReorderStreamsParameters, ReorderStreamsType, NewPipeProducerParameters, NewPipeProducerType, ProducerClosedType,
9
+ ProducerClosedParameters, JoinConsumeRoomType, JoinConsumeRoomParameters, ConsumeSocket
10
+ } from '../types/types';
11
+
12
+ export interface ConnectIpsParameters extends ReorderStreamsParameters, JoinConsumeRoomParameters, ProducerClosedParameters, NewPipeProducerParameters {
13
+ device: Device | null;
14
+ roomRecvIPs: string[];
15
+ updateRoomRecvIPs: (roomRecvIPs: string[]) => void;
16
+ updateConsume_sockets: (consume_sockets: ConsumeSocket[]) => void;
17
+
18
+ // mediasfu functions
19
+ reorderStreams: ReorderStreamsType;
20
+ getUpdatedAllParams: () => ConnectIpsParameters;
21
+ [key: string]: any;
22
+ }
23
+
24
+ export interface ConnectIpsOptions {
25
+ consume_sockets: ConsumeSocket[];
26
+ remIP: string[];
27
+ apiUserName: string;
28
+ apiKey?: string;
29
+ apiToken: string;
30
+ newProducerMethod?: NewPipeProducerType;
31
+ closedProducerMethod?: ProducerClosedType;
32
+ joinConsumeRoomMethod?: JoinConsumeRoomType;
33
+ parameters: ConnectIpsParameters;
34
+ }
35
+
36
+ // Export the type definition for the function
37
+ export type ConnectIpsType = (options: ConnectIpsOptions) => Promise<[Record<string, any>[], string[]]>;
38
+
39
+ /**
40
+ * Connects to remote IPs and manages socket connections.
41
+ *
42
+ * @param {ConnectIpsOptions} options - The options for connecting IPs.
43
+ * @param {Record<string, any>[]} options.consume_sockets - The array of current socket connections.
44
+ * @param {string[]} options.remIP - The list of remote IPs to connect to.
45
+ * @param {string} options.apiUserName - The API username for authentication.
46
+ * @param {string} [options.apiKey] - The API key for authentication.
47
+ * @param {string} [options.apiToken] - The API token for authentication.
48
+ * @param {Function} [options.newProducerMethod=newPipeProducer] - The method to handle new pipe producer events.
49
+ * @param {Function} [options.closedProducerMethod=producerClosed] - The method to handle producer closed events.
50
+ * @param {Function} [options.joinConsumeRoomMethod=joinConsumeRoom] - The method to handle joining a consuming room.
51
+ * @param {ConnectIpsParameters} options.parameters - Additional parameters.
52
+ * @param {string[]} options.parameters.roomRecvIPs - The list of IPs that have been received in the room.
53
+ * @param {Function} options.parameters.updateRoomRecvIPs - The function to update the room received IPs.
54
+ * @param {Function} options.parameters.updateConsume_sockets - The function to update the consume sockets.
55
+ *
56
+ * @returns {Promise<[Record<string, any>[], string[]]>} A promise that resolves to an array containing the updated consume sockets and room received IPs.
57
+ *
58
+ * @throws Will throw an error if required parameters are missing or if there is an issue connecting to a remote IP.
59
+ *
60
+ * @example
61
+ * const options = {
62
+ * consume_sockets: [],
63
+ * remIP: ['ip1', 'ip2'],
64
+ * apiUserName: 'username',
65
+ * apiKey: 'apikey',
66
+ * apiToken: 'token',
67
+ * parameters: {
68
+ * roomRecvIPs: [],
69
+ * updateRoomRecvIPs: updateRoomRecvIPsFunction,
70
+ * updateConsume_sockets: updateConsumeSocketsFunction,
71
+ * },
72
+ * };
73
+ *
74
+ * connectIps(options)
75
+ * .then(([consume_sockets, roomRecvIPs]) => {
76
+ * console.log('Connected IPs:', consume_sockets);
77
+ * console.log('Room received IPs:', roomRecvIPs);
78
+ * });
79
+ */
80
+
81
+ export const connectIps = async ({
82
+ consume_sockets,
83
+ remIP,
84
+ apiUserName,
85
+ apiKey,
86
+ apiToken,
87
+
88
+ // mediasfu methods
89
+ newProducerMethod = newPipeProducer,
90
+ closedProducerMethod = producerClosed,
91
+ joinConsumeRoomMethod = joinConsumeRoom,
92
+ parameters,
93
+ }: ConnectIpsOptions): Promise<[Record<string, any>[], string[]]> => {
94
+ try {
95
+ const { roomRecvIPs, updateRoomRecvIPs, updateConsume_sockets } = parameters;
96
+
97
+ if (!consume_sockets || !remIP || !apiUserName || (!apiKey && !apiToken)) {
98
+ console.log("Missing required parameters", {
99
+ consume_sockets,
100
+ remIP,
101
+ apiUserName,
102
+ apiToken,
103
+ });
104
+ return [consume_sockets, roomRecvIPs];
105
+ }
106
+
107
+ for (const ip of remIP) {
108
+ try {
109
+ // Check if the IP is already connected
110
+ const matching = consume_sockets.find((socketObj) => Object.keys(socketObj)[0] === ip);
111
+
112
+ if (matching || !ip) {
113
+ // Skip if the IP is already connected or invalid
114
+ continue;
115
+ }
116
+
117
+ // Connect to the remote socket using socket.io-client
118
+ const remote_sock = await connectSocket({ apiUserName, apiKey, apiToken, link: `https://${ip}.mediasfu.com` });
119
+
120
+ if (remote_sock.id) {
121
+ // Check if the IP is in the roomRecvIPs, if not, add it
122
+ if (!roomRecvIPs.includes(ip)) {
123
+ roomRecvIPs.push(ip);
124
+ updateRoomRecvIPs(roomRecvIPs);
125
+ }
126
+
127
+ // Handle new pipe producer event
128
+ remote_sock.on("new-pipe-producer", async ({ producerId, islevel }: { producerId: string; islevel: string }) => {
129
+ if (newProducerMethod) {
130
+ await newProducerMethod({
131
+ producerId,
132
+ islevel,
133
+ nsock: remote_sock,
134
+ parameters,
135
+ });
136
+ }
137
+ });
138
+
139
+ // Handle producer closed event
140
+ remote_sock.on("producer-closed", async ({ remoteProducerId }: { remoteProducerId: string }) => {
141
+ if (closedProducerMethod) {
142
+ await closedProducerMethod({ remoteProducerId, parameters });
143
+ }
144
+ });
145
+
146
+ // Handle new consuming room by joining the room
147
+ if (joinConsumeRoomMethod) {
148
+ let data = await joinConsumeRoomMethod({
149
+ remote_sock,
150
+ apiToken,
151
+ apiUserName,
152
+ parameters,
153
+ });
154
+ if (!data.rtpCapabilities) {
155
+ return [consume_sockets, roomRecvIPs];
156
+ }
157
+ }
158
+
159
+ // Add the remote socket to the consume_sockets array
160
+ consume_sockets.push({ [ip]: remote_sock });
161
+ updateConsume_sockets(consume_sockets);
162
+ }
163
+ } catch (error) {
164
+ // Handle the error
165
+ console.log("connectIps error", error);
166
+ }
167
+ }
168
+
169
+ return [consume_sockets, roomRecvIPs];
170
+ } catch (error) {
171
+ // Handle the error
172
+ console.log("connectIps error", error);
173
+ return [consume_sockets, parameters.roomRecvIPs];
174
+ }
175
+ };
@@ -0,0 +1,103 @@
1
+
2
+ import { newPipeProducer } from "./socketReceiveMethods/newPipeProducer";
3
+ import { producerClosed } from "./socketReceiveMethods/producerClosed";
4
+ import {
5
+ ReorderStreamsParameters, ReorderStreamsType, NewPipeProducerParameters, NewPipeProducerType, ProducerClosedType,
6
+ ProducerClosedParameters,
7
+ ReceiveAllPipedTransportsParameters,
8
+ ReceiveAllPipedTransportsType} from '../types/types';
9
+ import { Socket } from "socket.io-client";
10
+
11
+ export interface ConnectLocalIpsParameters extends ReorderStreamsParameters, ProducerClosedParameters, NewPipeProducerParameters,
12
+ ReceiveAllPipedTransportsParameters {
13
+ socket: Socket;
14
+
15
+ // mediasfu functions
16
+ reorderStreams: ReorderStreamsType;
17
+ receiveAllPipedTransports: ReceiveAllPipedTransportsType;
18
+ getUpdatedAllParams: () => ConnectLocalIpsParameters;
19
+ [key: string]: any;
20
+ }
21
+
22
+ export interface ConnectLocalIpsOptions {
23
+ socket: Socket;
24
+ newProducerMethod?: NewPipeProducerType;
25
+ closedProducerMethod?: ProducerClosedType;
26
+ parameters: ConnectLocalIpsParameters;
27
+ }
28
+
29
+ // Export the type definition for the function
30
+ export type ConnectLocalIpsType = (options: ConnectLocalIpsOptions) => Promise<void>;
31
+
32
+ /**
33
+ * Connects to remote IPs and manages socket connections.
34
+ *
35
+ * @param {ConnectLocalIpsOptions} options - The options for connecting IPs.
36
+ * @param {Socket} options.socket - The socket to connect to.
37
+ * @param {Function} [options.newProducerMethod=newPipeProducer] - The method to handle new pipe producer events.
38
+ * @param {Function} [options.closedProducerMethod=producerClosed] - The method to handle producer closed events.
39
+ * @param {ConnectLocalIpsParameters} options.parameters - Additional parameters.
40
+ * @param {Function} options.parameters.reorderStreams - The function to reorder streams.
41
+ * @param {Function} options.parameters.getUpdatedAllParams - The function to get updated parameters.
42
+ * @param {Socket} options.parameters.socket - The socket to connect to.
43
+ *
44
+ * @returns {Promise<void>} A promise that resolves when the connection is established.
45
+ *
46
+ * @throws Will throw an error if required parameters are missing or if there is an issue connecting to a remote IP.
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * const options = {
51
+ * socket,
52
+ * newProducerMethod: newPipeProducer,
53
+ * closedProducerMethod: producerClosed,
54
+ * parameters: connectLocalIpsParameters,
55
+ * };
56
+ *
57
+ * connectLocalIps(options)
58
+ * .then(() => {
59
+ * console.log('Connected to local IPs');
60
+ * })
61
+ * .catch(error => {
62
+ * console.error('Error connecting to local IPs:', error);
63
+ * });
64
+ * ```
65
+ */
66
+
67
+ export const connectLocalIps = async ({
68
+ socket,
69
+
70
+ // mediasfu methods
71
+ newProducerMethod = newPipeProducer,
72
+ closedProducerMethod = producerClosed,
73
+ parameters,
74
+ }: ConnectLocalIpsOptions): Promise<void> => {
75
+ try {
76
+
77
+ // Connect to the remote socket using socket.io-client
78
+ // Handle new pipe producer event
79
+ socket.on("new-producer", async ({ producerId, islevel }: { producerId: string; islevel: string }) => {
80
+ if (newProducerMethod) {
81
+ await newProducerMethod({
82
+ producerId,
83
+ islevel,
84
+ nsock: socket,
85
+ parameters,
86
+ });
87
+ }
88
+ });
89
+
90
+ // Handle producer closed event
91
+ socket.on("producer-closed", async ({ remoteProducerId }: { remoteProducerId: string }) => {
92
+ if (closedProducerMethod) {
93
+ await closedProducerMethod({ remoteProducerId, parameters });
94
+ }
95
+ });
96
+
97
+ await parameters.receiveAllPipedTransports({ nsock: socket, community: true, parameters });
98
+
99
+ } catch (error) {
100
+ // Handle the error
101
+ console.log("ConnectLocalIps error", error);
102
+ }
103
+ };
@@ -0,0 +1,158 @@
1
+ import { Socket } from "socket.io-client";
2
+ import { ConsumerResumeType, ConsumerResumeParameters, Transport as TransportType } from "../types/types";
3
+ import type { Consumer, Device, Transport } from "mediasoup-client/lib/types";
4
+ interface Params {
5
+ id: string;
6
+ producerId: string;
7
+ kind: string;
8
+ rtpParameters: any;
9
+ serverConsumerId: string;
10
+ error?: string;
11
+ }
12
+
13
+ export interface ConnectRecvTransportParameters extends ConsumerResumeParameters {
14
+ device: Device | null;
15
+ consumerTransports: TransportType[];
16
+ updateConsumerTransports: (transports: TransportType[]) => void;
17
+
18
+ // mediasfu functions
19
+ consumerResume: ConsumerResumeType;
20
+ getUpdatedAllParams: () => ConnectRecvTransportParameters;
21
+ [key: string]: any; // Extendable for additional parameters
22
+ }
23
+ export interface ConnectRecvTransportOptions {
24
+ consumerTransport: Transport;
25
+ remoteProducerId: string;
26
+ serverConsumerTransportId: string;
27
+ nsock: Socket;
28
+ parameters: ConnectRecvTransportParameters;
29
+ }
30
+
31
+ // Export the type definition for the function
32
+ export type ConnectRecvTransportType = (options: ConnectRecvTransportOptions) => Promise<void>;
33
+
34
+ /**
35
+ * Connects the receiving transport to consume media from a remote producer.
36
+ *
37
+ * @param {ConnectRecvTransportOptions} options - The options for connecting the receiving transport.
38
+ * @param {Transport} options.consumerTransport - The transport used for consuming media.
39
+ * @param {string} options.remoteProducerId - The ID of the remote producer.
40
+ * @param {string} options.serverConsumerTransportId - The ID of the server consumer transport.
41
+ * @param {Socket} options.nsock - The socket used for communication.
42
+ * @param {ConnectRecvTransportParameters} options.parameters - The parameters for the connection.
43
+ *
44
+ * @returns {Promise<void>} A promise that resolves when the connection is established.
45
+ *
46
+ * @throws Will throw an error if the connection or consumption fails.
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * const options = {
51
+ * consumerTransport,
52
+ * remoteProducerId: 'producer-id',
53
+ * serverConsumerTransportId: 'transport-id',
54
+ * nsock: socket,
55
+ * parameters: connectRecvTransportOptions,
56
+ * };
57
+ *
58
+ * connectRecvTransport(options)
59
+ * .then(() => {
60
+ * console.log('Transport connected and consuming media');
61
+ * })
62
+ * .catch((error) => {
63
+ * console.error('Error connecting transport:', error);
64
+ * });
65
+ * ```
66
+ */
67
+
68
+ export const connectRecvTransport = async ({
69
+ consumerTransport,
70
+ remoteProducerId,
71
+ serverConsumerTransportId,
72
+ nsock,
73
+ parameters,
74
+ }: ConnectRecvTransportOptions): Promise<void> => {
75
+ parameters = parameters.getUpdatedAllParams();
76
+
77
+ const {
78
+ device,
79
+ consumerTransports,
80
+ updateConsumerTransports,
81
+ consumerResume,
82
+ } = parameters;
83
+
84
+ try {
85
+ // Emit 'consume' event to signal consumption initiation
86
+ nsock.emit(
87
+ "consume",
88
+ {
89
+ rtpCapabilities: device!.rtpCapabilities,
90
+ remoteProducerId,
91
+ serverConsumerTransportId,
92
+ },
93
+ async ({ params }: { params: Params }) => {
94
+ if (params.error) {
95
+ // Handle error
96
+ console.log("consume error", params.error);
97
+ return;
98
+ }
99
+
100
+ try {
101
+ // Consume media using received parameters
102
+ const consumer: Consumer = await consumerTransport.consume({
103
+ id: params.id,
104
+ producerId: params.producerId,
105
+ kind: params.kind as "audio" | "video",
106
+ rtpParameters: params.rtpParameters,
107
+ });
108
+
109
+ // Update consumerTransports array with the new consumer
110
+ consumerTransports.push({
111
+ consumerTransport,
112
+ serverConsumerTransportId: params.id,
113
+ producerId: remoteProducerId,
114
+ consumer,
115
+ socket_: nsock,
116
+ });
117
+
118
+ updateConsumerTransports(consumerTransports);
119
+
120
+ // Extract track from the consumer
121
+ const { track } = consumer;
122
+
123
+ // Emit 'consumer-resume' event to signal consumer resumption
124
+ nsock.emit(
125
+ "consumer-resume",
126
+ { serverConsumerId: params.serverConsumerId },
127
+ async ({ resumed }: { resumed: boolean }) => {
128
+ if (resumed) {
129
+ // Consumer resumed and ready to be used
130
+ try {
131
+ await consumerResume({
132
+ track,
133
+ kind: params.kind,
134
+ remoteProducerId,
135
+ params,
136
+ parameters,
137
+ nsock,
138
+ consumer,
139
+ });
140
+ } catch (error) {
141
+ // Handle error
142
+ console.log("consumerResume error", error);
143
+ }
144
+ }
145
+ }
146
+ );
147
+ } catch (error) {
148
+ // Handle error
149
+ console.log("consume error", error);
150
+ return;
151
+ }
152
+ }
153
+ );
154
+ } catch (error) {
155
+ // Handle error
156
+ console.log("connectRecvTransport error", error);
157
+ }
158
+ };