mediaconnection.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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.type,
  18. this.peer,
  19. this.id,
  20. this.provider,
  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. this.open = true;
  32. };
  33. MediaConnection.prototype.answer = function(stream) {
  34. if (this.localStream) {
  35. // Throw some error.
  36. return;
  37. }
  38. this.options._payload._stream = stream;
  39. this.localStream = stream;
  40. this._pc = Negotiator.startConnection(
  41. this.type,
  42. this.peer,
  43. this.id,
  44. this.provider,
  45. this.options._payload
  46. )
  47. };
  48. /**
  49. * Exposed functionality for users.
  50. */
  51. /** Allows user to close connection. */
  52. MediaConnection.prototype.close = function() {
  53. if (this.open) {
  54. this.open = false;
  55. this.emit('close')
  56. }
  57. };