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
347 // Use a custom bitrate
348 '-b' + streamString + ' 10K'
353 const encoder = 'libx264'
354 const profileName = 'low-quality'
356 // Support this profile for VOD transcoding
357 transcodingManager.addVODProfile(encoder, profileName, builder)
359 // And/Or support this profile for live transcoding
360 transcodingManager.addLiveProfile(encoder, profileName, builder)
364 const builder = (options) => {
365 const { streamNum } = options
367 const streamString = streamNum ? ':' + streamNum : ''
369 // Always copy stream when PeerTube use libfdk_aac or aac encoders
375 const profileName = 'copy-audio'
377 for (const encoder of [ 'libfdk_aac', 'aac' ]) {
378 transcodingManager.addVODProfile(encoder, profileName, builder)
383 PeerTube will try different encoders depending on their priority.
384 If the encoder is not available in the current transcoding profile or in ffmpeg, it tries the next one.
385 Plugins can change the order of these encoders and add their custom encoders:
388 async function register ({
392 // Adapt bitrate when using libx264 encoder
394 const builder = () => {
401 // Support libopus and libvpx-vp9 encoders (these codecs could be incompatible with the player)
402 transcodingManager.addVODProfile('libopus', 'test-vod-profile', builder)
404 // Default priorities are ~100
405 // Lowest priority = 1
406 transcodingManager.addVODEncoderPriority('audio', 'libopus', 1000)
408 transcodingManager.addVODProfile('libvpx-vp9', 'test-vod-profile', builder)
409 transcodingManager.addVODEncoderPriority('video', 'libvpx-vp9', 1000)
411 transcodingManager.addLiveProfile('libopus', 'test-live-profile', builder)
412 transcodingManager.addLiveEncoderPriority('audio', 'libopus', 1000)
418 PeerTube provides your plugin some helpers. For example:
421 async function register ({
426 const serverActor = await peertubeHelpers.server.getServerActor()
428 await peertubeHelpers.moderation.blockServer({ byAccountId: serverActor.Account.id, hostToBlock: '...' })
433 const video = await peertubeHelpers.videos.loadByUrl('...')
438 See the [plugin API reference](https://docs.joinpeertube.org/api-plugins) to see the complete helpers list.
440 ### Client API (themes & plugins)
442 #### Plugin static route
444 To get your plugin static route:
447 function register (...) {
448 const baseStaticUrl = peertubeHelpers.getBaseStaticRoute()
449 const imageUrl = baseStaticUrl + '/images/chocobo.png'
455 To notify the user with the PeerTube ToastModule:
458 function register (...) {
459 const { notifier } = peertubeHelpers
460 notifier.success('Success message content.')
461 notifier.error('Error message content.')
465 #### Markdown Renderer
467 To render a formatted markdown text to HTML:
470 function register (...) {
471 const { markdownRenderer } = peertubeHelpers
473 await markdownRenderer.textMarkdownToHTML('**My Bold Text**')
474 // return <strong>My Bold Text</strong>
476 await markdownRenderer.enhancedMarkdownToHTML('![alt-img](http://.../my-image.jpg)')
477 // return <img alt=alt-img src=http://.../my-image.jpg />
483 To show a custom modal:
486 function register (...) {
487 peertubeHelpers.showModal({
488 title: 'My custom modal title',
489 content: '<p>My custom modal content</p>',
490 // Optionals parameters :
493 // show cancel button and call action() after hiding modal
494 cancel: { value: 'cancel', action: () => {} },
495 // show confirm button and call action() after hiding modal
496 confirm: { value: 'confirm', action: () => {} },
503 You can translate some strings of your plugin (PeerTube will use your `translations` object of your `package.json` file):
506 function register (...) {
507 peertubeHelpers.translate('User name')
508 .then(translation => console.log('Translated User name by ' + translation))
512 #### Get public settings
514 To get your public plugin settings:
517 function register (...) {
518 peertubeHelpers.getSettings()
520 if (!s || !s['site-id'] || !s['url']) {
521 console.error('Matomo settings are not set.')
530 #### Get server config
533 function register (...) {
534 peertubeHelpers.getServerConfig()
536 console.log('Fetched server config.', config)
541 #### Add custom fields to video form
543 To add custom fields in the video form (in *Plugin settings* tab):
546 async function register ({ registerVideoField, peertubeHelpers }) {
547 const descriptionHTML = await peertubeHelpers.translate(descriptionSource)
548 const commonOptions = {
549 name: 'my-field-name,
550 label: 'My added field',
551 descriptionHTML: 'Optional description',
552 type: 'input-textarea',
556 for (const type of [ 'upload', 'import-url', 'import-torrent', 'update' ]) {
557 registerVideoField(commonOptions, { type })
562 PeerTube will send this field value in `body.pluginData['my-field-name']` and fetch it from `video.pluginData['my-field-name']`.
564 So for example, if you want to store an additional metadata for videos, register the following hooks in **server**:
567 async function register ({
571 const fieldName = 'my-field-name'
573 // Store data associated to this video
575 target: 'action:api.video.updated',
576 handler: ({ video, body }) => {
577 if (!body.pluginData) return
579 const value = body.pluginData[fieldName]
582 storageManager.storeData(fieldName + '-' + video.id, value)
586 // Add your custom value to the video, so the client autofill your field using the previously stored value
588 target: 'filter:api.video.get.result',
589 handler: async (video) => {
590 if (!video) return video
591 if (!video.pluginData) video.pluginData = {}
593 const result = await storageManager.getData(fieldName + '-' + video.id)
594 video.pluginData[fieldName] = result
602 #### Register settings script
604 To hide some fields in your settings plugin page depending on the form state:
607 async function register ({ registerSettingsScript }) {
608 registerSettingsScript({
609 isSettingHidden: options => {
610 if (options.setting.name === 'my-setting' && options.formValues['field45'] === '2') {
623 PeerTube plugins and themes should be published on [NPM](https://www.npmjs.com/) so that PeerTube indexes
624 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).
626 ## Write a plugin/theme
629 * Find a name for your plugin or your theme (must not have spaces, it can only contain lowercase letters and `-`)
630 * Add the appropriate prefix:
631 * If you develop a plugin, add `peertube-plugin-` prefix to your plugin name (for example: `peertube-plugin-mysupername`)
632 * If you develop a theme, add `peertube-theme-` prefix to your theme name (for example: `peertube-theme-mysupertheme`)
633 * Clone the quickstart repository
634 * Configure your repository
636 * Update `package.json`
637 * Register hooks, add CSS and static files
638 * Test your plugin/theme with a local PeerTube installation
639 * Publish your plugin/theme on NPM
641 ### Clone the quickstart repository
643 If you develop a plugin, clone the `peertube-plugin-quickstart` repository:
646 $ git clone https://framagit.org/framasoft/peertube/peertube-plugin-quickstart.git peertube-plugin-mysupername
649 If you develop a theme, clone the `peertube-theme-quickstart` repository:
652 $ git clone https://framagit.org/framasoft/peertube/peertube-theme-quickstart.git peertube-theme-mysupername
655 ### Configure your repository
657 Set your repository URL:
660 $ cd peertube-plugin-mysupername # or cd peertube-theme-mysupername
661 $ git remote set-url origin https://your-git-repo
666 Update `README.md` file:
672 ### Update package.json
674 Update the `package.json` fields:
675 * `name` (should start with `peertube-plugin-` or `peertube-theme-`)
680 * `engine.peertube` (the PeerTube version compatibility, must be `>=x.y.z` and nothing else)
682 **Caution:** Don't update or remove other keys, or PeerTube will not be able to index/install your plugin.
683 If you don't need static directories, use an empty `object`:
693 And if you don't need CSS or client script files, use an empty `array`:
706 Now you can register hooks or settings, write CSS and add static directories to your plugin or your theme :)
708 **Caution:** It's up to you to check the code you write will be compatible with the PeerTube NodeJS version,
709 and will be supported by web browsers.
710 If you want to write modern JavaScript, please use a transpiler like [Babel](https://babeljs.io/).
714 If you want to translate strings of your plugin (like labels of your registered settings), create a file and add it to `package.json`:
720 "fr-FR": "./languages/fr.json",
721 "pt-BR": "./languages/pt-BR.json"
727 The key should be one of the locales defined in [i18n.ts](https://github.com/Chocobozzz/PeerTube/blob/develop/shared/models/i18n/i18n.ts).
728 You **must** use the complete locales (`fr-FR` instead of `fr`).
730 Translation files are just objects, with the english sentence as the key and the translation as the value.
731 `fr.json` could contain for example:
735 "Hello world": "Hello le monde"
739 ### Build your plugin
741 If you added client scripts, you'll need to build them using webpack.
749 Add/update your files in the `clientFiles` array of `webpack.config.js`:
752 $ $EDITOR ./webpack.config.js
755 Build your client files:
761 You built files are in the `dist/` directory. Check `package.json` to correctly point to them.
764 ### Test your plugin/theme
766 You'll need to have a local PeerTube instance:
767 * Follow the [dev prerequisites](https://github.com/Chocobozzz/PeerTube/blob/develop/.github/CONTRIBUTING.md#prerequisites)
768 (to clone the repository, install dependencies and prepare the database)
769 * Build PeerTube (`--light` to only build the english language):
772 $ npm run build -- --light
781 * Run PeerTube (you can access to your instance on http://localhost:9000):
784 $ NODE_ENV=test npm start
787 * Register the instance via the CLI:
790 $ node ./dist/server/tools/peertube.js auth add -u 'http://localhost:9000' -U 'root' --password 'test'
793 Then, you can install or reinstall your local plugin/theme by running:
796 $ node ./dist/server/tools/peertube.js plugins install --path /your/absolute/plugin-or-theme/path
801 Go in your plugin/theme directory, and run:
807 Every time you want to publish another version of your plugin/theme, just update the `version` key from the `package.json`
808 and republish it on NPM. Remember that the PeerTube index will take into account your new plugin/theme version after ~24 hours.
811 ## Plugin & Theme hooks/helpers API
813 See the dedicated documentation: https://docs.joinpeertube.org/api-plugins
818 ### Compatibility with PeerTube
820 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`).
822 * Don't make assumptions and check every parameter you want to use. For example:
826 target: 'filter:api.video.get.result',
828 // We check the parameter exists and the name field exists too, to avoid exceptions
829 if (video && video.name) video.name += ' <3'
835 * 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)
836 * Don't use PeerTube dependencies. Use your own :)
838 If your plugin is broken with a new PeerTube release, update your code and the `peertubeEngine` field of your `package.json` field.
839 This way, older PeerTube versions will still use your old plugin, and new PeerTube versions will use your updated plugin.
841 ### Spam/moderation plugin
843 If you want to create an antispam/moderation plugin, you could use the following hooks:
844 * `filter:api.video.upload.accept.result`: to accept or not local uploads
845 * `filter:api.video-thread.create.accept.result`: to accept or not local thread
846 * `filter:api.video-comment-reply.create.accept.result`: to accept or not local replies
847 * `filter:api.video-threads.list.result`: to change/hide the text of threads
848 * `filter:api.video-thread-comments.list.result`: to change/hide the text of replies
849 * `filter:video.auto-blacklist.result`: to automatically blacklist local or remote videos
851 ### Other plugin examples
853 You can take a look to "official" PeerTube plugins if you want to take inspiration from them: https://framagit.org/framasoft/peertube/official-plugins