您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

strophe.jingle.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /* jshint -W117 */
  2. /* jshint -W101 */
  3. var JingleSession = require("./JingleSessionPC");
  4. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  5. var RTCBrowserType = require("../RTC/RTCBrowserType");
  6. module.exports = function(XMPP, eventEmitter) {
  7. Strophe.addConnectionPlugin('jingle', {
  8. connection: null,
  9. sessions: {},
  10. jid2session: {},
  11. ice_config: {iceServers: []},
  12. pc_constraints: {},
  13. activecall: null,
  14. media_constraints: {
  15. mandatory: {
  16. 'OfferToReceiveAudio': true,
  17. 'OfferToReceiveVideo': true
  18. }
  19. // MozDontOfferDataChannel: true when this is firefox
  20. },
  21. init: function (conn) {
  22. this.connection = conn;
  23. if (this.connection.disco) {
  24. // http://xmpp.org/extensions/xep-0167.html#support
  25. // http://xmpp.org/extensions/xep-0176.html#support
  26. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  27. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  28. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  29. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  30. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  31. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  32. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  33. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  34. RTCBrowserType.isTemasysPluginUsed()) {
  35. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  36. }
  37. // this is dealt with by SDP O/A so we don't need to announce this
  38. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  39. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  40. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  41. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  42. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  43. }
  44. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  45. },
  46. onJingle: function (iq) {
  47. var sid = $(iq).find('jingle').attr('sid');
  48. var action = $(iq).find('jingle').attr('action');
  49. var fromJid = iq.getAttribute('from');
  50. // send ack first
  51. var ack = $iq({type: 'result',
  52. to: fromJid,
  53. id: iq.getAttribute('id')
  54. });
  55. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  56. var sess = this.sessions[sid];
  57. if ('session-initiate' != action) {
  58. if (sess === null) {
  59. ack.type = 'error';
  60. ack.c('error', {type: 'cancel'})
  61. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  62. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  63. this.connection.send(ack);
  64. return true;
  65. }
  66. // local jid is not checked
  67. if (fromJid != sess.peerjid) {
  68. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  69. ack.type = 'error';
  70. ack.c('error', {type: 'cancel'})
  71. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  72. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  73. this.connection.send(ack);
  74. return true;
  75. }
  76. } else if (sess !== undefined) {
  77. // existing session with same session id
  78. // this might be out-of-order if the sess.peerjid is the same as from
  79. ack.type = 'error';
  80. ack.c('error', {type: 'cancel'})
  81. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  82. console.warn('duplicate session id', sid);
  83. this.connection.send(ack);
  84. return true;
  85. }
  86. // FIXME: check for a defined action
  87. this.connection.send(ack);
  88. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  89. switch (action) {
  90. case 'session-initiate':
  91. console.log("(TIME) received session-initiate:\t",
  92. window.performance.now());
  93. var startMuted = $(iq).find('jingle>startmuted');
  94. if (startMuted && startMuted.length > 0) {
  95. var audioMuted = startMuted.attr("audio");
  96. var videoMuted = startMuted.attr("video");
  97. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  98. audioMuted === "true", videoMuted === "true");
  99. }
  100. sess = new JingleSession(
  101. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  102. this.connection, XMPP, eventEmitter);
  103. // configure session
  104. sess.media_constraints = this.media_constraints;
  105. sess.pc_constraints = this.pc_constraints;
  106. sess.ice_config = this.ice_config;
  107. sess.initialize(fromJid, false);
  108. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  109. sess.setOffer($(iq).find('>jingle'));
  110. this.sessions[sess.sid] = sess;
  111. this.jid2session[sess.peerjid] = sess;
  112. // the callback should either
  113. // .sendAnswer and .accept
  114. // or .sendTerminate -- not necessarily synchronous
  115. // TODO: do we check activecall == null?
  116. this.connection.jingle.activecall = sess;
  117. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  118. // TODO: check affiliation and/or role
  119. console.log('emuc data for', sess.peerjid,
  120. this.connection.emuc.members[sess.peerjid]);
  121. sess.sendAnswer();
  122. sess.accept();
  123. break;
  124. case 'session-accept':
  125. sess.setAnswer($(iq).find('>jingle'));
  126. sess.accept();
  127. $(document).trigger('callaccepted.jingle', [sess.sid]);
  128. break;
  129. case 'session-terminate':
  130. if (!sess) {
  131. break;
  132. }
  133. console.log('terminating...', sess.sid);
  134. sess.terminate();
  135. this.terminate(sess.sid);
  136. if ($(iq).find('>jingle>reason').length) {
  137. $(document).trigger('callterminated.jingle', [
  138. sess.sid,
  139. sess.peerjid,
  140. $(iq).find('>jingle>reason>:first')[0].tagName,
  141. $(iq).find('>jingle>reason>text').text()
  142. ]);
  143. } else {
  144. $(document).trigger('callterminated.jingle',
  145. [sess.sid, sess.peerjid]);
  146. }
  147. break;
  148. case 'transport-info':
  149. sess.addIceCandidate($(iq).find('>jingle>content'));
  150. break;
  151. case 'session-info':
  152. var affected;
  153. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  154. $(document).trigger('ringing.jingle', [sess.sid]);
  155. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  156. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  157. $(document).trigger('mute.jingle', [sess.sid, affected]);
  158. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  159. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  160. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  161. }
  162. break;
  163. case 'addsource': // FIXME: proprietary, un-jingleish
  164. case 'source-add': // FIXME: proprietary
  165. sess.addSource($(iq).find('>jingle>content'));
  166. break;
  167. case 'removesource': // FIXME: proprietary, un-jingleish
  168. case 'source-remove': // FIXME: proprietary
  169. sess.removeSource($(iq).find('>jingle>content'));
  170. break;
  171. default:
  172. console.warn('jingle action not implemented', action);
  173. break;
  174. }
  175. return true;
  176. },
  177. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  178. var sess = new JingleSession(myjid || this.connection.jid,
  179. Math.random().toString(36).substr(2, 12), // random string
  180. this.connection, XMPP, eventEmitter);
  181. // configure session
  182. sess.media_constraints = this.media_constraints;
  183. sess.pc_constraints = this.pc_constraints;
  184. sess.ice_config = this.ice_config;
  185. sess.initialize(peerjid, true);
  186. this.sessions[sess.sid] = sess;
  187. this.jid2session[sess.peerjid] = sess;
  188. sess.sendOffer();
  189. return sess;
  190. },
  191. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  192. if (sid === null || sid === undefined) {
  193. for (sid in this.sessions) {
  194. if (this.sessions[sid].state != 'ended') {
  195. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  196. this.sessions[sid].terminate();
  197. }
  198. delete this.jid2session[this.sessions[sid].peerjid];
  199. delete this.sessions[sid];
  200. }
  201. } else if (this.sessions.hasOwnProperty(sid)) {
  202. if (this.sessions[sid].state != 'ended') {
  203. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  204. this.sessions[sid].terminate();
  205. }
  206. delete this.jid2session[this.sessions[sid].peerjid];
  207. delete this.sessions[sid];
  208. }
  209. },
  210. // Used to terminate a session when an unavailable presence is received.
  211. terminateByJid: function (jid) {
  212. if (this.jid2session.hasOwnProperty(jid)) {
  213. var sess = this.jid2session[jid];
  214. if (sess) {
  215. sess.terminate();
  216. console.log('peer went away silently', jid);
  217. delete this.sessions[sess.sid];
  218. delete this.jid2session[jid];
  219. $(document).trigger('callterminated.jingle',
  220. [sess.sid, jid], 'gone');
  221. }
  222. }
  223. },
  224. terminateRemoteByJid: function (jid, reason) {
  225. if (this.jid2session.hasOwnProperty(jid)) {
  226. var sess = this.jid2session[jid];
  227. if (sess) {
  228. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  229. sess.terminate();
  230. console.log('terminate peer with jid', sess.sid, jid);
  231. delete this.sessions[sess.sid];
  232. delete this.jid2session[jid];
  233. $(document).trigger('callterminated.jingle',
  234. [sess.sid, jid, 'kicked']);
  235. }
  236. }
  237. },
  238. getStunAndTurnCredentials: function () {
  239. // get stun and turn configuration from server via xep-0215
  240. // uses time-limited credentials as described in
  241. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  242. //
  243. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  244. // for a prosody module which implements this
  245. //
  246. // currently, this doesn't work with updateIce and therefore credentials with a long
  247. // validity have to be fetched before creating the peerconnection
  248. // TODO: implement refresh via updateIce as described in
  249. // https://code.google.com/p/webrtc/issues/detail?id=1650
  250. var self = this;
  251. this.connection.sendIQ(
  252. $iq({type: 'get', to: this.connection.domain})
  253. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  254. function (res) {
  255. var iceservers = [];
  256. $(res).find('>services>service').each(function (idx, el) {
  257. el = $(el);
  258. var dict = {};
  259. var type = el.attr('type');
  260. switch (type) {
  261. case 'stun':
  262. dict.url = 'stun:' + el.attr('host');
  263. if (el.attr('port')) {
  264. dict.url += ':' + el.attr('port');
  265. }
  266. iceservers.push(dict);
  267. break;
  268. case 'turn':
  269. case 'turns':
  270. dict.url = type + ':';
  271. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  272. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  273. dict.url += el.attr('username') + '@';
  274. } else {
  275. dict.username = el.attr('username'); // only works in M28
  276. }
  277. }
  278. dict.url += el.attr('host');
  279. if (el.attr('port') && el.attr('port') != '3478') {
  280. dict.url += ':' + el.attr('port');
  281. }
  282. if (el.attr('transport') && el.attr('transport') != 'udp') {
  283. dict.url += '?transport=' + el.attr('transport');
  284. }
  285. if (el.attr('password')) {
  286. dict.credential = el.attr('password');
  287. }
  288. iceservers.push(dict);
  289. break;
  290. }
  291. });
  292. self.ice_config.iceServers = iceservers;
  293. },
  294. function (err) {
  295. console.warn('getting turn credentials failed', err);
  296. console.warn('is mod_turncredentials or similar installed?');
  297. }
  298. );
  299. // implement push?
  300. },
  301. /**
  302. * Returns the data saved in 'updateLog' in a format to be logged.
  303. */
  304. getLog: function () {
  305. var data = {};
  306. var self = this;
  307. Object.keys(this.sessions).forEach(function (sid) {
  308. var session = self.sessions[sid];
  309. if (session.peerconnection && session.peerconnection.updateLog) {
  310. // FIXME: should probably be a .dump call
  311. data["jingle_" + session.sid] = {
  312. updateLog: session.peerconnection.updateLog,
  313. stats: session.peerconnection.stats,
  314. url: window.location.href
  315. };
  316. }
  317. });
  318. return data;
  319. }
  320. });
  321. };