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