# API Reference
> RTCMultiConnection API References
You can search docs/APIs here:
* http://www.rtcmulticonnection.org/
* http://www.rtcmulticonnection.org/docs/
### `socketURL`
1. You can run nodejs on a separate domain or separate port or on a separate server
2. You can set `socketURL="ip-address"` to link nodejs server
3. Now you can run RTCMultiConnection demos on any webpage; whether it is PHP page, ASP.net page, python or ruby page or whatever framework running top over HTML.
```javascript
connection.socketURL = 'https://onlyChangingPort.com:8888/';
connection.socketURL = 'https://separateDomain.com:443/';
connection.socketURL = '/'; // same domain
// or a free signaling server:
// v3.4.7 or newer
connection.socketURL = 'https://rtcmulticonnection.herokuapp.com:443/';
// v3.4.6 or older
connection.socketURL = 'https://webrtcweb.com:9001/';
```
### `socketCustomParameters`
You can pass your custom socket.io parameters as well:
```javascript
// starts with "&"
// &fullName=Muaz
// &meetingId=xyz
connection.socketCustomParameters = '&fullName=Muaz&country=PK&meetingId=xyz';
```
Now you can open `server.js` and access above parameters here:
```javascript
// you can find below line on "server.js" file
require('./Signaling-Server.js')(app, function(socket) {
var params = socket.handshake.query;
var meetingId = params.meetingId;
var fullName = params.fullName;
var country = params.country;
var userid = params.userid;
// etc.
});
```
### Update Extra-Data before Socket connects
This feature allows you reliably update-extra data on nodejs before socket.io connection opens.
```javascript
connection.extra = {
fullName: 'Muaz Khan',
joinedAt: (new Date).toISOString()
};s
connection.socketCustomParameters = '&extra=' + JSON.stringify(connection.extra);
connection.openOrJoin('room-id');
```
### `applyConstraints`
This method allows you change video resolutions or audio sources without making a new getUserMedia request i.e. it modifies your existing MediaStream:
```javascript
var width = 1280;
var height = 720;
var supports = navigator.mediaDevices.getSupportedConstraints();
var constraints = {};
if (supports.width && supports.height) {
constraints = {
width: width,
height: height
};
}
connection.applyConstraints({
video: constraints
});
```
`applyConstraints` access `mediaConstraints` object, defined here:
* [http://www.rtcmulticonnection.org/docs/mediaConstraints/](http://www.rtcmulticonnection.org/docs/mediaConstraints/)
### `replaceTrack`
This method allows you replace your front-camera video with back-camera video or replace video with screen or replace older low-quality video with new high quality video.
```javascript
// here is its simpler usage
connection.replaceTrack({
screen: true,
oneway: true
});
```
You can even pass `MediaStreamTrack` object:
```javascript
var videoTrack = yourVideoStream.getVideoTracks()[0];
connection.replaceTrack(videoTrack);
```
You can even pass `MediaStream` object:
```javascript
connection.replaceTrack(yourVideoStream);
```
You can even force to replace tracks only with a single user:
```javascript
var remoteUserId = 'single-remote-userid';
var videoTrack = yourVideoStream.getVideoTracks()[0];
connection.replaceTrack(videoTrack, remoteUserId);
```
### `resetTrack`
If you replaced a video or audio track, RTCMultiConnection keeps record of old track, and allows you move-back-to previous track:
```javascript
connection.resetTrack(null, true);
```
It takes following arguments:
1. `[Array of user-ids]` or `"single-user-id"` or `null`
2. Is video track (boolean): Either `true` or `false`. `null` means replace all last tracks.
```javascript
// with single user
connection.resetTrack('specific-userid', true);
// with multiple users
connection.resetTrack(['first-user', 'second-user'], true);
// NULL means all users
connection.resetTrack(null, true);
// reset only audio
connection.resetTrack(null, false);
// to reset all last-tracks (both audio and video)
connection.resetTrack();
```
> Means that you can reset all tracks that are replaced recently.
### `onUserStatusChanged`
This event allows you show online/offline statuses of the user:
```javascript
connection.onUserStatusChanged = function(status) {
document.getElementById(event.userid).src = status === 'online' ? 'online.gif' : 'offline.gif';
};
```
You can even manually call above method from `onopen`, `onstream` and similar events to get the most accurate result possible:
```javascript
connection.onopen = connection.stream = function(event) {
connection.onUserStatusChanged({
userid: event.userid,
extra: event.extra,
status: 'online'
});
};
connection.onleave = connection.streamended = connection.onclose = function(event) {
connection.onUserStatusChanged({
userid: event.userid,
extra: event.extra,
status: 'offline'
});
};
```
### `onRoomFull`
```javascript
connection.maxParticipantsAllowed = 1; // one-to-one
connection.onRoomFull = function(roomid) {
alert('Room is full.');
};
```
### `getSocket`
This method allows you get the `socket` object used for signaling (handshake/presence-detection/etc.):
```javascript
var socket = connection.getSocket();
socket.emit('custom-event', 'hi there');
socket.on('custom-event', function(message) {
alert(message);
});
```
If socket isn't connected yet, then above method will auto-connect it. It is using `connectSocket` to connect socket. See below section.
### `connectSocket`
It is same like old RTCMultiConnection `connect` method:
* [http://www.rtcmulticonnection.org/docs/connect/](http://www.rtcmulticonnection.org/docs/connect/)
`connectSocket` method simply initializes socket.io server so that you can send custom-messages before creating/joining rooms:
```javascript
connection.connectSocket(function(socket) {
socket.on('custom-message', function(message) {
alert(message);
// custom message
if(message.joinMyRoom) {
connection.join(message.roomid);
}
});
socket.emit('custom-message', 'hi there');
connection.open('room-id');
});
```
### `socketCustomEvent`
A `string` property, allows you set custom socket.io event listener:
```javascript
connection.socketCustomEvent = 'abcdef';
connection.openOrJoin('roomid', function() {
connection.socket.on(connection.socketCustomEvent, function(message) {
alert(message);
});
connection.socket.emit(connection.socketCustomEvent, 'My userid is: ' + connection.userid);
});
```
### `setCustomSocketEvent`
This method allows you set custom socket listeners anytime, during a live session:
```javascript
connection.setCustomSocketEvent('abcdef');
connection.socket.on('abcdef', function(message) {
alert(message);
});
connection.socket.emit('abcdef', 'My userid is: ' + connection.userid);
```
### `getUserMediaHandler`
This object allows you capture audio/video stream yourself. RTCMultiConnection will NEVER know about your stream until you add it yourself, manually:
```javascript
var options = {
localMediaConstraints: {
audio: true,
video: true
},
onGettingLocalMedia: function(stream) {},
onLocalMediaError: function(error) {}
};
connection.getUserMediaHandler(options);
```
Its defined here:
* [getUserMedia.js#L20](https://github.com/muaz-khan/RTCMultiConnection/tree/master/dev/getUserMedia.js#L20)
## `setUserPreferences`
You can force `dontAttachStream` and `dontGetRemoteStream` for any or each user in any situation:
```javascript
connection.setUserPreferences = function(userPreferences) {
if (connection.dontAttachStream) {
// current user's streams will NEVER be shared with any other user
userPreferences.dontAttachLocalStream = true;
}
if (connection.dontGetRemoteStream) {
// current user will NEVER receive any stream from any other user
userPreferences.dontGetRemoteStream = true;
}
return userPreferences;
};
```
Scenarios:
1. All users in the room are having cameras
2. All users in the room can see only **self video**
3. All users in the room can text-chat or share files; but can't share videos
4. As soon as teacher or moderator or presenter enters in the room; he can ask all the participants or specific participants to share their cameras with single or multiple users.
They can enable cameras as following:
```javascritp
connection.onmessage = function(event) {
var message = event.data;
if(message.shareYourCameraWithMe) {
connection.dontAttachStream = false;
connection.renegotiate(event.userid); // share only with single user
}
if(message.shareYourCameraWithAllUsers) {
connection.dontAttachStream = false;
connection.renegotiate(); // share with all users
}
}
```
i.e. `setUserPreferences` allows you enable camera on demand.
## `checkPresence`
This method allows you check presence of the moderators/rooms:
```javascript
connection.checkPresence('roomid', function(isRoomEists, roomid) {
if(isRoomEists) {
connection.join(roomid);
}
else {
connection.open(roomid);
}
});
```
## `onReadyForOffer`
This event is fired as soon as callee says "I am ready for offer. I enabled camera. Please create offer and share.".
```javascript
connection.onReadyForOffer = function(remoteUserId, userPreferences) {
// if OfferToReceiveAudio/OfferToReceiveVideo should be enabled for specific users
userPreferences.localPeerSdpConstraints.OfferToReceiveAudio = true;
userPreferences.localPeerSdpConstraints.OfferToReceiveVideo = true;
userPreferences.dontAttachStream = false; // according to situation
userPreferences.dontGetRemoteStream = false; // according to situation
// below line must be included. Above all lines are optional.
connection.multiPeersHandler.createNewPeer(remoteUserId, userPreferences);
};
```
## `onNewParticipant`
This event is fired as soon as someone tries to join you. You can either reject his request or set preferences.
```javascript
connection.onNewParticipant = function(participantId, userPreferences) {
// if OfferToReceiveAudio/OfferToReceiveVideo should be enabled for specific users
userPreferences.localPeerSdpConstraints.OfferToReceiveAudio = true;
userPreferences.localPeerSdpConstraints.OfferToReceiveVideo = true;
userPreferences.dontAttachStream = false; // according to situation
userPreferences.dontGetRemoteStream = false; // according to situation
// below line must be included. Above all lines are optional.
// if below line is NOT included; "join-request" will be considered rejected.
connection.acceptParticipationRequest(participantId, userPreferences);
};
```
Or:
```javascript
var alreadyAllowed = {};
connection.onNewParticipant = function(participantId, userPreferences) {
if(alreadyAllowed[participantId]) {
connection.addParticipationRequest(participantId, userPreferences);
return;
}
var message = participantId + ' is trying to join your room. Confirm to accept his request.';
if( window.confirm(messsage ) ) {
connection.addParticipationRequest(participantId, userPreferences);
}
};
```
## `disconnectWith`
Disconnect with single or multiple users. This method allows you keep connected to `socket` however either leave entire room or remove single or multiple users:
```javascript
connection.disconnectWith('remoteUserId');
// to leave entire room
connection.getAllParticipants().forEach(function(participantId) {
connection.disconnectWith(participantId);
});
```
## `getAllParticipants`
Get list of all participants that are connected with current user.
```javascript
var numberOfUsersInTheRoom = connection.getAllParticipants().length;
var remoteUserId = 'xyz';
var isUserConnectedWithYou = connection.getAllParticipants().indexOf(remoteUserId) !== -1;
connection.getAllParticipants().forEach(function(remoteUserId) {
var user = connection.peers[remoteUserId];
console.log(user.extra);
user.peer.close();
alert(user.peer === webkitRTCPeerConnection);
});
```
## `maxParticipantsAllowed`
Set number of users who can join your room.
```javascript
// to allow another single person to join your room
// it will become one-to-one (i.e. you+anotherUser)
connection.maxParticipantsAllowed = 1;
```
## `setCustomSocketHandler`
This method allows you skip Socket.io and force custom signaling implementations e.g. SIP-signaling, XHR-signaling, SignalR/WebSync signaling, Firebase/PubNub signaling etc.
Here is Firebase example:
```html
```
Here is PubNub example:
```html
```
SIP/SignalR/WebSync/XHR signaling:
```javascript
// please don't forget linking /dev/globals.js
var connection = new RTCMultiConnection();
// SignalR (requires /dev/SignalRConnection.js)
connection.setCustomSocketHandler(SignalRConnection);
// WebSync (requires /dev/WebSyncConnection.js)
connection.setCustomSocketHandler(WebSyncConnection);
// XHR (requires /dev/XHRConnection.js)
connection.setCustomSocketHandler(XHRConnection);
// Sip (requires /dev/SipConnection.js)
connection.setCustomSocketHandler(SipConnection);
```
Please check [`FirebaseConnection`](https://github.com/muaz-khan/RTCMultiConnection/tree/master/dev/FirebaseConnection.js) or [`PubNubConnection.js`](https://github.com/muaz-khan/RTCMultiConnection/tree/master/dev/PubNubConnection.js) to understand how it works.
For more information:
* https://rtcmulticonnection.herokuapp.com/demos/Audio+Video+TextChat+FileSharing.html#comment-2670178473
* https://rtcmulticonnection.herokuapp.com/demos/Audio+Video+TextChat+FileSharing.html#comment-2670182313
## `enableLogs`
By default, logs are enabled.
```javascript
connection.enableLogs = false; // to disable logs
```
## Get Remote User Extra Data
```javascript
connection.extra = {
joinTime: new Date()
};
connection.updateExtraData();
```
Here is how to get extra-data:
```javascript
var extra = connection.peers['remote-userid'].extra;
alert( extra.joinTime);
```
Recent commit supports this as well:
```javascript
connection.onstream = function(event) {
if(event.type === 'remote') {
connection.socket.emit('get-remote-user-extra-data', event.userid, function(extra) {
alert( extra.joinTime );
});
}
}:
```
## `updateExtraData`
You can force all the extra-data to be synced among all connected users.
```javascript
connection.extra.fullName = 'New Full Name';
connection.updateExtraData(); // now above value will be auto synced among all connected users
```
## `onExtraDataUpdated`
This event is fired as soon as extra-data from any user is updated:
```javascript
connection.onExtraDataUpdated = function(event) {
console.log('extra data updated', event.userid, event.extra);
// make sure that