選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

xmpp.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /* global $, APP, config, Strophe */
  2. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3. var EventEmitter = require("events");
  4. var Pako = require("pako");
  5. var RTCEvents = require("../../service/RTC/RTCEvents");
  6. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  8. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  9. var RTC = require("../RTC/RTC");
  10. var authenticatedUser = false;
  11. function createConnection(bosh) {
  12. bosh = bosh || '/http-bind';
  13. // Append token as URL param
  14. if (this.token) {
  15. bosh += (bosh.indexOf('?') == -1 ? '?' : '&') + 'token=' + this.token;
  16. }
  17. return new Strophe.Connection(bosh);
  18. };
  19. //!!!!!!!!!! FIXME: ...
  20. function initStrophePlugins(XMPP) {
  21. require("./strophe.emuc")(XMPP);
  22. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  23. // require("./strophe.moderate")(XMPP, eventEmitter);
  24. require("./strophe.util")();
  25. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  26. require("./strophe.rayo")();
  27. require("./strophe.logger")();
  28. }
  29. //!!!!!!!!!! FIXME: ...
  30. ///**
  31. // * If given <tt>localStream</tt> is video one this method will advertise it's
  32. // * video type in MUC presence.
  33. // * @param localStream new or modified <tt>LocalStream</tt>.
  34. // */
  35. //function broadcastLocalVideoType(localStream) {
  36. // if (localStream.videoType)
  37. // XMPP.addToPresence('videoType', localStream.videoType);
  38. //}
  39. //
  40. //function registerListeners() {
  41. // RTC.addStreamListener(
  42. // broadcastLocalVideoType,
  43. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  44. // );
  45. //}
  46. function XMPP(options) {
  47. this.eventEmitter = new EventEmitter();
  48. this.connection = null;
  49. this.disconnectInProgress = false;
  50. this.forceMuted = false;
  51. this.options = options;
  52. initStrophePlugins(this);
  53. // registerListeners();
  54. this.connection = createConnection(options.bosh);
  55. // Setup a disconnect on unload as a way to facilitate API consumers. It
  56. // sounds like they would want that. A problem for them though may be if
  57. // they wanted to utilize the connected connection in an unload handler of
  58. // their own. However, it should be fairly easy for them to do that by
  59. // registering their unload handler before us.
  60. $(window).on('beforeunload unload', this.disconnect.bind(this));
  61. }
  62. XMPP.prototype.getConnection = function () { return this.connection; };
  63. XMPP.prototype._connect = function (jid, password) {
  64. var self = this;
  65. // connection.connect() starts the connection process.
  66. //
  67. // As the connection process proceeds, the user supplied callback will
  68. // be triggered multiple times with status updates. The callback should
  69. // take two arguments - the status code and the error condition.
  70. //
  71. // The status code will be one of the values in the Strophe.Status
  72. // constants. The error condition will be one of the conditions defined
  73. // in RFC 3920 or the condition ‘strophe-parsererror’.
  74. //
  75. // The Parameters wait, hold and route are optional and only relevant
  76. // for BOSH connections. Please see XEP 124 for a more detailed
  77. // explanation of the optional parameters.
  78. //
  79. // Connection status constants for use by the connection handler
  80. // callback.
  81. //
  82. // Status.ERROR - An error has occurred (websockets specific)
  83. // Status.CONNECTING - The connection is currently being made
  84. // Status.CONNFAIL - The connection attempt failed
  85. // Status.AUTHENTICATING - The connection is authenticating
  86. // Status.AUTHFAIL - The authentication attempt failed
  87. // Status.CONNECTED - The connection has succeeded
  88. // Status.DISCONNECTED - The connection has been terminated
  89. // Status.DISCONNECTING - The connection is currently being terminated
  90. // Status.ATTACHED - The connection has been attached
  91. var anonymousConnectionFailed = false;
  92. var connectionFailed = false;
  93. var lastErrorMsg;
  94. this.connection.connect(jid, password, function (status, msg) {
  95. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  96. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  97. if (status === Strophe.Status.CONNECTED) {
  98. if (self.options.useStunTurn) {
  99. self.connection.jingle.getStunAndTurnCredentials();
  100. }
  101. logger.info("My Jabber ID: " + self.connection.jid);
  102. // Schedule ping ?
  103. var pingJid = self.connection.domain;
  104. self.connection.ping.hasPingSupport(
  105. pingJid,
  106. function (hasPing) {
  107. if (hasPing)
  108. self.connection.ping.startInterval(pingJid);
  109. else
  110. logger.warn("Ping NOT supported by " + pingJid);
  111. }
  112. );
  113. if (password)
  114. authenticatedUser = true;
  115. if (self.connection && self.connection.connected &&
  116. Strophe.getResourceFromJid(self.connection.jid)) {
  117. // .connected is true while connecting?
  118. // self.connection.send($pres());
  119. self.eventEmitter.emit(
  120. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  121. Strophe.getResourceFromJid(self.connection.jid));
  122. }
  123. } else if (status === Strophe.Status.CONNFAIL) {
  124. if (msg === 'x-strophe-bad-non-anon-jid') {
  125. anonymousConnectionFailed = true;
  126. } else {
  127. connectionFailed = true;
  128. }
  129. lastErrorMsg = msg;
  130. } else if (status === Strophe.Status.DISCONNECTED) {
  131. // Stop ping interval
  132. self.connection.ping.stopInterval();
  133. self.disconnectInProgress = false;
  134. if (anonymousConnectionFailed) {
  135. // prompt user for username and password
  136. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  137. JitsiConnectionErrors.PASSWORD_REQUIRED);
  138. } else if(connectionFailed) {
  139. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  140. JitsiConnectionErrors.OTHER_ERROR,
  141. msg ? msg : lastErrorMsg);
  142. } else {
  143. self.eventEmitter.emit(
  144. JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  145. msg ? msg : lastErrorMsg);
  146. }
  147. } else if (status === Strophe.Status.AUTHFAIL) {
  148. // wrong password or username, prompt user
  149. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  150. JitsiConnectionErrors.PASSWORD_REQUIRED);
  151. }
  152. });
  153. }
  154. XMPP.prototype.connect = function (jid, password) {
  155. if (!jid) {
  156. var configDomain
  157. = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  158. // Force authenticated domain if room is appended with '?login=true'
  159. if (this.options.hosts.anonymousdomain
  160. && window.location.search.indexOf("login=true") !== -1) {
  161. configDomain = this.options.hosts.domain;
  162. }
  163. jid = configDomain || window.location.hostname;
  164. }
  165. return this._connect(jid, password);
  166. };
  167. XMPP.prototype.createRoom = function (roomName, options, settings) {
  168. var roomjid = roomName + '@' + this.options.hosts.muc;
  169. if (options.useNicks) {
  170. if (options.nick) {
  171. roomjid += '/' + options.nick;
  172. } else {
  173. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  174. }
  175. } else {
  176. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  177. if (!authenticatedUser)
  178. tmpJid = tmpJid.substr(0, 8);
  179. roomjid += '/' + tmpJid;
  180. }
  181. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  182. }
  183. XMPP.prototype.addListener = function(type, listener) {
  184. this.eventEmitter.on(type, listener);
  185. };
  186. XMPP.prototype.removeListener = function (type, listener) {
  187. this.eventEmitter.removeListener(type, listener);
  188. };
  189. //FIXME: this should work with the room
  190. XMPP.prototype.leaveRoom = function (jid) {
  191. var handler = this.connection.jingle.jid2session[jid];
  192. if (handler && handler.peerconnection) {
  193. // FIXME: probably removing streams is not required and close() should
  194. // be enough
  195. if (RTC.localAudio) {
  196. handler.peerconnection.removeStream(
  197. RTC.localAudio.getOriginalStream(), true);
  198. }
  199. if (RTC.localVideo) {
  200. handler.peerconnection.removeStream(
  201. RTC.localVideo.getOriginalStream(), true);
  202. }
  203. handler.peerconnection.close();
  204. }
  205. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  206. this.connection.emuc.doLeave(jid);
  207. };
  208. /**
  209. * Sends 'data' as a log message to the focus. Returns true iff a message
  210. * was sent.
  211. * @param data
  212. * @returns {boolean} true iff a message was sent.
  213. */
  214. XMPP.prototype.sendLogs = function (data) {
  215. if (!this.connection.emuc.focusMucJid)
  216. return false;
  217. var deflate = true;
  218. var content = JSON.stringify(data);
  219. if (deflate) {
  220. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  221. }
  222. content = Base64.encode(content);
  223. // XEP-0337-ish
  224. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  225. message.c('log', {xmlns: 'urn:xmpp:eventlog', id: 'PeerConnectionStats'});
  226. message.c('message').t(content).up();
  227. if (deflate) {
  228. message.c('tag', {name: "deflated", value: "true"}).up();
  229. }
  230. message.up();
  231. this.connection.send(message);
  232. return true;
  233. };
  234. // Gets the logs from strophe.jingle.
  235. XMPP.prototype.getJingleLog = function () {
  236. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  237. };
  238. // Gets the logs from strophe.
  239. XMPP.prototype.getXmppLog = function () {
  240. return this.connection.logger ? this.connection.logger.log : null;
  241. };
  242. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  243. this.connection.rayo.dial(to, from, roomName,roomPass);
  244. };
  245. XMPP.prototype.setMute = function (jid, mute) {
  246. this.connection.moderate.setMute(jid, mute);
  247. };
  248. XMPP.prototype.eject = function (jid) {
  249. this.connection.moderate.eject(jid);
  250. };
  251. XMPP.prototype.getSessions = function () {
  252. return this.connection.jingle.sessions;
  253. };
  254. /**
  255. * Disconnects this from the XMPP server (if this is connected).
  256. *
  257. * @param ev optionally, the event which triggered the necessity to disconnect
  258. * from the XMPP server (e.g. beforeunload, unload)
  259. */
  260. XMPP.prototype.disconnect = function (ev) {
  261. if (this.disconnectInProgress
  262. || !this.connection
  263. || !this.connection.connected) {
  264. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  265. return;
  266. }
  267. this.disconnectInProgress = true;
  268. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  269. // means that there may not be enough time to send an unavailable presence
  270. // or disconnect at all. Switching Strophe to synchronous sending is not
  271. // much of an option because it may lead to a noticeable delay in navigating
  272. // away from the current location. As a compromise, we will try to increase
  273. // the chances of sending an unavailable presence and/or disconecting within
  274. // the short time span that we have upon unloading by invoking flush() on
  275. // the connection. We flush() once before disconnect() in order to attemtp
  276. // to have its unavailable presence at the top of the send queue. We flush()
  277. // once more after disconnect() in order to attempt to have its unavailable
  278. // presence sent as soon as possible.
  279. this.connection.flush();
  280. if (ev !== null && typeof ev !== 'undefined') {
  281. var evType = ev.type;
  282. if (evType == 'beforeunload' || evType == 'unload') {
  283. // XXX Whatever we said above, synchronous sending is the best
  284. // (known) way to properly disconnect from the XMPP server.
  285. // Consequently, it may be fine to have the source code and comment
  286. // it in or out depending on whether we want to run with it for some
  287. // time.
  288. this.connection.options.sync = true;
  289. }
  290. }
  291. this.connection.disconnect();
  292. if (this.connection.options.sync !== true) {
  293. this.connection.flush();
  294. }
  295. };
  296. module.exports = XMPP;