mediaconnection.js 2.4 KB

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