Init commit

This commit is contained in:
ShreejitPanchal
2026-05-19 19:56:02 +08:00
commit 6601501eff
4047 changed files with 2185372 additions and 0 deletions

12
.dockerignore Normal file
View File

@@ -0,0 +1,12 @@
*.swp
.git
.github
support/doc
support/nginx
support/systemd
support/docker/*/Dockerfile.*
support/docker/*/*.yml
support/docker/*/docker-volume
storage
node_modules
client/node_modules

93
.dprint.json Normal file
View File

@@ -0,0 +1,93 @@
{
"typescript": {
"lineWidth": 140,
"indentWidth": 2,
"useTabs": false,
"semiColons": "asi",
"quoteStyle": "alwaysSingle",
"quoteProps": "preserve",
"newLineKind": "lf",
"useBraces": "whenNotSingleLine",
"bracePosition": "sameLineUnlessHanging",
"singleBodyPosition": "maintain",
"nextControlFlowPosition": "sameLine",
"trailingCommas": "never",
"operatorPosition": "maintain",
"preferHanging": false,
"preferSingleLine": false,
"arrowFunction.useParentheses": "preferNone",
"binaryExpression.linePerExpression": false,
"jsx.bracketPosition": "nextLine",
"jsx.forceNewLinesSurroundingContent": false,
"jsx.multiLineParens": "prefer",
"memberExpression.linePerExpression": false,
"typeLiteral.separatorKind.singleLine": "comma",
"enumDeclaration.memberSpacing": "maintain",
"spaceAround": false,
"spaceSurroundingProperties": true,
"binaryExpression.spaceSurroundingBitwiseAndArithmeticOperator": true,
"commentLine.forceSpaceAfterSlashes": true,
"constructor.spaceBeforeParentheses": true,
"constructorType.spaceAfterNewKeyword": false,
"constructSignature.spaceAfterNewKeyword": false,
"doWhileStatement.spaceAfterWhileKeyword": true,
"exportDeclaration.spaceSurroundingNamedExports": true,
"forInStatement.spaceAfterForKeyword": true,
"forOfStatement.spaceAfterForKeyword": true,
"forStatement.spaceAfterForKeyword": true,
"forStatement.spaceAfterSemiColons": true,
"functionDeclaration.spaceBeforeParentheses": true,
"functionExpression.spaceBeforeParentheses": true,
"functionExpression.spaceAfterFunctionKeyword": true,
"getAccessor.spaceBeforeParentheses": true,
"ifStatement.spaceAfterIfKeyword": true,
"importDeclaration.spaceSurroundingNamedImports": true,
"jsxSelfClosingElement.spaceBeforeSlash": true,
"jsxExpressionContainer.spaceSurroundingExpression": false,
"method.spaceBeforeParentheses": true,
"setAccessor.spaceBeforeParentheses": true,
"taggedTemplate.spaceBeforeLiteral": false,
"typeAnnotation.spaceBeforeColon": false,
"typeAssertion.spaceBeforeExpression": true,
"whileStatement.spaceAfterWhileKeyword": true,
"module.sortImportDeclarations": "maintain",
"module.sortExportDeclarations": "maintain",
"exportDeclaration.sortNamedExports": "maintain",
"importDeclaration.sortNamedImports": "maintain",
"ignoreNodeCommentText": "dprint-ignore",
"ignoreFileCommentText": "dprint-ignore-file",
"exportDeclaration.forceSingleLine": false,
"importDeclaration.forceSingleLine": false,
"exportDeclaration.forceMultiLine": "never",
"importDeclaration.forceMultiLine": "never",
"arrayExpression.spaceAround": true,
"arrayPattern.spaceAround": true,
"importDeclaration.preferSingleLine": true
},
"json": {},
"markdown": {},
"toml": {},
"malva": {
"quotes": "preferDouble",
"printWidth": 140,
"hexCase": "ignore",
"blockSelectorLinebreak": "always"
},
"markup": {
"printWidth": 160,
"preferAttrsSingleLine": true
},
"excludes": [
"**/node_modules",
"**/*-lock.json",
"packages/tests/fixtures/**/*"
],
"plugins": [
"https://plugins.dprint.dev/typescript-0.91.1.wasm",
"https://plugins.dprint.dev/json-0.19.3.wasm",
"https://plugins.dprint.dev/markdown-0.17.1.wasm",
"https://plugins.dprint.dev/toml-0.6.2.wasm",
"https://plugins.dprint.dev/g-plane/malva-v0.12.0.wasm",
"https://plugins.dprint.dev/g-plane/markup_fmt-v0.24.1.wasm"
]
}

12
.editorconfig Normal file
View File

@@ -0,0 +1,12 @@
; This file is for unifying the coding style for different editors and IDEs.
; More information at http://editorconfig.org to setup your IDE if need be.
root = true
[*]
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
indent_size = 2
indent_style = space

68
.gitignore vendored Normal file
View File

@@ -0,0 +1,68 @@
# NPM instalation
node_modules
*npm-debug.log
*-ci.log
# Testing
/test1/
/test2/
/test3/
/test4/
/test5/
/test6/
# Big fixtures generated/downloaded on-demand
/packages/tests/fixtures/video_high_bitrate_1080p.mp4
/packages/tests/fixtures/video_59fps.mp4
/packages/tests/fixtures/video_50fps.mp4
/packages/tests/fixtures/transcription/models-v1/
# PeerTube
/storage
/dev1
/config/production.yaml
/ffmpeg/
/ffmpeg-3/
/ffmpeg-4/
/thumbnails/
/torrents/
/web-videos/
/videos/
/previews/
/logs/
# IDE
/*.sublime-project
/*.sublime-workspace
/*.vscode
/**/.idea
/dist
/PeerTube.iml
*.swp
# Zanata
/.zanata-cache
/scripts/i18n/generate-iso639-target.ts
# Other
/dump.rdb
/.theia/
/profiling/
/*.zip
/*.tar.xz
/*.asc
*.DS_Store
/docker-volume/
/init.mp4
# TypeScript
*.tsbuildinfo
# EsLint
.eslintcache
# Compiled output
dist
# certs for ssl
certs

20
.gitpod.yml Normal file
View File

@@ -0,0 +1,20 @@
image:
file: support/docker/gitpod/Dockerfile
ports:
- port: 3000
onOpen: open-preview
- port: 5432
onOpen: ignore
- port: 6379
onOpen: ignore
- port: 9000
onOpen: ignore
tasks:
- name: Redis
command: redis-server
- name: PeerTube
before: export NODE_CONFIG="{\"import\":{\"videos\":{\"torrent\":{\"enabled\":false}}},\"webserver\":{\"hostname\":\"$(gp url 3000 | cut -d/ -f3)\",\"port\":\"443\",\"https\":true}}"
init: >
psql -h localhost -d postgres --file=support/docker/gitpod/setup_postgres.sql &&
npm run install-node-dependencies
command: npm run build:server && npm run dev

10
.mocharc.cjs Normal file
View File

@@ -0,0 +1,10 @@
process.env.TSX_TSCONFIG_PATH = './packages/tests/tsconfig.json'
module.exports = {
"node-option": [
"import=tsx",
"no-warnings",
"conditions=peertube:tsx"
],
"timeout": 30000
}

4706
CHANGELOG.md Normal file

File diff suppressed because it is too large Load Diff

86
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,86 @@
# Contributor Covenant Code of Conduct
## Our pledge
In order to create an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of:
* age
* body size
* disability
* gender identity and expression
* level of experience
* education
* socio-economic status
* nationality
* personal appearance
* ethnicity
* religion
* sexual identity and orientation
* etc.
## Our standards
A supplemental goal of this Code of Conduct is to increase open source and culture citizenship by encouraging participants to recognize and strengthen the relationships between our actions and their effects on our community.
Communities mirror the societies in which they exist and positive action is essential to counteract the many forms of inequality and abuses of power that exist in society.
If you see someone who is making an extra effort to ensure our community is welcoming, friendly, and encourages all participants to contribute to the fullest extent, please recognize their efforts.
You can contribute to creating a positive environment in many ways. For example you can:
* use welcoming and inclusive language
* be respectful of differing viewpoints and experiences
* accept constructive criticism gracefully
* focus on what is best for the community
* show empathy towards other community members
You should not:
* use sexualised language or imagery
* make unwelcome sexual advances
* troll, and make insulting or derogatory comments
* make personal or political attacks
* harass others, in public or private
* publish others' private information, such as a physical or electronic address, without explicit permission
* engage in any other conduct which could reasonably be considered inappropriate in a professional setting
* etc.
## Our responsibilities
As project maintainers, we are responsible for clarifying the standards of acceptable behaviour and we are expected to take appropriate and fair corrective action in response to any instances of unacceptable behaviour.
We have the right and responsibility to remove, edit, or reject:
* comments
* commits
* code
* wiki edits
* issues
* other contributions that are not aligned to this code of conduct
We also reserve the right to temporarily or permanently ban any contributor for other behaviours we deem inappropriate, threatening, offensive, or harmful.
## Scope
This code of conduct applies whenever you are representing the project or community. For example, you may be:
* working in a project space online or in the public (i.e.: github.com, framacolibri.org, IRC)
* using an official project email address
* posting via an official social media account
* participating in an online or offline event
Project maintainers may further define and clarify representation of a project.
## Enforcement
You should report any instances of abusive, harassing, or otherwise unacceptable behaviour to the project team at peertube@framasoft.org. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain the anonymity of the reporter of an incident. We may post further details of specific enforcement policies separately.
Project maintainers who do not follow or enforce this code of conduct in good faith may face temporary or permanent consequences. These will be determined by members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/

863
CREDITS.md Normal file
View File

@@ -0,0 +1,863 @@
# Code & Translators contributors
* Chocobozzz
* Rigel Kent
* DignifiedSilence
* T.S
* Александр
* Hồ Nhất Duy
* Jeff Huang
* josé m
* Milo Ivir
* Ihor Hordiichuk
* Filip Bengtsson
* fran secs
* kontrollanten
* Payman Moghadam
* Berto Te
* Simon Brosdetzko
* Jiri Podhorecky
* Phongpanot
* Sveinn í Felli
* Hannes Ylä-Jääski
* GunChleoc
* hecko
* Laurent Ettouati
* kimsible
* Zet
* Ewout van Mansom
* Aitor Salaberria
* Leif-Jöran Olsson
* Clemens Schielicke
* Luca Calcaterra
* Racida S
* Balázs Meskó
* Marcin Mikołajczak
* Wicklow
* Blood Axe
* Eivind Ødegård
* John Livingston
* Tirifto
* Besnik Bleta
* Kim
* Vodoyo Kamal
* Jiří Podhorecký
* Armin
* Fontan 030
* ButterflyOfFire
* Mohamad Reza
* Quentin PAGÈS
* Kimsible
* Felix Ableitner
* Frank Sträter
* Free coss
* Ettore Atalan
* Andrea Gavioli
* Mürteza MERT
* Gérald Niel
* Duy
* Eric Guichaoua
* Renne Rocha
* Slimane Selyan AMIRI
* Dingzhong Chen
* Filip Hanes
* Julien Maulny
* Mark Van den Borre
* x
* Booteille
* Manuel Viens
* Jorropo
* Josh Morel
* dxuser514
* BO41
* Marc Strange
* vachan
* AP
* Elegant Codes
* Florian CUNY
* Francesc
* alex gabilondo
* mando laress
* Ľubomír Šima
* Артём Котлубай
* Fjuro
* Ricardo Biloti
* 0que
* Cedric F
* Florent
* Ricardo Simões
* lutangar
* Ch
* J. Lavoie
* Luc Didry
* YILDIRIM YAPRAK
* barzofarev2
* jan Seli
* 李奕寯
* Erik Guldberg
* Kempelen
* Kerim Demirkaynak
* Martin Hoefler
* Porrumentzio
* Poslovitch
* Xabi
* buoyantair
* Alexander Ivanov
* Balázs Úr
* Echo Kilo
* Jan Keromnes
* Siourdakis Thanos
* Thomas Citharel
* knuxify
* tray
* Adrià Martín
* Agron Selimaj
* Attila F
* Caroline Chuong
* David Soh
* Diazepan Medina
* Jason Zhou
* Loukas Stamellos
* Ms Kimsible
* NorbiPeti
* Sergey Zigachev
* Txopi
* Benjamin Bouvier
* Cavernosa
* Ghost of Sparta
* Joe Bill
* Julien
* Jure Repinc
* Kemal Oktay Aktoğan
* Lucas Declercq
* Ryan He
* Sirxy
* Viorel-Cătălin Răpițeanu
* matograine
* 偶尔来巡山
* Ahmed ABERWAG
* Daniel Santos
* David Libeau
* Ewald Arnold
* Florent F
* Florent Poinsaut
* Ignacio Carrera González
* Jayme Soares Almeida Cruz
* Lety Does Stuff
* Nassim Bounouas
* Rafael Fontenelle
* Thomas Kuntz
* Tzafrir Cohen
* Vri
* miro
* nexi
* owiox8+1viroxeaziaxw@sharklasers.com
* spf
* wazakovsky
* yns bag
* Anne-Gaelle Moulun
* Arman
* Asier Iturralde Sarasola
* BRAINS YUM
* Belkacem Mohammed
* Bob Oob
* Côme 744
* Dimitri Gilbert
* Flavio F. M
* Frank Chang
* Green-Star
* I_Automne
* Ilia
* Marek Ľach
* Micah Elizabeth Scott
* Pierre-Jean
* Ret Samys
* SVNET Libre
* StarAtt
* Tomasz
* Tony Simoes
* William Lahti
* Wirebrass
* Yury Bulka
* boris joeson
* frankstrater
* mater
* test2a
* think4web
* 路过是好事
* Ajeje Brazorf
* Andreas Grupp
* Andrey
* Angristan
* Benjamin Seitz
* Cirnos
* Cokelat8
* DontUseGithub
* Eder Etxebarria
* Farooq Karimi Zadeh
* Frederic Bezies
* Iñigo
* Jim Kats
* Joan Montané
* José M
* Kristoffer Grundström
* LecygneNoir
* Liu Zhiyu
* Lukas
* MahdiTurki
* Martijn Dekker
* Mats Blomdahl
* Maxime Louet
* Mildred
* Murat Hasdemir
* Murat Özalp
* Nikolay
* Okhin
* Osama
* Pierre-Alain TORET
* Serge Victor
* Théo Le Calvar
* Ugaitz
* Vaclovas Intas
* Vincent Finance
* aschaap
* clementbrizard
* gohoso9454
* helabasa
* kaiyou
* max
* roberto marcolin
* Ahsan Haris Ahmed
* Alberto Teira
* Alejandro
* Alex
* Aliaksandr Hrankin
* Anael González Paz
* Andréas Livet
* Andrés Maldonado
* Arco
* Armin Kunkel
* Asr128
* Aurélien Bertron
* Axel Viala
* Casper Ruttten
* Charles-Edouard Gervais
* Danail Emandiev
* Daniele Garau
* Dep Pranata
* Dirk Kelly
* Ehsan Gholami
* Elga Ahmad Prayoga
* Girish Ramakrishnan
* Goudarz Jafari
* Hakim Oubouali
* Hans Meiser
* Iñigo A
* Jefferson Hernandez
* Jelle Besseling
* Jocelyn Jaubert
* Johan Fleury
* Jurij Podgoršek
* Kindred La Boneta
* Kiro
* Leopere
* Linus
* Lionel Caylat
* Lukas Winkler
* M Z
* Manuela Silva
* Marian
* Morpheus Tao
* Mélanie Chauvel
* Natsuki Tsukishiro
* Paolo Mauri
* Pedro
* Petr Balíček
* Piotr Sikora
* Stardream
* Stefan Keks
* Tom Wellington
* Urtzi Odriozola
* Victor Hampel
* Waazdakka
* Winfried Hyronimus
* Yohan Boniface
* am97
* anotheranonymoususer
* dada
* frankdelange
* h3n3
* iapellaniz
* jonathanraes
* legiorange
* numéro6
* saleh oukiki
* Àngel Pérez Beroy
* Ömer Faruk Çakmak
* AQR_Rastiq
* Al-Hassan Abdel-Raouf
* Alecks Gates
* Amos Tamam
* Andrea Monaco
* Andrew Morgan
* Andy Khit
* Antimidia
* Antonio Pandza
* Aristeidis Alexandridis
* Arne Uplegger
* Aurélien Béranger
* Average Dude
* BGR2
* BitTube
* Boo
* Boo Teille
* Branislav Pavelka
* Dashie
* David Luís Pereira Pires
* David Marzal
* Doug Luce
* Emv
* EndoGai
* Fatih Özsoy
* FediverseTV
* Florent Fayolle
* Florian
* Frank de Lange
* G4dter
* Gaëtan Rizio
* Gopherslol
* HHY
* Hange
* Hjalte
* HugeFrog24
* Hugo Peixoto
* HybridGlucose
* J C Worm
* Jan Ainali
* Jan Hartig
* Jan Marsalek
* Jerguš Fonfer
* Jeroen de Wijn
* José Daniel Angulo Plata
* Joël Galeran
* Julien Lemaire
* Julien Rabier
* Lucas Teixeira
* Mamiako Pavel
* Masood Masaeli
* Millicent Billette
* Mondo Xíbaro
* Moritz Warning
* Mostafa Ahangarha
* Neko Nekowazarashi
* Nicolai Larsen
* Nojus
* Olivier Bouillet
* Pedro hates github.com
* Pep
* Pierre Jaury
* Piotr Strębski
* Puryx
* Quentin
* ROBERT MCDOWELL
* Ronan
* SerCom_KC
* Skid
* Stakovicz
* Suthep
* Takeshi Umeda
* Thai Localization
* The Cashew Trader
* Thijs Kinkhorst
* Timur Seber
* Toso Malero
* Tsuki
* Túlio Simões Martins Padilha
* Valvin
* XblateX
* Yaron Shahrabani
* YiDai
* Yogesh K S
* ahmadsharifian
* bopol
* brucekomike
* darek
* dingycle
* framail
* imgradeone Yan
* kafbatur kafbatarsson
* les
* libertas
* merty
* ou jian bo
* plr20
* q_h
* qwerty
* taziden
* vancha march
* victor héry
* 3risian
* A.D.R.S
* Acid Chicken (硫酸鶏)
* Adam Adamsky
* Adam Gauthier
* Adam Magnier
* Adnane Belmadiaf
* Adrien A
* Agron
* Aitozl
* Alberto Mardegan
* Alejandro Criado-Pérez
* Aleksandr Sokolov
* Alessandro Molina
* Alexander F. Rødseth
* Ali Alim
* Alperen Abak
* Alvar C.H. Freude
* Aman Sharma
* Anatoly
* Anatoly Bogomolov
* Andrews Góes Santos
* Antoine Millet
* Anton Latukha
* Apps
* Armando Lüscher
* Artem Prosvetov
* Arthur Lutz
* Austin Heap
* Autom
* Ben Abbott
* Ben Lubar
* Benjamin EWFT
* Benoît Piédallu
* Bojidar Marinov
* Brad Johnson
* Cadence Ember
* Cale
* Carlos García Gutiérrez
* Charles de Lacombe
* Charlie Lambda
* Christoph Geschwind
* Chronos
* Claude
* Clifford Garwood II
* Clément Brizard
* Cédric Bahirwe
* DLP
* Daniel Dutra
* David Baumgold
* David Dobryakov
* DeeJayBro
* Denis Dupont
* Deval
* Dimitri DI GUSTO
* Dimitrios Glentadakis
* Durgaraj Karki
* Edouard SCHWEISGUTH
* Edwin Alberto Amado Baron
* Emmanuel Pret
* Enfong Cao
* Eric Brehault
* Erwan Croze
* Esmail_Hazem
* Ethan Corgatelli
* FB
* Fabio Agreles Bezerra
* FediThing
* Fernandez, ReK2
* Framasoft
* Gabriel Scherer
* Gergo Bogdan
* Glandos
* Grant
* Grzesiek11
* Guillaume Pérution-Kihli
* Gérald CHATAGNON
* Haelwenn (lanodan) Monnier
* Henri BAUDESSON
* HesioZ
* Hozan Şahin
* Hydrolien
* ICabaleiro
* Iker Garaialde
* Ismaël Bouya
* Ivan Ip
* Iván Cabaleiro
* J Webb
* Jacen
* Jackson
* Jackson Chen
* Jacob
* Jacques Foucry
* Jagannath Bhat
* Jan Prunk
* Janey Muñoz
* Jarosław Maciejewski
* Jaz Dina
* Jeena
* Jessica Fairchild
* Jeston Tan
* Jinn Koriech
* Jlll1
* Johan van Dongen
* Johnny Jazeix
* Jonas Sulzer
* Jonatan Nyberg
* Jonathan Weth
* Jorge Silva
* Jos
* Julien Le Bras
* Juraj Liso
* JustAnotherArchivist
* Kent Anderson
* Kevin Cope
* Kevin Pliester
* Khyvodul
* Knackie
* Kody
* Konstantinos Agiannis
* Kyâne Pichou
* Leo Mouyna
* Lesterpig
* Levi Bard
* LiPeK
* Lint
* LoveIsGrief
* Luca B
* Lucian I. Last
* Lucien A
* Lupinard
* Léane GRASSER
* Léo Andrès
* ManMade-cube42
* Marcel Fuhrmann
* Marco Zehe
* Marcus Schwarz
* Marian Steinbach
* Mario Pepe
* Markus Richter
* Martin Trigaux
* Matej Šujan
* Mateusz Piotrowski
* Mathieu Agopian
* Mathieu Brunot
* Matthias Frey
* Matthieu De Beule
* Max Rosenfors
* Michael Koppmann
* Michael Williams
* Midgard
* Miguel Mayol Tur
* Miguel P.L
* Mike
* Mikel Gartzia Santamaria
* Milo van der Linden
* MrGiga
* Mélanie Pin
* Nataly Rocha
* Nathanaël J
* Net
* Nicolas Fortin
* Niklas Reimer
* Nitesh Sawant
* Novel Martin Harianto
* Nuño Sempere
* Olivier Jolly
* Oliwier Jaszczyszyn
* Pablo Joubert
* Paul FLORENCE
* Paul V
* Pavel 7 Tomsk
* PhieF
* Philip Durbin
* Philipp Fischbeck
* Philo van Kemenade
* Predatorix Phoenix
* Quantic Axe
* Quentin Dupont
* Quentí
* RF9A5V
* ROPEDE
* Ramazan Geven
* Ramiellll
* Rangel Prodanov
* Raphael
* Raphaël Droz
* Ray
* Rebecca
* Rech
* Rep Dolsay
* RiQuY
* Robert Riemann
* Roberto Resoli
* Robin
* Rostyslav Haitkulov
* Salif Mehmed
* Sankar
* SansPseudoFix
* Sarah Lewis
* Scott Starkey
* Sebastian Paweł Wolski
* Seth Falco
* Shalabh Agarwal
* Showfom
* Shun Sakai
* Simon Gilliot
* Simounet
* Stefan Schüller
* Steffen
* Steffen Möller
* Subh B
* Sumit Khanna
* SupC
* Sébastien NOBILI
* TA
* Tanguy BERNARD
* Thavarasa Prasanth
* Theodore R. Smith
* Thomas
* Timo Gurr
* Timothée Grégoire
* Tolga KARABATAK
* Tomás Sebastián Romero
* TrashMacNugget
* Treacle
* Unetelle Inconnue
* Vagelis F
* Varik Valefor
* Vegard Fjeldberg
* VeryREAL
* Vik
* Vincent Stakenburg
* WhiredPlanck
* William Cliff
* WingsLikeEagles
* Yann Sionneau
* Yehuda Deutsch
* Yorwba
* Yun
* Zack Birkenbuel
* Zekovski
* Zig-03
* [ Bie ] Watcharapong Suriyawan
* adam iter
* allmiha2
* anmol26s
* april
* ar9708
* augier
* big gamer
* bikepunk
* bsky
* chagai95
* ctlaltdefeat
* decentral1se
* eduard pintilie
* framabr
* fuomag9
* gillux
* jameskimmel
* jinubook
* jomo
* kukhariev
* lambdacastix
* libertysoft3
* lost_geographer
* lsde
* ltsallas
* luz paz
* luz.paz
* luzpaz
* madmath03
* mahdi
* memorybox
* mike stedman
* mira.bat
* mj-saunders
* morteza
* no
* norrist
* nxjoseph
* osauzet
* paring
* paulienm
* philippe lhardy
* pitchum
* potedeo
* q0ntinuum
* rdxuan
* retiolus
* ruvilonix
* sanchis
* skyone-wzw
* slendermon
* smilekison
* sn0wygecko
* soonsouth
* thecashewtrader
* tilllt
* tmpod
* tomamplius
* toobad
* treac1e
* tuxayo
* victor-long
* xcffl
* zacharystenger
* Éloi Rivard
* Óscar Fernández Díaz
* Артур Кирпо
* Дмитрий Кузнецов
* noisawe
* 姚霁恒
* abdhessuk
* abidin24
* aditoo
* alice
* anastasia
* autom
* balaji
* bristow
* butterflyoffire
* claichou
* degrange
* dibek
* edu
* ehsaan
* esoforte
* fkohrt
* giqtaqisi
* goofy
* gorkaazk
* gwendald
* h3zjp
* jfblanc
* jhertel
* jmf
* jorropo
* kairozen
* kedemferre
* kousha
* krkk
* landrok
* leeroyepold48
* m4sk1n
* matograine
* medow
* mhu
* midgard
* nbrucy
* nitai
* noncommutativegeo
* nopsidy
* nvivant
* osoitz
* outloudvi
* quentin
* quentind
* rafaelff
* rigelk
* s8321414
* sato_ss
* sercom_kc
* severo
* silkevicious
* sosha
* spla
* strubbl
* swedneck
* tagomago
* talone
* thibaultmartin
* tirifto
* tuxayo
* unextro
* unzarida
* vincent
* wanhua
* xinayder
* xosem
* zveryok
* 6543
* aasami
* alidemirtas
* alpha
* ariasuni
* bfonton
* c0dr
* canony
* cat
* clerie
* curupira
* dhsets
* digitalkiller
* dwsage
* flauta
* frankstrater
* gillux
* gunchleoc
* jaidedtd
* joss2lyon
* kekkotranslates
* kingu
* kittybecca
* knuxify
* lapor
* laufor
* lstamellos
* lw1
* mablr
* marcinmalecki
* mayana
* mikeorlov
* nin
* norbipeti
* ppnplus
* predatorix
* robin
* rond
* secreet
* sftblw
* sporiff
* tekuteku
* thecatjustmeow
* tmota
* uranix
* wakutiteo
* wonderingdane
* zeynepeliacik
# Design
* [Olivier Massain](https://dribbble.com/omassain)
* [Marie-Cécile Godwin Paccard](https://mcgodwin.com/)
* [La Coopérative des Internets](https://www.lacooperativedesinternets.fr/)
# Icons
* [Feather Icons](https://feathericons.com) (MIT)
* [Lucide Icons](https://lucide.dev/) (ISC)
* `playlist add`, `history`, `subscriptions`, `miscellaneous-services.svg`, `tip` by Material UI (Apache 2.0)
* `support` by Chocobozzz (CC-BY)
* `language` by Aaron Jin (CC-BY)
* `video-language` by Rigel Kent (CC-BY)
* `peertube-x` by Solen DP (CC-BY)
* `flame` by Freepik (Flaticon License)
* `local` by Larea (CC-BY)
* X (Twitter) icon: [Wikimedia Commons](https://fr.m.wikipedia.org/wiki/Fichier:X_logo_2023.svg)
# Contributors to our 2020 crowdfunding :heart:
*We ran [a crowdfunding campaign](https://joinpeertube.org/roadmap) in 2020 to implement live streaming to the version 3.0.0 of PeerTube. Thanks to everyone who pitched in and shared the news!*
# Contributors to our 2018 crowdfunding :heart:
*We ran [a crowdfunding campaign](https://www.kisskissbankbank.com/en/projects/peertube-a-free-and-federated-video-platform) in 2018 to pave the road to the version 1.0.0 of PeerTube, with 1,379 backers. Thanks to everyone who pitched in and shared the news!*

1
FAQ.md Normal file
View File

@@ -0,0 +1 @@
Moved to https://joinpeertube.org/faq

576
INSTALLATION.md Normal file
View File

@@ -0,0 +1,576 @@
# SolTube Installation Guide
This guide covers two installation methods: local development server and Docker production deployment.
## Table of Contents
- [System Requirements](#system-requirements)
- [Development Server Setup](#development-server-setup)
- [Docker Deployment](#docker-deployment)
- [Environment Configuration](#environment-configuration)
- [Troubleshooting](#troubleshooting)
---
## System Requirements
### For Development Server
- **Node.js**: >= 20.x
- **pnpm**: >= 10.9
- **PostgreSQL**: >= 10.x
- **Redis**: >= 6.x
- **FFmpeg**: >= 4.3
- **Python**: >= 3.8
- **Operating System**: Linux, macOS, or WSL2 on Windows
### For Docker Deployment
- **Docker**: >= 20.10
- **Docker Compose**: >= 1.29
- **Disk Space**: >= 50GB (for video storage)
- **RAM**: >= 4GB recommended
---
## Development Server Setup
### 1. Prerequisites Installation
#### On Ubuntu/Debian:
```bash
# Install Node.js (if not already installed)
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt-get install -y nodejs
# Install pnpm
npm install -g pnpm
# Docker
sudo apt-get install -y docker.io docker-compose-plugin
sudo systemctl enable docker
sudo systemctl start docker
# Install FFmpeg
sudo apt-get install -y ffmpeg
# Install build tools
sudo apt-get install -y build-essential python3 python3-pip
```
#### On macOS (using Homebrew):
```bash
# Install Node.js
brew install node
# Install pnpm
npm install -g pnpm
# Install FFmpeg
brew install ffmpeg
# Install Python
brew install python3
# Install Docker Desktop
# https://www.docker.com/products/docker-desktop/
```
#### On Windows:
Download and install Node.js (v20):
[https://nodejs.org/en/download](https://nodejs.org/en/download)
```bash
# Install pnpm
npm install -g pnpm
#Install Chocolatey (admin PowerShell):
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
#Then:
choco install ffmpeg -y
```
Download:
[https://www.python.org/downloads/windows/](https://www.python.org/downloads/windows/)
IMPORTANT:
✔ Check **Add Python to PATH**
---
### 2. Start PostgreSQL + Redis using Docker
Create a directory for local containers:
```bash
mkdir -p dev-services
cd dev-services
```
---
Create docker-compose.yml
```yaml
version: "3.9"
services:
postgres:
image: postgres:17-alpine
container_name: soltube-postgres
restart: unless-stopped
environment:
POSTGRES_USER: peertube
POSTGRES_PASSWORD: peertube
POSTGRES_DB: peertube_dev
ports:
- "5432:5432"
volumes:
- soltube_pgdata:/var/lib/postgresql/data
redis:
image: redis:8-alpine
container_name: soltube-redis
restart: unless-stopped
ports:
- "6379:6379"
volumes:
- soltube_redisdata:/data
volumes:
soltube_pgdata:
soltube_redisdata:
```
------
Start services
```bash
docker compose up -d
```
Verify:
```bash
docker ps
# You should see:
# peertube-postgres
# peertube-redis
```
### 3. Initialize PostgreSQL extensions
Run:
```bash
docker exec -it peertube-postgres psql -U peertube -d peertube_dev
```
Inside psql:
```bash
CREATE EXTENSION pg_trgm;
CREATE EXTENSION unaccent;
\dx
\q
```
### 4. Clone and Install Dependencies
```bash
# Clone the repository
git clone https://gitea.hamlyn.app/Solace/soltube-peertube.git
cd soltube-peertube
# Install dependencies
pnpm install --frozen-lockfile
# Build the server
pnpm run build:server
```
### 5. Configure Environment
```bash
# Generate a secret key
openssl rand -hex 32
# Copy the output for later use
# Create development config
cp config/default.yaml config/dev.yaml
# Edit the dev config
nano config/dev.yaml
```
Add or update the following in `config/dev.yaml`:
```yaml
listen:
hostname: '127.0.0.1'
port: 9000
webserver:
https: false
hostname: 'localhost'
port: 9000
secrets:
peertube: '<YOUR_GENERATED_SECRET_HERE>'
database:
hostname: 'localhost'
port: 5432
username: 'peertube'
password: '<YOUR_DATABASE_PASSWORD>'
pool:
min: 2
max: 20
redis:
hostname: 'localhost'
port: 6379
log:
level: 'debug'
user:
video_quota: -1
```
### 6. Run Development Server
```bash
# Start the development server with hot reload
pnpm run dev:server
```
The server will start at `http://localhost:9000`
**Development Credentials:**
- Username: `root`
- Password: `test`
### 7. Access the Application
- **API**: http://localhost:9000/api/v1
- **Web UI**: http://localhost:3000 (if running full dev stack)
### Optional: Run Full Development Stack
If you want to also run the client development server:
```bash
# Start both server and client
pnpm run dev
```
This will run:
- Backend server on port 9000
- Frontend on port 3000
---
## Docker Deployment
### 1. Prepare Docker Environment
```bash
cd PeerTube/support/docker/production
# Create required directories
mkdir -p docker-volume/data
mkdir -p docker-volume/config
mkdir -p docker-volume/db
mkdir -p docker-volume/redis
mkdir -p docker-volume/nginx
```
### 2. Configure Environment Variables
```bash
# Copy the environment template
cp .env.example .env
# Edit the .env file with your settings
nano .env
```
**Essential variables to configure:**
```bash
# Database
POSTGRES_DB=peertube
POSTGRES_USER=peertube
POSTGRES_PASSWORD=<generate_strong_password>
POSTGRES_INITDB_ARGS=-c shared_preload_libraries=pg_stat_statements
# PeerTube
PEERTUBE_DB_USERNAME=peertube
PEERTUBE_DB_PASSWORD=<same_as_postgres_password>
PEERTUBE_DB_HOSTNAME=postgres
PEERTUBE_DB_PORT=5432
PEERTUBE_DB_SUFFIX=
# Secrets
PEERTUBE_SECRET=<generate_with_openssl_rand_-hex_32>
# WebServer
PEERTUBE_WEBSERVER_HOSTNAME=<your-domain.com>
PEERTUBE_WEBSERVER_HTTPS=true
PEERTUBE_WEBSERVER_PORT=443
# Email (optional but recommended)
PEERTUBE_SMTP_HOSTNAME=<your-smtp-server>
PEERTUBE_SMTP_PORT=587
PEERTUBE_SMTP_USERNAME=<your-email>
PEERTUBE_SMTP_PASSWORD=<your-password>
PEERTUBE_SMTP_FROM_ADDRESS=noreply@<your-domain.com>
# Admin user
PEERTUBE_ADMIN_EMAIL=admin@<your-domain.com>
```
### 3. Network Configuration
Create or edit docker-compose.yml to match your requirements:
```bash
# Uncomment and configure the nginx/webserver section for production
# Update the peertube service to use your domain
# Configure SSL certificates if using HTTPS
```
### 4. Build and Start Containers
```bash
# Option A: Using pre-built images (recommended for production)
docker-compose pull
docker-compose up -d
# Option B: Building from source
docker-compose build --build-arg ALREADY_BUILT=0
docker-compose up -d
# Verify all services are running
docker-compose ps
```
### 5. Initial Setup
```bash
# Wait for containers to be healthy (check docker-compose logs)
docker-compose logs -f peertube
# The application should be accessible at your configured domain
# You can also access it directly via port 9000 during setup:
# http://<your-server-ip>:9000
```
### 6. Common Docker Operations
```bash
# View logs
docker-compose logs -f peertube
docker-compose logs -f postgres
docker-compose logs -f redis
# Stop all services
docker-compose down
# Stop and remove all data (⚠️ careful - this deletes everything)
docker-compose down -v
# Restart a specific service
docker-compose restart peertube
# Execute a command in the container
docker-compose exec peertube npm run create-import-video-file-job -- --help
# Backup database
docker-compose exec postgres pg_dump -U peertube peertube > backup.sql
# Restore database
docker-compose exec -T postgres psql -U peertube peertube < backup.sql
# Update to latest image
docker-compose pull peertube
docker-compose up -d peertube
```
---
## Environment Configuration
### Application Configuration Files
Configuration files are located in `/config` directory inside the container:
- **Main Config**: `/app/config/default.yaml` - Default settings (don't edit)
- **Custom Config**: `/config/production.yaml` - Your custom configuration
- **Docker Config**: `/app/support/docker/production/config/` - Docker-specific defaults
### Key Configuration Options
**Video Upload Settings:**
```yaml
upload:
rate_limit_bytes_per_second: -1 # -1 means unlimited
max_file_size: 500GB
transcoding:
enabled: true
allow_additional_extensions: true
allow_audio_files: true
threads: 0 # 0 = auto-detect
```
**Federation:**
```yaml
federation:
videos:
federate_unlisted: true
max_followers: -1
```
**Live Streaming:**
```yaml
live:
enabled: true
allow_replay: true
max_duration: 0 # 0 = unlimited
max_user_lives: 3
```
---
## Troubleshooting
### Development Server Issues
**Port already in use:**
```bash
# Find process using port 9000
lsof -i :9000
# Kill the process
kill -9 <PID>
```
**PostgreSQL connection failed:**
```bash
# Check PostgreSQL is running
sudo systemctl status postgresql
# Check database exists
sudo -u postgres psql -l | grep peertube
# Check extensions
sudo -u postgres psql -d peertube_dev -c "\dx"
```
**Redis connection failed:**
```bash
# Check Redis is running
sudo systemctl status redis-server
# Test Redis connection
redis-cli ping
```
**Build errors:**
```bash
# Clear node_modules and reinstall
rm -rf node_modules pnpm-lock.yaml
pnpm install --frozen-lockfile
# Rebuild
pnpm run build:server
```
### Docker Deployment Issues
**Containers not starting:**
```bash
# Check logs for errors
docker-compose logs peertube
docker-compose logs postgres
docker-compose logs redis
# Verify environment variables
cat .env
# Restart services
docker-compose restart
```
**Database permission errors:**
```bash
# Fix directory permissions
sudo chown -R $(id -u):$(id -g) docker-volume/
# Restart database
docker-compose restart postgres
```
**Port conflicts:**
```bash
# Check if ports are in use
netstat -tlnp | grep 9000
netstat -tlnp | grep 5432
netstat -tlnp | grep 6379
# Change ports in docker-compose.yml and .env
```
**Memory issues:**
```bash
# Check Docker memory limits
docker stats
# Increase Docker memory in Docker Desktop Settings
# Or adjust container memory limits in docker-compose.yml
```
**Certificate renewal failing:**
```bash
# Check Certbot logs
docker-compose logs certbot
# Manual renewal
docker-compose exec certbot certbot renew --force-renewal
# Verify certificate
docker-compose exec webserver nginx -t
```
---
## Next Steps
### After Installation
1. **Admin Panel**: Access `/admin` to configure instance settings
2. **User Management**: Create additional user accounts
3. **Plugin Installation**: Install plugins from the admin panel
4. **Custom Branding**: Customize theme and instance name
5. **Federation**: Configure federation settings if needed
### Maintenance
- **Regular Backups**: Set up automated PostgreSQL backups
- **Log Monitoring**: Monitor application and system logs
- **Updates**: Keep Docker images updated
- **Disk Space**: Monitor storage for videos and uploads
- **Database Maintenance**: Run `VACUUM` and `ANALYZE` periodically
### Security
- Change default admin password immediately
- Configure firewall rules
- Use HTTPS in production
- Keep Node.js and dependencies updated
- Review security settings in admin panel
- Configure rate limiting appropriately

661
LICENSE Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

188
README.md Normal file
View File

@@ -0,0 +1,188 @@
<h1 align="center">
<a href="https://joinpeertube.org">
<img src="https://joinpeertube.org/img/brand.png" alt="PeerTube">
</a>
</h1>
<p align=center>
<strong><a href="https://joinpeertube.org">Website</a></strong>
| <strong><a href="https://joinpeertube.org/instances">Join an instance</a></strong>
| <strong><a href="https://github.com/Chocobozzz/PeerTube/blob/develop/README.md#package-create-your-own-instance">Create an instance</a></strong>
| <strong><a href="https://github.com/Chocobozzz/PeerTube/blob/develop/README.md#contact">Chat with us</a></strong>
| <strong><a href="https://framasoft.org/en/#soutenir">Donate</a></strong>
</p>
<p align="center">
Be part of a network of multiple small federated, interoperable video hosting providers. Follow video creators and create videos. No vendor lock-in. All on a platform that is community-owned and ad-free.
</p>
<p align="center">
<strong>Developed with &#10084; by <a href="https://framasoft.org">Framasoft</a></strong>
</p>
<p align="center">
<a href="https://framasoft.org">
<img width="150px" src="https://lutim.cpy.re/FeRgHH8r.png" alt="Framasoft logo"/>
</a>
</p>
<div align="center">
<a href="https://github.com/Chocobozzz/PeerTube/actions?query=workflow%3A%22Test%22+branch%3Adevelop">
<img src="https://github.com/Chocobozzz/PeerTube/workflows/Test/badge.svg" alt="GitHub Test Status">
</a>
<a href="https://automate.browserstack.com/public-build/d0ZMeGpSUFRjaUpDNnN3NUdKY1l2TnNpTGVJaUI0bm9hYkNxMTRtQ1lHTT0tLVZQa2crbFB1c2RDZUl1Y1Blck02SFE9PQ==--5f956d6857c50e06a0b7b1fe405fb93d0f2d0e11%">
<img src="https://automate.browserstack.com/badge.svg?badge_key=d0ZMeGpSUFRjaUpDNnN3NUdKY1l2TnNpTGVJaUI0bm9hYkNxMTRtQ1lHTT0tLVZQa2crbFB1c2RDZUl1Y1Blck02SFE9PQ==--5f956d6857c50e06a0b7b1fe405fb93d0f2d0e11%" alt="BrowserStack Status">
</a>
<a href="https://weblate.framasoft.org/projects/peertube/angular/">
<img src="https://weblate.framasoft.org/widgets/peertube/-/angular/svg-badge.svg" alt="Weblate Status">
</a>
</div>
<br />
<p align="center">
<a href="https://framatube.org/videos/watch/217eefeb-883d-45be-b7fc-a788ad8507d3">
<img src="https://lutim.cpy.re/9CLXh0Ys.png" alt="screenshot" />
</a>
</p>
Introduction
----------------------------------------------------------------
PeerTube is a free, decentralized and federated video platform developed as an alternative to other platforms that centralize our data and attention, such as YouTube, Dailymotion or Vimeo. :clapper:
To learn more:
* This [two-minute video](https://framatube.org/videos/watch/217eefeb-883d-45be-b7fc-a788ad8507d3) (hosted on PeerTube) explaining what PeerTube is and how it works
* PeerTube's project homepage, [joinpeertube.org](https://joinpeertube.org)
* Demonstration instances:
* [peertube.cpy.re](https://peertube.cpy.re) (stable)
* [peertube2.cpy.re](https://peertube2.cpy.re) (Nightly)
* [peertube3.cpy.re](https://peertube3.cpy.re) (RC)
* This [video](https://peertube.cpy.re/videos/watch/da2b08d4-a242-4170-b32a-4ec8cbdca701) demonstrating the communication between PeerTube and [Mastodon](https://github.com/tootsuite/mastodon) (a decentralized Twitter alternative)
:sparkles: Features
----------------------------------------------------------------
<p align=center>
<strong><a href="https://joinpeertube.org/faq#what-are-the-peertube-features-for-viewers">All features for viewers</a></strong>
| <strong><a href="https://joinpeertube.org/faq#what-are-the-peertube-features-for-content-creators">All features for content creators</a></strong>
| <strong><a href="https://joinpeertube.org/faq#what-are-the-peertube-features-for-administrators">All features for administrators</a></strong>
</p>
<img src="https://lutim.cpy.re/AHbctLjn.png" align="left" height="300px"/>
<h3 align="left">Video streaming, even in live!</h3>
<p align="left">
Just upload your videos, and be sure they will stream anywhere. Add a description, some tags and your video will be discoverable by the entire video fediverse, not just your instance. You can even embed a player on your favorite website!
</p>
<p align="left">
You are used to hosting live events? We got you covered too! Start livestreaming from your favorite client, and even host permanent streams!
</p>
---
<img src="https://lutim.cpy.re/cxWccUK7.png" align="right" height="200px"/>
<h3 align="right">Keep in touch with video creators</h3>
<p align="right">
Follow your favorite channels from PeerTube or really any other place. No need to have an account on the instance you watched a video to follow its author, you can do all of that from the Fediverse (Mastodon, Pleroma, and plenty others), or just with good ol' RSS.
</p>
---
<img src="https://lutim.cpy.re/K07EhFbt.png" align="left" height="200px"/>
<h3 align="left">An interface to call home</h3>
<p align="left">
Be it as a user or an instance administrator, you can decide what your experience will be like. Don't like the colors? They are easy to change. Don't want to list videos of an instance but let your users subscribe to them? Don't like the regular web client? All of that can be changed, and much more. No UX dark pattern, no mining your data, no video recommendation bullshit™.
</p>
---
<h3 align="right">Communities that help each other</h3>
<p align="right">
In addition to visitors using P2P with WebRTC to share the load among them, instances can help each other by caching one another's videos. This way even small instances have a way to show content to a wider audience, as they will be shouldered by friend instances (more about that in our <a href="https://docs.joinpeertube.org/contribute/architecture#redundancy-between-instances">redundancy guide</a>).
</p>
<p align="right">
Content creators can get help from their viewers in the simplest way possible: a support button showing a message linking to their donation accounts or really anything else. No more pay-per-view and advertisements that hurt visitors and alter creativity (more about that in our <a href="https://github.com/Chocobozzz/PeerTube/blob/develop/FAQ.md">FAQ</a>).
</p>
:raised_hands: Contributing
----------------------------------------------------------------
You don't need to be a programmer to help!
You can give us your feedback, report bugs, help us translate PeerTube, write documentation, and more. Check out the [contributing
guide](https://docs.joinpeertube.org/contribute/getting-started) to know how, it takes less than 2 minutes to get started. :wink:
You can also join the cheerful bunch that makes our community:
* Chat<a name="contact"></a>:
* Matrix (bridged on IRC and [Discord](https://discord.gg/wj8DDUT)) : **[#peertube:matrix.org](https://matrix.to/#/#peertube:matrix.org)**
* IRC : **[#peertube on irc.libera.chat:6697](https://web.libera.chat/#peertube)**
* Forum:
* Framacolibri: [https://framacolibri.org/c/peertube](https://framacolibri.org/c/peertube)
Feel free to reach out if you have any questions or ideas! :speech_balloon:
:package: Create your own instance
----------------------------------------------------------------
See the [production guide](https://docs.joinpeertube.org/install/any-os), which is the recommended way to install or upgrade PeerTube. For hardware requirements, see [Should I have a big server to run PeerTube?](https://joinpeertube.org/faq#should-i-have-a-big-server-to-run-peertube) in the FAQ.
See the [community packages](https://docs.joinpeertube.org/install/unofficial), which cover various platforms (including [YunoHost](https://install-app.yunohost.org/?app=peertube) and [Docker](https://github.com/Chocobozzz/PeerTube/blob/develop/support/doc/docker.md)).
:book: Documentation
----------------------------------------------------------------
If you have a question, please try to find the answer in the [FAQ](https://joinpeertube.org/faq) first.
### User documentation
See the [user documentation](https://docs.joinpeertube.org/use/setup-account).
### Admin documentation
See [how to create your own instance](https://github.com/Chocobozzz/PeerTube/blob/develop/README.md#package-create-your-own-instance).
See the more general [admin documentation](https://docs.joinpeertube.org/admin/following-instances).
### Tools documentation
Learn how to import/upload videos from CLI or admin your PeerTube instance with the [tools documentation](https://docs.joinpeertube.org/maintain/tools).
### Technical documentation
See the [architecture blueprint](https://docs.joinpeertube.org/contribute/architecture) for a more detailed explanation of the architectural choices.
See our REST API documentation:
* OpenAPI 3.0.0 schema: [/support/doc/api/openapi.yaml](https://github.com/Chocobozzz/PeerTube/blob/develop/support/doc/api/openapi.yaml)
* Spec explorer: [docs.joinpeertube.org/api-rest-reference.html](https://docs.joinpeertube.org/api-rest-reference.html)
See our [ActivityPub documentation](https://docs.joinpeertube.org/api/activitypub).
## License
### Logo
[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/), by [Framasoft](https://framasoft.org)
### Code
Copyright (C) 2015-2025 PeerTube Contributors (see [CREDITS.md](/CREDITS.md))
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

71
SECURITY.md Normal file
View File

@@ -0,0 +1,71 @@
Security is core to our values, and we value the input of hackers acting in good faith to help us maintain a high standard for the security and privacy for our users. This includes encouraging responsible vulnerability research and disclosure. This policy sets out our definition of good faith in the context of finding and reporting vulnerabilities, as well as what you can expect from us in return.
## Expectations
When working with us according to this policy, you can expect us to:
- Extend Safe Harbor (see below) for your vulnerability research that is related to this policy;
- Work with you to understand and validate your report
- Work to remediate discovered vulnerabilities in a timely manner; and
- Recognize your contribution to improving our security if you are the first to report a unique vulnerability, and your report triggers a code or configuration change.
## Safe Harbor
When conducting vulnerability research according to this policy, we consider this research to be:
- Authorized in accordance with the law, and we will not initiate or support legal action against you for accidental, good faith violations of this policy;
- Exempt from the Digital Millennium Copyright Act (DMCA), and we will not bring a claim against you for circumvention of technology controls;
- Exempt from restrictions in our Terms & Conditions that would interfere with conducting security research, and we waive those restrictions on a limited basis for work done under this policy;
- Lawful, helpful to the overall security of the Internet, and conducted in good faith.
You are expected, as always, to comply with all applicable laws.
If at any time you have concerns or are uncertain whether your security research is consistent with this policy, please submit a report through one of our Official Channels before going any further.
## Ground Rules
To encourage vulnerability research and to avoid any confusion between good-faith hacking and malicious attack, we ask that you:
- Play by the rules. This includes following this policy, as well as any other relevant agreements. If there is any inconsistency between this policy and any other relevant terms, the terms of this policy will prevail.
- Report any vulnerability you have discovered promptly.
- Avoid violating the privacy of others, disrupting our systems, destroying data, and/or harming user experience.
- Use only the Official Channels to discuss vulnerability information with us.
- Keep the details of any discovered vulnerabilities confidential until they are fixed, according to the Disclosure Terms in this policy.
- Perform testing only on in-scope systems, and respect systems and activities which are out-of-scope. Systems currently considered in-scope are the official demonstration/test servers provided by the PeerTube development team.
- If a vulnerability provides unintended access to data: Limit the amount of data you access to the minimum required for effectively demonstrating a Proof of Concept; and cease testing and submit a report immediately if you encounter any user data during testing, such as Personally Identifiable Information (PII), Personal Healthcare Information (PHI), credit card data, or proprietary information.
- You should only interact with test accounts you own or with explicit permission from the account holder.
- Do not engage in extortion.
## Disclosure Terms
The vulnerability is kept private until a majority of instances known on instances.joinpeertube.org have updated to a safe version of PeerTube or applied a hotfix. The PeerTube development team coordinates efforts to update once the patch is issued.
## Official Channels
To help us receive vulnerability submissions we use the following official reporting channel:
- peertube-security@framasoft.org
The following PGP key can be used to encrypt your email:
```
-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEZjD41hYJKwYBBAHaRw8BAQdAfhTpNfIk8/doN8j+PnGzNazK6p6KXEatqz1L
ARAmlU20M1BlZXJUdWJlIFNlY3VyaXR5IDxwZWVydHViZS1zZWN1cml0eUBmcmFt
YXNvZnQub3JnPoiTBBMWCgA7FiEEr+3Jvd9JW64FG8cvQOaXHEo/b6cFAmYw+NYC
GwMFCwkIBwICIgIGFQoJCAsCBBYCAwECHgcCF4AACgkQQOaXHEo/b6fRbgD8DiAL
7o3eeHuYnQe1I+SnSHU6RDVk/OY27+ZFSrWgsYMBAAA16aGGkbmme1mmig+iEMiL
uhjVAfwuXb0VzrxqqmYMuDgEZjD41hIKKwYBBAGXVQEFAQEHQDCVpwHHyrS9rCQq
0uXbPTWkWuf8yZJqpzZSoG3KY5JZAwEIB4h4BBgWCgAgFiEEr+3Jvd9JW64FG8cv
QOaXHEo/b6cFAmYw+NYCGwwACgkQQOaXHEo/b6fwmAEAsiJDN2GG7sNA2ExjoNT8
P0hnqJkaRh8WJ/pi3u+QlWABAJj5qRhA3Om7SYJjzYfe3fEnrS5cTW51qc96r7GU
IdUI
=y06w
-----END PGP PUBLIC KEY BLOCK-----
```
If you think you have found a vulnerability, please include the following details with your report and be as descriptive as possible:
- The location and nature of the vulnerability,
- A detailed description of the steps required to reproduce the vulnerability (screenshots, compressed screen recordings, and proof-of-concept scripts are all helpful), and
- Your name/handle and a link for recognition.
If you would like to encrypt the information, please use our GPG key.
We may modify the terms of this program or terminate this program at any time. We will not apply any changes we make to these program terms retroactively.

View File

@@ -0,0 +1,4 @@
src
meta.json
tsconfig.json
scripts

View File

@@ -0,0 +1,5 @@
# Changelog
## v1.0.3
* Fix `util.isArray` deprecation warning

View File

@@ -0,0 +1,42 @@
# PeerTube CLI
## Usage
See https://docs.joinpeertube.org/maintain/tools#remote-tools
## Dev
## Install dependencies
```bash
cd peertube-root
npm run install-node-dependencies
```
## Develop
```bash
cd peertube-root
npm run dev:peertube-cli
```
## Build
```bash
cd peertube-root
npm run build:peertube-cli
```
## Run
```bash
cd peertube-root
node apps/peertube-cli/dist/peertube-cli.js --help
```
## Publish on NPM
```bash
cd peertube-root
(cd apps/peertube-cli && npm version patch) && npm run build:peertube-cli && (cd apps/peertube-cli && npm publish --access=public)
```

View File

@@ -0,0 +1,16 @@
{
"name": "@peertube/peertube-cli",
"version": "1.0.3",
"type": "module",
"main": "dist/peertube.js",
"bin": "dist/peertube.js",
"scripts": {},
"license": "AGPL-3.0",
"private": false,
"devDependencies": {
"application-config": "^3.0.0",
"cli-table3": "^0.6.0",
"netrc-parser": "^3.1.6"
},
"dependencies": {}
}

View File

@@ -0,0 +1,27 @@
import * as esbuild from 'esbuild'
import { readFileSync } from 'fs'
const packageJSON = JSON.parse(readFileSync(new URL('../package.json', import.meta.url)))
export const esbuildOptions = {
entryPoints: [ './src/peertube.ts' ],
bundle: true,
platform: 'node',
format: 'esm',
target: 'node16',
external: [
'./lib-cov/fluent-ffmpeg',
'pg-hstore'
],
outfile: './dist/peertube.js',
banner: {
js: `const require = (await import("node:module")).createRequire(import.meta.url);` +
`const __filename = (await import("node:url")).fileURLToPath(import.meta.url);` +
`const __dirname = (await import("node:path")).dirname(__filename);`
},
define: {
'process.env.PACKAGE_VERSION': `'${packageJSON.version}'`
}
}
await esbuild.build(esbuildOptions)

View File

@@ -0,0 +1,7 @@
import * as esbuild from 'esbuild'
import { esbuildOptions } from './build.js'
const context = await esbuild.context(esbuildOptions)
// Enable watch mode
await context.watch()

View File

@@ -0,0 +1,171 @@
import CliTable3 from 'cli-table3'
import prompt from 'prompt'
import { Command } from '@commander-js/extra-typings'
import { assignToken, buildServer, getNetrc, getSettings, writeSettings } from './shared/index.js'
export function defineAuthProgram () {
const program = new Command()
.name('auth')
.description('Register your accounts on remote instances to use them with other commands')
program
.command('add')
.description('remember your accounts on remote instances for easier use')
.option('-u, --url <url>', 'Server url')
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.option('--default', 'add the entry as the new default')
.action(options => {
prompt.override = options
prompt.start()
prompt.get({
properties: {
url: {
description: 'instance url',
conform: value => isURLaPeerTubeInstance(value),
message: 'It should be an URL (https://peertube.example.com)',
required: true
},
username: {
conform: value => typeof value === 'string' && value.length !== 0,
message: 'Name must be only letters, spaces, or dashes',
required: true
},
password: {
hidden: true,
replace: '*',
required: true
}
}
}, async (_, result) => {
// Check credentials
try {
// Strip out everything after the domain:port.
// See https://github.com/Chocobozzz/PeerTube/issues/3520
result.url = stripExtraneousFromPeerTubeUrl(result.url)
const server = buildServer(result.url)
await assignToken(server, result.username, result.password)
} catch (err) {
console.error(err.message)
process.exit(-1)
}
await setInstance(result.url, result.username, result.password, options.default)
process.exit(0)
})
})
program
.command('del <url>')
.description('Unregisters a remote instance')
.action(async url => {
await delInstance(url)
process.exit(0)
})
program
.command('list')
.description('List registered remote instances')
.action(async () => {
const [ settings, netrc ] = await Promise.all([ getSettings(), getNetrc() ])
const table = new CliTable3({
head: [ 'instance', 'login' ],
colWidths: [ 30, 30 ]
}) as any
settings.remotes.forEach(element => {
if (!netrc.machines[element]) return
table.push([
element,
netrc.machines[element].login
])
})
console.log(table.toString())
process.exit(0)
})
program
.command('set-default <url>')
.description('Set an existing entry as default')
.action(async url => {
const settings = await getSettings()
const instanceExists = settings.remotes.includes(url)
if (instanceExists) {
settings.default = settings.remotes.indexOf(url)
await writeSettings(settings)
process.exit(0)
} else {
console.log('<url> is not a registered instance.')
process.exit(-1)
}
})
program.addHelpText(
'after',
'\n\n Examples:\n\n' +
' $ peertube auth add -u https://peertube.cpy.re -U "PEERTUBE_USER" --password "PEERTUBE_PASSWORD"\n' +
' $ peertube auth add -u https://peertube.cpy.re -U root\n' +
' $ peertube auth list\n' +
' $ peertube auth del https://peertube.cpy.re\n'
)
return program
}
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
async function delInstance (url: string) {
const [ settings, netrc ] = await Promise.all([ getSettings(), getNetrc() ])
const index = settings.remotes.indexOf(url)
settings.remotes.splice(index)
if (settings.default === index) settings.default = -1
await writeSettings(settings)
delete netrc.machines[url]
await netrc.save()
}
async function setInstance (url: string, username: string, password: string, isDefault: boolean) {
const [ settings, netrc ] = await Promise.all([ getSettings(), getNetrc() ])
if (settings.remotes.includes(url) === false) {
settings.remotes.push(url)
}
if (isDefault || settings.remotes.length === 1) {
settings.default = settings.remotes.length - 1
}
await writeSettings(settings)
netrc.machines[url] = { login: username, password }
await netrc.save()
}
function isURLaPeerTubeInstance (url: string) {
return url.startsWith('http://') || url.startsWith('https://')
}
function stripExtraneousFromPeerTubeUrl (url: string) {
// Get everything before the 3rd /.
const urlLength = url.includes('/', 8)
? url.indexOf('/', 8)
: url.length
return url.substring(0, urlLength)
}

View File

@@ -0,0 +1,39 @@
import { Command } from '@commander-js/extra-typings'
import { assignToken, buildServer } from './shared/index.js'
export function defineGetAccessProgram () {
const program = new Command()
.name('get-access-token')
.description('Get a peertube access token')
.alias('token')
program
.option('-u, --url <url>', 'Server url')
.option('-n, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.action(async options => {
try {
if (
!options.url ||
!options.username ||
!options.password
) {
if (!options.url) console.error('--url field is required.')
if (!options.username) console.error('--username field is required.')
if (!options.password) console.error('--password field is required.')
process.exit(-1)
}
const server = buildServer(options.url)
await assignToken(server, options.username, options.password)
console.log(server.accessToken)
} catch (err) {
console.error('Cannot get access token: ' + err.message)
process.exit(-1)
}
})
return program
}

View File

@@ -0,0 +1,167 @@
import CliTable3 from 'cli-table3'
import { isAbsolute } from 'path'
import { Command } from '@commander-js/extra-typings'
import { PluginType, PluginType_Type } from '@peertube/peertube-models'
import { assignToken, buildServer, CommonProgramOptions, getServerCredentials } from './shared/index.js'
export function definePluginsProgram () {
const program = new Command()
program
.name('plugins')
.description('Manage instance plugins/themes')
.alias('p')
program
.command('list')
.description('List installed plugins')
.option('-u, --url <url>', 'Server url')
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.option('-t, --only-themes', 'List themes only')
.option('-P, --only-plugins', 'List plugins only')
.action(async options => {
try {
await pluginsListCLI(options)
} catch (err) {
console.error('Cannot list plugins: ' + err.message)
process.exit(-1)
}
})
program
.command('install')
.description('Install a plugin or a theme')
.option('-u, --url <url>', 'Server url')
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.option('-P --path <path>', 'Install from a path')
.option('-n, --npm-name <npmName>', 'Install from npm')
.option('--plugin-version <pluginVersion>', 'Specify the plugin version to install (only available when installing from npm)')
.action(async options => {
try {
await installPluginCLI(options)
} catch (err) {
console.error('Cannot install plugin: ' + err.message)
process.exit(-1)
}
})
program
.command('update')
.description('Update a plugin or a theme')
.option('-u, --url <url>', 'Server url')
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.option('-P --path <path>', 'Update from a path')
.option('-n, --npm-name <npmName>', 'Update from npm')
.action(async options => {
try {
await updatePluginCLI(options)
} catch (err) {
console.error('Cannot update plugin: ' + err.message)
process.exit(-1)
}
})
program
.command('uninstall')
.description('Uninstall a plugin or a theme')
.option('-u, --url <url>', 'Server url')
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.option('-n, --npm-name <npmName>', 'NPM plugin/theme name')
.action(async options => {
try {
await uninstallPluginCLI(options)
} catch (err) {
console.error('Cannot uninstall plugin: ' + err.message)
process.exit(-1)
}
})
return program
}
// ----------------------------------------------------------------------------
async function pluginsListCLI (options: CommonProgramOptions & { onlyThemes?: true, onlyPlugins?: true }) {
const { url, username, password } = await getServerCredentials(options)
const server = buildServer(url)
await assignToken(server, username, password)
let pluginType: PluginType_Type
if (options.onlyThemes) pluginType = PluginType.THEME
if (options.onlyPlugins) pluginType = PluginType.PLUGIN
const { data } = await server.plugins.list({ start: 0, count: 100, sort: 'name', pluginType })
const table = new CliTable3({
head: [ 'name', 'version', 'homepage' ],
colWidths: [ 50, 20, 50 ]
}) as any
for (const plugin of data) {
const npmName = plugin.type === PluginType.PLUGIN
? 'peertube-plugin-' + plugin.name
: 'peertube-theme-' + plugin.name
table.push([
npmName,
plugin.version,
plugin.homepage
])
}
console.log(table.toString())
}
async function installPluginCLI (options: CommonProgramOptions & { path?: string, npmName?: string, pluginVersion?: string }) {
if (!options.path && !options.npmName) {
throw new Error('You need to specify the npm name or the path of the plugin you want to install.')
}
if (options.path && !isAbsolute(options.path)) {
throw new Error('Path should be absolute.')
}
const { url, username, password } = await getServerCredentials(options)
const server = buildServer(url)
await assignToken(server, username, password)
await server.plugins.install({ npmName: options.npmName, path: options.path, pluginVersion: options.pluginVersion })
console.log('Plugin installed.')
}
async function updatePluginCLI (options: CommonProgramOptions & { path?: string, npmName?: string }) {
if (!options.path && !options.npmName) {
throw new Error('You need to specify the npm name or the path of the plugin you want to update.')
}
if (options.path && !isAbsolute(options.path)) {
throw new Error('Path should be absolute.')
}
const { url, username, password } = await getServerCredentials(options)
const server = buildServer(url)
await assignToken(server, username, password)
await server.plugins.update({ npmName: options.npmName, path: options.path })
console.log('Plugin updated.')
}
async function uninstallPluginCLI (options: CommonProgramOptions & { npmName?: string }) {
if (!options.npmName) {
throw new Error('You need to specify the npm name of the plugin/theme you want to uninstall.')
}
const { url, username, password } = await getServerCredentials(options)
const server = buildServer(url)
await assignToken(server, username, password)
await server.plugins.uninstall({ npmName: options.npmName })
console.log('Plugin uninstalled.')
}

View File

@@ -0,0 +1,181 @@
import { Command } from '@commander-js/extra-typings'
import { forceNumber, uniqify } from '@peertube/peertube-core-utils'
import { HttpStatusCode, VideoRedundanciesTarget } from '@peertube/peertube-models'
import bytes from 'bytes'
import CliTable3 from 'cli-table3'
import { URL } from 'url'
import { assignToken, buildServer, CommonProgramOptions, getServerCredentials } from './shared/index.js'
export function defineRedundancyProgram () {
const program = new Command()
.name('redundancy')
.description('Manage instance redundancies')
.alias('r')
program
.command('list-remote-redundancies')
.description('List remote redundancies on your videos')
.option('-u, --url <url>', 'Server url')
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.action(async options => {
try {
await listRedundanciesCLI({ target: 'my-videos', ...options })
} catch (err) {
console.error('Cannot list remote redundancies: ' + err.message)
process.exit(-1)
}
})
program
.command('list-my-redundancies')
.description('List your redundancies of remote videos')
.option('-u, --url <url>', 'Server url')
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.action(async options => {
try {
await listRedundanciesCLI({ target: 'remote-videos', ...options })
} catch (err) {
console.error('Cannot list redundancies: ' + err.message)
process.exit(-1)
}
})
program
.command('add')
.description('Duplicate a video in your redundancy system')
.option('-u, --url <url>', 'Server url')
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.requiredOption('-v, --video <videoId>', 'Video id to duplicate', parseInt)
.action(async options => {
try {
await addRedundancyCLI(options)
} catch (err) {
console.error('Cannot duplicate video: ' + err.message)
process.exit(-1)
}
})
program
.command('remove')
.description('Remove a video from your redundancies')
.option('-u, --url <url>', 'Server url')
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.requiredOption('-v, --video <videoId>', 'Video id to remove from redundancies', parseInt)
.action(async options => {
try {
await removeRedundancyCLI(options)
} catch (err) {
console.error('Cannot remove redundancy: ' + err)
process.exit(-1)
}
})
return program
}
// ----------------------------------------------------------------------------
async function listRedundanciesCLI (options: CommonProgramOptions & { target: VideoRedundanciesTarget }) {
const { target } = options
const { url, username, password } = await getServerCredentials(options)
const server = buildServer(url)
await assignToken(server, username, password)
const { data } = await server.redundancy.listVideos({ start: 0, count: 100, sort: 'name', target })
const table = new CliTable3({
head: [ 'video id', 'video name', 'video url', 'playlists', 'by instances', 'total size' ]
}) as any
for (const redundancy of data) {
const streamingPlaylists = redundancy.redundancies.streamingPlaylists
let totalSize = ''
if (target === 'remote-videos') {
const tmp = streamingPlaylists.reduce((a, b) => a + b.size, 0)
totalSize = bytes(tmp)
}
const instances = uniqify(
streamingPlaylists
.map(r => r.fileUrl)
.map(u => new URL(u).host)
)
table.push([
redundancy.id.toString(),
redundancy.name,
redundancy.url,
streamingPlaylists.length,
instances.join('\n'),
totalSize
])
}
console.log(table.toString())
}
async function addRedundancyCLI (options: { video: number } & CommonProgramOptions) {
const { url, username, password } = await getServerCredentials(options)
const server = buildServer(url)
await assignToken(server, username, password)
if (!options.video || isNaN(options.video)) {
throw new Error('You need to specify the video id to duplicate and it should be a number.')
}
try {
await server.redundancy.addVideo({ videoId: options.video })
console.log('Video will be duplicated by your instance!')
} catch (err) {
if (err.message.includes(HttpStatusCode.CONFLICT_409)) {
throw new Error('This video is already duplicated by your instance.', { cause: err })
}
if (err.message.includes(HttpStatusCode.NOT_FOUND_404)) {
throw new Error('This video id does not exist.', { cause: err })
}
throw err
}
}
async function removeRedundancyCLI (options: CommonProgramOptions & { video: number }) {
const { url, username, password } = await getServerCredentials(options)
const server = buildServer(url)
await assignToken(server, username, password)
if (!options.video || isNaN(options.video)) {
throw new Error('You need to specify the video id to remove from your redundancies')
}
const videoId = forceNumber(options.video)
const myVideoRedundancies = await server.redundancy.listVideos({ target: 'my-videos' })
let videoRedundancy = myVideoRedundancies.data.find(r => videoId === r.id)
if (!videoRedundancy) {
const remoteVideoRedundancies = await server.redundancy.listVideos({ target: 'remote-videos' })
videoRedundancy = remoteVideoRedundancies.data.find(r => videoId === r.id)
}
if (!videoRedundancy) {
throw new Error('Video redundancy not found.')
}
const ids = videoRedundancy.redundancies.streamingPlaylists
.map(r => r.id)
for (const id of ids) {
await server.redundancy.removeVideo({ redundancyId: id })
}
console.log('Video redundancy removed!')
}

View File

@@ -0,0 +1,175 @@
import { Command } from '@commander-js/extra-typings'
import { VideoCommentPolicy, VideoPrivacy, VideoPrivacyType } from '@peertube/peertube-models'
import { PeerTubeServer } from '@peertube/peertube-server-commands'
import { access, constants } from 'fs/promises'
import { isAbsolute } from 'path'
import { inspect } from 'util'
import { assignToken, buildServer, getServerCredentials, listOptions } from './shared/index.js'
type UploadOptions = {
url?: string
username?: string
password?: string
thumbnail?: string
preview?: string
file?: string
videoName?: string
category?: number
licence?: number
language?: string
tags?: string[]
nsfw?: true
videoDescription?: string
privacy?: VideoPrivacyType
channelName?: string
noCommentsEnabled?: true
support?: string
noWaitTranscoding?: true
noDownloadEnabled?: true
}
export function defineUploadProgram () {
const program = new Command('upload')
.description('Upload a video on a PeerTube instance')
.alias('up')
program
.option('-u, --url <url>', 'Server url')
.option('-U, --username <username>', 'Username')
.option('-p, --password <token>', 'Password')
.option('-b, --thumbnail <thumbnailPath>', 'Thumbnail path')
.option('--preview <previewPath>', 'Preview path')
.option('-f, --file <file>', 'Video absolute file path')
.option('-n, --video-name <name>', 'Video name')
.option('-c, --category <category_number>', 'Category number', parseInt)
.option('-l, --licence <licence_number>', 'Licence number', parseInt)
.option('-L, --language <language_code>', 'Language ISO 639 code (fr or en...)')
.option('-t, --tags <tags>', 'Video tags', listOptions)
.option('-N, --nsfw', 'Video is Not Safe For Work')
.option('-d, --video-description <description>', 'Video description')
.option('-P, --privacy <privacy_number>', 'Privacy', v => parseInt(v) as VideoPrivacyType)
.option('-C, --channel-name <channel_name>', 'Channel name')
.option('--no-comments-enabled', 'Disable video comments')
.option('-s, --support <support>', 'Video support text')
.option('--no-wait-transcoding', 'Do not wait transcoding before publishing the video')
.option('--no-download-enabled', 'Disable video download')
.option('-v, --verbose <verbose>', 'Verbosity, from 0/\'error\' to 4/\'debug\'', 'info')
.action(async options => {
try {
const { url, username, password } = await getServerCredentials(options)
if (!options.videoName || !options.file) {
if (!options.videoName) console.error('--video-name is required.')
if (!options.file) console.error('--file is required.')
process.exit(-1)
}
if (isAbsolute(options.file) === false) {
console.error('File path should be absolute.')
process.exit(-1)
}
await run({ ...options, url, username, password })
} catch (err) {
if (err.code === 'ECONNREFUSED') {
console.error(`Server is not responding`)
} else {
console.error('Cannot upload video: ' + err.message)
}
process.exit(-1)
}
})
return program
}
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
async function run (options: UploadOptions) {
const { url, username, password } = options
const server = buildServer(url)
await assignToken(server, username, password)
await access(options.file, constants.F_OK)
console.log('Uploading %s video...', options.videoName)
const baseAttributes = await buildVideoAttributesFromCommander(server, options)
const attributes = {
...baseAttributes,
fixture: options.file,
thumbnailfile: options.thumbnail,
previewfile: options.preview
}
try {
await server.videos.upload({ attributes })
console.log(`Video ${options.videoName} uploaded.`)
process.exit(0)
} catch (err) {
const message = err.message || ''
if (message.includes('413')) {
console.error('Aborted: user quota is exceeded or video file is too big for this PeerTube instance.')
} else {
console.error(inspect(err))
}
process.exit(-1)
}
}
async function buildVideoAttributesFromCommander (server: PeerTubeServer, options: UploadOptions) {
const defaultBooleanAttributes = {
nsfw: false,
downloadEnabled: true,
waitTranscoding: true
}
const booleanAttributes: { [id in keyof typeof defaultBooleanAttributes]: boolean } = {} as any
for (const key of Object.keys(defaultBooleanAttributes)) {
if (options[key] !== undefined) {
booleanAttributes[key] = options[key]
} else {
booleanAttributes[key] = defaultBooleanAttributes[key]
}
}
const videoAttributes = {
name: options.videoName,
category: options.category || undefined,
licence: options.licence || undefined,
language: options.language || undefined,
privacy: options.privacy || VideoPrivacy.PUBLIC,
support: options.support || undefined,
description: options.videoDescription || undefined,
tags: options.tags || undefined,
commentsPolicy: options.noCommentsEnabled !== undefined
? options.noCommentsEnabled === true
? VideoCommentPolicy.DISABLED
: VideoCommentPolicy.ENABLED
: undefined,
...booleanAttributes
}
if (options.channelName) {
const videoChannel = await server.channels.get({ channelName: options.channelName })
Object.assign(videoAttributes, { channelId: videoChannel.id })
if (!videoAttributes.support && videoChannel.support) {
Object.assign(videoAttributes, { support: videoChannel.support })
}
}
return videoAttributes
}

View File

@@ -0,0 +1,64 @@
#!/usr/bin/env node
import { Command } from '@commander-js/extra-typings'
import { defineAuthProgram } from './peertube-auth.js'
import { defineGetAccessProgram } from './peertube-get-access-token.js'
import { definePluginsProgram } from './peertube-plugins.js'
import { defineRedundancyProgram } from './peertube-redundancy.js'
import { defineUploadProgram } from './peertube-upload.js'
import { getSettings, version } from './shared/index.js'
const program = new Command()
program
.version(version, '-v, --version')
.usage('[command] [options]')
program.addCommand(defineAuthProgram())
program.addCommand(defineUploadProgram())
program.addCommand(defineRedundancyProgram())
program.addCommand(definePluginsProgram())
program.addCommand(defineGetAccessProgram())
// help on no command
if (!process.argv.slice(2).length) {
const logo = '░P░e░e░r░T░u░b░e░'
console.log(`
___/),.._ ` + logo + `
/' ,. ."'._
( "' '-.__"-._ ,-
\\'='='), "\\ -._-"-. -"/
/ ""/"\\,_\\,__"" _" /,-
/ / -" _/"/
/ | ._\\\\ |\\ |_.".-" /
/ | __\\)|)|),/|_." _,."
/ \\_." " ") | ).-""---''--
( "/.""7__-""''
| " ."._--._
\\ \\ (_ __ "" ".,_
\\.,. \\ "" -"".-"
".,_, (",_-,,,-".-
"'-,\\_ __,-"
",)" ")
/"\\-"
,"\\/
_,.__/"\\/_ (the CLI for red chocobos)
/ \\) "./, ".
--/---"---" "-) )---- by Chocobozzz et al.\n`)
}
getSettings()
.then(settings => {
const state = (settings.default === undefined || settings.default === -1)
? 'no instance selected, commands will require explicit arguments'
: 'instance ' + settings.remotes[settings.default] + ' selected'
program
.addHelpText('after', '\n\n State: ' + state + '\n\n' +
' Examples:\n\n' +
' $ peertube auth add -u "PEERTUBE_URL" -U "PEERTUBE_USER" --password "PEERTUBE_PASSWORD"\n' +
' $ peertube up <videoFile>\n'
)
.parse(process.argv)
})
.catch(err => console.error(err))

View File

@@ -0,0 +1,191 @@
import applicationConfig from 'application-config'
import { Netrc } from 'netrc-parser'
import { join } from 'path'
import { createLogger, format, transports } from 'winston'
import { UserRole } from '@peertube/peertube-models'
import { getAppNumber, isTestInstance, root } from '@peertube/peertube-node-utils'
import { PeerTubeServer } from '@peertube/peertube-server-commands'
export type CommonProgramOptions = {
url?: string
username?: string
password?: string
}
let configName = 'PeerTube/CLI'
if (isTestInstance()) configName += `-${getAppNumber()}`
const config = applicationConfig(configName)
const version: string = process.env.PACKAGE_VERSION
async function getAdminTokenOrDie (server: PeerTubeServer, username: string, password: string) {
const token = await server.login.getAccessToken(username, password)
const me = await server.users.getMyInfo({ token })
if (me.role.id !== UserRole.ADMINISTRATOR) {
console.error('You must be an administrator.')
process.exit(-1)
}
return token
}
interface Settings {
remotes: any[]
default: number
}
async function getSettings () {
const defaultSettings: Settings = {
remotes: [],
default: -1
}
const data = await config.read() as Promise<Settings>
return Object.keys(data).length === 0
? defaultSettings
: data
}
async function getNetrc () {
const netrc = isTestInstance()
? new Netrc(join(root(import.meta.url), 'test' + getAppNumber(), 'netrc'))
: new Netrc()
await netrc.load()
return netrc
}
function writeSettings (settings: Settings) {
return config.write(settings)
}
function deleteSettings () {
return config.trash()
}
function getRemoteObjectOrDie (
options: CommonProgramOptions,
settings: Settings,
netrc: Netrc
): { url: string, username: string, password: string } {
function exitIfNoOptions (optionNames: string[], errorPrefix = '') {
let exit = false
for (const key of optionNames) {
if (!options[key]) {
if (exit === false && errorPrefix) console.error(errorPrefix)
console.error(`--${key} field is required`)
exit = true
}
}
if (exit) process.exit(-1)
}
// If username or password are specified, both are mandatory
if (options.username || options.password) {
exitIfNoOptions([ 'username', 'password' ])
}
// If no available machines, url, username and password args are mandatory
if (Object.keys(netrc.machines).length === 0) {
exitIfNoOptions([ 'url', 'username', 'password' ], 'No account found in netrc')
}
if (settings.remotes.length === 0 || settings.default === -1) {
exitIfNoOptions([ 'url' ], 'No default instance found')
}
let url: string = options.url
let username: string = options.username
let password: string = options.password
if (!url && settings.default !== -1) url = settings.remotes[settings.default]
const machine = netrc.machines[url]
if ((!username || !password) && !machine) {
console.error('Cannot find existing configuration for %s.', url)
process.exit(-1)
}
if (!username && machine) username = machine.login
if (!password && machine) password = machine.password
return { url, username, password }
}
function listOptions (val: string) {
return val.split(',')
}
function getServerCredentials (options: CommonProgramOptions) {
return Promise.all([ getSettings(), getNetrc() ])
.then(([ settings, netrc ]) => {
return getRemoteObjectOrDie(options, settings, netrc)
})
}
function buildServer (url: string) {
return new PeerTubeServer({ url })
}
async function assignToken (server: PeerTubeServer, username: string, password: string) {
const bodyClient = await server.login.getClient()
const client = { id: bodyClient.client_id, secret: bodyClient.client_secret }
const body = await server.login.login({ client, user: { username, password } })
server.accessToken = body.access_token
}
function getLogger (logLevel = 'info') {
const logLevels = {
0: 0,
error: 0,
1: 1,
warn: 1,
2: 2,
info: 2,
3: 3,
verbose: 3,
4: 4,
debug: 4
}
const logger = createLogger({
levels: logLevels,
format: format.combine(
format.splat(),
format.simple()
),
transports: [
new (transports.Console)({
level: logLevel
})
]
})
return logger
}
// ---------------------------------------------------------------------------
export {
version,
getLogger,
getSettings,
getNetrc,
getRemoteObjectOrDie,
writeSettings,
deleteSettings,
getServerCredentials,
listOptions,
getAdminTokenOrDie,
buildServer,
assignToken
}

View File

@@ -0,0 +1 @@
export * from './cli.js'

View File

@@ -0,0 +1,15 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist",
"rootDir": "src",
"tsBuildInfoFile": "./dist/.tsbuildinfo"
},
"references": [
{ "path": "../../packages/core-utils" },
{ "path": "../../packages/models" },
{ "path": "../../packages/node-utils" },
{ "path": "../../packages/server-commands" }
]
}

3
apps/peertube-runner/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
node_modules
dist
meta.json

View File

@@ -0,0 +1,4 @@
src
meta.json
tsconfig.json
scripts

View File

@@ -0,0 +1,34 @@
# Changelog
## v0.4.0
* Copy codecs for HLS transcoding if possible
## v0.3.0
* Add generate storyboard support (PeerTube >= 8.0)
## v0.2.0
* Add runner version in request and register payloads
* Update dependencies to fix vulnerabilities
## v0.1.3
* Disable log coloring when TTY does not support it
* Add download file timeout (2 hours) to prevent stuck jobs
## v0.1.2
* Support query params in custom upload URL
## v0.1.1
* Fix adding studio watermark with audio/video split HLS file
## v0.1.0
* Requires Node 20
* Introduce `list-jobs` command to list processing jobs
* Update dependencies
* Send last chunks/playlist content to correctly end the live

View File

@@ -0,0 +1,42 @@
# PeerTube runner
Runner program to execute jobs (transcoding...) of remote PeerTube instances.
Commands below has to be run at the root of PeerTube git repository.
## Dev
### Install dependencies
```bash
cd peertube-root
npm run install-node-dependencies
```
### Develop
```bash
cd peertube-root
npm run dev:peertube-runner
```
### Build
```bash
cd peertube-root
npm run build:peertube-runner
```
### Run
```bash
cd peertube-root
node apps/peertube-runner/dist/peertube-runner.js --help
```
### Publish on NPM
```bash
cd peertube-root
(cd apps/peertube-runner && npm version patch) && npm run build:peertube-runner && (cd apps/peertube-runner && npm publish --access=public)
```

View File

@@ -0,0 +1,18 @@
{
"name": "@peertube/peertube-runner",
"version": "0.4.0",
"type": "module",
"main": "dist/peertube-runner.js",
"bin": "dist/peertube-runner.js",
"license": "AGPL-3.0",
"devDependencies": {
"@iarna/toml": "^2.2.5",
"@types/follow-redirects": "1.14.4",
"cli-table3": "^0.6.5",
"env-paths": "^3.0.0",
"follow-redirects": "^1.15.5",
"net-ipc": "^2.2.2",
"pino": "^9.6.0",
"pino-pretty": "^13.0.0"
}
}

View File

@@ -0,0 +1,27 @@
import * as esbuild from 'esbuild'
import { readFileSync } from 'fs'
const packageJSON = JSON.parse(readFileSync(new URL('../package.json', import.meta.url)))
export const esbuildOptions = {
entryPoints: [ './src/peertube-runner.ts' ],
bundle: true,
platform: 'node',
format: 'esm',
target: 'node16',
external: [
'./lib-cov/fluent-ffmpeg',
'pg-hstore'
],
outfile: './dist/peertube-runner.js',
banner: {
js: `const require = (await import("node:module")).createRequire(import.meta.url);` +
`const __filename = (await import("node:url")).fileURLToPath(import.meta.url);` +
`const __dirname = (await import("node:path")).dirname(__filename);`
},
define: {
'process.env.PACKAGE_VERSION': `'${packageJSON.version}'`
}
}
await esbuild.build(esbuildOptions)

View File

@@ -0,0 +1,7 @@
import * as esbuild from 'esbuild'
import { esbuildOptions } from './build.js'
const context = await esbuild.context(esbuildOptions)
// Enable watch mode
await context.watch()

View File

@@ -0,0 +1,139 @@
#!/usr/bin/env node
import { Command, InvalidArgumentError } from '@commander-js/extra-typings'
import { RunnerJobType } from '@peertube/peertube-models'
import { listJobs, listRegistered, registerRunner, unregisterRunner } from './register/index.js'
import { gracefulShutdown } from './register/shutdown.js'
import { RunnerServer } from './server/index.js'
import { getSupportedJobsList } from './server/shared/supported-job.js'
import { ConfigManager, logger } from './shared/index.js'
const program = new Command()
.version(process.env.PACKAGE_VERSION)
.option(
'--id <id>',
'Runner server id, so you can run multiple PeerTube server runners with different configurations on the same machine',
'default'
)
.option('--verbose', 'Run in verbose mode')
.hook('preAction', thisCommand => {
const options = thisCommand.opts()
ConfigManager.Instance.init(options.id)
if (options.verbose === true) {
logger.level = 'debug'
}
})
program.command('server')
.description('Run in server mode, to execute remote jobs of registered PeerTube instances')
.option(
'--enable-job <type>',
'Enable this job type (multiple --enable-job options can be specified). ' +
'By default all supported jobs are enabled). ' +
'Supported job types: ' + getSupportedJobsList().join(', '),
(value: RunnerJobType, previous: RunnerJobType[]) => [ ...previous, value ],
[]
)
.action(async options => {
try {
let enabledJobs: Set<RunnerJobType>
if (options.enableJob) {
for (const jobType of options.enableJob) {
if (getSupportedJobsList().includes(jobType) !== true) {
throw new InvalidArgumentError(`${jobType} is not a supported job`)
}
enabledJobs = new Set(options.enableJob)
}
}
await new RunnerServer(enabledJobs).run()
} catch (err) {
logger.error(err, 'Cannot run PeerTube runner as server mode')
process.exit(-1)
}
})
program.command('register')
.description('Register a new PeerTube instance to process runner jobs')
.requiredOption('--url <url>', 'PeerTube instance URL', parseUrl)
.requiredOption('--registration-token <token>', 'Runner registration token (can be found in PeerTube instance administration')
.requiredOption('--runner-name <name>', 'Runner name')
.option('--runner-description <description>', 'Runner description')
.action(async options => {
try {
await registerRunner(options)
} catch (err) {
console.error('Cannot register this PeerTube runner.')
console.error(err)
process.exit(-1)
}
})
program.command('unregister')
.description('Unregister the runner from PeerTube instance')
.requiredOption('--url <url>', 'PeerTube instance URL', parseUrl)
.requiredOption('--runner-name <name>', 'Runner name')
.action(async options => {
try {
await unregisterRunner(options)
} catch (err) {
console.error('Cannot unregister this PeerTube runner.')
console.error(err)
process.exit(-1)
}
})
program.command('list-registered')
.description('List registered PeerTube instances')
.action(async () => {
try {
await listRegistered()
} catch (err) {
console.error('Cannot list registered PeerTube instances.')
console.error(err)
process.exit(-1)
}
})
program.command('list-jobs')
.description('List processing jobs')
.option('--include-payload', 'Include job payload in the output')
.action(async options => {
try {
await listJobs({ includePayload: options.includePayload })
} catch (err) {
console.error('Cannot list processing jobs.')
console.error(err)
process.exit(-1)
}
})
program.command('graceful-shutdown')
.description('Exit runner when all processing tasks are finished')
.action(async () => {
try {
await gracefulShutdown()
} catch (err) {
console.error('Cannot graceful shutdown the runner.')
console.error(err)
process.exit(-1)
}
})
program.parse()
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
function parseUrl (url: string) {
if (url.startsWith('http://') !== true && url.startsWith('https://') !== true) {
throw new InvalidArgumentError('URL should start with a http:// or https://')
}
return url
}

View File

@@ -0,0 +1 @@
export * from './register.js'

View File

@@ -0,0 +1,47 @@
import { IPCClient } from '../shared/ipc/index.js'
export async function registerRunner (options: {
url: string
registrationToken: string
runnerName: string
runnerDescription?: string
}) {
const client = new IPCClient()
await client.run()
await client.askRegister(options)
client.stop()
}
export async function unregisterRunner (options: {
url: string
runnerName: string
}) {
const client = new IPCClient()
await client.run()
await client.askUnregister(options)
client.stop()
}
export async function listRegistered () {
const client = new IPCClient()
await client.run()
await client.askListRegistered()
client.stop()
}
export async function listJobs (options: {
includePayload: boolean
}) {
const client = new IPCClient()
await client.run()
await client.askListJobs(options)
client.stop()
}

View File

@@ -0,0 +1,10 @@
import { IPCClient } from '../shared/ipc/index.js'
export async function gracefulShutdown () {
const client = new IPCClient()
await client.run()
await client.askGracefulShutdown()
client.stop()
}

View File

@@ -0,0 +1 @@
export * from './server.js'

View File

@@ -0,0 +1,2 @@
export * from './shared/index.js'
export * from './process.js'

View File

@@ -0,0 +1,61 @@
import {
RunnerJobLiveRTMPHLSTranscodingPayload,
RunnerJobStudioTranscodingPayload,
RunnerJobTranscriptionPayload,
RunnerJobVODAudioMergeTranscodingPayload,
RunnerJobVODHLSTranscodingPayload,
RunnerJobVODWebVideoTranscodingPayload
} from '@peertube/peertube-models'
import { logger } from '../../shared/index.js'
import {
processAudioMergeTranscoding,
processGenerateStoryboard,
processHLSTranscoding,
ProcessOptions,
processWebVideoTranscoding
} from './shared/index.js'
import { ProcessLiveRTMPHLSTranscoding } from './shared/process-live.js'
import { processStudioTranscoding } from './shared/process-studio.js'
import { processVideoTranscription } from './shared/process-transcription.js'
export async function processJob (options: ProcessOptions) {
const { server, job } = options
logger.info({ payload: job.payload }, `[${server.url}] Processing job of type ${job.type}: ${job.uuid}`)
switch (job.type) {
case 'vod-audio-merge-transcoding':
await processAudioMergeTranscoding(options as ProcessOptions<RunnerJobVODAudioMergeTranscodingPayload>)
break
case 'vod-web-video-transcoding':
await processWebVideoTranscoding(options as ProcessOptions<RunnerJobVODWebVideoTranscodingPayload>)
break
case 'vod-hls-transcoding':
await processHLSTranscoding(options as ProcessOptions<RunnerJobVODHLSTranscodingPayload>)
break
case 'live-rtmp-hls-transcoding':
await new ProcessLiveRTMPHLSTranscoding(options as ProcessOptions<RunnerJobLiveRTMPHLSTranscodingPayload>).process()
break
case 'video-studio-transcoding':
await processStudioTranscoding(options as ProcessOptions<RunnerJobStudioTranscodingPayload>)
break
case 'video-transcription':
await processVideoTranscription(options as ProcessOptions<RunnerJobTranscriptionPayload>)
break
case 'generate-video-storyboard':
await processGenerateStoryboard(options as any)
break
default:
logger.error(`Unknown job ${job.type} to process`)
return
}
logger.info(`[${server.url}] Finished processing job of type ${job.type}: ${job.uuid}`)
}

View File

@@ -0,0 +1,136 @@
import { pick } from '@peertube/peertube-core-utils'
import {
FFmpegEdition,
FFmpegImage,
FFmpegLive,
FFmpegVOD,
getDefaultAvailableEncoders,
getDefaultEncodersToTry
} from '@peertube/peertube-ffmpeg'
import { RunnerJob, RunnerJobPayload } from '@peertube/peertube-models'
import { buildUUID } from '@peertube/peertube-node-utils'
import { PeerTubeServer } from '@peertube/peertube-server-commands'
import { remove } from 'fs-extra/esm'
import { join } from 'path'
import { ConfigManager, downloadFile, logger } from '../../../shared/index.js'
import { getWinstonLogger } from './winston-logger.js'
export type JobWithToken<T extends RunnerJobPayload = RunnerJobPayload> = RunnerJob<T> & { jobToken: string }
export type ProcessOptions<T extends RunnerJobPayload = RunnerJobPayload> = {
server: PeerTubeServer
job: JobWithToken<T>
runnerToken: string
}
export async function downloadInputFile (options: {
url: string
job: JobWithToken
runnerToken: string
}) {
const { url, job, runnerToken } = options
const destination = join(ConfigManager.Instance.getTranscodingDirectory(), buildUUID())
try {
await downloadFile({ url, jobToken: job.jobToken, runnerToken, destination })
} catch (err) {
remove(destination)
.catch(err => logger.error({ err }, `Cannot remove ${destination}`))
throw err
}
return destination
}
export async function downloadSeparatedAudioFileIfNeeded (options: {
urls: string[]
job: JobWithToken
runnerToken: string
}) {
const { urls } = options
if (!urls || urls.length === 0) return undefined
return downloadInputFile({ url: urls[0], ...pick(options, [ 'job', 'runnerToken' ]) })
}
export function scheduleTranscodingProgress (options: {
server: PeerTubeServer
runnerToken: string
job: JobWithToken
progressGetter: () => number
}) {
const { job, server, progressGetter, runnerToken } = options
const updateInterval = ConfigManager.Instance.isTestInstance()
? 500
: 60000
const update = () => {
job.progress = progressGetter() || 0
server.runnerJobs.update({
jobToken: job.jobToken,
jobUUID: job.uuid,
runnerToken,
progress: job.progress
}).catch(err => logger.error({ err }, 'Cannot send job progress'))
}
const interval = setInterval(() => {
update()
}, updateInterval)
update()
return interval
}
// ---------------------------------------------------------------------------
export function buildFFmpegVOD (options: {
onJobProgress: (progress: number) => void
}) {
const { onJobProgress } = options
return new FFmpegVOD({
...getCommonFFmpegOptions(),
updateJobProgress: arg => {
const progress = arg < 0 || arg > 100
? undefined
: arg
onJobProgress(progress)
}
})
}
export function buildFFmpegLive () {
return new FFmpegLive(getCommonFFmpegOptions())
}
export function buildFFmpegEdition () {
return new FFmpegEdition(getCommonFFmpegOptions())
}
export function buildFFmpegImage () {
return new FFmpegImage(getCommonFFmpegOptions())
}
function getCommonFFmpegOptions () {
const config = ConfigManager.Instance.getConfig()
return {
niceness: config.ffmpeg.nice,
threads: config.ffmpeg.threads,
tmpDirectory: ConfigManager.Instance.getTranscodingDirectory(),
profile: 'default',
availableEncoders: {
available: getDefaultAvailableEncoders(),
encodersToTry: getDefaultEncodersToTry()
},
logger: getWinstonLogger()
}
}

View File

@@ -0,0 +1,4 @@
export * from './common.js'
export * from './process-vod.js'
export * from './winston-logger.js'
export * from './process-storyboard.js'

View File

@@ -0,0 +1,407 @@
import { wait } from '@peertube/peertube-core-utils'
import {
ffprobePromise,
getVideoStreamBitrate,
getVideoStreamDimensionsInfo,
hasAudioStream,
hasVideoStream
} from '@peertube/peertube-ffmpeg'
import {
LiveRTMPHLSTranscodingSuccess,
LiveRTMPHLSTranscodingUpdatePayload,
PeerTubeProblemDocument,
RunnerJobLiveRTMPHLSTranscodingPayload,
ServerErrorCode
} from '@peertube/peertube-models'
import { buildUUID } from '@peertube/peertube-node-utils'
import { FSWatcher, watch } from 'chokidar'
import { FfmpegCommand } from 'fluent-ffmpeg'
import { ensureDir, remove } from 'fs-extra/esm'
import { readFile } from 'fs/promises'
import { basename, join } from 'path'
import { ConfigManager } from '../../../shared/config-manager.js'
import { logger } from '../../../shared/index.js'
import { buildFFmpegLive, ProcessOptions } from './common.js'
type CustomLiveRTMPHLSTranscodingUpdatePayload = Omit<LiveRTMPHLSTranscodingUpdatePayload, 'resolutionPlaylistFile'> & {
resolutionPlaylistFile?: [Buffer, string] | Blob | string
}
export class ProcessLiveRTMPHLSTranscoding {
private readonly outputPath: string
private readonly fsWatchers: FSWatcher[] = []
// Playlist name -> chunks
private readonly pendingChunksPerPlaylist = new Map<string, string[]>()
private readonly playlistsCreated = new Set<string>()
private allPlaylistsCreated = false
private latestFilteredPlaylistContent: { [name: string]: string } = {}
private ffmpegCommand: FfmpegCommand
private ended = false
private errored = false
constructor (private readonly options: ProcessOptions<RunnerJobLiveRTMPHLSTranscodingPayload>) {
this.outputPath = join(ConfigManager.Instance.getTranscodingDirectory(), buildUUID())
logger.debug(`Using ${this.outputPath} to process live rtmp hls transcoding job ${options.job.uuid}`)
}
private get payload () {
return this.options.job.payload
}
process () {
return new Promise<void>(async (res, rej) => {
try {
await ensureDir(this.outputPath)
logger.info(`Probing ${this.payload.input.rtmpUrl}`)
const probe = await ffprobePromise(this.payload.input.rtmpUrl)
logger.info({ probe }, `Probed ${this.payload.input.rtmpUrl}`)
const hasAudio = await hasAudioStream(this.payload.input.rtmpUrl, probe)
const hasVideo = await hasVideoStream(this.payload.input.rtmpUrl, probe)
const bitrate = await getVideoStreamBitrate(this.payload.input.rtmpUrl, probe)
const { ratio } = await getVideoStreamDimensionsInfo(this.payload.input.rtmpUrl, probe)
const m3u8Watcher = watch(this.outputPath, { ignored: path => path !== this.outputPath && !path.endsWith('.m3u8') })
this.fsWatchers.push(m3u8Watcher)
const tsWatcher = watch(this.outputPath, { ignored: path => path !== this.outputPath && !path.endsWith('.ts') })
this.fsWatchers.push(tsWatcher)
m3u8Watcher.on('change', p => {
logger.debug(`${p} m3u8 playlist changed`)
})
m3u8Watcher.on('add', p => {
this.playlistsCreated.add(p)
if (this.playlistsCreated.size === this.options.job.payload.output.toTranscode.length + 1) {
this.allPlaylistsCreated = true
logger.info('All m3u8 playlists are created.')
}
})
tsWatcher.on('add', async p => {
try {
await this.sendPendingChunks()
} catch (err) {
this.onUpdateError({ err, rej, res })
}
const playlistName = this.getPlaylistIdFromTS(p)
const pendingChunks = this.pendingChunksPerPlaylist.get(playlistName) || []
pendingChunks.push(p)
this.pendingChunksPerPlaylist.set(playlistName, pendingChunks)
})
tsWatcher.on('unlink', p => {
this.sendDeletedChunkUpdate(p)
.catch(err => this.onUpdateError({ err, rej, res }))
})
this.ffmpegCommand = await buildFFmpegLive().getLiveTranscodingCommand({
inputUrl: this.payload.input.rtmpUrl,
outPath: this.outputPath,
masterPlaylistName: 'master.m3u8',
segmentListSize: this.payload.output.segmentListSize,
segmentDuration: this.payload.output.segmentDuration,
toTranscode: this.payload.output.toTranscode,
splitAudioAndVideo: true,
bitrate,
ratio,
hasAudio,
hasVideo,
probe
})
logger.info(`Running live transcoding for ${this.payload.input.rtmpUrl}`)
this.ffmpegCommand.on('error', (err, stdout, stderr) => {
this.onFFmpegError({ err, stdout, stderr })
res()
})
this.ffmpegCommand.on('end', () => {
this.onFFmpegEnded()
.catch(err => logger.error({ err }, 'Error in FFmpeg end handler'))
res()
})
this.ffmpegCommand.run()
} catch (err) {
rej(err)
}
})
}
// ---------------------------------------------------------------------------
private onUpdateError (options: {
err: Error
res: () => void
rej: (reason?: any) => void
}) {
const { err, res, rej } = options
if (this.errored) return
if (this.ended) return
this.errored = true
this.ffmpegCommand.kill('SIGINT')
const type = ((err as any).res?.body as PeerTubeProblemDocument)?.code
if (type === ServerErrorCode.RUNNER_JOB_NOT_IN_PROCESSING_STATE) {
logger.info('Stopping transcoding as the job is not in processing state anymore')
this.sendSuccess()
.catch(err => logger.error({ err }, 'Cannot send success'))
res()
} else {
logger.error({ err }, 'Cannot send update after added/deleted chunk, stopping live transcoding')
this.sendError(err)
.catch(subErr => logger.error({ err: subErr }, 'Cannot send error'))
rej(err)
}
this.cleanup()
}
// ---------------------------------------------------------------------------
private onFFmpegError (options: {
err: any
stdout: string
stderr: string
}) {
const { err, stdout, stderr } = options
// Don't care that we killed the ffmpeg process
if (err?.message?.includes('Exiting normally')) return
if (this.errored) return
if (this.ended) return
this.errored = true
logger.error({ err, stdout, stderr }, 'FFmpeg transcoding error.')
this.sendError(err)
.catch(subErr => logger.error({ err: subErr }, 'Cannot send error'))
this.cleanup()
}
private async sendError (err: Error) {
await this.options.server.runnerJobs.error({
jobToken: this.options.job.jobToken,
jobUUID: this.options.job.uuid,
runnerToken: this.options.runnerToken,
message: err.message
})
}
// ---------------------------------------------------------------------------
private async onFFmpegEnded () {
if (this.ended) return
logger.info('FFmpeg ended, sending success to server')
// Wait last ffmpeg chunks generation
await wait(1500)
try {
await this.sendPendingChunks()
} catch (err) {
logger.error(err, 'Cannot send latest chunks after ffmpeg ended')
}
this.ended = true
this.sendSuccess()
.catch(err => logger.error({ err }, 'Cannot send success'))
this.cleanup()
}
private async sendSuccess () {
const successBody: LiveRTMPHLSTranscodingSuccess = {}
await this.options.server.runnerJobs.success({
jobToken: this.options.job.jobToken,
jobUUID: this.options.job.uuid,
runnerToken: this.options.runnerToken,
payload: successBody,
reqPayload: this.payload
})
}
// ---------------------------------------------------------------------------
private sendDeletedChunkUpdate (deletedChunk: string): Promise<any> {
if (this.ended) return Promise.resolve()
logger.debug(`Sending removed live chunk ${deletedChunk} update`)
const videoChunkFilename = basename(deletedChunk)
let payload: CustomLiveRTMPHLSTranscodingUpdatePayload = {
type: 'remove-chunk',
videoChunkFilename
}
if (this.allPlaylistsCreated) {
const playlistName = this.getPlaylistName(videoChunkFilename)
payload = {
...payload,
masterPlaylistFile: join(this.outputPath, 'master.m3u8'),
resolutionPlaylistFilename: playlistName,
resolutionPlaylistFile: this.buildPlaylistFileParam(playlistName)
}
}
return this.updateWithRetry(payload)
}
private async sendPendingChunks (): Promise<any> {
if (this.ended) return Promise.resolve()
const parallelPromises: Promise<any>[] = []
for (const playlist of this.pendingChunksPerPlaylist.keys()) {
let sequentialPromises: Promise<any>
for (const chunk of this.pendingChunksPerPlaylist.get(playlist)) {
logger.debug(`Sending added live chunk ${chunk} update`)
const videoChunkFilename = basename(chunk)
const payloadBuilder = async () => {
let payload: CustomLiveRTMPHLSTranscodingUpdatePayload = {
type: 'add-chunk',
videoChunkFilename,
videoChunkFile: chunk
}
if (this.allPlaylistsCreated) {
const playlistName = this.getPlaylistName(videoChunkFilename)
try {
await this.updatePlaylistContent(playlistName, videoChunkFilename)
payload = {
...payload,
masterPlaylistFile: join(this.outputPath, 'master.m3u8'),
resolutionPlaylistFilename: playlistName,
resolutionPlaylistFile: this.buildPlaylistFileParam(playlistName)
}
} catch (err) {
logger.warn(err, `Cannot fetch/update playlist content ${playlistName}`)
}
}
return payload
}
const p = payloadBuilder().then(p => this.updateWithRetry(p))
if (sequentialPromises === undefined) sequentialPromises = p
else sequentialPromises = sequentialPromises.then(() => p)
}
parallelPromises.push(sequentialPromises)
this.pendingChunksPerPlaylist.set(playlist, [])
}
await Promise.all(parallelPromises)
}
private async updateWithRetry (updatePayload: CustomLiveRTMPHLSTranscodingUpdatePayload, currentTry = 1): Promise<any> {
if (this.ended || this.errored) return
try {
await this.options.server.runnerJobs.update({
jobToken: this.options.job.jobToken,
jobUUID: this.options.job.uuid,
runnerToken: this.options.runnerToken,
payload: updatePayload as any,
reqPayload: this.payload
})
} catch (err) {
if (currentTry >= 3) throw err
if ((err.res?.body as PeerTubeProblemDocument)?.code === ServerErrorCode.RUNNER_JOB_NOT_IN_PROCESSING_STATE) throw err
logger.warn({ err }, 'Will retry update after error')
await wait(250)
return this.updateWithRetry(updatePayload, currentTry + 1)
}
}
private getPlaylistName (videoChunkFilename: string) {
return `${videoChunkFilename.split('-')[0]}.m3u8`
}
private getPlaylistIdFromTS (segmentPath: string) {
const playlistIdMatcher = /^([\d+])-/
return basename(segmentPath).match(playlistIdMatcher)[1]
}
private async updatePlaylistContent (playlistName: string, latestChunkFilename: string) {
const m3u8Path = join(this.outputPath, playlistName)
let playlistContent = await readFile(m3u8Path, 'utf-8')
if (!playlistContent.includes('#EXT-X-ENDLIST')) {
playlistContent = playlistContent.substring(
0,
playlistContent.lastIndexOf(latestChunkFilename) + latestChunkFilename.length
) + '\n'
}
// Remove new chunk references, that will be processed later
this.latestFilteredPlaylistContent[playlistName] = playlistContent
}
private buildPlaylistFileParam (playlistName: string) {
return [
Buffer.from(this.latestFilteredPlaylistContent[playlistName], 'utf-8'),
join(this.outputPath, 'master.m3u8')
] as [Buffer, string]
}
// ---------------------------------------------------------------------------
private cleanup () {
logger.debug(`Cleaning up job ${this.options.job.uuid}`)
for (const fsWatcher of this.fsWatchers) {
fsWatcher.close()
.catch(err => logger.error({ err }, 'Cannot close watcher'))
}
remove(this.outputPath)
.catch(err => logger.error({ err }, `Cannot remove ${this.outputPath}`))
}
}

View File

@@ -0,0 +1,60 @@
import { RunnerJobGenerateStoryboardPayload, GenerateStoryboardSuccess } from '@peertube/peertube-models'
import { buildUUID } from '@peertube/peertube-node-utils'
import { remove } from 'fs-extra/esm'
import { join } from 'path'
import { ConfigManager } from '../../../shared/config-manager.js'
import { logger } from '../../../shared/index.js'
import { buildFFmpegImage, downloadInputFile, ProcessOptions, scheduleTranscodingProgress } from './common.js'
export async function processGenerateStoryboard (options: ProcessOptions<RunnerJobGenerateStoryboardPayload>) {
const { server, job, runnerToken } = options
const payload = job.payload
let ffmpegProgress: number
let videoInputPath: string
const outputPath = join(ConfigManager.Instance.getStoryboardDirectory(), `storyboard-${buildUUID()}.jpg`)
const updateProgressInterval = scheduleTranscodingProgress({
job,
server,
runnerToken,
progressGetter: () => ffmpegProgress
})
try {
logger.info(`Downloading input file ${payload.input.videoFileUrl} for storyboard job ${job.jobToken}`)
videoInputPath = await downloadInputFile({ url: payload.input.videoFileUrl, runnerToken, job })
logger.info(`Downloaded input file ${payload.input.videoFileUrl} for job ${job.jobToken}. Generating storyboard.`)
const ffmpegImage = buildFFmpegImage()
await ffmpegImage.generateStoryboardFromVideo({
path: videoInputPath,
destination: outputPath,
inputFileMutexReleaser: () => {},
sprites: payload.sprites
})
const successBody: GenerateStoryboardSuccess = {
storyboardFile: outputPath
}
await server.runnerJobs.success({
jobToken: job.jobToken,
jobUUID: job.uuid,
runnerToken,
payload: successBody,
reqPayload: payload
})
} finally {
if (videoInputPath) await remove(videoInputPath)
if (outputPath) await remove(outputPath)
if (updateProgressInterval) clearInterval(updateProgressInterval)
}
}

View File

@@ -0,0 +1,187 @@
import { pick } from '@peertube/peertube-core-utils'
import {
RunnerJobStudioTranscodingPayload,
VideoStudioTask,
VideoStudioTaskCutPayload,
VideoStudioTaskIntroPayload,
VideoStudioTaskOutroPayload,
VideoStudioTaskPayload,
VideoStudioTaskWatermarkPayload,
VideoStudioTranscodingSuccess
} from '@peertube/peertube-models'
import { buildUUID } from '@peertube/peertube-node-utils'
import { remove } from 'fs-extra/esm'
import { join } from 'path'
import { ConfigManager } from '../../../shared/config-manager.js'
import { logger } from '../../../shared/index.js'
import {
buildFFmpegEdition,
downloadInputFile,
downloadSeparatedAudioFileIfNeeded,
JobWithToken,
ProcessOptions,
scheduleTranscodingProgress
} from './common.js'
export async function processStudioTranscoding (options: ProcessOptions<RunnerJobStudioTranscodingPayload>) {
const { server, job, runnerToken } = options
const payload = job.payload
let videoInputPath: string
let separatedAudioInputPath: string
let tmpVideoInputFilePath: string
let tmpSeparatedAudioInputFilePath: string
let outputPath: string
let tasksProgress = 0
const updateProgressInterval = scheduleTranscodingProgress({
job,
server,
runnerToken,
progressGetter: () => tasksProgress
})
try {
logger.info(`Downloading input file ${payload.input.videoFileUrl} for job ${job.jobToken}`)
videoInputPath = await downloadInputFile({ url: payload.input.videoFileUrl, runnerToken, job })
separatedAudioInputPath = await downloadSeparatedAudioFileIfNeeded({ urls: payload.input.separatedAudioFileUrl, runnerToken, job })
tmpVideoInputFilePath = videoInputPath
tmpSeparatedAudioInputFilePath = separatedAudioInputPath
logger.info(`Input file ${payload.input.videoFileUrl} downloaded for job ${job.jobToken}. Running studio transcoding tasks.`)
for (const task of payload.tasks) {
const outputFilename = 'output-edition-' + buildUUID() + '.mp4'
outputPath = join(ConfigManager.Instance.getTranscodingDirectory(), outputFilename)
await processTask({
videoInputPath: tmpVideoInputFilePath,
separatedAudioInputPath: tmpSeparatedAudioInputFilePath,
outputPath,
task,
job,
runnerToken
})
if (tmpVideoInputFilePath) await remove(tmpVideoInputFilePath)
if (tmpSeparatedAudioInputFilePath) await remove(tmpSeparatedAudioInputFilePath)
// For the next iteration
tmpVideoInputFilePath = outputPath
tmpSeparatedAudioInputFilePath = undefined
tasksProgress += Math.floor(100 / payload.tasks.length)
}
const successBody: VideoStudioTranscodingSuccess = {
videoFile: outputPath
}
await server.runnerJobs.success({
jobToken: job.jobToken,
jobUUID: job.uuid,
runnerToken,
payload: successBody,
reqPayload: payload
})
} finally {
if (tmpVideoInputFilePath) await remove(tmpVideoInputFilePath)
if (tmpSeparatedAudioInputFilePath) await remove(tmpSeparatedAudioInputFilePath)
if (outputPath) await remove(outputPath)
if (updateProgressInterval) clearInterval(updateProgressInterval)
}
}
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
type TaskProcessorOptions <T extends VideoStudioTaskPayload = VideoStudioTaskPayload> = {
videoInputPath: string
separatedAudioInputPath: string
outputPath: string
task: T
runnerToken: string
job: JobWithToken
}
const taskProcessors: { [id in VideoStudioTask['name']]: (options: TaskProcessorOptions) => Promise<any> } = {
'add-intro': processAddIntroOutro,
'add-outro': processAddIntroOutro,
'cut': processCut,
'add-watermark': processAddWatermark
}
async function processTask (options: TaskProcessorOptions) {
const { task } = options
const processor = taskProcessors[options.task.name]
if (!process) throw new Error('Unknown task ' + task.name)
return processor(options)
}
async function processAddIntroOutro (options: TaskProcessorOptions<VideoStudioTaskIntroPayload | VideoStudioTaskOutroPayload>) {
const { videoInputPath, task, runnerToken, job } = options
logger.debug(`Adding intro/outro to ${videoInputPath}`)
const introOutroPath = await downloadInputFile({ url: task.options.file, runnerToken, job })
try {
await buildFFmpegEdition().addIntroOutro({
...pick(options, [ 'videoInputPath', 'separatedAudioInputPath', 'outputPath' ]),
introOutroPath,
type: task.name === 'add-intro'
? 'intro'
: 'outro'
})
} finally {
await remove(introOutroPath)
}
}
function processCut (options: TaskProcessorOptions<VideoStudioTaskCutPayload>) {
const { videoInputPath, task } = options
logger.debug(`Cutting ${videoInputPath}`)
return buildFFmpegEdition().cutVideo({
...pick(options, [ 'videoInputPath', 'separatedAudioInputPath', 'outputPath' ]),
start: task.options.start,
end: task.options.end
})
}
async function processAddWatermark (options: TaskProcessorOptions<VideoStudioTaskWatermarkPayload>) {
const { videoInputPath, task, runnerToken, job } = options
logger.debug(`Adding watermark to ${videoInputPath}`)
const watermarkPath = await downloadInputFile({ url: task.options.file, runnerToken, job })
try {
await buildFFmpegEdition().addWatermark({
...pick(options, [ 'videoInputPath', 'separatedAudioInputPath', 'outputPath' ]),
watermarkPath,
videoFilters: {
watermarkSizeRatio: task.options.watermarkSizeRatio,
horitonzalMarginRatio: task.options.horitonzalMarginRatio,
verticalMarginRatio: task.options.verticalMarginRatio
}
})
} finally {
await remove(watermarkPath)
}
}

View File

@@ -0,0 +1,80 @@
import { hasAudioStream } from '@peertube/peertube-ffmpeg'
import { RunnerJobTranscriptionPayload, TranscriptionSuccess } from '@peertube/peertube-models'
import { buildSUUID } from '@peertube/peertube-node-utils'
import { TranscriptionModel, WhisperBuiltinModel, transcriberFactory } from '@peertube/peertube-transcription'
import { remove } from 'fs-extra/esm'
import { join } from 'path'
import { ConfigManager } from '../../../shared/config-manager.js'
import { logger } from '../../../shared/index.js'
import { ProcessOptions, downloadInputFile, scheduleTranscodingProgress } from './common.js'
import { getWinstonLogger } from './winston-logger.js'
export async function processVideoTranscription (options: ProcessOptions<RunnerJobTranscriptionPayload>) {
const { server, job, runnerToken } = options
const config = ConfigManager.Instance.getConfig().transcription
const payload = job.payload
let inputPath: string
const updateProgressInterval = scheduleTranscodingProgress({
job,
server,
runnerToken,
progressGetter: () => undefined
})
const outputPath = join(ConfigManager.Instance.getTranscriptionDirectory(), buildSUUID())
const transcriber = transcriberFactory.createFromEngineName({
engineName: config.engine,
enginePath: config.enginePath,
logger: getWinstonLogger()
})
try {
logger.info(`Downloading input file ${payload.input.videoFileUrl} for transcription job ${job.jobToken}`)
inputPath = await downloadInputFile({ url: payload.input.videoFileUrl, runnerToken, job })
logger.info(`Downloaded input file ${payload.input.videoFileUrl} for job ${job.jobToken}. Running transcription.`)
if (await hasAudioStream(inputPath) !== true) {
await server.runnerJobs.error({
jobToken: job.jobToken,
jobUUID: job.uuid,
runnerToken,
message: 'This input file does not contain audio'
})
return
}
const transcriptFile = await transcriber.transcribe({
mediaFilePath: inputPath,
model: config.modelPath
? await TranscriptionModel.fromPath(config.modelPath)
: new WhisperBuiltinModel(config.model),
format: 'vtt',
transcriptDirectory: outputPath
})
const successBody: TranscriptionSuccess = {
inputLanguage: transcriptFile.language,
vttFile: transcriptFile.path
}
await server.runnerJobs.success({
jobToken: job.jobToken,
jobUUID: job.uuid,
runnerToken,
payload: successBody,
reqPayload: payload
})
} finally {
if (inputPath) await remove(inputPath)
if (outputPath) await remove(outputPath)
if (updateProgressInterval) clearInterval(updateProgressInterval)
}
}

View File

@@ -0,0 +1,234 @@
import { canCopyForHLS } from '@peertube/peertube-ffmpeg'
import {
RunnerJobVODAudioMergeTranscodingPayload,
RunnerJobVODHLSTranscodingPayload,
RunnerJobVODWebVideoTranscodingPayload,
VODAudioMergeTranscodingSuccess,
VODHLSTranscodingSuccess,
VODWebVideoTranscodingSuccess
} from '@peertube/peertube-models'
import { buildUUID } from '@peertube/peertube-node-utils'
import { remove } from 'fs-extra/esm'
import { join } from 'path'
import { ConfigManager } from '../../../shared/config-manager.js'
import { logger } from '../../../shared/index.js'
import {
buildFFmpegVOD,
downloadInputFile,
downloadSeparatedAudioFileIfNeeded,
ProcessOptions,
scheduleTranscodingProgress
} from './common.js'
export async function processWebVideoTranscoding (options: ProcessOptions<RunnerJobVODWebVideoTranscodingPayload>) {
const { server, job, runnerToken } = options
const payload = job.payload
let ffmpegProgress: number
let videoInputPath: string
let separatedAudioInputPath: string
const outputPath = join(ConfigManager.Instance.getTranscodingDirectory(), `output-${buildUUID()}.mp4`)
const updateProgressInterval = scheduleTranscodingProgress({
job,
server,
runnerToken,
progressGetter: () => ffmpegProgress
})
try {
logger.info(`Downloading input file ${payload.input.videoFileUrl} for web video transcoding job ${job.jobToken}`)
videoInputPath = await downloadInputFile({ url: payload.input.videoFileUrl, runnerToken, job })
separatedAudioInputPath = await downloadSeparatedAudioFileIfNeeded({ urls: payload.input.separatedAudioFileUrl, runnerToken, job })
logger.info(`Downloaded input file ${payload.input.videoFileUrl} for job ${job.jobToken}. Running web video transcoding.`)
const ffmpegVod = buildFFmpegVOD({
onJobProgress: progress => {
ffmpegProgress = progress
}
})
await ffmpegVod.transcode({
type: 'video',
videoInputPath,
separatedAudioInputPath,
outputPath,
inputFileMutexReleaser: () => {},
resolution: payload.output.resolution,
fps: payload.output.fps
})
const successBody: VODWebVideoTranscodingSuccess = {
videoFile: outputPath
}
await server.runnerJobs.success({
jobToken: job.jobToken,
jobUUID: job.uuid,
runnerToken,
payload: successBody,
reqPayload: payload
})
} finally {
if (videoInputPath) await remove(videoInputPath)
if (separatedAudioInputPath) await remove(separatedAudioInputPath)
if (outputPath) await remove(outputPath)
if (updateProgressInterval) clearInterval(updateProgressInterval)
}
}
export async function processHLSTranscoding (options: ProcessOptions<RunnerJobVODHLSTranscodingPayload>) {
const { server, job, runnerToken } = options
const payload = job.payload
let ffmpegProgress: number
let videoInputPath: string
let separatedAudioInputPath: string
const uuid = buildUUID()
const outputPath = join(ConfigManager.Instance.getTranscodingDirectory(), `${uuid}-${payload.output.resolution}.m3u8`)
const videoFilename = `${uuid}-${payload.output.resolution}-fragmented.mp4`
const videoPath = join(join(ConfigManager.Instance.getTranscodingDirectory(), videoFilename))
const updateProgressInterval = scheduleTranscodingProgress({
job,
server,
runnerToken,
progressGetter: () => ffmpegProgress
})
try {
logger.info(`Downloading input file ${payload.input.videoFileUrl} for HLS transcoding job ${job.jobToken}`)
videoInputPath = await downloadInputFile({ url: payload.input.videoFileUrl, runnerToken, job })
separatedAudioInputPath = await downloadSeparatedAudioFileIfNeeded({ urls: payload.input.separatedAudioFileUrl, runnerToken, job })
const copyCodecs = await canCopyForHLS({
fps: payload.output.fps,
resolution: payload.output.resolution,
path: videoInputPath
})
logger.info(`Downloaded input file ${payload.input.videoFileUrl} for job ${job.jobToken}. Running HLS transcoding.`)
const ffmpegVod = buildFFmpegVOD({
onJobProgress: progress => {
ffmpegProgress = progress
}
})
await ffmpegVod.transcode({
type: 'hls',
copyCodecs,
videoInputPath,
separatedAudioInputPath,
hlsPlaylist: { videoFilename },
outputPath,
inputFileMutexReleaser: () => {},
resolution: payload.output.resolution,
fps: payload.output.fps,
separatedAudio: payload.output.separatedAudio
})
const successBody: VODHLSTranscodingSuccess = {
resolutionPlaylistFile: outputPath,
videoFile: videoPath
}
await server.runnerJobs.success({
jobToken: job.jobToken,
jobUUID: job.uuid,
runnerToken,
payload: successBody,
reqPayload: payload
})
} finally {
if (videoInputPath) await remove(videoInputPath)
if (separatedAudioInputPath) await remove(separatedAudioInputPath)
if (outputPath) await remove(outputPath)
if (videoPath) await remove(videoPath)
if (updateProgressInterval) clearInterval(updateProgressInterval)
}
}
export async function processAudioMergeTranscoding (options: ProcessOptions<RunnerJobVODAudioMergeTranscodingPayload>) {
const { server, job, runnerToken } = options
const payload = job.payload
let ffmpegProgress: number
let audioPath: string
let previewPath: string
const outputPath = join(ConfigManager.Instance.getTranscodingDirectory(), `output-${buildUUID()}.mp4`)
const updateProgressInterval = scheduleTranscodingProgress({
job,
server,
runnerToken,
progressGetter: () => ffmpegProgress
})
try {
logger.info(
`Downloading input files ${payload.input.audioFileUrl} and ${payload.input.previewFileUrl} ` +
`for audio merge transcoding job ${job.jobToken}`
)
audioPath = await downloadInputFile({ url: payload.input.audioFileUrl, runnerToken, job })
previewPath = await downloadInputFile({ url: payload.input.previewFileUrl, runnerToken, job })
logger.info(
`Downloaded input files ${payload.input.audioFileUrl} and ${payload.input.previewFileUrl} ` +
`for job ${job.jobToken}. Running audio merge transcoding.`
)
const ffmpegVod = buildFFmpegVOD({
onJobProgress: progress => {
ffmpegProgress = progress
}
})
await ffmpegVod.transcode({
type: 'merge-audio',
audioPath,
videoInputPath: previewPath,
outputPath,
inputFileMutexReleaser: () => {},
resolution: payload.output.resolution,
fps: payload.output.fps
})
const successBody: VODAudioMergeTranscodingSuccess = {
videoFile: outputPath
}
await server.runnerJobs.success({
jobToken: job.jobToken,
jobUUID: job.uuid,
runnerToken,
payload: successBody,
reqPayload: payload
})
} finally {
if (audioPath) await remove(audioPath)
if (previewPath) await remove(previewPath)
if (outputPath) await remove(outputPath)
if (updateProgressInterval) clearInterval(updateProgressInterval)
}
}

View File

@@ -0,0 +1,19 @@
import { LogFn } from 'pino'
import { logger } from '../../../shared/index.js'
export function getWinstonLogger () {
return {
info: buildLogLevelFn(logger.info.bind(logger)),
debug: buildLogLevelFn(logger.debug.bind(logger)),
warn: buildLogLevelFn(logger.warn.bind(logger)),
error: buildLogLevelFn(logger.error.bind(logger))
}
}
function buildLogLevelFn (log: LogFn) {
return (arg1: string, arg2?: object) => {
if (arg2) return log(arg2, arg1)
return log(arg1)
}
}

View File

@@ -0,0 +1,388 @@
import { pick, shuffle, wait } from '@peertube/peertube-core-utils'
import { PeerTubeProblemDocument, RunnerJobType, ServerErrorCode } from '@peertube/peertube-models'
import { PeerTubeServer as PeerTubeServerCommand } from '@peertube/peertube-server-commands'
import { ensureDir, remove } from 'fs-extra/esm'
import { readdir } from 'fs/promises'
import { join } from 'path'
import { io, Socket } from 'socket.io-client'
import { ConfigManager } from '../shared/index.js'
import { IPCServer } from '../shared/ipc/index.js'
import { logger } from '../shared/logger.js'
import { JobWithToken, processJob } from './process/index.js'
import { getSupportedJobsList } from './shared/index.js'
type PeerTubeServer = PeerTubeServerCommand & {
runnerToken: string
runnerName: string
runnerDescription?: string
}
export class RunnerServer {
private servers: PeerTubeServer[] = []
private processingJobs: { job: JobWithToken, server: PeerTubeServer }[] = []
private checkingAvailableJobs = false
private gracefulShutdown = false
private cleaningUp = false
private initialized = false
private ipcServer: IPCServer
private readonly enabledJobsArray: RunnerJobType[]
private readonly sockets = new Map<PeerTubeServer, Socket>()
constructor (enabledJobs?: Set<RunnerJobType>) {
this.enabledJobsArray = enabledJobs
? Array.from(enabledJobs)
: getSupportedJobsList()
}
async run () {
logger.info('Running PeerTube runner in server mode')
logger.info('Supported and enabled job types: ' + this.enabledJobsArray.join(', '))
await ConfigManager.Instance.load()
for (const registered of ConfigManager.Instance.getConfig().registeredInstances) {
const serverCommand = new PeerTubeServerCommand({ url: registered.url })
this.loadServer(Object.assign(serverCommand, registered))
logger.info(`Loading registered instance ${registered.url}`)
}
// Run IPC
this.ipcServer = new IPCServer()
try {
await this.ipcServer.run(this)
} catch (err) {
logger.error(err, 'Cannot start local socket for IPC communication')
process.exit(-1)
}
// Cleanup on exit
for (const code of [ 'SIGTERM', 'SIGINT', 'SIGUSR1', 'SIGUSR2', 'uncaughtException' ]) {
process.on(code, async (err, origin) => {
if (code === 'uncaughtException') {
logger.error({ err, origin }, 'uncaughtException')
}
await this.onExit()
})
}
// Process jobs
await ensureDir(ConfigManager.Instance.getTranscodingDirectory())
await ensureDir(ConfigManager.Instance.getStoryboardDirectory())
await this.cleanupTMP()
logger.info(`Using ${ConfigManager.Instance.getTranscodingDirectory()} for transcoding directory`)
logger.info(`Using ${ConfigManager.Instance.getStoryboardDirectory()} for storyboard directory`)
this.initialized = true
await this.checkAvailableJobs()
}
// ---------------------------------------------------------------------------
async registerRunner (options: {
url: string
registrationToken: string
runnerName: string
runnerDescription?: string
}) {
const { url, registrationToken, runnerName, runnerDescription } = options
logger.info(`Registering runner ${runnerName} on ${url}...`)
const serverCommand = new PeerTubeServerCommand({ url })
const { runnerToken } = await serverCommand.runners.register({
name: runnerName,
description: runnerDescription,
registrationToken,
version: process.env.PACKAGE_VERSION
})
const server: PeerTubeServer = Object.assign(serverCommand, {
runnerToken,
runnerName,
runnerDescription
})
this.loadServer(server)
await this.saveRegisteredInstancesInConf()
logger.info(`Registered runner ${runnerName} on ${url}`)
}
private loadServer (server: PeerTubeServer) {
this.servers.push(server)
const url = server.url + '/runners'
const socket = io(url, {
auth: {
runnerToken: server.runnerToken
},
transports: [ 'websocket' ]
})
socket.on('connect_error', err => logger.warn({ err }, `Cannot connect to ${url} socket`))
socket.on('available-jobs', () => this.safeAsyncCheckAvailableJobs())
socket.on('connect', () => {
logger.info(`Connected to ${url} socket`)
this.safeAsyncCheckAvailableJobs()
})
socket.on('disconnect', () => logger.warn(`Disconnected from ${url} socket`))
socket.io.on('ping', () => logger.debug(`Received a "ping" for ${url}`))
this.sockets.set(server, socket)
}
async unregisterRunner (options: {
url: string
runnerName: string
}) {
const { url, runnerName } = options
const server = this.servers.find(s => s.url === url && s.runnerName === runnerName)
if (!server) {
logger.error(`Unknown server ${url} - ${runnerName} to unregister`)
return
}
logger.info(`Unregistering runner ${runnerName} on ${url}...`)
try {
await server.runners.unregister({ runnerToken: server.runnerToken })
} catch (err) {
logger.error({ err }, `Cannot unregister runner ${runnerName} on ${url}`)
}
this.unloadServer(server)
await this.saveRegisteredInstancesInConf()
logger.info(`Unregistered runner ${runnerName} on ${url}`)
}
private unloadServer (server: PeerTubeServer) {
this.servers = this.servers.filter(s => s !== server)
const socket = this.sockets.get(server)
socket.disconnect()
this.sockets.delete(server)
}
listRegistered () {
return {
servers: this.servers.map(s => {
return {
url: s.url,
runnerName: s.runnerName,
runnerDescription: s.runnerDescription
}
})
}
}
// ---------------------------------------------------------------------------
listJobs () {
return {
concurrency: ConfigManager.Instance.getConfig().jobs.concurrency,
processingJobs: this.processingJobs.map(j => ({
serverUrl: j.server.url,
job: pick(j.job, [ 'type', 'startedAt', 'progress', 'payload' ])
}))
}
}
// ---------------------------------------------------------------------------
requestGracefulShutdown () {
logger.info('Received graceful shutdown request')
this.gracefulShutdown = true
this.exitGracefullyIfNoProcessingJobs()
}
// ---------------------------------------------------------------------------
private safeAsyncCheckAvailableJobs () {
this.checkAvailableJobs()
.catch(err => logger.error({ err }, `Cannot check available jobs`))
}
private async checkAvailableJobs () {
if (!this.initialized) return
if (this.checkingAvailableJobs) return
if (this.gracefulShutdown) return
this.checkingAvailableJobs = true
let hadAvailableJob = false
for (const server of shuffle([ ...this.servers ])) {
try {
logger.info('Checking available jobs on ' + server.url)
const job = await this.requestJob(server)
if (!job) continue
hadAvailableJob = true
await this.tryToExecuteJobAsync(server, job)
} catch (err) {
hadAvailableJob = false
const code = (err.res?.body as PeerTubeProblemDocument)?.code
if (code === ServerErrorCode.RUNNER_JOB_NOT_IN_PENDING_STATE) {
logger.debug({ err }, 'Runner job is not in pending state anymore, retry later')
continue
}
if (code === ServerErrorCode.UNKNOWN_RUNNER_TOKEN) {
logger.error({ err }, `Unregistering ${server.url} as the runner token ${server.runnerToken} is invalid`)
await this.unregisterRunner({ url: server.url, runnerName: server.runnerName })
continue
}
logger.error({ err }, `Cannot request/accept job on ${server.url} for runner ${server.runnerName}`)
}
}
this.checkingAvailableJobs = false
if (hadAvailableJob && this.canProcessMoreJobs()) {
await wait(2500)
this.checkAvailableJobs()
.catch(err => logger.error({ err }, 'Cannot check more available jobs'))
}
}
private async requestJob (server: PeerTubeServer) {
logger.debug(`Requesting jobs on ${server.url} for runner ${server.runnerName}`)
const { availableJobs } = await server.runnerJobs.request({
runnerToken: server.runnerToken,
jobTypes: this.enabledJobsArray.length !== getSupportedJobsList().length
? this.enabledJobsArray
: undefined,
version: process.env.PACKAGE_VERSION
})
if (availableJobs.length === 0) {
logger.debug(`No job available on ${server.url} for runner ${server.runnerName}`)
return undefined
}
return availableJobs[0]
}
private async tryToExecuteJobAsync (server: PeerTubeServer, jobToAccept: { uuid: string }) {
if (!this.canProcessMoreJobs()) {
if (!this.gracefulShutdown) {
logger.info(
`Do not process more jobs (processing ${this.processingJobs.length} / ${ConfigManager.Instance.getConfig().jobs.concurrency})`
)
}
return
}
const { job } = await server.runnerJobs.accept({ runnerToken: server.runnerToken, jobUUID: jobToAccept.uuid })
const processingJob = { job, server }
this.processingJobs.push(processingJob)
processJob({ server, job, runnerToken: server.runnerToken })
.catch(err => {
logger.error({ err }, 'Cannot process job')
server.runnerJobs.error({ jobToken: job.jobToken, jobUUID: job.uuid, runnerToken: server.runnerToken, message: err.message })
.catch(err2 => logger.error({ err: err2 }, 'Cannot abort job after error'))
})
.finally(() => {
this.processingJobs = this.processingJobs.filter(p => p !== processingJob)
if (this.gracefulShutdown) this.exitGracefullyIfNoProcessingJobs()
return this.checkAvailableJobs()
})
}
// ---------------------------------------------------------------------------
private saveRegisteredInstancesInConf () {
const data = this.servers.map(s => {
return pick(s, [ 'url', 'runnerToken', 'runnerName', 'runnerDescription' ])
})
return ConfigManager.Instance.setRegisteredInstances(data)
}
private canProcessMoreJobs () {
if (this.cleaningUp) return false
if (this.gracefulShutdown) return false
return this.processingJobs.length < ConfigManager.Instance.getConfig().jobs.concurrency
}
// ---------------------------------------------------------------------------
private async cleanupTMP () {
const files = await readdir(ConfigManager.Instance.getTranscodingDirectory())
for (const file of files) {
await remove(join(ConfigManager.Instance.getTranscodingDirectory(), file))
}
}
private exitGracefullyIfNoProcessingJobs () {
if (this.processingJobs.length !== 0) return
logger.info('Shutting down the runner after graceful shutdown request')
this.onExit()
.catch(err => logger.error({ err }, 'Cannot exit runner'))
}
private async onExit () {
if (this.cleaningUp) return
this.cleaningUp = true
logger.info('Cleaning up after program exit')
try {
for (const { server, job } of this.processingJobs) {
logger.info(`Aborting job ${job.uuid} on ${server.url} as the runner is stopping`)
await server.runnerJobs.abort({
jobToken: job.jobToken,
jobUUID: job.uuid,
reason: 'Runner stopped',
runnerToken: server.runnerToken
})
}
await this.cleanupTMP()
await this.ipcServer?.stop()
} catch (err) {
logger.error(err)
process.exit(-1)
}
process.exit()
}
}

View File

@@ -0,0 +1 @@
export * from './supported-job.js'

View File

@@ -0,0 +1,43 @@
import {
RunnerJobGenerateStoryboardPayload,
RunnerJobLiveRTMPHLSTranscodingPayload,
RunnerJobPayload,
RunnerJobStudioTranscodingPayload,
RunnerJobTranscriptionPayload,
RunnerJobType,
RunnerJobVODAudioMergeTranscodingPayload,
RunnerJobVODHLSTranscodingPayload,
RunnerJobVODWebVideoTranscodingPayload,
VideoStudioTaskPayload
} from '@peertube/peertube-models'
const supportedMatrix: { [id in RunnerJobType]: (payload: RunnerJobPayload) => boolean } = {
'vod-web-video-transcoding': (_payload: RunnerJobVODWebVideoTranscodingPayload) => {
return true
},
'vod-hls-transcoding': (_payload: RunnerJobVODHLSTranscodingPayload) => {
return true
},
'vod-audio-merge-transcoding': (_payload: RunnerJobVODAudioMergeTranscodingPayload) => {
return true
},
'live-rtmp-hls-transcoding': (_payload: RunnerJobLiveRTMPHLSTranscodingPayload) => {
return true
},
'video-studio-transcoding': (payload: RunnerJobStudioTranscodingPayload) => {
const tasks = payload?.tasks
const supported = new Set<VideoStudioTaskPayload['name']>([ 'add-intro', 'add-outro', 'add-watermark', 'cut' ])
if (!Array.isArray(tasks)) return false
return tasks.every(t => t && supported.has(t.name))
},
'video-transcription': (_payload: RunnerJobTranscriptionPayload) => {
return true
},
'generate-video-storyboard': (_payload: RunnerJobGenerateStoryboardPayload) => true
}
export function getSupportedJobsList () {
return Object.keys(supportedMatrix) as unknown as RunnerJobType[]
}

View File

@@ -0,0 +1,162 @@
import { parse, stringify } from '@iarna/toml'
import { TranscriptionEngineName, WhisperBuiltinModelName } from '@peertube/peertube-transcription'
import envPaths from 'env-paths'
import { ensureDir, pathExists, remove } from 'fs-extra/esm'
import { readFile, writeFile } from 'fs/promises'
import merge from 'lodash-es/merge.js'
import { dirname, join } from 'path'
import { logger } from '../shared/index.js'
const paths = envPaths('peertube-runner')
type Config = {
jobs: {
concurrency: number
}
ffmpeg: {
threads: number
nice: number
}
registeredInstances: {
url: string
runnerToken: string
runnerName: string
runnerDescription?: string
}[]
transcription: {
engine: TranscriptionEngineName
enginePath: string | null
model: WhisperBuiltinModelName
modelPath: string | null
}
}
export class ConfigManager {
private static instance: ConfigManager
private config: Config = {
jobs: {
concurrency: 2
},
ffmpeg: {
threads: 2,
nice: 20
},
transcription: {
engine: 'whisper-ctranslate2',
enginePath: null,
model: 'small',
modelPath: null
},
registeredInstances: []
}
private id: string
private configFilePath: string
private constructor () {}
init (id: string) {
this.id = id
this.configFilePath = join(this.getConfigDir(), 'config.toml')
}
async load () {
logger.info(`Using ${this.configFilePath} as configuration file`)
if (this.isTestInstance()) {
logger.info('Removing configuration file as we are using the "test" id')
await remove(this.configFilePath)
}
await ensureDir(dirname(this.configFilePath))
if (!await pathExists(this.configFilePath)) {
await this.save()
}
const file = await readFile(this.configFilePath, 'utf-8')
this.config = merge(this.config, parse(file))
}
save () {
return writeFile(this.configFilePath, stringify(this.config))
}
// ---------------------------------------------------------------------------
async setRegisteredInstances (registeredInstances: {
url: string
runnerToken: string
runnerName: string
runnerDescription?: string
}[]) {
this.config.registeredInstances = registeredInstances
await this.save()
}
// ---------------------------------------------------------------------------
getConfig () {
return this.deepFreeze(this.config)
}
// ---------------------------------------------------------------------------
getStoryboardDirectory () {
return join(paths.cache, this.id, 'storyboard')
}
getTranscodingDirectory () {
return join(paths.cache, this.id, 'transcoding')
}
getTranscriptionDirectory () {
return join(paths.cache, this.id, 'transcription')
}
getSocketDirectory () {
return join(paths.data, this.id)
}
getSocketPath () {
return join(this.getSocketDirectory(), 'peertube-runner.sock')
}
getConfigDir () {
return join(paths.config, this.id)
}
// ---------------------------------------------------------------------------
isTestInstance () {
return typeof this.id === 'string' && this.id.match(/^test-\d$/)
}
// ---------------------------------------------------------------------------
// Thanks: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
private deepFreeze<T extends object> (object: T) {
const propNames = Reflect.ownKeys(object)
// Freeze properties before freezing self
for (const name of propNames) {
const value = object[name]
if ((value && typeof value === 'object') || typeof value === 'function') {
this.deepFreeze(value)
}
}
return Object.freeze({ ...object })
}
static get Instance () {
return this.instance || (this.instance = new this())
}
}

View File

@@ -0,0 +1,79 @@
import { createWriteStream } from 'fs'
import { remove } from 'fs-extra/esm'
import { RequestOptions } from 'https'
import { http, https } from 'follow-redirects'
import { logger } from './logger.js'
export function downloadFile (options: {
url: string
destination: string
runnerToken: string
jobToken: string
}) {
const { url, destination, runnerToken, jobToken } = options
logger.debug(`Downloading file ${url}`)
return new Promise<void>((res, rej) => {
const parsed = new URL(url)
const body = JSON.stringify({
runnerToken,
jobToken
})
const getOptions: RequestOptions = {
method: 'POST',
hostname: parsed.hostname,
port: parsed.port,
path: parsed.pathname,
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body, 'utf-8')
}
}
const request = getRequest(url)(getOptions, response => {
const code = response.statusCode ?? 0
if (code >= 400) {
return rej(new Error(response.statusMessage))
}
const file = createWriteStream(destination)
file.on('error', err => {
remove(destination)
.catch(err => logger.error(err))
return rej(err)
})
file.on('finish', () => res())
response.pipe(file)
})
request.on('error', err => {
remove(destination)
.catch(err => logger.error(err))
return rej(err)
})
request.write(body)
request.end()
setTimeout(() => {
request.destroy(new Error('Global request timeout'))
}, 2 * 3600 * 1000) // 2 hours
})
}
// ---------------------------------------------------------------------------
function getRequest (url: string) {
if (url.startsWith('https://')) return https.request.bind(https)
return http.request.bind(http)
}

View File

@@ -0,0 +1,3 @@
export * from './config-manager.js'
export * from './http.js'
export * from './logger.js'

View File

@@ -0,0 +1,2 @@
export * from './ipc-client.js'
export * from './ipc-server.js'

View File

@@ -0,0 +1,145 @@
import { Client as NetIPC } from 'net-ipc'
import CliTable3 from 'cli-table3'
import { ensureDir } from 'fs-extra/esm'
import { ConfigManager } from '../config-manager.js'
import { IPCRequest, IPCResponse, IPCResponseListJobs, IPCResponseListRegistered } from './shared/index.js'
export class IPCClient {
private netIPC: NetIPC
async run () {
await ensureDir(ConfigManager.Instance.getSocketDirectory())
const socketPath = ConfigManager.Instance.getSocketPath()
this.netIPC = new NetIPC({ path: socketPath })
try {
await this.netIPC.connect()
} catch (err) {
if (err.code === 'ECONNREFUSED') {
throw new Error(
'This runner is not currently running in server mode on this system. ' +
'Please run it using the `server` command first (in another terminal for example) and then retry your command.',
{ cause: err }
)
}
throw err
}
}
async askRegister (options: {
url: string
registrationToken: string
runnerName: string
runnerDescription?: string
}) {
const req: IPCRequest = {
type: 'register',
...options
}
const { success, error } = await this.netIPC.request(req) as IPCResponse
if (success) console.log('PeerTube instance registered')
else console.error('Could not register PeerTube instance on runner server side', error)
}
async askUnregister (options: {
url: string
runnerName: string
}) {
const req: IPCRequest = {
type: 'unregister',
...options
}
const { success, error } = await this.netIPC.request(req) as IPCResponse
if (success) console.log('PeerTube instance unregistered')
else console.error('Could not unregister PeerTube instance on runner server side', error)
}
async askListRegistered () {
const req: IPCRequest = {
type: 'list-registered'
}
const { success, error, data } = await this.netIPC.request(req) as IPCResponse<IPCResponseListRegistered>
if (!success) {
console.error('Could not list registered PeerTube instances', error)
return
}
const table = new CliTable3({
head: [ 'instance', 'runner name', 'runner description' ]
})
for (const server of data.servers) {
table.push([ server.url, server.runnerName, server.runnerDescription ])
}
console.log(table.toString())
}
async askListJobs (options: {
includePayload: boolean
}) {
const req: IPCRequest = {
type: 'list-jobs'
}
const { success, error, data } = await this.netIPC.request(req) as IPCResponse<IPCResponseListJobs>
if (!success) {
console.error('Could not list jobs', error)
return
}
const head = [ 'instance', 'type', 'started', 'progress' ]
if (options.includePayload) head.push('payload')
const table = new CliTable3({
head,
wordWrap: true,
wrapOnWordBoundary: false
})
for (const { serverUrl, job } of data.processingJobs) {
const row = [
serverUrl,
job.type,
job.startedAt?.toLocaleString(),
job.progress !== undefined && job.progress !== null
? `${job.progress}%`
: ''
]
if (options.includePayload) row.push(JSON.stringify(job.payload, undefined, 2))
table.push(row)
}
console.log(`Processing ${data.processingJobs.length}/${data.concurrency} jobs`)
console.log(table.toString())
}
// ---------------------------------------------------------------------------
async askGracefulShutdown () {
const req: IPCRequest = { type: 'graceful-shutdown' }
const { success, error } = await this.netIPC.request(req) as IPCResponse
if (success) console.log('Graceful shutdown acknowledged by the runner')
else console.error('Could not graceful shutdown runner', error)
}
// ---------------------------------------------------------------------------
stop () {
this.netIPC.destroy()
}
}

View File

@@ -0,0 +1,72 @@
import { ensureDir } from 'fs-extra/esm'
import { Server as NetIPC } from 'net-ipc'
import { pick } from '@peertube/peertube-core-utils'
import { RunnerServer } from '../../server/index.js'
import { ConfigManager } from '../config-manager.js'
import { logger } from '../logger.js'
import { IPCResponse, IPCResponseData, IPCRequest } from './shared/index.js'
export class IPCServer {
private netIPC: NetIPC
private runnerServer: RunnerServer
async run (runnerServer: RunnerServer) {
this.runnerServer = runnerServer
await ensureDir(ConfigManager.Instance.getSocketDirectory())
const socketPath = ConfigManager.Instance.getSocketPath()
this.netIPC = new NetIPC({ path: socketPath })
await this.netIPC.start()
logger.info(`IPC socket created on ${socketPath}`)
this.netIPC.on('request', async (req: IPCRequest, res) => {
try {
const data = await this.process(req)
this.sendResponse(res, { success: true, data })
} catch (err) {
logger.error({ err }, 'Cannot execute RPC call')
this.sendResponse(res, { success: false, error: err.message })
}
})
}
stop () {
return this.netIPC?.close()
}
private async process (req: IPCRequest) {
switch (req.type) {
case 'register':
await this.runnerServer.registerRunner(pick(req, [ 'url', 'registrationToken', 'runnerName', 'runnerDescription' ]))
return undefined
case 'unregister':
await this.runnerServer.unregisterRunner(pick(req, [ 'url', 'runnerName' ]))
return undefined
case 'list-registered':
return Promise.resolve(this.runnerServer.listRegistered())
case 'list-jobs':
return Promise.resolve(this.runnerServer.listJobs())
case 'graceful-shutdown':
this.runnerServer.requestGracefulShutdown()
return undefined
default:
throw new Error('Unknown RPC call ' + (req as any).type)
}
}
private sendResponse<T extends IPCResponseData> (
response: (data: any) => Promise<void>,
body: IPCResponse<T>
) {
response(body)
.catch(err => logger.error(err, 'Cannot send response after IPC request'))
}
}

View File

@@ -0,0 +1,2 @@
export * from './ipc-request.model.js'
export * from './ipc-response.model.js'

View File

@@ -0,0 +1,20 @@
export type IPCRequest =
IPCRequestRegister |
IPCRequestUnregister |
IPCRequestListRegistered |
IPCRequestGracefulShutdown |
IPCRequestListJobs
export type IPCRequestRegister = {
type: 'register'
url: string
registrationToken: string
runnerName: string
runnerDescription?: string
}
export type IPCRequestUnregister = { type: 'unregister', url: string, runnerName: string }
export type IPCRequestListRegistered = { type: 'list-registered' }
export type IPCRequestListJobs = { type: 'list-jobs' }
export type IPCRequestGracefulShutdown = { type: 'graceful-shutdown' }

View File

@@ -0,0 +1,24 @@
import { RunnerJob } from '@peertube/peertube-models'
export type IPCResponse <T extends IPCResponseData = undefined> = {
success: boolean
error?: string
data?: T
}
export type IPCResponseData = IPCResponseListRegistered | IPCResponseListJobs
export type IPCResponseListRegistered = {
servers: {
runnerName: string
runnerDescription: string
url: string
}[]
}
export type IPCResponseListJobs = {
concurrency: number
processingJobs: {
serverUrl: string
job: Pick<RunnerJob, 'type' | 'startedAt' | 'progress' | 'payload'>
}[]
}

View File

@@ -0,0 +1,4 @@
import { pino } from 'pino'
import pretty from 'pino-pretty'
export const logger = pino({ level: 'info' }, pretty())

View File

@@ -0,0 +1,17 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist",
"rootDir": "src",
"tsBuildInfoFile": "./dist/.tsbuildinfo"
},
"references": [
{ "path": "../../packages/core-utils" },
{ "path": "../../packages/ffmpeg" },
{ "path": "../../packages/models" },
{ "path": "../../packages/node-utils" },
{ "path": "../../packages/server-commands" },
{ "path": "../../packages/transcription" },
]
}

4
client/.browserslistrc Normal file
View File

@@ -0,0 +1,4 @@
last 1 Chrome version
last 2 Edge major versions
Firefox ESR
ios_saf >= 14

View File

@@ -0,0 +1,104 @@
---
description: 'Angular-specific coding standards and best practices'
applyTo: 'src/app/**/*.ts, src/app/**/*.html, src/app/**/*.scss, src/app/**/*.css'
---
# Angular Development Instructions
Instructions for generating high-quality Angular applications with TypeScript, using Angular Signals for state management, adhering to Angular best practices as outlined at https://angular.dev.
## Project Context
- Latest Angular version (use standalone components by default)
- TypeScript for type safety
- Angular CLI for project setup and scaffolding
- Follow Angular Style Guide (https://angular.dev/style-guide)
- Use Angular Material or other modern UI libraries for consistent styling (if specified)
## Development Standards
### Architecture
- Use standalone components unless modules are explicitly required
- Organize code by feature modules or domains for scalability
- Implement lazy loading for feature modules to optimize performance
- Use Angular's built-in dependency injection system effectively
- Structure components with a clear separation of concerns (smart vs. presentational components)
### TypeScript
- Enable strict mode in `tsconfig.json` for type safety
- Define clear interfaces and types for components, services, and models
- Use type guards and union types for robust type checking
- Implement proper error handling with RxJS operators (e.g., `catchError`)
- Use typed forms (e.g., `FormGroup`, `FormControl`) for reactive forms
### Component Design
- Follow Angular's component lifecycle hooks best practices
- When using Angular >= 19, Use `input()` `output()`, `viewChild()`, `viewChildren()`, `contentChild()` and `viewChildren()` functions instead of decorators; otherwise use decorators
- Leverage Angular's change detection strategy (default or `OnPush` for performance)
- Keep templates clean and logic in component classes or services
- Use Angular directives and pipes for reusable functionality
### Styling
- Use Angular's component-level CSS encapsulation (default: ViewEncapsulation.Emulated)
- Prefer SCSS for styling with consistent theming
- Implement responsive design using CSS Grid, Flexbox, or Angular CDK Layout utilities
- Follow Angular Material's theming guidelines if used
- Maintain accessibility (a11y) with ARIA attributes and semantic HTML
### State Management
- Use Angular Signals for reactive state management in components and services
- Leverage `signal()`, `computed()`, and `effect()` for reactive state updates
- Use writable signals for mutable state and computed signals for derived state
- Handle loading and error states with signals and proper UI feedback
- Use Angular's `AsyncPipe` to handle observables in templates when combining signals with RxJS
### Data Fetching
- Use Angular's `HttpClient` for API calls with proper typing
- Implement RxJS operators for data transformation and error handling
- Use Angular's `inject()` function for dependency injection in standalone components
- Implement caching strategies (e.g., `shareReplay` for observables)
- Store API response data in signals for reactive updates
- Handle API errors with global interceptors for consistent error handling
### Security
- Sanitize user inputs using Angular's built-in sanitization
- Implement route guards for authentication and authorization
- Use Angular's `HttpInterceptor` for CSRF protection and API authentication headers
- Validate form inputs with Angular's reactive forms and custom validators
- Follow Angular's security best practices (e.g., avoid direct DOM manipulation)
### Performance
- Enable production builds with `ng build --prod` for optimization
- Use lazy loading for routes to reduce initial bundle size
- Optimize change detection with `OnPush` strategy and signals for fine-grained reactivity
- Use trackBy in `ngFor` loops to improve rendering performance
- Implement server-side rendering (SSR) or static site generation (SSG) with Angular Universal (if specified)
### Testing
- Write unit tests for components, services, and pipes using Jasmine and Karma
- Use Angular's `TestBed` for component testing with mocked dependencies
- Test signal-based state updates using Angular's testing utilities
- Write end-to-end tests with Cypress or Playwright (if specified)
- Mock HTTP requests using `HttpClientTestingModule`
- Ensure high test coverage for critical functionality
## Implementation Process
1. Plan project structure and feature modules
2. Define TypeScript interfaces and models
3. Scaffold components, services, and pipes using Angular CLI
4. Implement data services and API integrations with signal-based state
5. Build reusable components with clear inputs and outputs
6. Add reactive forms and validation
7. Apply styling with SCSS and responsive design
8. Implement lazy-loaded routes and guards
9. Add error handling and loading states using signals
10. Write unit and end-to-end tests
11. Optimize performance and bundle size
## Additional Guidelines
- Follow Angular's naming conventions (e.g., `feature.component.ts`, `feature.service.ts`)
- Use Angular CLI commands for generating boilerplate code
- Document components and services with clear JSDoc comments
- Ensure accessibility compliance (WCAG 2.1) where applicable
- Use Angular's built-in i18n for internationalization (if specified)
- Keep code DRY by creating reusable utilities and shared modules
- Use signals consistently for state management to ensure reactive updates

View File

@@ -0,0 +1,112 @@
# PeerTube Client Development Instructions for Coding Agents
## Client Overview
This is the Angular frontend for PeerTube, a decentralized video hosting platform. The client is built with Angular 20+, TypeScript, and SCSS. It communicates with the PeerTube server API and provides the web interface for users, administrators, and content creators.
**Key Technologies:**
- Angular 20+ with standalone components
- TypeScript 5+
- SCSS for styling
- RxJS for reactive programming
- PrimeNg and Bootstrap for UI components
- WebdriverIO for E2E testing
- Angular CLI
## Client Build and Development Commands
### Prerequisites (for client development)
- Node.js 20+
- yarn 1
- Running PeerTube server (see ../server instructions)
### Essential Client Commands
```bash
# From the client directory:
cd /client
# 1. Install dependencies (ALWAYS first)
yarn install --pure-lockfile
# 2. Development server with hot reload
npm run dev
# 3. Build for production
npm run build
```
### Client Testing Commands
```bash
# From client directory:
npm run lint # ESLint for client code
```
### Common Client Issues and Solutions
**Angular Build Failures:**
- Always run `yarn install --pure-lockfile` after pulling changes
- Clear `node_modules` and reinstall if dependency errors occur
- Build may fail on memory issues: `NODE_OPTIONS="--max-old-space-size=4096" npm run build`
- Check TypeScript errors carefully - Angular is strict about types
**Development Server Issues:**
- Default port is 3000, ensure it's not in use
- Hot reload may fail on file permission issues
- Clear browser cache if changes don't appear
## Client Architecture and File Structure
### Client Directory Structure
```
/src/
/app/
+admin/ # Admin interface components
+my-account/ # User account management pages
+my-library/ # User's videos, playlists, subscriptions
+search/ # Search functionality and results
+shared/ # Shared Angular components, services, pipes
+standalone/ # Standalone Angular components
+videos/ # Video-related components (watch, upload, etc.)
/core/ # Core services (auth, server, notifications)
/helpers/ # Utility functions and helpers
/menu/ # Navigation menu components
/assets/ # Static assets (images, icons, etc.)
/environments/ # Environment configurations
/locale/ # Internationalization files
/sass/ # Global SCSS styles
```
### Key Client Configuration Files
- `angular.json` - Angular CLI workspace configuration
- `tsconfig.json` - TypeScript configuration for client
- `e2e/wdio*.conf.js` - WebdriverIO E2E test configurations
- `src/environments/` - Environment-specific configurations
### Shared Code with Server (`../shared/`)
The client imports TypeScript models and utilities from the shared directory:
- `../shared/models/` - Data models (Video, User, Channel, etc.). Import these in client code: `import { Video } from '@peertube/peertube-models'`
- `../shared/core-utils/` - Utility functions shared between client/server. Import these in client code: `import { ... } from '@peertube/peertube-core-utils'`
-
## Client Development Workflow
### Making Client Changes
1. **Angular Components:** Create/modify in `/src/app/` following existing patterns
2. **Shared Components:** Reusable components go in `/src/app/shared/`
3. **Services:** Core services in `/src/app/core/`, feature services with components
4. **Styles:** Component styles in `.scss` files, global styles in `/src/sass/`
5. **Assets:** Images, icons in `/src/assets/`
6. **Routing:** Routes defined in feature modules or `app-routing.module.ts`
## Trust These Instructions
These instructions are comprehensive and tested specifically for client development. Only search for additional information if:
1. Commands fail despite following instructions exactly
2. New error messages appear that aren't documented here
3. You need specific Angular implementation details not covered above
For server-side questions, refer to the server instructions in `../.github/copilot-instructions.md`.

19
client/.gitignore vendored Normal file
View File

@@ -0,0 +1,19 @@
/.angular/cache
/dist/
/node_modules
/compiled
/stats.json
/dll
/.awcache
/src/locale/pending_target/
/src/locale/target/iso639_*.xml
/src/locale/target/player_*.xml
/src/locale/target/server_*.xml
/e2e/local.log
/e2e/browserstack.err
/e2e/screenshots
/src/standalone/player/build
/src/standalone/player/dist
/src/standalone/embed-player-api/build
/src/standalone/embed-player-api/dist
/e2e/logs

75
client/.stylelintrc.json Normal file
View File

@@ -0,0 +1,75 @@
{
"extends": "stylelint-config-sass-guidelines",
"plugins": [
"stylelint-order"
],
"rules": {
"declaration-empty-line-before": [
"always",
{
"except": [
"first-nested"
],
"ignore": [ "after-declaration", "after-comment" ]
}
],
"at-rule-empty-line-before": [
"always",
{
"except": [
"first-nested",
"blockless-after-blockless"
],
"ignore": [ "after-comment" ],
"ignoreAtRules": [ "else" ]
}
],
"order/order": [
"custom-properties",
"declarations",
{
"type": "at-rule",
"name": "include"
}
],
"scss/selector-no-redundant-nesting-selector": null,
"scss/at-import-no-partial-leading-underscore": null,
"color-hex-length": null,
"selector-pseudo-element-no-unknown": [
true,
{
"ignorePseudoElements": [
"ng-deep"
]
}
],
"max-nesting-depth": [
8,
{
"ignore": [
"blockless-at-rules",
"pseudo-classes"
]
}
],
"selector-max-compound-selectors": 9,
"selector-no-qualifying-type": null,
"scss/at-extend-no-missing-placeholder": null,
"rule-empty-line-before": null,
"selector-max-id": null,
"scss/at-function-pattern": null,
"scss/load-no-partial-leading-underscore": null,
"@stylistic/string-quotes": null,
"@stylistic/color-hex-case": null,
"@stylistic/function-parentheses-space-inside": null,
"property-no-vendor-prefix": [
true,
{
"ignoreProperties": [
"mask-image",
"mask-size"
]
}
]
}
}

9
client/.xliffmerge.json Normal file
View File

@@ -0,0 +1,9 @@
{
"xliffmergeOptions": {
"i18nFormat": "xlf",
"srcDir": "src/locale",
"genDir": "src/locale",
"i18nBaseFile": "angular",
"defaultLanguage": "en-US"
}
}

363
client/angular.json Normal file
View File

@@ -0,0 +1,363 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"PeerTube": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"i18n": {
"sourceLocale": {
"code": "en",
"baseHref": "/client/en-US/"
},
"locales": {
"ar": {
"translation": "src/locale/angular.ar.xlf",
"baseHref": "/client/ar/"
},
"sk": {
"translation": "src/locale/angular.sk-SK.xlf",
"baseHref": "/client/sk-SK/"
},
"fa": {
"translation": "src/locale/angular.fa-IR.xlf",
"baseHref": "/client/fa-IR/"
},
"hu": {
"translation": "src/locale/angular.hu-HU.xlf",
"baseHref": "/client/hu-HU/"
},
"th": {
"translation": "src/locale/angular.th-TH.xlf",
"baseHref": "/client/th-TH/"
},
"tr": {
"translation": "src/locale/angular.tr-TR.xlf",
"baseHref": "/client/tr-TR/"
},
"fi": {
"translation": "src/locale/angular.fi-FI.xlf",
"baseHref": "/client/fi-FI/"
},
"nl": {
"translation": "src/locale/angular.nl-NL.xlf",
"baseHref": "/client/nl-NL/"
},
"gd": {
"translation": "src/locale/angular.gd.xlf",
"baseHref": "/client/gd/"
},
"el": {
"translation": "src/locale/angular.el-GR.xlf",
"baseHref": "/client/el-GR/"
},
"es": {
"translation": "src/locale/angular.es-ES.xlf",
"baseHref": "/client/es-ES/"
},
"oc": {
"translation": "src/locale/angular.oc.xlf",
"baseHref": "/client/oc/"
},
"pt": {
"translation": "src/locale/angular.pt-BR.xlf",
"baseHref": "/client/pt-BR/"
},
"pt-PT": {
"translation": "src/locale/angular.pt-PT.xlf",
"baseHref": "/client/pt-PT/"
},
"sv": {
"translation": "src/locale/angular.sv-SE.xlf",
"baseHref": "/client/sv-SE/"
},
"pl": {
"translation": "src/locale/angular.pl-PL.xlf",
"baseHref": "/client/pl-PL/"
},
"ru": {
"translation": "src/locale/angular.ru-RU.xlf",
"baseHref": "/client/ru-RU/"
},
"sq": {
"translation": "src/locale/angular.sq.xlf",
"baseHref": "/client/sq/"
},
"hr": {
"translation": "src/locale/angular.hr.xlf",
"baseHref": "/client/hr/"
},
"zh-Hans": {
"translation": "src/locale/angular.zh-Hans-CN.xlf",
"baseHref": "/client/zh-Hans-CN/"
},
"zh-Hant": {
"translation": "src/locale/angular.zh-Hant-TW.xlf",
"baseHref": "/client/zh-Hant-TW/"
},
"fr": {
"translation": "src/locale/angular.fr-FR.xlf",
"baseHref": "/client/fr-FR/"
},
"ja": {
"translation": "src/locale/angular.ja-JP.xlf",
"baseHref": "/client/ja-JP/"
},
"eu": {
"translation": "src/locale/angular.eu-ES.xlf",
"baseHref": "/client/eu-ES/"
},
"ca": {
"translation": "src/locale/angular.ca-ES.xlf",
"baseHref": "/client/ca-ES/"
},
"gl": {
"translation": "src/locale/angular.gl-ES.xlf",
"baseHref": "/client/gl-ES/"
},
"cs": {
"translation": "src/locale/angular.cs-CZ.xlf",
"baseHref": "/client/cs-CZ/"
},
"eo": {
"translation": "src/locale/angular.eo.xlf",
"baseHref": "/client/eo/"
},
"de": {
"translation": "src/locale/angular.de-DE.xlf",
"baseHref": "/client/de-DE/"
},
"it": {
"translation": "src/locale/angular.it-IT.xlf",
"baseHref": "/client/it-IT/"
},
"vi": {
"translation": "src/locale/angular.vi-VN.xlf",
"baseHref": "/client/vi-VN/"
},
"kab": {
"translation": "src/locale/angular.kab.xlf",
"baseHref": "/client/kab/"
},
"nb": {
"translation": "src/locale/angular.nb-NO.xlf",
"baseHref": "/client/nb-NO/"
},
"tok": {
"translation": "src/locale/angular.tok.xlf",
"baseHref": "/client/tok/"
},
"nn": {
"translation": "src/locale/angular.nn.xlf",
"baseHref": "/client/nn/"
},
"is": {
"translation": "src/locale/angular.is.xlf",
"baseHref": "/client/is/"
},
"uk": {
"translation": "src/locale/angular.uk-UA.xlf",
"baseHref": "/client/uk-UA/"
}
}
},
"architect": {
"build": {
"builder": "@angular/build:application",
"options": {
"i18nMissingTranslation": "ignore",
"localize": true,
"outputPath": {
"base": "dist"
},
"index": "src/index.html",
"tsConfig": "tsconfig.json",
"polyfills": [
"src/polyfills.ts",
"@angular/localize/init"
],
"baseHref": "/",
"stylePreprocessorOptions": {
"includePaths": [
"src/sass/include",
"."
],
"sass": {
"silenceDeprecations": [ "import", "color-functions", "global-builtin" ]
}
},
"assets": [
"src/assets/images"
],
"styles": [
"src/sass/application.scss"
],
"allowedCommonJsDependencies": [
"qrcode",
"chart.js",
"htmlparser2",
"markdown-it-emoji/light",
"linkifyjs/lib/linkify-html",
"linkifyjs/lib/plugins/mention",
"sanitize-html",
"debug",
"@peertube/p2p-media-loader-hlsjs",
"video.js",
"sha.js",
"postcss",
"focus-visible",
"path-browserify",
"deep-merge",
"escape-string-regexp",
"is-plain-object",
"parse-srcset",
"core-js/features/reflect",
"hammerjs",
"jschannel",
"color-bits"
],
"scripts": [],
"extractLicenses": false,
"sourceMap": true,
"optimization": false,
"namedChunks": true,
"browser": "src/main.ts",
"loader": {
".svg": "text"
}
},
"configurations": {
"production": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true,
"serviceWorker": "src/ngsw-config.json",
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "140kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
},
"ar-locale": {
"localize": [
"ar"
],
"budgets": [
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.hmr.ts"
}
]
},
"hmr": {
"localize": false,
"budgets": [
{
"type": "anyComponentStyle",
"maximumWarning": "6kb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.hmr.ts"
}
]
}
}
},
"serve": {
"builder": "@angular/build:dev-server",
"options": {
"proxyConfig": "proxy.config.json",
"buildTarget": "PeerTube:build"
},
"configurations": {
"hmr": {
"buildTarget": "PeerTube:build:hmr"
},
"ar-locale": {
"buildTarget": "PeerTube:build:ar-locale"
}
}
},
"extract-i18n": {
"builder": "@angular/build:extract-i18n"
},
"lint": {
"builder": "@angular-eslint/builder:lint",
"options": {
"lintFilePatterns": [
"e2e/**/*.ts",
"src/**/*.ts",
"src/**/*.html"
]
}
}
}
}
},
"schematics": {
"@schematics/angular:component": {
"prefix": "my",
"style": "scss",
"skipTests": true,
"flat": true,
"type": "component"
},
"@schematics/angular:directive": {
"prefix": "my",
"type": "directive"
},
"@angular-eslint/schematics:application": {
"setParserOptionsProject": true
},
"@angular-eslint/schematics:library": {
"setParserOptionsProject": true
},
"@schematics/angular:service": {
"type": "service"
},
"@schematics/angular:guard": {
"typeSeparator": "."
},
"@schematics/angular:interceptor": {
"typeSeparator": "."
},
"@schematics/angular:module": {
"typeSeparator": "."
},
"@schematics/angular:pipe": {
"typeSeparator": "."
},
"@schematics/angular:resolver": {
"typeSeparator": "."
}
},
"cli": {
"analytics": false
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,12 @@
browser.addCommand('chooseFile', async function (this: WebdriverIO.Element, localFilePath: string) {
try {
const remoteFile = await browser.uploadFile(localFilePath)
return this.addValue(remoteFile)
} catch {
console.log('Cannot upload file, fallback to add value.')
// Firefox does not support upload file, but if we're running the test in local we don't really need it
return this.addValue(localFilePath)
}
}, true)

View File

@@ -0,0 +1,73 @@
import { NSFWPolicyType } from '@peertube/peertube-models'
import { browserSleep, go, setCheckboxEnabled } from '../utils'
export class AdminConfigPage {
async navigateTo (page: 'information' | 'live' | 'general' | 'homepage') {
const url = '/admin/settings/config/' + page
const currentUrl = await browser.getUrl()
if (!currentUrl.endsWith(url)) {
await go(url)
}
await $('a.active[href="' + url + '"]').waitForDisplayed()
}
async updateNSFWSetting (newValue: NSFWPolicyType) {
await this.navigateTo('information')
const elem = $(`#instanceDefaultNSFWPolicy-${newValue} + label`)
await elem.waitForDisplayed()
await elem.scrollIntoView({ block: 'center' }) // Avoid issues with fixed header
await elem.waitForClickable()
return elem.click()
}
async updateHomepage (newValue: string) {
await this.navigateTo('homepage')
return $('#homepageContent').setValue(newValue)
}
async toggleSignup (enabled: boolean) {
await this.navigateTo('general')
return setCheckboxEnabled('signupEnabled', enabled)
}
async toggleSignupApproval (required: boolean) {
await this.navigateTo('general')
return setCheckboxEnabled('signupRequiresApproval', required)
}
async toggleSignupEmailVerification (required: boolean) {
await this.navigateTo('general')
return setCheckboxEnabled('signupRequiresEmailVerification', required)
}
async toggleLive (enabled: boolean) {
await this.navigateTo('live')
return setCheckboxEnabled('liveEnabled', enabled)
}
async save () {
const button = $('my-admin-save-bar .save-button')
try {
await button.waitForClickable()
} catch {
// The config may have not been changed
return
} finally {
await browserSleep(1000) // Wait for the button to be clickable
}
await button.click()
await button.waitForClickable({ reverse: true })
}
}

View File

@@ -0,0 +1,31 @@
import { browserSleep, go } from '../utils'
export class AdminPluginPage {
async navigateToPluginSearch () {
await go('/admin/settings/plugins/search')
await $('my-plugin-search').waitForDisplayed()
}
async search (name: string) {
const input = $('.search-bar input')
await input.waitForDisplayed()
await input.clearValue()
await input.setValue(name)
await browserSleep(1000)
}
async installHelloWorld () {
$('.plugin-name=hello-world').waitForDisplayed()
await $('.card-body my-button[icon=cloud-download]').click()
const submitModalButton = $('.modal-content input[type=submit]')
await submitModalButton.waitForClickable()
await submitModalButton.click()
await $('.card-body my-edit-button').waitForDisplayed()
}
}

View File

@@ -0,0 +1,33 @@
import { browserSleep, findParentElement, go } from '../utils'
export class AdminRegistrationPage {
async navigateToRegistrationsList () {
await go('/admin/moderation/registrations/list')
await $('my-registration-list').waitForDisplayed()
}
async accept (username: string, moderationResponse: string) {
const usernameEl = $('*=' + username)
await usernameEl.waitForDisplayed()
const tr = await findParentElement(usernameEl, async el => await el.getTagName() === 'tr')
await tr.$('.action-cell .dropdown-root').click()
const accept = $('span*=Accept this request')
await accept.waitForClickable()
await accept.click()
const moderationResponseTextarea = $('#moderationResponse')
await moderationResponseTextarea.waitForDisplayed()
await moderationResponseTextarea.setValue(moderationResponse)
const submitButton = $('.modal-footer input[type=submit]')
await submitButton.waitForClickable()
await submitButton.click()
await browserSleep(1000)
}
}

View File

@@ -0,0 +1,24 @@
export class AdminUserPage {
async createUser (options: {
username: string
password: string
}) {
const { username, password } = options
await $('.menu-link[title=Overview]').click()
await $('a*=Create user').click()
await $('#username').waitForDisplayed()
await $('#username').setValue(username)
await $('#password').setValue(password)
await $('#channelName').setValue(`${username}_channel`)
await $('#email').setValue(`${username}@example.com`)
const submit = $('my-user-create .primary-button')
await submit.scrollIntoView()
await submit.waitForClickable()
await submit.click()
await $('.cell-username*=' + username).waitForDisplayed()
}
}

View File

@@ -0,0 +1,45 @@
import { NSFWPolicyType } from '@peertube/peertube-models'
import { getCheckbox } from '../utils'
export class AnonymousSettingsPage {
async openSettings () {
const link = $('my-header .settings-button')
await link.waitForClickable()
await link.click()
await $('my-user-video-settings').waitForDisplayed()
}
async closeSettings () {
const closeModal = $('.modal.show .modal-header > button')
await closeModal.waitForClickable()
await closeModal.click()
await $('.modal.show').waitForDisplayed({ reverse: true })
}
async clickOnP2PCheckbox () {
const p2p = await getCheckbox('p2pEnabled')
await p2p.waitForClickable()
await p2p.click()
}
async updateNSFW (newValue: NSFWPolicyType) {
const nsfw = $(`#nsfwPolicy-${newValue} + label`)
await nsfw.waitForClickable()
await nsfw.click()
await $(`#nsfwPolicy-${newValue}:checked`).waitForExist()
}
async updateViolentFlag (newValue: NSFWPolicyType) {
const nsfw = $(`#nsfwFlagViolent-${newValue} + label`)
await nsfw.waitForClickable()
await nsfw.click()
await $(`#nsfwFlagViolent-${newValue}:checked`).waitForExist()
}
}

View File

@@ -0,0 +1,97 @@
import { browserSleep, go, isAndroid } from '../utils'
export class LoginPage {
constructor (private isMobileDevice: boolean) {
}
async login (options: {
username: string
password: string
displayName?: string
url?: string
}) {
const { username, password, url = '/login', displayName = username } = options
await go(url)
await browser.execute(`window.localStorage.setItem('no_account_setup_warning_modal', 'true')`)
await browser.execute(`window.localStorage.setItem('no_instance_config_warning_modal', 'true')`)
await browser.execute(`window.localStorage.setItem('no_welcome_modal', 'true')`)
await $('input#username').setValue(username)
await $('input#password').setValue(password)
await browserSleep(1000)
const submit = $('.login-form-and-externals > form input[type=submit]')
await submit.click()
// Have to do this on Android, don't really know why
// I think we need to "escape" from the password input, so click twice on the submit button
if (isAndroid()) {
await browserSleep(2000)
await submit.click()
}
await this.ensureIsLoggedInAs(displayName)
}
async getLoginError (username: string, password: string) {
await go('/login')
await $('input#username').setValue(username)
await $('input#password').setValue(password)
await browser.pause(1000)
await $('form input[type=submit]').click()
return $('.alert-danger').getText()
}
loginAsRootUser () {
return this.login({ username: 'root', password: this.getRootPassword() })
}
getRootPassword () {
return 'test' + this.getSuffix()
}
loginOnPeerTube2 () {
if (!process.env.PEERTUBE2_E2E_PASSWORD) {
throw new Error('PEERTUBE2_E2E_PASSWORD env is missing for user e2e on peertube2.cpy.re')
}
return this.login({ username: 'e2e', password: process.env.PEERTUBE2_E2E_PASSWORD, url: 'https://peertube2.cpy.re/login' })
}
async logout () {
const loggedInDropdown = $('.logged-in-container .dropdown-toggle')
await loggedInDropdown.waitForClickable()
await loggedInDropdown.click()
const logout = $('.dropdown-item.logout')
await logout.waitForClickable()
await logout.click()
await browser.waitUntil(() => {
return $$('my-login-link, my-error-page a[href="/login"]').some(e => e.isDisplayed())
})
}
async ensureIsLoggedInAs (displayName: string) {
await this.getLoggedInInfoElem(displayName).waitForExist()
}
private getLoggedInInfoElem (displayName: string) {
return $('.logged-in-info').$('.display-name*=' + displayName)
}
private getSuffix () {
return browser.options.baseUrl
? browser.options.baseUrl.slice(-1)
: '1'
}
}

View File

@@ -0,0 +1,203 @@
import { NSFWPolicyType } from '@peertube/peertube-models'
import { getCheckbox, go, selectCustomSelect } from '../utils'
export class MyAccountPage {
navigateToMyVideos () {
return $('a[href="/my-library/videos"]').click()
}
navigateToMyPlaylists () {
return $('a[href="/my-library/video-playlists"]').click()
}
navigateToMyHistory () {
return $('a[href="/my-library/history/videos"]').click()
}
// ---------------------------------------------------------------------------
// My account settings
// ---------------------------------------------------------------------------
navigateToMySettings () {
return $('a[href="/my-account"]').click()
}
async updateNSFW (newValue: NSFWPolicyType) {
const nsfw = $(`#nsfwPolicy-${newValue} + label`)
await nsfw.waitForDisplayed()
await nsfw.scrollIntoView({ block: 'center' }) // Avoid issues with fixed header
await nsfw.waitForClickable()
await nsfw.click()
await this.submitVideoSettings()
}
async updateViolentFlag (newValue: NSFWPolicyType) {
const nsfw = $(`#nsfwFlagViolent-${newValue} + label`)
await nsfw.waitForDisplayed()
await nsfw.scrollIntoView({ block: 'center' }) // Avoid issues with fixed header
await nsfw.waitForClickable()
await nsfw.click()
await this.submitVideoSettings()
}
async clickOnP2PCheckbox () {
const p2p = await getCheckbox('p2pEnabled')
await p2p.waitForClickable()
await p2p.scrollIntoView({ block: 'center' }) // Avoid issues with fixed header
await p2p.click()
await this.submitVideoSettings()
}
private async submitVideoSettings () {
const submit = $('my-user-video-settings input[type=submit]')
await submit.waitForClickable()
await submit.scrollIntoView({ block: 'center' }) // Avoid issues with fixed header
await submit.click()
}
async updateEmail (email: string, password: string) {
const emailInput = $('my-account-change-email #new-email')
await emailInput.waitForDisplayed()
await emailInput.scrollIntoView({ block: 'center' }) // Avoid issues with fixed header
await emailInput.setValue(email)
const passwordInput = $('my-account-change-email #password')
await passwordInput.waitForDisplayed()
await passwordInput.setValue(password)
const submit = $('my-account-change-email input[type=submit]')
await submit.scrollIntoView({ block: 'center' }) // Avoid issues with fixed header
await submit.waitForClickable()
await submit.click()
}
// ---------------------------------------------------------------------------
// My account videos
// ---------------------------------------------------------------------------
async removeVideo (name: string) {
const container = await this.getVideoRow(name)
await container.$('my-action-dropdown .dropdown-toggle').click()
const deleteItem = () => {
return $$('.dropdown-menu .dropdown-item').find<WebdriverIO.Element>(async v => {
const text = await v.getText()
return text.includes('Delete')
})
}
await (await deleteItem()).waitForClickable()
return (await deleteItem()).click()
}
validRemove () {
return $('input[type=submit]').click()
}
async countVideos (names: string[]) {
const elements = await $$('.video-cell-name .name').filter(async e => {
const t = await e.getText()
return names.some(n => t.includes(n))
})
return elements.length
}
async getVideoRow (name: string) {
let el = $('.name*=' + name)
await el.waitForDisplayed()
while (await el.getTagName() !== 'tr') {
el = el.parentElement()
}
return el
}
// ---------------------------------------------------------------------------
// My account playlists
// ---------------------------------------------------------------------------
async getPlaylistVideosText (name: string) {
const elem = await this.getPlaylist(name)
return elem.$('.miniature-playlist-info-overlay').getText()
}
async clickOnPlaylist (name: string) {
const elem = await this.getPlaylist(name)
return elem.$('.miniature-thumbnail').click()
}
async countTotalPlaylistElements () {
await $('<my-video-playlist-element-miniature>').waitForDisplayed()
return $$('<my-video-playlist-element-miniature>').length
}
playPlaylist () {
return $('.playlist-info .miniature-thumbnail').click()
}
async goOnAssociatedPlaylistEmbed () {
let url = await browser.getUrl()
url = url.replace('/w/p/', '/video-playlists/embed/')
url = url.replace(':3333', ':9001')
return go(url)
}
async updatePlaylistPrivacy (playlistUUID: string, privacy: 'Public' | 'Private' | 'Unlisted') {
go('/my-library/video-playlists/update/' + playlistUUID)
await $('a[href*="/my-library/video-playlists/update/"]').waitForDisplayed()
await selectCustomSelect('videoChannelId', 'Main root channel')
await selectCustomSelect('privacy', privacy)
const submit = $('form input[type=submit]')
await submit.waitForClickable()
await submit.scrollIntoView()
await submit.click()
return browser.waitUntil(async () => {
return (await browser.getUrl()).includes('my-library/video-playlists')
})
}
private async getPlaylist (name: string) {
const playlist = () => {
return $$('my-video-playlist-miniature')
.filter(async e => {
const t = await e.$('img').getAttribute('aria-label')
return t.includes(name)
})
.then(elems => elems[0])
}
await browser.waitUntil(async () => {
const el = await playlist()
return el?.isDisplayed()
})
return playlist()
}
}

View File

@@ -0,0 +1,107 @@
import { browserSleep, isIOS, isMobileDevice, isSafari } from '../utils'
export class PlayerPage {
getWatchVideoPlayerCurrentTime () {
const elem = $('video')
const p = isIOS()
? elem.getAttribute('currentTime')
: elem.getProperty('currentTime')
return p.then(t => parseInt(t + '', 10))
.then(t => Math.ceil(t))
}
waitUntilPlaylistInfo (text: string, maxTime: number) {
return browser.waitUntil(async () => {
// Without this we have issues on iphone
await $('.video-js').click()
return (await $('.video-js .vjs-playlist-info').getText()).includes(text)
}, { timeout: maxTime })
}
waitUntilPlayerWrapper () {
return $('#video-wrapper').waitForExist()
}
waitUntilPlaying () {
return $('.video-js.vjs-playing').waitForDisplayed()
}
async playAndPauseVideo (isAutoplay: boolean, waitUntilSec: number) {
// Autoplay is disabled on mobile and Safari
if (isIOS() || isSafari() || isMobileDevice() || isAutoplay === false) {
await this.playVideo()
}
await $('div.video-js.vjs-has-started').waitForExist()
await browserSleep(2000)
await browser.waitUntil(async () => {
return (await this.getWatchVideoPlayerCurrentTime()) >= waitUntilSec
}, { timeout: Math.max(waitUntilSec * 2 * 1000, 30000) })
// Pause video
await $('div.video-js').click()
}
async playVideo () {
await $('div.video-js.vjs-paused, div.video-js.vjs-playing').waitForExist()
if (await $('div.video-js.vjs-playing').isExisting()) {
if (!isIOS()) return
// On iOS, the web browser may have aborted player autoplay, so check the video is still autoplayed
await browserSleep(5000)
if (await $('div.video-js.vjs-playing').isExisting()) return
}
// Autoplay is disabled on iOS and Safari
if (isIOS() || isSafari() || isMobileDevice()) {
// We can't play the video if it is not muted
await browser.execute(`document.querySelector('video').muted = true`)
}
return this.clickOnPlayButton()
}
getPlayButton () {
return $('.vjs-big-play-button')
}
getNSFWContentText () {
return $('.video-js .nsfw-info').getText()
}
getNSFWDetailsContent () {
return $('.video-js .nsfw-details-content')
}
getMoreNSFWInfoButton () {
return $('.video-js .nsfw-info button')
}
async hasPoster () {
const img = $('.video-js .vjs-poster img')
return await img.isDisplayed() && (await img.getAttribute('src')).startsWith('http')
}
private async clickOnPlayButton () {
await this.getPlayButton().waitForClickable()
await this.getPlayButton().click()
}
async fillEmbedVideoPassword (videoPassword: string) {
const videoPasswordInput = $('input#video-password-input')
const confirmButton = $('button#video-password-submit')
await videoPasswordInput.clearValue()
await videoPasswordInput.setValue(videoPassword)
await confirmButton.waitForClickable()
return confirmButton.click()
}
}

View File

@@ -0,0 +1,87 @@
import { getCheckbox } from '../utils'
export class SignupPage {
getRegisterMenuButton () {
return $('.create-account-button')
}
async clickOnRegisterButton () {
const button = this.getRegisterMenuButton()
await button.waitForClickable()
await button.click()
}
async validateStep () {
const next = $('button[type=submit]')
await next.scrollIntoView({ block: 'center' })
await next.waitForClickable()
await next.click()
}
async checkTerms () {
const terms = await getCheckbox('terms')
await terms.waitForClickable()
return terms.click()
}
async getEndMessage () {
const alert = $('.pt-alert-primary')
await alert.waitForDisplayed()
return alert.getText()
}
async fillRegistrationReason (reason: string) {
await $('#registrationReason').setValue(reason)
}
async fillAccountStep (options: {
username: string
password?: string
displayName?: string
email?: string
}) {
await $('#displayName').setValue(options.displayName || `${options.username} display name`)
await $('#username').setValue(options.username)
await $('#password').setValue(options.password || 'superpassword')
// Fix weird bug on firefox that "cannot scroll into view" when using just `setValue`
await $('#email').scrollIntoView({ block: 'center' })
await $('#email').waitForClickable()
await $('#email').setValue(options.email || `${options.username}@example.com`)
}
async fillChannelStep (options: {
name: string
displayName?: string
}) {
await $('#displayName').setValue(options.displayName || `${options.name} channel display name`)
await $('#name').setValue(options.name)
}
async fullSignup ({ accountInfo, channelInfo }: {
accountInfo: {
username: string
password?: string
displayName?: string
email?: string
}
channelInfo: {
name: string
}
}) {
await this.clickOnRegisterButton()
await this.validateStep()
await this.checkTerms()
await this.validateStep()
await this.fillAccountStep(accountInfo)
await this.validateStep()
await this.fillChannelStep(channelInfo)
await this.validateStep()
await this.getEndMessage()
}
}

View File

@@ -0,0 +1,140 @@
import { browserSleep, findParentElement, go } from '../utils'
export class VideoListPage {
constructor (private isMobileDevice: boolean, private isSafari: boolean) {
}
async goOnVideosList () {
let url: string
// We did not upload a file on a mobile device
if (this.isMobileDevice === true || this.isSafari === true) {
url = 'https://peertube2.cpy.re/videos/browse?scope=local'
} else {
url = '/videos/browse'
}
await go(url)
// Waiting the following element does not work on Safari...
if (this.isSafari) return browserSleep(3000)
await this.waitForList()
}
async goOnBrowseVideos () {
await $('.menu-link*=Home').click()
const browseVideos = $('a*=Browse videos')
await browseVideos.waitForClickable()
await browseVideos.click()
await this.waitForList()
}
async goOnHomepage () {
await go('/home')
await this.waitForList()
}
async goOnRootChannel () {
await go('/c/root_channel/videos')
await this.waitForList()
}
async goOnRootAccount () {
await go('/a/root/videos')
await this.waitForList()
}
async goOnRootAccountChannels () {
await go('/a/root/video-channels')
await this.waitForList()
}
async getNSFWFilterText () {
const el = $('.active-filter*=Sensitive')
await el.waitForDisplayed()
return el.getText()
}
async getVideosListName () {
const elems = $$('.videos .video-miniature .video-name')
const texts = await elems.map(e => e.getText())
return texts.map(t => t.trim())
}
isVideoDisplayed (name: string) {
return $('.video-name=' + name).isDisplayed()
}
async isVideoBlurred (name: string) {
const miniature = await this.getVideoMiniature(name)
const filter = await miniature.$('my-video-thumbnail img').getCSSProperty('filter')
return filter.value !== 'none'
}
async hasVideoWarning (name: string) {
const miniature = await this.getVideoMiniature(name)
return miniature.$('.nsfw-warning').isDisplayed()
}
async expectVideoNSFWTooltip (name: string, summary?: string) {
const miniature = await this.getVideoMiniature(name)
const warning = miniature.$('.nsfw-warning')
await warning.waitForDisplayed()
expect(await warning.getAttribute('aria-label')).toEqual(summary)
}
private async getVideoMiniature (name: string) {
const videoName = $('.video-name=' + name)
await videoName.waitForDisplayed()
return findParentElement(videoName, async el => await el.getTagName() === 'my-video-miniature')
}
async clickOnVideo (videoName: string) {
const video = async () => {
const videos = await $$('.videos .video-miniature .video-name').filter(async e => {
const t = await e.getText()
return t === videoName
})
return videos[0]
}
await browser.waitUntil(async () => {
const elem = await video()
return elem?.isClickable()
})
;(await video()).click()
await browser.waitUntil(async () => (await browser.getUrl()).includes('/w/'))
}
async clickOnFirstVideo () {
const video = () => $('.videos .video-miniature .video-thumbnail')
const videoName = () => $('.videos .video-miniature .video-name')
await video().waitForClickable()
const textToReturn = await videoName().getText()
await video().click()
await browser.waitUntil(async () => (await browser.getUrl()).includes('/w/'))
return textToReturn
}
private waitForList () {
return $('.videos .video-miniature .video-name').waitForDisplayed()
}
}

View File

@@ -0,0 +1,148 @@
import { clickOnRadio, getCheckbox, go, isRadioSelected, selectCustomSelect, setCheckboxEnabled } from '../utils'
export abstract class VideoManage {
async clickOnSave () {
const button = this.getSaveButton()
await button.waitForClickable()
await button.click()
await this.waitForSaved()
}
async clickOnWatch () {
// Simulate the click, because the button opens a new tab
const button = $('.watch-save > my-button[icon=external-link] a')
await button.waitForClickable()
await go(await button.getAttribute('href'))
}
// ---------------------------------------------------------------------------
async setAsNSFW (options: {
violent?: boolean
summary?: string
} = {}) {
await this.goOnPage('Moderation')
const checkbox = await getCheckbox('nsfw')
await checkbox.waitForClickable()
await checkbox.click()
if (options.violent) {
await setCheckboxEnabled('nsfwFlagViolent', true)
}
if (options.summary) {
await $('#nsfwSummary').setValue(options.summary)
}
}
// ---------------------------------------------------------------------------
async setAsPublic () {
await this.goOnPage('Main information')
return selectCustomSelect('privacy', 'Public')
}
async setAsPrivate () {
await this.goOnPage('Main information')
return selectCustomSelect('privacy', 'Private')
}
async setAsPasswordProtected (videoPassword: string) {
await this.goOnPage('Main information')
selectCustomSelect('privacy', 'Password protected')
const videoPasswordInput = $('input#videoPassword')
await videoPasswordInput.waitForClickable()
await videoPasswordInput.clearValue()
return videoPasswordInput.setValue(videoPassword)
}
// ---------------------------------------------------------------------------
async scheduleUpload () {
await this.goOnPage('Main information')
selectCustomSelect('privacy', 'Scheduled')
const input = this.getScheduleInput()
await input.waitForClickable()
await input.click()
const nextMonth = $('.p-datepicker-next-button')
await nextMonth.click()
await $('.p-datepicker-calendar td[aria-label="1"] > span').click()
await $('.p-datepicker-calendar').waitForDisplayed({ reverse: true, timeout: 15000 }) // Can be slow
}
getScheduleInput () {
return $('#schedulePublicationAt input')
}
// ---------------------------------------------------------------------------
async setNormalLive () {
await this.goOnPage('Live settings')
await clickOnRadio('permanentLiveFalse')
}
async setPermanentLive () {
await this.goOnPage('Live settings')
await clickOnRadio('permanentLiveTrue')
}
async getLiveState () {
await this.goOnPage('Live settings')
if (await isRadioSelected('permanentLiveTrue')) return 'permanent'
return 'normal'
}
// ---------------------------------------------------------------------------
async refresh (videoName: string) {
await browser.refresh()
await browser.waitUntil(async () => {
const url = await browser.getUrl()
return url.includes('/videos/manage')
})
await browser.waitUntil(async () => {
return await $('#name').getValue() === videoName
})
}
// ---------------------------------------------------------------------------
protected getSaveButton () {
return $('.save-button > button:not([disabled])')
}
protected waitForSaved () {
return $('.save-button > button[disabled], my-manage-errors').waitForDisplayed()
}
protected async goOnPage (page: 'Main information' | 'Moderation' | 'Live settings') {
const urls = {
'Main information': '',
'Moderation': 'moderation',
'Live settings': 'live'
}
const el = $(`my-video-manage-container .menu a[href*="/${urls[page]}"]`)
await el.waitForClickable()
await el.click()
}
}

View File

@@ -0,0 +1,80 @@
import { join } from 'node:path'
import { VideoManage } from './video-manage'
import { FIXTURE_URLS } from '../utils'
export class VideoPublishPage extends VideoManage {
async navigateTo (tab?: 'Go live') {
const publishButton = $('.publish-button > a')
await publishButton.waitForClickable()
await publishButton.click()
await $('.upload-video-container').waitForDisplayed()
if (tab) {
const el = $(`.nav-link*=${tab}`)
await el.waitForClickable()
await el.click()
}
}
// ---------------------------------------------------------------------------
async uploadVideo (fixtureName: 'video.mp4' | 'video2.mp4' | 'video3.mp4') {
const fileToUpload = join(__dirname, '../../fixtures/' + fixtureName)
const fileInputSelector = '.upload-video-container input[type=file]'
const parentFileInput = '.upload-video-container .button-file'
// Avoid sending keys on non visible element
await browser.execute(`document.querySelector('${fileInputSelector}').style.opacity = 1`)
await browser.execute(`document.querySelector('${parentFileInput}').style.overflow = 'initial'`)
await browser.pause(1000)
const elem = $(fileInputSelector)
await elem.chooseFile(fileToUpload)
// Wait for the upload to finish
await this.getSaveButton().waitForClickable()
}
async importVideo () {
const tab = $('.nav-link*=Import with URL')
await tab.waitForClickable()
await tab.click()
const input = $('#targetUrl')
await input.waitForDisplayed()
await input.setValue(FIXTURE_URLS.IMPORT_URL)
const submit = $('.first-step-block .primary-button:not([disabled])')
await submit.waitForClickable()
await submit.click()
// Wait for the import to finish
await this.getSaveButton().waitForClickable({ timeout: 15000 }) // Can be slow
}
async publishLive () {
await $('#permanentLiveTrue').parentElement().click()
const submit = $('.upload-video-container .primary-button:not([disabled])')
await submit.waitForClickable()
await submit.click()
await this.getSaveButton().waitForClickable()
}
// ---------------------------------------------------------------------------
async validSecondStep (videoName: string) {
await this.goOnPage('Main information')
const nameInput = $('input#name')
await nameInput.scrollIntoView()
await nameInput.clearValue()
await nameInput.setValue(videoName)
await this.clickOnSave()
}
}

View File

@@ -0,0 +1,11 @@
export class VideoSearchPage {
async search (search: string) {
await $('#search-video').setValue(search)
await $('.search-button').click()
await browser.waitUntil(() => {
return $('my-video-miniature').isDisplayed()
})
}
}

View File

@@ -0,0 +1,11 @@
import { VideoManage } from './video-manage'
export class VideoUpdatePage extends VideoManage {
async updateName (videoName: string) {
const nameInput = $('input#name')
await nameInput.waitForDisplayed()
await nameInput.clearValue()
await nameInput.setValue(videoName)
}
}

View File

@@ -0,0 +1,229 @@
import { browserSleep, FIXTURE_URLS, go } from '../utils'
export class VideoWatchPage {
constructor (private isMobileDevice: boolean, private isSafari: boolean) {
}
waitWatchVideoName (videoName: string, maxTime?: number) {
if (this.isSafari) return browserSleep(5000)
// On mobile we display the first node, on desktop the second one
return browser.waitUntil(async () => {
return (await this.getVideoName()) === videoName
}, { timeout: maxTime })
}
getVideoName () {
return this.getVideoNameElement().then(e => e.getText())
}
getPrivacy () {
return $('.attribute-privacy .attribute-value').getText()
}
getLicence () {
return $('.attribute-licence .attribute-value').getText()
}
async isDownloadEnabled () {
try {
await this.clickOnMoreDropdownIcon()
return await $('.dropdown-item .icon-download').isExisting()
} catch {
return $('.action-button-download').isDisplayed()
}
}
areCommentsEnabled () {
return $('my-video-comment-add').isExisting()
}
isPrivacyWarningDisplayed () {
return $('.privacy-concerns-text').isDisplayed()
}
async goOnAssociatedEmbed (passwordProtected = false) {
let url = await browser.getUrl()
url = url.replace('/w/', '/videos/embed/')
url = url.replace(':3333', ':9001')
await go(url)
if (passwordProtected) await this.waitEmbedForVideoPasswordForm()
else await this.waitEmbedForDisplayed()
}
waitEmbedForDisplayed () {
return $('.vjs-big-play-button').waitForDisplayed()
}
waitEmbedForVideoPasswordForm () {
return $('#video-password-input').waitForDisplayed()
}
isEmbedWarningDisplayed () {
return $('.peertube-dock-description').isDisplayed()
}
goOnP2PMediaLoaderEmbed () {
return go(FIXTURE_URLS.HLS_EMBED)
}
goOnP2PMediaLoaderPlaylistEmbed () {
return go(FIXTURE_URLS.HLS_PLAYLIST_EMBED)
}
getModalTitleEl () {
return $('.modal-content .modal-title')
}
confirmModal () {
return $('.modal-content .modal-footer .primary-button').click()
}
private getVideoNameElement () {
return $('.video-info-first-row .video-info-name')
}
// ---------------------------------------------------------------------------
// Video password
// ---------------------------------------------------------------------------
async fillVideoPassword (videoPassword: string) {
const videoPasswordInput = $('input#confirmInput')
await videoPasswordInput.waitForClickable()
await videoPasswordInput.clearValue()
await videoPasswordInput.setValue(videoPassword)
const confirmButton = $('input[value="Confirm"]')
await confirmButton.waitForClickable()
return confirmButton.click()
}
// ---------------------------------------------------------------------------
// Video actions
// ---------------------------------------------------------------------------
async like () {
const likeButton = $('.action-button-like')
const isActivated = (await likeButton.getAttribute('class')).includes('activated')
let count: number
try {
count = parseInt(await $('.action-button-like > .count').getText())
} catch (error) {
count = 0
}
await likeButton.waitForClickable()
await likeButton.click()
if (isActivated) {
if (count === 1) {
return expect(!await $('.action-button-like > .count').isExisting())
} else {
return expect(parseInt(await $('.action-button-like > .count').getText())).toBe(count - 1)
}
} else {
return expect(parseInt(await $('.action-button-like > .count').getText())).toBe(count + 1)
}
}
async clickOnManage () {
await this.clickOnMoreDropdownIcon()
// We need the await expression
return $$('.dropdown-menu.show .dropdown-item').forEach(async item => {
const content = await item.getText()
if (content.includes('Manage')) {
await item.click()
await $('#name').waitForClickable()
return
}
})
}
async clickOnMoreDropdownIcon () {
const dropdown = $('my-video-actions-dropdown .action-button')
await dropdown.scrollIntoView({ block: 'center' })
await dropdown.click()
await $('.dropdown-menu.show .dropdown-item').waitForDisplayed()
}
// ---------------------------------------------------------------------------
// Playlists
// ---------------------------------------------------------------------------
async clickOnSave () {
const button = $('.action-button-save')
await button.scrollIntoView({ block: 'center' })
return button.click()
}
async createPlaylist (name: string) {
const newPlaylistButton = () => $('.new-playlist-button')
await newPlaylistButton().waitForClickable()
await newPlaylistButton().click()
const displayName = () => $('#displayName')
await displayName().waitForDisplayed()
await displayName().setValue(name)
return $('.new-playlist-block input[type=submit]').click()
}
async saveToPlaylist (name: string) {
const playlist = () => $('my-video-add-to-playlist').$(`.playlist=${name}`)
await playlist().waitForDisplayed()
return playlist().click()
}
// ---------------------------------------------------------------------------
// Comments
// ---------------------------------------------------------------------------
async createThread (comment: string) {
const textarea = $('my-video-comment-add textarea')
await textarea.waitForClickable()
await textarea.setValue(comment)
const confirmButton = $('.comment-buttons .primary-button')
await confirmButton.waitForClickable()
await confirmButton.click()
const createdComment = await $('.comment-html p').getText()
return expect(createdComment).toBe(comment)
}
async createReply (comment: string) {
const replyButton = $('button.comment-action-reply')
await replyButton.waitForClickable()
await replyButton.scrollIntoView({ block: 'center' })
await replyButton.click()
const textarea = $('my-video-comment my-video-comment-add textarea')
await textarea.waitForClickable()
await textarea.setValue(comment)
const confirmButton = $('my-video-comment .comment-buttons .primary-button')
await confirmButton.waitForClickable()
await replyButton.scrollIntoView({ block: 'center' })
await confirmButton.click()
const createdComment = $('.is-child .comment-html p')
await createdComment.waitForDisplayed()
return expect(await createdComment.getText()).toBe(comment)
}
}

View File

@@ -0,0 +1,33 @@
import { PlayerPage } from '../po/player.po'
import { VideoWatchPage } from '../po/video-watch.po'
import { FIXTURE_URLS, go, isMobileDevice, isSafari, prepareWebBrowser } from '../utils'
describe('Live all workflow', () => {
let videoWatchPage: VideoWatchPage
let playerPage: PlayerPage
beforeEach(async () => {
videoWatchPage = new VideoWatchPage(isMobileDevice(), isSafari())
playerPage = new PlayerPage()
await prepareWebBrowser()
})
it('Should go to the live page', async () => {
await go(FIXTURE_URLS.LIVE_VIDEO)
return videoWatchPage.waitWatchVideoName('E2E - Live')
})
it('Should play the live', async () => {
await playerPage.playAndPauseVideo(false, 45)
expect(await playerPage.getWatchVideoPlayerCurrentTime()).toBeGreaterThanOrEqual(45)
})
it('Should watch the associated live embed', async () => {
await videoWatchPage.goOnAssociatedEmbed()
await playerPage.playAndPauseVideo(false, 45)
expect(await playerPage.getWatchVideoPlayerCurrentTime()).toBeGreaterThanOrEqual(45)
})
})

View File

@@ -0,0 +1,73 @@
import { LoginPage } from '../po/login.po'
import { PlayerPage } from '../po/player.po'
import { VideoWatchPage } from '../po/video-watch.po'
import { FIXTURE_URLS, go, isMobileDevice, isSafari, prepareWebBrowser } from '../utils'
async function checkCorrectlyPlay (playerPage: PlayerPage) {
await playerPage.playAndPauseVideo(false, 2)
expect(await playerPage.getWatchVideoPlayerCurrentTime()).toBeGreaterThanOrEqual(2)
}
describe('Private videos all workflow', () => {
let videoWatchPage: VideoWatchPage
let loginPage: LoginPage
let playerPage: PlayerPage
const internalVideoName = 'Internal E2E test'
const internalHLSOnlyVideoName = 'Internal E2E test - HLS only'
beforeEach(async () => {
videoWatchPage = new VideoWatchPage(isMobileDevice(), isSafari())
loginPage = new LoginPage(isMobileDevice())
playerPage = new PlayerPage()
await prepareWebBrowser()
})
it('Should log in', async () => {
return loginPage.loginOnPeerTube2()
})
it('Should play an internal web video', async () => {
await go(FIXTURE_URLS.INTERNAL_WEB_VIDEO)
await videoWatchPage.waitWatchVideoName(internalVideoName)
await checkCorrectlyPlay(playerPage)
})
it('Should play an internal HLS video', async () => {
await go(FIXTURE_URLS.INTERNAL_HLS_VIDEO)
await videoWatchPage.waitWatchVideoName(internalVideoName)
await checkCorrectlyPlay(playerPage)
})
it('Should play an internal HLS only video', async () => {
await go(FIXTURE_URLS.INTERNAL_HLS_ONLY_VIDEO)
await videoWatchPage.waitWatchVideoName(internalHLSOnlyVideoName)
await checkCorrectlyPlay(playerPage)
})
it('Should play an internal Web Video in embed', async () => {
await go(FIXTURE_URLS.INTERNAL_EMBED_WEB_VIDEO)
await videoWatchPage.waitEmbedForDisplayed()
await checkCorrectlyPlay(playerPage)
})
it('Should play an internal HLS video in embed', async () => {
await go(FIXTURE_URLS.INTERNAL_EMBED_HLS_VIDEO)
await videoWatchPage.waitEmbedForDisplayed()
await checkCorrectlyPlay(playerPage)
})
it('Should play an internal HLS only video in embed', async () => {
await go(FIXTURE_URLS.INTERNAL_EMBED_HLS_ONLY_VIDEO)
await videoWatchPage.waitEmbedForDisplayed()
await checkCorrectlyPlay(playerPage)
})
})

View File

@@ -0,0 +1,233 @@
import { LoginPage } from '../po/login.po'
import { MyAccountPage } from '../po/my-account.po'
import { PlayerPage } from '../po/player.po'
import { VideoListPage } from '../po/video-list.po'
import { VideoPublishPage } from '../po/video-publish.po'
import { VideoUpdatePage } from '../po/video-update.po'
import { VideoWatchPage } from '../po/video-watch.po'
import { FIXTURE_URLS, go, isIOS, isMobileDevice, isSafari, prepareWebBrowser, waitServerUp } from '../utils'
function isUploadUnsupported () {
if (isMobileDevice() || isSafari()) {
console.log('Skipping because we are on a real device or Safari and BrowserStack does not support file upload.')
return true
}
return false
}
describe('Videos all workflow', () => {
let videoWatchPage: VideoWatchPage
let videoListPage: VideoListPage
let videoPublishPage: VideoPublishPage
let videoUpdatePage: VideoUpdatePage
let myAccountPage: MyAccountPage
let loginPage: LoginPage
let playerPage: PlayerPage
let videoName = Math.random() + ' video'
const video2Name = Math.random() + ' second video'
const playlistName = Math.random() + ' playlist'
let videoWatchUrl: string
before(async () => {
if (isIOS()) {
console.log('iOS detected')
} else if (isMobileDevice()) {
console.log('Android detected.')
} else if (isSafari()) {
console.log('Safari detected.')
}
if (isUploadUnsupported()) return
await waitServerUp()
})
beforeEach(async () => {
videoWatchPage = new VideoWatchPage(isMobileDevice(), isSafari())
videoPublishPage = new VideoPublishPage()
videoUpdatePage = new VideoUpdatePage()
myAccountPage = new MyAccountPage()
loginPage = new LoginPage(isMobileDevice())
playerPage = new PlayerPage()
videoListPage = new VideoListPage(isMobileDevice(), isSafari())
await prepareWebBrowser()
})
it('Should log in', async () => {
if (isMobileDevice() || isSafari()) {
console.log('Skipping because we are on a real device or Safari and BrowserStack does not support file upload.')
return
}
return loginPage.loginAsRootUser()
})
it('Should upload a video', async () => {
if (isUploadUnsupported()) return
await videoPublishPage.navigateTo()
await videoPublishPage.uploadVideo('video.mp4')
await videoPublishPage.validSecondStep(videoName)
})
it('Should list videos', async () => {
await videoListPage.goOnVideosList()
if (isUploadUnsupported()) return
const videoNames = await videoListPage.getVideosListName()
expect(videoNames).toContain(videoName)
})
it('Should go on video watch page', async () => {
let videoNameToExcept = videoName
if (isMobileDevice() || isSafari()) {
await go(FIXTURE_URLS.WEB_VIDEO)
videoNameToExcept = 'E2E tests'
} else {
await videoListPage.clickOnVideo(videoName)
}
return videoWatchPage.waitWatchVideoName(videoNameToExcept)
})
it('Should play the video', async () => {
videoWatchUrl = await browser.getUrl()
await playerPage.playAndPauseVideo(true, 2)
expect(await playerPage.getWatchVideoPlayerCurrentTime()).toBeGreaterThanOrEqual(2)
})
it('Should watch the associated embed video', async () => {
await videoWatchPage.goOnAssociatedEmbed()
await playerPage.playAndPauseVideo(false, 2)
expect(await playerPage.getWatchVideoPlayerCurrentTime()).toBeGreaterThanOrEqual(2)
})
it('Should watch the p2p media loader embed video', async () => {
await videoWatchPage.goOnP2PMediaLoaderEmbed()
await playerPage.playAndPauseVideo(false, 2)
expect(await playerPage.getWatchVideoPlayerCurrentTime()).toBeGreaterThanOrEqual(2)
})
it('Should update the video', async () => {
if (isUploadUnsupported()) return
await go(videoWatchUrl)
await videoWatchPage.clickOnManage()
videoName += ' updated'
await videoUpdatePage.updateName(videoName)
await videoUpdatePage.clickOnSave()
await videoUpdatePage.clickOnWatch()
const name = await videoWatchPage.getVideoName()
expect(name).toEqual(videoName)
})
it('Should add the video in my playlist', async () => {
if (isUploadUnsupported()) return
await videoWatchPage.clickOnSave()
await videoWatchPage.createPlaylist(playlistName)
await videoWatchPage.saveToPlaylist(playlistName)
await browser.pause(5000)
await videoPublishPage.navigateTo()
await videoPublishPage.uploadVideo('video2.mp4')
await videoPublishPage.validSecondStep(video2Name)
await videoPublishPage.clickOnWatch()
await videoWatchPage.clickOnSave()
await videoWatchPage.saveToPlaylist(playlistName)
})
it('Should have the playlist in my account', async () => {
if (isUploadUnsupported()) return
await myAccountPage.navigateToMyPlaylists()
const videosNumberText = await myAccountPage.getPlaylistVideosText(playlistName)
expect(videosNumberText).toEqual('2 videos')
await myAccountPage.clickOnPlaylist(playlistName)
const count = await myAccountPage.countTotalPlaylistElements()
expect(count).toEqual(2)
})
it('Should watch the playlist', async () => {
if (isUploadUnsupported()) return
await myAccountPage.playPlaylist()
await videoWatchPage.waitWatchVideoName(video2Name, 40 * 1000)
})
it('Should watch the Web Video playlist in the embed', async () => {
if (isUploadUnsupported()) return
const accessToken = await browser.execute(`return window.localStorage.getItem('access_token');`)
const refreshToken = await browser.execute(`return window.localStorage.getItem('refresh_token');`)
await myAccountPage.goOnAssociatedPlaylistEmbed()
await playerPage.waitUntilPlayerWrapper()
console.log('Will set %s and %s tokens in local storage.', accessToken, refreshToken)
await browser.execute(`window.localStorage.setItem('access_token', '${accessToken}');`)
await browser.execute(`window.localStorage.setItem('refresh_token', '${refreshToken}');`)
await browser.execute(`window.localStorage.setItem('token_type', 'Bearer');`)
await browser.refresh()
await playerPage.playVideo()
await playerPage.waitUntilPlaylistInfo('2/2', 30 * 1000)
})
it('Should watch the HLS playlist in the embed', async () => {
await videoWatchPage.goOnP2PMediaLoaderPlaylistEmbed()
await playerPage.playVideo()
await playerPage.waitUntilPlaylistInfo('2/2', 30 * 1000)
})
it('Should delete the video 2', async () => {
if (isUploadUnsupported()) return
// Go to the dev website
await go(videoWatchUrl)
await myAccountPage.navigateToMyVideos()
await myAccountPage.removeVideo(video2Name)
await myAccountPage.validRemove()
await browser.waitUntil(async () => {
const count = await myAccountPage.countVideos([ videoName, video2Name ])
return count === 1
})
})
it('Should delete the first video', async () => {
if (isUploadUnsupported()) return
await myAccountPage.removeVideo(videoName)
await myAccountPage.validRemove()
})
})

View File

@@ -0,0 +1,95 @@
import { LoginPage } from '../po/login.po'
import { VideoPublishPage } from '../po/video-publish.po'
import { VideoWatchPage } from '../po/video-watch.po'
import { go, isMobileDevice, isSafari, prepareWebBrowser, waitServerUp } from '../utils'
describe('Custom server defaults', () => {
let videoPublishPage: VideoPublishPage
let loginPage: LoginPage
let videoWatchPage: VideoWatchPage
before(async () => {
await waitServerUp()
loginPage = new LoginPage(isMobileDevice())
videoPublishPage = new VideoPublishPage()
videoWatchPage = new VideoWatchPage(isMobileDevice(), isSafari())
await prepareWebBrowser({ hidePrivacyConcerns: false })
})
describe('Publish default values', function () {
before(async function () {
await loginPage.loginAsRootUser()
})
it('Should upload a video with custom default values', async function () {
await videoPublishPage.navigateTo()
await videoPublishPage.uploadVideo('video.mp4')
await videoPublishPage.validSecondStep('video')
await videoPublishPage.clickOnWatch()
await videoWatchPage.waitWatchVideoName('video')
const videoUrl = await browser.getUrl()
expect(await videoWatchPage.getPrivacy()).toBe('Unlisted')
expect(await videoWatchPage.getLicence()).toBe('Attribution - Non Commercial')
expect(await videoWatchPage.areCommentsEnabled()).toBeFalsy()
// Owners can download their videos
expect(await videoWatchPage.isDownloadEnabled()).toBeTruthy()
// Logout to see if the download enabled is correct for anonymous users
await loginPage.logout()
await browser.url(videoUrl)
await videoWatchPage.waitWatchVideoName('video')
expect(await videoWatchPage.isDownloadEnabled()).toBeFalsy()
})
})
describe('P2P', function () {
let videoUrl: string
async function goOnVideoWatchPage () {
await go(videoUrl)
await videoWatchPage.waitWatchVideoName('video')
}
async function checkP2P (enabled: boolean) {
await goOnVideoWatchPage()
expect(await videoWatchPage.isPrivacyWarningDisplayed()).toEqual(enabled)
await videoWatchPage.goOnAssociatedEmbed()
expect(await videoWatchPage.isEmbedWarningDisplayed()).toEqual(enabled)
}
before(async () => {
await loginPage.loginAsRootUser()
await videoPublishPage.navigateTo()
await videoPublishPage.uploadVideo('video2.mp4')
await videoPublishPage.setAsPublic()
await videoPublishPage.validSecondStep('video')
await videoPublishPage.clickOnWatch()
await videoWatchPage.waitWatchVideoName('video')
videoUrl = await browser.getUrl()
})
beforeEach(async function () {
await goOnVideoWatchPage()
})
it('Should have P2P disabled for a logged in user', async function () {
await checkP2P(false)
})
it('Should have P2P disabled for anonymous users', async function () {
await loginPage.logout()
await checkP2P(false)
})
})
})

View File

@@ -0,0 +1,393 @@
import { NSFWPolicyType } from '@peertube/peertube-models'
import { AdminConfigPage } from '../po/admin-config.po'
import { AdminUserPage } from '../po/admin-user.po'
import { AnonymousSettingsPage } from '../po/anonymous-settings.po'
import { LoginPage } from '../po/login.po'
import { MyAccountPage } from '../po/my-account.po'
import { PlayerPage } from '../po/player.po'
import { VideoListPage } from '../po/video-list.po'
import { VideoPublishPage } from '../po/video-publish.po'
import { VideoSearchPage } from '../po/video-search.po'
import { VideoWatchPage } from '../po/video-watch.po'
import { getScreenshotPath, go, isMobileDevice, isSafari, prepareWebBrowser, waitServerUp } from '../utils'
describe('NSFW', () => {
let videoListPage: VideoListPage
let videoPublishPage: VideoPublishPage
let adminConfigPage: AdminConfigPage
let loginPage: LoginPage
let adminUserPage: AdminUserPage
let myAccountPage: MyAccountPage
let videoSearchPage: VideoSearchPage
let videoWatchPage: VideoWatchPage
let playerPage: PlayerPage
let anonymousSettingsPage: AnonymousSettingsPage
const seed = Math.random()
const nsfwVideo = seed + ' - nsfw'
const violentVideo = seed + ' - violent'
const normalVideo = seed + ' - normal'
let videoUrl: string
async function checkVideo (options: {
policy: NSFWPolicyType
videoName: string
nsfwTooltip?: string
}) {
const { policy, videoName, nsfwTooltip } = options
if (policy === 'do_not_list') {
expect(await videoListPage.isVideoDisplayed(videoName)).toBeFalsy()
} else if (policy === 'warn') {
expect(await videoListPage.isVideoDisplayed(videoName)).toBeTruthy()
expect(await videoListPage.isVideoBlurred(videoName)).toBeFalsy()
expect(await videoListPage.hasVideoWarning(videoName)).toBeTruthy()
} else if (policy === 'blur') {
expect(await videoListPage.isVideoDisplayed(videoName)).toBeTruthy()
expect(await videoListPage.isVideoBlurred(videoName)).toBeTruthy()
expect(await videoListPage.hasVideoWarning(videoName)).toBeTruthy()
} else { // Display
expect(await videoListPage.isVideoDisplayed(videoName)).toBeTruthy()
expect(await videoListPage.isVideoBlurred(videoName)).toBeFalsy()
expect(await videoListPage.hasVideoWarning(videoName)).toBeFalsy()
}
if (nsfwTooltip) {
await videoListPage.expectVideoNSFWTooltip(videoName, nsfwTooltip)
}
}
async function checkFilterText (policy: NSFWPolicyType) {
const pagesWithFilters = [
videoListPage.goOnRootAccount.bind(videoListPage),
videoListPage.goOnBrowseVideos.bind(videoListPage),
videoListPage.goOnRootChannel.bind(videoListPage)
]
for (const goOnPage of pagesWithFilters) {
await goOnPage()
const filterText = await videoListPage.getNSFWFilterText()
if (policy === 'do_not_list') {
expect(filterText).toContain('hidden')
} else if (policy === 'warn') {
expect(filterText).toContain('warned')
} else if (policy === 'blur') {
expect(filterText).toContain('blurred')
} else {
expect(filterText).toContain('displayed')
}
}
}
async function checkCommonVideoListPages (policy: NSFWPolicyType, videos: string[], nsfwTooltip?: string) {
const pages = [
videoListPage.goOnRootAccount.bind(videoListPage),
videoListPage.goOnBrowseVideos.bind(videoListPage),
videoListPage.goOnRootChannel.bind(videoListPage),
videoListPage.goOnRootAccountChannels.bind(videoListPage),
videoListPage.goOnHomepage.bind(videoListPage)
]
for (const goOnPage of pages) {
await goOnPage()
for (const video of videos) {
await browser.saveScreenshot(getScreenshotPath('before-nsfw-test.png'))
await checkVideo({ policy, videoName: video, nsfwTooltip })
}
}
for (const video of videos) {
await videoSearchPage.search(video)
await browser.saveScreenshot(getScreenshotPath('before-nsfw-test.png'))
await checkVideo({ policy, videoName: video, nsfwTooltip })
}
}
async function updateAdminNSFW (nsfw: NSFWPolicyType) {
await adminConfigPage.updateNSFWSetting(nsfw)
await adminConfigPage.save()
}
async function updateUserNSFW (nsfw: NSFWPolicyType, loggedIn: boolean) {
if (loggedIn) {
await myAccountPage.navigateToMySettings()
await myAccountPage.updateNSFW(nsfw)
return
}
await anonymousSettingsPage.openSettings()
await anonymousSettingsPage.updateNSFW(nsfw)
await anonymousSettingsPage.closeSettings()
}
async function updateUserViolentNSFW (nsfw: NSFWPolicyType, loggedIn: boolean) {
if (loggedIn) {
await myAccountPage.navigateToMySettings()
await myAccountPage.updateViolentFlag(nsfw)
return
}
await anonymousSettingsPage.openSettings()
await anonymousSettingsPage.updateViolentFlag(nsfw)
await anonymousSettingsPage.closeSettings()
}
before(async () => {
await waitServerUp()
})
beforeEach(async () => {
videoListPage = new VideoListPage(isMobileDevice(), isSafari())
adminConfigPage = new AdminConfigPage()
loginPage = new LoginPage(isMobileDevice())
adminUserPage = new AdminUserPage()
videoPublishPage = new VideoPublishPage()
myAccountPage = new MyAccountPage()
videoSearchPage = new VideoSearchPage()
playerPage = new PlayerPage()
videoWatchPage = new VideoWatchPage(isMobileDevice(), isSafari())
anonymousSettingsPage = new AnonymousSettingsPage()
await prepareWebBrowser()
})
describe('Preparation', function () {
it('Should login and disable NSFW', async () => {
await loginPage.loginAsRootUser()
await updateUserNSFW('display', true)
})
it('Should set the homepage', async () => {
await adminConfigPage.updateHomepage('<peertube-videos-list data-sort="-publishedAt"></peertube-videos-list>')
await adminConfigPage.save()
})
it('Should create a user', async () => {
await adminUserPage.createUser({
username: 'user_' + seed,
password: 'superpassword'
})
})
it('Should upload NSFW and normal videos', async () => {
await videoPublishPage.navigateTo()
await videoPublishPage.uploadVideo('video.mp4')
await videoPublishPage.setAsNSFW()
await videoPublishPage.validSecondStep(nsfwVideo)
await videoPublishPage.navigateTo()
await videoPublishPage.uploadVideo('video.mp4')
await videoPublishPage.setAsNSFW({ summary: 'bibi is violent', violent: true })
await videoPublishPage.validSecondStep(violentVideo)
await videoPublishPage.navigateTo()
await videoPublishPage.uploadVideo('video2.mp4')
await videoPublishPage.validSecondStep(normalVideo)
})
it('Should logout', async function () {
await loginPage.logout()
})
})
describe('NSFW with an anonymous users using instance default', function () {
it('Should correctly handle do not list', async () => {
await loginPage.loginAsRootUser()
await updateAdminNSFW('do_not_list')
await loginPage.logout()
await checkCommonVideoListPages('do_not_list', [ nsfwVideo, violentVideo ])
await checkCommonVideoListPages('display', [ normalVideo ])
await checkFilterText('do_not_list')
})
it('Should correctly handle blur', async () => {
await loginPage.loginAsRootUser()
await updateAdminNSFW('blur')
await loginPage.logout()
await checkCommonVideoListPages('blur', [ nsfwVideo, violentVideo ])
await checkCommonVideoListPages('display', [ normalVideo ])
await checkFilterText('blur')
})
it('Should not autoplay the video and display a warning on watch/embed page', async function () {
await videoListPage.clickOnVideo(nsfwVideo)
await videoWatchPage.waitWatchVideoName(nsfwVideo)
videoUrl = await browser.getUrl()
const check = async () => {
expect(await playerPage.getPlayButton().isDisplayed()).toBeTruthy()
expect(await playerPage.getNSFWContentText()).toContain('This video contains sensitive content')
expect(await playerPage.getMoreNSFWInfoButton().isDisplayed()).toBeFalsy()
expect(await playerPage.hasPoster()).toBeFalsy()
}
await check()
await videoWatchPage.goOnAssociatedEmbed()
await check()
})
it('Should correctly handle warn', async () => {
await loginPage.loginAsRootUser()
await updateAdminNSFW('warn')
await loginPage.logout()
await checkCommonVideoListPages('warn', [ nsfwVideo, violentVideo ])
await checkCommonVideoListPages('display', [ normalVideo ])
await checkFilterText('warn')
})
it('Should not autoplay the video and display a warning on watch/embed page', async function () {
await videoListPage.clickOnVideo(violentVideo)
await videoWatchPage.waitWatchVideoName(violentVideo)
const check = async () => {
expect(await playerPage.getPlayButton().isDisplayed()).toBeTruthy()
expect(await playerPage.getNSFWContentText()).toContain('This video contains sensitive content')
expect(await playerPage.hasPoster()).toBeTruthy()
const moreButton = playerPage.getMoreNSFWInfoButton()
expect(await moreButton.isDisplayed()).toBeTruthy()
await moreButton.click()
await playerPage.getNSFWDetailsContent().waitForDisplayed()
const moreContent = await playerPage.getNSFWDetailsContent().getText()
expect(moreContent).toContain('Potentially violent content')
expect(moreContent).toContain('bibi is violent')
}
await check()
await videoWatchPage.goOnAssociatedEmbed()
await check()
})
it('Should correctly handle display', async () => {
await loginPage.loginAsRootUser()
await updateAdminNSFW('display')
await loginPage.logout()
await checkCommonVideoListPages('display', [ nsfwVideo, violentVideo, normalVideo ])
await checkFilterText('display')
})
it('Should autoplay the video on watch page', async function () {
await videoListPage.clickOnVideo(nsfwVideo)
await videoWatchPage.waitWatchVideoName(nsfwVideo)
expect(await playerPage.getPlayButton().isDisplayed()).toBeFalsy()
})
})
describe('NSFW settings', function () {
function runSuite (loggedIn: boolean) {
it('Should correctly handle do not list', async () => {
await updateUserNSFW('do_not_list', loggedIn)
await checkCommonVideoListPages('do_not_list', [ nsfwVideo, violentVideo ])
await checkCommonVideoListPages('display', [ normalVideo ])
await checkFilterText('do_not_list')
})
it('Should use a confirm modal when viewing the video and watch the video', async function () {
await go(videoUrl)
const confirmTitle = videoWatchPage.getModalTitleEl()
await confirmTitle.waitForDisplayed()
expect(await confirmTitle.getText()).toContain('Sensitive video')
await videoWatchPage.confirmModal()
await videoWatchPage.waitWatchVideoName(nsfwVideo)
})
it('Should correctly handle blur', async () => {
await updateUserNSFW('blur', loggedIn)
await checkCommonVideoListPages('blur', [ nsfwVideo ], 'This video contains sensitive content')
await checkCommonVideoListPages('blur', [ violentVideo ], 'This video contains sensitive content: violence')
await checkCommonVideoListPages('display', [ normalVideo ])
await checkFilterText('blur')
})
it('Should correctly handle warn', async () => {
await updateUserNSFW('warn', loggedIn)
await checkCommonVideoListPages('warn', [ nsfwVideo ], 'This video contains sensitive content')
await checkCommonVideoListPages('warn', [ violentVideo ], 'This video contains sensitive content: violence')
await checkCommonVideoListPages('display', [ normalVideo ])
await checkFilterText('warn')
})
it('Should correctly handle display', async () => {
await updateUserNSFW('display', loggedIn)
await checkCommonVideoListPages('display', [ nsfwVideo, violentVideo, normalVideo ])
await checkFilterText('display')
})
it('Should update the setting to blur violent video with display NSFW setting', async () => {
await updateUserViolentNSFW('blur', loggedIn)
await checkCommonVideoListPages('display', [ nsfwVideo, normalVideo ])
await checkCommonVideoListPages('blur', [ violentVideo ])
})
it('Should update the setting to hide NSFW videos but warn violent videos', async () => {
await updateUserNSFW('do_not_list', loggedIn)
await updateUserViolentNSFW('warn', loggedIn)
await checkCommonVideoListPages('display', [ normalVideo ])
await checkCommonVideoListPages('warn', [ violentVideo ])
await checkCommonVideoListPages('do_not_list', [ nsfwVideo ])
})
it('Should update the setting to blur NSFW videos and hide violent videos', async () => {
await updateUserNSFW('blur', loggedIn)
await updateUserViolentNSFW('do_not_list', loggedIn)
await checkCommonVideoListPages('display', [ normalVideo ])
await checkCommonVideoListPages('do_not_list', [ violentVideo ])
await checkCommonVideoListPages('blur', [ nsfwVideo ])
})
}
describe('NSFW with an anonymous user', function () {
runSuite(false)
})
describe('NSFW with a logged in users', function () {
before(async () => {
await loginPage.login({ username: 'user_' + seed, password: 'superpassword' })
})
runSuite(true)
after(async () => {
await loginPage.logout()
})
})
})
})

View File

@@ -0,0 +1,141 @@
import { AdminConfigPage } from '../po/admin-config.po'
import { LoginPage } from '../po/login.po'
import { VideoPublishPage } from '../po/video-publish.po'
import { VideoWatchPage } from '../po/video-watch.po'
import { getScreenshotPath, go, isMobileDevice, isSafari, prepareWebBrowser, selectCustomSelect, waitServerUp } from '../utils'
// These tests help to notice crash with invalid translated strings
describe('Page crash', () => {
let videoPublishPage: VideoPublishPage
let loginPage: LoginPage
let videoWatchPage: VideoWatchPage
let adminConfigPage: AdminConfigPage
const languages = [
'العربية',
'Català',
'Čeština',
'Deutsch',
'ελληνικά',
'Esperanto',
'Español',
'Euskara',
'فارسی',
'Suomi',
'Français',
'Gàidhlig',
'Galego',
'Hrvatski',
'Magyar',
'Íslenska',
'Italiano',
'日本語',
'Taqbaylit',
'Norsk bokmål',
'Nederlands',
'Norsk nynorsk',
'Occitan',
'Polski',
'Português (Brasil)',
'Português (Portugal)',
'Pусский',
'Slovenčina',
'Shqip',
'Svenska',
'ไทย',
'Toki Pona',
'Türkçe',
'украї́нська мо́ва',
'Tiếng Việt',
'简体中文(中国)',
'繁體中文(台灣)'
]
before(async () => {
await waitServerUp()
adminConfigPage = new AdminConfigPage()
loginPage = new LoginPage(isMobileDevice())
videoPublishPage = new VideoPublishPage()
videoWatchPage = new VideoWatchPage(isMobileDevice(), isSafari())
await prepareWebBrowser()
})
for (const language of languages) {
describe('For language: ' + language, () => {
describe('Logged in user', () => {
before(async () => {
await loginPage.loginAsRootUser()
})
it('Should change the language', async function () {
await go('/')
await $('.settings-button').waitForClickable()
await $('.settings-button').click()
await selectCustomSelect('language', language)
await $('my-user-interface-settings .primary-button').waitForClickable()
await $('my-user-interface-settings .primary-button').click()
})
it('Should upload and watch a video', async function () {
await videoPublishPage.navigateTo()
await videoPublishPage.uploadVideo('video3.mp4')
await videoPublishPage.validSecondStep('video')
await videoPublishPage.clickOnWatch()
await videoWatchPage.waitWatchVideoName('video')
})
it('Should set a homepage', async function () {
await adminConfigPage.updateHomepage('My custom homepage content')
await adminConfigPage.save()
// All tests
await go('/home')
await $('*=My custom homepage content').waitForDisplayed()
})
it('Should go on overview page and not crash', async function () {
await $('a[href="/videos/overview"]').waitForClickable()
await $('a[href="/videos/overview"]').click()
await $('my-video-overview').waitForExist()
})
it('Should go on videos from subscriptions page', async function () {
await $('a[href="/videos/subscriptions"]').waitForClickable()
await $('a[href="/videos/subscriptions"]').click()
await $('my-videos-user-subscriptions').waitForExist()
})
})
describe('Anonymous user', () => {
before(async () => {
await adminConfigPage.toggleSignup(true)
await adminConfigPage.save()
await loginPage.logout()
await browser.refresh()
})
it('Should go on signup page', async function () {
await $('.create-account-button').waitForClickable()
await $('.create-account-button').click()
await $('.callout-content > h4').waitForExist()
})
})
after(async () => {
await browser.saveScreenshot(getScreenshotPath(`after-page-crash-test-${language}.png`))
})
})
}
})

View File

@@ -0,0 +1,83 @@
import { AnonymousSettingsPage } from '../po/anonymous-settings.po'
import { LoginPage } from '../po/login.po'
import { MyAccountPage } from '../po/my-account.po'
import { VideoPublishPage } from '../po/video-publish.po'
import { VideoWatchPage } from '../po/video-watch.po'
import { go, isMobileDevice, isSafari, prepareWebBrowser, waitServerUp } from '../utils'
describe('Player settings', () => {
let videoPublishPage: VideoPublishPage
let loginPage: LoginPage
let videoWatchPage: VideoWatchPage
let myAccountPage: MyAccountPage
let anonymousSettingsPage: AnonymousSettingsPage
before(async () => {
await waitServerUp()
loginPage = new LoginPage(isMobileDevice())
videoPublishPage = new VideoPublishPage()
videoWatchPage = new VideoWatchPage(isMobileDevice(), isSafari())
myAccountPage = new MyAccountPage()
anonymousSettingsPage = new AnonymousSettingsPage()
await prepareWebBrowser({ hidePrivacyConcerns: false })
})
describe('P2P', function () {
let videoUrl: string
async function goOnVideoWatchPage () {
await go(videoUrl)
await videoWatchPage.waitWatchVideoName('video')
}
async function checkP2P (enabled: boolean) {
await goOnVideoWatchPage()
expect(await videoWatchPage.isPrivacyWarningDisplayed()).toEqual(enabled)
await videoWatchPage.goOnAssociatedEmbed()
expect(await videoWatchPage.isEmbedWarningDisplayed()).toEqual(enabled)
}
before(async () => {
await loginPage.loginAsRootUser()
await videoPublishPage.navigateTo()
await videoPublishPage.uploadVideo('video.mp4')
await videoPublishPage.validSecondStep('video')
await videoPublishPage.clickOnWatch()
await videoWatchPage.waitWatchVideoName('video')
videoUrl = await browser.getUrl()
})
beforeEach(async function () {
await goOnVideoWatchPage()
})
it('Should have P2P enabled for a logged in user', async function () {
await checkP2P(true)
})
it('Should disable P2P for a logged in user', async function () {
await myAccountPage.navigateToMySettings()
await myAccountPage.clickOnP2PCheckbox()
await checkP2P(false)
})
it('Should have P2P enabled for anonymous users', async function () {
await loginPage.logout()
await checkP2P(true)
})
it('Should disable P2P for an anonymous user', async function () {
await anonymousSettingsPage.openSettings()
await anonymousSettingsPage.clickOnP2PCheckbox()
await checkP2P(false)
})
})
})

View File

@@ -0,0 +1,86 @@
import { AdminPluginPage } from '../po/admin-plugin.po'
import { LoginPage } from '../po/login.po'
import { VideoPublishPage } from '../po/video-publish.po'
import { getCheckbox, isMobileDevice, prepareWebBrowser, waitServerUp } from '../utils'
describe('Plugins', () => {
let videoPublishPage: VideoPublishPage
let loginPage: LoginPage
let adminPluginPage: AdminPluginPage
function getPluginCheckbox () {
return getCheckbox('hello-world-field-4')
}
async function expectSubmitError (hasError: boolean) {
await videoPublishPage.clickOnSave()
await $('.form-error*=Should be enabled').waitForDisplayed({ reverse: !hasError })
await $('li*=Should be enabled').waitForDisplayed({ reverse: !hasError })
}
before(async () => {
await waitServerUp()
})
beforeEach(async () => {
loginPage = new LoginPage(isMobileDevice())
videoPublishPage = new VideoPublishPage()
adminPluginPage = new AdminPluginPage()
await prepareWebBrowser()
})
it('Should install hello world plugin', async () => {
await loginPage.loginAsRootUser()
await adminPluginPage.navigateToPluginSearch()
await adminPluginPage.search('hello-world')
await adminPluginPage.installHelloWorld()
await browser.refresh()
})
it('Should have checkbox in video edit page', async () => {
await videoPublishPage.navigateTo()
await videoPublishPage.uploadVideo('video.mp4')
const el = () => $('span=Super field 4 in main tab')
await el().waitForDisplayed()
// Only displayed if the video is public
await videoPublishPage.setAsPrivate()
await el().waitForDisplayed({ reverse: true })
await videoPublishPage.setAsPublic()
await el().waitForDisplayed()
const checkbox = await getPluginCheckbox()
expect(await checkbox.isDisplayed()).toBeTruthy()
await expectSubmitError(true)
})
it('Should check the checkbox and be able to submit the video', async function () {
const checkbox = await getPluginCheckbox()
await checkbox.waitForClickable()
await checkbox.click()
await expectSubmitError(false)
})
it('Should uncheck the checkbox and not be able to submit the video', async function () {
const checkbox = await getPluginCheckbox()
await checkbox.waitForClickable()
await checkbox.click()
await expectSubmitError(true)
})
it('Should change the privacy and should hide the checkbox', async function () {
await videoPublishPage.setAsPrivate()
await expectSubmitError(false)
})
})

View File

@@ -0,0 +1,57 @@
import { AdminConfigPage } from '../po/admin-config.po'
import { LoginPage } from '../po/login.po'
import { VideoPublishPage } from '../po/video-publish.po'
import { VideoWatchPage } from '../po/video-watch.po'
import { isMobileDevice, isSafari, prepareWebBrowser, waitServerUp } from '../utils'
describe('Publish live', function () {
let videoPublishPage: VideoPublishPage
let loginPage: LoginPage
let adminConfigPage: AdminConfigPage
let videoWatchPage: VideoWatchPage
before(async () => {
await waitServerUp()
loginPage = new LoginPage(isMobileDevice())
videoPublishPage = new VideoPublishPage()
adminConfigPage = new AdminConfigPage()
videoWatchPage = new VideoWatchPage(isMobileDevice(), isSafari())
await prepareWebBrowser()
await loginPage.loginAsRootUser()
})
it('Should enable live', async function () {
await adminConfigPage.toggleLive(true)
await adminConfigPage.save()
})
it('Should create a classic permanent live', async function () {
await videoPublishPage.navigateTo('Go live')
await videoPublishPage.publishLive()
await videoPublishPage.validSecondStep('Permanent live test')
expect(await videoPublishPage.getLiveState()).toEqual('permanent')
await videoPublishPage.clickOnWatch()
await videoWatchPage.waitWatchVideoName('Permanent live test')
})
it('Should create a permanent live and update it to a normal live', async function () {
await videoPublishPage.navigateTo('Go live')
await videoPublishPage.publishLive()
await videoPublishPage.setNormalLive()
await videoPublishPage.validSecondStep('Normal live test')
await videoPublishPage.clickOnWatch()
await videoWatchPage.waitWatchVideoName('Normal live test')
await videoWatchPage.clickOnManage()
expect(await videoPublishPage.getLiveState()).toEqual('normal')
})
})

Some files were not shown because too many files have changed in this diff Show More