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