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