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 -->
6 - [Concepts](#concepts)
8 - [Static files](#static-files)
10 - [Server API (only for plugins)](#server-api-only-for-plugins)
11 - [Settings](#settings)
13 - [Update video constants](#update-video-constants)
14 - [Add custom routes](#add-custom-routes)
15 - [Add custom WebSocket handlers](#add-custom-websocket-handlers)
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 - [Get plugin static and router routes](#get-plugin-static-and-router-routes)
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 - [Plugin selector on HTML elements](#plugin-selector-on-html-elements)
31 - [HTML placeholder elements](#html-placeholder-elements)
32 - [Add/remove left menu links](#addremove-left-menu-links)
33 - [Create client page](#create-client-page)
34 - [Publishing](#publishing)
35 - [Write a plugin/theme](#write-a-plugintheme)
36 - [Clone the quickstart repository](#clone-the-quickstart-repository)
37 - [Configure your repository](#configure-your-repository)
38 - [Update README](#update-readme)
39 - [Update package.json](#update-packagejson)
40 - [Write code](#write-code)
41 - [Add translations](#add-translations)
42 - [Build your plugin](#build-your-plugin)
43 - [Test your plugin/theme](#test-your-plugintheme)
45 - [Unpublish](#unpublish)
46 - [Plugin & Theme hooks/helpers API](#plugin--theme-hookshelpers-api)
48 - [Compatibility with PeerTube](#compatibility-with-peertube)
49 - [Spam/moderation plugin](#spammoderation-plugin)
50 - [Other plugin examples](#other-plugin-examples)
52 <!-- END doctoc generated TOC please keep comment here to allow auto update -->
56 Themes are exactly the same as plugins, except that:
57 * Their name starts with `peertube-theme-` instead of `peertube-plugin-`
58 * They cannot declare server code (so they cannot register server hooks or settings)
59 * CSS files are loaded by client only if the theme is chosen by the administrator or the user
63 A plugin registers functions in JavaScript to execute when PeerTube (server and client) fires events. There are 3 types of hooks:
64 * `filter`: used to filter functions parameters or return values.
65 For example to replace words in video comments, or change the videos list behaviour
66 * `action`: used to do something after a certain trigger. For example to send a hook every time a video is published
67 * `static`: same than `action` but PeerTube waits their execution
69 On server side, these hooks are registered by the `library` file defined in `package.json`.
74 "library": "./main.js",
79 And `main.js` defines a `register` function:
84 async function register ({
100 registerExternalAuth,
101 unregisterExternalAuth,
102 registerIdAndPassAuth,
103 unregisterIdAndPassAuth
106 target: 'action:application.listening',
107 handler: () => displayHelloWorld()
112 Hooks prefixed by `action:api` also give access the original **express** [Request](http://expressjs.com/en/api.html#req) and [Response](http://expressjs.com/en/api.html#res):
115 async function register ({
117 peertubeHelpers: { logger }
120 target: 'action:api.video.updated',
121 handler: ({ req, res }) => logger.debug('original request parameters', { params: req.params })
127 On client side, these hooks are registered by the `clientScripts` files defined in `package.json`.
128 All client scripts have scopes so PeerTube client only loads scripts it needs:
135 "script": "client/common-client-plugin.js",
136 "scopes": [ "common" ]
139 "script": "client/video-watch-client-plugin.js",
140 "scopes": [ "video-watch" ]
147 And these scripts also define a `register` function:
150 function register ({ registerHook, peertubeHelpers }) {
152 target: 'action:application.init',
153 handler: () => onApplicationInit(peertubeHelpers)
160 Plugins can declare static directories that PeerTube will serve (images for example)
161 from `/plugins/{plugin-name}/{plugin-version}/static/`
162 or `/themes/{theme-name}/{theme-version}/static/` routes.
166 Plugins can declare CSS files that PeerTube will automatically inject in the client.
167 If you need to override existing style, you can use the `#custom-css` selector:
174 #custom-css .header {
175 background-color: red;
179 ### Server API (only for plugins)
183 Plugins can register settings, that PeerTube will inject in the administration interface.
184 The following fields will be automatically translated using the plugin translation files: `label`, `html`, `descriptionHTML`, `options.label`.
185 **These fields are injected in the plugin settings page as HTML, so pay attention to your translation files.**
190 function register (...) {
196 // type: 'input' | 'input-checkbox' | 'input-password' | 'input-textarea' | 'markdown-text' | 'markdown-enhanced' | 'select' | 'html'
198 // If type: 'select', give the select available options
200 { label: 'Label 1', value: 'value1' },
201 { label: 'Label 2', value: 'value2' }
204 // If type: 'html', set the HTML that will be injected in the page
205 html: '<strong class="...">Hello</strong><br /><br />'
208 descriptionHTML: 'The purpose of this field is...',
210 default: 'my super name',
212 // If the setting is not private, anyone can view its value (client code included)
213 // If the setting is private, only server-side hooks can access it
217 const adminName = await settingsManager.getSetting('admin-name')
219 const result = await settingsManager.getSettings([ 'admin-name', 'admin-password' ])
222 settingsManager.onSettingsChange(settings => {
223 settings['admin-name']
230 Plugins can store/load JSON data, that PeerTube will store in its database (so don't put files in there).
238 const value = await storageManager.getData('mykey')
239 await storageManager.storeData('mykey', { subkey: 'value' })
243 You can also store files in the plugin data directory (`/{plugins-directory}/data/{npm-plugin-name}`) **in PeerTube >= 3.2**.
244 This directory and its content won't be deleted when your plugin is uninstalled/upgraded.
251 const basePath = peertubeHelpers.plugin.getDataDirectoryPath()
253 fs.writeFile(path.join(basePath, 'filename.txt'), 'content of my file', function (err) {
259 #### Update video constants
261 You can add/delete video categories, licences or languages using the appropriate constant managers:
265 videoLanguageManager,
266 videoCategoryManager,
269 playlistPrivacyManager
271 videoLanguageManager.addConstant('al_bhed', 'Al Bhed')
272 videoLanguageManager.deleteConstant('fr')
274 videoCategoryManager.addConstant(42, 'Best category')
275 videoCategoryManager.deleteConstant(1) // Music
276 videoCategoryManager.resetConstants() // Reset to initial categories
277 videoCategoryManager.getConstants() // Retrieve all category constants
279 videoLicenceManager.addConstant(42, 'Best licence')
280 videoLicenceManager.deleteConstant(7) // Public domain
282 videoPrivacyManager.deleteConstant(2) // Remove Unlisted video privacy
283 playlistPrivacyManager.deleteConstant(3) // Remove Private video playlist privacy
287 #### Add custom routes
289 You can create custom routes using an [express Router](https://expressjs.com/en/4x/api.html#router) for your plugin:
295 const router = getRouter()
296 router.get('/ping', (req, res) => res.json({ message: 'pong' }))
298 // Users are automatically authenticated
299 router.get('/auth', async (res, res) => {
300 const user = await peertubeHelpers.user.getAuthUser(res)
302 const isAdmin = user.role === 0
303 const isModerator = user.role === 1
304 const isUser = user.role === 2
307 username: user.username,
316 The `ping` route can be accessed using:
317 * `/plugins/:pluginName/:pluginVersion/router/ping`
318 * Or `/plugins/:pluginName/router/ping`
321 #### Add custom WebSocket handlers
325 You can create custom WebSocket servers (like [ws](https://github.com/websockets/ws) for example) using `registerWebSocketRoute`:
329 registerWebSocketRoute,
332 const wss = new WebSocketServer({ noServer: true })
334 wss.on('connection', function connection(ws) {
335 peertubeHelpers.logger.info('WebSocket connected!')
338 ws.send('WebSocket message sent by server');
342 registerWebSocketRoute({
343 route: '/my-websocket-route',
345 handler: (request, socket, head) => {
346 wss.handleUpgrade(request, socket, head, ws => {
347 wss.emit('connection', ws, request)
354 The `my-websocket-route` route can be accessed using:
355 * `/plugins/:pluginName/:pluginVersion/ws/my-websocket-route`
356 * Or `/plugins/:pluginName/ws/my-websocket-route`
358 #### Add external auth methods
360 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):
363 function register (...) {
365 registerIdAndPassAuth({
366 authName: 'my-auth-method',
368 // PeerTube will try all id and pass plugins in the weight DESC order
369 // Exposing this value in the plugin settings could be interesting
372 // Optional function called by PeerTube when the user clicked on the logout button
374 console.log('User %s logged out.', user.username')
377 // Optional function called by PeerTube when the access token or refresh token are generated/refreshed
378 hookTokenValidity: ({ token, type }) => {
379 if (type === 'access') return { valid: true }
380 if (type === 'refresh') return { valid: false }
383 // Used by PeerTube when the user tries to authenticate
384 login: ({ id, password }) => {
385 if (id === 'user' && password === 'super password') {
388 email: 'user@example.com'
390 displayName: 'User display name'
399 // Unregister this auth method
400 unregisterIdAndPassAuth('my-auth-method')
404 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):
407 function register (...) {
409 // result contains the userAuthenticated auth method you can call to authenticate a user
410 const result = registerExternalAuth({
411 authName: 'my-auth-method',
413 // Will be displayed in a button next to the login form
414 authDisplayName: () => 'Auth method'
416 // If the user click on the auth button, PeerTube will forward the request in this function
417 onAuthRequest: (req, res) => {
418 res.redirect('https://external-auth.example.com/auth')
421 // Same than registerIdAndPassAuth option
424 // Same than registerIdAndPassAuth option
425 // hookTokenValidity: ...
428 router.use('/external-auth-callback', (req, res) => {
429 // Forward the request to PeerTube
430 result.userAuthenticated({
434 email: 'user@example.com'
436 displayName: 'User display name'
440 // Unregister this external auth method
441 unregisterExternalAuth('my-auth-method)
445 #### Add new transcoding profiles
447 Adding transcoding profiles allow admins to change ffmpeg encoding parameters and/or encoders.
448 A transcoding profile has to be chosen by the admin of the instance using the admin configuration.
451 async function register ({
455 // Adapt bitrate when using libx264 encoder
457 const builder = (options) => {
458 const { input, resolution, fps, streamNum } = options
460 const streamString = streamNum ? ':' + streamNum : ''
462 // You can also return a promise
463 // All these options are optional
466 // Used to define an alternative scale filter, needed by some encoders
467 // Default to 'scale'
474 // Use a custom bitrate
475 '-b' + streamString + ' 10K'
480 const encoder = 'libx264'
481 const profileName = 'low-quality'
483 // Support this profile for VOD transcoding
484 transcodingManager.addVODProfile(encoder, profileName, builder)
486 // And/Or support this profile for live transcoding
487 transcodingManager.addLiveProfile(encoder, profileName, builder)
491 const builder = (options) => {
492 const { streamNum } = options
494 const streamString = streamNum ? ':' + streamNum : ''
496 // Always copy stream when PeerTube use libfdk_aac or aac encoders
502 const profileName = 'copy-audio'
504 for (const encoder of [ 'libfdk_aac', 'aac' ]) {
505 transcodingManager.addVODProfile(encoder, profileName, builder)
510 PeerTube will try different encoders depending on their priority.
511 If the encoder is not available in the current transcoding profile or in ffmpeg, it tries the next one.
512 Plugins can change the order of these encoders and add their custom encoders:
515 async function register ({
519 // Adapt bitrate when using libx264 encoder
521 const builder = () => {
528 // Support libopus and libvpx-vp9 encoders (these codecs could be incompatible with the player)
529 transcodingManager.addVODProfile('libopus', 'test-vod-profile', builder)
531 // Default priorities are ~100
532 // Lowest priority = 1
533 transcodingManager.addVODEncoderPriority('audio', 'libopus', 1000)
535 transcodingManager.addVODProfile('libvpx-vp9', 'test-vod-profile', builder)
536 transcodingManager.addVODEncoderPriority('video', 'libvpx-vp9', 1000)
538 transcodingManager.addLiveProfile('libopus', 'test-live-profile', builder)
539 transcodingManager.addLiveEncoderPriority('audio', 'libopus', 1000)
543 During live transcode input options are applied once for each target resolution.
544 Plugins are responsible for detecting such situation and applying input options only once if necessary.
548 PeerTube provides your plugin some helpers. For example:
551 async function register ({
556 const serverActor = await peertubeHelpers.server.getServerActor()
558 await peertubeHelpers.moderation.blockServer({ byAccountId: serverActor.Account.id, hostToBlock: '...' })
563 const video = await peertubeHelpers.videos.loadByUrl('...')
568 See the [plugin API reference](https://docs.joinpeertube.org/api-plugins) to see the complete helpers list.
570 ### Client API (themes & plugins)
572 #### Get plugin static and router routes
574 To get your plugin static route:
577 function register (...) {
578 const baseStaticUrl = peertubeHelpers.getBaseStaticRoute()
579 const imageUrl = baseStaticUrl + '/images/chocobo.png'
583 And to get your plugin router route, use `peertubeHelpers.getBaseRouterRoute()`:
586 function register (...) {
588 target: 'action:video-watch.video.loaded',
589 handler: ({ video }) => {
590 fetch(peertubeHelpers.getBaseRouterRoute() + '/my/plugin/api', {
592 headers: peertubeHelpers.getAuthHeader()
593 }).then(res => res.json())
594 .then(data => console.log('Hi %s.', data))
603 To notify the user with the PeerTube ToastModule:
606 function register (...) {
607 const { notifier } = peertubeHelpers
608 notifier.success('Success message content.')
609 notifier.error('Error message content.')
613 #### Markdown Renderer
615 To render a formatted markdown text to HTML:
618 function register (...) {
619 const { markdownRenderer } = peertubeHelpers
621 await markdownRenderer.textMarkdownToHTML('**My Bold Text**')
622 // return <strong>My Bold Text</strong>
624 await markdownRenderer.enhancedMarkdownToHTML('![alt-img](http://.../my-image.jpg)')
625 // return <img alt=alt-img src=http://.../my-image.jpg />
633 To make your own HTTP requests using the current authenticated user, use an helper to automatically set appropriate headers:
636 function register (...) {
638 target: 'action:auth-user.information-loaded',
639 handler: ({ user }) => {
641 // Useless because we have the same info in the ({ user }) parameter
642 // It's just an example
643 fetch('/api/v1/users/me', {
645 headers: peertubeHelpers.getAuthHeader()
646 }).then(res => res.json())
647 .then(data => console.log('Hi %s.', data.username))
655 To show a custom modal:
658 function register (...) {
659 peertubeHelpers.showModal({
660 title: 'My custom modal title',
661 content: '<p>My custom modal content</p>',
662 // Optionals parameters :
665 // show cancel button and call action() after hiding modal
666 cancel: { value: 'cancel', action: () => {} },
667 // show confirm button and call action() after hiding modal
668 confirm: { value: 'confirm', action: () => {} },
675 You can translate some strings of your plugin (PeerTube will use your `translations` object of your `package.json` file):
678 function register (...) {
679 peertubeHelpers.translate('User name')
680 .then(translation => console.log('Translated User name by ' + translation))
684 #### Get public settings
686 To get your public plugin settings:
689 function register (...) {
690 peertubeHelpers.getSettings()
692 if (!s || !s['site-id'] || !s['url']) {
693 console.error('Matomo settings are not set.')
702 #### Get server config
705 function register (...) {
706 peertubeHelpers.getServerConfig()
708 console.log('Fetched server config.', config)
713 #### Add custom fields to video form
715 To add custom fields in the video form (in *Plugin settings* tab):
718 async function register ({ registerVideoField, peertubeHelpers }) {
719 const descriptionHTML = await peertubeHelpers.translate(descriptionSource)
720 const commonOptions = {
721 name: 'my-field-name,
722 label: 'My added field',
723 descriptionHTML: 'Optional description',
725 // type: 'input' | 'input-checkbox' | 'input-password' | 'input-textarea' | 'markdown-text' | 'markdown-enhanced' | 'select' | 'html'
726 // /!\ 'input-checkbox' could send "false" and "true" strings instead of boolean
727 type: 'input-textarea',
731 // Optional, to hide a field depending on the current form state
732 // liveVideo is in the options object when the user is creating/updating a live
733 // videoToUpdate is in the options object when the user is updating a video
734 hidden: ({ formValues, videoToUpdate, liveVideo }) => {
735 return formValues.pluginData['other-field'] === 'toto'
738 // Optional, to display an error depending on the form state
739 error: ({ formValues, value }) => {
740 if (formValues['privacy'] !== 1 && formValues['privacy'] !== 2) return { error: false }
741 if (value === true) return { error: false }
743 return { error: true, text: 'Should be enabled' }
747 const videoFormOptions = {
748 // Optional, to choose to put your setting in a specific tab in video form
749 // type: 'main' | 'plugin-settings'
753 for (const type of [ 'upload', 'import-url', 'import-torrent', 'update', 'go-live' ]) {
754 registerVideoField(commonOptions, { type, ...videoFormOptions })
759 PeerTube will send this field value in `body.pluginData['my-field-name']` and fetch it from `video.pluginData['my-field-name']`.
761 So for example, if you want to store an additional metadata for videos, register the following hooks in **server**:
764 async function register ({
768 const fieldName = 'my-field-name'
770 // Store data associated to this video
772 target: 'action:api.video.updated',
773 handler: ({ video, body }) => {
774 if (!body.pluginData) return
776 const value = body.pluginData[fieldName]
779 storageManager.storeData(fieldName + '-' + video.id, value)
783 // Add your custom value to the video, so the client autofill your field using the previously stored value
785 target: 'filter:api.video.get.result',
786 handler: async (video) => {
787 if (!video) return video
788 if (!video.pluginData) video.pluginData = {}
790 const result = await storageManager.getData(fieldName + '-' + video.id)
791 video.pluginData[fieldName] = result
799 #### Register settings script
801 To hide some fields in your settings plugin page depending on the form state:
804 async function register ({ registerSettingsScript }) {
805 registerSettingsScript({
806 isSettingHidden: options => {
807 if (options.setting.name === 'my-setting' && options.formValues['field45'] === '2') {
816 #### Plugin selector on HTML elements
818 PeerTube provides some selectors (using `id` HTML attribute) on important blocks so plugins can easily change their style.
820 For example `#plugin-selector-login-form` could be used to hide the login form.
822 See the complete list on https://docs.joinpeertube.org/api-plugins
824 #### HTML placeholder elements
826 PeerTube provides some HTML id so plugins can easily insert their own element:
829 async function register (...) {
830 const elem = document.createElement('div')
831 elem.className = 'hello-world-h4'
832 elem.innerHTML = '<h4>Hello everybody! This is an element next to the player</h4>'
834 document.getElementById('plugin-placeholder-player-next').appendChild(elem)
838 See the complete list on https://docs.joinpeertube.org/api-plugins
840 #### Add/remove left menu links
842 Left menu links can be filtered (add/remove a section or add/remove links) using the `filter:left-menu.links.create.result` client hook.
844 #### Create client page
846 To create a client page, register a new client route:
849 function register ({ registerClientRoute }) {
850 registerClientRoute({
851 route: 'my-super/route',
852 onMount: ({ rootEl }) => {
853 rootEl.innerHTML = 'hello'
862 PeerTube plugins and themes should be published on [NPM](https://www.npmjs.com/) so that PeerTube indexes take into account your plugin (after ~ 1 day). An official plugin index is available on [packages.joinpeertube.org](https://packages.joinpeertube.org/api/v1/plugins), with no interface to present packages.
864 > The official plugin index source code is available at https://framagit.org/framasoft/peertube/plugin-index
866 ## Write a plugin/theme
869 * Find a name for your plugin or your theme (must not have spaces, it can only contain lowercase letters and `-`)
870 * Add the appropriate prefix:
871 * If you develop a plugin, add `peertube-plugin-` prefix to your plugin name (for example: `peertube-plugin-mysupername`)
872 * If you develop a theme, add `peertube-theme-` prefix to your theme name (for example: `peertube-theme-mysupertheme`)
873 * Clone the quickstart repository
874 * Configure your repository
876 * Update `package.json`
877 * Register hooks, add CSS and static files
878 * Test your plugin/theme with a local PeerTube installation
879 * Publish your plugin/theme on NPM
881 ### Clone the quickstart repository
883 If you develop a plugin, clone the `peertube-plugin-quickstart` repository:
886 $ git clone https://framagit.org/framasoft/peertube/peertube-plugin-quickstart.git peertube-plugin-mysupername
889 If you develop a theme, clone the `peertube-theme-quickstart` repository:
892 $ git clone https://framagit.org/framasoft/peertube/peertube-theme-quickstart.git peertube-theme-mysupername
895 ### Configure your repository
897 Set your repository URL:
900 $ cd peertube-plugin-mysupername # or cd peertube-theme-mysupername
901 $ git remote set-url origin https://your-git-repo
906 Update `README.md` file:
912 ### Update package.json
914 Update the `package.json` fields:
915 * `name` (should start with `peertube-plugin-` or `peertube-theme-`)
920 * `engine.peertube` (the PeerTube version compatibility, must be `>=x.y.z` and nothing else)
922 **Caution:** Don't update or remove other keys, or PeerTube will not be able to index/install your plugin.
923 If you don't need static directories, use an empty `object`:
933 And if you don't need CSS or client script files, use an empty `array`:
946 Now you can register hooks or settings, write CSS and add static directories to your plugin or your theme :)
947 It's up to you to check the code you write will be compatible with the PeerTube NodeJS version, and will be supported by web browsers.
951 If you want to write modern JavaScript, please use a transpiler like [Babel](https://babeljs.io/).
955 The easiest way to use __Typescript__ for both front-end and backend code is to clone [peertube-plugin-quickstart-typescript](https://github.com/JohnXLivingston/peertube-plugin-quickstart-typescript/) (also available on [framagit](https://framagit.org/Livingston/peertube-plugin-quickstart-typescript/)) instead of `peertube-plugin-quickstart`.
956 Please read carefully the [README file](https://github.com/JohnXLivingston/peertube-plugin-quickstart-typescript/blob/main/README.md), as there are some other differences with `peertube-plugin-quickstart` (using SCSS instead of CSS, linting rules, ...).
958 If you don't want to use `peertube-plugin-quickstart-typescript`, you can also manually add a dev dependency to __Peertube__ types:
961 npm install --save-dev @peertube/peertube-types
964 This package exposes *server* definition files by default:
966 import { RegisterServerOptions } from '@peertube/peertube-types'
968 export async function register ({ registerHook }: RegisterServerOptions) {
970 target: 'action:application.listening',
971 handler: () => displayHelloWorld()
976 But it also exposes client types and various models used in __PeerTube__:
978 import { Video } from '@peertube/peertube-types';
979 import { RegisterClientOptions } from '@peertube/peertube-types/client';
981 function register({ registerHook, peertubeHelpers }: RegisterClientOptions) {
983 target: 'action:admin-plugin-settings.init',
984 handler: ({ npmName }: { npmName: string }) => {
985 if ('peertube-plugin-transcription' !== npmName) {
992 target: 'action:video-watch.video.loaded',
993 handler: ({ video }: { video: Video }) => {
994 fetch(`${peertubeHelpers.getBaseRouterRoute()}/videos/${video.uuid}/captions`, {
996 headers: peertubeHelpers.getAuthHeader(),
997 }).then((res) => res.json())
998 .then((data) => console.log('Hi %s.', data));
1003 export { register };
1006 ### Add translations
1008 If you want to translate strings of your plugin (like labels of your registered settings), create a file and add it to `package.json`:
1014 "fr": "./languages/fr.json",
1015 "pt-BR": "./languages/pt-BR.json"
1021 The key should be one of the locales defined in [i18n.ts](https://github.com/Chocobozzz/PeerTube/blob/develop/shared/models/i18n/i18n.ts).
1023 Translation files are just objects, with the english sentence as the key and the translation as the value.
1024 `fr.json` could contain for example:
1028 "Hello world": "Hello le monde"
1032 ### Build your plugin
1034 If you added client scripts, you'll need to build them using webpack.
1042 Add/update your files in the `clientFiles` array of `webpack.config.js`:
1045 $ $EDITOR ./webpack.config.js
1048 Build your client files:
1054 You built files are in the `dist/` directory. Check `package.json` to correctly point to them.
1057 ### Test your plugin/theme
1059 PeerTube dev server (ran with `npm run dev` on `localhost:3000`) can't inject plugin CSS.
1060 It's the reason why we don't use the dev mode but build PeerTube instead.
1062 You'll need to have a local PeerTube instance:
1063 * Follow the [dev prerequisites](https://github.com/Chocobozzz/PeerTube/blob/develop/.github/CONTRIBUTING.md#prerequisites)
1064 (to clone the repository, install dependencies and prepare the database)
1077 * Run PeerTube (you can access to your instance on http://localhost:9000):
1080 $ NODE_ENV=dev npm start
1083 * Register the instance via the CLI:
1086 $ node ./dist/server/tools/peertube.js auth add -u 'http://localhost:9000' -U 'root' --password 'test'
1089 Then, you can install or reinstall your local plugin/theme by running:
1092 $ node ./dist/server/tools/peertube.js plugins install --path /your/absolute/plugin-or-theme/path
1097 Go in your plugin/theme directory, and run:
1103 Every time you want to publish another version of your plugin/theme, just update the `version` key from the `package.json`
1104 and republish it on NPM. Remember that the PeerTube index will take into account your new plugin/theme version after ~24 hours.
1106 > If you need to force your plugin update on a specific __PeerTube__ instance, you may update the latest available version manually:
1108 > UPDATE "plugin" SET "latestVersion" = 'X.X.X' WHERE "plugin"."name" = 'plugin-shortname';
1110 > You'll then be able to click the __Update plugin__ button on the plugin list.
1114 If for a particular reason you don't want to maintain your plugin/theme anymore
1115 you can deprecate it. The plugin index will automatically remove it preventing users to find/install it from the PeerTube admin interface:
1118 $ npm deprecate peertube-plugin-xxx@"> 0.0.0" "explain here why you deprecate your plugin/theme"
1121 ## Plugin & Theme hooks/helpers API
1123 See the dedicated documentation: https://docs.joinpeertube.org/api-plugins
1128 ### Compatibility with PeerTube
1130 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`).
1132 * Don't make assumptions and check every parameter you want to use. For example:
1136 target: 'filter:api.video.get.result',
1138 // We check the parameter exists and the name field exists too, to avoid exceptions
1139 if (video && video.name) video.name += ' <3'
1145 * 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)
1146 * Don't use PeerTube dependencies. Use your own :)
1148 If your plugin is broken with a new PeerTube release, update your code and the `peertubeEngine` field of your `package.json` field.
1149 This way, older PeerTube versions will still use your old plugin, and new PeerTube versions will use your updated plugin.
1151 ### Spam/moderation plugin
1153 If you want to create an antispam/moderation plugin, you could use the following hooks:
1154 * `filter:api.video.upload.accept.result`: to accept or not local uploads
1155 * `filter:api.video-thread.create.accept.result`: to accept or not local thread
1156 * `filter:api.video-comment-reply.create.accept.result`: to accept or not local replies
1157 * `filter:api.video-threads.list.result`: to change/hide the text of threads
1158 * `filter:api.video-thread-comments.list.result`: to change/hide the text of replies
1159 * `filter:video.auto-blacklist.result`: to automatically blacklist local or remote videos
1161 ### Other plugin examples
1163 You can take a look to "official" PeerTube plugins if you want to take inspiration from them: https://framagit.org/framasoft/peertube/official-plugins