mediaconnection.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. this.open = true;
  29. };
  30. MediaConnection.prototype.handleMessage = function(message) {
  31. var payload = message.payload;
  32. switch (message.type) {
  33. case 'ANSWER':
  34. // TODO: assert sdp exists.
  35. // Should we pass `this`?
  36. // Forward to negotiator
  37. Negotiator.handleSDP(message.type, this, payload.sdp);
  38. break;
  39. case 'CANDIDATE':
  40. // TODO
  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. // Throw some error.
  51. return;
  52. }
  53. this.options._payload._stream = stream;
  54. this.localStream = stream;
  55. Negotiator.startConnection(
  56. this,
  57. this.options._payload
  58. )
  59. };
  60. /**
  61. * Exposed functionality for users.
  62. */
  63. /** Allows user to close connection. */
  64. MediaConnection.prototype.close = function() {
  65. // TODO: actually close PC.
  66. if (this.open) {
  67. this.open = false;
  68. this.emit('close')
  69. }
  70. };