plugin_development.rst 23 KB

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