]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - support/doc/plugins/guide.md
Fix plugin api guide transcoding section
[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 - [Add external auth methods](#add-external-auth-methods)
17 - [Add new transcoding profiles](#add-new-transcoding-profiles)
18 - [Client helpers (themes & plugins)](#client-helpers-themes--plugins)
19 - [Plugin static route](#plugin-static-route)
20 - [Notifier](#notifier)
21 - [Markdown Renderer](#markdown-renderer)
22 - [Custom Modal](#custom-modal)
23 - [Translate](#translate)
24 - [Get public settings](#get-public-settings)
25 - [Add custom fields to video form](#add-custom-fields-to-video-form)
26 - [Publishing](#publishing)
27 - [Write a plugin/theme](#write-a-plugintheme)
28 - [Clone the quickstart repository](#clone-the-quickstart-repository)
29 - [Configure your repository](#configure-your-repository)
30 - [Update README](#update-readme)
31 - [Update package.json](#update-packagejson)
32 - [Write code](#write-code)
33 - [Add translations](#add-translations)
34 - [Build your plugin](#build-your-plugin)
35 - [Test your plugin/theme](#test-your-plugintheme)
36 - [Publish](#publish)
37 - [Plugin & Theme hooks/helpers API](#plugin--theme-hookshelpers-api)
38 - [Tips](#tips)
39 - [Compatibility with PeerTube](#compatibility-with-peertube)
40 - [Spam/moderation plugin](#spammoderation-plugin)
41 - [Other plugin examples](#other-plugin-examples)
42
43 <!-- END doctoc generated TOC please keep comment here to allow auto update -->
44
45 ## Concepts
46
47 Themes are exactly the same as plugins, except that:
48 * Their name starts with `peertube-theme-` instead of `peertube-plugin-`
49 * They cannot declare server code (so they cannot register server hooks or settings)
50 * CSS files are loaded by client only if the theme is chosen by the administrator or the user
51
52 ### Hooks
53
54 A plugin registers functions in JavaScript to execute when PeerTube (server and client) fires events. There are 3 types of hooks:
55 * `filter`: used to filter functions parameters or return values.
56 For example to replace words in video comments, or change the videos list behaviour
57 * `action`: used to do something after a certain trigger. For example to send a hook every time a video is published
58 * `static`: same than `action` but PeerTube waits their execution
59
60 On server side, these hooks are registered by the `library` file defined in `package.json`.
61
62 ```json
63 {
64 ...,
65 "library": "./main.js",
66 ...,
67 }
68 ```
69
70 And `main.js` defines a `register` function:
71
72 Example:
73
74 ```js
75 async function register ({
76 registerHook,
77
78 registerSetting,
79 settingsManager,
80
81 storageManager,
82
83 videoCategoryManager,
84 videoLicenceManager,
85 videoLanguageManager,
86
87 peertubeHelpers,
88
89 getRouter,
90
91 registerExternalAuth,
92 unregisterExternalAuth,
93 registerIdAndPassAuth,
94 unregisterIdAndPassAuth
95 }) {
96 registerHook({
97 target: 'action:application.listening',
98 handler: () => displayHelloWorld()
99 })
100 }
101 ```
102
103
104 On client side, these hooks are registered by the `clientScripts` files defined in `package.json`.
105 All client scripts have scopes so PeerTube client only loads scripts it needs:
106
107 ```json
108 {
109 ...,
110 "clientScripts": [
111 {
112 "script": "client/common-client-plugin.js",
113 "scopes": [ "common" ]
114 },
115 {
116 "script": "client/video-watch-client-plugin.js",
117 "scopes": [ "video-watch" ]
118 }
119 ],
120 ...
121 }
122 ```
123
124 And these scripts also define a `register` function:
125
126 ```js
127 function register ({ registerHook, peertubeHelpers }) {
128 registerHook({
129 target: 'action:application.init',
130 handler: () => onApplicationInit(peertubeHelpers)
131 })
132 }
133 ```
134
135 ### Static files
136
137 Plugins can declare static directories that PeerTube will serve (images for example)
138 from `/plugins/{plugin-name}/{plugin-version}/static/`
139 or `/themes/{theme-name}/{theme-version}/static/` routes.
140
141 ### CSS
142
143 Plugins can declare CSS files that PeerTube will automatically inject in the client.
144 If you need to override existing style, you can use the `#custom-css` selector:
145
146 ```
147 body#custom-css {
148 color: red;
149 }
150
151 #custom-css .header {
152 background-color: red;
153 }
154 ```
155
156 ### Server helpers (only for plugins)
157
158 #### Settings
159
160 Plugins can register settings, that PeerTube will inject in the administration interface.
161
162 Example:
163
164 ```js
165 registerSetting({
166 name: 'admin-name',
167 label: 'Admin name',
168 type: 'input',
169 // type: input | input-checkbox | input-password | input-textarea | markdown-text | markdown-enhanced
170 default: 'my super name'
171 })
172
173 const adminName = await settingsManager.getSetting('admin-name')
174
175 const result = await settingsManager.getSettings([ 'admin-name', 'admin-password' ])
176 result['admin-name]
177
178 settingsManager.onSettingsChange(settings => {
179 settings['admin-name])
180 })
181 ```
182
183 #### Storage
184
185 Plugins can store/load JSON data, that PeerTube will store in its database (so don't put files in there).
186
187 Example:
188
189 ```js
190 const value = await storageManager.getData('mykey')
191 await storageManager.storeData('mykey', { subkey: 'value' })
192 ```
193
194 #### Update video constants
195
196 You can add/delete video categories, licences or languages using the appropriate managers:
197
198 ```js
199 videoLanguageManager.addLanguage('al_bhed', 'Al Bhed')
200 videoLanguageManager.deleteLanguage('fr')
201
202 videoCategoryManager.addCategory(42, 'Best category')
203 videoCategoryManager.deleteCategory(1) // Music
204
205 videoLicenceManager.addLicence(42, 'Best licence')
206 videoLicenceManager.deleteLicence(7) // Public domain
207
208 videoPrivacyManager.deletePrivacy(2) // Remove Unlisted video privacy
209 playlistPrivacyManager.deletePlaylistPrivacy(3) // Remove Private video playlist privacy
210 ```
211
212 #### Add custom routes
213
214 You can create custom routes using an [express Router](https://expressjs.com/en/4x/api.html#router) for your plugin:
215
216 ```js
217 const router = getRouter()
218 router.get('/ping', (req, res) => res.json({ message: 'pong' }))
219 ```
220
221 The `ping` route can be accessed using:
222 * `/plugins/:pluginName/:pluginVersion/router/ping`
223 * Or `/plugins/:pluginName/router/ping`
224
225
226 #### Add external auth methods
227
228 If you want to add a classic username/email and password auth method (like [LDAP](https://framagit.org/framasoft/peertube/official-plugins/-/tree/master/peertube-plugin-auth-ldap) for example):
229
230 ```js
231 registerIdAndPassAuth({
232 authName: 'my-auth-method',
233
234 // PeerTube will try all id and pass plugins in the weight DESC order
235 // Exposing this value in the plugin settings could be interesting
236 getWeight: () => 60,
237
238 // Optional function called by PeerTube when the user clicked on the logout button
239 onLogout: user => {
240 console.log('User %s logged out.', user.username')
241 },
242
243 // Optional function called by PeerTube when the access token or refresh token are generated/refreshed
244 hookTokenValidity: ({ token, type }) => {
245 if (type === 'access') return { valid: true }
246 if (type === 'refresh') return { valid: false }
247 },
248
249 // Used by PeerTube when the user tries to authenticate
250 login: ({ id, password }) => {
251 if (id === 'user' && password === 'super password') {
252 return {
253 username: 'user'
254 email: 'user@example.com'
255 role: 2
256 displayName: 'User display name'
257 }
258 }
259
260 // Auth failed
261 return null
262 }
263 })
264
265 // Unregister this auth method
266 unregisterIdAndPassAuth('my-auth-method')
267 ```
268
269 You can also add an external auth method (like [OpenID](https://framagit.org/framasoft/peertube/official-plugins/-/tree/master/peertube-plugin-auth-openid-connect), [SAML2](https://framagit.org/framasoft/peertube/official-plugins/-/tree/master/peertube-plugin-auth-saml2) etc):
270
271 ```js
272 // result contains the userAuthenticated auth method you can call to authenticate a user
273 const result = registerExternalAuth({
274 authName: 'my-auth-method',
275
276 // Will be displayed in a button next to the login form
277 authDisplayName: () => 'Auth method'
278
279 // If the user click on the auth button, PeerTube will forward the request in this function
280 onAuthRequest: (req, res) => {
281 res.redirect('https://external-auth.example.com/auth')
282 },
283
284 // Same than registerIdAndPassAuth option
285 // onLogout: ...
286
287 // Same than registerIdAndPassAuth option
288 // hookTokenValidity: ...
289 })
290
291 router.use('/external-auth-callback', (req, res) => {
292 // Forward the request to PeerTube
293 result.userAuthenticated({
294 req,
295 res,
296 username: 'user'
297 email: 'user@example.com'
298 role: 2
299 displayName: 'User display name'
300 })
301 })
302
303 // Unregister this external auth method
304 unregisterExternalAuth('my-auth-method)
305 ```
306
307 #### Add new transcoding profiles
308
309 Adding transcoding profiles allow admins to change ffmpeg encoding parameters and/or encoders.
310 A transcoding profile has to be chosen by the admin of the instance using the admin configuration.
311
312 ```js
313 async function register ({
314 transcodingManager
315 }) {
316
317 // Adapt bitrate when using libx264 encoder
318 {
319 const builder = (options) => {
320 const { input, resolution, fps, streamNum } = options
321
322 const streamString = streamNum ? ':' + streamNum : ''
323
324 // You can also return a promise
325 return {
326 outputOptions: [
327 // Use a custom bitrate
328 '-b' + streamString + ' 10K'
329 ]
330 }
331 }
332
333 const encoder = 'libx264'
334 const profileName = 'low-quality'
335
336 // Support this profile for VOD transcoding
337 transcodingManager.addVODProfile(encoder, profileName, builder)
338
339 // And/Or support this profile for live transcoding
340 transcodingManager.addLiveProfile(encoder, profileName, builder)
341 }
342
343 {
344 const builder = (options) => {
345 const { streamNum } = options
346
347 const streamString = streamNum ? ':' + streamNum : ''
348
349 // Always copy stream when PeerTube use libfdk_aac or aac encoders
350 return {
351 copy: true
352 }
353 }
354
355 const profileName = 'copy-audio'
356
357 for (const encoder of [ 'libfdk_aac', 'aac' ]) {
358 transcodingManager.addVODProfile(encoder, profileName, builder)
359 }
360 }
361 ```
362
363 PeerTube will try different encoders depending on their priority.
364 If the encoder is not available in the current transcoding profile or in ffmpeg, it tries the next one.
365 Plugins can change the order of these encoders and add their custom encoders:
366
367 ```js
368 async function register ({
369 transcodingManager
370 }) {
371
372 // Adapt bitrate when using libx264 encoder
373 {
374 const builder = () => {
375 return {
376 outputOptions: []
377 }
378 }
379
380 // Support libopus and libvpx-vp9 encoders (these codecs could be incompatible with the player)
381 transcodingManager.addVODProfile('libopus', 'test-vod-profile', builder)
382
383 // Default priorities are ~100
384 // Lowest priority = 1
385 transcodingManager.addVODEncoderPriority('audio', 'libopus', 1000)
386
387 transcodingManager.addVODProfile('libvpx-vp9', 'test-vod-profile', builder)
388 transcodingManager.addVODEncoderPriority('video', 'libvpx-vp9', 1000)
389
390 transcodingManager.addLiveProfile('libopus', 'test-live-profile', builder)
391 transcodingManager.addLiveEncoderPriority('audio', 'libopus', 1000)
392 }
393 ```
394
395 ### Client helpers (themes & plugins)
396
397 #### Plugin static route
398
399 To get your plugin static route:
400
401 ```js
402 const baseStaticUrl = peertubeHelpers.getBaseStaticRoute()
403 const imageUrl = baseStaticUrl + '/images/chocobo.png'
404 ```
405
406 #### Notifier
407
408 To notify the user with the PeerTube ToastModule:
409
410 ```js
411 const { notifier } = peertubeHelpers
412 notifier.success('Success message content.')
413 notifier.error('Error message content.')
414 ```
415
416 #### Markdown Renderer
417
418 To render a formatted markdown text to HTML:
419
420 ```js
421 const { markdownRenderer } = peertubeHelpers
422
423 await markdownRenderer.textMarkdownToHTML('**My Bold Text**')
424 // return <strong>My Bold Text</strong>
425
426 await markdownRenderer.enhancedMarkdownToHTML('![alt-img](http://.../my-image.jpg)')
427 // return <img alt=alt-img src=http://.../my-image.jpg />
428 ```
429
430 #### Custom Modal
431
432 To show a custom modal:
433
434 ```js
435 peertubeHelpers.showModal({
436 title: 'My custom modal title',
437 content: '<p>My custom modal content</p>',
438 // Optionals parameters :
439 // show close icon
440 close: true,
441 // show cancel button and call action() after hiding modal
442 cancel: { value: 'cancel', action: () => {} },
443 // show confirm button and call action() after hiding modal
444 confirm: { value: 'confirm', action: () => {} },
445 })
446 ```
447
448 #### Translate
449
450 You can translate some strings of your plugin (PeerTube will use your `translations` object of your `package.json` file):
451
452 ```js
453 peertubeHelpers.translate('User name')
454 .then(translation => console.log('Translated User name by ' + translation))
455 ```
456
457 #### Get public settings
458
459 To get your public plugin settings:
460
461 ```js
462 peertubeHelpers.getSettings()
463 .then(s => {
464 if (!s || !s['site-id'] || !s['url']) {
465 console.error('Matomo settings are not set.')
466 return
467 }
468
469 // ...
470 })
471 ```
472
473 #### Add custom fields to video form
474
475 To add custom fields in the video form (in *Plugin settings* tab):
476
477 ```js
478 async function register ({ registerVideoField, peertubeHelpers }) {
479 const descriptionHTML = await peertubeHelpers.translate(descriptionSource)
480 const commonOptions = {
481 name: 'my-field-name,
482 label: 'My added field',
483 descriptionHTML: 'Optional description',
484 type: 'input-textarea',
485 default: ''
486 }
487
488 for (const type of [ 'upload', 'import-url', 'import-torrent', 'update' ]) {
489 registerVideoField(commonOptions, { type })
490 }
491 }
492 ```
493
494 PeerTube will send this field value in `body.pluginData['my-field-name']` and fetch it from `video.pluginData['my-field-name']`.
495
496 So for example, if you want to store an additional metadata for videos, register the following hooks in **server**:
497
498 ```js
499 async function register ({
500 registerHook,
501 storageManager
502 }) {
503 const fieldName = 'my-field-name'
504
505 // Store data associated to this video
506 registerHook({
507 target: 'action:api.video.updated',
508 handler: ({ video, body }) => {
509 if (!body.pluginData) return
510
511 const value = body.pluginData[fieldName]
512 if (!value) return
513
514 storageManager.storeData(fieldName + '-' + video.id, value)
515 }
516 })
517
518 // Add your custom value to the video, so the client autofill your field using the previously stored value
519 registerHook({
520 target: 'filter:api.video.get.result',
521 handler: async (video) => {
522 if (!video) return video
523 if (!video.pluginData) video.pluginData = {}
524
525 const result = await storageManager.getData(fieldName + '-' + video.id)
526 video.pluginData[fieldName] = result
527
528 return video
529 }
530 })
531 }
532 ```
533 ### Publishing
534
535 PeerTube plugins and themes should be published on [NPM](https://www.npmjs.com/) so that PeerTube indexes
536 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).
537
538 ## Write a plugin/theme
539
540 Steps:
541 * Find a name for your plugin or your theme (must not have spaces, it can only contain lowercase letters and `-`)
542 * Add the appropriate prefix:
543 * If you develop a plugin, add `peertube-plugin-` prefix to your plugin name (for example: `peertube-plugin-mysupername`)
544 * If you develop a theme, add `peertube-theme-` prefix to your theme name (for example: `peertube-theme-mysupertheme`)
545 * Clone the quickstart repository
546 * Configure your repository
547 * Update `README.md`
548 * Update `package.json`
549 * Register hooks, add CSS and static files
550 * Test your plugin/theme with a local PeerTube installation
551 * Publish your plugin/theme on NPM
552
553 ### Clone the quickstart repository
554
555 If you develop a plugin, clone the `peertube-plugin-quickstart` repository:
556
557 ```
558 $ git clone https://framagit.org/framasoft/peertube/peertube-plugin-quickstart.git peertube-plugin-mysupername
559 ```
560
561 If you develop a theme, clone the `peertube-theme-quickstart` repository:
562
563 ```
564 $ git clone https://framagit.org/framasoft/peertube/peertube-theme-quickstart.git peertube-theme-mysupername
565 ```
566
567 ### Configure your repository
568
569 Set your repository URL:
570
571 ```
572 $ cd peertube-plugin-mysupername # or cd peertube-theme-mysupername
573 $ git remote set-url origin https://your-git-repo
574 ```
575
576 ### Update README
577
578 Update `README.md` file:
579
580 ```
581 $ $EDITOR README.md
582 ```
583
584 ### Update package.json
585
586 Update the `package.json` fields:
587 * `name` (should start with `peertube-plugin-` or `peertube-theme-`)
588 * `description`
589 * `homepage`
590 * `author`
591 * `bugs`
592 * `engine.peertube` (the PeerTube version compatibility, must be `>=x.y.z` and nothing else)
593
594 **Caution:** Don't update or remove other keys, or PeerTube will not be able to index/install your plugin.
595 If you don't need static directories, use an empty `object`:
596
597 ```json
598 {
599 ...,
600 "staticDirs": {},
601 ...
602 }
603 ```
604
605 And if you don't need CSS or client script files, use an empty `array`:
606
607 ```json
608 {
609 ...,
610 "css": [],
611 "clientScripts": [],
612 ...
613 }
614 ```
615
616 ### Write code
617
618 Now you can register hooks or settings, write CSS and add static directories to your plugin or your theme :)
619
620 **Caution:** It's up to you to check the code you write will be compatible with the PeerTube NodeJS version,
621 and will be supported by web browsers.
622 If you want to write modern JavaScript, please use a transpiler like [Babel](https://babeljs.io/).
623
624 ### Add translations
625
626 If you want to translate strings of your plugin (like labels of your registered settings), create a file and add it to `package.json`:
627
628 ```json
629 {
630 ...,
631 "translations": {
632 "fr-FR": "./languages/fr.json",
633 "pt-BR": "./languages/pt-BR.json"
634 },
635 ...
636 }
637 ```
638
639 The key should be one of the locales defined in [i18n.ts](https://github.com/Chocobozzz/PeerTube/blob/develop/shared/models/i18n/i18n.ts).
640 You **must** use the complete locales (`fr-FR` instead of `fr`).
641
642 Translation files are just objects, with the english sentence as the key and the translation as the value.
643 `fr.json` could contain for example:
644
645 ```json
646 {
647 "Hello world": "Hello le monde"
648 }
649 ```
650
651 ### Build your plugin
652
653 If you added client scripts, you'll need to build them using webpack.
654
655 Install webpack:
656
657 ```
658 $ npm install
659 ```
660
661 Add/update your files in the `clientFiles` array of `webpack.config.js`:
662
663 ```
664 $ $EDITOR ./webpack.config.js
665 ```
666
667 Build your client files:
668
669 ```
670 $ npm run build
671 ```
672
673 You built files are in the `dist/` directory. Check `package.json` to correctly point to them.
674
675
676 ### Test your plugin/theme
677
678 You'll need to have a local PeerTube instance:
679 * Follow the [dev prerequisites](https://github.com/Chocobozzz/PeerTube/blob/develop/.github/CONTRIBUTING.md#prerequisites)
680 (to clone the repository, install dependencies and prepare the database)
681 * Build PeerTube (`--light` to only build the english language):
682
683 ```
684 $ npm run build -- --light
685 ```
686
687 * Build the CLI:
688
689 ```
690 $ npm run setup:cli
691 ```
692
693 * Run PeerTube (you can access to your instance on http://localhost:9000):
694
695 ```
696 $ NODE_ENV=test npm start
697 ```
698
699 * Register the instance via the CLI:
700
701 ```
702 $ node ./dist/server/tools/peertube.js auth add -u 'http://localhost:9000' -U 'root' --password 'test'
703 ```
704
705 Then, you can install or reinstall your local plugin/theme by running:
706
707 ```
708 $ node ./dist/server/tools/peertube.js plugins install --path /your/absolute/plugin-or-theme/path
709 ```
710
711 ### Publish
712
713 Go in your plugin/theme directory, and run:
714
715 ```
716 $ npm publish
717 ```
718
719 Every time you want to publish another version of your plugin/theme, just update the `version` key from the `package.json`
720 and republish it on NPM. Remember that the PeerTube index will take into account your new plugin/theme version after ~24 hours.
721
722
723 ## Plugin & Theme hooks/helpers API
724
725 See the dedicated documentation: https://docs.joinpeertube.org/api-plugins
726
727
728 ## Tips
729
730 ### Compatibility with PeerTube
731
732 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`).
733 So please:
734 * Don't make assumptions and check every parameter you want to use. For example:
735
736 ```js
737 registerHook({
738 target: 'filter:api.video.get.result',
739 handler: video => {
740 // We check the parameter exists and the name field exists too, to avoid exceptions
741 if (video && video.name) video.name += ' <3'
742
743 return video
744 }
745 })
746 ```
747 * 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/choose)
748 * Don't use PeerTube dependencies. Use your own :)
749
750 If your plugin is broken with a new PeerTube release, update your code and the `peertubeEngine` field of your `package.json` field.
751 This way, older PeerTube versions will still use your old plugin, and new PeerTube versions will use your updated plugin.
752
753 ### Spam/moderation plugin
754
755 If you want to create an antispam/moderation plugin, you could use the following hooks:
756 * `filter:api.video.upload.accept.result`: to accept or not local uploads
757 * `filter:api.video-thread.create.accept.result`: to accept or not local thread
758 * `filter:api.video-comment-reply.create.accept.result`: to accept or not local replies
759 * `filter:api.video-threads.list.result`: to change/hide the text of threads
760 * `filter:api.video-thread-comments.list.result`: to change/hide the text of replies
761 * `filter:video.auto-blacklist.result`: to automatically blacklist local or remote videos
762
763 ### Other plugin examples
764
765 You can take a look to "official" PeerTube plugins if you want to take inspiration from them: https://framagit.org/framasoft/peertube/official-plugins