plugin_development.rst 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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 has a plugin architecture based on `pluggable.js <https://github.com/jcbrand/pluggable.js/>`_
  9. and is itself composed out of plugins.
  10. There are only a few files that are included in the default build of Converse
  11. which aren't plugins.
  12. An important one is `converse-core.js <https://github.com/conversejs/converse.js/blob/master/src/headless/converse-core.js>`_,
  13. which is responsible for bootstrapping the plugin architecture,
  14. setting up and maintaining the connection to the XMPP
  15. server and declaring the public (`window.converse </docs/html/api/converse.html>`_) and protected (`_converse.api </docs/html/api/-_converse.api.html>`_) APIs.
  16. The other non-plugin files all contain utility methods in
  17. `src/utils <https://github.com/conversejs/converse.js/blob/master/src/utils>`_ and
  18. `src/headless/utils <https://github.com/conversejs/converse.js/blob/master/src/headless/utils>`_.
  19. As a general rule, any file in the ``./src`` directory that starts with
  20. ``converse-`` is a plugin (with the exception of ``converse-core.js``.
  21. The plugin architecture lets you add new features or modify existing functionality in a
  22. modular and self-contained way, without having to change other files.
  23. This ensures that plugins are fully optional (one of the design goals of
  24. Converse) and can be removed from the main build without breaking the app.
  25. For example, the ``converse-omemo``,
  26. ``converse-rosterview``, ``converse-dragresize``, ``converse-minimize``,
  27. ``converse-muc`` and ``converse-muc-views`` plugins can all be removed from the
  28. build without breaking the app.
  29. To more deeply understand how the plugin architecture works, read the
  30. `pluggable.js documentation <https://jcbrand.github.io/pluggable.js/>`_
  31. and to understand its inner workings, refer to the `annotated source code
  32. <https://jcbrand.github.io/pluggable.js/docs/pluggable.html>`_.
  33. Advantages of plugins
  34. ---------------------
  35. Writing a plugin is the recommended way to customize or add new features to Converse.
  36. The main benefit of plugins is that they allow for **isolation of concerns** (and features).
  37. From this benefit flows various 2nd order advantages, such as the ability to
  38. make smaller production builds (by excluding unused plugins) and an easier
  39. upgrade path by avoiding touching Converse's internals.
  40. Plugins are especially useful if you want to add proprietary modifications, since the
  41. Mozilla Public License version 2 doesn't require you to open source your
  42. plugin files. Be aware that this doesn't apply when you intend to use libsignal for
  43. OMEMO encryption because libsignal's license is GPLv3 (and turns the entire app
  44. into a GPLv3 app).
  45. Each plugin comes in its own file, and Converse's plugin architecture,
  46. `pluggable.js <https://github.com/jcbrand/pluggable.js/>`_, provides you
  47. with the ability to "hook in" to the core code and other plugins.
  48. Plugins enable developers to extend and override existing objects,
  49. functions and the models and views that make up
  50. Converse. You can also create new models and views.
  51. .. note:: **Trying out a plugin in JSFiddle**
  52. Because Converse consists only of JavaScript, HTML and CSS (with no backend
  53. code required like PHP, Python or Ruby) it runs fine in JSFiddle.
  54. Here's a Fiddle with a Converse plugin that calls ``alert`` once it gets
  55. initialized and also when a chat message gets rendered: https://jsfiddle.net/4drfaok0/15/
  56. .. note:: **Generating a plugin with Yeoman**
  57. The rest of this document explains how to write a plugin for Converse and
  58. ends with a documented example of a plugin.
  59. There is a `Yeoman <http://yeoman.io/>`_ code generator, called
  60. `generator-conversejs <https://github.com/jcbrand/generator-conversejs>`_, which
  61. you can use to generate plugin scaffolding/boilerplate that serves as a
  62. starting point and basis for writing your plugin.
  63. Please refer to the `generator-conversejs <https://github.com/jcbrand/generator-conversejs>`_
  64. README for information on how to use it.
  65. Registering a plugin
  66. --------------------
  67. Plugins need to be registered (and whitelisted) before they can be loaded and
  68. initialized.
  69. You register a Converse plugin by calling ``converse.plugins.add``.
  70. The plugin itself is a JavaScript object which usually has at least an
  71. ``initialize`` method, which gets called at the end of the
  72. ``converse.initialize`` method which is the top-level method that gets called
  73. by the website to configure and initialize Converse itself.
  74. Here's an example code snippet:
  75. .. code-block:: javascript
  76. converse.plugins.add('myplugin', {
  77. initialize: function () {
  78. // This method gets called once converse.initialize has been called
  79. // and the plugin itself has been loaded.
  80. // Inside this method, you have access to the closured
  81. // _converse object as an attribute on "this".
  82. // E.g. this._converse
  83. },
  84. });
  85. .. note:: It's important that `converse.plugins.add` is called **before**
  86. `converse.initialize` is called. Otherwise the plugin will never get
  87. registered and never get called.
  88. Whitelisting of plugins
  89. -----------------------
  90. As of Converse 3.0.0 and higher, plugins need to be whitelisted before they
  91. can be used. This is because plugins have access to a powerful API. For
  92. example, they can read all messages and send messages on the user's behalf.
  93. To avoid malicious plugins being registered (i.e. by malware infected
  94. advertising networks) we now require whitelisting.
  95. To whitelist a plugin simply means to specify :ref:`whitelisted_plugins` when
  96. you call ``converse.initialize``.
  97. If you're adding a "core" plugin, which means a plugin that will be
  98. included in the default, open-source version of Converse, then you'll
  99. instead whitelist the plugin by adding its name to the `core_plugins` array in
  100. `./src/headless/converse-core.js <https://github.com/jcbrand/converse.js/blob/master/src/headless/converse-core.js>`_.
  101. or the `WHITELISTED_PLUGINS` array in `./src/converse.js <https://github.com/jcbrand/converse.js/blob/master/src/converse.js>`_.
  102. Where you add it depends on whether your plugin is part of the headless build
  103. (which means it doesn't contain any view code) or not.
  104. Security and access to the inner workings
  105. -----------------------------------------
  106. The globally available ``converse`` object, which exposes the API methods, such
  107. as ``initialize`` and ``plugins.add``, is a wrapper that encloses and protects
  108. a sensitive inner object, named ``_converse`` (not the underscore prefix).
  109. This inner ``_converse`` object contains all the models and views,
  110. as well as various other attributes and functions.
  111. Within a plugin, you will have access to this internal
  112. `"closured" <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures>`_
  113. ``_converse`` object, which is normally not exposed in the global variable scope.
  114. The inner ``_converse`` object is made private in order to safely hide and
  115. encapsulate sensitive information and methods which should not be exposed
  116. to any 3rd-party scripts that might be running in the same page.
  117. Accessing 3rd party libraries
  118. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  119. Immediately inside the module shown above you can access 3rd party libraries (such
  120. dayjs and lodash) via the ``converse.env`` map.
  121. The code for it could look something like this:
  122. .. code-block:: javascript
  123. // Commonly used utilities and variables can be found under the "env"
  124. // namespace of the "converse" global.
  125. const { Promise, Strophe, dayjs, sizzle, _, $build, $iq, $msg, $pres } = converse.env;
  126. These dependencies are closured so that they don't pollute the global
  127. namespace, that's why you need to access them in such a way inside the module.
  128. Overrides
  129. ---------
  130. Plugins can override core code or code from other plugins. You can specify
  131. overrides in the object passed to ``converse.plugins.add``.
  132. In an override you can still call the overridden function, by calling
  133. ``this.__super__.methodName.apply(this, arguments);`` where ``methodName`` is
  134. the name of the function or method you're overriding.
  135. The following code snippet provides an example of two different overrides:
  136. .. code-block:: javascript
  137. overrides: {
  138. /* The *_converse* object has a method "onConnected".
  139. * You can override that method as follows:
  140. */
  141. onConnected: function () {
  142. // Overrides the onConnected method in Converse
  143. // Top-level functions in "overrides" are bound to the
  144. // inner "_converse" object.
  145. const _converse = this;
  146. // Your custom code can come here ...
  147. // You can access the original function being overridden
  148. // via the __super__ attribute.
  149. // Make sure to pass on the arguments supplied to this
  150. // function and also to apply the proper "this" object.
  151. _converse.__super__.onConnected.apply(this, arguments);
  152. // Your custom code can come here ...
  153. },
  154. /* On the XMPPStatus model is a method sendPresence.
  155. * We can override is as follows:
  156. */
  157. XMPPStatus: {
  158. sendPresence: function (type, status_message, jid) {
  159. // The "_converse" object is available via the __super__
  160. // attribute.
  161. const _converse = this.__super__._converse;
  162. // Custom code can come here ...
  163. // You can call the original overridden method, by
  164. // accessing it via the __super__ attribute.
  165. // When calling it, you need to apply the proper
  166. // context as reference by the "this" variable.
  167. this.__super__.sendPresence.apply(this, arguments);
  168. }
  169. }
  170. }
  171. Use the ``overrides`` feature with caution. It basically resorts to
  172. monkey patching which pollutes the call stack and can make your code fragile
  173. and prone to bugs when Converse gets updated. Too much use of ``overrides``
  174. is therefore a "code smell" which should ideally be avoided.
  175. A better approach is to listen to the events emitted by Converse, and to add
  176. your code in event handlers. This is however not always possible, in which case
  177. the overrides are a powerful tool.
  178. Also, while it's possible to add new methods to classes via the ``overrides``
  179. feature, it's better and more explicit to use composition with
  180. ``Object.assign``.
  181. For example:
  182. .. code-block:: javascript
  183. function doSomething () {
  184. // Your code comes here
  185. }
  186. Object.assign(_converse.ChatBoxView.prototype, { doSomething });
  187. Overriding a template
  188. ~~~~~~~~~~~~~~~~~~~~~
  189. Converse uses various templates, loaded with lodash, to generate its HTML.
  190. It's not possible to override a template with the plugin's ``overrides``
  191. feature, instead you should configure a new path to your own template via your
  192. module bundler.
  193. For example, with Webpack (which Converse uses internall), you can specify an
  194. ``alias`` for the template you want to override. This alias then points to your
  195. own custom template.
  196. For example, in your webpack config file, you could add the following to the
  197. ``config`` object that gets exported:
  198. .. code-block:: javascript
  199. module: {
  200. {
  201. test: /templates\/.*\.(html|svg)$/,
  202. use: [{
  203. loader: 'lodash-template-webpack-loader',
  204. options: {
  205. escape: /\{\{\{([\s\S]+?)\}\}\}/g,
  206. evaluate: /\{\[([\s\S]+?)\]\}/g,
  207. interpolate: /\{\{([\s\S]+?)\}\}/g,
  208. // By default, template places the values from your data in the
  209. // local scope via the with statement. However, you can specify
  210. // a single variable name with the variable setting. This can
  211. // significantly improve the speed at which a template is able
  212. // to render.
  213. variable: 'o',
  214. prependFilenameComment: __dirname
  215. }
  216. }]
  217. }
  218. },
  219. resolve: {
  220. extensions: ['.js'],
  221. modules: [
  222. path.join(__dirname, 'node_modules'),
  223. path.join(__dirname, 'node_modules/converse.js/src')
  224. ],
  225. alias: {
  226. 'templates/profile_view.html$': path.resolve(__dirname, 'templates/profile_view.html')
  227. }
  228. }
  229. You'll need to install ``lodash-template-webpack-loader``.
  230. Currently Converse uses a fork of `lodash-template-webpack-loader <https://github.com/jcbrand/lodash-template-webpack-loader>`_.
  231. To install it, you can add ``"lodash-template-webpack-loader": "jcbrand/lodash-template-webpack-loader"``
  232. to your package.json's ``devDependencies``.
  233. .. _`dependencies`:
  234. Plugin dependencies
  235. -------------------
  236. When using ``overrides``, the code that you want to override (which is either
  237. in ``converse-core`` or in other plugins), needs to be parsed already by the
  238. time your ``overrides`` are being parsed.
  239. Additionally, when you register event or promise handlers in your plugin for
  240. events/promises that fire in other plugins, then you want those plugins to have
  241. been loaded before your plugin gets loaded.
  242. To resolve this problem we have the ``dependencies`` Array attribute.
  243. With this you can specify those dependencies which need to be loaded before
  244. your plugin is loaded.
  245. In some cases, you might want to depend on another plugin if it's available,
  246. but don't care when it's not available.
  247. An example is the `converse-dragresize <https://github.com/jcbrand/converse.js/blob/master/src/converse-dragresize.js>`_
  248. plugin, which will add drag-resize handles to the headlines box (which shows
  249. messages of type ``headline``) but doesn't care when that particular plugin is
  250. not available.
  251. If the :ref:`strict_plugin_dependencies` setting is set to ``false`` (which is
  252. its default value), then no error will be raised if the plugin is not found.
  253. In this case, you can't specify the plugin as a dependency in the ``define``
  254. statement at the top of the plugin, since it might not always be available,
  255. which would cause ``require.js`` to throw an error.
  256. Extending Converse's configuration settings
  257. ----------------------------------------------
  258. Converse comes with various :ref:`configuration-settings` that can be used to
  259. modify its functionality and behavior.
  260. All configuration settings have default values which can be overridden when
  261. `converse.initialize` (see `converse.initialize </docs/html/api/converse.html#.initialize>`_)
  262. gets called.
  263. Plugins often need their own additional configuration settings and you can add
  264. these settings with the `_converse.api.settings.update </docs/html/api/-_converse.api.settings.html#.update>`_
  265. method.
  266. Exposing promises
  267. -----------------
  268. Converse has a `waitUntil </docs/html/api/-_converse.api.html#.waitUntil>`_ API method
  269. which allows you to wait for various promises to resolve before executing a
  270. piece of code.
  271. You can add new promises for your plugin by calling
  272. `_converse.api.promises.add </docs/html/api/-_converse.api.promises.html#.add>`_.
  273. Generally, your plugin will then also be responsible for making sure these
  274. promises are resolved. You do this by calling
  275. `_converse.api.trigger </docs/html/api/-_converse.api.html#.trigger>`_, which not
  276. only resolves the plugin but will also emit an event with the same name.
  277. Dealing with asynchronicity
  278. ---------------------------
  279. Due to the asynchronous nature of XMPP, many subroutines in Converse execute
  280. at different times and not necessarily in the same order.
  281. In many cases, when you want to execute a piece of code in a plugin, you first
  282. want to make sure that the supporting data-structures that your code might rely
  283. on have been created and populated with data.
  284. There are two ways of waiting for the right time before executing your code.
  285. You can either listen for certain events, or you can wait for promises to
  286. resolve.
  287. For example, when you want to query the message archive between you and a
  288. friend, you would call ``this._converse.api.archive.query({'with': 'friend@example.org'});``
  289. However, simply calling this immediately in the ``initialize`` method of your plugin will
  290. not work, since the user is not logged in yet.
  291. In this case, you should first listen for the ``connection`` event, and then do your query, like so:
  292. .. code-block:: javascript
  293. converse.plugins.add('myplugin', {
  294. initialize: function () {
  295. const _converse = this._converse;
  296. _converse.api.listen.on('connected', function () {
  297. _converse.api.archive.query({'with': 'admin2@localhost'});
  298. });
  299. }
  300. });
  301. Another example is in the ``Bookmarks`` plugin (in
  302. `src/converse-bookmarks.js <https://github.com/jcbrand/converse.js/blob/6c3aa34c23d97d679823a64376418cd0f40a8b94/src/converse-bookmarks.js#L528>`_).
  303. Before bookmarks can be fetched and shown to the user, we first have to wait until
  304. the `"Rooms"` panel of the ``ControlBox`` has been rendered and inserted into
  305. the DOM. Otherwise we have no place to show the bookmarks yet.
  306. Therefore, there are the following lines of code in the ``initialize`` method of
  307. `converse-bookmarks.js <https://github.com/jcbrand/converse.js/blob/6c3aa34c23d97d679823a64376418cd0f40a8b94/src/converse-bookmarks.js#L528>`_:
  308. .. code-block:: javascript
  309. Promise.all([
  310. _converse.api.waitUntil('chatBoxesFetched'),
  311. _converse.api.waitUntil('roomsPanelRendered')
  312. ]).then(initBookmarks);
  313. What this means, is that the plugin will wait until the ``chatBoxesFetched``
  314. and ``roomsPanelRendered`` promises have been resolved before it calls the
  315. ``initBookmarks`` method (which is defined inside the plugin).
  316. This way, we know that we have everything in place and set up correctly before
  317. fetching the bookmarks.
  318. As yet another example, there is also the following code in the ``initialize``
  319. method of the plugin:
  320. .. code-block:: javascript
  321. _converse.api.listen.on('chatBoxOpened', function renderMinimizeButton (view) {
  322. // Inserts a "minimize" button in the chatview's header
  323. // Implementation code removed for brevity
  324. // ...
  325. });
  326. In this case, the plugin waits for the ``chatBoxOpened`` event, before it then
  327. calls ``renderMinimizeButton``, which adds a new button to the chatbox (which
  328. enables you to minimize it).
  329. Finding the right promises and/or events to listen to, can be a bit
  330. challenging, and sometimes it might be necessary to create new events or
  331. promises.
  332. Please refer to the `API documentation </docs/html/api/http://localhost:8008/docs/html/api/>`_
  333. for an overview of what's available to you. If you need new events or promises, then
  334. `please open an issue or make a pull request on Github <https://github.com/jcbrand/converse.js>`_
  335. A full example plugin
  336. ---------------------
  337. Below follows a documented example of a plugin. This is the same code that gets
  338. generated by `generator-conversejs <https://github.com/jcbrand/generator-conversejs>`_.
  339. .. code-block:: javascript
  340. import converse from "@converse/headless/converse-core";
  341. // Commonly used utilities and variables can be found under the "env"
  342. // namespace of the "converse" global.
  343. const { Promise, Strophe, dayjs, sizzle, _, $build, $iq, $msg, $pres } = converse.env;
  344. // The following line registers your plugin.
  345. converse.plugins.add("myplugin", {
  346. /* Dependencies are other plugins which might be
  347. * overridden or relied upon, and therefore need to be loaded before
  348. * this plugin. They are "optional" because they might not be
  349. * available, in which case any overrides applicable to them will be
  350. * ignored.
  351. *
  352. * NB: These plugins need to have already been imported or loaded,
  353. * either in your plugin or somewhere else.
  354. *
  355. * It's possible to make these dependencies "non-optional".
  356. * If the setting "strict_plugin_dependencies" is set to true,
  357. * an error will be raised if the plugin is not found.
  358. */
  359. dependencies: [],
  360. /* Converse's plugin mechanism will call the initialize
  361. * method on any plugin (if it exists) as soon as the plugin has
  362. * been loaded.
  363. */
  364. initialize: function () {
  365. /* Inside this method, you have access to the private
  366. * `_converse` object.
  367. */
  368. const _converse = this._converse;
  369. _converse.log("The \"myplugin\" plugin is being initialized");
  370. /* From the `_converse` object you can get any configuration
  371. * options that the user might have passed in via
  372. * `converse.initialize`.
  373. *
  374. * You can also specify new configuration settings for this
  375. * plugin, or override the default values of existing
  376. * configuration settings. This is done like so:
  377. */
  378. _converse.api.settings.update({
  379. 'initialize_message': 'Initializing myplugin!'
  380. });
  381. /* The user can then pass in values for the configuration
  382. * settings when `converse.initialize` gets called.
  383. * For example:
  384. *
  385. * converse.initialize({
  386. * "initialize_message": "My plugin has been initialized"
  387. * });
  388. */
  389. alert(this._converse.initialize_message);
  390. /* Besides `_converse.api.settings.update`, there is also a
  391. * `_converse.api.promises.add` method, which allows you to
  392. * add new promises that your plugin is obligated to fulfill.
  393. *
  394. * This method takes a string or a list of strings which
  395. * represent the promise names:
  396. *
  397. * _converse.api.promises.add('myPromise');
  398. *
  399. * Your plugin should then, when appropriate, resolve the
  400. * promise by calling `_converse.api.emit`, which will also
  401. * emit an event with the same name as the promise.
  402. * For example:
  403. *
  404. * _converse.api.trigger('operationCompleted');
  405. *
  406. * Other plugins can then either listen for the event
  407. * `operationCompleted` like so:
  408. *
  409. * _converse.api.listen.on('operationCompleted', function { ... });
  410. *
  411. * or they can wait for the promise to be fulfilled like so:
  412. *
  413. * _converse.api.waitUntil('operationCompleted', function { ... });
  414. */
  415. },
  416. /* If you want to override some function or a model or
  417. * view defined elsewhere in Converse, then you do that under
  418. * the "overrides" namespace.
  419. */
  420. overrides: {
  421. /* For example, the private *_converse* object has a
  422. * method "onConnected". You can override that method as follows:
  423. */
  424. onConnected: function () {
  425. // Overrides the onConnected method in Converse
  426. // Top-level functions in "overrides" are bound to the
  427. // inner "_converse" object.
  428. const _converse = this;
  429. // Your custom code can come here ...
  430. // You can access the original function being overridden
  431. // via the __super__ attribute.
  432. // Make sure to pass on the arguments supplied to this
  433. // function and also to apply the proper "this" object.
  434. _converse.__super__.onConnected.apply(this, arguments);
  435. // Your custom code can come here ...
  436. },
  437. /* Override Converse's XMPPStatus model so that we can override the
  438. * function that sends out the presence stanza.
  439. */
  440. XMPPStatus: {
  441. sendPresence: function (type, status_message, jid) {
  442. // The "_converse" object is available via the __super__
  443. // attribute.
  444. const _converse = this.__super__._converse;
  445. // Custom code can come here ...
  446. // You can call the original overridden method, by
  447. // accessing it via the __super__ attribute.
  448. // When calling it, you need to apply the proper
  449. // context as reference by the "this" variable.
  450. this.__super__.sendPresence.apply(this, arguments);
  451. // Custom code can come here ...
  452. }
  453. }
  454. }
  455. });