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 - [Custom Modal](#custom-modal)
25 - [Translate](#translate)
26 - [Get public settings](#get-public-settings)
27 - [Get server config](#get-server-config)
28 - [Add custom fields to video form](#add-custom-fields-to-video-form)
29 - [Register settings script](#register-settings-script)
30 - [HTML placeholder elements](#html-placeholder-elements)
31 - [Publishing](#publishing)
32 - [Write a plugin/theme](#write-a-plugintheme)
33 - [Clone the quickstart repository](#clone-the-quickstart-repository)
34 - [Configure your repository](#configure-your-repository)
35 - [Update README](#update-readme)
36 - [Update package.json](#update-packagejson)
37 - [Write code](#write-code)
38 - [Add translations](#add-translations)
39 - [Build your plugin](#build-your-plugin)
40 - [Test your plugin/theme](#test-your-plugintheme)
42 - [Plugin & Theme hooks/helpers API](#plugin--theme-hookshelpers-api)
44 - [Compatibility with PeerTube](#compatibility-with-peertube)
45 - [Spam/moderation plugin](#spammoderation-plugin)
46 - [Other plugin examples](#other-plugin-examples)
48 <!-- END doctoc generated TOC please keep comment here to allow auto update -->
52 Themes are exactly the same as plugins, except that:
53 * Their name starts with `peertube-theme-` instead of `peertube-plugin-`
54 * They cannot declare server code (so they cannot register server hooks or settings)
55 * CSS files are loaded by client only if the theme is chosen by the administrator or the user
59 A plugin registers functions in JavaScript to execute when PeerTube (server and client) fires events. There are 3 types of hooks:
60 * `filter`: used to filter functions parameters or return values.
61 For example to replace words in video comments, or change the videos list behaviour
62 * `action`: used to do something after a certain trigger. For example to send a hook every time a video is published
63 * `static`: same than `action` but PeerTube waits their execution
65 On server side, these hooks are registered by the `library` file defined in `package.json`.
70 "library": "./main.js",
75 And `main.js` defines a `register` function:
80 async function register ({
97 unregisterExternalAuth,
98 registerIdAndPassAuth,
99 unregisterIdAndPassAuth
102 target: 'action:application.listening',
103 handler: () => displayHelloWorld()
109 On client side, these hooks are registered by the `clientScripts` files defined in `package.json`.
110 All client scripts have scopes so PeerTube client only loads scripts it needs:
117 "script": "client/common-client-plugin.js",
118 "scopes": [ "common" ]
121 "script": "client/video-watch-client-plugin.js",
122 "scopes": [ "video-watch" ]
129 And these scripts also define a `register` function:
132 function register ({ registerHook, peertubeHelpers }) {
134 target: 'action:application.init',
135 handler: () => onApplicationInit(peertubeHelpers)
142 Plugins can declare static directories that PeerTube will serve (images for example)
143 from `/plugins/{plugin-name}/{plugin-version}/static/`
144 or `/themes/{theme-name}/{theme-version}/static/` routes.
148 Plugins can declare CSS files that PeerTube will automatically inject in the client.
149 If you need to override existing style, you can use the `#custom-css` selector:
156 #custom-css .header {
157 background-color: red;
161 ### Server API (only for plugins)
165 Plugins can register settings, that PeerTube will inject in the administration interface.
166 The following fields will be automatically translated using the plugin translation files: `label`, `html`, `descriptionHTML`, `options.label`.
167 **These fields are injected in the plugin settings page as HTML, so pay attention to your translation files.**
172 function register (...) {
177 // type: input | input-checkbox | input-password | input-textarea | markdown-text | markdown-enhanced | 'select' | 'html'
178 default: 'my super name'
181 const adminName = await settingsManager.getSetting('admin-name')
183 const result = await settingsManager.getSettings([ 'admin-name', 'admin-password' ])
186 settingsManager.onSettingsChange(settings => {
187 settings['admin-name])
194 Plugins can store/load JSON data, that PeerTube will store in its database (so don't put files in there).
202 const value = await storageManager.getData('mykey')
203 await storageManager.storeData('mykey', { subkey: 'value' })
207 You can also store files in the plugin data directory (`/{plugins-directory}/data/{npm-plugin-name}`) **in PeerTube >= 3.2**.
208 This directory and its content won't be deleted when your plugin is uninstalled/upgraded.
215 const basePath = peertubeHelpers.plugin.getDataDirectoryPath()
217 fs.writeFile(path.join(basePath, 'filename.txt'), 'content of my file', function (err) {
223 #### Update video constants
225 You can add/delete video categories, licences or languages using the appropriate managers:
228 function register (...) {
229 videoLanguageManager.addLanguage('al_bhed', 'Al Bhed')
230 videoLanguageManager.deleteLanguage('fr')
232 videoCategoryManager.addCategory(42, 'Best category')
233 videoCategoryManager.deleteCategory(1) // Music
235 videoLicenceManager.addLicence(42, 'Best licence')
236 videoLicenceManager.deleteLicence(7) // Public domain
238 videoPrivacyManager.deletePrivacy(2) // Remove Unlisted video privacy
239 playlistPrivacyManager.deletePlaylistPrivacy(3) // Remove Private video playlist privacy
243 #### Add custom routes
245 You can create custom routes using an [express Router](https://expressjs.com/en/4x/api.html#router) for your plugin:
251 const router = getRouter()
252 router.get('/ping', (req, res) => res.json({ message: 'pong' }))
254 // Users are automatically authenticated
255 router.get('/auth', (res, res) => {
256 const user = peertubeHelpers.user.getAuthUser(res)
258 const isAdmin = user.role === 0
259 const isModerator = user.role === 1
260 const isUser = user.role === 2
263 username: user.username,
272 The `ping` route can be accessed using:
273 * `/plugins/:pluginName/:pluginVersion/router/ping`
274 * Or `/plugins/:pluginName/router/ping`
277 #### Add external auth methods
279 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):
282 function register (...) {
284 registerIdAndPassAuth({
285 authName: 'my-auth-method',
287 // PeerTube will try all id and pass plugins in the weight DESC order
288 // Exposing this value in the plugin settings could be interesting
291 // Optional function called by PeerTube when the user clicked on the logout button
293 console.log('User %s logged out.', user.username')
296 // Optional function called by PeerTube when the access token or refresh token are generated/refreshed
297 hookTokenValidity: ({ token, type }) => {
298 if (type === 'access') return { valid: true }
299 if (type === 'refresh') return { valid: false }
302 // Used by PeerTube when the user tries to authenticate
303 login: ({ id, password }) => {
304 if (id === 'user' && password === 'super password') {
307 email: 'user@example.com'
309 displayName: 'User display name'
318 // Unregister this auth method
319 unregisterIdAndPassAuth('my-auth-method')
323 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):
326 function register (...) {
328 // result contains the userAuthenticated auth method you can call to authenticate a user
329 const result = registerExternalAuth({
330 authName: 'my-auth-method',
332 // Will be displayed in a button next to the login form
333 authDisplayName: () => 'Auth method'
335 // If the user click on the auth button, PeerTube will forward the request in this function
336 onAuthRequest: (req, res) => {
337 res.redirect('https://external-auth.example.com/auth')
340 // Same than registerIdAndPassAuth option
343 // Same than registerIdAndPassAuth option
344 // hookTokenValidity: ...
347 router.use('/external-auth-callback', (req, res) => {
348 // Forward the request to PeerTube
349 result.userAuthenticated({
353 email: 'user@example.com'
355 displayName: 'User display name'
359 // Unregister this external auth method
360 unregisterExternalAuth('my-auth-method)
364 #### Add new transcoding profiles
366 Adding transcoding profiles allow admins to change ffmpeg encoding parameters and/or encoders.
367 A transcoding profile has to be chosen by the admin of the instance using the admin configuration.
370 async function register ({
374 // Adapt bitrate when using libx264 encoder
376 const builder = (options) => {
377 const { input, resolution, fps, streamNum } = options
379 const streamString = streamNum ? ':' + streamNum : ''
381 // You can also return a promise
382 // All these options are optional
385 // Used to define an alternative scale filter, needed by some encoders
386 // Default to 'scale'
393 // Use a custom bitrate
394 '-b' + streamString + ' 10K'
399 const encoder = 'libx264'
400 const profileName = 'low-quality'
402 // Support this profile for VOD transcoding
403 transcodingManager.addVODProfile(encoder, profileName, builder)
405 // And/Or support this profile for live transcoding
406 transcodingManager.addLiveProfile(encoder, profileName, builder)
410 const builder = (options) => {
411 const { streamNum } = options
413 const streamString = streamNum ? ':' + streamNum : ''
415 // Always copy stream when PeerTube use libfdk_aac or aac encoders
421 const profileName = 'copy-audio'
423 for (const encoder of [ 'libfdk_aac', 'aac' ]) {
424 transcodingManager.addVODProfile(encoder, profileName, builder)
429 PeerTube will try different encoders depending on their priority.
430 If the encoder is not available in the current transcoding profile or in ffmpeg, it tries the next one.
431 Plugins can change the order of these encoders and add their custom encoders:
434 async function register ({
438 // Adapt bitrate when using libx264 encoder
440 const builder = () => {
447 // Support libopus and libvpx-vp9 encoders (these codecs could be incompatible with the player)
448 transcodingManager.addVODProfile('libopus', 'test-vod-profile', builder)
450 // Default priorities are ~100
451 // Lowest priority = 1
452 transcodingManager.addVODEncoderPriority('audio', 'libopus', 1000)
454 transcodingManager.addVODProfile('libvpx-vp9', 'test-vod-profile', builder)
455 transcodingManager.addVODEncoderPriority('video', 'libvpx-vp9', 1000)
457 transcodingManager.addLiveProfile('libopus', 'test-live-profile', builder)
458 transcodingManager.addLiveEncoderPriority('audio', 'libopus', 1000)
462 During live transcode input options are applied once for each target resolution.
463 Plugins are responsible for detecting such situation and applying input options only once if necessary.
467 PeerTube provides your plugin some helpers. For example:
470 async function register ({
475 const serverActor = await peertubeHelpers.server.getServerActor()
477 await peertubeHelpers.moderation.blockServer({ byAccountId: serverActor.Account.id, hostToBlock: '...' })
482 const video = await peertubeHelpers.videos.loadByUrl('...')
487 See the [plugin API reference](https://docs.joinpeertube.org/api-plugins) to see the complete helpers list.
489 ### Client API (themes & plugins)
491 #### Plugin static route
493 To get your plugin static route:
496 function register (...) {
497 const baseStaticUrl = peertubeHelpers.getBaseStaticRoute()
498 const imageUrl = baseStaticUrl + '/images/chocobo.png'
504 To notify the user with the PeerTube ToastModule:
507 function register (...) {
508 const { notifier } = peertubeHelpers
509 notifier.success('Success message content.')
510 notifier.error('Error message content.')
514 #### Markdown Renderer
516 To render a formatted markdown text to HTML:
519 function register (...) {
520 const { markdownRenderer } = peertubeHelpers
522 await markdownRenderer.textMarkdownToHTML('**My Bold Text**')
523 // return <strong>My Bold Text</strong>
525 await markdownRenderer.enhancedMarkdownToHTML('![alt-img](http://.../my-image.jpg)')
526 // return <img alt=alt-img src=http://.../my-image.jpg />
534 To make your own HTTP requests using the current authenticated user, use an helper to automatically set appropriate headers:
537 function register (...) {
539 target: 'action:auth-user.information-loaded',
540 handler: ({ user }) => {
542 // Useless because we have the same info in the ({ user }) parameter
543 // It's just an example
544 fetch('/api/v1/users/me', {
546 headers: peertubeHelpers.getAuthHeader()
547 }).then(res => res.json())
548 .then(data => console.log('Hi %s.', data.username))
556 To show a custom modal:
559 function register (...) {
560 peertubeHelpers.showModal({
561 title: 'My custom modal title',
562 content: '<p>My custom modal content</p>',
563 // Optionals parameters :
566 // show cancel button and call action() after hiding modal
567 cancel: { value: 'cancel', action: () => {} },
568 // show confirm button and call action() after hiding modal
569 confirm: { value: 'confirm', action: () => {} },
576 You can translate some strings of your plugin (PeerTube will use your `translations` object of your `package.json` file):
579 function register (...) {
580 peertubeHelpers.translate('User name')
581 .then(translation => console.log('Translated User name by ' + translation))
585 #### Get public settings
587 To get your public plugin settings:
590 function register (...) {
591 peertubeHelpers.getSettings()
593 if (!s || !s['site-id'] || !s['url']) {
594 console.error('Matomo settings are not set.')
603 #### Get server config
606 function register (...) {
607 peertubeHelpers.getServerConfig()
609 console.log('Fetched server config.', config)
614 #### Add custom fields to video form
616 To add custom fields in the video form (in *Plugin settings* tab):
619 async function register ({ registerVideoField, peertubeHelpers }) {
620 const descriptionHTML = await peertubeHelpers.translate(descriptionSource)
621 const commonOptions = {
622 name: 'my-field-name,
623 label: 'My added field',
624 descriptionHTML: 'Optional description',
625 type: 'input-textarea',
627 // Optional, to hide a field depending on the current form state
628 // liveVideo is in the options object when the user is creating/updating a live
629 // videoToUpdate is in the options object when the user is updating a video
630 hidden: ({ formValues, videoToUpdate, liveVideo }) => {
631 return formValues.pluginData['other-field'] === 'toto'
635 for (const type of [ 'upload', 'import-url', 'import-torrent', 'update', 'go-live' ]) {
636 registerVideoField(commonOptions, { type })
641 PeerTube will send this field value in `body.pluginData['my-field-name']` and fetch it from `video.pluginData['my-field-name']`.
643 So for example, if you want to store an additional metadata for videos, register the following hooks in **server**:
646 async function register ({
650 const fieldName = 'my-field-name'
652 // Store data associated to this video
654 target: 'action:api.video.updated',
655 handler: ({ video, body }) => {
656 if (!body.pluginData) return
658 const value = body.pluginData[fieldName]
661 storageManager.storeData(fieldName + '-' + video.id, value)
665 // Add your custom value to the video, so the client autofill your field using the previously stored value
667 target: 'filter:api.video.get.result',
668 handler: async (video) => {
669 if (!video) return video
670 if (!video.pluginData) video.pluginData = {}
672 const result = await storageManager.getData(fieldName + '-' + video.id)
673 video.pluginData[fieldName] = result
681 #### Register settings script
683 To hide some fields in your settings plugin page depending on the form state:
686 async function register ({ registerSettingsScript }) {
687 registerSettingsScript({
688 isSettingHidden: options => {
689 if (options.setting.name === 'my-setting' && options.formValues['field45'] === '2') {
699 #### HTML placeholder elements
701 PeerTube provides some HTML id so plugins can easily insert their own element:
704 async function register (...) {
705 const elem = document.createElement('div')
706 elem.className = 'hello-world-h4'
707 elem.innerHTML = '<h4>Hello everybody! This is an element next to the player</h4>'
709 document.getElementById('plugin-placeholder-player-next').appendChild(elem)
713 See the complete list on https://docs.joinpeertube.org/api-plugins
717 PeerTube plugins and themes should be published on [NPM](https://www.npmjs.com/) so that PeerTube indexes
718 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).
720 ## Write a plugin/theme
723 * Find a name for your plugin or your theme (must not have spaces, it can only contain lowercase letters and `-`)
724 * Add the appropriate prefix:
725 * If you develop a plugin, add `peertube-plugin-` prefix to your plugin name (for example: `peertube-plugin-mysupername`)
726 * If you develop a theme, add `peertube-theme-` prefix to your theme name (for example: `peertube-theme-mysupertheme`)
727 * Clone the quickstart repository
728 * Configure your repository
730 * Update `package.json`
731 * Register hooks, add CSS and static files
732 * Test your plugin/theme with a local PeerTube installation
733 * Publish your plugin/theme on NPM
735 ### Clone the quickstart repository
737 If you develop a plugin, clone the `peertube-plugin-quickstart` repository:
740 $ git clone https://framagit.org/framasoft/peertube/peertube-plugin-quickstart.git peertube-plugin-mysupername
743 If you develop a theme, clone the `peertube-theme-quickstart` repository:
746 $ git clone https://framagit.org/framasoft/peertube/peertube-theme-quickstart.git peertube-theme-mysupername
749 ### Configure your repository
751 Set your repository URL:
754 $ cd peertube-plugin-mysupername # or cd peertube-theme-mysupername
755 $ git remote set-url origin https://your-git-repo
760 Update `README.md` file:
766 ### Update package.json
768 Update the `package.json` fields:
769 * `name` (should start with `peertube-plugin-` or `peertube-theme-`)
774 * `engine.peertube` (the PeerTube version compatibility, must be `>=x.y.z` and nothing else)
776 **Caution:** Don't update or remove other keys, or PeerTube will not be able to index/install your plugin.
777 If you don't need static directories, use an empty `object`:
787 And if you don't need CSS or client script files, use an empty `array`:
800 Now you can register hooks or settings, write CSS and add static directories to your plugin or your theme :)
802 **Caution:** It's up to you to check the code you write will be compatible with the PeerTube NodeJS version,
803 and will be supported by web browsers.
804 If you want to write modern JavaScript, please use a transpiler like [Babel](https://babeljs.io/).
808 If you want to translate strings of your plugin (like labels of your registered settings), create a file and add it to `package.json`:
814 "fr": "./languages/fr.json",
815 "pt-BR": "./languages/pt-BR.json"
821 The key should be one of the locales defined in [i18n.ts](https://github.com/Chocobozzz/PeerTube/blob/develop/shared/models/i18n/i18n.ts).
823 Translation files are just objects, with the english sentence as the key and the translation as the value.
824 `fr.json` could contain for example:
828 "Hello world": "Hello le monde"
832 ### Build your plugin
834 If you added client scripts, you'll need to build them using webpack.
842 Add/update your files in the `clientFiles` array of `webpack.config.js`:
845 $ $EDITOR ./webpack.config.js
848 Build your client files:
854 You built files are in the `dist/` directory. Check `package.json` to correctly point to them.
857 ### Test your plugin/theme
859 You'll need to have a local PeerTube instance:
860 * Follow the [dev prerequisites](https://github.com/Chocobozzz/PeerTube/blob/develop/.github/CONTRIBUTING.md#prerequisites)
861 (to clone the repository, install dependencies and prepare the database)
862 * Build PeerTube (`--light` to only build the english language):
865 $ npm run build -- --light
874 * Run PeerTube (you can access to your instance on http://localhost:9000):
877 $ NODE_ENV=test npm start
880 * Register the instance via the CLI:
883 $ node ./dist/server/tools/peertube.js auth add -u 'http://localhost:9000' -U 'root' --password 'test'
886 Then, you can install or reinstall your local plugin/theme by running:
889 $ node ./dist/server/tools/peertube.js plugins install --path /your/absolute/plugin-or-theme/path
894 Go in your plugin/theme directory, and run:
900 Every time you want to publish another version of your plugin/theme, just update the `version` key from the `package.json`
901 and republish it on NPM. Remember that the PeerTube index will take into account your new plugin/theme version after ~24 hours.
904 ## Plugin & Theme hooks/helpers API
906 See the dedicated documentation: https://docs.joinpeertube.org/api-plugins
911 ### Compatibility with PeerTube
913 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`).
915 * Don't make assumptions and check every parameter you want to use. For example:
919 target: 'filter:api.video.get.result',
921 // We check the parameter exists and the name field exists too, to avoid exceptions
922 if (video && video.name) video.name += ' <3'
928 * 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)
929 * Don't use PeerTube dependencies. Use your own :)
931 If your plugin is broken with a new PeerTube release, update your code and the `peertubeEngine` field of your `package.json` field.
932 This way, older PeerTube versions will still use your old plugin, and new PeerTube versions will use your updated plugin.
934 ### Spam/moderation plugin
936 If you want to create an antispam/moderation plugin, you could use the following hooks:
937 * `filter:api.video.upload.accept.result`: to accept or not local uploads
938 * `filter:api.video-thread.create.accept.result`: to accept or not local thread
939 * `filter:api.video-comment-reply.create.accept.result`: to accept or not local replies
940 * `filter:api.video-threads.list.result`: to change/hide the text of threads
941 * `filter:api.video-thread-comments.list.result`: to change/hide the text of replies
942 * `filter:video.auto-blacklist.result`: to automatically blacklist local or remote videos
944 ### Other plugin examples
946 You can take a look to "official" PeerTube plugins if you want to take inspiration from them: https://framagit.org/framasoft/peertube/official-plugins