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 API (only for plugins)](#server-api-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 - [Server helpers](#server-helpers)
19 - [Client API (themes & plugins)](#client-api-themes--plugins)
20 - [Plugin static route](#plugin-static-route)
21 - [Notifier](#notifier)
22 - [Markdown Renderer](#markdown-renderer)
23 - [Custom Modal](#custom-modal)
24 - [Translate](#translate)
25 - [Get public settings](#get-public-settings)
26 - [Get server config](#get-server-config)
27 - [Add custom fields to video form](#add-custom-fields-to-video-form)
28 - [Register settings script](#register-settings-script)
29 - [HTML placeholder elements](#html-placeholder-elements)
30 - [Publishing](#publishing)
31 - [Write a plugin/theme](#write-a-plugintheme)
32 - [Clone the quickstart repository](#clone-the-quickstart-repository)
33 - [Configure your repository](#configure-your-repository)
34 - [Update README](#update-readme)
35 - [Update package.json](#update-packagejson)
36 - [Write code](#write-code)
37 - [Add translations](#add-translations)
38 - [Build your plugin](#build-your-plugin)
39 - [Test your plugin/theme](#test-your-plugintheme)
41 - [Plugin & Theme hooks/helpers API](#plugin--theme-hookshelpers-api)
43 - [Compatibility with PeerTube](#compatibility-with-peertube)
44 - [Spam/moderation plugin](#spammoderation-plugin)
45 - [Other plugin examples](#other-plugin-examples)
47 <!-- END doctoc generated TOC please keep comment here to allow auto update -->
51 Themes are exactly the same as plugins, except that:
52 * Their name starts with `peertube-theme-` instead of `peertube-plugin-`
53 * They cannot declare server code (so they cannot register server hooks or settings)
54 * CSS files are loaded by client only if the theme is chosen by the administrator or the user
58 A plugin registers functions in JavaScript to execute when PeerTube (server and client) fires events. There are 3 types of hooks:
59 * `filter`: used to filter functions parameters or return values.
60 For example to replace words in video comments, or change the videos list behaviour
61 * `action`: used to do something after a certain trigger. For example to send a hook every time a video is published
62 * `static`: same than `action` but PeerTube waits their execution
64 On server side, these hooks are registered by the `library` file defined in `package.json`.
69 "library": "./main.js",
74 And `main.js` defines a `register` function:
79 async function register ({
96 unregisterExternalAuth,
97 registerIdAndPassAuth,
98 unregisterIdAndPassAuth
101 target: 'action:application.listening',
102 handler: () => displayHelloWorld()
108 On client side, these hooks are registered by the `clientScripts` files defined in `package.json`.
109 All client scripts have scopes so PeerTube client only loads scripts it needs:
116 "script": "client/common-client-plugin.js",
117 "scopes": [ "common" ]
120 "script": "client/video-watch-client-plugin.js",
121 "scopes": [ "video-watch" ]
128 And these scripts also define a `register` function:
131 function register ({ registerHook, peertubeHelpers }) {
133 target: 'action:application.init',
134 handler: () => onApplicationInit(peertubeHelpers)
141 Plugins can declare static directories that PeerTube will serve (images for example)
142 from `/plugins/{plugin-name}/{plugin-version}/static/`
143 or `/themes/{theme-name}/{theme-version}/static/` routes.
147 Plugins can declare CSS files that PeerTube will automatically inject in the client.
148 If you need to override existing style, you can use the `#custom-css` selector:
155 #custom-css .header {
156 background-color: red;
160 ### Server API (only for plugins)
164 Plugins can register settings, that PeerTube will inject in the administration interface.
165 The following fields will be automatically translated using the plugin translation files: `label`, `html`, `descriptionHTML`, `options.label`.
166 **These fields are injected in the plugin settings page as HTML, so pay attention to your translation files.**
171 function register (...) {
176 // type: input | input-checkbox | input-password | input-textarea | markdown-text | markdown-enhanced | 'select' | 'html'
177 default: 'my super name'
180 const adminName = await settingsManager.getSetting('admin-name')
182 const result = await settingsManager.getSettings([ 'admin-name', 'admin-password' ])
185 settingsManager.onSettingsChange(settings => {
186 settings['admin-name])
193 Plugins can store/load JSON data, that PeerTube will store in its database (so don't put files in there).
198 function register (...) {
199 const value = await storageManager.getData('mykey')
200 await storageManager.storeData('mykey', { subkey: 'value' })
204 #### Update video constants
206 You can add/delete video categories, licences or languages using the appropriate managers:
209 function register (...) {
210 videoLanguageManager.addLanguage('al_bhed', 'Al Bhed')
211 videoLanguageManager.deleteLanguage('fr')
213 videoCategoryManager.addCategory(42, 'Best category')
214 videoCategoryManager.deleteCategory(1) // Music
216 videoLicenceManager.addLicence(42, 'Best licence')
217 videoLicenceManager.deleteLicence(7) // Public domain
219 videoPrivacyManager.deletePrivacy(2) // Remove Unlisted video privacy
220 playlistPrivacyManager.deletePlaylistPrivacy(3) // Remove Private video playlist privacy
224 #### Add custom routes
226 You can create custom routes using an [express Router](https://expressjs.com/en/4x/api.html#router) for your plugin:
229 function register (...) {
230 const router = getRouter()
231 router.get('/ping', (req, res) => res.json({ message: 'pong' }))
235 The `ping` route can be accessed using:
236 * `/plugins/:pluginName/:pluginVersion/router/ping`
237 * Or `/plugins/:pluginName/router/ping`
240 #### Add external auth methods
242 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):
245 function register (...) {
247 registerIdAndPassAuth({
248 authName: 'my-auth-method',
250 // PeerTube will try all id and pass plugins in the weight DESC order
251 // Exposing this value in the plugin settings could be interesting
254 // Optional function called by PeerTube when the user clicked on the logout button
256 console.log('User %s logged out.', user.username')
259 // Optional function called by PeerTube when the access token or refresh token are generated/refreshed
260 hookTokenValidity: ({ token, type }) => {
261 if (type === 'access') return { valid: true }
262 if (type === 'refresh') return { valid: false }
265 // Used by PeerTube when the user tries to authenticate
266 login: ({ id, password }) => {
267 if (id === 'user' && password === 'super password') {
270 email: 'user@example.com'
272 displayName: 'User display name'
281 // Unregister this auth method
282 unregisterIdAndPassAuth('my-auth-method')
286 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):
289 function register (...) {
291 // result contains the userAuthenticated auth method you can call to authenticate a user
292 const result = registerExternalAuth({
293 authName: 'my-auth-method',
295 // Will be displayed in a button next to the login form
296 authDisplayName: () => 'Auth method'
298 // If the user click on the auth button, PeerTube will forward the request in this function
299 onAuthRequest: (req, res) => {
300 res.redirect('https://external-auth.example.com/auth')
303 // Same than registerIdAndPassAuth option
306 // Same than registerIdAndPassAuth option
307 // hookTokenValidity: ...
310 router.use('/external-auth-callback', (req, res) => {
311 // Forward the request to PeerTube
312 result.userAuthenticated({
316 email: 'user@example.com'
318 displayName: 'User display name'
322 // Unregister this external auth method
323 unregisterExternalAuth('my-auth-method)
327 #### Add new transcoding profiles
329 Adding transcoding profiles allow admins to change ffmpeg encoding parameters and/or encoders.
330 A transcoding profile has to be chosen by the admin of the instance using the admin configuration.
333 async function register ({
337 // Adapt bitrate when using libx264 encoder
339 const builder = (options) => {
340 const { input, resolution, fps, streamNum } = options
342 const streamString = streamNum ? ':' + streamNum : ''
344 // You can also return a promise
345 // All these options are optional
348 // Used to define an alternative scale filter, needed by some encoders
349 // Default to 'scale'
356 // Use a custom bitrate
357 '-b' + streamString + ' 10K'
362 const encoder = 'libx264'
363 const profileName = 'low-quality'
365 // Support this profile for VOD transcoding
366 transcodingManager.addVODProfile(encoder, profileName, builder)
368 // And/Or support this profile for live transcoding
369 transcodingManager.addLiveProfile(encoder, profileName, builder)
373 const builder = (options) => {
374 const { streamNum } = options
376 const streamString = streamNum ? ':' + streamNum : ''
378 // Always copy stream when PeerTube use libfdk_aac or aac encoders
384 const profileName = 'copy-audio'
386 for (const encoder of [ 'libfdk_aac', 'aac' ]) {
387 transcodingManager.addVODProfile(encoder, profileName, builder)
392 PeerTube will try different encoders depending on their priority.
393 If the encoder is not available in the current transcoding profile or in ffmpeg, it tries the next one.
394 Plugins can change the order of these encoders and add their custom encoders:
397 async function register ({
401 // Adapt bitrate when using libx264 encoder
403 const builder = () => {
410 // Support libopus and libvpx-vp9 encoders (these codecs could be incompatible with the player)
411 transcodingManager.addVODProfile('libopus', 'test-vod-profile', builder)
413 // Default priorities are ~100
414 // Lowest priority = 1
415 transcodingManager.addVODEncoderPriority('audio', 'libopus', 1000)
417 transcodingManager.addVODProfile('libvpx-vp9', 'test-vod-profile', builder)
418 transcodingManager.addVODEncoderPriority('video', 'libvpx-vp9', 1000)
420 transcodingManager.addLiveProfile('libopus', 'test-live-profile', builder)
421 transcodingManager.addLiveEncoderPriority('audio', 'libopus', 1000)
425 During live transcode input options are applied once for each target resolution.
426 Plugins are responsible for detecting such situation and applying input options only once if necessary.
430 PeerTube provides your plugin some helpers. For example:
433 async function register ({
438 const serverActor = await peertubeHelpers.server.getServerActor()
440 await peertubeHelpers.moderation.blockServer({ byAccountId: serverActor.Account.id, hostToBlock: '...' })
445 const video = await peertubeHelpers.videos.loadByUrl('...')
450 See the [plugin API reference](https://docs.joinpeertube.org/api-plugins) to see the complete helpers list.
452 ### Client API (themes & plugins)
454 #### Plugin static route
456 To get your plugin static route:
459 function register (...) {
460 const baseStaticUrl = peertubeHelpers.getBaseStaticRoute()
461 const imageUrl = baseStaticUrl + '/images/chocobo.png'
467 To notify the user with the PeerTube ToastModule:
470 function register (...) {
471 const { notifier } = peertubeHelpers
472 notifier.success('Success message content.')
473 notifier.error('Error message content.')
477 #### Markdown Renderer
479 To render a formatted markdown text to HTML:
482 function register (...) {
483 const { markdownRenderer } = peertubeHelpers
485 await markdownRenderer.textMarkdownToHTML('**My Bold Text**')
486 // return <strong>My Bold Text</strong>
488 await markdownRenderer.enhancedMarkdownToHTML('![alt-img](http://.../my-image.jpg)')
489 // return <img alt=alt-img src=http://.../my-image.jpg />
495 To show a custom modal:
498 function register (...) {
499 peertubeHelpers.showModal({
500 title: 'My custom modal title',
501 content: '<p>My custom modal content</p>',
502 // Optionals parameters :
505 // show cancel button and call action() after hiding modal
506 cancel: { value: 'cancel', action: () => {} },
507 // show confirm button and call action() after hiding modal
508 confirm: { value: 'confirm', action: () => {} },
515 You can translate some strings of your plugin (PeerTube will use your `translations` object of your `package.json` file):
518 function register (...) {
519 peertubeHelpers.translate('User name')
520 .then(translation => console.log('Translated User name by ' + translation))
524 #### Get public settings
526 To get your public plugin settings:
529 function register (...) {
530 peertubeHelpers.getSettings()
532 if (!s || !s['site-id'] || !s['url']) {
533 console.error('Matomo settings are not set.')
542 #### Get server config
545 function register (...) {
546 peertubeHelpers.getServerConfig()
548 console.log('Fetched server config.', config)
553 #### Add custom fields to video form
555 To add custom fields in the video form (in *Plugin settings* tab):
558 async function register ({ registerVideoField, peertubeHelpers }) {
559 const descriptionHTML = await peertubeHelpers.translate(descriptionSource)
560 const commonOptions = {
561 name: 'my-field-name,
562 label: 'My added field',
563 descriptionHTML: 'Optional description',
564 type: 'input-textarea',
568 for (const type of [ 'upload', 'import-url', 'import-torrent', 'update' ]) {
569 registerVideoField(commonOptions, { type })
574 PeerTube will send this field value in `body.pluginData['my-field-name']` and fetch it from `video.pluginData['my-field-name']`.
576 So for example, if you want to store an additional metadata for videos, register the following hooks in **server**:
579 async function register ({
583 const fieldName = 'my-field-name'
585 // Store data associated to this video
587 target: 'action:api.video.updated',
588 handler: ({ video, body }) => {
589 if (!body.pluginData) return
591 const value = body.pluginData[fieldName]
594 storageManager.storeData(fieldName + '-' + video.id, value)
598 // Add your custom value to the video, so the client autofill your field using the previously stored value
600 target: 'filter:api.video.get.result',
601 handler: async (video) => {
602 if (!video) return video
603 if (!video.pluginData) video.pluginData = {}
605 const result = await storageManager.getData(fieldName + '-' + video.id)
606 video.pluginData[fieldName] = result
614 #### Register settings script
616 To hide some fields in your settings plugin page depending on the form state:
619 async function register ({ registerSettingsScript }) {
620 registerSettingsScript({
621 isSettingHidden: options => {
622 if (options.setting.name === 'my-setting' && options.formValues['field45'] === '2') {
632 #### HTML placeholder elements
634 PeerTube provides some HTML id so plugins can easily insert their own element:
637 async function register (...) {
638 const elem = document.createElement('div')
639 elem.className = 'hello-world-h4'
640 elem.innerHTML = '<h4>Hello everybody! This is an element next to the player</h4>'
642 document.getElementById('plugin-placeholder-player-next').appendChild(elem)
646 See the complete list on https://docs.joinpeertube.org/api-plugins
650 PeerTube plugins and themes should be published on [NPM](https://www.npmjs.com/) so that PeerTube indexes
651 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).
653 ## Write a plugin/theme
656 * Find a name for your plugin or your theme (must not have spaces, it can only contain lowercase letters and `-`)
657 * Add the appropriate prefix:
658 * If you develop a plugin, add `peertube-plugin-` prefix to your plugin name (for example: `peertube-plugin-mysupername`)
659 * If you develop a theme, add `peertube-theme-` prefix to your theme name (for example: `peertube-theme-mysupertheme`)
660 * Clone the quickstart repository
661 * Configure your repository
663 * Update `package.json`
664 * Register hooks, add CSS and static files
665 * Test your plugin/theme with a local PeerTube installation
666 * Publish your plugin/theme on NPM
668 ### Clone the quickstart repository
670 If you develop a plugin, clone the `peertube-plugin-quickstart` repository:
673 $ git clone https://framagit.org/framasoft/peertube/peertube-plugin-quickstart.git peertube-plugin-mysupername
676 If you develop a theme, clone the `peertube-theme-quickstart` repository:
679 $ git clone https://framagit.org/framasoft/peertube/peertube-theme-quickstart.git peertube-theme-mysupername
682 ### Configure your repository
684 Set your repository URL:
687 $ cd peertube-plugin-mysupername # or cd peertube-theme-mysupername
688 $ git remote set-url origin https://your-git-repo
693 Update `README.md` file:
699 ### Update package.json
701 Update the `package.json` fields:
702 * `name` (should start with `peertube-plugin-` or `peertube-theme-`)
707 * `engine.peertube` (the PeerTube version compatibility, must be `>=x.y.z` and nothing else)
709 **Caution:** Don't update or remove other keys, or PeerTube will not be able to index/install your plugin.
710 If you don't need static directories, use an empty `object`:
720 And if you don't need CSS or client script files, use an empty `array`:
733 Now you can register hooks or settings, write CSS and add static directories to your plugin or your theme :)
735 **Caution:** It's up to you to check the code you write will be compatible with the PeerTube NodeJS version,
736 and will be supported by web browsers.
737 If you want to write modern JavaScript, please use a transpiler like [Babel](https://babeljs.io/).
741 If you want to translate strings of your plugin (like labels of your registered settings), create a file and add it to `package.json`:
747 "fr-FR": "./languages/fr.json",
748 "pt-BR": "./languages/pt-BR.json"
754 The key should be one of the locales defined in [i18n.ts](https://github.com/Chocobozzz/PeerTube/blob/develop/shared/models/i18n/i18n.ts).
755 You **must** use the complete locales (`fr-FR` instead of `fr`).
757 Translation files are just objects, with the english sentence as the key and the translation as the value.
758 `fr.json` could contain for example:
762 "Hello world": "Hello le monde"
766 ### Build your plugin
768 If you added client scripts, you'll need to build them using webpack.
776 Add/update your files in the `clientFiles` array of `webpack.config.js`:
779 $ $EDITOR ./webpack.config.js
782 Build your client files:
788 You built files are in the `dist/` directory. Check `package.json` to correctly point to them.
791 ### Test your plugin/theme
793 You'll need to have a local PeerTube instance:
794 * Follow the [dev prerequisites](https://github.com/Chocobozzz/PeerTube/blob/develop/.github/CONTRIBUTING.md#prerequisites)
795 (to clone the repository, install dependencies and prepare the database)
796 * Build PeerTube (`--light` to only build the english language):
799 $ npm run build -- --light
808 * Run PeerTube (you can access to your instance on http://localhost:9000):
811 $ NODE_ENV=test npm start
814 * Register the instance via the CLI:
817 $ node ./dist/server/tools/peertube.js auth add -u 'http://localhost:9000' -U 'root' --password 'test'
820 Then, you can install or reinstall your local plugin/theme by running:
823 $ node ./dist/server/tools/peertube.js plugins install --path /your/absolute/plugin-or-theme/path
828 Go in your plugin/theme directory, and run:
834 Every time you want to publish another version of your plugin/theme, just update the `version` key from the `package.json`
835 and republish it on NPM. Remember that the PeerTube index will take into account your new plugin/theme version after ~24 hours.
838 ## Plugin & Theme hooks/helpers API
840 See the dedicated documentation: https://docs.joinpeertube.org/api-plugins
845 ### Compatibility with PeerTube
847 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`).
849 * Don't make assumptions and check every parameter you want to use. For example:
853 target: 'filter:api.video.get.result',
855 // We check the parameter exists and the name field exists too, to avoid exceptions
856 if (video && video.name) video.name += ' <3'
862 * 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)
863 * Don't use PeerTube dependencies. Use your own :)
865 If your plugin is broken with a new PeerTube release, update your code and the `peertubeEngine` field of your `package.json` field.
866 This way, older PeerTube versions will still use your old plugin, and new PeerTube versions will use your updated plugin.
868 ### Spam/moderation plugin
870 If you want to create an antispam/moderation plugin, you could use the following hooks:
871 * `filter:api.video.upload.accept.result`: to accept or not local uploads
872 * `filter:api.video-thread.create.accept.result`: to accept or not local thread
873 * `filter:api.video-comment-reply.create.accept.result`: to accept or not local replies
874 * `filter:api.video-threads.list.result`: to change/hide the text of threads
875 * `filter:api.video-thread-comments.list.result`: to change/hide the text of replies
876 * `filter:video.auto-blacklist.result`: to automatically blacklist local or remote videos
878 ### Other plugin examples
880 You can take a look to "official" PeerTube plugins if you want to take inspiration from them: https://framagit.org/framasoft/peertube/official-plugins