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)
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 - [Publishing](#publishing)
30 - [Write a plugin/theme](#write-a-plugintheme)
31 - [Clone the quickstart repository](#clone-the-quickstart-repository)
32 - [Configure your repository](#configure-your-repository)
33 - [Update README](#update-readme)
34 - [Update package.json](#update-packagejson)
35 - [Write code](#write-code)
36 - [Add translations](#add-translations)
37 - [Build your plugin](#build-your-plugin)
38 - [Test your plugin/theme](#test-your-plugintheme)
40 - [Plugin & Theme hooks/helpers API](#plugin--theme-hookshelpers-api)
42 - [Compatibility with PeerTube](#compatibility-with-peertube)
43 - [Spam/moderation plugin](#spammoderation-plugin)
44 - [Other plugin examples](#other-plugin-examples)
46 <!-- END doctoc generated TOC please keep comment here to allow auto update -->
50 Themes are exactly the same as plugins, except that:
51 * Their name starts with `peertube-theme-` instead of `peertube-plugin-`
52 * They cannot declare server code (so they cannot register server hooks or settings)
53 * CSS files are loaded by client only if the theme is chosen by the administrator or the user
57 A plugin registers functions in JavaScript to execute when PeerTube (server and client) fires events. There are 3 types of hooks:
58 * `filter`: used to filter functions parameters or return values.
59 For example to replace words in video comments, or change the videos list behaviour
60 * `action`: used to do something after a certain trigger. For example to send a hook every time a video is published
61 * `static`: same than `action` but PeerTube waits their execution
63 On server side, these hooks are registered by the `library` file defined in `package.json`.
68 "library": "./main.js",
73 And `main.js` defines a `register` function:
78 async function register ({
95 unregisterExternalAuth,
96 registerIdAndPassAuth,
97 unregisterIdAndPassAuth
100 target: 'action:application.listening',
101 handler: () => displayHelloWorld()
107 On client side, these hooks are registered by the `clientScripts` files defined in `package.json`.
108 All client scripts have scopes so PeerTube client only loads scripts it needs:
115 "script": "client/common-client-plugin.js",
116 "scopes": [ "common" ]
119 "script": "client/video-watch-client-plugin.js",
120 "scopes": [ "video-watch" ]
127 And these scripts also define a `register` function:
130 function register ({ registerHook, peertubeHelpers }) {
132 target: 'action:application.init',
133 handler: () => onApplicationInit(peertubeHelpers)
140 Plugins can declare static directories that PeerTube will serve (images for example)
141 from `/plugins/{plugin-name}/{plugin-version}/static/`
142 or `/themes/{theme-name}/{theme-version}/static/` routes.
146 Plugins can declare CSS files that PeerTube will automatically inject in the client.
147 If you need to override existing style, you can use the `#custom-css` selector:
154 #custom-css .header {
155 background-color: red;
159 ### Server API (only for plugins)
163 Plugins can register settings, that PeerTube will inject in the administration interface.
164 The following fields will be automatically translated using the plugin translation files: `label`, `html`, `descriptionHTML`, `options.label`.
165 **These fields are injected in the plugin settings page as HTML, so pay attention to your translation files.**
170 function register (...) {
175 // type: input | input-checkbox | input-password | input-textarea | markdown-text | markdown-enhanced | 'select' | 'html'
176 default: 'my super name'
179 const adminName = await settingsManager.getSetting('admin-name')
181 const result = await settingsManager.getSettings([ 'admin-name', 'admin-password' ])
184 settingsManager.onSettingsChange(settings => {
185 settings['admin-name])
192 Plugins can store/load JSON data, that PeerTube will store in its database (so don't put files in there).
197 function register (...) {
198 const value = await storageManager.getData('mykey')
199 await storageManager.storeData('mykey', { subkey: 'value' })
203 #### Update video constants
205 You can add/delete video categories, licences or languages using the appropriate managers:
208 function register (...) {
209 videoLanguageManager.addLanguage('al_bhed', 'Al Bhed')
210 videoLanguageManager.deleteLanguage('fr')
212 videoCategoryManager.addCategory(42, 'Best category')
213 videoCategoryManager.deleteCategory(1) // Music
215 videoLicenceManager.addLicence(42, 'Best licence')
216 videoLicenceManager.deleteLicence(7) // Public domain
218 videoPrivacyManager.deletePrivacy(2) // Remove Unlisted video privacy
219 playlistPrivacyManager.deletePlaylistPrivacy(3) // Remove Private video playlist privacy
223 #### Add custom routes
225 You can create custom routes using an [express Router](https://expressjs.com/en/4x/api.html#router) for your plugin:
228 function register (...) {
229 const router = getRouter()
230 router.get('/ping', (req, res) => res.json({ message: 'pong' }))
234 The `ping` route can be accessed using:
235 * `/plugins/:pluginName/:pluginVersion/router/ping`
236 * Or `/plugins/:pluginName/router/ping`
239 #### Add external auth methods
241 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):
244 function register (...) {
246 registerIdAndPassAuth({
247 authName: 'my-auth-method',
249 // PeerTube will try all id and pass plugins in the weight DESC order
250 // Exposing this value in the plugin settings could be interesting
253 // Optional function called by PeerTube when the user clicked on the logout button
255 console.log('User %s logged out.', user.username')
258 // Optional function called by PeerTube when the access token or refresh token are generated/refreshed
259 hookTokenValidity: ({ token, type }) => {
260 if (type === 'access') return { valid: true }
261 if (type === 'refresh') return { valid: false }
264 // Used by PeerTube when the user tries to authenticate
265 login: ({ id, password }) => {
266 if (id === 'user' && password === 'super password') {
269 email: 'user@example.com'
271 displayName: 'User display name'
280 // Unregister this auth method
281 unregisterIdAndPassAuth('my-auth-method')
285 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):
288 function register (...) {
290 // result contains the userAuthenticated auth method you can call to authenticate a user
291 const result = registerExternalAuth({
292 authName: 'my-auth-method',
294 // Will be displayed in a button next to the login form
295 authDisplayName: () => 'Auth method'
297 // If the user click on the auth button, PeerTube will forward the request in this function
298 onAuthRequest: (req, res) => {
299 res.redirect('https://external-auth.example.com/auth')
302 // Same than registerIdAndPassAuth option
305 // Same than registerIdAndPassAuth option
306 // hookTokenValidity: ...
309 router.use('/external-auth-callback', (req, res) => {
310 // Forward the request to PeerTube
311 result.userAuthenticated({
315 email: 'user@example.com'
317 displayName: 'User display name'
321 // Unregister this external auth method
322 unregisterExternalAuth('my-auth-method)
326 #### Add new transcoding profiles
328 Adding transcoding profiles allow admins to change ffmpeg encoding parameters and/or encoders.
329 A transcoding profile has to be chosen by the admin of the instance using the admin configuration.
332 async function register ({
336 // Adapt bitrate when using libx264 encoder
338 const builder = (options) => {
339 const { input, resolution, fps, streamNum } = options
341 const streamString = streamNum ? ':' + streamNum : ''
343 // You can also return a promise
344 // All these options are optional
347 // Used to define an alternative scale filter, needed by some encoders
348 // Default to 'scale'
355 // Use a custom bitrate
356 '-b' + streamString + ' 10K'
361 const encoder = 'libx264'
362 const profileName = 'low-quality'
364 // Support this profile for VOD transcoding
365 transcodingManager.addVODProfile(encoder, profileName, builder)
367 // And/Or support this profile for live transcoding
368 transcodingManager.addLiveProfile(encoder, profileName, builder)
372 const builder = (options) => {
373 const { streamNum } = options
375 const streamString = streamNum ? ':' + streamNum : ''
377 // Always copy stream when PeerTube use libfdk_aac or aac encoders
383 const profileName = 'copy-audio'
385 for (const encoder of [ 'libfdk_aac', 'aac' ]) {
386 transcodingManager.addVODProfile(encoder, profileName, builder)
391 PeerTube will try different encoders depending on their priority.
392 If the encoder is not available in the current transcoding profile or in ffmpeg, it tries the next one.
393 Plugins can change the order of these encoders and add their custom encoders:
396 async function register ({
400 // Adapt bitrate when using libx264 encoder
402 const builder = () => {
409 // Support libopus and libvpx-vp9 encoders (these codecs could be incompatible with the player)
410 transcodingManager.addVODProfile('libopus', 'test-vod-profile', builder)
412 // Default priorities are ~100
413 // Lowest priority = 1
414 transcodingManager.addVODEncoderPriority('audio', 'libopus', 1000)
416 transcodingManager.addVODProfile('libvpx-vp9', 'test-vod-profile', builder)
417 transcodingManager.addVODEncoderPriority('video', 'libvpx-vp9', 1000)
419 transcodingManager.addLiveProfile('libopus', 'test-live-profile', builder)
420 transcodingManager.addLiveEncoderPriority('audio', 'libopus', 1000)
424 During live transcode input options are applied once for each target resolution.
425 Plugins are responsible for detecting such situation and applying input options only once if necessary.
429 PeerTube provides your plugin some helpers. For example:
432 async function register ({
437 const serverActor = await peertubeHelpers.server.getServerActor()
439 await peertubeHelpers.moderation.blockServer({ byAccountId: serverActor.Account.id, hostToBlock: '...' })
444 const video = await peertubeHelpers.videos.loadByUrl('...')
449 See the [plugin API reference](https://docs.joinpeertube.org/api-plugins) to see the complete helpers list.
451 ### Client API (themes & plugins)
453 #### Plugin static route
455 To get your plugin static route:
458 function register (...) {
459 const baseStaticUrl = peertubeHelpers.getBaseStaticRoute()
460 const imageUrl = baseStaticUrl + '/images/chocobo.png'
466 To notify the user with the PeerTube ToastModule:
469 function register (...) {
470 const { notifier } = peertubeHelpers
471 notifier.success('Success message content.')
472 notifier.error('Error message content.')
476 #### Markdown Renderer
478 To render a formatted markdown text to HTML:
481 function register (...) {
482 const { markdownRenderer } = peertubeHelpers
484 await markdownRenderer.textMarkdownToHTML('**My Bold Text**')
485 // return <strong>My Bold Text</strong>
487 await markdownRenderer.enhancedMarkdownToHTML('![alt-img](http://.../my-image.jpg)')
488 // return <img alt=alt-img src=http://.../my-image.jpg />
494 To show a custom modal:
497 function register (...) {
498 peertubeHelpers.showModal({
499 title: 'My custom modal title',
500 content: '<p>My custom modal content</p>',
501 // Optionals parameters :
504 // show cancel button and call action() after hiding modal
505 cancel: { value: 'cancel', action: () => {} },
506 // show confirm button and call action() after hiding modal
507 confirm: { value: 'confirm', action: () => {} },
514 You can translate some strings of your plugin (PeerTube will use your `translations` object of your `package.json` file):
517 function register (...) {
518 peertubeHelpers.translate('User name')
519 .then(translation => console.log('Translated User name by ' + translation))
523 #### Get public settings
525 To get your public plugin settings:
528 function register (...) {
529 peertubeHelpers.getSettings()
531 if (!s || !s['site-id'] || !s['url']) {
532 console.error('Matomo settings are not set.')
541 #### Get server config
544 function register (...) {
545 peertubeHelpers.getServerConfig()
547 console.log('Fetched server config.', config)
552 #### Add custom fields to video form
554 To add custom fields in the video form (in *Plugin settings* tab):
557 async function register ({ registerVideoField, peertubeHelpers }) {
558 const descriptionHTML = await peertubeHelpers.translate(descriptionSource)
559 const commonOptions = {
560 name: 'my-field-name,
561 label: 'My added field',
562 descriptionHTML: 'Optional description',
563 type: 'input-textarea',
567 for (const type of [ 'upload', 'import-url', 'import-torrent', 'update' ]) {
568 registerVideoField(commonOptions, { type })
573 PeerTube will send this field value in `body.pluginData['my-field-name']` and fetch it from `video.pluginData['my-field-name']`.
575 So for example, if you want to store an additional metadata for videos, register the following hooks in **server**:
578 async function register ({
582 const fieldName = 'my-field-name'
584 // Store data associated to this video
586 target: 'action:api.video.updated',
587 handler: ({ video, body }) => {
588 if (!body.pluginData) return
590 const value = body.pluginData[fieldName]
593 storageManager.storeData(fieldName + '-' + video.id, value)
597 // Add your custom value to the video, so the client autofill your field using the previously stored value
599 target: 'filter:api.video.get.result',
600 handler: async (video) => {
601 if (!video) return video
602 if (!video.pluginData) video.pluginData = {}
604 const result = await storageManager.getData(fieldName + '-' + video.id)
605 video.pluginData[fieldName] = result
613 #### Register settings script
615 To hide some fields in your settings plugin page depending on the form state:
618 async function register ({ registerSettingsScript }) {
619 registerSettingsScript({
620 isSettingHidden: options => {
621 if (options.setting.name === 'my-setting' && options.formValues['field45'] === '2') {
634 PeerTube plugins and themes should be published on [NPM](https://www.npmjs.com/) so that PeerTube indexes
635 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).
637 ## Write a plugin/theme
640 * Find a name for your plugin or your theme (must not have spaces, it can only contain lowercase letters and `-`)
641 * Add the appropriate prefix:
642 * If you develop a plugin, add `peertube-plugin-` prefix to your plugin name (for example: `peertube-plugin-mysupername`)
643 * If you develop a theme, add `peertube-theme-` prefix to your theme name (for example: `peertube-theme-mysupertheme`)
644 * Clone the quickstart repository
645 * Configure your repository
647 * Update `package.json`
648 * Register hooks, add CSS and static files
649 * Test your plugin/theme with a local PeerTube installation
650 * Publish your plugin/theme on NPM
652 ### Clone the quickstart repository
654 If you develop a plugin, clone the `peertube-plugin-quickstart` repository:
657 $ git clone https://framagit.org/framasoft/peertube/peertube-plugin-quickstart.git peertube-plugin-mysupername
660 If you develop a theme, clone the `peertube-theme-quickstart` repository:
663 $ git clone https://framagit.org/framasoft/peertube/peertube-theme-quickstart.git peertube-theme-mysupername
666 ### Configure your repository
668 Set your repository URL:
671 $ cd peertube-plugin-mysupername # or cd peertube-theme-mysupername
672 $ git remote set-url origin https://your-git-repo
677 Update `README.md` file:
683 ### Update package.json
685 Update the `package.json` fields:
686 * `name` (should start with `peertube-plugin-` or `peertube-theme-`)
691 * `engine.peertube` (the PeerTube version compatibility, must be `>=x.y.z` and nothing else)
693 **Caution:** Don't update or remove other keys, or PeerTube will not be able to index/install your plugin.
694 If you don't need static directories, use an empty `object`:
704 And if you don't need CSS or client script files, use an empty `array`:
717 Now you can register hooks or settings, write CSS and add static directories to your plugin or your theme :)
719 **Caution:** It's up to you to check the code you write will be compatible with the PeerTube NodeJS version,
720 and will be supported by web browsers.
721 If you want to write modern JavaScript, please use a transpiler like [Babel](https://babeljs.io/).
725 If you want to translate strings of your plugin (like labels of your registered settings), create a file and add it to `package.json`:
731 "fr-FR": "./languages/fr.json",
732 "pt-BR": "./languages/pt-BR.json"
738 The key should be one of the locales defined in [i18n.ts](https://github.com/Chocobozzz/PeerTube/blob/develop/shared/models/i18n/i18n.ts).
739 You **must** use the complete locales (`fr-FR` instead of `fr`).
741 Translation files are just objects, with the english sentence as the key and the translation as the value.
742 `fr.json` could contain for example:
746 "Hello world": "Hello le monde"
750 ### Build your plugin
752 If you added client scripts, you'll need to build them using webpack.
760 Add/update your files in the `clientFiles` array of `webpack.config.js`:
763 $ $EDITOR ./webpack.config.js
766 Build your client files:
772 You built files are in the `dist/` directory. Check `package.json` to correctly point to them.
775 ### Test your plugin/theme
777 You'll need to have a local PeerTube instance:
778 * Follow the [dev prerequisites](https://github.com/Chocobozzz/PeerTube/blob/develop/.github/CONTRIBUTING.md#prerequisites)
779 (to clone the repository, install dependencies and prepare the database)
780 * Build PeerTube (`--light` to only build the english language):
783 $ npm run build -- --light
792 * Run PeerTube (you can access to your instance on http://localhost:9000):
795 $ NODE_ENV=test npm start
798 * Register the instance via the CLI:
801 $ node ./dist/server/tools/peertube.js auth add -u 'http://localhost:9000' -U 'root' --password 'test'
804 Then, you can install or reinstall your local plugin/theme by running:
807 $ node ./dist/server/tools/peertube.js plugins install --path /your/absolute/plugin-or-theme/path
812 Go in your plugin/theme directory, and run:
818 Every time you want to publish another version of your plugin/theme, just update the `version` key from the `package.json`
819 and republish it on NPM. Remember that the PeerTube index will take into account your new plugin/theme version after ~24 hours.
822 ## Plugin & Theme hooks/helpers API
824 See the dedicated documentation: https://docs.joinpeertube.org/api-plugins
829 ### Compatibility with PeerTube
831 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`).
833 * Don't make assumptions and check every parameter you want to use. For example:
837 target: 'filter:api.video.get.result',
839 // We check the parameter exists and the name field exists too, to avoid exceptions
840 if (video && video.name) video.name += ' <3'
846 * 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)
847 * Don't use PeerTube dependencies. Use your own :)
849 If your plugin is broken with a new PeerTube release, update your code and the `peertubeEngine` field of your `package.json` field.
850 This way, older PeerTube versions will still use your old plugin, and new PeerTube versions will use your updated plugin.
852 ### Spam/moderation plugin
854 If you want to create an antispam/moderation plugin, you could use the following hooks:
855 * `filter:api.video.upload.accept.result`: to accept or not local uploads
856 * `filter:api.video-thread.create.accept.result`: to accept or not local thread
857 * `filter:api.video-comment-reply.create.accept.result`: to accept or not local replies
858 * `filter:api.video-threads.list.result`: to change/hide the text of threads
859 * `filter:api.video-thread-comments.list.result`: to change/hide the text of replies
860 * `filter:video.auto-blacklist.result`: to automatically blacklist local or remote videos
862 ### Other plugin examples
864 You can take a look to "official" PeerTube plugins if you want to take inspiration from them: https://framagit.org/framasoft/peertube/official-plugins