mediaconnection.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /**
  2. * Wraps the streaming interface between two Peers.
  3. */
  4. function MediaConnection(peer, provider, options) {
  5. if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options);
  6. EventEmitter.call(this);
  7. this.options = util.extend({}, options);
  8. this.open = false;
  9. this.type = 'media';
  10. this.peer = peer;
  11. this.provider = provider;
  12. this.metadata = this.options.metadata;
  13. this.localStream = this.options._stream;
  14. this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
  15. if (this.localStream) {
  16. Negotiator.startConnection(
  17. this,
  18. {_stream: this.localStream, originator: true}
  19. );
  20. }
  21. };
  22. util.inherits(MediaConnection, EventEmitter);
  23. MediaConnection._idPrefix = 'mc_';
  24. MediaConnection.prototype.addStream = function(remoteStream) {
  25. util.log('Receiving stream', remoteStream);
  26. this.remoteStream = remoteStream;
  27. this.emit('stream', remoteStream); // Should we call this `open`?
  28. };
  29. MediaConnection.prototype.handleMessage = function(message) {
  30. var payload = message.payload;
  31. switch (message.type) {
  32. case 'ANSWER':
  33. // Forward to negotiator
  34. Negotiator.handleSDP(message.type, this, payload.sdp);
  35. this.open = true;
  36. break;
  37. case 'CANDIDATE':
  38. Negotiator.handleCandidate(this, payload.candidate);
  39. break;
  40. default:
  41. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  42. break;
  43. }
  44. }
  45. MediaConnection.prototype.answer = function(stream) {
  46. if (this.localStream) {
  47. util.warn('Local stream already exists on this MediaConnection. Are you answering a call twice?');
  48. return;
  49. }
  50. this.options._payload._stream = stream;
  51. this.localStream = stream;
  52. Negotiator.startConnection(
  53. this,
  54. this.options._payload
  55. )
  56. // Retrieve lost messages stored because PeerConnection not set up.
  57. var messages = this.provider._getMessages(this.id);
  58. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  59. this.handleMessage(messages[i]);
  60. }
  61. this.open = true;
  62. };
  63. /**
  64. * Exposed functionality for users.
  65. */
  66. /** Allows user to close connection. */
  67. MediaConnection.prototype.close = function() {
  68. if (!this.open) {
  69. return;
  70. }
  71. this.open = false;
  72. Negotiator.cleanup(this);
  73. this.emit('close')
  74. };