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 -->
7 - [Concepts](#concepts)
9 - [Static files](#static-files)
11 - [Server helpers (only for plugins)](#server-helpers-only-for-plugins)
12 - [Settings](#settings)
14 - [Update video constants](#update-video-constants)
15 - [Add custom routes](#add-custom-routes)
16 - [Add external auth methods](#add-external-auth-methods)
17 - [Add new transcoding profiles](#add-new-transcoding-profiles)
18 - [Client helpers (themes & plugins)](#client-helpers-themes--plugins)
19 - [Plugin static route](#plugin-static-route)
20 - [Notifier](#notifier)
21 - [Markdown Renderer](#markdown-renderer)
22 - [Custom Modal](#custom-modal)
23 - [Translate](#translate)
24 - [Get public settings](#get-public-settings)
25 - [Get server config](#get-server-config)
26 - [Add custom fields to video form](#add-custom-fields-to-video-form)
27 - [Publishing](#publishing)
28 - [Write a plugin/theme](#write-a-plugintheme)
29 - [Clone the quickstart repository](#clone-the-quickstart-repository)
30 - [Configure your repository](#configure-your-repository)
31 - [Update README](#update-readme)
32 - [Update package.json](#update-packagejson)
33 - [Write code](#write-code)
34 - [Add translations](#add-translations)
35 - [Build your plugin](#build-your-plugin)
36 - [Test your plugin/theme](#test-your-plugintheme)
38 - [Plugin & Theme hooks/helpers API](#plugin--theme-hookshelpers-api)
40 - [Compatibility with PeerTube](#compatibility-with-peertube)
41 - [Spam/moderation plugin](#spammoderation-plugin)
42 - [Other plugin examples](#other-plugin-examples)
44 <!-- END doctoc generated TOC please keep comment here to allow auto update -->
48 Themes are exactly the same as plugins, except that:
49 * Their name starts with `peertube-theme-` instead of `peertube-plugin-`
50 * They cannot declare server code (so they cannot register server hooks or settings)
51 * CSS files are loaded by client only if the theme is chosen by the administrator or the user
55 A plugin registers functions in JavaScript to execute when PeerTube (server and client) fires events. There are 3 types of hooks:
56 * `filter`: used to filter functions parameters or return values.
57 For example to replace words in video comments, or change the videos list behaviour
58 * `action`: used to do something after a certain trigger. For example to send a hook every time a video is published
59 * `static`: same than `action` but PeerTube waits their execution
61 On server side, these hooks are registered by the `library` file defined in `package.json`.
66 "library": "./main.js",
71 And `main.js` defines a `register` function:
76 async function register ({
93 unregisterExternalAuth,
94 registerIdAndPassAuth,
95 unregisterIdAndPassAuth
98 target: 'action:application.listening',
99 handler: () => displayHelloWorld()
105 On client side, these hooks are registered by the `clientScripts` files defined in `package.json`.
106 All client scripts have scopes so PeerTube client only loads scripts it needs:
113 "script": "client/common-client-plugin.js",
114 "scopes": [ "common" ]
117 "script": "client/video-watch-client-plugin.js",
118 "scopes": [ "video-watch" ]
125 And these scripts also define a `register` function:
128 function register ({ registerHook, peertubeHelpers }) {
130 target: 'action:application.init',
131 handler: () => onApplicationInit(peertubeHelpers)
138 Plugins can declare static directories that PeerTube will serve (images for example)
139 from `/plugins/{plugin-name}/{plugin-version}/static/`
140 or `/themes/{theme-name}/{theme-version}/static/` routes.
144 Plugins can declare CSS files that PeerTube will automatically inject in the client.
145 If you need to override existing style, you can use the `#custom-css` selector:
152 #custom-css .header {
153 background-color: red;
157 ### Server helpers (only for plugins)
161 Plugins can register settings, that PeerTube will inject in the administration interface.
170 // type: input | input-checkbox | input-password | input-textarea | markdown-text | markdown-enhanced
171 default: 'my super name'
174 const adminName = await settingsManager.getSetting('admin-name')
176 const result = await settingsManager.getSettings([ 'admin-name', 'admin-password' ])
179 settingsManager.onSettingsChange(settings => {
180 settings['admin-name])
186 Plugins can store/load JSON data, that PeerTube will store in its database (so don't put files in there).
191 const value = await storageManager.getData('mykey')
192 await storageManager.storeData('mykey', { subkey: 'value' })
195 #### Update video constants
197 You can add/delete video categories, licences or languages using the appropriate managers:
200 videoLanguageManager.addLanguage('al_bhed', 'Al Bhed')
201 videoLanguageManager.deleteLanguage('fr')
203 videoCategoryManager.addCategory(42, 'Best category')
204 videoCategoryManager.deleteCategory(1) // Music
206 videoLicenceManager.addLicence(42, 'Best licence')
207 videoLicenceManager.deleteLicence(7) // Public domain
209 videoPrivacyManager.deletePrivacy(2) // Remove Unlisted video privacy
210 playlistPrivacyManager.deletePlaylistPrivacy(3) // Remove Private video playlist privacy
213 #### Add custom routes
215 You can create custom routes using an [express Router](https://expressjs.com/en/4x/api.html#router) for your plugin:
218 const router = getRouter()
219 router.get('/ping', (req, res) => res.json({ message: 'pong' }))
222 The `ping` route can be accessed using:
223 * `/plugins/:pluginName/:pluginVersion/router/ping`
224 * Or `/plugins/:pluginName/router/ping`
227 #### Add external auth methods
229 If you want to add a classic username/email and password auth method (like [LDAP](https://framagit.org/framasoft/peertube/official-plugins/-/tree/master/peertube-plugin-auth-ldap) for example):
232 registerIdAndPassAuth({
233 authName: 'my-auth-method',
235 // PeerTube will try all id and pass plugins in the weight DESC order
236 // Exposing this value in the plugin settings could be interesting
239 // Optional function called by PeerTube when the user clicked on the logout button
241 console.log('User %s logged out.', user.username')
244 // Optional function called by PeerTube when the access token or refresh token are generated/refreshed
245 hookTokenValidity: ({ token, type }) => {
246 if (type === 'access') return { valid: true }
247 if (type === 'refresh') return { valid: false }
250 // Used by PeerTube when the user tries to authenticate
251 login: ({ id, password }) => {
252 if (id === 'user' && password === 'super password') {
255 email: 'user@example.com'
257 displayName: 'User display name'
266 // Unregister this auth method
267 unregisterIdAndPassAuth('my-auth-method')
270 You can also add an external auth method (like [OpenID](https://framagit.org/framasoft/peertube/official-plugins/-/tree/master/peertube-plugin-auth-openid-connect), [SAML2](https://framagit.org/framasoft/peertube/official-plugins/-/tree/master/peertube-plugin-auth-saml2) etc):
273 // result contains the userAuthenticated auth method you can call to authenticate a user
274 const result = registerExternalAuth({
275 authName: 'my-auth-method',
277 // Will be displayed in a button next to the login form
278 authDisplayName: () => 'Auth method'
280 // If the user click on the auth button, PeerTube will forward the request in this function
281 onAuthRequest: (req, res) => {
282 res.redirect('https://external-auth.example.com/auth')
285 // Same than registerIdAndPassAuth option
288 // Same than registerIdAndPassAuth option
289 // hookTokenValidity: ...
292 router.use('/external-auth-callback', (req, res) => {
293 // Forward the request to PeerTube
294 result.userAuthenticated({
298 email: 'user@example.com'
300 displayName: 'User display name'
304 // Unregister this external auth method
305 unregisterExternalAuth('my-auth-method)
308 #### Add new transcoding profiles
310 Adding transcoding profiles allow admins to change ffmpeg encoding parameters and/or encoders.
311 A transcoding profile has to be chosen by the admin of the instance using the admin configuration.
314 async function register ({
318 // Adapt bitrate when using libx264 encoder
320 const builder = (options) => {
321 const { input, resolution, fps, streamNum } = options
323 const streamString = streamNum ? ':' + streamNum : ''
325 // You can also return a promise
328 // Use a custom bitrate
329 '-b' + streamString + ' 10K'
334 const encoder = 'libx264'
335 const profileName = 'low-quality'
337 // Support this profile for VOD transcoding
338 transcodingManager.addVODProfile(encoder, profileName, builder)
340 // And/Or support this profile for live transcoding
341 transcodingManager.addLiveProfile(encoder, profileName, builder)
345 const builder = (options) => {
346 const { streamNum } = options
348 const streamString = streamNum ? ':' + streamNum : ''
350 // Always copy stream when PeerTube use libfdk_aac or aac encoders
356 const profileName = 'copy-audio'
358 for (const encoder of [ 'libfdk_aac', 'aac' ]) {
359 transcodingManager.addVODProfile(encoder, profileName, builder)
364 PeerTube will try different encoders depending on their priority.
365 If the encoder is not available in the current transcoding profile or in ffmpeg, it tries the next one.
366 Plugins can change the order of these encoders and add their custom encoders:
369 async function register ({
373 // Adapt bitrate when using libx264 encoder
375 const builder = () => {
381 // Support libopus and libvpx-vp9 encoders (these codecs could be incompatible with the player)
382 transcodingManager.addVODProfile('libopus', 'test-vod-profile', builder)
384 // Default priorities are ~100
385 // Lowest priority = 1
386 transcodingManager.addVODEncoderPriority('audio', 'libopus', 1000)
388 transcodingManager.addVODProfile('libvpx-vp9', 'test-vod-profile', builder)
389 transcodingManager.addVODEncoderPriority('video', 'libvpx-vp9', 1000)
391 transcodingManager.addLiveProfile('libopus', 'test-live-profile', builder)
392 transcodingManager.addLiveEncoderPriority('audio', 'libopus', 1000)
396 ### Client helpers (themes & plugins)
398 #### Plugin static route
400 To get your plugin static route:
403 const baseStaticUrl = peertubeHelpers.getBaseStaticRoute()
404 const imageUrl = baseStaticUrl + '/images/chocobo.png'
409 To notify the user with the PeerTube ToastModule:
412 const { notifier } = peertubeHelpers
413 notifier.success('Success message content.')
414 notifier.error('Error message content.')
417 #### Markdown Renderer
419 To render a formatted markdown text to HTML:
422 const { markdownRenderer } = peertubeHelpers
424 await markdownRenderer.textMarkdownToHTML('**My Bold Text**')
425 // return <strong>My Bold Text</strong>
427 await markdownRenderer.enhancedMarkdownToHTML('![alt-img](http://.../my-image.jpg)')
428 // return <img alt=alt-img src=http://.../my-image.jpg />
433 To show a custom modal:
436 peertubeHelpers.showModal({
437 title: 'My custom modal title',
438 content: '<p>My custom modal content</p>',
439 // Optionals parameters :
442 // show cancel button and call action() after hiding modal
443 cancel: { value: 'cancel', action: () => {} },
444 // show confirm button and call action() after hiding modal
445 confirm: { value: 'confirm', action: () => {} },
451 You can translate some strings of your plugin (PeerTube will use your `translations` object of your `package.json` file):
454 peertubeHelpers.translate('User name')
455 .then(translation => console.log('Translated User name by ' + translation))
458 #### Get public settings
460 To get your public plugin settings:
463 peertubeHelpers.getSettings()
465 if (!s || !s['site-id'] || !s['url']) {
466 console.error('Matomo settings are not set.')
474 #### Get server config
477 peertubeHelpers.getServerConfig()
479 console.log('Fetched server config.', config)
483 #### Add custom fields to video form
485 To add custom fields in the video form (in *Plugin settings* tab):
488 async function register ({ registerVideoField, peertubeHelpers }) {
489 const descriptionHTML = await peertubeHelpers.translate(descriptionSource)
490 const commonOptions = {
491 name: 'my-field-name,
492 label: 'My added field',
493 descriptionHTML: 'Optional description',
494 type: 'input-textarea',
498 for (const type of [ 'upload', 'import-url', 'import-torrent', 'update' ]) {
499 registerVideoField(commonOptions, { type })
504 PeerTube will send this field value in `body.pluginData['my-field-name']` and fetch it from `video.pluginData['my-field-name']`.
506 So for example, if you want to store an additional metadata for videos, register the following hooks in **server**:
509 async function register ({
513 const fieldName = 'my-field-name'
515 // Store data associated to this video
517 target: 'action:api.video.updated',
518 handler: ({ video, body }) => {
519 if (!body.pluginData) return
521 const value = body.pluginData[fieldName]
524 storageManager.storeData(fieldName + '-' + video.id, value)
528 // Add your custom value to the video, so the client autofill your field using the previously stored value
530 target: 'filter:api.video.get.result',
531 handler: async (video) => {
532 if (!video) return video
533 if (!video.pluginData) video.pluginData = {}
535 const result = await storageManager.getData(fieldName + '-' + video.id)
536 video.pluginData[fieldName] = result
545 PeerTube plugins and themes should be published on [NPM](https://www.npmjs.com/) so that PeerTube indexes
546 take into account your plugin (after ~ 1 day). An official PeerTube index is available on https://packages.joinpeertube.org/ (it's just a REST API, so don't expect a beautiful website).
548 ## Write a plugin/theme
551 * Find a name for your plugin or your theme (must not have spaces, it can only contain lowercase letters and `-`)
552 * Add the appropriate prefix:
553 * If you develop a plugin, add `peertube-plugin-` prefix to your plugin name (for example: `peertube-plugin-mysupername`)
554 * If you develop a theme, add `peertube-theme-` prefix to your theme name (for example: `peertube-theme-mysupertheme`)
555 * Clone the quickstart repository
556 * Configure your repository
558 * Update `package.json`
559 * Register hooks, add CSS and static files
560 * Test your plugin/theme with a local PeerTube installation
561 * Publish your plugin/theme on NPM
563 ### Clone the quickstart repository
565 If you develop a plugin, clone the `peertube-plugin-quickstart` repository:
568 $ git clone https://framagit.org/framasoft/peertube/peertube-plugin-quickstart.git peertube-plugin-mysupername
571 If you develop a theme, clone the `peertube-theme-quickstart` repository:
574 $ git clone https://framagit.org/framasoft/peertube/peertube-theme-quickstart.git peertube-theme-mysupername
577 ### Configure your repository
579 Set your repository URL:
582 $ cd peertube-plugin-mysupername # or cd peertube-theme-mysupername
583 $ git remote set-url origin https://your-git-repo
588 Update `README.md` file:
594 ### Update package.json
596 Update the `package.json` fields:
597 * `name` (should start with `peertube-plugin-` or `peertube-theme-`)
602 * `engine.peertube` (the PeerTube version compatibility, must be `>=x.y.z` and nothing else)
604 **Caution:** Don't update or remove other keys, or PeerTube will not be able to index/install your plugin.
605 If you don't need static directories, use an empty `object`:
615 And if you don't need CSS or client script files, use an empty `array`:
628 Now you can register hooks or settings, write CSS and add static directories to your plugin or your theme :)
630 **Caution:** It's up to you to check the code you write will be compatible with the PeerTube NodeJS version,
631 and will be supported by web browsers.
632 If you want to write modern JavaScript, please use a transpiler like [Babel](https://babeljs.io/).
636 If you want to translate strings of your plugin (like labels of your registered settings), create a file and add it to `package.json`:
642 "fr-FR": "./languages/fr.json",
643 "pt-BR": "./languages/pt-BR.json"
649 The key should be one of the locales defined in [i18n.ts](https://github.com/Chocobozzz/PeerTube/blob/develop/shared/models/i18n/i18n.ts).
650 You **must** use the complete locales (`fr-FR` instead of `fr`).
652 Translation files are just objects, with the english sentence as the key and the translation as the value.
653 `fr.json` could contain for example:
657 "Hello world": "Hello le monde"
661 ### Build your plugin
663 If you added client scripts, you'll need to build them using webpack.
671 Add/update your files in the `clientFiles` array of `webpack.config.js`:
674 $ $EDITOR ./webpack.config.js
677 Build your client files:
683 You built files are in the `dist/` directory. Check `package.json` to correctly point to them.
686 ### Test your plugin/theme
688 You'll need to have a local PeerTube instance:
689 * Follow the [dev prerequisites](https://github.com/Chocobozzz/PeerTube/blob/develop/.github/CONTRIBUTING.md#prerequisites)
690 (to clone the repository, install dependencies and prepare the database)
691 * Build PeerTube (`--light` to only build the english language):
694 $ npm run build -- --light
703 * Run PeerTube (you can access to your instance on http://localhost:9000):
706 $ NODE_ENV=test npm start
709 * Register the instance via the CLI:
712 $ node ./dist/server/tools/peertube.js auth add -u 'http://localhost:9000' -U 'root' --password 'test'
715 Then, you can install or reinstall your local plugin/theme by running:
718 $ node ./dist/server/tools/peertube.js plugins install --path /your/absolute/plugin-or-theme/path
723 Go in your plugin/theme directory, and run:
729 Every time you want to publish another version of your plugin/theme, just update the `version` key from the `package.json`
730 and republish it on NPM. Remember that the PeerTube index will take into account your new plugin/theme version after ~24 hours.
733 ## Plugin & Theme hooks/helpers API
735 See the dedicated documentation: https://docs.joinpeertube.org/api-plugins
740 ### Compatibility with PeerTube
742 Unfortunately, we don't have enough resources to provide hook compatibility between minor releases of PeerTube (for example between `1.2.x` and `1.3.x`).
744 * Don't make assumptions and check every parameter you want to use. For example:
748 target: 'filter:api.video.get.result',
750 // We check the parameter exists and the name field exists too, to avoid exceptions
751 if (video && video.name) video.name += ' <3'
757 * 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)
758 * Don't use PeerTube dependencies. Use your own :)
760 If your plugin is broken with a new PeerTube release, update your code and the `peertubeEngine` field of your `package.json` field.
761 This way, older PeerTube versions will still use your old plugin, and new PeerTube versions will use your updated plugin.
763 ### Spam/moderation plugin
765 If you want to create an antispam/moderation plugin, you could use the following hooks:
766 * `filter:api.video.upload.accept.result`: to accept or not local uploads
767 * `filter:api.video-thread.create.accept.result`: to accept or not local thread
768 * `filter:api.video-comment-reply.create.accept.result`: to accept or not local replies
769 * `filter:api.video-threads.list.result`: to change/hide the text of threads
770 * `filter:api.video-thread-comments.list.result`: to change/hide the text of replies
771 * `filter:video.auto-blacklist.result`: to automatically blacklist local or remote videos
773 ### Other plugin examples
775 You can take a look to "official" PeerTube plugins if you want to take inspiration from them: https://framagit.org/framasoft/peertube/official-plugins