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

strophe.jingle.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. var startMuted = $(iq).find('jingle>startmuted');
  92. if (startMuted && startMuted.length > 0) {
  93. var audioMuted = startMuted.attr("audio");
  94. var videoMuted = startMuted.attr("video");
  95. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  96. audioMuted === "true", videoMuted === "true");
  97. }
  98. sess = new JingleSession(
  99. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  100. this.connection, XMPP, eventEmitter);
  101. // configure session
  102. sess.media_constraints = this.media_constraints;
  103. sess.pc_constraints = this.pc_constraints;
  104. sess.ice_config = this.ice_config;
  105. sess.initialize(fromJid, false);
  106. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  107. sess.setOffer($(iq).find('>jingle'));
  108. this.sessions[sess.sid] = sess;
  109. this.jid2session[sess.peerjid] = sess;
  110. // the callback should either
  111. // .sendAnswer and .accept
  112. // or .sendTerminate -- not necessarily synchronous
  113. // TODO: do we check activecall == null?
  114. this.connection.jingle.activecall = sess;
  115. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  116. // TODO: check affiliation and/or role
  117. console.log('emuc data for', sess.peerjid,
  118. this.connection.emuc.members[sess.peerjid]);
  119. sess.sendAnswer();
  120. sess.accept();
  121. break;
  122. case 'session-accept':
  123. sess.setAnswer($(iq).find('>jingle'));
  124. sess.accept();
  125. $(document).trigger('callaccepted.jingle', [sess.sid]);
  126. break;
  127. case 'session-terminate':
  128. if (!sess) {
  129. break;
  130. }
  131. console.log('terminating...', sess.sid);
  132. sess.terminate();
  133. this.terminate(sess.sid);
  134. if ($(iq).find('>jingle>reason').length) {
  135. $(document).trigger('callterminated.jingle', [
  136. sess.sid,
  137. sess.peerjid,
  138. $(iq).find('>jingle>reason>:first')[0].tagName,
  139. $(iq).find('>jingle>reason>text').text()
  140. ]);
  141. } else {
  142. $(document).trigger('callterminated.jingle',
  143. [sess.sid, sess.peerjid]);
  144. }
  145. break;
  146. case 'transport-info':
  147. sess.addIceCandidate($(iq).find('>jingle>content'));
  148. break;
  149. case 'session-info':
  150. var affected;
  151. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  152. $(document).trigger('ringing.jingle', [sess.sid]);
  153. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  154. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  155. $(document).trigger('mute.jingle', [sess.sid, affected]);
  156. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  157. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  158. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  159. }
  160. break;
  161. case 'addsource': // FIXME: proprietary, un-jingleish
  162. case 'source-add': // FIXME: proprietary
  163. sess.addSource($(iq).find('>jingle>content'), fromJid);
  164. break;
  165. case 'removesource': // FIXME: proprietary, un-jingleish
  166. case 'source-remove': // FIXME: proprietary
  167. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  168. break;
  169. default:
  170. console.warn('jingle action not implemented', action);
  171. break;
  172. }
  173. return true;
  174. },
  175. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  176. var sess = new JingleSession(myjid || this.connection.jid,
  177. Math.random().toString(36).substr(2, 12), // random string
  178. this.connection, XMPP, eventEmitter);
  179. // configure session
  180. sess.media_constraints = this.media_constraints;
  181. sess.pc_constraints = this.pc_constraints;
  182. sess.ice_config = this.ice_config;
  183. sess.initialize(peerjid, true);
  184. this.sessions[sess.sid] = sess;
  185. this.jid2session[sess.peerjid] = sess;
  186. sess.sendOffer();
  187. return sess;
  188. },
  189. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  190. if (sid === null || sid === undefined) {
  191. for (sid in this.sessions) {
  192. if (this.sessions[sid].state != 'ended') {
  193. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  194. this.sessions[sid].terminate();
  195. }
  196. delete this.jid2session[this.sessions[sid].peerjid];
  197. delete this.sessions[sid];
  198. }
  199. } else if (this.sessions.hasOwnProperty(sid)) {
  200. if (this.sessions[sid].state != 'ended') {
  201. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  202. this.sessions[sid].terminate();
  203. }
  204. delete this.jid2session[this.sessions[sid].peerjid];
  205. delete this.sessions[sid];
  206. }
  207. },
  208. // Used to terminate a session when an unavailable presence is received.
  209. terminateByJid: function (jid) {
  210. if (this.jid2session.hasOwnProperty(jid)) {
  211. var sess = this.jid2session[jid];
  212. if (sess) {
  213. sess.terminate();
  214. console.log('peer went away silently', jid);
  215. delete this.sessions[sess.sid];
  216. delete this.jid2session[jid];
  217. $(document).trigger('callterminated.jingle',
  218. [sess.sid, jid], 'gone');
  219. }
  220. }
  221. },
  222. terminateRemoteByJid: function (jid, reason) {
  223. if (this.jid2session.hasOwnProperty(jid)) {
  224. var sess = this.jid2session[jid];
  225. if (sess) {
  226. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  227. sess.terminate();
  228. console.log('terminate peer with jid', sess.sid, jid);
  229. delete this.sessions[sess.sid];
  230. delete this.jid2session[jid];
  231. $(document).trigger('callterminated.jingle',
  232. [sess.sid, jid, 'kicked']);
  233. }
  234. }
  235. },
  236. getStunAndTurnCredentials: function () {
  237. // get stun and turn configuration from server via xep-0215
  238. // uses time-limited credentials as described in
  239. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  240. //
  241. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  242. // for a prosody module which implements this
  243. //
  244. // currently, this doesn't work with updateIce and therefore credentials with a long
  245. // validity have to be fetched before creating the peerconnection
  246. // TODO: implement refresh via updateIce as described in
  247. // https://code.google.com/p/webrtc/issues/detail?id=1650
  248. var self = this;
  249. this.connection.sendIQ(
  250. $iq({type: 'get', to: this.connection.domain})
  251. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  252. function (res) {
  253. var iceservers = [];
  254. $(res).find('>services>service').each(function (idx, el) {
  255. el = $(el);
  256. var dict = {};
  257. var type = el.attr('type');
  258. switch (type) {
  259. case 'stun':
  260. dict.url = 'stun:' + el.attr('host');
  261. if (el.attr('port')) {
  262. dict.url += ':' + el.attr('port');
  263. }
  264. iceservers.push(dict);
  265. break;
  266. case 'turn':
  267. case 'turns':
  268. dict.url = type + ':';
  269. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  270. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  271. dict.url += el.attr('username') + '@';
  272. } else {
  273. dict.username = el.attr('username'); // only works in M28
  274. }
  275. }
  276. dict.url += el.attr('host');
  277. if (el.attr('port') && el.attr('port') != '3478') {
  278. dict.url += ':' + el.attr('port');
  279. }
  280. if (el.attr('transport') && el.attr('transport') != 'udp') {
  281. dict.url += '?transport=' + el.attr('transport');
  282. }
  283. if (el.attr('password')) {
  284. dict.credential = el.attr('password');
  285. }
  286. iceservers.push(dict);
  287. break;
  288. }
  289. });
  290. self.ice_config.iceServers = iceservers;
  291. },
  292. function (err) {
  293. console.warn('getting turn credentials failed', err);
  294. console.warn('is mod_turncredentials or similar installed?');
  295. }
  296. );
  297. // implement push?
  298. },
  299. /**
  300. * Returns the data saved in 'updateLog' in a format to be logged.
  301. */
  302. getLog: function () {
  303. var data = {};
  304. var self = this;
  305. Object.keys(this.sessions).forEach(function (sid) {
  306. var session = self.sessions[sid];
  307. if (session.peerconnection && session.peerconnection.updateLog) {
  308. // FIXME: should probably be a .dump call
  309. data["jingle_" + session.sid] = {
  310. updateLog: session.peerconnection.updateLog,
  311. stats: session.peerconnection.stats,
  312. url: window.location.href
  313. };
  314. }
  315. });
  316. return data;
  317. }
  318. });
  319. };