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