]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - support/doc/plugins/guide.md
Add custom modal to plugin helpers (#2631)
[github/Chocobozzz/PeerTube.git] / support / doc / plugins / guide.md
CommitLineData
662e5d4f
C
1# Plugins & Themes
2
d8e9a42c
C
3<!-- START doctoc generated TOC please keep comment here to allow auto update -->
4<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
5
6
7- [Concepts](#concepts)
8 - [Hooks](#hooks)
9 - [Static files](#static-files)
10 - [CSS](#css)
11 - [Server helpers (only for plugins)](#server-helpers-only-for-plugins)
12 - [Settings](#settings)
13 - [Storage](#storage)
7545a094 14 - [Update video constants](#update-video-constants)
5e2b2e27 15 - [Add custom routes](#add-custom-routes)
7545a094
C
16 - [Client helpers (themes & plugins)](#client-helpers-themes--plugins)
17 - [Plugin static route](#plugin-static-route)
18 - [Translate](#translate)
19 - [Get public settings](#get-public-settings)
d8e9a42c
C
20 - [Publishing](#publishing)
21- [Write a plugin/theme](#write-a-plugintheme)
22 - [Clone the quickstart repository](#clone-the-quickstart-repository)
23 - [Configure your repository](#configure-your-repository)
24 - [Update README](#update-readme)
25 - [Update package.json](#update-packagejson)
26 - [Write code](#write-code)
7545a094 27 - [Add translations](#add-translations)
d8e9a42c
C
28 - [Test your plugin/theme](#test-your-plugintheme)
29 - [Publish](#publish)
7545a094 30- [Plugin & Theme hooks/helpers API](#plugin--theme-hookshelpers-api)
d8e9a42c
C
31- [Tips](#tips)
32 - [Compatibility with PeerTube](#compatibility-with-peertube)
33 - [Spam/moderation plugin](#spammoderation-plugin)
112be80e 34 - [Other plugin examples](#other-plugin-examples)
d8e9a42c
C
35
36<!-- END doctoc generated TOC please keep comment here to allow auto update -->
37
662e5d4f
C
38## Concepts
39
32d7f2b7 40Themes are exactly the same as plugins, except that:
662e5d4f
C
41 * Their name starts with `peertube-theme-` instead of `peertube-plugin-`
42 * They cannot declare server code (so they cannot register server hooks or settings)
43 * CSS files are loaded by client only if the theme is chosen by the administrator or the user
44
45### Hooks
46
47A plugin registers functions in JavaScript to execute when PeerTube (server and client) fires events. There are 3 types of hooks:
48 * `filter`: used to filter functions parameters or return values.
49 For example to replace words in video comments, or change the videos list behaviour
50 * `action`: used to do something after a certain trigger. For example to send a hook every time a video is published
51 * `static`: same than `action` but PeerTube waits their execution
662e5d4f
C
52
53On server side, these hooks are registered by the `library` file defined in `package.json`.
54
55```json
56{
57 ...,
58 "library": "./main.js",
59 ...,
60}
61```
62
7545a094
C
63And `main.js` defines a `register` function:
64
65Example:
66
67```js
68async function register ({
69 registerHook,
70 registerSetting,
71 settingsManager,
72 storageManager,
73 videoCategoryManager,
74 videoLicenceManager,
5e2b2e27
C
75 videoLanguageManager,
76 peertubeHelpers,
77 getRouter
7545a094
C
78}) {
79 registerHook({
80 target: 'action:application.listening',
81 handler: () => displayHelloWorld()
82 })
83}
84```
85
662e5d4f
C
86
87On client side, these hooks are registered by the `clientScripts` files defined in `package.json`.
88All client scripts have scopes so PeerTube client only loads scripts it needs:
89
90```json
91{
92 ...,
93 "clientScripts": [
94 {
95 "script": "client/common-client-plugin.js",
96 "scopes": [ "common" ]
97 },
98 {
99 "script": "client/video-watch-client-plugin.js",
100 "scopes": [ "video-watch" ]
101 }
102 ],
103 ...
104}
105```
106
7545a094
C
107And these scripts also define a `register` function:
108
109```js
110function register ({ registerHook, peertubeHelpers }) {
111 registerHook({
112 target: 'action:application.init',
113 handler: () => onApplicationInit(peertubeHelpers)
114 })
115}
116```
117
662e5d4f
C
118### Static files
119
120Plugins can declare static directories that PeerTube will serve (images for example)
121from `/plugins/{plugin-name}/{plugin-version}/static/`
122or `/themes/{theme-name}/{theme-version}/static/` routes.
123
124### CSS
125
126Plugins can declare CSS files that PeerTube will automatically inject in the client.
7545a094
C
127If you need to override existing style, you can use the `#custom-css` selector:
128
129```
130body#custom-css {
131 color: red;
132}
133
134#custom-css .header {
135 background-color: red;
136}
137```
662e5d4f 138
9fa6ca16 139### Server helpers (only for plugins)
662e5d4f
C
140
141#### Settings
142
143Plugins can register settings, that PeerTube will inject in the administration interface.
144
145Example:
146
147```js
148registerSetting({
149 name: 'admin-name',
150 label: 'Admin name',
151 type: 'input',
152 default: 'my super name'
153})
154
155const adminName = await settingsManager.getSetting('admin-name')
156```
157
d8e9a42c 158#### Storage
662e5d4f
C
159
160Plugins can store/load JSON data, that PeerTube will store in its database (so don't put files in there).
161
162Example:
163
164```js
165const value = await storageManager.getData('mykey')
9fa6ca16 166await storageManager.storeData('mykey', { subkey: 'value' })
662e5d4f
C
167```
168
7545a094
C
169#### Update video constants
170
171You can add/delete video categories, licences or languages using the appropriate managers:
172
173```js
174videoLanguageManager.addLanguage('al_bhed', 'Al Bhed')
175videoLanguageManager.deleteLanguage('fr')
176
177videoCategoryManager.addCategory(42, 'Best category')
178videoCategoryManager.deleteCategory(1) // Music
179
180videoLicenceManager.addLicence(42, 'Best licence')
181videoLicenceManager.deleteLicence(7) // Public domain
182```
183
5e2b2e27
C
184#### Add custom routes
185
186You can create custom routes using an [express Router](https://expressjs.com/en/4x/api.html#router) for your plugin:
187
188```js
189const router = getRouter()
190router.get('/ping', (req, res) => res.json({ message: 'pong' }))
191```
192
193The `ping` route can be accessed using:
194 * `/plugins/:pluginName/:pluginVersion/router/ping`
195 * Or `/plugins/:pluginName/router/ping`
196
197
7545a094
C
198### Client helpers (themes & plugins)
199
74c2dece 200#### Plugin static route
7545a094
C
201
202To get your plugin static route:
203
204```js
205const baseStaticUrl = peertubeHelpers.getBaseStaticRoute()
206const imageUrl = baseStaticUrl + '/images/chocobo.png'
207```
208
74c2dece
K
209#### Notifier
210
211To notify the user with the PeerTube ToastModule:
212
213```js
214const { notifier } = peertubeHelpers
215notifier.success('Success message content.')
216notifier.error('Error message content.')
217```
218
437e8e06
K
219#### Custom Modal
220
221To show a custom modal:
222
223```js
224 peertubeHelpers.showModal({
225 title: 'My custom modal title',
226 content: '<p>My custom modal content</p>',
227 // Optionals parameters :
228 // show close icon
229 close: true,
230 // show cancel button and call action() after hiding modal
231 cancel: { value: 'cancel', action: () => {} },
232 // show confirm button and call action() after hiding modal
233 confirm: { value: 'confirm', action: () => {} },
234 })
235```
236
7545a094
C
237#### Translate
238
239You can translate some strings of your plugin (PeerTube will use your `translations` object of your `package.json` file):
240
241```js
242peertubeHelpers.translate('User name')
243 .then(translation => console.log('Translated User name by ' + translation))
244```
245
246#### Get public settings
247
248To get your public plugin settings:
249
250```js
251peertubeHelpers.getSettings()
252 .then(s => {
253 if (!s || !s['site-id'] || !s['url']) {
254 console.error('Matomo settings are not set.')
255 return
256 }
257
258 // ...
259 })
260```
261
262
662e5d4f
C
263### Publishing
264
265PeerTube plugins and themes should be published on [NPM](https://www.npmjs.com/) so that PeerTube indexes
266take into account your plugin (after ~ 1 day). An official PeerTube index is available on https://packages.joinpeertube.org/ (it's just a REST API, so don't expect a beautiful website).
267
268## Write a plugin/theme
269
270Steps:
271 * Find a name for your plugin or your theme (must not have spaces, it can only contain lowercase letters and `-`)
272 * Add the appropriate prefix:
273 * If you develop a plugin, add `peertube-plugin-` prefix to your plugin name (for example: `peertube-plugin-mysupername`)
274 * If you develop a theme, add `peertube-theme-` prefix to your theme name (for example: `peertube-theme-mysupertheme`)
275 * Clone the quickstart repository
276 * Configure your repository
277 * Update `README.md`
278 * Update `package.json`
279 * Register hooks, add CSS and static files
280 * Test your plugin/theme with a local PeerTube installation
281 * Publish your plugin/theme on NPM
282
283### Clone the quickstart repository
284
285If you develop a plugin, clone the `peertube-plugin-quickstart` repository:
286
287```
288$ git clone https://framagit.org/framasoft/peertube/peertube-plugin-quickstart.git peertube-plugin-mysupername
289```
290
291If you develop a theme, clone the `peertube-theme-quickstart` repository:
292
293```
294$ git clone https://framagit.org/framasoft/peertube/peertube-theme-quickstart.git peertube-theme-mysupername
295```
296
297### Configure your repository
298
299Set your repository URL:
300
301```
302$ cd peertube-plugin-mysupername # or cd peertube-theme-mysupername
303$ git remote set-url origin https://your-git-repo
304```
305
306### Update README
307
308Update `README.md` file:
309
310```
311$ $EDITOR README.md
312```
313
314### Update package.json
315
316Update the `package.json` fields:
317 * `name` (should start with `peertube-plugin-` or `peertube-theme-`)
318 * `description`
319 * `homepage`
320 * `author`
321 * `bugs`
322 * `engine.peertube` (the PeerTube version compatibility, must be `>=x.y.z` and nothing else)
323
324**Caution:** Don't update or remove other keys, or PeerTube will not be able to index/install your plugin.
325If you don't need static directories, use an empty `object`:
326
327```json
328{
329 ...,
330 "staticDirs": {},
331 ...
332}
333```
334
9fa6ca16 335And if you don't need CSS or client script files, use an empty `array`:
662e5d4f
C
336
337```json
338{
339 ...,
340 "css": [],
9fa6ca16 341 "clientScripts": [],
662e5d4f
C
342 ...
343}
344```
345
346### Write code
347
348Now you can register hooks or settings, write CSS and add static directories to your plugin or your theme :)
349
350**Caution:** It's up to you to check the code you write will be compatible with the PeerTube NodeJS version,
351and will be supported by web browsers.
352If you want to write modern JavaScript, please use a transpiler like [Babel](https://babeljs.io/).
353
7545a094
C
354### Add translations
355
356If you want to translate strings of your plugin (like labels of your registered settings), create a file and add it to `package.json`:
357
358```json
359{
360 ...,
361 "translations": {
362 "fr-FR": "./languages/fr.json",
363 "pt-BR": "./languages/pt-BR.json"
364 },
365 ...
366}
367```
368
369The key should be one of the locales defined in [i18n.ts](https://github.com/Chocobozzz/PeerTube/blob/develop/shared/models/i18n/i18n.ts).
370You **must** use the complete locales (`fr-FR` instead of `fr`).
371
112be80e
C
372Translation files are just objects, with the english sentence as the key and the translation as the value.
373`fr.json` could contain for example:
374
375```json
376{
377 "Hello world": "Hello le monde"
378}
379```
380
662e5d4f
C
381### Test your plugin/theme
382
383You'll need to have a local PeerTube instance:
384 * Follow the [dev prerequisites](https://github.com/Chocobozzz/PeerTube/blob/develop/.github/CONTRIBUTING.md#prerequisites)
385 (to clone the repository, install dependencies and prepare the database)
386 * Build PeerTube (`--light` to only build the english language):
387
388```
389$ npm run build -- --light
9fa6ca16
C
390```
391
392 * Build the CLI:
393
394```
395$ npm run setup:cli
662e5d4f
C
396```
397
9fa6ca16 398 * Run PeerTube (you can access to your instance on http://localhost:9000):
662e5d4f
C
399
400```
401$ NODE_ENV=test npm start
402```
403
404 * Register the instance via the CLI:
405
406```
407$ node ./dist/server/tools/peertube.js auth add -u 'http://localhost:9000' -U 'root' --password 'test'
408```
409
410Then, you can install or reinstall your local plugin/theme by running:
411
412```
413$ node ./dist/server/tools/peertube.js plugins install --path /your/absolute/plugin-or-theme/path
414```
415
416### Publish
417
418Go in your plugin/theme directory, and run:
419
420```
421$ npm publish
422```
423
424Every time you want to publish another version of your plugin/theme, just update the `version` key from the `package.json`
425and republish it on NPM. Remember that the PeerTube index will take into account your new plugin/theme version after ~24 hours.
426
d8e9a42c 427
bfa1a32b
C
428## Plugin & Theme hooks/helpers API
429
195474f9 430See the dedicated documentation: https://docs.joinpeertube.org/#/api-plugins
bfa1a32b
C
431
432
d8e9a42c
C
433## Tips
434
435### Compatibility with PeerTube
436
437Unfortunately, we don't have enough resources to provide hook compatibility between minor releases of PeerTube (for example between `1.2.x` and `1.3.x`).
438So please:
439 * Don't make assumptions and check every parameter you want to use. For example:
440
441```js
442registerHook({
443 target: 'filter:api.video.get.result',
444 handler: video => {
445 // We check the parameter exists and the name field exists too, to avoid exceptions
446 if (video && video.name) video.name += ' <3'
447
448 return video
449 }
450})
451```
51326912 452 * Don't try to require parent PeerTube modules, only use `peertubeHelpers`. If you need another helper or a specific hook, please [create an issue](https://github.com/Chocobozzz/PeerTube/issues/new)
d8e9a42c
C
453 * Don't use PeerTube dependencies. Use your own :)
454
51326912 455If your plugin is broken with a new PeerTube release, update your code and the `peertubeEngine` field of your `package.json` field.
d8e9a42c
C
456This way, older PeerTube versions will still use your old plugin, and new PeerTube versions will use your updated plugin.
457
458### Spam/moderation plugin
459
460If you want to create an antispam/moderation plugin, you could use the following hooks:
461 * `filter:api.video.upload.accept.result`: to accept or not local uploads
462 * `filter:api.video-thread.create.accept.result`: to accept or not local thread
463 * `filter:api.video-comment-reply.create.accept.result`: to accept or not local replies
464 * `filter:api.video-threads.list.result`: to change/hide the text of threads
465 * `filter:api.video-thread-comments.list.result`: to change/hide the text of replies
466 * `filter:video.auto-blacklist.result`: to automatically blacklist local or remote videos
467
112be80e
C
468### Other plugin examples
469
470You can take a look to "official" PeerTube plugins if you want to take inspiration from them: https://framagit.org/framasoft/peertube/official-plugins