plugin_development.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  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. .. _`writing-a-plugin`:
  4. Writing a plugin
  5. ================
  6. Introduction
  7. ------------
  8. Converse.js is exposes a plugin architecture which allows developers to modify
  9. and extend its functionality.
  10. Specifically, plugins enable developers to extend and override existing objects,
  11. functions and `Backbone <http://backbonejs.org/>`_ models and views that make up
  12. Converse.js, and also give them the ability to write new models and views.
  13. Various core features of Converse.js, such as
  14. `Message Archive Management <https://xmpp.org/extensions/xep-0313.html>`_ and
  15. `Group chats <https://xmpp.org/extensions/xep-0045.html>`_ are implemented
  16. as plugins, thereby showing their power and flexibility.
  17. Converse.js uses `pluggable.js <https://github.com/jcbrand/pluggable.js/>`_ as
  18. its plugin architecture.
  19. To more deeply understand how this plugin architecture works, please read the
  20. `pluggable.js documentation <https://jcbrand.github.io/pluggable.js/>`_
  21. and to understand its inner workins, please refer to the `annotated source code
  22. <https://jcbrand.github.io/pluggable.js/docs/pluggable.html>`_.
  23. .. note:: **Trying out a plugin in JSFiddle**
  24. Because Converse.js consists only of JavaScript, HTML and CSS (with no backend
  25. code required like PHP, Python or Ruby) it runs fine in JSFiddle.
  26. Here's a Fiddle with a Converse.js plugin that calls ``alert`` once it gets
  27. initialized and also when a chat message gets rendered: https://jsfiddle.net/4drfaok0/15/
  28. .. note:: **Generating a plugin with Yeoman**
  29. The rest of this document explains how to write a plugin for Converse.js and
  30. ends with a documented example of a plugin.
  31. There is a `Yeoman <http://yeoman.io/>`_ code generator, called
  32. `generator-conversejs <https://github.com/jcbrand/generator-conversejs>`_, which
  33. you can use to generate plugin scaffolding/boilerplate, which you can use as a
  34. starting point and basis for writing your plugin.
  35. Please refer to the `generator-conversejs <https://github.com/jcbrand/generator-conversejs>`_
  36. README for information on how to use it.
  37. Registering a plugin
  38. --------------------
  39. Plugins need to be registered (and whitelisted) before they can be loaded and
  40. initialized.
  41. You register a converse.js plugin by calling ``converse.plugins.add``.
  42. The plugin itself is a JavaScript object which usually has at least an
  43. ``initialize`` method, which gets called at the end of the
  44. ``converse.initialize`` method which is the top-level method that gets called
  45. by the website to configure and initialize Converse.js itself.
  46. Here's an example code snippet:
  47. .. code-block:: javascript
  48. converse.plugins.add('myplugin', {
  49. initialize: function () {
  50. // This method gets called once converse.initialize has been called
  51. // and the plugin itself has been loaded.
  52. // Inside this method, you have access to the closured
  53. // _converse object as an attribute on "this".
  54. // E.g. this._converse
  55. },
  56. });
  57. .. note:: It's important that `converse.plugins.add` is called **before**
  58. `converse.initialize` is called. Otherwise the plugin will never get
  59. registered and never get called.
  60. Whitelisting of plugins
  61. -----------------------
  62. As of converse.js 3.0.0 and higher, plugins need to be whitelisted before they
  63. can be used. This is because plugins have access to a powerful API. For
  64. example, they can read all messages and send messages on the user's behalf.
  65. To avoid malicious plugins being registered (i.e. by malware infected
  66. advertising networks) we now require whitelisting.
  67. To whitelist a plugin simply means to specify :ref:`whitelisted_plugins` when
  68. you call ``converse.initialize``.
  69. Security and access to the inner workings
  70. -----------------------------------------
  71. The globally available ``converse`` object, which exposes the API methods, such
  72. as ``initialize`` and ``plugins.add``, is a wrapper that encloses and protects
  73. a sensitive inner object, named ``_converse`` (not the underscore prefix).
  74. This inner ``_converse`` object contains all the Backbone models and views,
  75. as well as various other attributes and functions.
  76. Within a plugin, you will have access to this internal
  77. `"closured" <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures>`_
  78. ``_converse`` object, which is normally not exposed in the global variable scope.
  79. The inner ``_converse`` object is made private in order to safely hide and
  80. encapsulate sensitive information and methods which should not be exposed
  81. to any 3rd-party scripts that might be running in the same page.
  82. Loading a plugin module
  83. -----------------------
  84. Converse.js uses the UMD (Universal Modules Definition) as its module syntax.
  85. This makes modules loadable via `require.js`, `webpack` or other module
  86. loaders, but also includable as old-school `<script>` tags in your HTML.
  87. Here's an example of the plugin shown above wrapped inside a UMD module:
  88. .. code-block:: javascript
  89. (function (root, factory) {
  90. if (typeof define === 'function' && define.amd) {
  91. // AMD. Register as a module called "myplugin"
  92. define(["converse"], factory);
  93. } else {
  94. // Browser globals. If you're not using a module loader such as require.js,
  95. // then this line below executes. Make sure that your plugin's <script> tag
  96. // appears after the one from converse.js.
  97. factory(converse);
  98. }
  99. }(this, function (converse) {
  100. converse.plugins.add('myplugin', {
  101. initialize: function () {
  102. // This method gets called once converse.initialize has been called
  103. // and the plugin itself has been loaded.
  104. // Inside this method, you have access to the closured
  105. // _converse object as an attribute on "this".
  106. // E.g. this._converse
  107. },
  108. });
  109. });
  110. Accessing 3rd party libraries
  111. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  112. Immediately inside the module shown above you can access 3rd party libraries (such
  113. moment, underscore and jQuery) via the ``converse.env`` map.
  114. The code for it would look something like this:
  115. .. code-block:: javascript
  116. // Commonly used utilities and variables can be found under the "env"
  117. // namespace of the "converse" global.
  118. var Strophe = converse.env.Strophe,
  119. $iq = converse.env.$iq,
  120. $msg = converse.env.$msg,
  121. $pres = converse.env.$pres,
  122. $build = converse.env.$build,
  123. b64_sha1 = converse.env.b64_sha1;
  124. $ = converse.env.jQuery,
  125. _ = converse.env._,
  126. moment = converse.env.moment;
  127. These dependencies are closured so that they don't pollute the global
  128. namespace, that's why you need to access them in such a way inside the module.
  129. Overrides
  130. ---------
  131. Plugins can override core code or code from other plugins. Refer to the full
  132. example at the bottom for code details.
  133. Use the ``overrides`` functionality with caution. It basically resorts to
  134. monkey patching which pollutes the call stack and can make your code fragile
  135. and prone to bugs when Converse.js gets updated. Too much use of ``overrides``
  136. is therefore a "code smell" which should ideally be avoided.
  137. A better approach is to listen to the events emitted by Converse.js, and to add
  138. your code in event handlers. This is however not always possible, in which case
  139. the overrides are a powerful tool.
  140. .. _`optional_dependencies`:
  141. Optional plugin dependencies
  142. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  143. When using ``overrides``, the code that you want to override (which is either
  144. in ``converse-core`` or in other plugins), needs to be loaded already by the
  145. type the ``overrides`` object is being parsed.
  146. So it's important to include overridden plugins in the AMD ``define`` statement
  147. at the top of the plugin module.
  148. However, sometimes you want to override parts of another plugin if it exists, but you
  149. don't want anything to break if it doesn't exist (for example when using a
  150. custom build which excludes that plugin). An example is the
  151. `converse-dragresize <https://github.com/jcbrand/converse.js/blob/master/src/converse-dragresize.js>`_
  152. plugin, which will add drag-resize handles to the headlines box (which shows
  153. messages of type ``headline``) but doesn't care if that particular plugin isn't
  154. actually loaded.
  155. In this case, you can't specify the plugin as a dependency in the ``define``
  156. statement at the top of the plugin, since it might not always be available,
  157. which would cause ``require.js`` to throw an error.
  158. To resolve this problem we have the ``optional_dependencies`` Array attribute.
  159. With this you can specify those dependencies which need to be loaded before
  160. your plugin, if they exist. If they don't exist, they won't be ignored.
  161. If the setting :ref:`strict_plugin_dependencies` is set to true,
  162. an error will be raised if the plugin is not found, thereby making them
  163. non-optional.
  164. Extending converse.js's configuration settings
  165. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  166. Converse.js comes with various :ref:`configuration-settings`_ that can be used to
  167. modify its functionality and behavior.
  168. All configuration settings have default values which can be overridden when
  169. `converse.initialize` (see :ref:`initialize`_) gets called.
  170. Plugins often need their own additional configuration settings and you can add
  171. these settings with the `_converse.api.settings.update` method (see
  172. :ref:`settings-update`_).
  173. Exposing promises
  174. ~~~~~~~~~~~~~~~~~
  175. Converse.js has a ``waitUntil`` API method (see :ref:`waituntil-grouping`_)
  176. which allows you to wait for various promises to resolve before executing a
  177. piece of code.
  178. You can add new promises for your plugin by calling
  179. ``_converse.api.promises.add`` (see :ref:`promises-grouping`_).
  180. Generally, your plugin will then also be responsible for making sure these
  181. promises are resolved. You do this by calling ``_converse.api.emit``, which not
  182. only resolves the plugin but will also emit an event with the same name.
  183. Dealing with asynchronicity
  184. ---------------------------
  185. Due to the asynchronous nature of XMPP, many subroutines in Converse.js execute
  186. at different times and not necessarily in the same order.
  187. In many cases, when you want to execute a piece of code in a plugin, you first
  188. want to make sure that the supporting data-structures that your code might rely
  189. on have been created and populated with data.
  190. There are two ways of waiting for the right time before executing your code.
  191. You can either listen for certain events, or you can wait for promises to
  192. resolve.
  193. For example, when you want to query the message archive between you and a
  194. friend, you would call ``this._converse.api.archive.query({'with': 'friend@example.org'});``
  195. However, simply calling this immediately in the ``initialize`` method of your plugin will
  196. not work, since the user is not logged in yet.
  197. In this case, you should first listen for the ``connection`` event, and then do your query, like so:
  198. .. code-block:: javascript
  199. converse.plugins.add('myplugin', {
  200. initialize: function () {
  201. var _converse = this._converse;
  202. _converse.on('connected', function () {
  203. _converse.api.archive.query({'with': 'admin2@localhost'});
  204. });
  205. }
  206. });
  207. Another example is in the ``Bookmarks`` plugin (in
  208. `src/converse-bookmarks.js <https://github.com/jcbrand/converse.js/blob/6c3aa34c23d97d679823a64376418cd0f40a8b94/src/converse-bookmarks.js#L528>`_).
  209. Before bookmarks can be fetched and shown to the user, we first have to wait until
  210. the `"Rooms"` panel of the ``ControlBox`` has been rendered and inserted into
  211. the DOM. Otherwise we have no place to show the bookmarks yet.
  212. Therefore, there are the following lines of code in the ``initialize`` method of
  213. `converse-bookmarks.js <https://github.com/jcbrand/converse.js/blob/6c3aa34c23d97d679823a64376418cd0f40a8b94/src/converse-bookmarks.js#L528>`_:
  214. .. code-block:: javascript
  215. Promise.all([
  216. _converse.api.waitUntil('chatBoxesFetched'),
  217. _converse.api.waitUntil('roomsPanelRendered')
  218. ]).then(initBookmarks);
  219. What this means, is that the plugin will wait until the ``chatBoxesFetched``
  220. and ``roomsPanelRendered`` promises have been resolved before it calls the
  221. ``initBookmarks`` method (which is defined inside the plugin).
  222. This way, we know that we have everything in place and set up correctly before
  223. fetching the bookmarks.
  224. As yet another example, there is also the following code in the ``initialize``
  225. method of the plugin:
  226. .. code-block:: javascript
  227. _converse.on('chatBoxOpened', function renderMinimizeButton (view) {
  228. // Inserts a "minimize" button in the chatview's header
  229. // Implementation code removed for brevity
  230. // ...
  231. });
  232. In this case, the plugin waits for the ``chatBoxOpened`` event, before it then
  233. calls ``renderMinimizeButton``, which adds a new button to the chat box (which
  234. enables you to minimize it).
  235. Finding the right promises and/or events to listen to, can be a bit
  236. challenging, and sometimes it might be necessary to create new events or
  237. promises.
  238. Please refer to the :ref:`events-API` section of the documentation for an
  239. overview of what's available to you. If you need new events or promises, then
  240. `please open an issue or make a pull request on Github <https://github.com/jcbrand/converse.js>`_
  241. A full example plugin
  242. ---------------------
  243. Below follows a documented example of a plugin. This is the same code that gets
  244. generated by `generator-conversejs <https://github.com/jcbrand/generator-conversejs>`_.
  245. .. code-block:: javascript
  246. (function (root, factory) {
  247. if (typeof define === 'function' && define.amd) {
  248. // AMD. Register as a module called "myplugin"
  249. define(["converse"], factory);
  250. } else {
  251. // Browser globals. If you're not using a module loader such as require.js,
  252. // then this line below executes. Make sure that your plugin's <script> tag
  253. // appears after the one from converse.js.
  254. factory(converse);
  255. }
  256. }(this, function (converse) {
  257. // Commonly used utilities and variables can be found under the "env"
  258. // namespace of the "converse" global.
  259. var Strophe = converse.env.Strophe,
  260. $iq = converse.env.$iq,
  261. $msg = converse.env.$msg,
  262. $pres = converse.env.$pres,
  263. $build = converse.env.$build,
  264. b64_sha1 = converse.env.b64_sha1;
  265. $ = converse.env.jQuery,
  266. _ = converse.env._,
  267. moment = converse.env.moment;
  268. // The following line registers your plugin.
  269. converse.plugins.add("myplugin", {
  270. /* Optional dependencies are other plugins which might be
  271. * overridden or relied upon, and therefore need to be loaded before
  272. * this plugin. They are called "optional" because they might not be
  273. * available, in which case any overrides applicable to them will be
  274. * ignored.
  275. *
  276. * NB: These plugins need to have already been loaded via require.js.
  277. *
  278. * It's possible to make optional dependencies non-optional.
  279. * If the setting "strict_plugin_dependencies" is set to true,
  280. * an error will be raised if the plugin is not found.
  281. */
  282. 'optional_dependencies': [],
  283. /* Converse.js's plugin mechanism will call the initialize
  284. * method on any plugin (if it exists) as soon as the plugin has
  285. * been loaded.
  286. */
  287. 'initialize': function () {
  288. /* Inside this method, you have access to the private
  289. * `_converse` object.
  290. */
  291. var _converse = this._converse;
  292. _converse.log("The \"myplugin\" plugin is being initialized");
  293. /* From the `_converse` object you can get any configuration
  294. * options that the user might have passed in via
  295. * `converse.initialize`. These values are stored in the
  296. * "user_settings" attribute.
  297. *
  298. * You can also specify new configuration settings for this
  299. * plugin, or override the default values of existing
  300. * configuration settings. This is done like so:
  301. */
  302. _converse.api.settings.update({
  303. 'initialize_message': 'Initializing myplugin!'
  304. });
  305. /* The user can then pass in values for the configuration
  306. * settings when `converse.initialize` gets called.
  307. * For example:
  308. *
  309. * converse.initialize({
  310. * "initialize_message": "My plugin has been initialized"
  311. * });
  312. *
  313. * And the configuration setting is then available via the
  314. * `user_settings` attribute:
  315. */
  316. alert(this._converse.user_settings.initialize_message);
  317. /* Besides `_converse.api.settings.update`, there is also a
  318. * `_converse.api.promises.add` method, which allows you to
  319. * add new promises that your plugin is obligated to fulfill.
  320. *
  321. * This method takes a string or a list of strings which
  322. * represent the promise names:
  323. *
  324. * _converse.api.promises.add('myPromise');
  325. *
  326. * Your plugin should then, when appropriate, resolve the
  327. * promise by calling `_converse.api.emit`, which will also
  328. * emit an event with the same name as the promise.
  329. * For example:
  330. *
  331. * _converse.api.emit('operationCompleted');
  332. *
  333. * Other plugins can then either listen for the event
  334. * `operationCompleted` like so:
  335. *
  336. * _converse.api.listen.on('operationCompleted', function { ... });
  337. *
  338. * or they can wait for the promise to be fulfilled like so:
  339. *
  340. * _converse.api.waitUntil('operationCompleted', function { ... });
  341. */
  342. },
  343. /* If you want to override some function or a Backbone model or
  344. * view defined elsewhere in converse.js, then you do that under
  345. * the "overrides" namespace.
  346. */
  347. 'overrides': {
  348. /* For example, the private *_converse* object has a
  349. * method "onConnected". You can override that method as follows:
  350. */
  351. 'onConnected': function () {
  352. // Overrides the onConnected method in converse.js
  353. // Top-level functions in "overrides" are bound to the
  354. // inner "_converse" object.
  355. var _converse = this;
  356. // Your custom code can come here ...
  357. // You can access the original function being overridden
  358. // via the __super__ attribute.
  359. // Make sure to pass on the arguments supplied to this
  360. // function and also to apply the proper "this" object.
  361. _converse.__super__.onConnected.apply(this, arguments);
  362. // Your custom code can come here ...
  363. },
  364. /* Override converse.js's XMPPStatus Backbone model so that we can override the
  365. * function that sends out the presence stanza.
  366. */
  367. 'XMPPStatus': {
  368. 'sendPresence': function (type, status_message, jid) {
  369. // The "_converse" object is available via the __super__
  370. // attribute.
  371. var _converse = this.__super__._converse;
  372. // Custom code can come here ...
  373. // You can call the original overridden method, by
  374. // accessing it via the __super__ attribute.
  375. // When calling it, you need to apply the proper
  376. // context as reference by the "this" variable.
  377. this.__super__.sendPresence.apply(this, arguments);
  378. // Custom code can come here ...
  379. }
  380. }
  381. }
  382. });
  383. }));