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