mediaconnection.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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._id || MediaConnection._idPrefix + util.randomToken();
  15. if (this.localStream) {
  16. this._pc = Negotiator.startConnection(
  17. this.peer,
  18. this.id,
  19. this.provider,
  20. {_stream: this.localStream, originator: true }
  21. )
  22. }
  23. };
  24. util.inherits(MediaConnection, EventEmitter);
  25. MediaConnection._idPrefix = 'mc_';
  26. MediaConnection.prototype.addStream = function(remoteStream) {
  27. util.log('Receiving stream', remoteStream);
  28. this.remoteStream = remoteStream;
  29. this.emit('stream', remoteStream); // Should we call this `open`?
  30. this.open = true;
  31. };
  32. MediaConnection.prototype.answer = function(stream) {
  33. if (this.localStream) {
  34. // Throw some error.
  35. return;
  36. }
  37. this.options._payload._stream = stream;
  38. this.localStream = stream;
  39. this._pc = Negotiator.startConnection(
  40. this.peer,
  41. this.id,
  42. this.provider,
  43. this.options._payload
  44. )
  45. };
  46. /**
  47. * Exposed functionality for users.
  48. */
  49. /** Allows user to close connection. */
  50. MediaConnection.prototype.close = function() {
  51. if (this.open) {
  52. this.open = false;
  53. this.emit('close')
  54. }
  55. };