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