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 - [Auth header](#auth-header)
24 - [Plugin router route](#plugin-router-route)
25 - [Custom Modal](#custom-modal)
26 - [Translate](#translate)
27 - [Get public settings](#get-public-settings)
28 - [Get server config](#get-server-config)
29 - [Add custom fields to video form](#add-custom-fields-to-video-form)
30 - [Register settings script](#register-settings-script)
31 - [HTML placeholder elements](#html-placeholder-elements)
32 - [Publishing](#publishing)
33 - [Write a plugin/theme](#write-a-plugintheme)
34 - [Clone the quickstart repository](#clone-the-quickstart-repository)
35 - [Configure your repository](#configure-your-repository)
36 - [Update README](#update-readme)
37 - [Update package.json](#update-packagejson)
38 - [Write code](#write-code)
39 - [Add translations](#add-translations)
40 - [Build your plugin](#build-your-plugin)
41 - [Test your plugin/theme](#test-your-plugintheme)
43 - [Unpublish](#unpublish)
44 - [Plugin & Theme hooks/helpers API](#plugin--theme-hookshelpers-api)
46 - [Compatibility with PeerTube](#compatibility-with-peertube)
47 - [Spam/moderation plugin](#spammoderation-plugin)
48 - [Other plugin examples](#other-plugin-examples)
50 <!-- END doctoc generated TOC please keep comment here to allow auto update -->
54 Themes are exactly the same as plugins, except that:
55 * Their name starts with `peertube-theme-` instead of `peertube-plugin-`
56 * They cannot declare server code (so they cannot register server hooks or settings)
57 * CSS files are loaded by client only if the theme is chosen by the administrator or the user
61 A plugin registers functions in JavaScript to execute when PeerTube (server and client) fires events. There are 3 types of hooks:
62 * `filter`: used to filter functions parameters or return values.
63 For example to replace words in video comments, or change the videos list behaviour
64 * `action`: used to do something after a certain trigger. For example to send a hook every time a video is published
65 * `static`: same than `action` but PeerTube waits their execution
67 On server side, these hooks are registered by the `library` file defined in `package.json`.
72 "library": "./main.js",
77 And `main.js` defines a `register` function:
82 async function register ({
99 unregisterExternalAuth,
100 registerIdAndPassAuth,
101 unregisterIdAndPassAuth
104 target: 'action:application.listening',
105 handler: () => displayHelloWorld()
111 On client side, these hooks are registered by the `clientScripts` files defined in `package.json`.
112 All client scripts have scopes so PeerTube client only loads scripts it needs:
119 "script": "client/common-client-plugin.js",
120 "scopes": [ "common" ]
123 "script": "client/video-watch-client-plugin.js",
124 "scopes": [ "video-watch" ]
131 And these scripts also define a `register` function:
134 function register ({ registerHook, peertubeHelpers }) {
136 target: 'action:application.init',
137 handler: () => onApplicationInit(peertubeHelpers)
144 Plugins can declare static directories that PeerTube will serve (images for example)
145 from `/plugins/{plugin-name}/{plugin-version}/static/`
146 or `/themes/{theme-name}/{theme-version}/static/` routes.
150 Plugins can declare CSS files that PeerTube will automatically inject in the client.
151 If you need to override existing style, you can use the `#custom-css` selector:
158 #custom-css .header {
159 background-color: red;
163 ### Server API (only for plugins)
167 Plugins can register settings, that PeerTube will inject in the administration interface.
168 The following fields will be automatically translated using the plugin translation files: `label`, `html`, `descriptionHTML`, `options.label`.
169 **These fields are injected in the plugin settings page as HTML, so pay attention to your translation files.**
174 function register (...) {
180 // type: 'input' | 'input-checkbox' | 'input-password' | 'input-textarea' | 'markdown-text' | 'markdown-enhanced' | 'select' | 'html'
183 descriptionHTML: 'The purpose of this field is...',
185 default: 'my super name',
187 // If the setting is not private, anyone can view its value (client code included)
188 // If the setting is private, only server-side hooks can access it
192 const adminName = await settingsManager.getSetting('admin-name')
194 const result = await settingsManager.getSettings([ 'admin-name', 'admin-password' ])
197 settingsManager.onSettingsChange(settings => {
198 settings['admin-name])
205 Plugins can store/load JSON data, that PeerTube will store in its database (so don't put files in there).
213 const value = await storageManager.getData('mykey')
214 await storageManager.storeData('mykey', { subkey: 'value' })
218 You can also store files in the plugin data directory (`/{plugins-directory}/data/{npm-plugin-name}`) **in PeerTube >= 3.2**.
219 This directory and its content won't be deleted when your plugin is uninstalled/upgraded.
226 const basePath = peertubeHelpers.plugin.getDataDirectoryPath()
228 fs.writeFile(path.join(basePath, 'filename.txt'), 'content of my file', function (err) {
234 #### Update video constants
236 You can add/delete video categories, licences or languages using the appropriate managers:
239 function register (...) {
240 videoLanguageManager.addLanguage('al_bhed', 'Al Bhed')
241 videoLanguageManager.deleteLanguage('fr')
243 videoCategoryManager.addCategory(42, 'Best category')
244 videoCategoryManager.deleteCategory(1) // Music
246 videoLicenceManager.addLicence(42, 'Best licence')
247 videoLicenceManager.deleteLicence(7) // Public domain
249 videoPrivacyManager.deletePrivacy(2) // Remove Unlisted video privacy
250 playlistPrivacyManager.deletePlaylistPrivacy(3) // Remove Private video playlist privacy
254 #### Add custom routes
256 You can create custom routes using an [express Router](https://expressjs.com/en/4x/api.html#router) for your plugin:
262 const router = getRouter()
263 router.get('/ping', (req, res) => res.json({ message: 'pong' }))
265 // Users are automatically authenticated
266 router.get('/auth', async (res, res) => {
267 const user = await peertubeHelpers.user.getAuthUser(res)
269 const isAdmin = user.role === 0
270 const isModerator = user.role === 1
271 const isUser = user.role === 2
274 username: user.username,
283 The `ping` route can be accessed using:
284 * `/plugins/:pluginName/:pluginVersion/router/ping`
285 * Or `/plugins/:pluginName/router/ping`
288 #### Add external auth methods
290 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):
293 function register (...) {
295 registerIdAndPassAuth({
296 authName: 'my-auth-method',
298 // PeerTube will try all id and pass plugins in the weight DESC order
299 // Exposing this value in the plugin settings could be interesting
302 // Optional function called by PeerTube when the user clicked on the logout button
304 console.log('User %s logged out.', user.username')
307 // Optional function called by PeerTube when the access token or refresh token are generated/refreshed
308 hookTokenValidity: ({ token, type }) => {
309 if (type === 'access') return { valid: true }
310 if (type === 'refresh') return { valid: false }
313 // Used by PeerTube when the user tries to authenticate
314 login: ({ id, password }) => {
315 if (id === 'user' && password === 'super password') {
318 email: 'user@example.com'
320 displayName: 'User display name'
329 // Unregister this auth method
330 unregisterIdAndPassAuth('my-auth-method')
334 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):
337 function register (...) {
339 // result contains the userAuthenticated auth method you can call to authenticate a user
340 const result = registerExternalAuth({
341 authName: 'my-auth-method',
343 // Will be displayed in a button next to the login form
344 authDisplayName: () => 'Auth method'
346 // If the user click on the auth button, PeerTube will forward the request in this function
347 onAuthRequest: (req, res) => {
348 res.redirect('https://external-auth.example.com/auth')
351 // Same than registerIdAndPassAuth option
354 // Same than registerIdAndPassAuth option
355 // hookTokenValidity: ...
358 router.use('/external-auth-callback', (req, res) => {
359 // Forward the request to PeerTube
360 result.userAuthenticated({
364 email: 'user@example.com'
366 displayName: 'User display name'
370 // Unregister this external auth method
371 unregisterExternalAuth('my-auth-method)
375 #### Add new transcoding profiles
377 Adding transcoding profiles allow admins to change ffmpeg encoding parameters and/or encoders.
378 A transcoding profile has to be chosen by the admin of the instance using the admin configuration.
381 async function register ({
385 // Adapt bitrate when using libx264 encoder
387 const builder = (options) => {
388 const { input, resolution, fps, streamNum } = options
390 const streamString = streamNum ? ':' + streamNum : ''
392 // You can also return a promise
393 // All these options are optional
396 // Used to define an alternative scale filter, needed by some encoders
397 // Default to 'scale'
404 // Use a custom bitrate
405 '-b' + streamString + ' 10K'
410 const encoder = 'libx264'
411 const profileName = 'low-quality'
413 // Support this profile for VOD transcoding
414 transcodingManager.addVODProfile(encoder, profileName, builder)
416 // And/Or support this profile for live transcoding
417 transcodingManager.addLiveProfile(encoder, profileName, builder)
421 const builder = (options) => {
422 const { streamNum } = options
424 const streamString = streamNum ? ':' + streamNum : ''
426 // Always copy stream when PeerTube use libfdk_aac or aac encoders
432 const profileName = 'copy-audio'
434 for (const encoder of [ 'libfdk_aac', 'aac' ]) {
435 transcodingManager.addVODProfile(encoder, profileName, builder)
440 PeerTube will try different encoders depending on their priority.
441 If the encoder is not available in the current transcoding profile or in ffmpeg, it tries the next one.
442 Plugins can change the order of these encoders and add their custom encoders:
445 async function register ({
449 // Adapt bitrate when using libx264 encoder
451 const builder = () => {
458 // Support libopus and libvpx-vp9 encoders (these codecs could be incompatible with the player)
459 transcodingManager.addVODProfile('libopus', 'test-vod-profile', builder)
461 // Default priorities are ~100
462 // Lowest priority = 1
463 transcodingManager.addVODEncoderPriority('audio', 'libopus', 1000)
465 transcodingManager.addVODProfile('libvpx-vp9', 'test-vod-profile', builder)
466 transcodingManager.addVODEncoderPriority('video', 'libvpx-vp9', 1000)
468 transcodingManager.addLiveProfile('libopus', 'test-live-profile', builder)
469 transcodingManager.addLiveEncoderPriority('audio', 'libopus', 1000)
473 During live transcode input options are applied once for each target resolution.
474 Plugins are responsible for detecting such situation and applying input options only once if necessary.
478 PeerTube provides your plugin some helpers. For example:
481 async function register ({
486 const serverActor = await peertubeHelpers.server.getServerActor()
488 await peertubeHelpers.moderation.blockServer({ byAccountId: serverActor.Account.id, hostToBlock: '...' })
493 const video = await peertubeHelpers.videos.loadByUrl('...')
498 See the [plugin API reference](https://docs.joinpeertube.org/api-plugins) to see the complete helpers list.
500 ### Client API (themes & plugins)
502 #### Plugin static route
504 To get your plugin static route:
507 function register (...) {
508 const baseStaticUrl = peertubeHelpers.getBaseStaticRoute()
509 const imageUrl = baseStaticUrl + '/images/chocobo.png'
515 To notify the user with the PeerTube ToastModule:
518 function register (...) {
519 const { notifier } = peertubeHelpers
520 notifier.success('Success message content.')
521 notifier.error('Error message content.')
525 #### Markdown Renderer
527 To render a formatted markdown text to HTML:
530 function register (...) {
531 const { markdownRenderer } = peertubeHelpers
533 await markdownRenderer.textMarkdownToHTML('**My Bold Text**')
534 // return <strong>My Bold Text</strong>
536 await markdownRenderer.enhancedMarkdownToHTML('![alt-img](http://.../my-image.jpg)')
537 // return <img alt=alt-img src=http://.../my-image.jpg />
545 To make your own HTTP requests using the current authenticated user, use an helper to automatically set appropriate headers:
548 function register (...) {
550 target: 'action:auth-user.information-loaded',
551 handler: ({ user }) => {
553 // Useless because we have the same info in the ({ user }) parameter
554 // It's just an example
555 fetch('/api/v1/users/me', {
557 headers: peertubeHelpers.getAuthHeader()
558 }).then(res => res.json())
559 .then(data => console.log('Hi %s.', data.username))
565 #### Plugin router route
569 To get your plugin router route, you can use `peertubeHelpers.getBaseRouterRoute()`:
572 function register (...) {
574 target: 'action:video-watch.video.loaded',
575 handler: ({ video }) => {
576 fetch(peertubeHelpers.getBaseRouterRoute() + '/my/plugin/api', {
578 headers: peertubeHelpers.getAuthHeader()
579 }).then(res => res.json())
580 .then(data => console.log('Hi %s.', data))
588 To show a custom modal:
591 function register (...) {
592 peertubeHelpers.showModal({
593 title: 'My custom modal title',
594 content: '<p>My custom modal content</p>',
595 // Optionals parameters :
598 // show cancel button and call action() after hiding modal
599 cancel: { value: 'cancel', action: () => {} },
600 // show confirm button and call action() after hiding modal
601 confirm: { value: 'confirm', action: () => {} },
608 You can translate some strings of your plugin (PeerTube will use your `translations` object of your `package.json` file):
611 function register (...) {
612 peertubeHelpers.translate('User name')
613 .then(translation => console.log('Translated User name by ' + translation))
617 #### Get public settings
619 To get your public plugin settings:
622 function register (...) {
623 peertubeHelpers.getSettings()
625 if (!s || !s['site-id'] || !s['url']) {
626 console.error('Matomo settings are not set.')
635 #### Get server config
638 function register (...) {
639 peertubeHelpers.getServerConfig()
641 console.log('Fetched server config.', config)
646 #### Add custom fields to video form
648 To add custom fields in the video form (in *Plugin settings* tab):
651 async function register ({ registerVideoField, peertubeHelpers }) {
652 const descriptionHTML = await peertubeHelpers.translate(descriptionSource)
653 const commonOptions = {
654 name: 'my-field-name,
655 label: 'My added field',
656 descriptionHTML: 'Optional description',
657 type: 'input-textarea',
659 // Optional, to hide a field depending on the current form state
660 // liveVideo is in the options object when the user is creating/updating a live
661 // videoToUpdate is in the options object when the user is updating a video
662 hidden: ({ formValues, videoToUpdate, liveVideo }) => {
663 return formValues.pluginData['other-field'] === 'toto'
667 for (const type of [ 'upload', 'import-url', 'import-torrent', 'update', 'go-live' ]) {
668 registerVideoField(commonOptions, { type })
673 PeerTube will send this field value in `body.pluginData['my-field-name']` and fetch it from `video.pluginData['my-field-name']`.
675 So for example, if you want to store an additional metadata for videos, register the following hooks in **server**:
678 async function register ({
682 const fieldName = 'my-field-name'
684 // Store data associated to this video
686 target: 'action:api.video.updated',
687 handler: ({ video, body }) => {
688 if (!body.pluginData) return
690 const value = body.pluginData[fieldName]
693 storageManager.storeData(fieldName + '-' + video.id, value)
697 // Add your custom value to the video, so the client autofill your field using the previously stored value
699 target: 'filter:api.video.get.result',
700 handler: async (video) => {
701 if (!video) return video
702 if (!video.pluginData) video.pluginData = {}
704 const result = await storageManager.getData(fieldName + '-' + video.id)
705 video.pluginData[fieldName] = result
713 #### Register settings script
715 To hide some fields in your settings plugin page depending on the form state:
718 async function register ({ registerSettingsScript }) {
719 registerSettingsScript({
720 isSettingHidden: options => {
721 if (options.setting.name === 'my-setting' && options.formValues['field45'] === '2') {
731 #### HTML placeholder elements
733 PeerTube provides some HTML id so plugins can easily insert their own element:
736 async function register (...) {
737 const elem = document.createElement('div')
738 elem.className = 'hello-world-h4'
739 elem.innerHTML = '<h4>Hello everybody! This is an element next to the player</h4>'
741 document.getElementById('plugin-placeholder-player-next').appendChild(elem)
745 See the complete list on https://docs.joinpeertube.org/api-plugins
749 PeerTube plugins and themes should be published on [NPM](https://www.npmjs.com/) so that PeerTube indexes
750 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).
752 ## Write a plugin/theme
755 * Find a name for your plugin or your theme (must not have spaces, it can only contain lowercase letters and `-`)
756 * Add the appropriate prefix:
757 * If you develop a plugin, add `peertube-plugin-` prefix to your plugin name (for example: `peertube-plugin-mysupername`)
758 * If you develop a theme, add `peertube-theme-` prefix to your theme name (for example: `peertube-theme-mysupertheme`)
759 * Clone the quickstart repository
760 * Configure your repository
762 * Update `package.json`
763 * Register hooks, add CSS and static files
764 * Test your plugin/theme with a local PeerTube installation
765 * Publish your plugin/theme on NPM
767 ### Clone the quickstart repository
769 If you develop a plugin, clone the `peertube-plugin-quickstart` repository:
772 $ git clone https://framagit.org/framasoft/peertube/peertube-plugin-quickstart.git peertube-plugin-mysupername
775 If you develop a theme, clone the `peertube-theme-quickstart` repository:
778 $ git clone https://framagit.org/framasoft/peertube/peertube-theme-quickstart.git peertube-theme-mysupername
781 ### Configure your repository
783 Set your repository URL:
786 $ cd peertube-plugin-mysupername # or cd peertube-theme-mysupername
787 $ git remote set-url origin https://your-git-repo
792 Update `README.md` file:
798 ### Update package.json
800 Update the `package.json` fields:
801 * `name` (should start with `peertube-plugin-` or `peertube-theme-`)
806 * `engine.peertube` (the PeerTube version compatibility, must be `>=x.y.z` and nothing else)
808 **Caution:** Don't update or remove other keys, or PeerTube will not be able to index/install your plugin.
809 If you don't need static directories, use an empty `object`:
819 And if you don't need CSS or client script files, use an empty `array`:
832 Now you can register hooks or settings, write CSS and add static directories to your plugin or your theme :)
834 **Caution:** It's up to you to check the code you write will be compatible with the PeerTube NodeJS version,
835 and will be supported by web browsers.
836 If you want to write modern JavaScript, please use a transpiler like [Babel](https://babeljs.io/).
840 If you want to translate strings of your plugin (like labels of your registered settings), create a file and add it to `package.json`:
846 "fr": "./languages/fr.json",
847 "pt-BR": "./languages/pt-BR.json"
853 The key should be one of the locales defined in [i18n.ts](https://github.com/Chocobozzz/PeerTube/blob/develop/shared/models/i18n/i18n.ts).
855 Translation files are just objects, with the english sentence as the key and the translation as the value.
856 `fr.json` could contain for example:
860 "Hello world": "Hello le monde"
864 ### Build your plugin
866 If you added client scripts, you'll need to build them using webpack.
874 Add/update your files in the `clientFiles` array of `webpack.config.js`:
877 $ $EDITOR ./webpack.config.js
880 Build your client files:
886 You built files are in the `dist/` directory. Check `package.json` to correctly point to them.
889 ### Test your plugin/theme
891 You'll need to have a local PeerTube instance:
892 * Follow the [dev prerequisites](https://github.com/Chocobozzz/PeerTube/blob/develop/.github/CONTRIBUTING.md#prerequisites)
893 (to clone the repository, install dependencies and prepare the database)
894 * Build PeerTube (`--light` to only build the english language):
897 $ npm run build -- --light
906 * Run PeerTube (you can access to your instance on http://localhost:9000):
909 $ NODE_ENV=test npm start
912 * Register the instance via the CLI:
915 $ node ./dist/server/tools/peertube.js auth add -u 'http://localhost:9000' -U 'root' --password 'test'
918 Then, you can install or reinstall your local plugin/theme by running:
921 $ node ./dist/server/tools/peertube.js plugins install --path /your/absolute/plugin-or-theme/path
926 Go in your plugin/theme directory, and run:
932 Every time you want to publish another version of your plugin/theme, just update the `version` key from the `package.json`
933 and republish it on NPM. Remember that the PeerTube index will take into account your new plugin/theme version after ~24 hours.
937 If for a particular reason you don't want to maintain your plugin/theme anymore
938 you can deprecate it. The plugin index will automatically remove it preventing users to find/install it from the PeerTube admin interface:
941 $ npm deprecate peertube-plugin-xxx@"> 0.0.0" "explain here why you deprecate your plugin/theme"
944 ## Plugin & Theme hooks/helpers API
946 See the dedicated documentation: https://docs.joinpeertube.org/api-plugins
951 ### Compatibility with PeerTube
953 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`).
955 * Don't make assumptions and check every parameter you want to use. For example:
959 target: 'filter:api.video.get.result',
961 // We check the parameter exists and the name field exists too, to avoid exceptions
962 if (video && video.name) video.name += ' <3'
968 * 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)
969 * Don't use PeerTube dependencies. Use your own :)
971 If your plugin is broken with a new PeerTube release, update your code and the `peertubeEngine` field of your `package.json` field.
972 This way, older PeerTube versions will still use your old plugin, and new PeerTube versions will use your updated plugin.
974 ### Spam/moderation plugin
976 If you want to create an antispam/moderation plugin, you could use the following hooks:
977 * `filter:api.video.upload.accept.result`: to accept or not local uploads
978 * `filter:api.video-thread.create.accept.result`: to accept or not local thread
979 * `filter:api.video-comment-reply.create.accept.result`: to accept or not local replies
980 * `filter:api.video-threads.list.result`: to change/hide the text of threads
981 * `filter:api.video-thread-comments.list.result`: to change/hide the text of replies
982 * `filter:video.auto-blacklist.result`: to automatically blacklist local or remote videos
984 ### Other plugin examples
986 You can take a look to "official" PeerTube plugins if you want to take inspiration from them: https://framagit.org/framasoft/peertube/official-plugins