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