]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - support/doc/plugins/guide.md
Add auth header in plugins guide
[github/Chocobozzz/PeerTube.git] / support / doc / plugins / guide.md
CommitLineData
662e5d4f
C
1# Plugins & Themes
2
d8e9a42c
C
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 -->
5
6
7- [Concepts](#concepts)
8 - [Hooks](#hooks)
9 - [Static files](#static-files)
10 - [CSS](#css)
d2466f0a 11 - [Server API (only for plugins)](#server-api-only-for-plugins)
d8e9a42c
C
12 - [Settings](#settings)
13 - [Storage](#storage)
7545a094 14 - [Update video constants](#update-video-constants)
5e2b2e27 15 - [Add custom routes](#add-custom-routes)
1a2820e6 16 - [Add external auth methods](#add-external-auth-methods)
7aca6b24 17 - [Add new transcoding profiles](#add-new-transcoding-profiles)
62bc0352 18 - [Server helpers](#server-helpers)
d2466f0a 19 - [Client API (themes & plugins)](#client-api-themes--plugins)
b3af2601
C
20 - [Plugin static route](#plugin-static-route)
21 - [Notifier](#notifier)
22 - [Markdown Renderer](#markdown-renderer)
096231d0 23 - [Auth header](#auth-header)
b3af2601 24 - [Custom Modal](#custom-modal)
7545a094
C
25 - [Translate](#translate)
26 - [Get public settings](#get-public-settings)
ec99e848 27 - [Get server config](#get-server-config)
8546fe87 28 - [Add custom fields to video form](#add-custom-fields-to-video-form)
d2466f0a 29 - [Register settings script](#register-settings-script)
62bc0352 30 - [HTML placeholder elements](#html-placeholder-elements)
d8e9a42c
C
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)
7545a094 38 - [Add translations](#add-translations)
8546fe87 39 - [Build your plugin](#build-your-plugin)
d8e9a42c
C
40 - [Test your plugin/theme](#test-your-plugintheme)
41 - [Publish](#publish)
7545a094 42- [Plugin & Theme hooks/helpers API](#plugin--theme-hookshelpers-api)
d8e9a42c
C
43- [Tips](#tips)
44 - [Compatibility with PeerTube](#compatibility-with-peertube)
45 - [Spam/moderation plugin](#spammoderation-plugin)
112be80e 46 - [Other plugin examples](#other-plugin-examples)
d8e9a42c
C
47
48<!-- END doctoc generated TOC please keep comment here to allow auto update -->
49
662e5d4f
C
50## Concepts
51
32d7f2b7 52Themes are exactly the same as plugins, except that:
662e5d4f
C
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
56
57### Hooks
58
59A plugin registers functions in JavaScript to execute when PeerTube (server and client) fires events. There are 3 types of hooks:
5831dbcb 60 * `filter`: used to filter functions parameters or return values.
662e5d4f
C
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
662e5d4f
C
64
65On server side, these hooks are registered by the `library` file defined in `package.json`.
66
67```json
68{
69 ...,
70 "library": "./main.js",
71 ...,
72}
73```
74
7545a094
C
75And `main.js` defines a `register` function:
76
77Example:
78
79```js
80async function register ({
81 registerHook,
5831dbcb 82
7545a094
C
83 registerSetting,
84 settingsManager,
5831dbcb 85
7545a094 86 storageManager,
5831dbcb 87
7545a094
C
88 videoCategoryManager,
89 videoLicenceManager,
5e2b2e27 90 videoLanguageManager,
5831dbcb 91
5e2b2e27 92 peertubeHelpers,
5831dbcb
C
93
94 getRouter,
95
96 registerExternalAuth,
97 unregisterExternalAuth,
98 registerIdAndPassAuth,
99 unregisterIdAndPassAuth
7545a094
C
100}) {
101 registerHook({
102 target: 'action:application.listening',
103 handler: () => displayHelloWorld()
104 })
105}
106```
107
662e5d4f
C
108
109On client side, these hooks are registered by the `clientScripts` files defined in `package.json`.
110All client scripts have scopes so PeerTube client only loads scripts it needs:
111
112```json
113{
114 ...,
115 "clientScripts": [
116 {
117 "script": "client/common-client-plugin.js",
118 "scopes": [ "common" ]
119 },
120 {
121 "script": "client/video-watch-client-plugin.js",
122 "scopes": [ "video-watch" ]
123 }
124 ],
125 ...
126}
127```
128
7545a094
C
129And these scripts also define a `register` function:
130
131```js
132function register ({ registerHook, peertubeHelpers }) {
133 registerHook({
134 target: 'action:application.init',
135 handler: () => onApplicationInit(peertubeHelpers)
136 })
137}
138```
139
662e5d4f
C
140### Static files
141
5831dbcb
C
142Plugins can declare static directories that PeerTube will serve (images for example)
143from `/plugins/{plugin-name}/{plugin-version}/static/`
662e5d4f
C
144or `/themes/{theme-name}/{theme-version}/static/` routes.
145
146### CSS
147
148Plugins can declare CSS files that PeerTube will automatically inject in the client.
7545a094
C
149If you need to override existing style, you can use the `#custom-css` selector:
150
151```
152body#custom-css {
153 color: red;
154}
155
156#custom-css .header {
157 background-color: red;
158}
159```
662e5d4f 160
d2466f0a 161### Server API (only for plugins)
662e5d4f
C
162
163#### Settings
164
165Plugins can register settings, that PeerTube will inject in the administration interface.
d2466f0a
C
166The 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.**
662e5d4f
C
168
169Example:
170
171```js
d2466f0a
C
172function register (...) {
173 registerSetting({
174 name: 'admin-name',
175 label: 'Admin name',
176 type: 'input',
177 // type: input | input-checkbox | input-password | input-textarea | markdown-text | markdown-enhanced | 'select' | 'html'
178 default: 'my super name'
179 })
180
181 const adminName = await settingsManager.getSetting('admin-name')
182
183 const result = await settingsManager.getSettings([ 'admin-name', 'admin-password' ])
184 result['admin-name]
185
186 settingsManager.onSettingsChange(settings => {
187 settings['admin-name])
188 })
189}
662e5d4f
C
190```
191
d8e9a42c 192#### Storage
662e5d4f
C
193
194Plugins can store/load JSON data, that PeerTube will store in its database (so don't put files in there).
195
196Example:
197
198```js
302eba0d
C
199function register ({
200 storageManager
201}) {
d2466f0a
C
202 const value = await storageManager.getData('mykey')
203 await storageManager.storeData('mykey', { subkey: 'value' })
204}
662e5d4f
C
205```
206
096231d0 207You can also store files in the plugin data directory (`/{plugins-directory}/data/{npm-plugin-name}`) **in PeerTube >= 3.2**.
302eba0d
C
208This directory and its content won't be deleted when your plugin is uninstalled/upgraded.
209
210```js
211function register ({
212 storageManager,
213 peertubeHelpers
214}) {
215 const basePath = peertubeHelpers.plugin.getDataDirectoryPath()
216
217 fs.writeFile(path.join(basePath, 'filename.txt'), 'content of my file', function (err) {
218 ...
219 })
220}
221```
222
7545a094
C
223#### Update video constants
224
225You can add/delete video categories, licences or languages using the appropriate managers:
226
227```js
d2466f0a
C
228function register (...) {
229 videoLanguageManager.addLanguage('al_bhed', 'Al Bhed')
230 videoLanguageManager.deleteLanguage('fr')
7545a094 231
d2466f0a
C
232 videoCategoryManager.addCategory(42, 'Best category')
233 videoCategoryManager.deleteCategory(1) // Music
7545a094 234
d2466f0a
C
235 videoLicenceManager.addLicence(42, 'Best licence')
236 videoLicenceManager.deleteLicence(7) // Public domain
b3af2601 237
d2466f0a
C
238 videoPrivacyManager.deletePrivacy(2) // Remove Unlisted video privacy
239 playlistPrivacyManager.deletePlaylistPrivacy(3) // Remove Private video playlist privacy
240}
7545a094
C
241```
242
5e2b2e27
C
243#### Add custom routes
244
245You can create custom routes using an [express Router](https://expressjs.com/en/4x/api.html#router) for your plugin:
246
247```js
302eba0d
C
248function register ({
249 router
250}) {
d2466f0a
C
251 const router = getRouter()
252 router.get('/ping', (req, res) => res.json({ message: 'pong' }))
302eba0d
C
253
254 // Users are automatically authenticated
255 router.get('/auth', (res, res) => {
256 const user = peertubeHelpers.user.getAuthUser(res)
257
258 const isAdmin = user.role === 0
259 const isModerator = user.role === 1
260 const isUser = user.role === 2
261
262 res.json({
263 username: user.username,
264 isAdmin,
265 isModerator,
266 isUser
267 })
268 })
d2466f0a 269}
5e2b2e27
C
270```
271
272The `ping` route can be accessed using:
273 * `/plugins/:pluginName/:pluginVersion/router/ping`
274 * Or `/plugins/:pluginName/router/ping`
275
276
5831dbcb
C
277#### Add external auth methods
278
279If 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):
280
281```js
d2466f0a
C
282function register (...) {
283
284 registerIdAndPassAuth({
285 authName: 'my-auth-method',
286
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
289 getWeight: () => 60,
290
291 // Optional function called by PeerTube when the user clicked on the logout button
292 onLogout: user => {
293 console.log('User %s logged out.', user.username')
294 },
295
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 }
300 },
301
302 // Used by PeerTube when the user tries to authenticate
303 login: ({ id, password }) => {
304 if (id === 'user' && password === 'super password') {
305 return {
306 username: 'user'
307 email: 'user@example.com'
308 role: 2
309 displayName: 'User display name'
310 }
5831dbcb 311 }
5831dbcb 312
d2466f0a
C
313 // Auth failed
314 return null
315 }
316 })
5831dbcb 317
d2466f0a
C
318 // Unregister this auth method
319 unregisterIdAndPassAuth('my-auth-method')
320}
5831dbcb
C
321```
322
323You 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):
324
325```js
d2466f0a
C
326function register (...) {
327
328 // result contains the userAuthenticated auth method you can call to authenticate a user
329 const result = registerExternalAuth({
330 authName: 'my-auth-method',
331
332 // Will be displayed in a button next to the login form
333 authDisplayName: () => 'Auth method'
334
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')
338 },
339
340 // Same than registerIdAndPassAuth option
341 // onLogout: ...
342
343 // Same than registerIdAndPassAuth option
344 // hookTokenValidity: ...
345 })
346
347 router.use('/external-auth-callback', (req, res) => {
348 // Forward the request to PeerTube
349 result.userAuthenticated({
350 req,
351 res,
352 username: 'user'
353 email: 'user@example.com'
354 role: 2
355 displayName: 'User display name'
356 })
5831dbcb 357 })
5831dbcb 358
d2466f0a
C
359 // Unregister this external auth method
360 unregisterExternalAuth('my-auth-method)
361}
5831dbcb
C
362```
363
7aca6b24
C
364#### Add new transcoding profiles
365
366Adding transcoding profiles allow admins to change ffmpeg encoding parameters and/or encoders.
367A transcoding profile has to be chosen by the admin of the instance using the admin configuration.
368
369```js
370async function register ({
371 transcodingManager
372}) {
373
374 // Adapt bitrate when using libx264 encoder
375 {
376 const builder = (options) => {
377 const { input, resolution, fps, streamNum } = options
378
379 const streamString = streamNum ? ':' + streamNum : ''
380
381 // You can also return a promise
a60696ab 382 // All these options are optional
7aca6b24 383 return {
a60696ab
C
384 scaleFilter: {
385 // Used to define an alternative scale filter, needed by some encoders
386 // Default to 'scale'
387 name: 'scale_vaapi'
388 },
389 // Default to []
5fb7cfba 390 inputOptions: [],
a60696ab 391 // Default to []
7aca6b24
C
392 outputOptions: [
393 // Use a custom bitrate
394 '-b' + streamString + ' 10K'
395 ]
396 }
397 }
398
399 const encoder = 'libx264'
400 const profileName = 'low-quality'
401
402 // Support this profile for VOD transcoding
403 transcodingManager.addVODProfile(encoder, profileName, builder)
404
405 // And/Or support this profile for live transcoding
406 transcodingManager.addLiveProfile(encoder, profileName, builder)
407 }
408
409 {
410 const builder = (options) => {
411 const { streamNum } = options
412
413 const streamString = streamNum ? ':' + streamNum : ''
414
415 // Always copy stream when PeerTube use libfdk_aac or aac encoders
416 return {
417 copy: true
418 }
419 }
420
421 const profileName = 'copy-audio'
422
423 for (const encoder of [ 'libfdk_aac', 'aac' ]) {
424 transcodingManager.addVODProfile(encoder, profileName, builder)
425 }
426 }
427```
428
429PeerTube will try different encoders depending on their priority.
430If the encoder is not available in the current transcoding profile or in ffmpeg, it tries the next one.
431Plugins can change the order of these encoders and add their custom encoders:
432
433```js
434async function register ({
435 transcodingManager
436}) {
437
438 // Adapt bitrate when using libx264 encoder
439 {
440 const builder = () => {
441 return {
5fb7cfba 442 inputOptions: [],
7aca6b24
C
443 outputOptions: []
444 }
445 }
446
447 // Support libopus and libvpx-vp9 encoders (these codecs could be incompatible with the player)
448 transcodingManager.addVODProfile('libopus', 'test-vod-profile', builder)
449
450 // Default priorities are ~100
451 // Lowest priority = 1
452 transcodingManager.addVODEncoderPriority('audio', 'libopus', 1000)
453
454 transcodingManager.addVODProfile('libvpx-vp9', 'test-vod-profile', builder)
455 transcodingManager.addVODEncoderPriority('video', 'libvpx-vp9', 1000)
456
457 transcodingManager.addLiveProfile('libopus', 'test-live-profile', builder)
458 transcodingManager.addLiveEncoderPriority('audio', 'libopus', 1000)
459 }
460```
461
d5fc35c2
TLC
462During live transcode input options are applied once for each target resolution.
463Plugins are responsible for detecting such situation and applying input options only once if necessary.
464
62bc0352 465#### Server helpers
d2466f0a
C
466
467PeerTube provides your plugin some helpers. For example:
468
469```js
470async function register ({
471 peertubeHelpers
472}) {
473 // Block a server
474 {
475 const serverActor = await peertubeHelpers.server.getServerActor()
476
477 await peertubeHelpers.moderation.blockServer({ byAccountId: serverActor.Account.id, hostToBlock: '...' })
478 }
479
480 // Load a video
481 {
482 const video = await peertubeHelpers.videos.loadByUrl('...')
483 }
484}
485```
486
487See the [plugin API reference](https://docs.joinpeertube.org/api-plugins) to see the complete helpers list.
488
489### Client API (themes & plugins)
7545a094 490
74c2dece 491#### Plugin static route
7545a094
C
492
493To get your plugin static route:
494
495```js
d2466f0a
C
496function register (...) {
497 const baseStaticUrl = peertubeHelpers.getBaseStaticRoute()
498 const imageUrl = baseStaticUrl + '/images/chocobo.png'
499}
7545a094
C
500```
501
74c2dece
K
502#### Notifier
503
504To notify the user with the PeerTube ToastModule:
505
506```js
d2466f0a
C
507function register (...) {
508 const { notifier } = peertubeHelpers
509 notifier.success('Success message content.')
510 notifier.error('Error message content.')
511}
74c2dece
K
512```
513
8c7725dc
K
514#### Markdown Renderer
515
516To render a formatted markdown text to HTML:
517
518```js
d2466f0a
C
519function register (...) {
520 const { markdownRenderer } = peertubeHelpers
8c7725dc 521
d2466f0a
C
522 await markdownRenderer.textMarkdownToHTML('**My Bold Text**')
523 // return <strong>My Bold Text</strong>
8c7725dc 524
d2466f0a
C
525 await markdownRenderer.enhancedMarkdownToHTML('![alt-img](http://.../my-image.jpg)')
526 // return <img alt=alt-img src=http://.../my-image.jpg />
527}
8c7725dc
K
528```
529
096231d0
C
530#### Auth header
531
532**PeerTube >= 3.2**
533
534To make your own HTTP requests using the current authenticated user, use an helper to automatically set appropriate headers:
535
536```js
537function register (...) {
538 registerHook({
539 target: 'action:auth-user.information-loaded',
540 handler: ({ user }) => {
541
542 // Useless because we have the same info in the ({ user }) parameter
543 // It's just an example
544 fetch('/api/v1/users/me', {
545 method: 'GET',
546 headers: peertubeHelpers.getAuthHeader()
547 }).then(res => res.json())
548 .then(data => console.log('Hi %s.', data.username))
549 }
550 })
551}
552```
553
437e8e06
K
554#### Custom Modal
555
556To show a custom modal:
557
558```js
d2466f0a
C
559function register (...) {
560 peertubeHelpers.showModal({
561 title: 'My custom modal title',
562 content: '<p>My custom modal content</p>',
563 // Optionals parameters :
564 // show close icon
565 close: true,
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: () => {} },
570 })
571}
437e8e06
K
572```
573
7545a094
C
574#### Translate
575
576You can translate some strings of your plugin (PeerTube will use your `translations` object of your `package.json` file):
577
578```js
d2466f0a
C
579function register (...) {
580 peertubeHelpers.translate('User name')
581 .then(translation => console.log('Translated User name by ' + translation))
582}
7545a094
C
583```
584
585#### Get public settings
586
587To get your public plugin settings:
588
589```js
d2466f0a
C
590function register (...) {
591 peertubeHelpers.getSettings()
592 .then(s => {
593 if (!s || !s['site-id'] || !s['url']) {
594 console.error('Matomo settings are not set.')
595 return
596 }
5831dbcb 597
d2466f0a
C
598 // ...
599 })
600}
5831dbcb 601```
7545a094 602
ec99e848
C
603#### Get server config
604
605```js
d2466f0a
C
606function register (...) {
607 peertubeHelpers.getServerConfig()
608 .then(config => {
609 console.log('Fetched server config.', config)
610 })
611}
ec99e848
C
612```
613
8546fe87 614#### Add custom fields to video form
e08a26e2
C
615
616To add custom fields in the video form (in *Plugin settings* tab):
617
8546fe87 618```js
e08a26e2
C
619async 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',
626 default: ''
627 }
628
629 for (const type of [ 'upload', 'import-url', 'import-torrent', 'update' ]) {
630 registerVideoField(commonOptions, { type })
631 }
632}
633```
634
635PeerTube will send this field value in `body.pluginData['my-field-name']` and fetch it from `video.pluginData['my-field-name']`.
636
637So for example, if you want to store an additional metadata for videos, register the following hooks in **server**:
638
8546fe87 639```js
e08a26e2
C
640async function register ({
641 registerHook,
642 storageManager
643}) {
644 const fieldName = 'my-field-name'
645
646 // Store data associated to this video
647 registerHook({
648 target: 'action:api.video.updated',
649 handler: ({ video, body }) => {
650 if (!body.pluginData) return
651
652 const value = body.pluginData[fieldName]
653 if (!value) return
654
655 storageManager.storeData(fieldName + '-' + video.id, value)
656 }
657 })
658
659 // Add your custom value to the video, so the client autofill your field using the previously stored value
660 registerHook({
661 target: 'filter:api.video.get.result',
662 handler: async (video) => {
663 if (!video) return video
664 if (!video.pluginData) video.pluginData = {}
665
666 const result = await storageManager.getData(fieldName + '-' + video.id)
667 video.pluginData[fieldName] = result
668
669 return video
670 }
671 })
672}
2498aaea 673```
d2466f0a
C
674
675#### Register settings script
676
677To hide some fields in your settings plugin page depending on the form state:
678
679```js
680async function register ({ registerSettingsScript }) {
681 registerSettingsScript({
682 isSettingHidden: options => {
683 if (options.setting.name === 'my-setting' && options.formValues['field45'] === '2') {
684 return true
685 }
686
687 return false
688 }
689 })
690}
691```
692
62bc0352
C
693#### HTML placeholder elements
694
695PeerTube provides some HTML id so plugins can easily insert their own element:
696
b044cb18 697```js
62bc0352
C
698async function register (...) {
699 const elem = document.createElement('div')
700 elem.className = 'hello-world-h4'
701 elem.innerHTML = '<h4>Hello everybody! This is an element next to the player</h4>'
702
703 document.getElementById('plugin-placeholder-player-next').appendChild(elem)
704}
705```
706
707See the complete list on https://docs.joinpeertube.org/api-plugins
d2466f0a 708
662e5d4f
C
709### Publishing
710
711PeerTube plugins and themes should be published on [NPM](https://www.npmjs.com/) so that PeerTube indexes
712take 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).
713
714## Write a plugin/theme
715
716Steps:
717 * Find a name for your plugin or your theme (must not have spaces, it can only contain lowercase letters and `-`)
718 * Add the appropriate prefix:
719 * If you develop a plugin, add `peertube-plugin-` prefix to your plugin name (for example: `peertube-plugin-mysupername`)
720 * If you develop a theme, add `peertube-theme-` prefix to your theme name (for example: `peertube-theme-mysupertheme`)
721 * Clone the quickstart repository
722 * Configure your repository
723 * Update `README.md`
724 * Update `package.json`
725 * Register hooks, add CSS and static files
726 * Test your plugin/theme with a local PeerTube installation
727 * Publish your plugin/theme on NPM
728
729### Clone the quickstart repository
730
731If you develop a plugin, clone the `peertube-plugin-quickstart` repository:
732
733```
734$ git clone https://framagit.org/framasoft/peertube/peertube-plugin-quickstart.git peertube-plugin-mysupername
735```
736
737If you develop a theme, clone the `peertube-theme-quickstart` repository:
738
739```
740$ git clone https://framagit.org/framasoft/peertube/peertube-theme-quickstart.git peertube-theme-mysupername
741```
742
743### Configure your repository
744
745Set your repository URL:
746
747```
748$ cd peertube-plugin-mysupername # or cd peertube-theme-mysupername
749$ git remote set-url origin https://your-git-repo
750```
751
752### Update README
753
754Update `README.md` file:
755
756```
757$ $EDITOR README.md
758```
759
760### Update package.json
761
762Update the `package.json` fields:
763 * `name` (should start with `peertube-plugin-` or `peertube-theme-`)
764 * `description`
765 * `homepage`
766 * `author`
767 * `bugs`
768 * `engine.peertube` (the PeerTube version compatibility, must be `>=x.y.z` and nothing else)
5831dbcb 769
662e5d4f 770**Caution:** Don't update or remove other keys, or PeerTube will not be able to index/install your plugin.
5831dbcb 771If you don't need static directories, use an empty `object`:
662e5d4f
C
772
773```json
774{
775 ...,
776 "staticDirs": {},
777 ...
778}
779```
780
9fa6ca16 781And if you don't need CSS or client script files, use an empty `array`:
662e5d4f
C
782
783```json
784{
785 ...,
786 "css": [],
9fa6ca16 787 "clientScripts": [],
662e5d4f
C
788 ...
789}
790```
791
792### Write code
793
794Now you can register hooks or settings, write CSS and add static directories to your plugin or your theme :)
795
5831dbcb 796**Caution:** It's up to you to check the code you write will be compatible with the PeerTube NodeJS version,
662e5d4f
C
797and will be supported by web browsers.
798If you want to write modern JavaScript, please use a transpiler like [Babel](https://babeljs.io/).
799
7545a094
C
800### Add translations
801
802If you want to translate strings of your plugin (like labels of your registered settings), create a file and add it to `package.json`:
803
804```json
805{
806 ...,
807 "translations": {
67baf647 808 "fr": "./languages/fr.json",
7545a094
C
809 "pt-BR": "./languages/pt-BR.json"
810 },
811 ...
812}
813```
814
815The key should be one of the locales defined in [i18n.ts](https://github.com/Chocobozzz/PeerTube/blob/develop/shared/models/i18n/i18n.ts).
7545a094 816
112be80e
C
817Translation files are just objects, with the english sentence as the key and the translation as the value.
818`fr.json` could contain for example:
819
820```json
821{
822 "Hello world": "Hello le monde"
823}
824```
825
36578353
C
826### Build your plugin
827
828If you added client scripts, you'll need to build them using webpack.
829
830Install webpack:
831
832```
833$ npm install
834```
835
836Add/update your files in the `clientFiles` array of `webpack.config.js`:
837
838```
839$ $EDITOR ./webpack.config.js
840```
841
842Build your client files:
843
844```
845$ npm run build
846```
847
848You built files are in the `dist/` directory. Check `package.json` to correctly point to them.
849
850
662e5d4f
C
851### Test your plugin/theme
852
853You'll need to have a local PeerTube instance:
5831dbcb 854 * Follow the [dev prerequisites](https://github.com/Chocobozzz/PeerTube/blob/develop/.github/CONTRIBUTING.md#prerequisites)
662e5d4f 855 (to clone the repository, install dependencies and prepare the database)
5831dbcb 856 * Build PeerTube (`--light` to only build the english language):
662e5d4f
C
857
858```
859$ npm run build -- --light
9fa6ca16
C
860```
861
862 * Build the CLI:
5831dbcb 863
9fa6ca16
C
864```
865$ npm run setup:cli
662e5d4f 866```
5831dbcb
C
867
868 * Run PeerTube (you can access to your instance on http://localhost:9000):
662e5d4f
C
869
870```
871$ NODE_ENV=test npm start
872```
873
5831dbcb 874 * Register the instance via the CLI:
662e5d4f
C
875
876```
877$ node ./dist/server/tools/peertube.js auth add -u 'http://localhost:9000' -U 'root' --password 'test'
878```
879
880Then, you can install or reinstall your local plugin/theme by running:
881
882```
883$ node ./dist/server/tools/peertube.js plugins install --path /your/absolute/plugin-or-theme/path
884```
885
886### Publish
887
888Go in your plugin/theme directory, and run:
889
890```
891$ npm publish
892```
893
894Every time you want to publish another version of your plugin/theme, just update the `version` key from the `package.json`
895and republish it on NPM. Remember that the PeerTube index will take into account your new plugin/theme version after ~24 hours.
896
d8e9a42c 897
bfa1a32b
C
898## Plugin & Theme hooks/helpers API
899
7cf88d09 900See the dedicated documentation: https://docs.joinpeertube.org/api-plugins
bfa1a32b
C
901
902
d8e9a42c
C
903## Tips
904
905### Compatibility with PeerTube
906
907Unfortunately, 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`).
908So please:
909 * Don't make assumptions and check every parameter you want to use. For example:
910
911```js
912registerHook({
913 target: 'filter:api.video.get.result',
914 handler: video => {
915 // We check the parameter exists and the name field exists too, to avoid exceptions
916 if (video && video.name) video.name += ' <3'
917
918 return video
919 }
920})
921```
a4879b53 922 * 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)
5831dbcb 923 * Don't use PeerTube dependencies. Use your own :)
d8e9a42c 924
51326912 925If your plugin is broken with a new PeerTube release, update your code and the `peertubeEngine` field of your `package.json` field.
5831dbcb 926This way, older PeerTube versions will still use your old plugin, and new PeerTube versions will use your updated plugin.
d8e9a42c
C
927
928### Spam/moderation plugin
929
930If you want to create an antispam/moderation plugin, you could use the following hooks:
931 * `filter:api.video.upload.accept.result`: to accept or not local uploads
932 * `filter:api.video-thread.create.accept.result`: to accept or not local thread
933 * `filter:api.video-comment-reply.create.accept.result`: to accept or not local replies
934 * `filter:api.video-threads.list.result`: to change/hide the text of threads
935 * `filter:api.video-thread-comments.list.result`: to change/hide the text of replies
936 * `filter:video.auto-blacklist.result`: to automatically blacklist local or remote videos
5831dbcb 937
112be80e
C
938### Other plugin examples
939
940You can take a look to "official" PeerTube plugins if you want to take inspiration from them: https://framagit.org/framasoft/peertube/official-plugins