diff --git a/peer.js b/peer.js index 8ae5a31..e4e0172 100644 --- a/peer.js +++ b/peer.js @@ -2,6 +2,7 @@ var util = require('util'); var webrtc = require('webrtcsupport'); var PeerConnection = require('rtcpeerconnection'); var WildEmitter = require('wildemitter'); +var FileTransfer = require('filetransfer'); function Peer(options) { @@ -95,6 +96,8 @@ Peer.prototype.handleMessage = function (message) { this.parent.emit('mute', {id: message.from, name: message.payload.name}); } else if (message.type === 'unmute') { this.parent.emit('unmute', {id: message.from, name: message.payload.name}); + } else if (message.type === 'fileTransfer') { + this.parent.emit('fileTransfer', this, message.payload); } }; @@ -206,4 +209,51 @@ Peer.prototype.handleDataChannelAdded = function (channel) { this._observeDataChannel(channel); }; +Peer.prototype.sendFile = function (file) { + if (!this.enableDataChannels) { + return; + } + if (!(this.pc.iceConnectionState === 'connected' || + this.pc.iceConnectionState === 'completed')) { + return; + } + var dc = this.pc.createDataChannel('filetransfer', { + reliable: true, + negotiated: true + }); + console.log('dc', dc); + console.log('file', file); + this.send('fileTransfer', { + channelId: dc.id, + metadata: { + name: file.name, + size: file.size + } + }); + var sender = new FileTransfer.Sender(); + sender.on('progress', function (sent, size) { + console.log('sent', sent, '/', size); + }); + // doesn't work with a 0 timeout... + window.setTimeout(function () { + sender.send(file, dc); + }, 1000); +}; + +Peer.prototype.acceptFileTransfer = function (channelId) { + var dc = this.pc.createDataChannel('filetransfer', { + negotiated: true, + id: channelId + }); + return dc; +}; + +Peer.prototype.rejectFileTransfer = function (channelId) { + var dc = this.getDataChannel('filetransfer', { + negotiated: true, + id: channelId + }); + dc.close(); +}; + module.exports = Peer;