ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

guide.md 33 KiB

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