developer_api.rst 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. .. raw:: html
  2. <div id="banner"><a href="https://github.com/jcbrand/converse.js/blob/master/docs/source/theming.rst">Edit me on GitHub</a></div>
  3. =============================
  4. The converse.js developer API
  5. =============================
  6. .. note:: The API documented here is available in Converse.js 0.8.4 and higher.
  7. Earlier versions of Converse.js might have different API methods or none at all.
  8. .. note:: From version 3.0.0 and onwards many API methods have been made
  9. private and available to plugins only. This means that if you want to
  10. use the API, you'll first need to create a plugin from which you can
  11. access it. This change is done to avoid leakage of sensitive data to
  12. malicious or non-whitelisted scripts.
  13. The Converse.js API is broken up into different logical "groupings" (for
  14. example ``converse.plugins`` or ``converse.contacts``).
  15. There are some exceptions to this, like ``converse.initialize``, which aren't
  16. groupings but single methods.
  17. The groupings logically group methods, such as standardised accessors and
  18. mutators::
  19. .get
  20. .set
  21. .add
  22. .remove
  23. So for example, to get a contact, you would do the following::
  24. _converse.api.contacts.get('jid@example.com');
  25. To get multiple contacts, just pass in an array of jids::
  26. _converse.api.contacts.get(['jid1@example.com', 'jid2@example.com']);
  27. To get all contacts, simply call ``get`` without any jids::
  28. _converse.api.contacts.get();
  29. Public API methods
  30. ==================
  31. Publich API methods are those methods that are accessible on the global
  32. ``window.converse`` object. They are public, because any JavaScript in the page
  33. can call them. Public methods therefore don't expose any sensitive or closured
  34. data. To do that, you'll need to create a plugin, which has access to the
  35. private API method.
  36. .. _`initialize`:
  37. initialize
  38. ----------
  39. .. note:: This method is the one exception of a method which is not logically grouped as explained above.
  40. Publich API method which initializes converse.js.
  41. This method must always be called when using converse.js.
  42. The `initialize` method takes a map of :ref:`configuration-settings`.
  43. Example:
  44. .. code-block:: javascript
  45. converse.initialize({
  46. allow_otr: true,
  47. auto_list_rooms: false,
  48. auto_subscribe: false,
  49. bosh_service_url: 'https://bind.example.com',
  50. hide_muc_server: false,
  51. i18n: locales['en'],
  52. keepalive: true,
  53. play_sounds: true,
  54. prebind: false,
  55. show_controlbox_by_default: true,
  56. debug: false,
  57. roster_groups: true
  58. });
  59. The **plugin** grouping
  60. ------------------------
  61. Exposes methods for adding and removing plugins. You'll need to write a plugin
  62. if you want to have access to the private API methods defined further down below.
  63. For more information on plugins, read the section :ref:`writing-a-plugin`.
  64. add
  65. ~~~
  66. Registers a new plugin.
  67. .. code-block:: javascript
  68. var plugin = {
  69. initialize: function () {
  70. // method on any plugin (if it exists) as soon as the plugin has
  71. // been loaded.
  72. // Inside this method, you have access to the closured
  73. // _converse object, which contains the core logic and data
  74. // structures of converse.js
  75. }
  76. }
  77. converse.plugins.add('myplugin', plugin);
  78. Private API methods
  79. ===================
  80. The private API methods are only accessible via the closured ``_converse``
  81. object, which is only available to plugins.
  82. These methods are kept private (i.e. not global) because they may return
  83. sensitive data which should be kept off-limits to other 3rd-party scripts
  84. that might be running in the page.
  85. .. note:: The example code snippets shown below are a bit contrived. I've added
  86. the minimum plugin boilerplace around the actual example, to show that
  87. these API methods can only be called inside a plugin where the
  88. ``_converse`` object is available. However, sometimes other considerations
  89. need to be made as well. For example, for certain API methods it is
  90. necessary to first wait until the data has been received from the XMPP
  91. server (or from the browser's sessionStorage cache). Due to
  92. time-constriaints these limitations are ignored in the examples below. For
  93. a fuller picture, refer to the section :ref:`events-API` as well.
  94. emit
  95. ----
  96. This method allows you to emit events, which can be listened to via
  97. ``_converse.api.listen.on`` or ``_converse.api.listen.once``.
  98. For example:
  99. .. code-block:: javascript
  100. _converse.emit('foo-completed');
  101. Additionally, if a promise has been registered under the same name
  102. (via ``_converse.api.promises.add``), then that promise will also be resolved
  103. when calling ``emit``.
  104. send
  105. ----
  106. Allows you to send XML stanzas.
  107. For example, to send a message stanza:
  108. .. code-block:: javascript
  109. converse.plugins.add('myplugin', {
  110. initialize: function () {
  111. var msg = converse.env.$msg({
  112. from: 'juliet@example.com/balcony',
  113. to:'romeo@example.net',
  114. type:'chat'
  115. });
  116. this._converse.api.send(msg);
  117. }
  118. });
  119. .. _`waituntil-grouping`:
  120. waitUntil
  121. ---------
  122. This method can be used to wait for promises. Promises are similar to events
  123. (for event handling, refer to the :ref:`listen-grouping`), but they differ in
  124. two important ways:
  125. * A promise gets resolved only once, whereas events can fire multiple times.
  126. * A handler registered for a promise, will still fire *after* the promise has
  127. been resolved, which is not the case with an event handler.
  128. Converse.js has the following promises:
  129. * :ref:`cachedRoster`
  130. * :ref:`chatBoxesFetched`
  131. * :ref:`pluginsInitialized`
  132. * :ref:`roster`
  133. * :ref:`rosterContactsFetched`
  134. * :ref:`rosterGroupsFetched`
  135. * :ref:`rosterInitialized`
  136. * :ref:`statusInitialized`
  137. * :ref:`roomsPanelRendered` (only via the `converse-muc` plugin)
  138. Below is an example from `converse-muc.js <https://github.com/jcbrand/converse.js/blob/master/src/converse-muc.js>`_
  139. where the `rosterContactsFetched` promise is waited on. The method
  140. `this.initInviteWidget` will initialize the chatroom invitation widget.
  141. .. code-block:: javascript
  142. _converse.api.waitUntil('rosterContactsFetched').then(this.initInviteWidget.bind(this));
  143. The line above executes only once a chatroom has been opened and entered, so
  144. using an event handler here would not work, since the event might have fired
  145. already by that time.
  146. The **archive** grouping
  147. ------------------------
  148. Converse.js supports the *Message Archive Management*
  149. (`XEP-0313 <https://xmpp.org/extensions/xep-0313.html>`_) protocol,
  150. through which it is able to query an XMPP server for archived messages.
  151. See also the **message_archiving** option in the :ref:`configuration-settings` section, which you'll usually
  152. want to in conjunction with this API.
  153. query
  154. ~~~~~
  155. The ``query`` method is used to query for archived messages.
  156. It accepts the following optional parameters:
  157. * **options** an object containing the query parameters. Valid query parameters
  158. are ``with``, ``start``, ``end``, ``first``, ``last``, ``after``, ``before``, ``index`` and ``count``.
  159. * **callback** is the callback method that will be called when all the messages
  160. have been received.
  161. * **errback** is the callback method to be called when an error is returned by
  162. the XMPP server, for example when it doesn't support message archiving.
  163. Examples
  164. ^^^^^^^^
  165. **Requesting all archived messages**
  166. The simplest query that can be made is to simply not pass in any parameters.
  167. Such a query will return all archived messages for the current user.
  168. Generally, you'll however always want to pass in a callback method, to receive
  169. the returned messages.
  170. .. code-block:: javascript
  171. converse.plugins.add('myplugin', {
  172. initialize: function () {
  173. var errback = function (iq) {
  174. // The query was not successful, perhaps inform the user?
  175. // The IQ stanza returned by the XMPP server is passed in, so that you
  176. // may inspect it and determine what the problem was.
  177. }
  178. var callback = function (messages) {
  179. // Do something with the messages, like showing them in your webpage.
  180. }
  181. this._converse.api.archive.query(callback, errback))
  182. }
  183. });
  184. **Waiting until server support has been determined**
  185. The query method will only work if converse.js has been able to determine that
  186. the server supports MAM queries, otherwise the following error will be raised:
  187. - *This server does not support XEP-0313, Message Archive Management*
  188. The very first time converse.js loads in a browser tab, if you call the query
  189. API too quickly, the above error might appear because service discovery has not
  190. yet been completed.
  191. To work solve this problem, you can first listen for the ``serviceDiscovered`` event,
  192. through which you can be informed once support for MAM has been determined.
  193. For example:
  194. .. code-block:: javascript
  195. converse.plugins.add('myplugin', {
  196. initialize: function () {
  197. var _converse = this._converse;
  198. _converse.api.listen.on('serviceDiscovered', function (feature) {
  199. if (feature.get('var') === converse.env.Strophe.NS.MAM) {
  200. _converse.api.archive.query()
  201. }
  202. });
  203. converse.listen.on('serviceDiscovered', function (feature) {
  204. if (feature.get('var') === converse.env.Strophe.NS.MAM) {
  205. converse.archive.query()
  206. }
  207. });
  208. **Requesting all archived messages for a particular contact or room**
  209. To query for messages sent between the current user and another user or room,
  210. the query options need to contain the the JID (Jabber ID) of the user or
  211. room under the ``with`` key.
  212. .. code-block:: javascript
  213. converse.plugins.add('myplugin', {
  214. initialize: function () {
  215. // For a particular user
  216. this._converse.api.archive.query({'with': 'john@doe.net'}, callback, errback);)
  217. // For a particular room
  218. this._converse.api.archive.query({'with': 'discuss@conference.doglovers.net'}, callback, errback);)
  219. }
  220. });
  221. **Requesting all archived messages before or after a certain date**
  222. The ``start`` and ``end`` parameters are used to query for messages
  223. within a certain timeframe. The passed in date values may either be ISO8601
  224. formatted date strings, or JavaScript Date objects.
  225. .. code-block:: javascript
  226. converse.plugins.add('myplugin', {
  227. initialize: function () {
  228. var options = {
  229. 'with': 'john@doe.net',
  230. 'start': '2010-06-07T00:00:00Z',
  231. 'end': '2010-07-07T13:23:54Z'
  232. };
  233. this._converse.api.archive.query(options, callback, errback);
  234. }
  235. });
  236. **Limiting the amount of messages returned**
  237. The amount of returned messages may be limited with the ``max`` parameter.
  238. By default, the messages are returned from oldest to newest.
  239. .. code-block:: javascript
  240. converse.plugins.add('myplugin', {
  241. initialize: function () {
  242. // Return maximum 10 archived messages
  243. this._converse.api.archive.query({'with': 'john@doe.net', 'max':10}, callback, errback);
  244. }
  245. });
  246. **Paging forwards through a set of archived messages**
  247. When limiting the amount of messages returned per query, you might want to
  248. repeatedly make a further query to fetch the next batch of messages.
  249. To simplify this usecase for you, the callback method receives not only an array
  250. with the returned archived messages, but also a special RSM (*Result Set
  251. Management*) object which contains the query parameters you passed in, as well
  252. as two utility methods ``next``, and ``previous``.
  253. When you call one of these utility methods on the returned RSM object, and then
  254. pass the result into a new query, you'll receive the next or previous batch of
  255. archived messages. Please note, when calling these methods, pass in an integer
  256. to limit your results.
  257. .. code-block:: javascript
  258. converse.plugins.add('myplugin', {
  259. initialize: function () {
  260. var _converse = this._converse;
  261. var callback = function (messages, rsm) {
  262. // Do something with the messages, like showing them in your webpage.
  263. // ...
  264. // You can now use the returned "rsm" object, to fetch the next batch of messages:
  265. _converse.api.archive.query(rsm.next(10), callback, errback))
  266. }
  267. _converse.api.archive.query({'with': 'john@doe.net', 'max':10}, callback, errback);
  268. }
  269. });
  270. **Paging backwards through a set of archived messages**
  271. To page backwards through the archive, you need to know the UID of the message
  272. which you'd like to page backwards from and then pass that as value for the
  273. ``before`` parameter. If you simply want to page backwards from the most recent
  274. message, pass in the ``before`` parameter with an empty string value ``''``.
  275. .. code-block:: javascript
  276. converse.plugins.add('myplugin', {
  277. initialize: function () {
  278. var _converse = this._converse;
  279. _converse.api.archive.query({'before': '', 'max':5}, function (message, rsm) {
  280. // Do something with the messages, like showing them in your webpage.
  281. // ...
  282. // You can now use the returned "rsm" object, to fetch the previous batch of messages:
  283. rsm.previous(5); // Call previous method, to update the object's parameters,
  284. // passing in a limit value of 5.
  285. // Now we query again, to get the previous batch.
  286. _converse.api.archive.query(rsm, callback, errback);
  287. }
  288. }
  289. });
  290. The **connection** grouping
  291. ---------------------------
  292. This grouping collects API functions related to the XMPP connection.
  293. connected
  294. ~~~~~~~~~
  295. A boolean attribute (i.e. not a callable) which is set to `true` or `false` depending
  296. on whether there is an established connection.
  297. disconnect
  298. ~~~~~~~~~~
  299. Terminates the connection.
  300. The **disco** grouping
  301. ----------------------
  302. This grouping collects API functions related to `service discovery
  303. <https://xmpp.org/extensions/xep-0030.html>`_.
  304. supports
  305. ~~~~~~~~
  306. Used to determine whether an entity supports a given feature.
  307. Returns a `Promise` which, when resolved, returns a map/object with keys
  308. `supported` (a boolean) and `feature` which is a `Backbone.Model <http://backbonejs.org/#Model>`_.
  309. .. code-block:: javascript
  310. converse.plugins.add('myplugin', {
  311. initialize: function () {
  312. _converse.api.disco.supports(_converse.bare_jid, Strophe.NS.MAM).then(
  313. function (value) {
  314. // `value` is a map with two keys, `supported` and `feature`.
  315. if (value.supported) {
  316. // The feature is supported
  317. } else {
  318. // The feature is not supported
  319. }
  320. },
  321. function () { // Error
  322. _converse.log(
  323. "Error or timeout while checking for feature support",
  324. Strophe.LogLevel.ERROR
  325. );
  326. }
  327. ).catch((msg) => {
  328. _converse.log(msg, Strophe.LogLevel.FATAL);
  329. });
  330. }
  331. });
  332. The **user** grouping
  333. ---------------------
  334. This grouping collects API functions related to the current logged in user.
  335. jid
  336. ~~~
  337. Return's the current user's full JID (Jabber ID).
  338. .. code-block:: javascript
  339. converse.plugins.add('myplugin', {
  340. initialize: function () {
  341. alert(this._converse.api.user.jid());
  342. }
  343. });
  344. login
  345. ~~~~~
  346. Logs the user in. This method can accept a map with the credentials, like this:
  347. .. code-block:: javascript
  348. converse.plugins.add('myplugin', {
  349. initialize: function () {
  350. this._converse.api.user.login({
  351. 'jid': 'dummy@example.com',
  352. 'password': 'secret'
  353. });
  354. }
  355. });
  356. or it can be called without any parameters, in which case converse.js will try
  357. to log the user in by calling the `prebind_url` or `credentials_url` depending
  358. on whether prebinding is used or not.
  359. logout
  360. ~~~~~~
  361. Log the user out of the current XMPP session.
  362. .. code-block:: javascript
  363. converse.plugins.add('myplugin', {
  364. initialize: function () {
  365. this._converse.api.user.logout();
  366. }
  367. });
  368. The **status** sub-grouping
  369. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  370. Set and get the user's chat status, also called their *availability*.
  371. get
  372. ^^^
  373. Return the current user's availability status:
  374. .. code-block:: javascript
  375. converse.plugins.add('myplugin', {
  376. initialize: function () {
  377. alert(this._converse.api.user.status.get()); // For example "dnd"
  378. }
  379. });
  380. set
  381. ^^^
  382. The user's status can be set to one of the following values:
  383. * **away**
  384. * **dnd**
  385. * **offline**
  386. * **online**
  387. * **unavailable**
  388. * **xa**
  389. For example:
  390. .. code-block:: javascript
  391. converse.plugins.add('myplugin', {
  392. initialize: function () {
  393. this._converse.api.user.status.set('dnd');
  394. }
  395. });
  396. Because the user's availability is often set together with a custom status
  397. message, this method also allows you to pass in a status message as a
  398. second parameter:
  399. .. code-block:: javascript
  400. converse.plugins.add('myplugin', {
  401. initialize: function () {
  402. this._converse.api.user.status.set('dnd', 'In a meeting');
  403. }
  404. });
  405. The **message** sub-grouping
  406. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  407. The ``user.status.message`` sub-grouping exposes methods for setting and
  408. retrieving the user's custom status message.
  409. .. code-block:: javascript
  410. converse.plugins.add('myplugin', {
  411. initialize: function () {
  412. this._converse.api.user.status.message.set('In a meeting');
  413. // Returns "In a meeting"
  414. return this._converse.api.user.status.message.get();
  415. }
  416. });
  417. The **contacts** grouping
  418. -------------------------
  419. get
  420. ~~~
  421. This method is used to retrieve roster contacts.
  422. To get a single roster contact, call the method with the contact's JID (Jabber ID):
  423. .. code-block:: javascript
  424. converse.plugins.add('myplugin', {
  425. initialize: function () {
  426. var _converse = this._converse;
  427. _converse.api.listen.on('rosterContactsFetched', function () {
  428. var contact = _converse.api.contacts.get('buddy@example.com')
  429. });
  430. }
  431. });
  432. To get multiple contacts, pass in an array of JIDs:
  433. .. code-block:: javascript
  434. converse.plugins.add('myplugin', {
  435. initialize: function () {
  436. var _converse = this._converse;
  437. _converse.api.listen.on('rosterContactsFetched', function () {
  438. var contacts = _converse.api.contacts.get(
  439. ['buddy1@example.com', 'buddy2@example.com']
  440. )
  441. });
  442. }
  443. });
  444. To return all contacts, simply call ``get`` without any parameters:
  445. .. code-block:: javascript
  446. converse.plugins.add('myplugin', {
  447. initialize: function () {
  448. var _converse = this._converse;
  449. _converse.api.listen.on('rosterContactsFetched', function () {
  450. var contacts = _converse.api.contacts.get();
  451. });
  452. }
  453. });
  454. The returned roster contact objects have these attributes:
  455. +----------------+-----------------------------------------------------------------------------------------------------------------+
  456. | Attribute | |
  457. +================+=================================================================================================================+
  458. | ask | If ask === 'subscribe', then we have asked this person to be our chat buddy. |
  459. +----------------+-----------------------------------------------------------------------------------------------------------------+
  460. | fullname | The person's full name. |
  461. +----------------+-----------------------------------------------------------------------------------------------------------------+
  462. | jid | The person's Jabber/XMPP username. |
  463. +----------------+-----------------------------------------------------------------------------------------------------------------+
  464. | requesting | If true, then this person is asking to be our chat buddy. |
  465. +----------------+-----------------------------------------------------------------------------------------------------------------+
  466. | subscription | The subscription state between the current user and this chat buddy. Can be `none`, `to`, `from` or `both`. |
  467. +----------------+-----------------------------------------------------------------------------------------------------------------+
  468. | id | A unique id, same as the jid. |
  469. +----------------+-----------------------------------------------------------------------------------------------------------------+
  470. | chat_status | The person's chat status. Can be `online`, `offline`, `busy`, `xa` (extended away) or `away`. |
  471. +----------------+-----------------------------------------------------------------------------------------------------------------+
  472. | user_id | The user id part of the JID (the part before the `@`). |
  473. +----------------+-----------------------------------------------------------------------------------------------------------------+
  474. | resources | The known resources for this chat buddy. Each resource denotes a separate and connected chat client. |
  475. +----------------+-----------------------------------------------------------------------------------------------------------------+
  476. | groups | The roster groups in which this chat buddy was placed. |
  477. +----------------+-----------------------------------------------------------------------------------------------------------------+
  478. | status | Their human readable custom status message. |
  479. +----------------+-----------------------------------------------------------------------------------------------------------------+
  480. | image_type | The image's file type. |
  481. +----------------+-----------------------------------------------------------------------------------------------------------------+
  482. | image | The Base64 encoded image data. |
  483. +----------------+-----------------------------------------------------------------------------------------------------------------+
  484. | url | The buddy's website URL, as specified in their VCard data. |
  485. +----------------+-----------------------------------------------------------------------------------------------------------------+
  486. | vcard_updated | When last the buddy's VCard was updated. |
  487. +----------------+-----------------------------------------------------------------------------------------------------------------+
  488. add
  489. ~~~
  490. Add a contact.
  491. Provide the JID of the contact you want to add:
  492. .. code-block:: javascript
  493. _converse.api.contacts.add('buddy@example.com')
  494. You may also provide the fullname. If not present, we use the jid as fullname:
  495. .. code-block:: javascript
  496. _converse.api.contacts.add('buddy@example.com', 'Buddy')
  497. The **chats** grouping
  498. ----------------------
  499. Note, for MUC chat rooms, you need to use the "rooms" grouping instead.
  500. get
  501. ~~~
  502. Returns an object representing a chat box. The chat box should already be open.
  503. To return a single chat box, provide the JID of the contact you're chatting
  504. with in that chat box:
  505. .. code-block:: javascript
  506. _converse.api.chats.get('buddy@example.com')
  507. To return an array of chat boxes, provide an array of JIDs:
  508. .. code-block:: javascript
  509. _converse.api.chats.get(['buddy1@example.com', 'buddy2@example.com'])
  510. To return all open chat boxes, call the method without any JIDs::
  511. _converse.api.chats.get()
  512. open
  513. ~~~~
  514. Opens a chat box and returns a `Backbone.View <http://backbonejs.org/#View>`_ object
  515. representing a chat box.
  516. Note that converse doesn't allow opening chats with users who aren't in your roster
  517. (unless you have set :ref:`allow_non_roster_messaging` to ``true``).
  518. Before opening a chat, you should first wait until the roster has been populated.
  519. This is the :ref:`rosterContactsFetched` event/promise.
  520. Besides that, it's a good idea to also first wait until already opened chat boxes
  521. (which are cached in sessionStorage) have also been fetched from the cache.
  522. This is the :ref:`chatBoxesFetched` event/promise.
  523. These two events fire only once per session, so they're also available as promises.
  524. So, to open a single chat box:
  525. .. code-block:: javascript
  526. converse.plugins.add('myplugin', {
  527. initialize: function() {
  528. var _converse = this._converse;
  529. Promise.all([
  530. _converse.api.waitUntil('rosterContactsFetched'),
  531. _converse.api.waitUntil('chatBoxesFetched')
  532. ]).then(function() {
  533. // Note, buddy@example.org must be in your contacts roster!
  534. _converse.api.chats.open('buddy@example.com')
  535. });
  536. }
  537. });
  538. To return an array of chat boxes, provide an array of JIDs:
  539. .. code-block:: javascript
  540. converse.plugins.add('myplugin', {
  541. initialize: function () {
  542. var _converse = this._converse;
  543. Promise.all([
  544. _converse.api.waitUntil('rosterContactsFetched'),
  545. _converse.api.waitUntil('chatBoxesFetched')
  546. ]).then(function() {
  547. // Note, these users must first be in your contacts roster!
  548. _converse.api.chats.open(['buddy1@example.com', 'buddy2@example.com'])
  549. });
  550. }
  551. });
  552. *The returned chat box object contains the following methods:*
  553. +-------------------+------------------------------------------+
  554. | Method | Description |
  555. +===================+==========================================+
  556. | close | Close the chat box. |
  557. +-------------------+------------------------------------------+
  558. | focus | Focuses the chat box textarea |
  559. +-------------------+------------------------------------------+
  560. | model.endOTR | End an OTR (Off-the-record) session. |
  561. +-------------------+------------------------------------------+
  562. | model.get | Get an attribute (i.e. accessor). |
  563. +-------------------+------------------------------------------+
  564. | model.initiateOTR | Start an OTR (off-the-record) session. |
  565. +-------------------+------------------------------------------+
  566. | model.maximize | Minimize the chat box. |
  567. +-------------------+------------------------------------------+
  568. | model.minimize | Maximize the chat box. |
  569. +-------------------+------------------------------------------+
  570. | model.set | Set an attribute (i.e. mutator). |
  571. +-------------------+------------------------------------------+
  572. | show | Opens/shows the chat box. |
  573. +-------------------+------------------------------------------+
  574. *The get and set methods can be used to retrieve and change the following attributes:*
  575. +-------------+-----------------------------------------------------+
  576. | Attribute | Description |
  577. +=============+=====================================================+
  578. | height | The height of the chat box. |
  579. +-------------+-----------------------------------------------------+
  580. | url | The URL of the chat box heading. |
  581. +-------------+-----------------------------------------------------+
  582. .. _`listen-grouping`:
  583. The **listen** grouping
  584. -----------------------
  585. Converse.js emits events to which you can subscribe from your own JavaScript.
  586. Concerning events, the following methods are available under the "listen"
  587. grouping:
  588. * **on(eventName, callback, [context])**:
  589. Calling the ``on`` method allows you to subscribe to an event.
  590. Every time the event fires, the callback method specified by ``callback`` will be
  591. called.
  592. Parameters:
  593. * ``eventName`` is the event name as a string.
  594. * ``callback`` is the callback method to be called when the event is emitted.
  595. * ``context`` (optional), the value of the `this` parameter for the callback.
  596. For example:
  597. .. code-block:: javascript
  598. _converse.api.listen.on('message', function (messageXML) { ... });
  599. * **once(eventName, callback, [context])**:
  600. Calling the ``once`` method allows you to listen to an event
  601. exactly once.
  602. Parameters:
  603. * ``eventName`` is the event name as a string.
  604. * ``callback`` is the callback method to be called when the event is emitted.
  605. * ``context`` (optional), the value of the `this` parameter for the callback.
  606. For example:
  607. .. code-block:: javascript
  608. _converse.api.listen.once('message', function (messageXML) { ... });
  609. * **not(eventName, callback)**
  610. To stop listening to an event, you can use the ``not`` method.
  611. Parameters:
  612. * ``eventName`` is the event name as a string.
  613. * ``callback`` refers to the function that is to be no longer executed.
  614. For example:
  615. .. code-block:: javascript
  616. _converse.api.listen.not('message', function (messageXML) { ... });
  617. The **rooms** grouping
  618. ----------------------
  619. get
  620. ~~~
  621. Returns an object representing a multi user chat box (room).
  622. It takes 3 parameters:
  623. * the room JID (if not specified, all rooms will be returned).
  624. * a map (object) containing any extra room attributes For example, if you want
  625. to specify the nickname, use ``{'nick': 'bloodninja'}``. Previously (before
  626. version 1.0.7, the second parameter only accepted the nickname (as a string
  627. value). This is currently still accepted, but then you can't pass in any
  628. other room attributes. If the nickname is not specified then the node part of
  629. the user's JID will be used.
  630. * a boolean, indicating whether the room should be created if not found (default: `false`)
  631. .. code-block:: javascript
  632. converse.plugins.add('myplugin', {
  633. initialize: function () {
  634. var _converse = this._converse;
  635. _converse.api.waitUntil('roomsAutoJoined').then(function () {
  636. var create_if_not_found = true;
  637. this._converse.api.rooms.open(
  638. 'group@muc.example.com',
  639. {'nick': 'dread-pirate-roberts'},
  640. create_if_not_found
  641. )
  642. });
  643. }
  644. });
  645. open
  646. ~~~~
  647. Opens a multi user chat box and returns an object representing it.
  648. Similar to the ``chats.get`` API.
  649. It takes 2 parameters:
  650. * The room JID or JIDs (if not specified, all currently open rooms will be returned).
  651. * A map (object) containing any extra room attributes. For example, if you want
  652. to specify the nickname, use ``{'nick': 'bloodninja'}``.
  653. To open a single multi user chat box, provide the JID of the room:
  654. .. code-block:: javascript
  655. converse.plugins.add('myplugin', {
  656. initialize: function () {
  657. this._converse.api.rooms.open('group@muc.example.com')
  658. }
  659. });
  660. To return an array of rooms, provide an array of room JIDs:
  661. .. code-block:: javascript
  662. converse.plugins.add('myplugin', {
  663. initialize: function () {
  664. this._converse.api.rooms.open(['group1@muc.example.com', 'group2@muc.example.com'])
  665. }
  666. });
  667. To setup a custom nickname when joining the room, provide the optional nick argument:
  668. .. code-block:: javascript
  669. converse.plugins.add('myplugin', {
  670. initialize: function () {
  671. this._converse.api.rooms.open('group@muc.example.com', {'nick': 'mycustomnick'})
  672. }
  673. });
  674. Room attributes that may be passed in:
  675. * *nick*: The nickname to be used
  676. * *auto_configure*: A boolean, indicating whether the room should be configured
  677. automatically or not. If set to ``true``, then it makes sense to pass in
  678. configuration settings.
  679. * *roomconfig*: A map of configuration settings to be used when the room gets
  680. configured automatically. Currently it doesn't make sense to specify
  681. ``roomconfig`` values if ``auto_configure`` is set to ``false``.
  682. For a list of configuration values that can be passed in, refer to these values
  683. in the `XEP-0045 MUC specification <http://xmpp.org/extensions/xep-0045.html#registrar-formtype-owner>`_.
  684. The values should be named without the ``muc#roomconfig_`` prefix.
  685. * *maximize*: A boolean, indicating whether minimized rooms should also be
  686. maximized, when opened. Set to ``false`` by default.
  687. For example, opening a room with a specific default configuration:
  688. .. code-block:: javascript
  689. converse.plugins.add('myplugin', {
  690. initialize: function () {
  691. this._converse.api.rooms.open(
  692. 'myroom@conference.example.org',
  693. { 'nick': 'coolguy69',
  694. 'auto_configure': true,
  695. 'roomconfig': {
  696. 'changesubject': false,
  697. 'membersonly': true,
  698. 'persistentroom': true,
  699. 'publicroom': true,
  700. 'roomdesc': 'Comfy room for hanging out',
  701. 'whois': 'anyone'
  702. }
  703. },
  704. true
  705. );
  706. }
  707. });
  708. .. note:: `multi-list` configuration values are not yet supported.
  709. close
  710. ~~~~~
  711. Lets you close open chat rooms. You can call this method without any arguments
  712. to close all open chat rooms, or you can specify a single JID or an array of
  713. JIDs.
  714. .. _`promises-grouping`:
  715. The **promises** grouping
  716. -------------------------
  717. Converse.js and its plugins emit various events which you can listen to via the
  718. :ref:`listen-grouping`.
  719. Some of these events are also available as `ES2015 Promises <http://es6-features.org/#PromiseUsage>`_,
  720. although not all of them could logically act as promises, since some events
  721. might be fired multpile times whereas promises are to be resolved (or
  722. rejected) only once.
  723. The core events, which are also promises are:
  724. * :ref:`cachedRoster`
  725. * :ref:`chatBoxesFetched`
  726. * :ref:`pluginsInitialized`
  727. * :ref:`roster`
  728. * :ref:`rosterContactsFetched`
  729. * :ref:`rosterGroupsFetched`
  730. * :ref:`rosterInitialized`
  731. * :ref:`statusInitialized`
  732. * :ref:`roomsPanelRendered` (only via the `converse-muc` plugin)
  733. The various plugins might also provide promises, and they do this by using the
  734. ``promises.add`` api method.
  735. add(promises)
  736. ~~~~~~~~~~~~~
  737. By calling ``promises.add``, a new promise is made available for other code or
  738. plugins to depend on via the ``_converse.api.waitUntil`` method.
  739. This method accepts either a string or list of strings which specify the
  740. promise(s) to be added.
  741. For example:
  742. .. code-block:: javascript
  743. converse.plugins.add('myplugin', {
  744. initialize: function () {
  745. this._converse.api.promises.add('foo-completed');
  746. }
  747. });
  748. Generally, it's the responsibility of the plugin which adds the promise to
  749. also resolve it.
  750. This is done by calling ``_converse.api.emit``, which not only resolve the
  751. promise, but also emit an event with the same name (which can be listened to
  752. via ``_converse.api.listen``).
  753. For example:
  754. .. code-block:: javascript
  755. _converse.api.emit('foo-completed');
  756. The **settings** grouping
  757. -------------------------
  758. This grouping allows access to the configuration settings of converse.js.
  759. .. _`settings-update`:
  760. update(settings)
  761. ~~~~~~~~~~~~~~~~
  762. Allows new configuration settings to be specified, or new default values for
  763. existing configuration settings to be specified.
  764. For example:
  765. .. code-block:: javascript
  766. converse.plugins.add('myplugin', {
  767. initialize: function () {
  768. this._converse.api.settings.update({
  769. 'enable_foo': true
  770. });
  771. }
  772. });
  773. The user can then override the default value of the configuration setting when
  774. calling `converse.initialize`.
  775. For example:
  776. .. code-block:: javascript
  777. converse.initialize({
  778. 'enable_foo': false
  779. });
  780. get(key)
  781. ~~~~~~~~
  782. Returns the value of a configuration settings. For example:
  783. .. code-block:: javascript
  784. converse.plugins.add('myplugin', {
  785. initialize: function () {
  786. // default value would be false;
  787. alert(this._converse.api.settings.get("play_sounds"));
  788. }
  789. });
  790. set(key, value) or set(object)
  791. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  792. Set one or many configuration settings. For example:
  793. .. code-block:: javascript
  794. converse.plugins.add('myplugin', {
  795. initialize: function () {
  796. this._converse.api.settings.set("play_sounds", true);
  797. }
  798. });
  799. or :
  800. .. code-block:: javascript
  801. converse.plugins.add('myplugin', {
  802. initialize: function () {
  803. this._converse.api.settings.set({
  804. "play_sounds", true,
  805. "hide_offline_users" true
  806. });
  807. }
  808. });
  809. Note, this is not an alternative to calling ``converse.initialize``, which still needs
  810. to be called. Generally, you'd use this method after converse.js is already
  811. running and you want to change the configuration on-the-fly.
  812. The **tokens** grouping
  813. -----------------------
  814. get
  815. ~~~
  816. Returns a token, either the RID or SID token depending on what's asked for.
  817. Example:
  818. .. code-block:: javascript
  819. converse.plugins.add('myplugin', {
  820. initialize: function () {
  821. alert(this._converse.api.tokens.get('rid'));
  822. }
  823. });
  824. The **vcard** grouping
  825. -----------------------
  826. get
  827. ~~~
  828. Returns a Promise which results with the VCard data for a particular JID.
  829. Example:
  830. .. code-block:: javascript
  831. converse.plugins.add('myplugin', {
  832. initialize: function () {
  833. _converse.api.waitUntil('rosterContactsFetched').then(() => {
  834. this._converse.api.vcard.get('someone@example.org').then(
  835. (vcard) => {
  836. // Do something with the vcard...
  837. }
  838. );
  839. });
  840. }
  841. });