Compare commits
227
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc9c4a1120 | ||
|
|
2db6541c91 | ||
|
|
5d4bd8544d | ||
|
|
cc95fcacbf | ||
|
|
d7dd744c32 | ||
|
|
adfea01cdb | ||
|
|
81e7e3c9af | ||
|
|
53ad26fdbe | ||
|
|
db0e842ca7 | ||
|
|
2e67e590d6 | ||
|
|
bb342ead79 | ||
|
|
ce81bb5789 | ||
|
|
24c6ce4da0 | ||
|
|
c3ef8e91a6 | ||
|
|
b09e83db09 | ||
|
|
097e55df79 | ||
|
|
a1f4c24a43 | ||
|
|
7c7b2bf14c | ||
|
|
d52434fb2e | ||
|
|
356aa28fad | ||
|
|
1185d0ce61 | ||
|
|
90d481a2d1 | ||
|
|
50b8a8c8e2 | ||
|
|
79850dfc2c | ||
|
|
645807b853 | ||
|
|
b08049cf69 | ||
|
|
29c8afb94d | ||
|
|
e0e07e5316 | ||
|
|
42dadb993d | ||
|
|
05ef56c56d | ||
|
|
35dfa923e3 | ||
|
|
9d8b35c06c | ||
|
|
873e0ea55c | ||
|
|
4573edfedc | ||
|
|
b301868774 | ||
|
|
b87a0f7bc0 | ||
|
|
70fccc493e | ||
|
|
406a90ae5b | ||
|
|
8e7bbdf8b2 | ||
|
|
b84321346f | ||
|
|
8a07c5d569 | ||
|
|
cc96c0396a | ||
|
|
79c48b226e | ||
|
|
c9b75065bc | ||
|
|
4ca9f3af8b | ||
|
|
f02782d0f0 | ||
|
|
fb82b74e92 | ||
|
|
60dfe7a75b | ||
|
|
a07f231417 | ||
|
|
43d5003de8 | ||
|
|
eadfc29da3 | ||
|
|
50d3e2cf16 | ||
|
|
55e71ca838 | ||
|
|
5b723bf844 | ||
|
|
e502844b88 | ||
|
|
0702cb699c | ||
|
|
e09b3ffcf8 | ||
|
|
41d4235258 | ||
|
|
a51d5e8da5 | ||
|
|
5bcb4170c7 | ||
|
|
e436f5ece4 | ||
|
|
1e4e0560f1 | ||
|
|
841a6a15be | ||
|
|
dd94bf7e66 | ||
|
|
baa6283a15 | ||
|
|
bfb3115a64 | ||
|
|
db8b14ba4e | ||
|
|
46244fe066 | ||
|
|
3ed70b6999 | ||
|
|
b05b1acd7a | ||
|
|
c777853c97 | ||
|
|
9225318e1a | ||
|
|
061b7fad8b | ||
|
|
be7957c078 | ||
|
|
91667e1bfd | ||
|
|
f92ab3a813 | ||
|
|
1fecccaafd | ||
|
|
d100c8030f | ||
|
|
bc2257efd2 | ||
|
|
f1906517a9 | ||
|
|
00fde25c50 | ||
|
|
4c5af99efa | ||
|
|
8bf12e7721 | ||
|
|
5a0ca8ef1c | ||
|
|
714602f3da | ||
|
|
baac3a512b | ||
|
|
559284f0b2 | ||
|
|
e5fc925bae | ||
|
|
318a319608 | ||
|
|
0b55d5a8fa | ||
|
|
c3878cdc6d | ||
|
|
4af4fa68ac | ||
|
|
45bdda7c95 | ||
|
|
b926531447 | ||
|
|
da6fc1d523 | ||
|
|
1d1cbf9f3f | ||
|
|
dd9901519a | ||
|
|
53449c5d3c | ||
|
|
db908e3109 | ||
|
|
5857f60d79 | ||
|
|
83a804a709 | ||
|
|
b8694a6b7b | ||
|
|
5daada81b0 | ||
|
|
d85bab30d1 | ||
|
|
7b3256c8a0 | ||
|
|
9bc89fceba | ||
|
|
d5ec266437 | ||
|
|
a448ad59ee | ||
|
|
74a156cedc | ||
|
|
97d787f758 | ||
|
|
ea5da1eb86 | ||
|
|
ff4de33cc5 | ||
|
|
97af398654 | ||
|
|
0a9185347f | ||
|
|
5ff22c7586 | ||
|
|
adceb8f13f | ||
|
|
f2498a9761 | ||
|
|
b88f44ab1c | ||
|
|
fb7068f86c | ||
|
|
1d97271555 | ||
|
|
7d5d66840f | ||
|
|
e20c2ae619 | ||
|
|
793cfaaaf1 | ||
|
|
c92099a41b | ||
|
|
270bf680a4 | ||
|
|
731b43ea88 | ||
|
|
0f69ebcccb | ||
|
|
5c85eb3524 | ||
|
|
a303a94671 | ||
|
|
ed0f913138 | ||
|
|
d8af931bfb | ||
|
|
fbc9bb5858 | ||
|
|
827abf80cb | ||
|
|
594853ed04 | ||
|
|
80813b390b | ||
|
|
5de3a1a1cf | ||
|
|
585332e32e | ||
|
|
b798e0ea06 | ||
|
|
498f6069d0 | ||
|
|
a44d9fbadd | ||
|
|
13390d8a3c | ||
|
|
e1636139a9 | ||
|
|
949a0a01fb | ||
|
|
208664848e | ||
|
|
b802cf3309 | ||
|
|
dc309fbeb0 | ||
|
|
89854869c7 | ||
|
|
da75582dae | ||
|
|
52cfffb83f | ||
|
|
ce8939fffb | ||
|
|
2b7e8b9e36 | ||
|
|
34c97f4447 | ||
|
|
01b7a3c96b | ||
|
|
ad9d67ddb6 | ||
|
|
c0ede48091 | ||
|
|
e727069d43 | ||
|
|
53f9a6a884 | ||
|
|
0621efb839 | ||
|
|
214d276508 | ||
|
|
9177e9e5a2 | ||
|
|
4ed15bc235 | ||
|
|
74eee24293 | ||
|
|
ae36d17adb | ||
|
|
08e800120a | ||
|
|
f3ff657fc2 | ||
|
|
68b4390282 | ||
|
|
499aee8988 | ||
|
|
854738b46d | ||
|
|
1058c644bd | ||
|
|
3ef3c59d94 | ||
|
|
61bb22ce44 | ||
|
|
10fff7ffcb | ||
|
|
d835bce148 | ||
|
|
4c7be615f1 | ||
|
|
fde1213ca5 | ||
|
|
841e99c775 | ||
|
|
02ff1de0f6 | ||
|
|
8263475146 | ||
|
|
bac655aca8 | ||
|
|
d08cd36527 | ||
|
|
2c5f4f82eb | ||
|
|
2ccbfea75e | ||
|
|
1d67459bbe | ||
|
|
9fd4d865b3 | ||
|
|
70e704827e | ||
|
|
fd7a5c2c8e | ||
|
|
8139d84d88 | ||
|
|
ab9cb02083 | ||
|
|
fd225fbadd | ||
|
|
565bc2c548 | ||
|
|
1f273f849d | ||
|
|
a87cda156b | ||
|
|
1bd81d84af | ||
|
|
8882e7854f | ||
|
|
422d8848f6 | ||
|
|
787161807c | ||
|
|
1677df7f86 | ||
|
|
1fb5cd5aa2 | ||
|
|
6ac4db98bb | ||
|
|
92c0058085 | ||
|
|
9b40deeb61 | ||
|
|
82ff1972a0 | ||
|
|
566104aff4 | ||
|
|
2cb267f991 | ||
|
|
d051d60415 | ||
|
|
cd8e97243f | ||
|
|
71eaf9cf56 | ||
|
|
462f050977 | ||
|
|
d0552e1aaa | ||
|
|
994c1e3c09 | ||
|
|
1a84d6ae42 | ||
|
|
2b8f842752 | ||
|
|
964e3f472c | ||
|
|
b073ded6c1 | ||
|
|
ef805984ee | ||
|
|
15e57cddee | ||
|
|
cf06acf24d | ||
|
|
1901fcce68 | ||
|
|
62d86d16ec | ||
|
|
a5e781729c | ||
|
|
148402a97c | ||
|
|
f4b7be0f80 | ||
|
|
4083bc5dee | ||
|
|
471291b2c4 | ||
|
|
3a5649f482 | ||
|
|
3d3420cc4a | ||
|
|
bba6df52c0 |
@@ -0,0 +1,26 @@
|
||||
---
|
||||
description: Scalare soft limit ingest/autoscaler man mano che crescono i clienti
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# Soft limit stream / autoscaler
|
||||
|
||||
Con la crescita del numero di clienti (e delle dirette concorrenti attese), **alzare i soft limit** prima di restare a corto di capacità.
|
||||
|
||||
Config rilevante (prod, tipicamente `infra/.env` + `StreamNode`):
|
||||
|
||||
| Parametro | Ruolo (qualità-first 2026-09) |
|
||||
|-----------|-------------------------------|
|
||||
| `STREAM_NODE_HOME_MAX_PUBLISHERS` | Soft home (**4** — scale-out anticipato) |
|
||||
| `STREAM_CLOUD_MAX_PUBLISHERS` | Soft per CPX (**6**; 8 solo dopo misure QoS) |
|
||||
| `STREAM_AUTOSCALE_MAX_NODES` | Quanti CPX in parallelo (fase A **12** → B 22 → C 33) |
|
||||
| `STREAM_AUTOSCALE_SOFT_FREE_SLOTS` | Anticipo scale-out |
|
||||
| `STREAM_AUTOSCALE_MONTHLY_BUDGET_EUR` | Gate 24/7 (fase A **150**) |
|
||||
| `STREAM_AUTOSCALE_QUIET_HOURS` | `02:00-07:00` Europe/Rome: no scale-out/warm-spare; sweeper chiude CPX idle |
|
||||
| Piano `concurrent_streams_limit` | Tetto **per club** (Premium Full = 10): indipendente dal cluster |
|
||||
|
||||
Capienza cluster soft ≈ `home_max + max_overflow × cloud_max` (fase A: 4+12×6 = **76**; fase C: 4+33×6 = **202**).
|
||||
|
||||
Quiet hours: `Streams::NightCloudSweeper` + blocco provision in `Streams::Autoscaler`. Nodi cloud con sessioni attive di notte → alert Ops, non spegnere.
|
||||
|
||||
Quando si parla di capacity planning, deploy autoscale, o “troppe dirette”, ricordare di rivedere questi valori (e il limite piano) in base ai clienti reali — non lasciare i soft limit di collaudo/early-prod a lungo. Densità 8 solo dopo misure.
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
# Ruby
|
||||
backend/.bundle
|
||||
backend/vendor/bundle
|
||||
backend/tmp/
|
||||
backend/log/
|
||||
backend/storage/
|
||||
backend/.env
|
||||
backend/.env.*
|
||||
|
||||
# Flutter
|
||||
mobile/.dart_tool/
|
||||
mobile/.flutter-plugins
|
||||
mobile/.flutter-plugins-dependencies
|
||||
mobile/build/
|
||||
mobile/.packages
|
||||
mobile/pubspec.lock
|
||||
|
||||
# Infra
|
||||
infra/certs/
|
||||
infra/recordings/
|
||||
infra/.env
|
||||
infra/.env.production.generated
|
||||
infra/garage/dev-credentials.env
|
||||
infra/garage/prod-credentials.env
|
||||
infra/garage/garage.prod.toml
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
*.swp
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
# Secrets
|
||||
.env
|
||||
*.pem
|
||||
credentials.json
|
||||
@@ -1,3 +1,76 @@
|
||||
# MatchLiveTv
|
||||
# Match Live TV
|
||||
|
||||
Piattaforma di live streaming per sport dilettantistico con regia remota, gestione squadre, streaming mobile e archivio partite.
|
||||
Piattaforma mobile-first per streaming di partite sportive giovanili — MVP su **Match Live TV** (HLS sul nostro sito); YouTube/Facebook/Twitch come integrazioni premium.
|
||||
|
||||
**Slogan:** *Ogni partita, ogni evento, per i tuoi tifosi.*
|
||||
|
||||
## Struttura monorepo
|
||||
|
||||
```
|
||||
├── backend/ # Rails 7.2 API + Action Cable + Sidekiq
|
||||
├── native/android/ # App Android nativa (Kotlin + Compose)
|
||||
├── infra/ # Docker Compose, MediaMTX, Nginx, Kamal
|
||||
└── docs/ # Documentazione
|
||||
```
|
||||
|
||||
## Deploy produzione (server 192.168.1.146)
|
||||
|
||||
Vedi [docs/infrastructure/SERVER_DEPLOYMENT.md](docs/infrastructure/SERVER_DEPLOYMENT.md) per porte router, NPM e procedura completa.
|
||||
|
||||
**Porte da aprire sul router:** `1935/TCP` (RTMP). Opzionale `8888/TCP` (HLS). HTTPS via Nginx Proxy Manager verso `http://192.168.1.146:3000`.
|
||||
|
||||
**Sul server (una tantum, con sudo):**
|
||||
```bash
|
||||
sudo bash ~/matchlivetv/scripts/deploy/server_bootstrap.sh
|
||||
bash ~/matchlivetv/scripts/deploy/post_bootstrap_deploy.sh
|
||||
```
|
||||
|
||||
## Avvio rapido (locale)
|
||||
|
||||
```bash
|
||||
cd infra
|
||||
cp .env.example .env
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
- API Rails: http://localhost:3000
|
||||
- MediaMTX RTMP: rtmp://localhost:1935
|
||||
- MediaMTX API: http://localhost:9997
|
||||
- Admin: http://localhost:3000/admin
|
||||
|
||||
### Seed utente demo
|
||||
|
||||
```
|
||||
email: coach@matchlivetv.test
|
||||
password: password123
|
||||
```
|
||||
|
||||
## App Android nativa
|
||||
|
||||
```bash
|
||||
./scripts/build_native_android_apk_prod.sh
|
||||
adb install -r native/android/app/build/outputs/apk/release/app-release.apk
|
||||
```
|
||||
|
||||
API produzione: `https://www.matchlivetv.it` (override con `-PAPI_BASE_URL=...` in Gradle).
|
||||
|
||||
Vedi [native/android/README.md](native/android/README.md).
|
||||
|
||||
## Architettura
|
||||
|
||||
Documentazione completa: **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)** (rete, edge nginx, flussi video, ops).
|
||||
|
||||
In sintesi:
|
||||
|
||||
- Video live: Phone → MediaMTX (RTMP) → HLS via edge `/hls/` (non Puma)
|
||||
- Video replay: Rails auth → redirect `/media/` → Garage (non Puma)
|
||||
- Video premium: stesso ingest + relay ffmpeg verso YouTube
|
||||
- Controllo: Phone ↔ Action Cable ↔ Rails ↔ PostgreSQL
|
||||
- Disconnessioni: MediaMTX `alwaysAvailable` slate + timeout 5 min (Sidekiq)
|
||||
|
||||
### App Android produzione
|
||||
|
||||
```bash
|
||||
./scripts/build_native_android_apk_prod.sh
|
||||
# API: https://www.matchlivetv.it
|
||||
```
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files.
|
||||
|
||||
# Ignore git directory.
|
||||
/.git/
|
||||
/.gitignore
|
||||
|
||||
# Ignore bundler config.
|
||||
/.bundle
|
||||
|
||||
# Ignore all environment files (except templates).
|
||||
/.env*
|
||||
!/.env*.erb
|
||||
|
||||
# Ignore all default key files.
|
||||
/config/master.key
|
||||
/config/credentials/*.key
|
||||
|
||||
# Ignore all logfiles and tempfiles.
|
||||
/log/*
|
||||
/tmp/*
|
||||
!/log/.keep
|
||||
!/tmp/.keep
|
||||
|
||||
# Ignore pidfiles, but keep the directory.
|
||||
/tmp/pids/*
|
||||
!/tmp/pids/.keep
|
||||
|
||||
# Ignore storage (uploaded files in development and any SQLite databases).
|
||||
/storage/*
|
||||
!/storage/.keep
|
||||
/tmp/storage/*
|
||||
!/tmp/storage/.keep
|
||||
|
||||
# Ignore CI service files.
|
||||
/.github
|
||||
|
||||
# Ignore development files
|
||||
/.devcontainer
|
||||
|
||||
# Ignore Docker-related files
|
||||
/.dockerignore
|
||||
/Dockerfile*
|
||||
@@ -0,0 +1,9 @@
|
||||
# See https://git-scm.com/docs/gitattributes for more about git attribute files.
|
||||
|
||||
# Mark the database schema as having been generated.
|
||||
db/schema.rb linguist-generated
|
||||
|
||||
# Mark any vendored files as having been vendored.
|
||||
vendor/* linguist-vendored
|
||||
config/credentials/*.yml.enc diff=rails_credentials
|
||||
config/credentials.yml.enc diff=rails_credentials
|
||||
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: bundler
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
- package-ecosystem: github-actions
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: daily
|
||||
open-pull-requests-limit: 10
|
||||
Vendored
+39
@@ -0,0 +1,39 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
scan_ruby:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Ruby
|
||||
uses: ruby/setup-ruby@v1
|
||||
with:
|
||||
ruby-version: .ruby-version
|
||||
bundler-cache: true
|
||||
|
||||
- name: Scan for common Rails security vulnerabilities using static analysis
|
||||
run: bin/brakeman --no-pager
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Ruby
|
||||
uses: ruby/setup-ruby@v1
|
||||
with:
|
||||
ruby-version: .ruby-version
|
||||
bundler-cache: true
|
||||
|
||||
- name: Lint code for consistent style
|
||||
run: bin/rubocop -f github
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# See https://help.github.com/articles/ignoring-files for more about ignoring files.
|
||||
#
|
||||
# Temporary files generated by your text editor or operating system
|
||||
# belong in git's global ignore instead:
|
||||
# `$XDG_CONFIG_HOME/git/ignore` or `~/.config/git/ignore`
|
||||
|
||||
# Ignore bundler config.
|
||||
/.bundle
|
||||
|
||||
# Ignore all environment files (except templates).
|
||||
/.env*
|
||||
!/.env*.erb
|
||||
|
||||
# Ignore all logfiles and tempfiles.
|
||||
/log/*
|
||||
/tmp/*
|
||||
!/log/.keep
|
||||
!/tmp/.keep
|
||||
|
||||
# Ignore pidfiles, but keep the directory.
|
||||
/tmp/pids/*
|
||||
!/tmp/pids/
|
||||
!/tmp/pids/.keep
|
||||
|
||||
# Ignore storage (uploaded files in development and any SQLite databases).
|
||||
/storage/*
|
||||
!/storage/.keep
|
||||
/tmp/storage/*
|
||||
!/tmp/storage/
|
||||
!/tmp/storage/.keep
|
||||
|
||||
# Ignore master key for decrypting credentials and more.
|
||||
/config/master.key
|
||||
@@ -0,0 +1,8 @@
|
||||
# Omakase Ruby styling for Rails
|
||||
inherit_gem: { rubocop-rails-omakase: rubocop.yml }
|
||||
|
||||
# Overwrite or add rules to create your own house style
|
||||
#
|
||||
# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]`
|
||||
# Layout/SpaceInsideArrayLiteralBrackets:
|
||||
# Enabled: false
|
||||
@@ -0,0 +1 @@
|
||||
ruby-3.3.11
|
||||
@@ -0,0 +1,19 @@
|
||||
FROM ruby:3.3-bookworm
|
||||
|
||||
RUN apt-get update -qq && \
|
||||
apt-get install -y --no-install-recommends build-essential libpq-dev curl ffmpeg librsvg2-bin fonts-dejavu-core && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV BUNDLE_WITHOUT="development:test"
|
||||
ENV BUNDLE_DEPLOYMENT="1"
|
||||
|
||||
COPY Gemfile Gemfile.lock ./
|
||||
RUN bundle install
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["bundle", "exec", "puma", "-C", "config/puma.rb", "-b", "tcp://0.0.0.0:3000"]
|
||||
@@ -0,0 +1,36 @@
|
||||
source "https://rubygems.org"
|
||||
|
||||
gem "rails", "~> 7.2.2"
|
||||
gem "pg", "~> 1.1"
|
||||
gem "puma", ">= 5.0"
|
||||
gem "bootsnap", require: false
|
||||
gem "tzinfo-data", platforms: %i[ windows jruby ]
|
||||
|
||||
gem "redis", ">= 4.0.1"
|
||||
gem "bcrypt", "~> 3.1.7"
|
||||
gem "rack-cors"
|
||||
gem "jwt"
|
||||
gem "sidekiq"
|
||||
gem "rack-attack"
|
||||
gem "aasm"
|
||||
gem "attr_encrypted"
|
||||
gem "google-apis-youtube_v3"
|
||||
gem "faraday"
|
||||
gem "stripe"
|
||||
gem "aws-sdk-s3", "~> 1.0", require: false
|
||||
gem "kamal", require: false
|
||||
gem "sentry-ruby"
|
||||
gem "sentry-rails"
|
||||
|
||||
group :development, :test do
|
||||
gem "debug", platforms: %i[ mri windows ], require: "debug/prelude"
|
||||
gem "brakeman", require: false
|
||||
gem "rubocop-rails-omakase", require: false
|
||||
gem "rspec-rails"
|
||||
gem "factory_bot_rails"
|
||||
gem "faker"
|
||||
end
|
||||
|
||||
group :development do
|
||||
gem "letter_opener"
|
||||
end
|
||||
@@ -0,0 +1,473 @@
|
||||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
aasm (5.5.2)
|
||||
concurrent-ruby (~> 1.0)
|
||||
actioncable (7.2.3.1)
|
||||
actionpack (= 7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
nio4r (~> 2.0)
|
||||
websocket-driver (>= 0.6.1)
|
||||
zeitwerk (~> 2.6)
|
||||
actionmailbox (7.2.3.1)
|
||||
actionpack (= 7.2.3.1)
|
||||
activejob (= 7.2.3.1)
|
||||
activerecord (= 7.2.3.1)
|
||||
activestorage (= 7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
mail (>= 2.8.0)
|
||||
actionmailer (7.2.3.1)
|
||||
actionpack (= 7.2.3.1)
|
||||
actionview (= 7.2.3.1)
|
||||
activejob (= 7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
mail (>= 2.8.0)
|
||||
rails-dom-testing (~> 2.2)
|
||||
actionpack (7.2.3.1)
|
||||
actionview (= 7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
cgi
|
||||
nokogiri (>= 1.8.5)
|
||||
racc
|
||||
rack (>= 2.2.4, < 3.3)
|
||||
rack-session (>= 1.0.1)
|
||||
rack-test (>= 0.6.3)
|
||||
rails-dom-testing (~> 2.2)
|
||||
rails-html-sanitizer (~> 1.6)
|
||||
useragent (~> 0.16)
|
||||
actiontext (7.2.3.1)
|
||||
actionpack (= 7.2.3.1)
|
||||
activerecord (= 7.2.3.1)
|
||||
activestorage (= 7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
globalid (>= 0.6.0)
|
||||
nokogiri (>= 1.8.5)
|
||||
actionview (7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
builder (~> 3.1)
|
||||
cgi
|
||||
erubi (~> 1.11)
|
||||
rails-dom-testing (~> 2.2)
|
||||
rails-html-sanitizer (~> 1.6)
|
||||
activejob (7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
globalid (>= 0.3.6)
|
||||
activemodel (7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
activerecord (7.2.3.1)
|
||||
activemodel (= 7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
timeout (>= 0.4.0)
|
||||
activestorage (7.2.3.1)
|
||||
actionpack (= 7.2.3.1)
|
||||
activejob (= 7.2.3.1)
|
||||
activerecord (= 7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
marcel (~> 1.0)
|
||||
activesupport (7.2.3.1)
|
||||
base64
|
||||
benchmark (>= 0.3)
|
||||
bigdecimal
|
||||
concurrent-ruby (~> 1.0, >= 1.3.1)
|
||||
connection_pool (>= 2.2.5)
|
||||
drb
|
||||
i18n (>= 1.6, < 2)
|
||||
logger (>= 1.4.2)
|
||||
minitest (>= 5.1, < 6)
|
||||
securerandom (>= 0.3)
|
||||
tzinfo (~> 2.0, >= 2.0.5)
|
||||
addressable (2.9.0)
|
||||
public_suffix (>= 2.0.2, < 8.0)
|
||||
ast (2.4.3)
|
||||
attr_encrypted (4.2.0)
|
||||
encryptor (~> 3.0.0)
|
||||
aws-eventstream (1.4.0)
|
||||
aws-partitions (1.1256.0)
|
||||
aws-sdk-core (3.251.0)
|
||||
aws-eventstream (~> 1, >= 1.3.0)
|
||||
aws-partitions (~> 1, >= 1.992.0)
|
||||
aws-sigv4 (~> 1.9)
|
||||
base64
|
||||
bigdecimal
|
||||
jmespath (~> 1, >= 1.6.1)
|
||||
logger
|
||||
aws-sdk-kms (1.129.0)
|
||||
aws-sdk-core (~> 3, >= 3.248.0)
|
||||
aws-sigv4 (~> 1.5)
|
||||
aws-sdk-s3 (1.225.0)
|
||||
aws-sdk-core (~> 3, >= 3.248.0)
|
||||
aws-sdk-kms (~> 1)
|
||||
aws-sigv4 (~> 1.5)
|
||||
aws-sigv4 (1.12.1)
|
||||
aws-eventstream (~> 1, >= 1.0.2)
|
||||
base64 (0.3.0)
|
||||
bcrypt (3.1.22)
|
||||
bcrypt_pbkdf (1.1.2)
|
||||
bcrypt_pbkdf (1.1.2-arm64-darwin)
|
||||
bcrypt_pbkdf (1.1.2-x86_64-darwin)
|
||||
benchmark (0.5.0)
|
||||
bigdecimal (4.1.2)
|
||||
bootsnap (1.24.5)
|
||||
msgpack (~> 1.2)
|
||||
brakeman (8.0.4)
|
||||
racc
|
||||
builder (3.3.0)
|
||||
cgi (0.5.1)
|
||||
childprocess (5.1.0)
|
||||
logger (~> 1.5)
|
||||
concurrent-ruby (1.3.6)
|
||||
connection_pool (3.0.2)
|
||||
crass (1.0.6)
|
||||
date (3.5.1)
|
||||
debug (1.11.1)
|
||||
irb (~> 1.10)
|
||||
reline (>= 0.3.8)
|
||||
declarative (0.0.20)
|
||||
diff-lcs (1.6.2)
|
||||
dotenv (3.2.0)
|
||||
drb (2.2.3)
|
||||
ed25519 (1.4.0)
|
||||
encryptor (3.0.0)
|
||||
erb (6.0.4)
|
||||
erubi (1.13.1)
|
||||
factory_bot (6.6.0)
|
||||
activesupport (>= 6.1.0)
|
||||
factory_bot_rails (6.5.1)
|
||||
factory_bot (~> 6.5)
|
||||
railties (>= 6.1.0)
|
||||
faker (3.8.0)
|
||||
i18n (>= 1.8.11, < 2)
|
||||
faraday (2.14.2)
|
||||
faraday-net_http (>= 2.0, < 3.5)
|
||||
json
|
||||
logger
|
||||
faraday-follow_redirects (0.5.0)
|
||||
faraday (>= 1, < 3)
|
||||
faraday-net_http (3.4.3)
|
||||
net-http (~> 0.5)
|
||||
globalid (1.3.0)
|
||||
activesupport (>= 6.1)
|
||||
google-apis-core (1.0.2)
|
||||
addressable (~> 2.8, >= 2.8.7)
|
||||
faraday (~> 2.13)
|
||||
faraday-follow_redirects (~> 0.3)
|
||||
googleauth (~> 1.14)
|
||||
mini_mime (~> 1.1)
|
||||
representable (~> 3.0)
|
||||
retriable (~> 3.1)
|
||||
google-apis-youtube_v3 (0.64.0)
|
||||
google-apis-core (>= 0.15.0, < 2.a)
|
||||
google-cloud-env (2.3.1)
|
||||
base64 (~> 0.2)
|
||||
faraday (>= 1.0, < 3.a)
|
||||
google-logging-utils (0.2.0)
|
||||
googleauth (1.16.2)
|
||||
faraday (>= 1.0, < 3.a)
|
||||
google-cloud-env (~> 2.2)
|
||||
google-logging-utils (~> 0.1)
|
||||
jwt (>= 1.4, < 4.0)
|
||||
multi_json (~> 1.11)
|
||||
os (>= 0.9, < 2.0)
|
||||
signet (>= 0.16, < 2.a)
|
||||
i18n (1.14.8)
|
||||
concurrent-ruby (~> 1.0)
|
||||
io-console (0.8.2)
|
||||
irb (1.18.0)
|
||||
pp (>= 0.6.0)
|
||||
prism (>= 1.3.0)
|
||||
rdoc (>= 4.0.0)
|
||||
reline (>= 0.4.2)
|
||||
jmespath (1.6.2)
|
||||
json (2.19.5)
|
||||
jwt (3.2.0)
|
||||
base64
|
||||
kamal (2.11.0)
|
||||
activesupport (>= 7.0)
|
||||
base64 (~> 0.2)
|
||||
bcrypt_pbkdf (~> 1.0)
|
||||
concurrent-ruby (~> 1.2)
|
||||
dotenv (~> 3.1)
|
||||
ed25519 (~> 1.4)
|
||||
net-ssh (~> 7.3)
|
||||
sshkit (>= 1.23.0, < 2.0)
|
||||
thor (~> 1.3)
|
||||
zeitwerk (>= 2.6.18, < 3.0)
|
||||
language_server-protocol (3.17.0.5)
|
||||
launchy (3.1.1)
|
||||
addressable (~> 2.8)
|
||||
childprocess (~> 5.0)
|
||||
logger (~> 1.6)
|
||||
letter_opener (1.10.0)
|
||||
launchy (>= 2.2, < 4)
|
||||
lint_roller (1.1.0)
|
||||
logger (1.7.0)
|
||||
loofah (2.25.1)
|
||||
crass (~> 1.0.2)
|
||||
nokogiri (>= 1.12.0)
|
||||
mail (2.9.0)
|
||||
logger
|
||||
mini_mime (>= 0.1.1)
|
||||
net-imap
|
||||
net-pop
|
||||
net-smtp
|
||||
marcel (1.2.1)
|
||||
mini_mime (1.1.5)
|
||||
minitest (5.27.0)
|
||||
msgpack (1.8.0)
|
||||
multi_json (1.21.1)
|
||||
net-http (0.9.1)
|
||||
uri (>= 0.11.1)
|
||||
net-imap (0.6.4)
|
||||
date
|
||||
net-protocol
|
||||
net-pop (0.1.2)
|
||||
net-protocol
|
||||
net-protocol (0.2.2)
|
||||
timeout
|
||||
net-scp (4.1.0)
|
||||
net-ssh (>= 2.6.5, < 8.0.0)
|
||||
net-sftp (4.0.0)
|
||||
net-ssh (>= 5.0.0, < 8.0.0)
|
||||
net-smtp (0.5.1)
|
||||
net-protocol
|
||||
net-ssh (7.3.2)
|
||||
nio4r (2.7.5)
|
||||
nokogiri (1.19.3-aarch64-linux-gnu)
|
||||
racc (~> 1.4)
|
||||
nokogiri (1.19.3-aarch64-linux-musl)
|
||||
racc (~> 1.4)
|
||||
nokogiri (1.19.3-arm-linux-gnu)
|
||||
racc (~> 1.4)
|
||||
nokogiri (1.19.3-arm-linux-musl)
|
||||
racc (~> 1.4)
|
||||
nokogiri (1.19.3-arm64-darwin)
|
||||
racc (~> 1.4)
|
||||
nokogiri (1.19.3-x86_64-darwin)
|
||||
racc (~> 1.4)
|
||||
nokogiri (1.19.3-x86_64-linux-gnu)
|
||||
racc (~> 1.4)
|
||||
nokogiri (1.19.3-x86_64-linux-musl)
|
||||
racc (~> 1.4)
|
||||
os (1.1.4)
|
||||
ostruct (0.6.3)
|
||||
parallel (2.1.0)
|
||||
parser (3.3.11.1)
|
||||
ast (~> 2.4.1)
|
||||
racc
|
||||
pg (1.6.3)
|
||||
pg (1.6.3-aarch64-linux)
|
||||
pg (1.6.3-aarch64-linux-musl)
|
||||
pg (1.6.3-arm64-darwin)
|
||||
pg (1.6.3-x86_64-darwin)
|
||||
pg (1.6.3-x86_64-linux)
|
||||
pg (1.6.3-x86_64-linux-musl)
|
||||
pp (0.6.3)
|
||||
prettyprint
|
||||
prettyprint (0.2.0)
|
||||
prism (1.9.0)
|
||||
psych (5.3.1)
|
||||
date
|
||||
stringio
|
||||
public_suffix (7.0.5)
|
||||
puma (8.0.1)
|
||||
nio4r (~> 2.0)
|
||||
racc (1.8.1)
|
||||
rack (3.2.6)
|
||||
rack-attack (6.8.0)
|
||||
rack (>= 1.0, < 4)
|
||||
rack-cors (3.0.0)
|
||||
logger
|
||||
rack (>= 3.0.14)
|
||||
rack-session (2.1.2)
|
||||
base64 (>= 0.1.0)
|
||||
rack (>= 3.0.0)
|
||||
rack-test (2.2.0)
|
||||
rack (>= 1.3)
|
||||
rackup (2.3.1)
|
||||
rack (>= 3)
|
||||
rails (7.2.3.1)
|
||||
actioncable (= 7.2.3.1)
|
||||
actionmailbox (= 7.2.3.1)
|
||||
actionmailer (= 7.2.3.1)
|
||||
actionpack (= 7.2.3.1)
|
||||
actiontext (= 7.2.3.1)
|
||||
actionview (= 7.2.3.1)
|
||||
activejob (= 7.2.3.1)
|
||||
activemodel (= 7.2.3.1)
|
||||
activerecord (= 7.2.3.1)
|
||||
activestorage (= 7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
bundler (>= 1.15.0)
|
||||
railties (= 7.2.3.1)
|
||||
rails-dom-testing (2.3.0)
|
||||
activesupport (>= 5.0.0)
|
||||
minitest
|
||||
nokogiri (>= 1.6)
|
||||
rails-html-sanitizer (1.7.0)
|
||||
loofah (~> 2.25)
|
||||
nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0)
|
||||
railties (7.2.3.1)
|
||||
actionpack (= 7.2.3.1)
|
||||
activesupport (= 7.2.3.1)
|
||||
cgi
|
||||
irb (~> 1.13)
|
||||
rackup (>= 1.0.0)
|
||||
rake (>= 12.2)
|
||||
thor (~> 1.0, >= 1.2.2)
|
||||
tsort (>= 0.2)
|
||||
zeitwerk (~> 2.6)
|
||||
rainbow (3.1.1)
|
||||
rake (13.4.2)
|
||||
rdoc (7.2.0)
|
||||
erb
|
||||
psych (>= 4.0.0)
|
||||
tsort
|
||||
redis (5.4.1)
|
||||
redis-client (>= 0.22.0)
|
||||
redis-client (0.29.0)
|
||||
connection_pool
|
||||
regexp_parser (2.12.0)
|
||||
reline (0.6.3)
|
||||
io-console (~> 0.5)
|
||||
representable (3.2.0)
|
||||
declarative (< 0.1.0)
|
||||
trailblazer-option (>= 0.1.1, < 0.2.0)
|
||||
uber (< 0.2.0)
|
||||
retriable (3.5.0)
|
||||
rspec-core (3.13.6)
|
||||
rspec-support (~> 3.13.0)
|
||||
rspec-expectations (3.13.5)
|
||||
diff-lcs (>= 1.2.0, < 2.0)
|
||||
rspec-support (~> 3.13.0)
|
||||
rspec-mocks (3.13.8)
|
||||
diff-lcs (>= 1.2.0, < 2.0)
|
||||
rspec-support (~> 3.13.0)
|
||||
rspec-rails (8.0.4)
|
||||
actionpack (>= 7.2)
|
||||
activesupport (>= 7.2)
|
||||
railties (>= 7.2)
|
||||
rspec-core (>= 3.13.0, < 5.0.0)
|
||||
rspec-expectations (>= 3.13.0, < 5.0.0)
|
||||
rspec-mocks (>= 3.13.0, < 5.0.0)
|
||||
rspec-support (>= 3.13.0, < 5.0.0)
|
||||
rspec-support (3.13.7)
|
||||
rubocop (1.86.2)
|
||||
json (~> 2.3)
|
||||
language_server-protocol (~> 3.17.0.2)
|
||||
lint_roller (~> 1.1.0)
|
||||
parallel (>= 1.10)
|
||||
parser (>= 3.3.0.2)
|
||||
rainbow (>= 2.2.2, < 4.0)
|
||||
regexp_parser (>= 2.9.3, < 3.0)
|
||||
rubocop-ast (>= 1.49.0, < 2.0)
|
||||
ruby-progressbar (~> 1.7)
|
||||
unicode-display_width (>= 2.4.0, < 4.0)
|
||||
rubocop-ast (1.49.1)
|
||||
parser (>= 3.3.7.2)
|
||||
prism (~> 1.7)
|
||||
rubocop-performance (1.26.1)
|
||||
lint_roller (~> 1.1)
|
||||
rubocop (>= 1.75.0, < 2.0)
|
||||
rubocop-ast (>= 1.47.1, < 2.0)
|
||||
rubocop-rails (2.35.2)
|
||||
activesupport (>= 4.2.0)
|
||||
lint_roller (~> 1.1)
|
||||
rack (>= 1.1)
|
||||
rubocop (>= 1.75.0, < 2.0)
|
||||
rubocop-ast (>= 1.44.0, < 2.0)
|
||||
rubocop-rails-omakase (1.1.0)
|
||||
rubocop (>= 1.72)
|
||||
rubocop-performance (>= 1.24)
|
||||
rubocop-rails (>= 2.30)
|
||||
ruby-progressbar (1.13.0)
|
||||
securerandom (0.4.1)
|
||||
sentry-rails (6.6.2)
|
||||
railties (>= 5.2.0)
|
||||
sentry-ruby (~> 6.6.2)
|
||||
sentry-ruby (6.6.2)
|
||||
bigdecimal
|
||||
concurrent-ruby (~> 1.0, >= 1.0.2)
|
||||
logger
|
||||
sidekiq (8.1.5)
|
||||
connection_pool (>= 3.0.0)
|
||||
json (>= 2.16.0)
|
||||
logger (>= 1.7.0)
|
||||
rack (>= 3.2.0)
|
||||
redis-client (>= 0.29.0)
|
||||
signet (0.21.0)
|
||||
addressable (~> 2.8)
|
||||
faraday (>= 0.17.5, < 3.a)
|
||||
jwt (>= 1.5, < 4.0)
|
||||
multi_json (~> 1.10)
|
||||
sshkit (1.25.0)
|
||||
base64
|
||||
logger
|
||||
net-scp (>= 1.1.2)
|
||||
net-sftp (>= 2.1.2)
|
||||
net-ssh (>= 2.8.0)
|
||||
ostruct
|
||||
stringio (3.2.0)
|
||||
stripe (19.1.0)
|
||||
bigdecimal
|
||||
logger
|
||||
thor (1.5.0)
|
||||
timeout (0.6.1)
|
||||
trailblazer-option (0.1.2)
|
||||
tsort (0.2.0)
|
||||
tzinfo (2.0.6)
|
||||
concurrent-ruby (~> 1.0)
|
||||
uber (0.1.0)
|
||||
unicode-display_width (3.2.0)
|
||||
unicode-emoji (~> 4.1)
|
||||
unicode-emoji (4.2.0)
|
||||
uri (1.1.1)
|
||||
useragent (0.16.11)
|
||||
websocket-driver (0.8.0)
|
||||
base64
|
||||
websocket-extensions (>= 0.1.0)
|
||||
websocket-extensions (0.1.5)
|
||||
zeitwerk (2.8.2)
|
||||
|
||||
PLATFORMS
|
||||
aarch64-linux
|
||||
aarch64-linux-gnu
|
||||
aarch64-linux-musl
|
||||
arm-linux-gnu
|
||||
arm-linux-musl
|
||||
arm64-darwin
|
||||
x86_64-darwin
|
||||
x86_64-linux
|
||||
x86_64-linux-gnu
|
||||
x86_64-linux-musl
|
||||
|
||||
DEPENDENCIES
|
||||
aasm
|
||||
attr_encrypted
|
||||
aws-sdk-s3 (~> 1.0)
|
||||
bcrypt (~> 3.1.7)
|
||||
bootsnap
|
||||
brakeman
|
||||
debug
|
||||
factory_bot_rails
|
||||
faker
|
||||
faraday
|
||||
google-apis-youtube_v3
|
||||
jwt
|
||||
kamal
|
||||
letter_opener
|
||||
pg (~> 1.1)
|
||||
puma (>= 5.0)
|
||||
rack-attack
|
||||
rack-cors
|
||||
rails (~> 7.2.2)
|
||||
redis (>= 4.0.1)
|
||||
rspec-rails
|
||||
rubocop-rails-omakase
|
||||
sentry-rails
|
||||
sentry-ruby
|
||||
sidekiq
|
||||
stripe
|
||||
tzinfo-data
|
||||
|
||||
BUNDLED WITH
|
||||
2.5.22
|
||||
@@ -0,0 +1,24 @@
|
||||
# README
|
||||
|
||||
This README would normally document whatever steps are necessary to get the
|
||||
application up and running.
|
||||
|
||||
Things you may want to cover:
|
||||
|
||||
* Ruby version
|
||||
|
||||
* System dependencies
|
||||
|
||||
* Configuration
|
||||
|
||||
* Database creation
|
||||
|
||||
* Database initialization
|
||||
|
||||
* How to run the test suite
|
||||
|
||||
* Services (job queues, cache servers, search engines, etc.)
|
||||
|
||||
* Deployment instructions
|
||||
|
||||
* ...
|
||||
@@ -0,0 +1,6 @@
|
||||
# Add your own tasks in files placed in lib/tasks ending in .rake,
|
||||
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
|
||||
|
||||
require_relative "config/application"
|
||||
|
||||
Rails.application.load_tasks
|
||||
@@ -0,0 +1,4 @@
|
||||
module ApplicationCable
|
||||
class Channel < ActionCable::Channel::Base
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,23 @@
|
||||
module ApplicationCable
|
||||
class Connection < ActionCable::Connection::Base
|
||||
identified_by :current_user, :regia_session
|
||||
|
||||
def connect
|
||||
if (regia_token = request.params[:regia_token].presence)
|
||||
self.regia_session = Sessions::RegiaAccess.find_session_by_token(regia_token)
|
||||
reject_unauthorized_connection unless regia_session
|
||||
return
|
||||
end
|
||||
|
||||
payload = JsonWebToken.decode(token_from_header)
|
||||
self.current_user = User.find_by(id: payload[:user_id]) if payload
|
||||
reject_unauthorized_connection unless current_user
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def token_from_header
|
||||
request.headers["Authorization"].to_s.delete_prefix("Bearer ").presence
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
module CableBroadcastable
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
class_methods do
|
||||
def broadcast_message(session, data)
|
||||
broadcast_to(session, data)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,94 @@
|
||||
class SessionChannel < ApplicationCable::Channel
|
||||
include CableBroadcastable
|
||||
def subscribed
|
||||
session = resolve_session
|
||||
reject unless session && session.id.to_s == params[:session_id].to_s
|
||||
|
||||
stream_for session
|
||||
session.device_states.find_or_create_by!(device_role: params[:device_role] || "controller")
|
||||
end
|
||||
|
||||
def resolve_session
|
||||
if connection.regia_session
|
||||
connection.regia_session
|
||||
else
|
||||
StreamSession.joins(match: :team)
|
||||
.merge(connection.current_user.manageable_teams)
|
||||
.find_by(id: params[:session_id])
|
||||
end
|
||||
end
|
||||
|
||||
def unsubscribed
|
||||
stop_all_streams
|
||||
end
|
||||
|
||||
def receive(data)
|
||||
session = resolve_session
|
||||
return unless session
|
||||
|
||||
handle_message(session, data)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def handle_message(session, data)
|
||||
case data["type"]
|
||||
when "command"
|
||||
SessionChannel.broadcast_message(session, data)
|
||||
execute_command(session, data)
|
||||
when "score_update"
|
||||
update_score(session, data)
|
||||
when "timeout"
|
||||
update_timeout(session, data)
|
||||
when "device_state"
|
||||
update_device(session, data)
|
||||
end
|
||||
end
|
||||
|
||||
def execute_command(session, data)
|
||||
case data["action"]
|
||||
when "start_stream"
|
||||
Sessions::Start.new(session).call
|
||||
when "stop_stream"
|
||||
Sessions::Stop.new(session).call
|
||||
when "pause_stream"
|
||||
Sessions::Pause.new(session).call
|
||||
when "resume_stream"
|
||||
Sessions::Resume.new(session).call
|
||||
when "mute_audio"
|
||||
Sessions::SetAudioMute.new(session, muted: true).call
|
||||
when "unmute_audio"
|
||||
Sessions::SetAudioMute.new(session, muted: false).call
|
||||
when "set_min_quality"
|
||||
Sessions::SetMinQuality.new(session, preset: data["min_quality_preset"]).call
|
||||
end
|
||||
end
|
||||
|
||||
def update_score(session, data)
|
||||
Scoring::SyncState.new(session: session, payload: data).call
|
||||
end
|
||||
|
||||
def update_timeout(session, data)
|
||||
score = session.score_state
|
||||
return unless score
|
||||
|
||||
if data["team"] == "home"
|
||||
score.update!(timeout_home: true)
|
||||
else
|
||||
score.update!(timeout_away: true)
|
||||
end
|
||||
SessionChannel.broadcast_message(session, { type: "timeout", team: data["team"] })
|
||||
end
|
||||
|
||||
def update_device(session, data)
|
||||
state = session.device_states.find_or_initialize_by(device_role: data["device_role"] || "camera")
|
||||
state.update!(
|
||||
battery_level: data["battery"],
|
||||
network_type: data["network"],
|
||||
current_bitrate: data["bitrate"],
|
||||
fps: data["fps"],
|
||||
last_seen_at: Time.current
|
||||
)
|
||||
SessionChannel.broadcast_message(session, state.as_cable_payload)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,183 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Admin
|
||||
class AnalyticsController < Admin::BaseController
|
||||
def index
|
||||
@filters = {
|
||||
from: parse_date(params[:from]) || 7.days.ago.to_date,
|
||||
to: parse_date(params[:to]) || Time.zone.today,
|
||||
device: params[:device].presence,
|
||||
chart_path: params[:chart_path].presence
|
||||
}
|
||||
@analytics_preview_active = analytics_preview_active?
|
||||
|
||||
scope = AnalyticsPageStat.where(day: @filters[:from]..@filters[:to])
|
||||
scope = scope.where(device: @filters[:device]) if @filters[:device].present? && AnalyticsEvent::DEVICES.include?(@filters[:device])
|
||||
|
||||
cell_scope = AnalyticsPageCell.where(day: @filters[:from]..@filters[:to])
|
||||
cell_scope = cell_scope.where(device: @filters[:device]) if @filters[:device].present? && AnalyticsEvent::DEVICES.include?(@filters[:device])
|
||||
|
||||
clicks_by_path = cell_scope.group(:page_path).sum(:click_count)
|
||||
moves_by_path = cell_scope.group(:page_path).sum(:move_count)
|
||||
pageviews_by_path = scope.group(:page_path).sum(:pageview_count)
|
||||
scroll_samples_by_path = scope.group(:page_path).sum(:scroll_samples)
|
||||
scroll_sum_by_path = scope.group(:page_path).sum(:scroll_sum_pct)
|
||||
max_scroll_by_path = scope.group(:page_path).maximum(:max_scroll_pct)
|
||||
|
||||
paths = (pageviews_by_path.keys + clicks_by_path.keys + moves_by_path.keys).uniq
|
||||
@pages = paths.map do |path|
|
||||
samples = scroll_samples_by_path[path].to_i
|
||||
{
|
||||
page_path: path,
|
||||
pageviews: pageviews_by_path[path].to_i,
|
||||
clicks: clicks_by_path[path].to_i,
|
||||
moves: moves_by_path[path].to_i,
|
||||
scroll_samples: samples,
|
||||
scroll_sum: scroll_sum_by_path[path].to_i,
|
||||
max_scroll: max_scroll_by_path[path].to_i
|
||||
}
|
||||
end.sort_by { |r| [-r[:pageviews], -r[:moves], -r[:clicks], r[:page_path]] }
|
||||
|
||||
@chart_path_options = @pages.map { |row| row[:page_path] }
|
||||
if @filters[:chart_path].present? && @chart_path_options.exclude?(@filters[:chart_path])
|
||||
@filters[:chart_path] = nil
|
||||
end
|
||||
|
||||
trend_scope = scope
|
||||
trend_scope = trend_scope.where(page_path: @filters[:chart_path]) if @filters[:chart_path].present?
|
||||
pageviews_by_day = trend_scope.group(:day).sum(:pageview_count)
|
||||
@trend = (@filters[:from]..@filters[:to]).map do |day|
|
||||
{
|
||||
day: day.iso8601,
|
||||
pageviews: pageviews_by_day[day].to_i
|
||||
}
|
||||
end
|
||||
@trend_totals = {
|
||||
pageviews: @trend.sum { |r| r[:pageviews] }
|
||||
}
|
||||
end
|
||||
|
||||
def show
|
||||
@page_path = params[:page_path].to_s
|
||||
redirect_to admin_analytics_path, alert: t("admin.analytics.missing_path") and return if @page_path.blank?
|
||||
|
||||
from = parse_date(params[:from]) || 7.days.ago.to_date
|
||||
to = parse_date(params[:to]) || Time.zone.today
|
||||
@device_tab_stats = device_tab_stats(@page_path, from, to)
|
||||
device = resolve_heatmap_device(@device_tab_stats, params[:device].presence)
|
||||
|
||||
@filters = {
|
||||
from: from,
|
||||
to: to,
|
||||
device: device,
|
||||
layer: params[:layer].to_s
|
||||
}
|
||||
|
||||
cells = AnalyticsPageCell.where(
|
||||
page_path: @page_path,
|
||||
day: @filters[:from]..@filters[:to],
|
||||
device: @filters[:device]
|
||||
)
|
||||
|
||||
@click_total = cells.sum(:click_count)
|
||||
@move_total = cells.sum(:move_count)
|
||||
@filters[:layer] =
|
||||
if %w[move click].include?(@filters[:layer])
|
||||
@filters[:layer]
|
||||
elsif @move_total.positive?
|
||||
"move"
|
||||
else
|
||||
"click"
|
||||
end
|
||||
|
||||
counter = @filters[:layer] == "click" ? :click_count : :move_count
|
||||
@cells = cells.group(:cell_x, :cell_y).sum(counter)
|
||||
@max_weight = @cells.values.max.to_i
|
||||
@total_points = @cells.values.sum
|
||||
|
||||
stats = AnalyticsPageStat.where(
|
||||
page_path: @page_path,
|
||||
day: @filters[:from]..@filters[:to],
|
||||
device: @filters[:device]
|
||||
)
|
||||
@pageviews = stats.sum(:pageview_count)
|
||||
@scroll_samples = stats.sum(:scroll_samples)
|
||||
@scroll_sum = stats.sum(:scroll_sum_pct)
|
||||
@max_scroll = stats.maximum(:max_scroll_pct).to_i
|
||||
@avg_scroll = @scroll_samples.positive? ? (@scroll_sum.to_f / @scroll_samples).round : 0
|
||||
@grid = AnalyticsPageCell::GRID_SIZE
|
||||
@snapshot = find_snapshot(@page_path, @filters[:device])
|
||||
end
|
||||
|
||||
def preview_enable
|
||||
Analytics::Suppress.enable!(cookies)
|
||||
redirect_to preview_return_to(params[:return_to]), notice: t("admin.analytics.preview.enabled")
|
||||
end
|
||||
|
||||
def preview_disable
|
||||
Analytics::Suppress.disable!(cookies)
|
||||
redirect_to admin_analytics_path, notice: t("admin.analytics.preview.disabled")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def analytics_preview_active?
|
||||
Analytics::Suppress.active?(cookies[Analytics::Suppress::COOKIE_NAME])
|
||||
end
|
||||
|
||||
def preview_return_to(value)
|
||||
path = value.to_s.strip
|
||||
return root_path if path.blank?
|
||||
return path if path.start_with?("/") && !path.start_with?("//")
|
||||
|
||||
admin_analytics_path
|
||||
end
|
||||
|
||||
def parse_date(value)
|
||||
return nil if value.blank?
|
||||
|
||||
Date.parse(value.to_s)
|
||||
rescue ArgumentError, TypeError
|
||||
nil
|
||||
end
|
||||
|
||||
def device_tab_stats(page_path, from, to)
|
||||
cell_totals = AnalyticsPageCell.where(page_path: page_path, day: from..to)
|
||||
.group(:device)
|
||||
.pluck(
|
||||
:device,
|
||||
Arel.sql("SUM(click_count)"),
|
||||
Arel.sql("SUM(move_count)")
|
||||
)
|
||||
cell_by_device = cell_totals.to_h { |device, clicks, moves| [device, { clicks: clicks.to_i, moves: moves.to_i }] }
|
||||
|
||||
pageview_totals = AnalyticsPageStat.where(page_path: page_path, day: from..to)
|
||||
.group(:device)
|
||||
.sum(:pageview_count)
|
||||
|
||||
AnalyticsEvent::DEVICES.index_with do |device|
|
||||
cells = cell_by_device[device] || { clicks: 0, moves: 0 }
|
||||
cells.merge(pageviews: pageview_totals[device].to_i)
|
||||
end
|
||||
end
|
||||
|
||||
def resolve_heatmap_device(tab_stats, requested)
|
||||
if requested.present? && AnalyticsEvent::DEVICES.include?(requested)
|
||||
return requested
|
||||
end
|
||||
|
||||
AnalyticsEvent::DEVICES.max_by do |device|
|
||||
stats = tab_stats[device]
|
||||
stats[:clicks] + stats[:moves] + stats[:pageviews]
|
||||
end
|
||||
end
|
||||
|
||||
def find_snapshot(page_path, device)
|
||||
return nil unless AnalyticsEvent::DEVICES.include?(device)
|
||||
|
||||
AnalyticsPageSnapshot.where(page_path: page_path, device: device)
|
||||
.order(captured_at: :desc)
|
||||
.detect { |snapshot| snapshot.image.attached? }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,76 @@
|
||||
module Admin
|
||||
class AnnouncementsController < Admin::BaseController
|
||||
before_action :set_announcement, only: %i[edit update destroy]
|
||||
|
||||
def index
|
||||
@announcements = AppAnnouncement.newest
|
||||
end
|
||||
|
||||
def new
|
||||
@announcement = AppAnnouncement.new(
|
||||
kind: "info",
|
||||
severity: "info",
|
||||
status: "draft",
|
||||
show_on_android: true,
|
||||
show_on_ios: true,
|
||||
show_on_web_public: true,
|
||||
show_on_web_private: true,
|
||||
dismissible: true
|
||||
)
|
||||
end
|
||||
|
||||
def create
|
||||
@announcement = AppAnnouncement.new(announcement_params)
|
||||
@announcement.created_by_admin = current_admin_account
|
||||
if @announcement.save
|
||||
redirect_to admin_announcements_path, notice: t("admin.flash.announcement_created")
|
||||
else
|
||||
flash.now[:alert] = @announcement.errors.full_messages.join(", ")
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def edit; end
|
||||
|
||||
def update
|
||||
if @announcement.update(announcement_params)
|
||||
redirect_to admin_announcements_path, notice: t("admin.flash.announcement_updated")
|
||||
else
|
||||
flash.now[:alert] = @announcement.errors.full_messages.join(", ")
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
@announcement.destroy!
|
||||
redirect_to admin_announcements_path, notice: t("admin.flash.announcement_destroyed")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_announcement
|
||||
@announcement = AppAnnouncement.find(params[:id])
|
||||
end
|
||||
|
||||
def announcement_params
|
||||
params.require(:app_announcement).permit(
|
||||
:kind, :severity, :status, :title, :body,
|
||||
:action_url, :action_label, :dismissible, :starts_at, :ends_at,
|
||||
:show_on_android, :show_on_ios, :show_on_web_public, :show_on_web_private,
|
||||
translations: {
|
||||
en: AppAnnouncement::COPY_KEYS,
|
||||
fr: AppAnnouncement::COPY_KEYS,
|
||||
de: AppAnnouncement::COPY_KEYS,
|
||||
es: AppAnnouncement::COPY_KEYS
|
||||
}
|
||||
).tap do |permitted|
|
||||
%i[dismissible show_on_android show_on_ios show_on_web_public show_on_web_private].each do |key|
|
||||
permitted[key] = ActiveModel::Type::Boolean.new.cast(permitted[key])
|
||||
end
|
||||
%i[starts_at ends_at action_url action_label].each do |key|
|
||||
permitted[key] = nil if permitted[key].blank?
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,27 @@
|
||||
module Admin
|
||||
class AuthController < Admin::BaseController
|
||||
skip_before_action :require_admin_login, only: %i[new create]
|
||||
# Same as public logout: tolerate stale CSRF after long-lived admin tabs.
|
||||
skip_before_action :verify_authenticity_token, only: :destroy
|
||||
|
||||
def new
|
||||
redirect_to admin_root_path if admin_logged_in?
|
||||
end
|
||||
|
||||
def create
|
||||
account = AdminAccount.find_by(username: params[:username]&.strip)
|
||||
if account&.authenticate(params[:password])
|
||||
session[:admin_account_id] = account.id
|
||||
redirect_to session.delete(:admin_return_to) || admin_root_path, notice: t("admin.flash.login_success")
|
||||
else
|
||||
flash.now[:alert] = t("admin.flash.invalid_credentials")
|
||||
render :new, status: :unauthorized
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
reset_session
|
||||
redirect_to admin_login_path, notice: t("admin.flash.logout_success")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,52 @@
|
||||
module Admin
|
||||
class BaseController < ActionController::Base
|
||||
layout "admin"
|
||||
protect_from_forgery with: :exception
|
||||
|
||||
before_action :set_admin_locale
|
||||
before_action :require_admin_login
|
||||
|
||||
include ::AdminHelper
|
||||
helper ApplicationHelper
|
||||
helper RecordingsArchiveHelper
|
||||
helper_method :current_admin_account, :admin_logged_in?, :current_locale, :language_options, :current_language_option
|
||||
|
||||
private
|
||||
|
||||
def set_admin_locale
|
||||
I18n.locale = LocaleResolver.resolve(
|
||||
cookie_jar: request.cookie_jar,
|
||||
accept_language: request.get_header("HTTP_ACCEPT_LANGUAGE")
|
||||
)
|
||||
end
|
||||
|
||||
def current_locale
|
||||
I18n.locale
|
||||
end
|
||||
|
||||
def language_options
|
||||
LocaleResolver.language_options
|
||||
end
|
||||
|
||||
def current_language_option
|
||||
LocaleResolver.current_language_option
|
||||
end
|
||||
|
||||
def require_admin_login
|
||||
return if admin_logged_in?
|
||||
|
||||
session[:admin_return_to] = request.fullpath unless request.path == admin_login_path
|
||||
redirect_to admin_login_path, alert: t("admin.flash.login_required")
|
||||
end
|
||||
|
||||
def current_admin_account
|
||||
return unless session[:admin_account_id]
|
||||
|
||||
@current_admin_account ||= AdminAccount.find_by(id: session[:admin_account_id])
|
||||
end
|
||||
|
||||
def admin_logged_in?
|
||||
current_admin_account.present?
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,59 @@
|
||||
module Admin
|
||||
class BillingController < BaseController
|
||||
def index
|
||||
@pending_payments = pending_scope.recent
|
||||
@pending_transfers = transfer_scope
|
||||
@completed_payments = Billing::Payment.with_invoice_pdf.includes(:club, :invoice).recent.limit(40)
|
||||
@filter_club = Club.find_by(id: params[:club_id]) if params[:club_id].present?
|
||||
@clubs = Club.order(:name)
|
||||
end
|
||||
|
||||
def attach_pdf
|
||||
payment = Billing::Payment.find(params[:payment_id])
|
||||
Billing::AttachPaymentInvoice.call(payment: payment, pdf: params[:pdf])
|
||||
redirect_to admin_billing_path(billing_redirect_params(payment)),
|
||||
notice: t("admin.flash.invoice_uploaded", email: payment.club.billing_email)
|
||||
rescue Billing::AttachPaymentInvoice::Error, Billing::IssueInvoice::Error => e
|
||||
payment ||= Billing::Payment.find_by(id: params[:payment_id])
|
||||
redirect_to admin_billing_path(payment ? billing_redirect_params(payment) : {}),
|
||||
alert: e.message
|
||||
end
|
||||
|
||||
def confirm_transfer
|
||||
order = Billing::TransferOrder.find(params[:id])
|
||||
Billing::ConfirmBankTransfer.call(
|
||||
order: order,
|
||||
admin: current_admin_account,
|
||||
pdf: params[:pdf]
|
||||
)
|
||||
redirect_to admin_billing_path(club_id: order.club_id),
|
||||
notice: t("admin.flash.transfer_confirmed", plan: order.plan.name, club: order.club.name)
|
||||
rescue Billing::ConfirmBankTransfer::Error, Billing::AttachPaymentInvoice::Error, Billing::IssueInvoice::Error => e
|
||||
redirect_to admin_billing_path, alert: e.message
|
||||
end
|
||||
|
||||
def cancel_transfer
|
||||
order = Billing::TransferOrder.find(params[:id])
|
||||
order.cancel!
|
||||
redirect_to admin_billing_path(club_id: order.club_id), notice: t("admin.flash.transfer_cancelled")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def pending_scope
|
||||
scope = Billing::Payment.awaiting_invoice_pdf.includes(:club, invoice: { pdf_attachment: :blob })
|
||||
scope = scope.where(club_id: params[:club_id]) if params[:club_id].present?
|
||||
scope
|
||||
end
|
||||
|
||||
def transfer_scope
|
||||
scope = Billing::TransferOrder.awaiting_payment.includes(:club, :requested_by_user)
|
||||
scope = scope.where(club_id: params[:club_id]) if params[:club_id].present?
|
||||
scope
|
||||
end
|
||||
|
||||
def billing_redirect_params(payment)
|
||||
{ club_id: payment.club_id, anchor: "payment-#{payment.id}" }.compact
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,84 @@
|
||||
module Admin
|
||||
class BillingInvoicesController < BaseController
|
||||
before_action :set_club
|
||||
before_action :set_invoice, only: %i[edit update]
|
||||
|
||||
def index
|
||||
redirect_to admin_billing_path(club_id: @club.id)
|
||||
end
|
||||
|
||||
def new
|
||||
redirect_to admin_billing_path(club_id: @club.id), alert: t("admin.flash.invoice_upload_hint")
|
||||
end
|
||||
|
||||
def create
|
||||
@invoice = @club.billing_invoices.build(invoice_params)
|
||||
@invoice.source = "manual"
|
||||
@invoice.status = "draft"
|
||||
|
||||
if @invoice.save
|
||||
redirect_to edit_admin_club_billing_invoice_path(@club, @invoice),
|
||||
notice: t("admin.flash.invoice_draft_created")
|
||||
else
|
||||
@payment = @invoice.billing_payment
|
||||
flash.now[:alert] = @invoice.errors.full_messages.join(", ")
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def edit
|
||||
@payment = @invoice.billing_payment
|
||||
end
|
||||
|
||||
def update
|
||||
@invoice.assign_attributes(invoice_params.except(:pdf))
|
||||
|
||||
if issuing?
|
||||
Billing::IssueInvoice.call(invoice: @invoice, pdf: params.dig(:billing_invoice, :pdf))
|
||||
redirect_to admin_billing_path(club_id: @club.id),
|
||||
notice: t("admin.flash.invoice_issued", number: @invoice.number, email: @club.billing_email)
|
||||
elsif @invoice.save
|
||||
redirect_to admin_billing_path(club_id: @club.id), notice: t("admin.flash.invoice_updated", number: @invoice.number)
|
||||
else
|
||||
@payment = @invoice.billing_payment
|
||||
flash.now[:alert] = @invoice.errors.full_messages.join(", ")
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
rescue Billing::IssueInvoice::Error => e
|
||||
@payment = @invoice.billing_payment
|
||||
flash.now[:alert] = e.message
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_club
|
||||
@club = Club.find(params[:club_id])
|
||||
end
|
||||
|
||||
def set_invoice
|
||||
@invoice = @club.billing_invoices.find(params[:id])
|
||||
end
|
||||
|
||||
def issuing?
|
||||
params[:commit_action].to_s == "issue"
|
||||
end
|
||||
|
||||
def invoice_params
|
||||
params.require(:billing_invoice).permit(
|
||||
:number,
|
||||
:issued_on,
|
||||
:amount_cents,
|
||||
:amount_euros,
|
||||
:currency,
|
||||
:billing_payment_id,
|
||||
:notes,
|
||||
:pdf
|
||||
).tap do |p|
|
||||
if p[:amount_euros].present?
|
||||
p[:amount_cents] = (p.delete(:amount_euros).to_f * 100).round
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,15 @@
|
||||
module Admin
|
||||
class ClubRecordingsController < BaseController
|
||||
include Recordings::ClubArchiveActions
|
||||
|
||||
private
|
||||
|
||||
def archive_namespace
|
||||
:admin
|
||||
end
|
||||
|
||||
def authorize_recording_management!
|
||||
# Admin può gestire tutti i replay della società senza vincoli di ruolo utente.
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,159 @@
|
||||
module Admin
|
||||
class ClubsController < BaseController
|
||||
before_action :set_club, only: %i[show edit update grant_comped revoke_comped set_quote revoke_quote]
|
||||
|
||||
def index
|
||||
@clubs = Club.includes(:teams, :billing_quote, { club_memberships: :user }, subscription: %i[plan admin_comped_by])
|
||||
.order(:name)
|
||||
end
|
||||
|
||||
def show
|
||||
load_show_context
|
||||
end
|
||||
|
||||
def edit
|
||||
load_edit_context
|
||||
end
|
||||
|
||||
def update
|
||||
Admin::UpdateClubData.call(
|
||||
club: @club,
|
||||
club_attrs: club_update_params,
|
||||
owner_attrs: owner_params,
|
||||
staff_attrs: staff_params,
|
||||
invitation_attrs: invitation_params,
|
||||
team_attrs: team_params
|
||||
)
|
||||
redirect_to admin_club_path(@club), notice: t("admin.flash.club_updated", club: @club.name)
|
||||
rescue Admin::UpdateClubData::Error, ActiveRecord::RecordInvalid => e
|
||||
flash.now[:alert] = e.message
|
||||
load_edit_context
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def grant_comped
|
||||
Billing::AdminCompedSubscription.grant(
|
||||
club: @club,
|
||||
plan_slug: params.require(:plan_slug),
|
||||
reason: params[:reason],
|
||||
admin: current_admin_account
|
||||
)
|
||||
redirect_back_or_club notice: t("admin.flash.comped_granted", plan: Plan[params[:plan_slug]].name, club: @club.name)
|
||||
rescue Billing::AdminCompedSubscription::Error, ActiveRecord::RecordInvalid => e
|
||||
redirect_back_or_club alert: e.message
|
||||
end
|
||||
|
||||
def revoke_comped
|
||||
Billing::AdminCompedSubscription.revoke(club: @club, admin: current_admin_account)
|
||||
redirect_back_or_club notice: t("admin.flash.comped_revoked", club: @club.name)
|
||||
rescue Billing::AdminCompedSubscription::Error => e
|
||||
redirect_back_or_club alert: e.message
|
||||
end
|
||||
|
||||
def set_quote
|
||||
quote = Billing::SetClubQuote.upsert(
|
||||
club: @club,
|
||||
plan_slug: params.require(:plan_slug),
|
||||
interval: params[:interval],
|
||||
amount_euros: params[:amount_euros],
|
||||
note: params[:note],
|
||||
admin: current_admin_account
|
||||
)
|
||||
redirect_back_or_club notice: t(
|
||||
"admin.flash.quote_saved",
|
||||
club: @club.name,
|
||||
plan: quote.plan.name,
|
||||
amount: quote.formatted_amount
|
||||
)
|
||||
rescue Billing::SetClubQuote::Error, ActionController::ParameterMissing => e
|
||||
redirect_back_or_club alert: e.message
|
||||
end
|
||||
|
||||
def revoke_quote
|
||||
Billing::SetClubQuote.revoke(club: @club, admin: current_admin_account)
|
||||
redirect_back_or_club notice: t("admin.flash.quote_revoked", club: @club.name)
|
||||
rescue Billing::SetClubQuote::Error => e
|
||||
redirect_back_or_club alert: e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_club
|
||||
@club = Club.includes(club_memberships: :user).find(params[:id])
|
||||
end
|
||||
|
||||
def load_show_context
|
||||
@subscription = @club.subscription || @club.build_subscription(plan: Plan["free"], status: "active")
|
||||
@plans = Plan.ordered.reject { |p| p.slug == "free" }
|
||||
@teams = @club.teams.order(:name)
|
||||
@quote = @club.active_billing_quote
|
||||
@concurrency_violations = StreamConcurrencyViolation.for_club(@club.id).recent.limit(20)
|
||||
end
|
||||
|
||||
def load_edit_context
|
||||
@teams = @club.teams.includes(:user_teams, :team_invitations).order(:name)
|
||||
@owner = @club.owner
|
||||
@staff_users = User.joins(:user_teams)
|
||||
.where(user_teams: { team_id: @club.teams.select(:id) })
|
||||
.distinct
|
||||
.order(:email)
|
||||
.to_a
|
||||
@pending_invitations = TeamInvitation.pending
|
||||
.where(team_id: @club.teams.select(:id))
|
||||
.includes(:team)
|
||||
.order(:email)
|
||||
@sport_options = Sports::Catalog.as_api_list.map { |entry| [entry[:label], entry[:key]] }
|
||||
end
|
||||
|
||||
def club_update_params
|
||||
params.require(:club).permit(
|
||||
:name, :sport, :logo_url, :primary_color, :secondary_color,
|
||||
:billing_entity_type, :billing_legal_name, :billing_vat_number, :billing_fiscal_code,
|
||||
:billing_email, :billing_phone, :billing_address_line, :billing_city, :billing_province,
|
||||
:billing_postal_code, :billing_country, :billing_recipient_code, :billing_pec
|
||||
)
|
||||
end
|
||||
|
||||
def owner_params
|
||||
params.fetch(:owner, {}).permit(:name, :email).to_h.symbolize_keys
|
||||
end
|
||||
|
||||
def staff_params
|
||||
raw = params[:staff_users]
|
||||
return {} if raw.blank?
|
||||
|
||||
raw.permit!.to_h.each_with_object({}) do |(user_id, attrs), acc|
|
||||
next unless attrs.is_a?(Hash)
|
||||
|
||||
acc[user_id] = attrs.slice("name", "email").symbolize_keys
|
||||
end
|
||||
end
|
||||
|
||||
def invitation_params
|
||||
raw = params[:invitations]
|
||||
return {} if raw.blank?
|
||||
|
||||
raw.permit!.to_h.each_with_object({}) do |(invitation_id, attrs), acc|
|
||||
next unless attrs.is_a?(Hash)
|
||||
|
||||
acc[invitation_id] = attrs.slice("email").symbolize_keys
|
||||
end
|
||||
end
|
||||
|
||||
def team_params
|
||||
raw = params[:teams]
|
||||
return {} if raw.blank?
|
||||
|
||||
raw.permit!.to_h.each_with_object({}) do |(team_id, attrs), acc|
|
||||
next unless attrs.is_a?(Hash)
|
||||
|
||||
acc[team_id] = attrs.slice("name", "sport").symbolize_keys
|
||||
end
|
||||
end
|
||||
|
||||
def redirect_back_or_club(notice: nil, alert: nil)
|
||||
target = params[:return_to].presence || admin_club_path(@club)
|
||||
redirect_to target, notice: notice, alert: alert
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,68 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Admin
|
||||
class CostEntriesController < Admin::BaseController
|
||||
before_action :set_entry, only: %i[edit update destroy]
|
||||
|
||||
def new
|
||||
@entry = PlatformCostEntry.new(
|
||||
month: parse_month(params[:month]) || Time.zone.today.beginning_of_month,
|
||||
label: PlatformCostEntry::DEFAULT_LABEL
|
||||
)
|
||||
end
|
||||
|
||||
def create
|
||||
@entry = PlatformCostEntry.new(entry_attributes)
|
||||
if @entry.save
|
||||
redirect_to admin_costs_path(month: month_param(@entry.month)), notice: t("admin.flash.cost_entry_created")
|
||||
else
|
||||
flash.now[:alert] = @entry.errors.full_messages.join(", ")
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def edit; end
|
||||
|
||||
def update
|
||||
if @entry.update(entry_attributes)
|
||||
redirect_to admin_costs_path(month: month_param(@entry.month)), notice: t("admin.flash.cost_entry_updated")
|
||||
else
|
||||
flash.now[:alert] = @entry.errors.full_messages.join(", ")
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
month = @entry.month
|
||||
@entry.destroy!
|
||||
redirect_to admin_costs_path(month: month_param(month)), notice: t("admin.flash.cost_entry_destroyed")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_entry
|
||||
@entry = PlatformCostEntry.find(params[:id])
|
||||
end
|
||||
|
||||
def entry_attributes
|
||||
attrs = params.require(:platform_cost_entry).permit(:month, :label, :amount_euros, :notes)
|
||||
if attrs[:amount_euros].present?
|
||||
attrs[:amount_cents] = Billing::EuroAmount.to_cents(attrs.delete(:amount_euros))
|
||||
end
|
||||
attrs[:notes] = nil if attrs[:notes].blank?
|
||||
attrs
|
||||
end
|
||||
|
||||
def parse_month(value)
|
||||
return nil if value.blank?
|
||||
|
||||
Date.strptime(value.to_s, "%Y-%m").beginning_of_month
|
||||
rescue ArgumentError, TypeError
|
||||
nil
|
||||
end
|
||||
|
||||
def month_param(date)
|
||||
date.strftime("%Y-%m")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,30 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Admin
|
||||
class CostsController < Admin::BaseController
|
||||
def index
|
||||
@month = parse_month(params[:month]) || Time.zone.today.beginning_of_month
|
||||
analytics = Admin::CostAnalytics.new(month: @month)
|
||||
@summary = analytics.summary
|
||||
@trend = analytics.trend
|
||||
@clubs = analytics.club_breakdown
|
||||
@entries = PlatformCostEntry.for_month(@month).ordered
|
||||
@month_options = month_options(@month)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def parse_month(value)
|
||||
return nil if value.blank?
|
||||
|
||||
Date.strptime(value.to_s, "%Y-%m").beginning_of_month
|
||||
rescue ArgumentError, TypeError
|
||||
nil
|
||||
end
|
||||
|
||||
def month_options(selected)
|
||||
start = selected - 23.months
|
||||
(0..23).map { |i| start + i.months }.reverse
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,36 @@
|
||||
module Admin
|
||||
class DashboardController < Admin::BaseController
|
||||
def index
|
||||
@stats = DashboardStats.new.call
|
||||
@host = HostMetrics.new.sample!
|
||||
@active_sessions = StreamSession
|
||||
.where(status: DashboardStats::ACTIVE_STATUSES)
|
||||
.includes(:stream_node, match: :team)
|
||||
.order(started_at: :desc)
|
||||
@teams = Team.includes(:matches).order(:name).limit(8)
|
||||
@recent_concurrency_violations = StreamConcurrencyViolation.recent.limit(8)
|
||||
@concurrency_violation_lookback = StreamConcurrencyViolation.lookback.count
|
||||
end
|
||||
|
||||
def metrics
|
||||
host = HostMetrics.new.sample!
|
||||
stats = DashboardStats.new.call
|
||||
render json: {
|
||||
host: host,
|
||||
stats: stats,
|
||||
ops_summary: ops_summary,
|
||||
at: Time.current.iso8601
|
||||
}
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def ops_summary
|
||||
{
|
||||
open_critical: Ops::Incident.critical_open.count,
|
||||
open_warning: Ops::Incident.open.where(severity: "warning").count,
|
||||
open_total: Ops::Incident.open.count
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,11 @@
|
||||
module Admin
|
||||
class LocalesController < BaseController
|
||||
skip_before_action :require_admin_login
|
||||
|
||||
def update
|
||||
locale = LocaleResolver.persist!(cookies, params[:locale])
|
||||
I18n.locale = locale
|
||||
redirect_back fallback_location: admin_root_path
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,37 @@
|
||||
module Admin
|
||||
class OpsController < Admin::BaseController
|
||||
def index
|
||||
@open_incidents = Ops::Incident.open.recent.limit(50)
|
||||
@resolved_incidents = Ops::Incident.where(status: "resolved").since(30.days.ago).recent.limit(30)
|
||||
@summary = ops_summary
|
||||
end
|
||||
|
||||
def acknowledge
|
||||
incident = Ops::Incident.find(params[:id])
|
||||
incident.acknowledge!
|
||||
redirect_to admin_ops_path, notice: t("admin.flash.ops_acknowledged")
|
||||
end
|
||||
|
||||
def resolve
|
||||
incident = Ops::Incident.find(params[:id])
|
||||
incident.resolve!
|
||||
redirect_to admin_ops_path, notice: t("admin.flash.ops_resolved")
|
||||
end
|
||||
|
||||
def mute
|
||||
incident = Ops::Incident.find(params[:id])
|
||||
incident.mute!(duration: 24.hours)
|
||||
redirect_to admin_ops_path, notice: t("admin.flash.ops_muted")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def ops_summary
|
||||
{
|
||||
open_critical: Ops::Incident.critical_open.count,
|
||||
open_warning: Ops::Incident.open.where(severity: "warning").count,
|
||||
open_total: Ops::Incident.open.count
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,40 @@
|
||||
module Admin
|
||||
class PasswordsController < Admin::BaseController
|
||||
def edit
|
||||
end
|
||||
|
||||
def update
|
||||
unless current_admin_account.authenticate(params[:current_password])
|
||||
flash.now[:alert] = t("admin.flash.password_current_incorrect")
|
||||
return render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
if params[:password] != params[:password_confirmation]
|
||||
flash.now[:alert] = t("admin.flash.password_mismatch")
|
||||
return render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
if (code = PasswordComplexity.violation(params[:password]))
|
||||
key = case code
|
||||
when :blank, :too_short then :password_too_short
|
||||
when :too_long then :password_too_long
|
||||
else :password_too_weak
|
||||
end
|
||||
flash.now[:alert] = t("admin.flash.#{key}")
|
||||
return render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
if PasswordComplexity.same_as_current?(current_admin_account, params[:password])
|
||||
flash.now[:alert] = t("admin.flash.password_same_as_current")
|
||||
return render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
if current_admin_account.update(password: params[:password])
|
||||
redirect_to admin_root_path, notice: t("admin.flash.password_updated")
|
||||
else
|
||||
flash.now[:alert] = current_admin_account.errors.full_messages.to_sentence
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,123 @@
|
||||
module Admin
|
||||
class SessionsController < Admin::BaseController
|
||||
def index
|
||||
@filters = session_filters
|
||||
scope = filtered_sessions
|
||||
@total_count = scope.count
|
||||
@sessions = scope
|
||||
.includes(:stream_node, :user, match: { team: :club })
|
||||
.order(Arel.sql("COALESCE(stream_sessions.started_at, stream_sessions.created_at) DESC"))
|
||||
.limit(100)
|
||||
@clubs = Club.order(:name)
|
||||
@nodes = StreamNode.order(:slug)
|
||||
end
|
||||
|
||||
def show
|
||||
@session = StreamSession
|
||||
.includes(:stream_node, :user, :device_states, :recording, match: { team: :club })
|
||||
.find(params[:id])
|
||||
@events = @session.stream_events.recent.limit(100)
|
||||
@club = @session.match.team.club
|
||||
@concurrency_violations = StreamConcurrencyViolation.for_session(@session.id).recent.limit(20)
|
||||
end
|
||||
|
||||
def stop
|
||||
@session = StreamSession.find(params[:id])
|
||||
if @session.terminal?
|
||||
redirect_to admin_session_path(@session), alert: t("admin.flash.session_already_terminated", status: @session.status)
|
||||
return
|
||||
end
|
||||
|
||||
Sessions::Stop.new(@session).call
|
||||
redirect_to admin_session_path(@session), notice: t("admin.flash.session_stopped")
|
||||
rescue StandardError => e
|
||||
Rails.logger.error("[admin] stop session #{@session.id}: #{e.class} #{e.message}")
|
||||
redirect_to admin_session_path(@session), alert: t("admin.flash.session_stop_error", error: e.message)
|
||||
end
|
||||
|
||||
def regia_link
|
||||
@session = StreamSession.find(params[:id])
|
||||
if @session.terminal?
|
||||
redirect_to admin_session_path(@session), alert: t("admin.flash.session_terminated_no_regia")
|
||||
return
|
||||
end
|
||||
|
||||
access = Sessions::RegiaAccess.new(@session)
|
||||
token = access.issue_token!
|
||||
redirect_to admin_session_path(@session),
|
||||
notice: t("admin.flash.session_regia_generated"),
|
||||
flash: {
|
||||
regia_url: access.url(token),
|
||||
regia_expires_at: @session.regia_token_expires_at&.iso8601
|
||||
}
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def session_filters
|
||||
{
|
||||
q: params[:q].to_s.strip.presence,
|
||||
status: params[:status].to_s.strip.presence,
|
||||
platform: params[:platform].to_s.strip.presence,
|
||||
club_id: params[:club_id].to_s.strip.presence,
|
||||
stream_node_id: params[:stream_node_id].to_s.strip.presence,
|
||||
from: params[:from].to_s.strip.presence,
|
||||
to: params[:to].to_s.strip.presence
|
||||
}
|
||||
end
|
||||
|
||||
def filtered_sessions
|
||||
scope = StreamSession.left_outer_joins(match: { team: :club })
|
||||
|
||||
if @filters[:q].present?
|
||||
term = "%#{ActiveRecord::Base.sanitize_sql_like(@filters[:q])}%"
|
||||
scope = scope.where(
|
||||
"teams.name ILIKE :term OR matches.opponent_name ILIKE :term OR clubs.name ILIKE :term OR matches.location ILIKE :term",
|
||||
term: term
|
||||
)
|
||||
end
|
||||
|
||||
if @filters[:status].present? && StreamSession::STATUSES.include?(@filters[:status])
|
||||
scope = scope.where(stream_sessions: { status: @filters[:status] })
|
||||
end
|
||||
if @filters[:platform].present? && StreamSession::LIVE_PLATFORMS.include?(@filters[:platform])
|
||||
scope = scope.where(stream_sessions: { platform: @filters[:platform] })
|
||||
end
|
||||
if @filters[:club_id].present?
|
||||
scope = scope.where(teams: { club_id: @filters[:club_id] })
|
||||
end
|
||||
if @filters[:stream_node_id].present?
|
||||
node = StreamNode.find_by(id: @filters[:stream_node_id])
|
||||
if node
|
||||
scope = scope.where(
|
||||
"stream_sessions.stream_node_id = :id OR stream_sessions.ingest_slug = :slug",
|
||||
id: node.id,
|
||||
slug: node.slug
|
||||
)
|
||||
end
|
||||
end
|
||||
if (from_time = parse_filter_date(@filters[:from], end_of_day: false))
|
||||
scope = scope.where(
|
||||
"COALESCE(stream_sessions.started_at, stream_sessions.created_at) >= ?",
|
||||
from_time
|
||||
)
|
||||
end
|
||||
if (to_time = parse_filter_date(@filters[:to], end_of_day: true))
|
||||
scope = scope.where(
|
||||
"COALESCE(stream_sessions.started_at, stream_sessions.created_at) <= ?",
|
||||
to_time
|
||||
)
|
||||
end
|
||||
scope
|
||||
end
|
||||
|
||||
def parse_filter_date(value, end_of_day:)
|
||||
return nil if value.blank?
|
||||
|
||||
date = Date.parse(value)
|
||||
end_of_day ? date.end_of_day : date.beginning_of_day
|
||||
rescue ArgumentError, TypeError
|
||||
nil
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,25 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Admin
|
||||
class StreamConcurrencyViolationsController < Admin::BaseController
|
||||
def index
|
||||
@filters = {
|
||||
q: params[:q].to_s.strip.presence,
|
||||
devices_differ: params[:devices_differ].to_s == "1"
|
||||
}
|
||||
scope = StreamConcurrencyViolation.recent
|
||||
if @filters[:q]
|
||||
term = "%#{ActiveRecord::Base.sanitize_sql_like(@filters[:q])}%"
|
||||
scope = scope.where(
|
||||
"user_email ILIKE :term OR user_name ILIKE :term OR occupying_club_name ILIKE :term OR attempted_club_name ILIKE :term OR occupying_match_label ILIKE :term OR attempted_match_label ILIKE :term",
|
||||
term: term
|
||||
)
|
||||
end
|
||||
scope = scope.two_devices if @filters[:devices_differ]
|
||||
@total_count = scope.count
|
||||
@violations = scope.limit(200)
|
||||
@lookback_count = StreamConcurrencyViolation.lookback.count
|
||||
@two_devices_count = StreamConcurrencyViolation.lookback.two_devices.count
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,67 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Admin
|
||||
class StreamNodesController < Admin::BaseController
|
||||
def index
|
||||
Streams::NodeRegistry.ensure_home_from_env!
|
||||
@nodes = StreamNode.order(:role, :slug)
|
||||
@dns_provider = ENV.fetch("STREAM_DNS_PROVIDER", "lab")
|
||||
@cloud_provider = ENV.fetch("STREAM_CLOUD_PROVIDER", "local_lab")
|
||||
@lab_hosts = lab_dns_snippet
|
||||
@hetzner_configured = ENV["HCLOUD_TOKEN"].present?
|
||||
@autoscale_metrics = Streams::Autoscaler.metrics
|
||||
end
|
||||
|
||||
def create
|
||||
kind = params[:kind].to_s
|
||||
node =
|
||||
if kind == "cloud"
|
||||
Streams::NodeProvisioner.new.provision_cloud!
|
||||
else
|
||||
Streams::NodeProvisioner.new.provision_lab!
|
||||
end
|
||||
redirect_to admin_stream_nodes_path,
|
||||
notice: t("admin.flash.stream_node_created", slug: node.slug)
|
||||
rescue Streams::NodeProvisioner::Error, Streams::CloudProviders::Error, Streams::DnsProviders::Error,
|
||||
KeyError => e
|
||||
redirect_to admin_stream_nodes_path, alert: e.message
|
||||
end
|
||||
|
||||
def drain
|
||||
node = StreamNode.find(params[:id])
|
||||
Streams::NodeProvisioner.new.drain!(node)
|
||||
redirect_to admin_stream_nodes_path, notice: t("admin.flash.stream_node_draining", slug: node.slug)
|
||||
rescue Streams::NodeProvisioner::Error => e
|
||||
redirect_to admin_stream_nodes_path, alert: e.message
|
||||
end
|
||||
|
||||
def destroy
|
||||
node = StreamNode.find(params[:id])
|
||||
Streams::NodeProvisioner.new.decommission!(node)
|
||||
redirect_to admin_stream_nodes_path, notice: t("admin.flash.stream_node_destroyed", slug: node.slug)
|
||||
rescue Streams::NodeProvisioner::BusyError, Streams::NodeProvisioner::Error,
|
||||
Streams::CloudProviders::Error, Streams::DnsProviders::Error => e
|
||||
redirect_to admin_stream_nodes_path, alert: e.message
|
||||
end
|
||||
|
||||
def kill_switch
|
||||
Streams::Autoscaler.engage_kill_switch!
|
||||
redirect_to admin_stream_nodes_path, notice: t("admin.flash.autoscale_kill_on")
|
||||
end
|
||||
|
||||
def clear_kill_switch
|
||||
Streams::Autoscaler.clear_kill_switch!
|
||||
redirect_to admin_stream_nodes_path, notice: t("admin.flash.autoscale_kill_off")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def lab_dns_snippet
|
||||
return "" unless @dns_provider == "lab"
|
||||
|
||||
Streams::DnsProviders::Lab.new.hosts_file_snippet
|
||||
rescue Redis::BaseError
|
||||
""
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,12 @@
|
||||
module Admin
|
||||
class TeamsController < Admin::BaseController
|
||||
def index
|
||||
redirect_to admin_clubs_path, status: :moved_permanently
|
||||
end
|
||||
|
||||
def show
|
||||
@team = Team.find(params[:id])
|
||||
@matches = @team.matches.order(scheduled_at: :desc)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,13 @@
|
||||
module Admin
|
||||
class YoutubeController < Admin::BaseController
|
||||
def platform
|
||||
if ENV["YOUTUBE_CLIENT_ID"].blank?
|
||||
redirect_to admin_root_path, alert: t("admin.flash.youtube_not_configured")
|
||||
return
|
||||
end
|
||||
|
||||
state = Youtube::OauthState.for_platform(admin_id: current_admin_account.id)
|
||||
redirect_to Youtube::OauthUrl.build(state: state), allow_other_host: true
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,45 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Analytics
|
||||
class EventsController < ActionController::API
|
||||
include ActionController::Cookies
|
||||
|
||||
def create
|
||||
if analytics_suppressed?
|
||||
return render json: { accepted: 0, rejected: 0, suppressed: true }, status: :accepted
|
||||
end
|
||||
|
||||
payload = parse_payload
|
||||
result = Analytics::Ingest.new(events: payload, remote_ip: request.remote_ip).call
|
||||
|
||||
if result.rate_limited
|
||||
return head :too_many_requests
|
||||
end
|
||||
|
||||
render json: { accepted: result.accepted, rejected: result.rejected }, status: :accepted
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def analytics_suppressed?
|
||||
Analytics::Suppress.active?(cookies[Analytics::Suppress::COOKIE_NAME])
|
||||
end
|
||||
|
||||
def parse_payload
|
||||
body = request.request_parameters
|
||||
return body["events"] if body.is_a?(Hash) && body["events"].is_a?(Array)
|
||||
return body if body.is_a?(Array)
|
||||
|
||||
raw = request.raw_post
|
||||
return [] if raw.blank?
|
||||
|
||||
parsed = JSON.parse(raw)
|
||||
return parsed["events"] if parsed.is_a?(Hash) && parsed["events"].is_a?(Array)
|
||||
return parsed if parsed.is_a?(Array)
|
||||
|
||||
[]
|
||||
rescue JSON::ParserError
|
||||
[]
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,33 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Analytics
|
||||
class SnapshotsController < ActionController::API
|
||||
include ActionController::Cookies
|
||||
|
||||
def create
|
||||
if analytics_suppressed?
|
||||
return render json: { ok: true, skipped: true, suppressed: true }, status: :accepted
|
||||
end
|
||||
|
||||
result = Analytics::SnapshotIngest.new(
|
||||
path: params[:path] || params[:page_path],
|
||||
device: params[:device],
|
||||
width: params[:width],
|
||||
height: params[:height],
|
||||
image: params[:image],
|
||||
remote_ip: request.remote_ip
|
||||
).call
|
||||
|
||||
return head :too_many_requests if result.rate_limited
|
||||
return render json: { ok: false, error: result.error }, status: :unprocessable_content unless result.ok
|
||||
|
||||
render json: { ok: true, skipped: result.skipped }, status: :accepted
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def analytics_suppressed?
|
||||
Analytics::Suppress.active?(cookies[Analytics::Suppress::COOKIE_NAME])
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,60 @@
|
||||
module Api
|
||||
module V1
|
||||
class AccountsController < ApplicationController
|
||||
def show
|
||||
render json: user_json(current_user)
|
||||
end
|
||||
|
||||
def update
|
||||
name = params[:name].to_s.strip
|
||||
if name.blank?
|
||||
return render json: { error: I18n.t("flash.accounts.name_required") }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
if current_user.update(name: name)
|
||||
render json: user_json(current_user)
|
||||
else
|
||||
render json: { error: current_user.errors.full_messages.join(", ") }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def password
|
||||
result = Users::ChangePassword.call(
|
||||
user: current_user,
|
||||
current_password: params[:current_password],
|
||||
password: params[:password],
|
||||
password_confirmation: params[:password_confirmation]
|
||||
)
|
||||
|
||||
unless result.ok?
|
||||
return render json: { error: password_error_message(result.error) }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
render json: { message: I18n.t("flash.accounts.password_updated") }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def user_json(user)
|
||||
{
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role
|
||||
}
|
||||
end
|
||||
|
||||
def password_error_message(code)
|
||||
case code
|
||||
when :current_incorrect then I18n.t("flash.accounts.password_current_incorrect")
|
||||
when :too_short then I18n.t("flash.accounts.password_too_short")
|
||||
when :too_long then I18n.t("flash.accounts.password_too_long")
|
||||
when :too_weak then I18n.t("flash.accounts.password_too_weak")
|
||||
when :same_as_current then I18n.t("flash.accounts.password_same_as_current")
|
||||
when :mismatch then I18n.t("flash.accounts.password_mismatch")
|
||||
else I18n.t("flash.accounts.password_update_failed")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,13 @@
|
||||
module Api
|
||||
module V1
|
||||
class AnnouncementsController < BaseController
|
||||
skip_before_action :authenticate_request!
|
||||
|
||||
def index
|
||||
platform = params[:platform].to_s.presence
|
||||
announcements = AppAnnouncement.for_platform(platform).newest
|
||||
render json: announcements.map { |item| item.as_api_json(platform: platform) }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,72 @@
|
||||
module Api
|
||||
module V1
|
||||
class AuthController < ApplicationController
|
||||
skip_before_action :authenticate_request!, only: %i[login refresh register forgot_password]
|
||||
|
||||
def register
|
||||
user = User.new(
|
||||
email: params[:email]&.downcase,
|
||||
name: params[:name],
|
||||
password: params[:password],
|
||||
role: "coach"
|
||||
)
|
||||
if user.save
|
||||
render json: token_response(user), status: :created
|
||||
else
|
||||
render json: { error: user.errors.full_messages.join(", ") }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def login
|
||||
user = User.find_by(email: params[:email]&.downcase)
|
||||
if user&.authenticate(params[:password])
|
||||
render json: token_response(user), status: :ok
|
||||
else
|
||||
render json: { error: I18n.t("flash.sessions.invalid_credentials") }, status: :unauthorized
|
||||
end
|
||||
end
|
||||
|
||||
def logout
|
||||
render json: { message: I18n.t("flash.sessions.logged_out") }
|
||||
end
|
||||
|
||||
def refresh
|
||||
payload = JsonWebToken.decode(params[:refresh_token] || bearer_token)
|
||||
user = User.find_by(id: payload&.dig(:user_id))
|
||||
return render json: { error: I18n.t("flash.sessions.invalid_token") }, status: :unauthorized unless user
|
||||
|
||||
render json: token_response(user)
|
||||
end
|
||||
|
||||
def me
|
||||
render json: user_json(current_user)
|
||||
end
|
||||
|
||||
def forgot_password
|
||||
Users::RequestPasswordReset.call(email: params[:email])
|
||||
render json: {
|
||||
message: I18n.t("flash.password_resets.email_sent")
|
||||
}
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def token_response(user)
|
||||
{
|
||||
user: user_json(user),
|
||||
access_token: JsonWebToken.encode({ user_id: user.id, type: "access" }),
|
||||
refresh_token: JsonWebToken.encode({ user_id: user.id, type: "refresh" }, exp: 30.days.from_now)
|
||||
}
|
||||
end
|
||||
|
||||
def user_json(user)
|
||||
{
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
role: user.role
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,38 @@
|
||||
module Api
|
||||
module V1
|
||||
class BaseController < ApplicationController
|
||||
rescue_from Teams::EntitlementError, with: :render_entitlement_error
|
||||
rescue_from Streams::IngestUnavailableError, with: :render_ingest_unavailable
|
||||
rescue_from BrandingAttachments::CoverUploadError, with: :render_cover_upload_error
|
||||
rescue_from Youtube::BroadcastService::Error, with: :render_youtube_error
|
||||
|
||||
private
|
||||
|
||||
def render_youtube_error(error)
|
||||
render json: {
|
||||
error: "YouTube: #{error.message}",
|
||||
error_code: "youtube_api_error"
|
||||
}, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def render_entitlement_error(error)
|
||||
render json: {
|
||||
error: error.message,
|
||||
error_code: error.code,
|
||||
billing_url: error.billing_url
|
||||
}, status: :forbidden
|
||||
end
|
||||
|
||||
def render_ingest_unavailable(error)
|
||||
render json: {
|
||||
error: error.message,
|
||||
error_code: error.code
|
||||
}, status: :service_unavailable
|
||||
end
|
||||
|
||||
def render_cover_upload_error(error)
|
||||
render json: { error: error.message, error_code: "cover_upload_invalid" }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,76 @@
|
||||
module Api
|
||||
module V1
|
||||
class InvitationsController < BaseController
|
||||
skip_before_action :authenticate_request!, only: :show
|
||||
|
||||
def show
|
||||
invitation = find_pending_invitation
|
||||
unless invitation
|
||||
return render json: { valid: false, error: "Invito non valido o scaduto" }, status: :not_found
|
||||
end
|
||||
|
||||
render json: invitation_json(invitation).merge(valid: true)
|
||||
end
|
||||
|
||||
def accept
|
||||
invitation = find_pending_invitation
|
||||
return render json: { error: "Invito non valido o scaduto" }, status: :not_found unless invitation
|
||||
|
||||
email = invitation.email
|
||||
if current_user.email.downcase != email.downcase
|
||||
return render json: {
|
||||
error: "Questo invito è per #{email}. Accedi con quell'indirizzo email.",
|
||||
invited_email: email
|
||||
}, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
invitation.accept!(current_user)
|
||||
render json: invitation_json(invitation).merge(message: accept_message(invitation))
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_pending_invitation
|
||||
token = params[:token].to_s
|
||||
return nil if token.blank?
|
||||
|
||||
digest = Digest::SHA256.hexdigest(token)
|
||||
TeamInvitation.pending.find_by(token_digest: digest) ||
|
||||
TournamentBroadcastInvitation.pending.find_by(token_digest: digest)
|
||||
end
|
||||
|
||||
def invitation_json(invitation)
|
||||
if invitation.is_a?(TournamentBroadcastInvitation)
|
||||
tournament = invitation.tournament
|
||||
{
|
||||
email: invitation.email,
|
||||
tournament_id: tournament.id,
|
||||
tournament_name: tournament.name,
|
||||
club_name: tournament.club.name,
|
||||
team_id: tournament.broadcast_team_id,
|
||||
team_name: tournament.name,
|
||||
staff_kind: "transmission",
|
||||
expires_at: invitation.expires_at
|
||||
}
|
||||
else
|
||||
{
|
||||
email: invitation.email,
|
||||
team_id: invitation.team_id,
|
||||
team_name: invitation.team.name,
|
||||
club_name: invitation.team.club.name,
|
||||
staff_kind: invitation.staff_kind,
|
||||
expires_at: invitation.expires_at
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
def accept_message(invitation)
|
||||
if invitation.is_a?(TournamentBroadcastInvitation)
|
||||
"Sei incaricato delle dirette per #{invitation.tournament.name}."
|
||||
else
|
||||
"Sei entrato in #{invitation.team.name} come responsabile trasmissione."
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,159 @@
|
||||
module Api
|
||||
module V1
|
||||
class MatchesController < BaseController
|
||||
include Api::UrlHelper
|
||||
include Api::CoverJson
|
||||
include BrandingAttachments
|
||||
|
||||
before_action :set_team, only: %i[index create]
|
||||
before_action :set_match, only: %i[show update destroy]
|
||||
|
||||
def index
|
||||
matches = @team.matches
|
||||
.includes(:team, :stream_sessions, :home_participant, :away_participant, :tournament)
|
||||
.order(Arel.sql("scheduled_at ASC NULLS LAST"), created_at: :desc)
|
||||
unless current_user.club_admin?(@team.club)
|
||||
if @team.tournament_broadcast?
|
||||
assigned_ids = current_user.tournament_broadcast_assignments.select(:match_id)
|
||||
matches = matches.where(id: assigned_ids)
|
||||
end
|
||||
end
|
||||
render json: matches.select(&:coach_hub_visible?).map { |m| match_json(m) }
|
||||
end
|
||||
|
||||
def create
|
||||
if @team.tournament_broadcast?
|
||||
return render json: { error: "Le partite del torneo si programmano dal sito web." }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
attrs = match_params.to_h
|
||||
attrs["sport_key"] = @team.sport_key
|
||||
normalize_scoring_rules!(attrs)
|
||||
match = @team.matches.create!(attrs)
|
||||
attach_opponent_logo(match)
|
||||
attach_match_cover(match)
|
||||
render json: match_json(match), status: :created
|
||||
end
|
||||
|
||||
def show
|
||||
render json: match_json(@match, detail: true)
|
||||
end
|
||||
|
||||
def update
|
||||
attrs = match_params.to_h
|
||||
normalize_scoring_rules!(attrs)
|
||||
normalize_opponent_color!(attrs)
|
||||
@match.update!(attrs)
|
||||
attach_opponent_logo(@match)
|
||||
attach_match_cover(@match)
|
||||
render json: match_json(@match)
|
||||
end
|
||||
|
||||
def destroy
|
||||
active = active_session_for(@match)
|
||||
if active&.resumable?
|
||||
return render json: {
|
||||
error: "Chiudi la diretta prima di eliminare questa partita"
|
||||
}, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
@match.destroy!
|
||||
head :no_content
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_team
|
||||
@team = current_user.streamable_teams.find { |t| t.id == params[:team_id] }
|
||||
raise ActiveRecord::RecordNotFound unless @team
|
||||
end
|
||||
|
||||
def set_match
|
||||
team_ids = current_user.streamable_teams.map(&:id)
|
||||
@match = Match.includes(:team).where(team_id: team_ids).find(params[:id])
|
||||
end
|
||||
|
||||
def match_params
|
||||
p = params.require(:match).permit(
|
||||
:opponent_name, :location, :scheduled_at, :sport, :sport_key, :sets_to_win,
|
||||
:category, :opponent_primary_color, :overlay_kind,
|
||||
scoring_rules: {}
|
||||
)
|
||||
if p[:sport].present? && p[:sport_key].blank?
|
||||
p[:sport_key] = p.delete(:sport)
|
||||
end
|
||||
p[:overlay_kind] = nil if p.key?(:overlay_kind) && p[:overlay_kind].blank?
|
||||
p
|
||||
end
|
||||
|
||||
def normalize_scoring_rules!(attrs)
|
||||
return unless attrs.key?("scoring_rules")
|
||||
|
||||
rules = attrs["scoring_rules"]
|
||||
attrs["scoring_rules"] = {} if rules.blank?
|
||||
if attrs["sets_to_win"].present? && attrs["scoring_rules"].is_a?(Hash)
|
||||
attrs["scoring_rules"]["sets_to_win"] ||= attrs["sets_to_win"]
|
||||
end
|
||||
end
|
||||
|
||||
def normalize_opponent_color!(attrs)
|
||||
return unless attrs.key?("opponent_primary_color")
|
||||
|
||||
attrs["opponent_primary_color"] = normalize_hex_color(
|
||||
attrs["opponent_primary_color"],
|
||||
Match::DEFAULT_OPPONENT_COLOR
|
||||
)
|
||||
end
|
||||
|
||||
def attach_opponent_logo(match)
|
||||
file = params[:opponent_logo_file]
|
||||
match.opponent_logo_file.attach(file) if file.present?
|
||||
end
|
||||
|
||||
def attach_match_cover(match)
|
||||
attach_cover_image(match, entitlements: match.team.entitlements)
|
||||
enqueue_cover_slate_generation(match)
|
||||
end
|
||||
|
||||
def match_json(match, detail: false)
|
||||
active = active_session_for(match)
|
||||
team = match.team
|
||||
{
|
||||
id: match.id,
|
||||
team_id: match.team_id,
|
||||
team_name: match.home_display_name,
|
||||
opponent_name: match.away_display_name,
|
||||
location: match.court_or_location,
|
||||
court: match.court,
|
||||
tournament_id: match.tournament_id,
|
||||
tournament_name: match.tournament&.name,
|
||||
scheduled_at: match.scheduled_at,
|
||||
sport: match.sport_key,
|
||||
sport_key: match.sport_key,
|
||||
sport_label: match.sport_label,
|
||||
board_type: match.effective_board_type,
|
||||
overlay_kind: match.overlay_kind,
|
||||
effective_overlay_kind: match.effective_overlay_kind,
|
||||
sets_to_win: match.sets_to_win,
|
||||
scoring_rules: match.scoring_rules.presence,
|
||||
effective_scoring_rules: match.effective_scoring_rules,
|
||||
category: match.category,
|
||||
home_primary_color: match.home_participant&.effective_primary_color || team.effective_primary_color,
|
||||
home_secondary_color: match.home_participant&.effective_secondary_color || team.effective_secondary_color,
|
||||
home_logo_url: api_absolute_url(match.home_participant&.effective_logo_url || team.effective_logo_url),
|
||||
opponent_primary_color: match.away_participant&.effective_primary_color || match.effective_opponent_primary_color,
|
||||
opponent_logo_url: api_absolute_url(match.away_participant&.effective_logo_url || match.opponent_logo_url),
|
||||
**match_cover_json(match),
|
||||
active_session_id: active&.id,
|
||||
active_session_status: active&.status,
|
||||
stream_completed: match.stream_completed?,
|
||||
coach_hub_visible: match.coach_hub_visible?
|
||||
}
|
||||
end
|
||||
|
||||
def active_session_for(match)
|
||||
match.active_stream_session
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,114 @@
|
||||
module Api
|
||||
module V1
|
||||
class RecordingsController < BaseController
|
||||
before_action :set_recording
|
||||
|
||||
def update
|
||||
authorize_manage!
|
||||
attrs = recording_update_attrs
|
||||
privacy_changed = attrs.key?(:privacy_status) && attrs[:privacy_status] != @recording.privacy_status
|
||||
@recording.update!(attrs)
|
||||
Recordings::SyncYoutubePrivacyJob.perform_async(@recording.id) if privacy_changed && @recording.youtube_video_id.present?
|
||||
render json: recording_json(@recording)
|
||||
end
|
||||
|
||||
def destroy
|
||||
authorize_manage!
|
||||
scope = params[:delete_scope].to_s
|
||||
scope = "both" unless Recordings::Delete::SCOPES.include?(scope)
|
||||
Recordings::Delete.new(@recording, scope: scope).call
|
||||
head :no_content
|
||||
end
|
||||
|
||||
def download
|
||||
url = Recordings::DownloadUrl.new(@recording, viewer: current_user).call
|
||||
render json: { download_url: url, expires_in_seconds: MatchLiveTv.replay_download_url_ttl_seconds }
|
||||
rescue Recordings::DownloadUrl::NotAllowed
|
||||
render json: { error: "Download non disponibile per il tuo piano", error_code: "download_not_allowed" },
|
||||
status: :forbidden
|
||||
rescue ArgumentError => e
|
||||
render json: { error: e.message }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def publish_youtube
|
||||
authorize_manage!
|
||||
ent = @recording.team.entitlements
|
||||
unless ent.premium_full? && ent.youtube_enabled?
|
||||
return render json: { error: "Republicazione YouTube con Premium Full" }, status: :forbidden
|
||||
end
|
||||
|
||||
Recordings::PublishToYoutubeJob.perform_async(@recording.id)
|
||||
render json: { queued: true, message: "Pubblicazione su YouTube in corso" }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_recording
|
||||
team_ids = current_user.manageable_teams.map(&:id)
|
||||
@recording = Recording.not_deleted
|
||||
.includes(stream_session: :match)
|
||||
.where(team_id: team_ids)
|
||||
.find(params[:id])
|
||||
end
|
||||
|
||||
def authorize_manage!
|
||||
team = @recording.team
|
||||
return if team.club.owned_by?(current_user)
|
||||
return if current_user.manageable_teams.exists?(id: team.id)
|
||||
|
||||
render json: { error: "Non autorizzato" }, status: :forbidden
|
||||
end
|
||||
|
||||
def recording_update_attrs
|
||||
p = params.require(:recording).permit(:privacy_status, :title)
|
||||
p = p.to_h
|
||||
p[:privacy_status] = "unlisted" if p[:privacy_status] == "private"
|
||||
if params.dig(:recording, :metadata).present?
|
||||
p[:metadata] = @recording.metadata.merge(
|
||||
params[:recording][:metadata].to_unsafe_h.stringify_keys
|
||||
)
|
||||
end
|
||||
p
|
||||
end
|
||||
|
||||
def recording_json(recording)
|
||||
session = recording.stream_session
|
||||
match = session.match
|
||||
ent = recording.team.entitlements
|
||||
{
|
||||
id: recording.id,
|
||||
session_id: session.id,
|
||||
match_id: match.id,
|
||||
title: recording.title_or_default,
|
||||
opponent_name: match.opponent_name,
|
||||
team_name: match.team.name,
|
||||
team_id: recording.team_id,
|
||||
status: recording.status,
|
||||
status_label: recording.status_label,
|
||||
privacy_status: recording.privacy_status,
|
||||
ended_at: session.ended_at,
|
||||
recorded_at: recording.recorded_at_or_fallback,
|
||||
duration_secs: recording.duration_secs,
|
||||
duration_label: recording.duration_label,
|
||||
byte_size: recording.byte_size,
|
||||
byte_size_label: recording.byte_size_label,
|
||||
view_count: recording.view_count,
|
||||
views_label: recording.views_label,
|
||||
replay_url: recording.replay_url,
|
||||
playback_url: recording.playback_stream_url,
|
||||
thumbnail_url: recording.thumbnail_url,
|
||||
download_enabled: ent.phone_download_enabled? && recording.storage_key.present?,
|
||||
youtube_video_id: recording.youtube_video_id,
|
||||
youtube_watch_url: recording.youtube_watch_url,
|
||||
youtube_publish_enabled: ent.premium_full? && ent.youtube_enabled? && recording.storage_key.present? && recording.youtube_video_id.blank?,
|
||||
replay_source: recording.replay_source,
|
||||
source_platform: recording.source_platform,
|
||||
source_platform_label: recording.source_platform_label,
|
||||
expires_at: recording.expires_at,
|
||||
days_until_expiry: recording.days_until_expiry,
|
||||
metadata: recording.metadata
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
module Api
|
||||
module V1
|
||||
class SportsController < BaseController
|
||||
def index
|
||||
render json: ::Sports::Catalog.as_api_list
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,256 @@
|
||||
module Api
|
||||
module V1
|
||||
class StreamSessionsController < BaseController
|
||||
before_action :set_session, except: :create
|
||||
|
||||
def create
|
||||
team_ids = current_user.streamable_teams.map(&:id)
|
||||
match = Match.where(team_id: team_ids).find(params[:match_id])
|
||||
unless current_user.can_broadcast_match?(match)
|
||||
return render json: { error: "Non sei incaricato di trasmettere questa partita" }, status: :forbidden
|
||||
end
|
||||
|
||||
session = Sessions::Create.new(user: current_user, match: match, params: session_params).call
|
||||
render json: session_json(session), status: :created
|
||||
end
|
||||
|
||||
def show
|
||||
render json: session_json(@session, detail: true)
|
||||
end
|
||||
|
||||
def start
|
||||
Sessions::Start.new(@session).call
|
||||
render json: session_json(@session)
|
||||
end
|
||||
|
||||
def stop
|
||||
Sessions::Stop.new(@session).call
|
||||
render json: session_json(@session)
|
||||
end
|
||||
|
||||
def pause
|
||||
Sessions::Pause.new(@session).call
|
||||
render json: session_json(@session)
|
||||
end
|
||||
|
||||
def resume
|
||||
Sessions::Resume.new(@session).call
|
||||
render json: session_json(@session)
|
||||
end
|
||||
|
||||
def audio_mute
|
||||
muted = params.key?(:muted) ? params[:muted] : true
|
||||
Sessions::SetAudioMute.new(@session, muted: muted).call
|
||||
render json: session_json(@session)
|
||||
end
|
||||
|
||||
def score
|
||||
Scoring::SyncState.new(session: @session, payload: score_sync_params).call
|
||||
render json: session_json(@session, detail: true)
|
||||
end
|
||||
|
||||
def score_action
|
||||
action = params[:score_action].presence
|
||||
raise ArgumentError, "Azione mancante" if action.blank?
|
||||
|
||||
result = Scoring::ApplyAction.new(session: @session, action: action).call
|
||||
render json: session_json(@session, detail: true).merge(
|
||||
set_won: result.set_won,
|
||||
match_won: result.match_won,
|
||||
winner: result.winner&.to_s
|
||||
)
|
||||
rescue ArgumentError => e
|
||||
render json: { error: e.message }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def events
|
||||
events = @session.stream_events.recent.limit(100)
|
||||
render json: events.map { |e| event_json(e) }
|
||||
end
|
||||
|
||||
def telemetry
|
||||
role = params.require(:device_role)
|
||||
state = @session.device_states.find_or_initialize_by(device_role: role)
|
||||
state.update!(
|
||||
battery_level: params[:battery_level],
|
||||
network_type: params[:network_type],
|
||||
signal_strength: params[:signal_strength],
|
||||
current_bitrate: params[:current_bitrate],
|
||||
target_bitrate: params[:target_bitrate],
|
||||
fps: params[:fps],
|
||||
thermal_state: sanitized_thermal_state,
|
||||
last_seen_at: Time.current
|
||||
)
|
||||
Sessions::ApplyClientInfo.call(@session, params[:client]) if params[:client].present?
|
||||
sync_publisher_when_streaming!(params[:fps].to_f)
|
||||
SessionChannel.broadcast_message(@session, state.as_cable_payload)
|
||||
head :no_content
|
||||
end
|
||||
|
||||
def pairing_token
|
||||
token = SecureRandom.urlsafe_base64(24)
|
||||
@session.update!(
|
||||
pairing_token_digest: Digest::SHA256.hexdigest(token),
|
||||
pairing_token_expires_at: 15.minutes.from_now
|
||||
)
|
||||
render json: {
|
||||
pairing_token: token,
|
||||
expires_at: @session.pairing_token_expires_at,
|
||||
qr_payload: {
|
||||
session_id: @session.id,
|
||||
pairing_token: token,
|
||||
api_url: request.base_url
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
def regia_link
|
||||
access = Sessions::RegiaAccess.new(@session)
|
||||
token = access.issue_token!
|
||||
render json: {
|
||||
regia_url: access.url(token),
|
||||
expires_at: @session.regia_token_expires_at
|
||||
}
|
||||
end
|
||||
|
||||
def claim_pairing
|
||||
token = params.require(:pairing_token)
|
||||
digest = Digest::SHA256.hexdigest(token)
|
||||
unless @session.pairing_token_digest == digest &&
|
||||
@session.pairing_token_expires_at&.future?
|
||||
return render json: { error: "Invalid or expired token" }, status: :unauthorized
|
||||
end
|
||||
|
||||
@session.device_states.find_or_create_by!(device_role: params[:device_role] || "controller")
|
||||
render json: session_json(@session)
|
||||
end
|
||||
|
||||
def network_test
|
||||
upload_mbps = params[:upload_mbps].to_f
|
||||
preset = Sessions::SelectQuality.call(upload_mbps: upload_mbps)
|
||||
@session.update!(
|
||||
quality_preset: preset[:id],
|
||||
target_bitrate: preset[:target_bitrate],
|
||||
target_fps: preset[:target_fps]
|
||||
)
|
||||
@session.stream_events.create!(
|
||||
event_type: "network_test",
|
||||
metadata: params.permit(:download_mbps, :upload_mbps, :latency_ms, :network_type)
|
||||
.to_h.merge(
|
||||
"quality_preset" => preset[:id],
|
||||
"target_bitrate" => preset[:target_bitrate]
|
||||
),
|
||||
occurred_at: Time.current
|
||||
)
|
||||
target_upload = preset[:target_bitrate] / 1_000_000.0
|
||||
ready = upload_mbps >= (target_upload * Sessions::SelectQuality::UPLOAD_HEADROOM)
|
||||
render json: {
|
||||
ready: ready,
|
||||
target_upload_mbps: target_upload,
|
||||
quality_preset: preset[:id],
|
||||
target_bitrate: preset[:target_bitrate],
|
||||
target_fps: preset[:target_fps]
|
||||
}
|
||||
end
|
||||
|
||||
def min_quality
|
||||
Sessions::SetMinQuality.new(@session, preset: params[:min_quality_preset]).call
|
||||
render json: session_json(@session)
|
||||
rescue ArgumentError => e
|
||||
render json: { error: e.message }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def youtube_stats
|
||||
count = if @session.platform == "youtube" && @session.youtube_broadcast_id.present?
|
||||
Youtube::BroadcastService.new(@session.match.team)
|
||||
.viewer_count(@session.youtube_broadcast_id)
|
||||
else
|
||||
0
|
||||
end
|
||||
render json: { concurrent_viewers: count, live: @session.live? }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_session
|
||||
team_ids = current_user.streamable_teams.map(&:id)
|
||||
@session = StreamSession.joins(:match)
|
||||
.where(matches: { team_id: team_ids })
|
||||
.find(params[:id])
|
||||
end
|
||||
|
||||
def sanitized_thermal_state
|
||||
value = params[:thermal_state].to_s.downcase.presence
|
||||
value if value.in?(%w[nominal fair serious critical])
|
||||
end
|
||||
|
||||
def session_params
|
||||
params.permit(
|
||||
:platform, :privacy_status, :quality_preset, :target_bitrate, :target_fps, :youtube_channel,
|
||||
client: %i[os client_os app_version app_build version build build_number
|
||||
device_manufacturer manufacturer device_model model
|
||||
os_version system_version carrier network_operator operator]
|
||||
)
|
||||
end
|
||||
|
||||
def score_sync_params
|
||||
params.permit(
|
||||
:home_sets, :away_sets, :home_points, :away_points, :current_set,
|
||||
:clock_secs, :clock_running, :period, :home_score, :away_score, :overtime,
|
||||
set_partials: %i[set home away]
|
||||
)
|
||||
end
|
||||
|
||||
def session_json(session, detail: false)
|
||||
data = {
|
||||
id: session.id,
|
||||
match_id: session.match_id,
|
||||
status: session.status,
|
||||
platform: session.platform,
|
||||
rtmp_ingest_url: session.rtmp_ingest_url,
|
||||
hls_playback_url: session.hls_playback_url,
|
||||
stream_node: session.stream_node&.slug,
|
||||
watch_page_url: session.matchlivetv_platform? ? session.watch_page_url : nil,
|
||||
share_url: session.share_url,
|
||||
youtube_watch_url: session.youtube_watch_url,
|
||||
youtube_broadcast_id: session.youtube_broadcast_id,
|
||||
youtube_ready: session.youtube_ready?,
|
||||
privacy_status: session.privacy_status,
|
||||
quality_preset: session.quality_preset,
|
||||
min_quality_preset: session.min_quality_preset,
|
||||
target_bitrate: session.target_bitrate,
|
||||
started_at: session.started_at,
|
||||
disconnection_count: session.disconnection_count,
|
||||
audio_muted: session.audio_muted
|
||||
}
|
||||
if detail
|
||||
data[:score] = session.score_state&.as_cable_payload
|
||||
data[:devices] = session.device_states.map(&:as_cable_payload)
|
||||
end
|
||||
data
|
||||
end
|
||||
|
||||
def event_json(event)
|
||||
{
|
||||
id: event.id,
|
||||
event_type: event.event_type,
|
||||
metadata: event.metadata,
|
||||
occurred_at: event.occurred_at
|
||||
}
|
||||
end
|
||||
|
||||
# L'app invia fps ogni ~10s; poll status.json per allineare stato sessione e relay YouTube.
|
||||
def sync_publisher_when_streaming!(fps)
|
||||
return if fps < 1
|
||||
return if @session.terminal? || @session.paused?
|
||||
return unless @session.platform == "youtube"
|
||||
return unless @session.status.in?(%w[connecting live reconnecting])
|
||||
|
||||
Mediamtx::PublisherSync.new(@session).call
|
||||
if @session.platform == "youtube" && @session.status.in?(%w[live connecting reconnecting])
|
||||
Mediamtx::PublisherSync.schedule_youtube_pipeline!(@session, force: false)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,193 @@
|
||||
module Api
|
||||
module V1
|
||||
class TeamsController < BaseController
|
||||
include Api::UrlHelper
|
||||
include BrandingAttachments
|
||||
|
||||
def index
|
||||
teams = current_user.streamable_teams
|
||||
render json: teams.map { |t| team_json(t) }
|
||||
end
|
||||
|
||||
def show
|
||||
team = current_user.manageable_teams.find(params[:id])
|
||||
render json: team_json(team, detail: true)
|
||||
end
|
||||
|
||||
def create
|
||||
if current_user.owned_clubs.exists?
|
||||
return render json: {
|
||||
error: "Registra o gestisci la società dal sito web per aggiungere squadre."
|
||||
}, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
sport_key = ::Sports::Catalog.normalize_key(team_params[:sport_key] || team_params[:sport] || "pallavolo")
|
||||
club = Club.create!(name: team_params[:name], sport: sport_key,
|
||||
primary_color: "#e53935", secondary_color: "#ffffff")
|
||||
ClubMembership.create!(user: current_user, club: club, role: "owner")
|
||||
team = club.teams.create!(name: team_params[:name], sport_key: sport_key)
|
||||
Billing::AssignPlan.call(club: club, plan_slug: "free")
|
||||
render json: team_json(team), status: :created
|
||||
end
|
||||
|
||||
def recordings
|
||||
team = current_user.streamable_teams.find { |t| t.id.to_s == params[:id].to_s }
|
||||
raise ActiveRecord::RecordNotFound unless team
|
||||
unless team.entitlements.can_access_recordings?
|
||||
return render json: {
|
||||
error: "Archivio gare disponibile con Premium Light o Full",
|
||||
error_code: "premium_required",
|
||||
billing_url: team.entitlements.billing_url
|
||||
}, status: :forbidden
|
||||
end
|
||||
|
||||
recs = team.recordings.not_deleted
|
||||
.where(status: %w[ready processing])
|
||||
.where("expires_at IS NULL OR expires_at > ?", Time.current)
|
||||
.includes(stream_session: :match)
|
||||
.order(recorded_at: :desc, created_at: :desc)
|
||||
.limit(50)
|
||||
render json: recs.map { |r| recording_json(r) }
|
||||
end
|
||||
|
||||
def update
|
||||
team = current_user.manageable_teams.find(params[:id])
|
||||
team.update!(team_params)
|
||||
attach_team_logo(team)
|
||||
render json: team_json(team)
|
||||
end
|
||||
|
||||
def add_member
|
||||
team = current_user.manageable_teams.find(params[:id])
|
||||
team.entitlements.assert_can_invite!
|
||||
member = User.find(params[:user_id])
|
||||
UserTeam.find_or_create_by!(user: member, team: team) { |ut| ut.role = "member" }
|
||||
head :no_content
|
||||
end
|
||||
|
||||
def remove_member
|
||||
team = current_user.manageable_teams.find(params[:id])
|
||||
ut = team.user_teams.find_by!(user_id: params[:user_id], role: "member")
|
||||
ut.destroy!
|
||||
head :no_content
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def team_params
|
||||
p = params.require(:team).permit(:name, :sport, :sport_key, :logo_url, :primary_color, :secondary_color)
|
||||
if p[:sport].present? && p[:sport_key].blank?
|
||||
p[:sport_key] = p.delete(:sport)
|
||||
end
|
||||
p
|
||||
if p[:primary_color].present?
|
||||
p[:primary_color] = normalize_hex_color(p[:primary_color], p[:primary_color])
|
||||
end
|
||||
if p[:secondary_color].present?
|
||||
p[:secondary_color] = normalize_hex_color(p[:secondary_color], p[:secondary_color])
|
||||
end
|
||||
p
|
||||
end
|
||||
|
||||
def attach_team_logo(team)
|
||||
file = params[:logo_file]
|
||||
team.logo_file.attach(file) if file.present?
|
||||
end
|
||||
|
||||
def team_json(team, detail: false)
|
||||
ent = team.entitlements
|
||||
yt = Youtube::TeamStatus.new(team)
|
||||
resolver = Youtube::CredentialResolver.new(team)
|
||||
data = {
|
||||
id: team.id,
|
||||
name: team.name,
|
||||
sport: team.sport_key,
|
||||
sport_key: team.sport_key,
|
||||
sport_label: team.sport_label,
|
||||
board_type: team.effective_board_type,
|
||||
logo_url: api_absolute_url(team.effective_logo_url),
|
||||
primary_color: team.effective_primary_color,
|
||||
secondary_color: team.effective_secondary_color,
|
||||
club_id: team.club_id,
|
||||
club_name: team.club.name,
|
||||
tournament_broadcast: team.tournament_broadcast?,
|
||||
tournament_id: team.broadcast_tournament&.id,
|
||||
tournament_name: team.broadcast_tournament&.name,
|
||||
youtube_connected: yt.connected?,
|
||||
youtube_selectable: yt.selectable?,
|
||||
youtube_channel_title: yt.channel_title,
|
||||
youtube_uses_platform_channel: yt.uses_platform_channel?,
|
||||
youtube_platform_available: resolver.platform_available?,
|
||||
youtube_team_channel_available: resolver.team_channel_available?,
|
||||
youtube_team_channel_title: team.club.youtube_credential&.channel_title,
|
||||
plan_slug: ent.plan.slug,
|
||||
plan_name: ent.plan.name,
|
||||
premium_active: ent.premium_active?,
|
||||
premium_full: ent.premium_full?,
|
||||
subscription_status: ent.subscription.status,
|
||||
features: ent.plan.features,
|
||||
billing_url: ent.billing_url,
|
||||
staff_manage_url: ent.staff_manage_url,
|
||||
max_staff: ent.max_staff,
|
||||
max_staff_transmission: ent.max_staff_transmission,
|
||||
staff_used: ent.staff_count,
|
||||
staff_transmission_used: ent.staff_count_for("transmission"),
|
||||
concurrent_streams_used: ent.concurrent_streams_used,
|
||||
concurrent_streams_limit: ent.concurrent_streams_limit,
|
||||
recordings_enabled: ent.can_access_recordings?,
|
||||
phone_download_enabled: ent.phone_download_enabled?,
|
||||
youtube_enabled: ent.youtube_enabled?,
|
||||
youtube_mode: ent.plan.youtube_mode,
|
||||
staff_role: current_user.staff_role_for(team),
|
||||
can_stream: current_user.can_stream_for?(team),
|
||||
can_connect_youtube: team.club.owned_by?(current_user) && ent.premium_full? && ent.youtube_enabled?,
|
||||
custom_cover_enabled: ent.can_use_custom_cover?
|
||||
}
|
||||
if detail
|
||||
data[:members] = team.user_teams.includes(:user).where.not(role: "owner").map do |ut|
|
||||
{ id: ut.user.id, name: ut.user.name, email: ut.user.email, role: ut.role }
|
||||
end
|
||||
end
|
||||
data
|
||||
end
|
||||
|
||||
def recording_json(recording)
|
||||
session = recording.stream_session
|
||||
match = session.match
|
||||
ent = recording.team.entitlements
|
||||
{
|
||||
id: recording.id,
|
||||
session_id: session.id,
|
||||
match_id: match.id,
|
||||
title: recording.title_or_default,
|
||||
opponent_name: match.opponent_name,
|
||||
team_name: match.team.name,
|
||||
status: recording.status,
|
||||
status_label: recording.status_label,
|
||||
privacy_status: recording.privacy_status,
|
||||
ended_at: session.ended_at,
|
||||
recorded_at: recording.recorded_at_or_fallback,
|
||||
duration_secs: recording.duration_secs,
|
||||
duration_label: recording.duration_label,
|
||||
byte_size: recording.byte_size,
|
||||
byte_size_label: recording.byte_size_label,
|
||||
replay_url: recording.replay_url,
|
||||
playback_url: recording.playback_stream_url,
|
||||
thumbnail_url: recording.thumbnail_url,
|
||||
download_enabled: ent.phone_download_enabled? && recording.storage_key.present?,
|
||||
view_count: recording.view_count,
|
||||
views_label: recording.views_label,
|
||||
youtube_video_id: recording.youtube_video_id,
|
||||
youtube_watch_url: recording.youtube_watch_url,
|
||||
youtube_publish_enabled: ent.premium_full? && ent.youtube_enabled? && recording.storage_key.present? && recording.youtube_video_id.blank?,
|
||||
replay_source: recording.replay_source,
|
||||
source_platform: recording.source_platform,
|
||||
source_platform_label: recording.source_platform_label,
|
||||
expires_at: recording.expires_at,
|
||||
days_until_expiry: recording.days_until_expiry,
|
||||
metadata: recording.metadata
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,23 @@
|
||||
module Api
|
||||
module V1
|
||||
class YoutubeController < BaseController
|
||||
def authorize
|
||||
team = current_user.streamable_teams.find { |t| t.id.to_s == params[:team_id].to_s }
|
||||
raise ActiveRecord::RecordNotFound unless team
|
||||
unless team.club.owned_by?(current_user)
|
||||
return render json: { error: "Solo il titolare della società può collegare YouTube" }, status: :forbidden
|
||||
end
|
||||
|
||||
team.entitlements.assert_can_connect_youtube!
|
||||
return_app = ActiveModel::Type::Boolean.new.cast(params[:return_app])
|
||||
state = Youtube::OauthState.for_team(
|
||||
team_id: team.id,
|
||||
user_id: current_user.id,
|
||||
return_app: return_app
|
||||
)
|
||||
url = Youtube::OauthUrl.build(state: state, redirect_uri: ENV.fetch("YOUTUBE_REDIRECT_URI"))
|
||||
render json: { authorization_url: url, return_app: return_app }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,33 @@
|
||||
class ApplicationController < ActionController::API
|
||||
include ActionController::HttpAuthentication::Token::ControllerMethods
|
||||
|
||||
before_action :set_api_locale
|
||||
before_action :authenticate_request!
|
||||
|
||||
attr_reader :current_user
|
||||
|
||||
private
|
||||
|
||||
def set_api_locale
|
||||
explicit = LocaleResolver.normalize(request.headers["X-Locale"])
|
||||
I18n.locale = explicit ||
|
||||
LocaleResolver.from_accept_language(request.headers["Accept-Language"]) ||
|
||||
I18n.default_locale
|
||||
end
|
||||
|
||||
def authenticate_request!
|
||||
token = bearer_token
|
||||
payload = JsonWebToken.decode(token)
|
||||
@current_user = User.find_by(id: payload[:user_id]) if payload
|
||||
render json: { error: I18n.t("flash.sessions.unauthorized") }, status: :unauthorized unless @current_user
|
||||
end
|
||||
|
||||
def bearer_token
|
||||
auth = request.headers["Authorization"].to_s
|
||||
auth.start_with?("Bearer ") ? auth.split(" ", 2).last : nil
|
||||
end
|
||||
|
||||
def skip_auth?
|
||||
false
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,16 @@
|
||||
module Api
|
||||
module CoverJson
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
private
|
||||
|
||||
def match_cover_json(match)
|
||||
resolver = Streams::CoverResolver.new(match)
|
||||
{
|
||||
effective_cover_url: api_absolute_url(resolver.effective_cover_url),
|
||||
cover_source: resolver.cover_source,
|
||||
custom_cover_enabled: match.team.entitlements.can_use_custom_cover?
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,16 @@
|
||||
module Api
|
||||
module UrlHelper
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
private
|
||||
|
||||
def api_absolute_url(path_or_url)
|
||||
return nil if path_or_url.blank?
|
||||
return path_or_url if path_or_url.match?(/\Ahttps?:\/\//i)
|
||||
|
||||
base = request.base_url
|
||||
path = path_or_url.start_with?("/") ? path_or_url : "/#{path_or_url}"
|
||||
"#{base}#{path}"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,58 @@
|
||||
module BrandingAttachments
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
private
|
||||
|
||||
def attach_branding_logo(record)
|
||||
file = params.dig(:branding, :logo_file)
|
||||
record.logo_file.attach(file) if file.present?
|
||||
end
|
||||
|
||||
def attach_cover_image(record, entitlements:)
|
||||
remove_flag = params[:remove_cover].to_s == "1" || params.dig(:match, :remove_cover).to_s == "1"
|
||||
if remove_flag
|
||||
record.cover_image.purge if record.cover_image.attached?
|
||||
record.cover_slate.purge if record.cover_slate.attached?
|
||||
return
|
||||
end
|
||||
|
||||
file = params.dig(:branding, :cover_image) || params[:cover_image]
|
||||
return if file.blank?
|
||||
|
||||
entitlements.assert_can_upload_cover!
|
||||
validate_cover_file!(file)
|
||||
record.cover_slate.purge if record.cover_slate.attached?
|
||||
record.cover_image.attach(file)
|
||||
end
|
||||
|
||||
def validate_cover_file!(file)
|
||||
allowed_types = Coverable::COVER_IMAGE_TYPES
|
||||
|
||||
# Rileva MIME dal contenuto (magic bytes) ignorando il declared_type del client.
|
||||
io = file.respond_to?(:tempfile) ? file.tempfile : file
|
||||
io.rewind if io.respond_to?(:rewind)
|
||||
detected = Marcel::MimeType.for(io, name: file.respond_to?(:original_filename) ? file.original_filename : nil)
|
||||
io.rewind if io.respond_to?(:rewind)
|
||||
|
||||
unless detected.in?(allowed_types)
|
||||
raise CoverUploadError, I18n.t("coverable.errors.invalid_type")
|
||||
end
|
||||
|
||||
byte_size = file.respond_to?(:size) ? file.size : File.size(file.path)
|
||||
if byte_size > Coverable::MAX_COVER_BYTES
|
||||
raise CoverUploadError, I18n.t("coverable.errors.too_large")
|
||||
end
|
||||
end
|
||||
|
||||
class CoverUploadError < StandardError; end
|
||||
|
||||
def enqueue_cover_slate_generation(record)
|
||||
GenerateCoverSlateJob.enqueue_for(record) if record.cover_image.attached?
|
||||
end
|
||||
|
||||
def normalize_hex_color(value, fallback)
|
||||
v = value.to_s.strip
|
||||
v = "##{v}" if v.match?(/\A[0-9A-Fa-f]{6}\z/)
|
||||
v.match?(Brandable::HEX_COLOR) ? v : fallback
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,43 @@
|
||||
module MediamtxPlayback
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
private
|
||||
|
||||
def mediamtx_paths_index
|
||||
mediamtx_paths_index_for_url(MatchLiveTv.mediamtx_api_url)
|
||||
end
|
||||
|
||||
def mediamtx_paths_index_for(session)
|
||||
mediamtx_paths_index_for_url(session.mediamtx_api_base_url)
|
||||
end
|
||||
|
||||
def mediamtx_paths_index_for_url(api_url)
|
||||
@mediamtx_paths_by_origin ||= {}
|
||||
@mediamtx_paths_by_origin[api_url] ||= Mediamtx::Client.new(base_url: api_url).list_paths.index_by { |i| i["name"] }
|
||||
end
|
||||
|
||||
def mediamtx_path_info(session, path_name: mediamtx_playback_path_name(session))
|
||||
mediamtx_paths_index_for(session)[path_name]
|
||||
end
|
||||
|
||||
def mediamtx_playback_path_name(session)
|
||||
session.effective_hls_path_name
|
||||
end
|
||||
|
||||
# Player HLS: path grezzo MediaMTX (live/match_{uuid}).
|
||||
def mediamtx_stream_playable?(session)
|
||||
return false if session.terminal?
|
||||
|
||||
mediamtx_path_has_output?(session)
|
||||
end
|
||||
|
||||
def mediamtx_path_has_output?(session)
|
||||
info = mediamtx_path_info(session)
|
||||
info && (info["ready"] || info["available"] || info["online"])
|
||||
end
|
||||
|
||||
def mediamtx_publisher_online?(session)
|
||||
info = mediamtx_paths_index_for(session)[session.mediamtx_path_name]
|
||||
info && info["online"]
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,140 @@
|
||||
module Recordings
|
||||
module ClubArchiveActions
|
||||
extend ActiveSupport::Concern
|
||||
include RecordingsArchiveHelper
|
||||
|
||||
included do
|
||||
before_action :set_club
|
||||
before_action :set_recording, only: %i[update destroy publish_youtube]
|
||||
end
|
||||
|
||||
def index
|
||||
load_archive
|
||||
end
|
||||
|
||||
def update
|
||||
if admin_expiry_update_requested?
|
||||
apply_admin_expiry_update!
|
||||
return
|
||||
end
|
||||
|
||||
permitted = recording_update_params
|
||||
attrs = {}
|
||||
privacy = permitted[:privacy_status]
|
||||
attrs[:privacy_status] = privacy if privacy.in?(Recording::PRIVACY_STATUSES)
|
||||
title = permitted[:title]
|
||||
attrs[:title] = title if title.present?
|
||||
privacy_changed = attrs.key?(:privacy_status) && attrs[:privacy_status] != @recording.privacy_status
|
||||
@recording.update!(attrs)
|
||||
Recordings::SyncYoutubePrivacyJob.perform_async(@recording.id) if privacy_changed && @recording.youtube_video_id.present?
|
||||
redirect_to archive_index_path, notice: "Replay aggiornato"
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
redirect_to archive_index_path, alert: e.record.errors.full_messages.join(", ")
|
||||
rescue Recordings::ExtendExpiry::Error => e
|
||||
redirect_to archive_index_path, alert: e.message
|
||||
end
|
||||
|
||||
def destroy
|
||||
scope = delete_scope_param
|
||||
Recordings::Delete.new(@recording, scope: scope).call
|
||||
redirect_to archive_index_path, notice: delete_notice_for(scope)
|
||||
end
|
||||
|
||||
def publish_youtube
|
||||
ent = @recording.team.entitlements
|
||||
unless ent.premium_full? && ent.youtube_enabled?
|
||||
redirect_to archive_index_path, alert: "Republicazione YouTube con Premium Full"
|
||||
return
|
||||
end
|
||||
|
||||
Recordings::PublishToYoutubeJob.perform_async(@recording.id)
|
||||
redirect_to archive_index_path, notice: "Pubblicazione su YouTube avviata"
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def load_archive
|
||||
archive = Recordings::ClubArchive.new(@club, params: params)
|
||||
@stats = archive.stats
|
||||
@recordings = archive.recordings
|
||||
@teams = archive.teams
|
||||
@filter_team_id = archive.filter_team_id
|
||||
@filter_status = archive.filter_status
|
||||
@archive_paths = recordings_archive_paths(@club, namespace: archive_namespace)
|
||||
@archive_filter_params = archive.filter_params
|
||||
end
|
||||
|
||||
def archive_index_path
|
||||
archive_paths.index + archive_query_string
|
||||
end
|
||||
|
||||
def archive_query_string
|
||||
q = @archive_filter_params.presence
|
||||
return "" if q.blank?
|
||||
|
||||
"?#{q.to_query}"
|
||||
end
|
||||
|
||||
def archive_paths
|
||||
@archive_paths ||= recordings_archive_paths(@club, namespace: archive_namespace)
|
||||
end
|
||||
|
||||
def set_club
|
||||
@club = Club.find(params[:club_id])
|
||||
end
|
||||
|
||||
def set_recording
|
||||
@recording = Recording.for_club(@club).not_deleted.find(params[:id])
|
||||
authorize_recording_management!
|
||||
end
|
||||
|
||||
def authorize_recording_management!
|
||||
# overridden in Public::ClubRecordingsController
|
||||
end
|
||||
|
||||
def archive_namespace
|
||||
raise NotImplementedError
|
||||
end
|
||||
|
||||
def recording_update_params
|
||||
params.require(:recording).permit(:privacy_status, :title, :expires_at, :extend_days)
|
||||
end
|
||||
|
||||
def delete_scope_param
|
||||
value = params[:delete_scope].to_s
|
||||
Recordings::Delete::SCOPES.include?(value) ? value : "both"
|
||||
end
|
||||
|
||||
def delete_notice_for(scope)
|
||||
case scope
|
||||
when "site"
|
||||
"Replay eliminato dal sito (YouTube invariato)"
|
||||
when "youtube"
|
||||
"Video rimosso da YouTube (resta disponibile sul sito)"
|
||||
else
|
||||
"Replay eliminato dal sito e da YouTube"
|
||||
end
|
||||
end
|
||||
|
||||
def admin_expiry_update_requested?
|
||||
return false unless archive_namespace == :admin
|
||||
|
||||
permitted = recording_update_params
|
||||
permitted[:extend_days].present? || permitted[:expires_at].present?
|
||||
end
|
||||
|
||||
def apply_admin_expiry_update!
|
||||
permitted = recording_update_params
|
||||
extender = Recordings::ExtendExpiry.new(@recording)
|
||||
|
||||
if permitted[:extend_days].present?
|
||||
extender.by_days(permitted[:extend_days])
|
||||
redirect_to archive_index_path, notice: "Scadenza replay prolungata di #{permitted[:extend_days].to_i} giorni"
|
||||
else
|
||||
expires_at = Time.zone.parse(permitted[:expires_at].to_s)&.end_of_day
|
||||
extender.to_time(expires_at)
|
||||
redirect_to archive_index_path, notice: "Scadenza replay aggiornata"
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,116 @@
|
||||
class HlsProxyController < ActionController::Base
|
||||
# Proxy pubblico verso MediaMTX HLS.
|
||||
# Dev: tutto passa da Rails (/hls/*).
|
||||
# Prod: edge inoltra /hls/ a MediaMTX; il redirect cookie di MediaMTX punta a
|
||||
# /live/match_{uuid}/… che deve essere gestito da #live_match (fallback).
|
||||
def show
|
||||
proxy_mediamtx_path(params[:path].to_s)
|
||||
end
|
||||
|
||||
def live_match
|
||||
session_id = params[:session_id].to_s
|
||||
return head :not_found unless session_id.match?(/\A[0-9a-f-]{36}\z/i)
|
||||
|
||||
segments = params[:segments].presence || "index.m3u8"
|
||||
proxy_mediamtx_path("live/match_#{session_id}/#{segments}")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def proxy_mediamtx_path(upstream_path)
|
||||
return head :not_found if upstream_path.blank?
|
||||
|
||||
origin = hls_origin_for(upstream_path)
|
||||
upstream = "#{origin}/#{upstream_path}"
|
||||
upstream = "#{upstream}?#{request.query_string}" if request.query_string.present?
|
||||
cookie = request.headers["Cookie"].presence || "cookieCheck=1"
|
||||
|
||||
5.times do
|
||||
response = hls_conn.get(upstream) { |req| req.headers["Cookie"] = cookie }
|
||||
|
||||
if response.status.in?([301, 302, 307, 308])
|
||||
location = response.headers["location"].to_s
|
||||
cookie = cookie_from_set_header(response.headers["set-cookie"]).presence || cookie
|
||||
upstream = resolve_upstream_url(location, origin)
|
||||
next
|
||||
end
|
||||
|
||||
return render_proxied_response(response)
|
||||
end
|
||||
|
||||
head :bad_gateway
|
||||
rescue Faraday::Error => e
|
||||
Rails.logger.warn("[HlsProxy] #{upstream_path}: #{e.message}")
|
||||
head :bad_gateway
|
||||
end
|
||||
|
||||
def hls_origin_for(upstream_path)
|
||||
session_id = upstream_path[/\Alive\/match_([0-9a-f-]{36})/i, 1]
|
||||
if session_id
|
||||
session = StreamSession.find_by(id: session_id)
|
||||
node_hls = session&.stream_node&.internal_hls_url.presence
|
||||
return node_hls.sub(%r{/$}, "") if node_hls.present?
|
||||
end
|
||||
|
||||
MatchLiveTv.mediamtx_hls_url.sub(%r{/$}, "")
|
||||
end
|
||||
|
||||
def resolve_upstream_url(location, origin)
|
||||
return location if location.start_with?("http://", "https://")
|
||||
|
||||
base = origin.to_s.sub(%r{/$}, "")
|
||||
location.start_with?("/") ? "#{base}#{location}" : "#{base}/#{location}"
|
||||
end
|
||||
|
||||
def render_proxied_response(response)
|
||||
body = response.body.to_s
|
||||
content_type = response.headers["content-type"].to_s
|
||||
|
||||
if m3u8_playlist?(content_type, body)
|
||||
public_hls_base = "#{request.base_url}/hls"
|
||||
body = body.gsub(%r{(?<=["'(\s])/live/(match_[0-9a-f-]{36}/)}, "/hls/live/\\1")
|
||||
body = body.gsub(%r{\A/live/(match_[0-9a-f-]{36}/)}, "/hls/live/\\1")
|
||||
end
|
||||
|
||||
response.headers.each do |key, value|
|
||||
next if %w[transfer-encoding connection content-length content-encoding].include?(key.downcase)
|
||||
|
||||
if key.downcase == "location"
|
||||
headers[key] = rewrite_public_location(value)
|
||||
else
|
||||
headers[key] = value
|
||||
end
|
||||
end
|
||||
|
||||
render body: body, status: response.status, content_type: content_type.presence
|
||||
end
|
||||
|
||||
def rewrite_public_location(location)
|
||||
loc = location.to_s
|
||||
if loc.start_with?("/live/match_")
|
||||
return loc.sub(%r{\A/live/}, "/hls/")
|
||||
end
|
||||
if loc.include?("/live/match_")
|
||||
return loc.gsub(%r{/(live/match_[0-9a-f-]{36}/)}, "/hls/live/\\1")
|
||||
end
|
||||
loc
|
||||
end
|
||||
|
||||
def m3u8_playlist?(content_type, body)
|
||||
return true if content_type.include?("mpegurl") || content_type.include?("m3u8")
|
||||
|
||||
body.lstrip.start_with?("#EXTM3U")
|
||||
end
|
||||
|
||||
def cookie_from_set_header(set_cookie_header)
|
||||
set_cookie_header.to_s[/cookieCheck=[^;]+/]
|
||||
end
|
||||
|
||||
def hls_conn
|
||||
@hls_conn ||= Faraday.new do |f|
|
||||
f.adapter Faraday.default_adapter
|
||||
f.options.timeout = 15
|
||||
f.options.open_timeout = 5
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,28 @@
|
||||
module Ops
|
||||
class HealthController < ActionController::API
|
||||
before_action :authorize_deep_health!
|
||||
|
||||
def show
|
||||
summary = Ops::HealthChecks.new.summary
|
||||
status_code = case summary[:status]
|
||||
when "ok" then :ok
|
||||
when "degraded" then :service_unavailable
|
||||
else :service_unavailable
|
||||
end
|
||||
|
||||
render json: summary, status: status_code
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def authorize_deep_health!
|
||||
token = ENV["OPS_HEALTH_TOKEN"].presence
|
||||
return if token.blank?
|
||||
|
||||
provided = request.headers["X-Ops-Token"].presence || params[:token].presence
|
||||
return head :unauthorized if provided.blank?
|
||||
|
||||
head :unauthorized unless ActiveSupport::SecurityUtils.secure_compare(provided, token)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,39 @@
|
||||
module Public
|
||||
class AccountsController < WebBaseController
|
||||
before_action :require_login!
|
||||
|
||||
def show
|
||||
end
|
||||
|
||||
def update
|
||||
name = params[:name].to_s.strip
|
||||
if name.blank?
|
||||
flash.now[:alert] = t("flash.accounts.name_required")
|
||||
return render :show, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
if current_user.update(name: name)
|
||||
redirect_to public_account_path, notice: t("flash.accounts.profile_updated")
|
||||
else
|
||||
flash.now[:alert] = current_user.errors.full_messages.to_sentence
|
||||
render :show, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def update_password
|
||||
result = Users::ChangePassword.call(
|
||||
user: current_user,
|
||||
current_password: params[:current_password],
|
||||
password: params[:password],
|
||||
password_confirmation: params[:password_confirmation]
|
||||
)
|
||||
|
||||
unless result.ok?
|
||||
redirect_to public_account_path, alert: t("flash.accounts.password_#{result.error}")
|
||||
return
|
||||
end
|
||||
|
||||
redirect_to public_account_path, notice: t("flash.accounts.password_updated")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,120 @@
|
||||
module Public
|
||||
class ClubBillingController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_club
|
||||
before_action :require_club_owner_for_club!
|
||||
|
||||
def profile
|
||||
end
|
||||
|
||||
def update_profile
|
||||
@club.assign_attributes(billing_profile_params)
|
||||
if @club.save(context: :billing_profile)
|
||||
if premium_checkout_return_params.present? && @club.billing_profile_complete?
|
||||
if @club.active_billing_quote.present?
|
||||
redirect_to public_club_billing_path(@club), notice: t("flash.club_billing.profile_updated")
|
||||
else
|
||||
redirect_to public_club_checkout_path(
|
||||
@club,
|
||||
plan: premium_checkout_return_params[:plan],
|
||||
interval: premium_checkout_return_params[:interval]
|
||||
), notice: t("flash.club_billing.profile_saved_proceed_payment")
|
||||
end
|
||||
else
|
||||
redirect_to public_club_billing_path(@club), notice: t("flash.club_billing.profile_updated")
|
||||
end
|
||||
else
|
||||
flash.now[:alert] = @club.errors.full_messages.join(", ")
|
||||
render :profile, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def cancel_subscription
|
||||
unless MatchLiveTv.stripe_enabled?
|
||||
redirect_to public_club_billing_path(@club), alert: t("flash.club_billing.stripe_not_configured")
|
||||
return
|
||||
end
|
||||
|
||||
Billing::Stripe::CancelSubscription.call(club: @club)
|
||||
sub = @club.subscription.reload
|
||||
date = sub.current_period_end ? helpers.l_local(sub.current_period_end.to_date) : t("billing.subscription_status.end_of_period")
|
||||
redirect_to public_club_billing_path(@club),
|
||||
notice: t("flash.club_billing.subscription_canceled", date: date)
|
||||
rescue ArgumentError, RuntimeError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
rescue ::Stripe::StripeError => e
|
||||
redirect_to public_club_billing_path(@club), alert: t("flash.club_billing.stripe_error", message: e.message)
|
||||
end
|
||||
|
||||
def request_bank_transfer
|
||||
if @club.subscription&.admin_comped?
|
||||
redirect_to public_club_billing_path(@club), alert: t("flash.clubs.comped_change_denied")
|
||||
return
|
||||
end
|
||||
|
||||
unless @club.billing_profile_complete?
|
||||
redirect_to public_club_billing_profile_path(@club, plan: params[:plan], interval: params[:interval]),
|
||||
alert: t("flash.clubs.complete_billing_first")
|
||||
return
|
||||
end
|
||||
|
||||
Billing::RequestBankTransfer.call(
|
||||
club: @club,
|
||||
user: current_user,
|
||||
plan_slug: params[:plan],
|
||||
interval: params[:interval]
|
||||
)
|
||||
redirect_to public_club_billing_path(@club), notice: t("flash.club_billing.bank_transfer_requested")
|
||||
rescue Billing::RequestBankTransfer::Error, ArgumentError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
end
|
||||
|
||||
def download_invoice
|
||||
invoice = @club.billing_invoices.find(params[:invoice_id])
|
||||
unless invoice.pdf.attached?
|
||||
redirect_to public_club_billing_path(@club), alert: t("flash.club_billing.invoice_pdf_unavailable")
|
||||
return
|
||||
end
|
||||
|
||||
redirect_to rails_blob_path(invoice.pdf, disposition: "attachment"), allow_other_host: true
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_club
|
||||
@club = current_user.owned_clubs.find(params[:id])
|
||||
end
|
||||
|
||||
def require_club_owner_for_club!
|
||||
require_club_owner!(@club)
|
||||
end
|
||||
|
||||
def premium_checkout_return_params
|
||||
plan = params[:plan].presence_in(%w[premium_light premium_full])
|
||||
return nil if plan.blank?
|
||||
|
||||
{
|
||||
plan: plan,
|
||||
interval: params[:interval].presence || Billing::Stripe::PriceCatalog::DEFAULT_INTERVAL
|
||||
}
|
||||
end
|
||||
|
||||
def billing_profile_params
|
||||
params.require(:club).permit(
|
||||
:billing_entity_type,
|
||||
:billing_legal_name,
|
||||
:billing_vat_number,
|
||||
:billing_fiscal_code,
|
||||
:billing_email,
|
||||
:billing_phone,
|
||||
:billing_address_line,
|
||||
:billing_city,
|
||||
:billing_province,
|
||||
:billing_postal_code,
|
||||
:billing_country,
|
||||
:billing_recipient_code,
|
||||
:billing_pec
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,85 @@
|
||||
module Public
|
||||
class ClubMatchesController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_club
|
||||
before_action :load_schedulable_teams
|
||||
before_action :require_any_schedulable_team!
|
||||
|
||||
def new
|
||||
@match = default_match_for_form
|
||||
@selected_team = resolve_selected_team
|
||||
end
|
||||
|
||||
def create
|
||||
@selected_team = @schedulable_teams.find { |t| t.id.to_s == params[:team_id].to_s }
|
||||
unless @selected_team
|
||||
@match = default_match_for_form
|
||||
flash.now[:alert] = t("flash.club_matches.invalid_team")
|
||||
return render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
@match = @selected_team.matches.create!(
|
||||
match_params.merge(sport: @selected_team.sport, sets_to_win: 3)
|
||||
)
|
||||
redirect_to public_live_index_path(club_id: @club.id),
|
||||
notice: t("flash.club_matches.scheduled", team: @selected_team.name, opponent: @match.opponent_name)
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
@match = @selected_team.matches.build(match_params)
|
||||
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_club
|
||||
@club = Club.find(params[:club_id])
|
||||
end
|
||||
|
||||
def load_schedulable_teams
|
||||
@schedulable_teams = current_user.schedulable_teams_for(@club)
|
||||
@club_admin = @club.owned_by?(current_user)
|
||||
end
|
||||
|
||||
def require_any_schedulable_team!
|
||||
return if @schedulable_teams.any?
|
||||
|
||||
redirect_to public_live_index_path(club_id: @club.id),
|
||||
alert: t("flash.club_matches.no_schedulable_teams")
|
||||
end
|
||||
|
||||
def resolve_selected_team
|
||||
if params[:team_id].present?
|
||||
@schedulable_teams.find { |t| t.id.to_s == params[:team_id].to_s }
|
||||
end || @schedulable_teams.first
|
||||
end
|
||||
|
||||
def default_match_for_form
|
||||
team = resolve_selected_team
|
||||
Match.new(
|
||||
sport: team&.sport || @club.sport,
|
||||
sets_to_win: 3,
|
||||
scheduled_at: default_scheduled_at
|
||||
)
|
||||
end
|
||||
|
||||
def match_params
|
||||
p = params.require(:match).permit(:opponent_name, :location, :scheduled_at)
|
||||
p[:scheduled_at] = parse_scheduled_at(p[:scheduled_at]) if p[:scheduled_at].present?
|
||||
p
|
||||
end
|
||||
|
||||
def parse_scheduled_at(value)
|
||||
raw = value.to_s.strip
|
||||
return nil if raw.blank?
|
||||
|
||||
Time.zone.strptime(raw, "%Y-%m-%dT%H:%M")
|
||||
rescue ArgumentError
|
||||
Time.zone.parse(raw)
|
||||
end
|
||||
|
||||
def default_scheduled_at
|
||||
t = Time.current + 2.hours
|
||||
Time.zone.local(t.year, t.month, t.day, t.hour, 0, 0)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,28 @@
|
||||
module Public
|
||||
class ClubRecordingsController < WebBaseController
|
||||
include Recordings::ClubArchiveActions
|
||||
helper RecordingsArchiveHelper
|
||||
|
||||
before_action :require_login!
|
||||
before_action :require_club_recording_manager!
|
||||
|
||||
private
|
||||
|
||||
def archive_namespace
|
||||
:public
|
||||
end
|
||||
|
||||
def authorize_recording_management!
|
||||
return if Recordings::AccessPolicy.new(@recording, viewer: current_user).manage_allowed?
|
||||
|
||||
raise ActiveRecord::RecordNotFound
|
||||
end
|
||||
|
||||
def require_club_recording_manager!
|
||||
return if current_user.owned_clubs.exists?(id: @club.id)
|
||||
return if current_user.manageable_teams.joins(:club).exists?(clubs: { id: @club.id })
|
||||
|
||||
redirect_to public_clubs_path, alert: t("flash.club_recordings.not_authorized")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,268 @@
|
||||
module Public
|
||||
class ClubsController < WebBaseController
|
||||
include BrandingAttachments
|
||||
|
||||
before_action :require_login!
|
||||
before_action :set_club, only: %i[show edit update billing checkout portal youtube_connect youtube_disconnect]
|
||||
before_action :require_billing_profile_for_premium_checkout!, only: :checkout
|
||||
|
||||
def new
|
||||
redirect_to public_club_path(current_user.primary_club) if current_user.primary_club
|
||||
end
|
||||
|
||||
def create
|
||||
if current_user.owned_clubs.exists?
|
||||
redirect_to public_club_path(current_user.primary_club), alert: t("flash.clubs.already_registered")
|
||||
return
|
||||
end
|
||||
|
||||
club = Club.new(club_params)
|
||||
attach_branding_logo(club)
|
||||
club.save!
|
||||
|
||||
ClubMembership.create!(user: current_user, club: club, role: "owner")
|
||||
|
||||
first_team_name = params.dig(:first_team, :name).presence || t("club.new.default_first_team_name")
|
||||
first_team = club.teams.create!(
|
||||
name: first_team_name,
|
||||
sport: club.sport
|
||||
)
|
||||
|
||||
desired_plan = params[:plan].presence_in(%w[free premium_light premium_full]) || "free"
|
||||
Billing::AssignPlan.call(club: club, plan_slug: "free")
|
||||
Teams::StaffAssignment.designate_club_owner!(team: first_team, user: current_user)
|
||||
|
||||
if desired_plan.in?(%w[premium_light premium_full])
|
||||
interval = Billing::Stripe::PriceCatalog::DEFAULT_INTERVAL
|
||||
if MatchLiveTv.stripe_enabled?
|
||||
unless club.billing_profile_complete?
|
||||
redirect_to public_club_billing_profile_path(club, plan: desired_plan, interval: interval),
|
||||
alert: t("flash.clubs.complete_billing_first")
|
||||
return
|
||||
end
|
||||
|
||||
redirect_to public_club_checkout_path(club, plan: desired_plan, interval: interval)
|
||||
else
|
||||
redirect_to public_club_billing_path(club), notice: t("flash.clubs.created_complete_subscription")
|
||||
end
|
||||
else
|
||||
redirect_to public_club_path(club), notice: t("flash.clubs.created")
|
||||
end
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def show
|
||||
require_club_owner!(@club)
|
||||
apply_checkout_flash!
|
||||
@entitlements_team = @club.teams.visible.first
|
||||
@entitlements = @entitlements_team&.entitlements
|
||||
@teams = @club.teams.visible.order(:name)
|
||||
@replay_stats = Recordings::ClubStats.new(@club).call if @entitlements&.can_access_recordings?
|
||||
end
|
||||
|
||||
def edit
|
||||
require_club_owner!(@club)
|
||||
@entitlements = @club.teams.first&.entitlements
|
||||
end
|
||||
|
||||
def update
|
||||
require_club_owner!(@club)
|
||||
@entitlements = @club.teams.first!.entitlements
|
||||
@club.assign_attributes(club_params)
|
||||
attach_branding_logo(@club)
|
||||
attach_cover_image(@club, entitlements: @entitlements)
|
||||
@club.save!
|
||||
enqueue_cover_slate_generation(@club)
|
||||
redirect_to public_club_path(@club), notice: t("flash.clubs.updated")
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
@entitlements = @club.teams.first&.entitlements
|
||||
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||
render :edit, status: :unprocessable_entity
|
||||
rescue Teams::EntitlementError, BrandingAttachments::CoverUploadError => e
|
||||
@entitlements = @club.teams.first&.entitlements
|
||||
flash.now[:alert] = e.message
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def billing
|
||||
require_club_owner!(@club)
|
||||
sync_checkout_return!
|
||||
finalize_subscription_if_due!
|
||||
@subscription = @club.subscription&.reload
|
||||
apply_checkout_flash!
|
||||
@team = @club.teams.first!
|
||||
@entitlements = @team.entitlements
|
||||
@plans = Plan.ordered
|
||||
@payments = @club.billing_payments.recent.includes(:invoice).limit(50)
|
||||
@quote = @club.active_billing_quote
|
||||
@pending_transfer = @club.billing_transfer_orders.awaiting_payment.first
|
||||
end
|
||||
|
||||
def checkout
|
||||
require_club_owner!(@club)
|
||||
if @club.subscription&.admin_comped?
|
||||
redirect_to public_club_billing_path(@club),
|
||||
alert: t("flash.clubs.comped_change_denied")
|
||||
return
|
||||
end
|
||||
|
||||
if @club.active_billing_quote.present?
|
||||
redirect_to public_club_billing_path(@club),
|
||||
alert: t("flash.club_billing.quote_checkout_denied")
|
||||
return
|
||||
end
|
||||
|
||||
unless MatchLiveTv.stripe_enabled?
|
||||
redirect_to public_club_billing_path(@club), alert: t("flash.clubs.stripe_not_configured")
|
||||
return
|
||||
end
|
||||
|
||||
plan_slug = params[:plan].presence_in(%w[premium_light premium_full]) || "premium_light"
|
||||
interval = checkout_interval_param
|
||||
target_plan = Plan[plan_slug]
|
||||
sub = @club.subscription
|
||||
|
||||
if sub&.stripe_subscription_id.present? && sub.active? &&
|
||||
sub.plan.slug == plan_slug && sub.billing_interval == interval && !sub.plan_change_pending?
|
||||
redirect_to public_club_billing_path(@club),
|
||||
notice: t("flash.clubs.already_on_plan", plan: target_plan.name, price: Billing::Stripe::PriceCatalog.label(plan_slug: plan_slug, interval: interval))
|
||||
return
|
||||
end
|
||||
|
||||
if sub&.plan_change_pending? && sub.pending_plan&.slug == plan_slug &&
|
||||
sub.pending_billing_interval == interval
|
||||
when_label = sub.current_period_end.present? ? I18n.l(sub.current_period_end, format: :long) : t("billing.messages.next_renewal")
|
||||
redirect_to public_club_billing_path(@club),
|
||||
notice: t("flash.clubs.change_already_scheduled", plan: target_plan.name, date: when_label)
|
||||
return
|
||||
end
|
||||
|
||||
if sub&.stripe_subscription_id.present? && sub.active?
|
||||
result = Billing::Stripe::ChangePlan.call(club: @club, plan_slug: plan_slug, interval: interval)
|
||||
redirect_to public_club_billing_path(@club),
|
||||
notice: Billing::Stripe::PlanChangeMessages.flash_notice(
|
||||
result,
|
||||
current_plan: sub.plan
|
||||
)
|
||||
else
|
||||
url = Billing::Stripe::CheckoutSession.new(
|
||||
club: @club, user: current_user, plan_slug: plan_slug, interval: interval
|
||||
).url
|
||||
redirect_to url, allow_other_host: true
|
||||
end
|
||||
rescue ArgumentError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
rescue ::Stripe::StripeError => e
|
||||
Rails.logger.warn("[Stripe checkout] #{e.message}")
|
||||
redirect_to public_club_billing_path(@club), alert: t("flash.clubs.stripe_error", message: e.message)
|
||||
end
|
||||
|
||||
def youtube_connect
|
||||
require_club_owner!(@club)
|
||||
entitlements = @club.teams.first!.entitlements
|
||||
entitlements.assert_can_connect_youtube!
|
||||
|
||||
if ENV["YOUTUBE_CLIENT_ID"].blank?
|
||||
redirect_to public_club_path(@club), alert: t("flash.clubs.youtube_oauth_not_configured")
|
||||
return
|
||||
end
|
||||
|
||||
return_app = params[:return_app] == "1"
|
||||
state = Youtube::OauthState.for_club(
|
||||
club_id: @club.id,
|
||||
user_id: current_user.id,
|
||||
return_app: return_app
|
||||
)
|
||||
redirect_to Youtube::OauthUrl.build(state: state), allow_other_host: true
|
||||
rescue Teams::EntitlementError => e
|
||||
redirect_to public_club_path(@club), alert: e.message
|
||||
end
|
||||
|
||||
def youtube_disconnect
|
||||
require_club_owner!(@club)
|
||||
@club.youtube_credential&.destroy!
|
||||
redirect_to public_club_path(@club), notice: t("flash.clubs.youtube_disconnected")
|
||||
end
|
||||
|
||||
def portal
|
||||
require_club_owner!(@club)
|
||||
unless MatchLiveTv.stripe_enabled?
|
||||
redirect_to public_club_billing_path(@club), alert: t("flash.clubs.portal_not_configured")
|
||||
return
|
||||
end
|
||||
|
||||
url = Billing::Stripe::CheckoutSession.new(club: @club, user: current_user).portal_url
|
||||
redirect_to url, allow_other_host: true
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_club
|
||||
@club = current_user.owned_clubs.find(params[:id])
|
||||
end
|
||||
|
||||
def club_params
|
||||
p = params.require(:club).permit(
|
||||
:name, :sport, :logo_url, :primary_color, :secondary_color,
|
||||
:billing_entity_type, :billing_legal_name, :billing_vat_number, :billing_fiscal_code,
|
||||
:billing_email, :billing_phone, :billing_address_line, :billing_city, :billing_province,
|
||||
:billing_postal_code, :billing_country, :billing_recipient_code, :billing_pec
|
||||
)
|
||||
p[:primary_color] = normalize_hex_color(p[:primary_color], "#e53935")
|
||||
p[:secondary_color] = normalize_hex_color(p[:secondary_color], "#ffffff")
|
||||
p[:sport] = Sports::Catalog.normalize_key(p[:sport]) if p[:sport].present?
|
||||
p
|
||||
end
|
||||
|
||||
def require_billing_profile_for_premium_checkout!
|
||||
require_club_owner!(@club)
|
||||
plan_slug = params[:plan].presence_in(%w[premium_light premium_full])
|
||||
return if plan_slug.blank?
|
||||
return if @club.billing_profile_complete?
|
||||
|
||||
redirect_to public_club_billing_profile_path(
|
||||
@club,
|
||||
plan: plan_slug,
|
||||
interval: params[:interval].presence
|
||||
), alert: t("flash.clubs.complete_billing_first")
|
||||
end
|
||||
|
||||
def checkout_interval_param
|
||||
Billing::Stripe::PriceCatalog.normalize_interval(params[:interval])
|
||||
rescue ArgumentError
|
||||
Billing::Stripe::PriceCatalog::DEFAULT_INTERVAL
|
||||
end
|
||||
|
||||
def finalize_subscription_if_due!
|
||||
return unless MatchLiveTv.stripe_enabled?
|
||||
|
||||
Billing::Stripe::FinalizeSubscription.call(club: @club)
|
||||
rescue ::Stripe::StripeError => e
|
||||
Rails.logger.warn("[Stripe finalize subscription] #{e.message}")
|
||||
end
|
||||
|
||||
def sync_checkout_return!
|
||||
return unless params[:checkout] == "success"
|
||||
return unless MatchLiveTv.stripe_enabled?
|
||||
|
||||
Billing::Stripe::CheckoutSync.call(
|
||||
club: @club,
|
||||
session_id: params[:session_id].presence
|
||||
)
|
||||
rescue ::Stripe::StripeError => e
|
||||
Rails.logger.warn("[Stripe checkout sync] #{e.message}")
|
||||
end
|
||||
|
||||
def apply_checkout_flash!
|
||||
case params[:checkout]
|
||||
when "success"
|
||||
plan_name = @subscription&.plan&.name || "Premium"
|
||||
flash.now[:notice] = t("flash.clubs.checkout_success", plan: plan_name)
|
||||
when "canceled"
|
||||
flash.now[:alert] = t("flash.clubs.checkout_canceled")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,46 @@
|
||||
module Public
|
||||
class ContactsController < WebBaseController
|
||||
def show
|
||||
@inquiry = empty_inquiry
|
||||
end
|
||||
|
||||
def create
|
||||
result = Contacts::SubmitInquiry.call(params: inquiry_params, ip: request.remote_ip)
|
||||
|
||||
if result.ok
|
||||
redirect_to public_contatti_path, notice: t("flash.contacts.sent")
|
||||
return
|
||||
end
|
||||
|
||||
@inquiry = inquiry_params
|
||||
flash.now[:alert] = t("flash.contacts.#{result.error}")
|
||||
render :show, status: result.error == :throttled ? :too_many_requests : :unprocessable_entity
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def inquiry_params
|
||||
{
|
||||
name: params[:name].to_s,
|
||||
email: params[:email].to_s,
|
||||
club_name: params[:club_name].to_s,
|
||||
topic: params[:topic].to_s,
|
||||
message: params[:message].to_s,
|
||||
website: params[:website].to_s,
|
||||
accept_privacy: params[:accept_privacy].to_s
|
||||
}
|
||||
end
|
||||
|
||||
def empty_inquiry
|
||||
{
|
||||
name: "",
|
||||
email: "",
|
||||
club_name: "",
|
||||
topic: "commercial",
|
||||
message: "",
|
||||
website: "",
|
||||
accept_privacy: ""
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,42 @@
|
||||
module Public
|
||||
class InvitationsController < WebBaseController
|
||||
def show
|
||||
@token = params[:token]
|
||||
digest = Digest::SHA256.hexdigest(@token.to_s)
|
||||
@invitation = TeamInvitation.pending.find_by(token_digest: digest)
|
||||
@tournament_invitation = TournamentBroadcastInvitation.pending.find_by(token_digest: digest) unless @invitation
|
||||
unless @invitation || @tournament_invitation
|
||||
redirect_to public_pricing_path, alert: t("flash.invitations.invalid_or_expired")
|
||||
end
|
||||
end
|
||||
|
||||
def accept
|
||||
token = params[:token].to_s
|
||||
digest = Digest::SHA256.hexdigest(token)
|
||||
invitation = TeamInvitation.pending.find_by(token_digest: digest)
|
||||
tournament_invitation = TournamentBroadcastInvitation.pending.find_by(token_digest: digest) unless invitation
|
||||
|
||||
unless invitation || tournament_invitation
|
||||
return redirect_to public_pricing_path, alert: t("flash.invitations.invalid")
|
||||
end
|
||||
|
||||
target_email = (invitation || tournament_invitation).email
|
||||
unless logged_in?
|
||||
session[:pending_invite_token] = token
|
||||
return redirect_to public_signup_path, notice: t("flash.invitations.signup_to_accept", email: target_email)
|
||||
end
|
||||
|
||||
if current_user.email.downcase != target_email.downcase
|
||||
return redirect_to public_pricing_path, alert: t("flash.invitations.wrong_email", email: target_email)
|
||||
end
|
||||
|
||||
if invitation
|
||||
invitation.accept!(current_user)
|
||||
redirect_to public_team_details_path(invitation.team), notice: t("flash.invitations.joined_team")
|
||||
else
|
||||
tournament_invitation.accept!(current_user)
|
||||
redirect_to public_account_path, notice: t("flash.invitations.joined_tournament")
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,99 @@
|
||||
module Public
|
||||
class LiveController < SiteBaseController
|
||||
include MediamtxPlayback
|
||||
|
||||
layout "marketing_live"
|
||||
|
||||
ACTIVE_STATUSES = %w[live connecting reconnecting].freeze
|
||||
|
||||
def index
|
||||
@query = params[:q].to_s.strip
|
||||
@club = Club.find_by(id: params[:club_id]) if params[:club_id].present?
|
||||
team_ids = @club&.teams&.pluck(:id)
|
||||
|
||||
sessions = StreamSession
|
||||
.broadcasting
|
||||
.publicly_listed
|
||||
.where(platform: "matchlivetv")
|
||||
.includes(:score_state, match: { team: :club })
|
||||
sessions = sessions.joins(:match).where(matches: { team_id: team_ids }) if team_ids.present?
|
||||
|
||||
@sessions = sessions
|
||||
.search_by_team_or_opponent(@query)
|
||||
.order(Arel.sql("started_at DESC NULLS LAST"), created_at: :desc)
|
||||
|
||||
# Solo dirette già in onda: le partite «programmate» restano visibili anche se c’è sessione idle.
|
||||
broadcasting_match_ids = StreamSession.broadcasting.select(:match_id)
|
||||
upcoming = Match.scheduled_for_live.includes(team: :club)
|
||||
upcoming = upcoming.where(team_id: team_ids) if team_ids.present?
|
||||
|
||||
@upcoming_matches = upcoming
|
||||
.search_teams_or_opponents(@query)
|
||||
.where.not(id: broadcasting_match_ids)
|
||||
.order(scheduled_at: :asc)
|
||||
.limit(50)
|
||||
|
||||
tournaments = Tournament.listed_on_live.with_attached_logo_file.includes(:club).search_public(@query)
|
||||
tournaments = tournaments.where(club_id: @club.id) if @club
|
||||
@public_tournaments = tournaments.order(starts_on: :desc, name: :asc).limit(12)
|
||||
|
||||
@online_paths = fetch_online_paths
|
||||
|
||||
return unless logged_in? && @club
|
||||
|
||||
@schedulable_teams = current_user.schedulable_teams_for(@club)
|
||||
@can_schedule_match = @schedulable_teams.any?
|
||||
end
|
||||
|
||||
def show
|
||||
@session = StreamSession.includes(match: { team: :club }).find(params[:id])
|
||||
@session = Mediamtx::PublisherSync.new(@session).call unless @session.terminal?
|
||||
@match = @session.match
|
||||
@stream_closed = @session.terminal?
|
||||
@on_air = !@stream_closed && (
|
||||
mediamtx_stream_playable?(@session) ||
|
||||
@session.status.in?(%w[connecting live reconnecting paused])
|
||||
)
|
||||
@publisher_online = !@stream_closed && mediamtx_publisher_online?(@session)
|
||||
@cover_poster_url = Streams::CoverResolver.new(@match).effective_cover_url
|
||||
end
|
||||
|
||||
def status
|
||||
# Mai cache: il tabellone deve restare allineato con l'app (poll ogni ~1,5s).
|
||||
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
|
||||
response.headers["Pragma"] = "no-cache"
|
||||
|
||||
session = StreamSession.includes(match: { team: :club }).find(params[:id])
|
||||
session = Mediamtx::PublisherSync.new(session).call unless session.terminal?
|
||||
closed = session.terminal?
|
||||
publisher_online = !closed && mediamtx_publisher_online?(session)
|
||||
playable = !closed && mediamtx_stream_playable?(session)
|
||||
render json: {
|
||||
status: session.status,
|
||||
paused: session.paused?,
|
||||
stream_closed: closed,
|
||||
live: !closed && (
|
||||
session.live? || session.paused? || session.connecting? || session.reconnecting? ||
|
||||
mediamtx_publisher_online?(session)
|
||||
),
|
||||
on_air: playable || (!closed && session.status.in?(%w[connecting live reconnecting paused])),
|
||||
publisher_online: publisher_online,
|
||||
awaiting_signal: !closed && !mediamtx_path_has_output?(session),
|
||||
showing_cover: !closed && mediamtx_path_has_output?(session) &&
|
||||
(session.paused? || !mediamtx_publisher_online?(session)),
|
||||
ended_at: session.ended_at,
|
||||
home_name: session.match.team.name,
|
||||
away_name: session.match.opponent_name,
|
||||
score: session.score_state&.as_cable_payload
|
||||
}
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def fetch_online_paths
|
||||
Mediamtx::Client.new.online_path_names
|
||||
rescue Mediamtx::Client::Error, Errno::ECONNREFUSED, SocketError
|
||||
[]
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
module Public
|
||||
class LocalesController < SiteBaseController
|
||||
def update
|
||||
locale = LocaleResolver.persist!(cookies, params[:locale])
|
||||
I18n.locale = locale
|
||||
redirect_back fallback_location: root_path
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,100 @@
|
||||
module Public
|
||||
class MatchesController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_team
|
||||
before_action :require_can_schedule!
|
||||
before_action :set_match, only: %i[edit update destroy]
|
||||
|
||||
def index
|
||||
@matches = @team.matches
|
||||
.includes(:stream_sessions)
|
||||
.order(Arel.sql("scheduled_at ASC NULLS LAST"), created_at: :desc)
|
||||
@can_manage = @team.club.owned_by?(current_user)
|
||||
end
|
||||
|
||||
def new
|
||||
@match = @team.matches.build(
|
||||
sport: @team.sport,
|
||||
sets_to_win: 3,
|
||||
scheduled_at: default_scheduled_at
|
||||
)
|
||||
end
|
||||
|
||||
def create
|
||||
@match = @team.matches.create!(
|
||||
match_params.merge(sport: @team.sport, sets_to_win: match_params[:sets_to_win].presence || 3)
|
||||
)
|
||||
redirect_to public_team_matches_path(@team),
|
||||
notice: t("flash.matches.scheduled", opponent: @match.opponent_name)
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
@match = @team.matches.build(match_params)
|
||||
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def edit
|
||||
end
|
||||
|
||||
def update
|
||||
@match.update!(match_params)
|
||||
redirect_to public_team_matches_path(@team), notice: t("flash.matches.updated")
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def destroy
|
||||
active = active_session_for(@match)
|
||||
if active&.resumable?
|
||||
redirect_to public_team_matches_path(@team),
|
||||
alert: t("flash.matches.close_live_before_delete")
|
||||
return
|
||||
end
|
||||
|
||||
@match.destroy!
|
||||
redirect_to public_team_matches_path(@team), notice: t("flash.matches.deleted")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_team
|
||||
@team = current_user.manageable_teams.find(params[:team_id])
|
||||
@club = @team.club
|
||||
end
|
||||
|
||||
def require_can_schedule!
|
||||
return if current_user.can_schedule_for?(@team)
|
||||
|
||||
redirect_to public_team_details_path(@team),
|
||||
alert: t("flash.matches.schedule_denied")
|
||||
end
|
||||
|
||||
def set_match
|
||||
@match = @team.matches.find(params[:id])
|
||||
end
|
||||
|
||||
def match_params
|
||||
p = params.require(:match).permit(:opponent_name, :location, :scheduled_at, :sport, :sets_to_win)
|
||||
p[:scheduled_at] = parse_scheduled_at(p[:scheduled_at]) if p[:scheduled_at].present?
|
||||
p
|
||||
end
|
||||
|
||||
def parse_scheduled_at(value)
|
||||
raw = value.to_s.strip
|
||||
return nil if raw.blank?
|
||||
|
||||
Time.zone.strptime(raw, "%Y-%m-%dT%H:%M")
|
||||
rescue ArgumentError
|
||||
Time.zone.parse(raw)
|
||||
end
|
||||
|
||||
def default_scheduled_at
|
||||
t = Time.current + 2.hours
|
||||
Time.zone.local(t.year, t.month, t.day, t.hour, 0, 0)
|
||||
end
|
||||
|
||||
def active_session_for(match)
|
||||
match.active_stream_session
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,46 @@
|
||||
module Public
|
||||
class PagesController < WebBaseController
|
||||
def home
|
||||
end
|
||||
|
||||
def features
|
||||
end
|
||||
|
||||
def pricing
|
||||
@plans = Plan.ordered
|
||||
load_club_billing_context_for_pricing
|
||||
end
|
||||
|
||||
def support
|
||||
@app_store_review_chrome = true
|
||||
end
|
||||
|
||||
def privacy
|
||||
end
|
||||
|
||||
def terms
|
||||
end
|
||||
|
||||
def cookies
|
||||
end
|
||||
|
||||
def faq
|
||||
end
|
||||
|
||||
def pallavolo
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def load_club_billing_context_for_pricing
|
||||
return unless logged_in?
|
||||
|
||||
@club = current_user.primary_club
|
||||
return unless @club
|
||||
|
||||
@subscription = @club.subscription
|
||||
@team = @club.teams.order(:name).first
|
||||
@entitlements = @team&.entitlements
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,54 @@
|
||||
module Public
|
||||
class PasswordResetsController < WebBaseController
|
||||
def new
|
||||
end
|
||||
|
||||
def create
|
||||
Users::RequestPasswordReset.call(email: params[:email])
|
||||
|
||||
redirect_to public_login_path,
|
||||
notice: t("flash.password_resets.email_sent")
|
||||
end
|
||||
|
||||
def edit
|
||||
@user = User.find_by_password_reset_token(params[:token])
|
||||
if @user.nil? || @user.password_reset_expired?
|
||||
redirect_to public_password_forgot_path,
|
||||
alert: t("flash.password_resets.invalid_or_expired_link")
|
||||
return
|
||||
end
|
||||
@token = params[:token]
|
||||
end
|
||||
|
||||
def update
|
||||
@user = User.find_by_password_reset_token(params[:token])
|
||||
if @user.nil? || @user.password_reset_expired?
|
||||
redirect_to public_password_forgot_path,
|
||||
alert: t("flash.password_resets.invalid_or_expired_link")
|
||||
return
|
||||
end
|
||||
|
||||
if params[:password] != params[:password_confirmation]
|
||||
flash.now[:alert] = t("flash.password_resets.password_mismatch")
|
||||
@token = params[:token]
|
||||
return render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
if (code = PasswordComplexity.violation(params[:password]))
|
||||
flash.now[:alert] = t("flash.password_resets.password_#{code == :blank ? :too_short : code}")
|
||||
@token = params[:token]
|
||||
return render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
if PasswordComplexity.same_as_current?(@user, params[:password])
|
||||
flash.now[:alert] = t("flash.password_resets.password_same_as_current")
|
||||
@token = params[:token]
|
||||
return render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
@user.update!(password: params[:password])
|
||||
@user.clear_password_reset!
|
||||
redirect_to public_login_path, notice: t("flash.password_resets.password_updated")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,115 @@
|
||||
module Public
|
||||
class RegiaController < SiteBaseController
|
||||
include Public::LiveHelper
|
||||
include Public::RegiaHelper
|
||||
include MediamtxPlayback
|
||||
|
||||
layout "regia"
|
||||
|
||||
protect_from_forgery with: :null_session
|
||||
skip_before_action :verify_authenticity_token, only: %i[score pause resume stop audio_mute min_quality]
|
||||
|
||||
before_action :set_session_from_token
|
||||
|
||||
def show
|
||||
@match = @session.match
|
||||
@team = @match.team
|
||||
@score = @session.score_state || Scoring::Engine.ensure_score_for(@session)
|
||||
@rules = Scoring::Rules.from_match(@match)
|
||||
@stream_closed = @session.terminal?
|
||||
@on_air = !@stream_closed && (
|
||||
mediamtx_stream_playable?(@session) ||
|
||||
@session.status.in?(%w[connecting live reconnecting paused])
|
||||
)
|
||||
@regia_share_url = request.original_url
|
||||
@regia_share_title = "Regia — #{@team.name} vs #{@match.opponent_name}"
|
||||
@live_share_url = @session.share_url
|
||||
@live_share_title = "#{@team.name} vs #{@match.opponent_name} — Diretta Match Live TV"
|
||||
end
|
||||
|
||||
def status
|
||||
render json: status_payload
|
||||
end
|
||||
|
||||
def score
|
||||
cmd = params[:cmd].presence || params[:score_action].presence
|
||||
result = Scoring::ApplyAction.new(session: @session, action: cmd).call
|
||||
@session.reload
|
||||
render json: status_payload.merge(
|
||||
set_won: result.set_won,
|
||||
match_won: result.match_won,
|
||||
winner: result.winner&.to_s
|
||||
)
|
||||
rescue ArgumentError => e
|
||||
render json: { error: e.message }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def pause
|
||||
Sessions::Pause.new(@session).call
|
||||
render json: status_payload
|
||||
end
|
||||
|
||||
def resume
|
||||
Sessions::Resume.new(@session).call
|
||||
render json: status_payload
|
||||
rescue Teams::EntitlementError => e
|
||||
render json: status_payload.merge(error: e.message), status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def stop
|
||||
Sessions::Stop.new(@session).call
|
||||
render json: status_payload
|
||||
end
|
||||
|
||||
def audio_mute
|
||||
muted = params.key?(:muted) ? params[:muted] : !@session.audio_muted
|
||||
Sessions::SetAudioMute.new(@session, muted: muted).call
|
||||
render json: status_payload
|
||||
end
|
||||
|
||||
def min_quality
|
||||
Sessions::SetMinQuality.new(@session, preset: params[:min_quality_preset]).call
|
||||
render json: status_payload
|
||||
rescue ArgumentError => e
|
||||
render json: status_payload.merge(error: e.message), status: :unprocessable_entity
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def camera_telemetry_payload(publisher_online)
|
||||
cam = @session.device_states.find_by(device_role: "camera")
|
||||
(cam&.as_regia_payload || {}).merge(publisher_online: publisher_online)
|
||||
end
|
||||
|
||||
def set_session_from_token
|
||||
@session = Sessions::RegiaAccess.find_session_by_token(params[:token])
|
||||
return if @session
|
||||
|
||||
head :not_found
|
||||
end
|
||||
|
||||
def status_payload
|
||||
score = @session.score_state
|
||||
closed = @session.terminal?
|
||||
playable = !closed && mediamtx_stream_playable?(@session)
|
||||
publisher_online = !closed && mediamtx_publisher_online?(@session)
|
||||
{
|
||||
status: @session.status,
|
||||
paused: @session.paused?,
|
||||
audio_muted: @session.audio_muted,
|
||||
stream_closed: closed,
|
||||
live: !closed && (@session.live? || @session.paused? || publisher_online),
|
||||
on_air: playable || (!closed && @session.status.in?(%w[connecting live reconnecting paused])),
|
||||
publisher_online: publisher_online,
|
||||
ended_at: @session.ended_at,
|
||||
home_name: @session.match.team.name,
|
||||
away_name: @session.match.opponent_name,
|
||||
points_target: Scoring::Rules.points_target_for_match(@session.match, current_set: score&.current_set || 1),
|
||||
score: score&.as_cable_payload,
|
||||
min_quality_preset: @session.min_quality_preset,
|
||||
min_quality_options: Sessions::SelectQuality.allowed_min_ids(@session.quality_preset),
|
||||
telemetry: camera_telemetry_payload(publisher_online)
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,46 @@
|
||||
module Public
|
||||
class RegistrationsController < WebBaseController
|
||||
def new
|
||||
redirect_to public_club_path(current_user.primary_club) if logged_in? && current_user.primary_club
|
||||
@user = User.new
|
||||
end
|
||||
|
||||
def create
|
||||
unless params[:accept_terms] == "1"
|
||||
@user = User.new(user_params.merge(role: "coach"))
|
||||
flash.now[:alert] = t("flash.registrations.accept_terms_required")
|
||||
return render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
@user = User.new(user_params.merge(role: "coach"))
|
||||
if @user.save
|
||||
session[:user_id] = @user.id
|
||||
if session[:pending_invite_token].present?
|
||||
token = session.delete(:pending_invite_token)
|
||||
digest = Digest::SHA256.hexdigest(token)
|
||||
invitation = TeamInvitation.pending.find_by(token_digest: digest)
|
||||
if invitation && invitation.email.downcase == @user.email.downcase
|
||||
invitation.accept!(@user)
|
||||
return redirect_to public_team_details_path(invitation.team), notice: t("flash.registrations.welcome_to_team")
|
||||
end
|
||||
|
||||
tournament_invitation = TournamentBroadcastInvitation.pending.find_by(token_digest: digest)
|
||||
if tournament_invitation && tournament_invitation.email.downcase == @user.email.downcase
|
||||
tournament_invitation.accept!(@user)
|
||||
return redirect_to public_account_path, notice: t("flash.invitations.joined_tournament")
|
||||
end
|
||||
end
|
||||
redirect_to public_new_club_path, notice: t("flash.registrations.account_created")
|
||||
else
|
||||
flash.now[:alert] = @user.errors.full_messages.join(", ")
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def user_params
|
||||
params.require(:user).permit(:name, :email, :password, :password_confirmation)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,117 @@
|
||||
module Public
|
||||
class ReplayController < SiteBaseController
|
||||
include Public::LiveHelper
|
||||
|
||||
layout "marketing_live"
|
||||
|
||||
before_action :set_session_and_recording, only: %i[show stream thumbnail download]
|
||||
before_action :authorize_replay_access!, only: %i[show stream thumbnail download]
|
||||
|
||||
def index
|
||||
@query = params[:q].to_s.strip
|
||||
@recordings = Recording.ready.publicly_listed
|
||||
.includes(stream_session: { match: { team: :club } })
|
||||
.search_replays(@query)
|
||||
.order(recorded_at: :desc, created_at: :desc)
|
||||
.limit(100)
|
||||
if params[:club_id].present?
|
||||
@recordings = @recordings.joins(:team).where(teams: { club_id: params[:club_id] })
|
||||
end
|
||||
if params[:team_id].present?
|
||||
@recordings = @recordings.where(team_id: params[:team_id])
|
||||
end
|
||||
@clubs = Club.joins(teams: :recordings)
|
||||
.merge(Recording.ready.publicly_listed)
|
||||
.distinct
|
||||
.order(:name)
|
||||
@filter_club = @clubs.find { |c| c.id.to_s == params[:club_id].to_s } if params[:club_id].present?
|
||||
end
|
||||
|
||||
def show
|
||||
@match = @session.match
|
||||
end
|
||||
|
||||
def stream
|
||||
Recordings::IncrementViews.new(@recording).call
|
||||
serve_video(disposition: "inline")
|
||||
end
|
||||
|
||||
def thumbnail
|
||||
serve_thumbnail
|
||||
end
|
||||
|
||||
def download
|
||||
unless download_allowed?
|
||||
redirect_to public_replay_path(@session), alert: t("flash.replay.download_unavailable")
|
||||
return
|
||||
end
|
||||
|
||||
serve_video(disposition: "attachment")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def serve_video(disposition:)
|
||||
expires_in = disposition == "attachment" ? MatchLiveTv.replay_download_url_ttl_seconds : MatchLiveTv.replay_presigned_url_ttl_seconds
|
||||
redirect_url = Recordings::PublicMediaUrl.new(
|
||||
key: @recording.storage_key,
|
||||
expires_in: expires_in,
|
||||
disposition: disposition,
|
||||
filename: disposition == "attachment" ? download_filename : nil
|
||||
).call
|
||||
return redirect_to redirect_url, allow_other_host: true if redirect_url.present?
|
||||
|
||||
Recordings::ServeFromStorage.new(
|
||||
key: @recording.storage_key,
|
||||
content_type: "video/mp4",
|
||||
disposition: disposition,
|
||||
filename: disposition == "attachment" ? download_filename : nil
|
||||
).call(self)
|
||||
rescue ArgumentError
|
||||
head :not_found
|
||||
end
|
||||
|
||||
def serve_thumbnail
|
||||
key = @recording.thumbnail_storage_key
|
||||
return head :not_found if key.blank?
|
||||
|
||||
redirect_url = Recordings::PublicMediaUrl.new(key: key, expires_in: MatchLiveTv.replay_presigned_url_ttl_seconds).call
|
||||
return redirect_to redirect_url, allow_other_host: true if redirect_url.present?
|
||||
|
||||
Recordings::ServeFromStorage.new(
|
||||
key: key,
|
||||
content_type: "image/jpeg",
|
||||
disposition: "inline"
|
||||
).call(self)
|
||||
rescue ArgumentError
|
||||
head :not_found
|
||||
end
|
||||
|
||||
def download_allowed?
|
||||
ent = @recording.team.entitlements
|
||||
return false unless ent.phone_download_enabled?
|
||||
|
||||
Recordings::AccessPolicy.new(@recording, viewer: current_user).allowed? ||
|
||||
Recordings::AccessPolicy.new(@recording, viewer: current_user).manage_allowed?
|
||||
end
|
||||
|
||||
def download_filename
|
||||
slug = @recording.title_or_default.parameterize.presence || "replay"
|
||||
"#{slug}.mp4"
|
||||
end
|
||||
|
||||
def set_session_and_recording
|
||||
@session = StreamSession.includes(match: { team: :club }).find(params[:id])
|
||||
@recording = Recording.not_deleted.find_by(stream_session: @session)
|
||||
return if @recording
|
||||
|
||||
redirect_to public_live_path(@session), alert: t("flash.replay.not_available")
|
||||
end
|
||||
|
||||
def authorize_replay_access!
|
||||
return if Recordings::AccessPolicy.new(@recording, viewer: current_user).allowed?
|
||||
|
||||
redirect_to public_live_index_path, alert: t("flash.replay.not_available")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,36 @@
|
||||
module Public
|
||||
class SessionsController < WebBaseController
|
||||
# Logout must succeed even with a stale CSRF token (old tab after deploy /
|
||||
# session rotate). SameSite=Lax already blocks cross-site cookie POSTs.
|
||||
skip_before_action :verify_authenticity_token, only: :destroy
|
||||
|
||||
def new
|
||||
if logged_in? && current_user.primary_club
|
||||
redirect_to public_club_path(current_user.primary_club)
|
||||
end
|
||||
end
|
||||
|
||||
def create
|
||||
user = User.find_by(email: params[:email]&.downcase)
|
||||
if user&.authenticate(params[:password])
|
||||
session[:user_id] = user.id
|
||||
dest = if user.primary_club
|
||||
public_club_path(user.primary_club)
|
||||
elsif user.manageable_teams.first
|
||||
public_team_details_path(user.manageable_teams.first)
|
||||
else
|
||||
public_new_club_path
|
||||
end
|
||||
redirect_to dest, notice: t("flash.sessions.welcome_back")
|
||||
else
|
||||
flash.now[:alert] = t("flash.sessions.invalid_credentials")
|
||||
render :new, status: :unauthorized
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
reset_session
|
||||
redirect_to public_pricing_path, notice: t("flash.sessions.logged_out")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,69 @@
|
||||
module Public
|
||||
class SiteBaseController < ActionController::Base
|
||||
layout "marketing"
|
||||
|
||||
include ::SeoHelper
|
||||
include ::LegalHelper
|
||||
helper ApplicationHelper
|
||||
helper_method :current_user, :logged_in?, :current_locale, :language_options, :current_language_option
|
||||
|
||||
protect_from_forgery with: :exception
|
||||
before_action :set_site_locale
|
||||
before_action :load_site_announcements
|
||||
|
||||
private
|
||||
|
||||
def set_site_locale
|
||||
I18n.locale = LocaleResolver.resolve(
|
||||
cookie_jar: request.cookie_jar,
|
||||
accept_language: request.get_header("HTTP_ACCEPT_LANGUAGE")
|
||||
)
|
||||
end
|
||||
|
||||
def current_locale
|
||||
I18n.locale
|
||||
end
|
||||
|
||||
def language_options
|
||||
LocaleResolver.language_options
|
||||
end
|
||||
|
||||
def current_language_option
|
||||
LocaleResolver.current_language_option
|
||||
end
|
||||
|
||||
def current_user
|
||||
return @current_user if defined?(@current_user)
|
||||
|
||||
@current_user = User.find_by(id: session[:user_id]) if session[:user_id]
|
||||
end
|
||||
|
||||
def logged_in?
|
||||
current_user.present?
|
||||
end
|
||||
|
||||
PRIVATE_WEB_CONTROLLERS = %w[
|
||||
accounts clubs teams club_recordings club_billing
|
||||
club_matches matches team_roster_members
|
||||
tournaments tournament_participants tournament_groups
|
||||
tournament_matches tournament_invitations tournament_results
|
||||
].freeze
|
||||
|
||||
def load_site_announcements
|
||||
@site_announcements = if skip_site_announcements?
|
||||
AppAnnouncement.none
|
||||
else
|
||||
channel = private_web_area? ? :web_private : :web_public
|
||||
AppAnnouncement.for_channel(channel).newest
|
||||
end
|
||||
end
|
||||
|
||||
def skip_site_announcements?
|
||||
controller_name == "regia"
|
||||
end
|
||||
|
||||
def private_web_area?
|
||||
PRIVATE_WEB_CONTROLLERS.include?(controller_name)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,42 @@
|
||||
module Public
|
||||
class SitemapController < ActionController::Base
|
||||
def show
|
||||
base = MatchLiveTv.app_public_url.chomp("/")
|
||||
@entries = [
|
||||
{ loc: "#{base}/", changefreq: "weekly", priority: "1.0" },
|
||||
{ loc: "#{base}/funzionalita", changefreq: "monthly", priority: "0.9" },
|
||||
{ loc: "#{base}/prezzi", changefreq: "monthly", priority: "0.9" },
|
||||
{ loc: "#{base}/pallavolo-giovanile", changefreq: "monthly", priority: "0.85" },
|
||||
{ loc: "#{base}/faq", changefreq: "monthly", priority: "0.8" },
|
||||
{ loc: "#{base}/contatti", changefreq: "monthly", priority: "0.6" },
|
||||
{ loc: "#{base}/live", changefreq: "hourly", priority: "0.85" },
|
||||
{ loc: "#{base}/squadre", changefreq: "daily", priority: "0.85" },
|
||||
{ loc: "#{base}/tornei", changefreq: "daily", priority: "0.8" },
|
||||
{ loc: "#{base}/privacy", changefreq: "yearly", priority: "0.3" },
|
||||
{ loc: "#{base}/support", changefreq: "yearly", priority: "0.3" },
|
||||
{ loc: "#{base}/cookie", changefreq: "yearly", priority: "0.3" },
|
||||
{ loc: "#{base}/termini", changefreq: "yearly", priority: "0.3" }
|
||||
]
|
||||
|
||||
Team.find_each do |team|
|
||||
@entries << {
|
||||
loc: "#{base}/squadre/#{team.slug}",
|
||||
changefreq: "daily",
|
||||
priority: "0.7"
|
||||
}
|
||||
end
|
||||
|
||||
Tournament.visible_to_public.find_each do |tournament|
|
||||
@entries << {
|
||||
loc: "#{base}/tornei/#{tournament.slug}",
|
||||
changefreq: "daily",
|
||||
priority: "0.75"
|
||||
}
|
||||
end
|
||||
|
||||
respond_to do |format|
|
||||
format.xml { render layout: false }
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,64 @@
|
||||
module Public
|
||||
class TeamPagesController < SiteBaseController
|
||||
include Public::LiveHelper
|
||||
|
||||
layout "marketing_live"
|
||||
|
||||
def index
|
||||
@query = params[:q].to_s.strip
|
||||
@sport = params[:sport].to_s.strip.presence
|
||||
@live_filter = params[:live].present?
|
||||
@replays_filter = params[:replays].present?
|
||||
@entries = Teams::PublicDirectory.call(
|
||||
q: @query,
|
||||
sport: @sport,
|
||||
live: @live_filter,
|
||||
replays: @replays_filter
|
||||
)
|
||||
@sport_options = Sports::Catalog.as_api_list
|
||||
end
|
||||
|
||||
def show
|
||||
@team = Team.includes(:club, roster_members: []).find_by!(slug: params[:slug])
|
||||
@club = @team.club
|
||||
load_live_content!
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def load_live_content!
|
||||
@online_paths = fetch_online_paths
|
||||
|
||||
@live_sessions = StreamSession
|
||||
.broadcasting
|
||||
.publicly_listed
|
||||
.where(platform: "matchlivetv")
|
||||
.includes(:score_state, match: { team: :club })
|
||||
.joins(:match)
|
||||
.where(matches: { team_id: @team.id })
|
||||
.order(Arel.sql("started_at DESC NULLS LAST"), created_at: :desc)
|
||||
|
||||
broadcasting_match_ids = StreamSession.broadcasting.select(:match_id)
|
||||
@upcoming_matches = @team.matches
|
||||
.scheduled_for_live
|
||||
.where.not(id: broadcasting_match_ids)
|
||||
.order(scheduled_at: :asc)
|
||||
.limit(20)
|
||||
|
||||
@recordings = @team.recordings
|
||||
.ready
|
||||
.publicly_listed
|
||||
.includes(stream_session: :match)
|
||||
.order(recorded_at: :desc, created_at: :desc)
|
||||
.limit(12)
|
||||
|
||||
@roster_by_category = @team.roster_public? ? @team.roster_by_category : nil
|
||||
end
|
||||
|
||||
def fetch_online_paths
|
||||
Mediamtx::Client.new.online_path_names
|
||||
rescue Mediamtx::Client::Error, Errno::ECONNREFUSED, SocketError
|
||||
[]
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,63 @@
|
||||
module Public
|
||||
class TeamRosterMembersController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_team
|
||||
before_action :require_team_owner!
|
||||
before_action :set_member, only: %i[edit update destroy]
|
||||
|
||||
def create
|
||||
member = @team.roster_members.build(member_params)
|
||||
attach_photo(member)
|
||||
member.save!
|
||||
redirect_to public_team_details_path(@team), notice: t("flash.team_roster_members.added", name: member.full_name)
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
redirect_to public_team_details_path(@team), alert: e.record.errors.full_messages.join(", ")
|
||||
end
|
||||
|
||||
def edit
|
||||
@club = @team.club
|
||||
end
|
||||
|
||||
def update
|
||||
@member.assign_attributes(member_params)
|
||||
attach_photo(@member)
|
||||
@member.save!
|
||||
redirect_to public_team_details_path(@team), notice: t("flash.team_roster_members.updated")
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
@club = @team.club
|
||||
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def destroy
|
||||
name = @member.full_name
|
||||
@member.destroy!
|
||||
redirect_to public_team_details_path(@team), notice: t("flash.team_roster_members.removed", name: name)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_team
|
||||
@team = current_user.manageable_teams.find(params[:team_id])
|
||||
end
|
||||
|
||||
def require_team_owner!
|
||||
require_club_owner_for_team!(@team)
|
||||
end
|
||||
|
||||
def set_member
|
||||
@member = @team.roster_members.find(params[:id])
|
||||
end
|
||||
|
||||
def member_params
|
||||
params.require(:team_roster_member).permit(
|
||||
:category, :full_name, :role_label, :jersey_number, :bio, :position
|
||||
)
|
||||
end
|
||||
|
||||
def attach_photo(member)
|
||||
file = params.dig(:team_roster_member, :photo_file)
|
||||
member.photo_file.attach(file) if file.present?
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,214 @@
|
||||
module Public
|
||||
class TeamsController < WebBaseController
|
||||
include BrandingAttachments
|
||||
|
||||
before_action :require_login!
|
||||
before_action :set_club, only: %i[new create]
|
||||
before_action :set_team, only: %i[
|
||||
details dashboard roster edit update invite create_invitation
|
||||
assign_self_staff clear_self_staff remove_member destroy_invitation
|
||||
youtube_connect youtube_disconnect
|
||||
]
|
||||
|
||||
def new
|
||||
redirect_to public_new_club_path if current_user.owned_clubs.none?
|
||||
require_club_owner!(@club)
|
||||
end
|
||||
|
||||
def create
|
||||
require_club_owner!(@club)
|
||||
team = @club.teams.create!(team_params)
|
||||
attach_branding_logo(team)
|
||||
Teams::StaffAssignment.designate_club_owner!(team: team, user: current_user)
|
||||
redirect_to public_club_path(@club), notice: t("flash.teams.added", name: team.name)
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def details
|
||||
if @team.tournament_broadcast? && @team.broadcast_tournament
|
||||
redirect_to public_tournament_path(@team.broadcast_tournament)
|
||||
return
|
||||
end
|
||||
|
||||
load_team_details!
|
||||
render :details
|
||||
end
|
||||
|
||||
def dashboard
|
||||
redirect_to public_team_details_path(params[:id])
|
||||
end
|
||||
|
||||
def roster
|
||||
redirect_to public_team_details_path(params[:id])
|
||||
end
|
||||
|
||||
def edit
|
||||
require_club_owner_for_team!(@team)
|
||||
@club = @team.club
|
||||
@entitlements = @team.entitlements
|
||||
end
|
||||
|
||||
def update
|
||||
require_club_owner_for_team!(@team)
|
||||
@team.assign_attributes(team_params)
|
||||
attach_branding_logo(@team)
|
||||
attach_cover_image(@team, entitlements: @team.entitlements)
|
||||
attach_team_photo(@team)
|
||||
@team.save!
|
||||
enqueue_cover_slate_generation(@team)
|
||||
redirect_to public_team_details_path(@team), notice: t("flash.teams.updated")
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
@club = @team.club
|
||||
@entitlements = @team.entitlements
|
||||
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||
render :edit, status: :unprocessable_entity
|
||||
rescue Teams::EntitlementError, BrandingAttachments::CoverUploadError => e
|
||||
@club = @team.club
|
||||
@entitlements = @team.entitlements
|
||||
flash.now[:alert] = e.message
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def invite
|
||||
require_club_owner_for_team!(@team)
|
||||
redirect_to public_team_details_path(@team, anchor: "invita-trasmissione")
|
||||
end
|
||||
|
||||
def assign_self_staff
|
||||
require_club_owner_for_team!(@team)
|
||||
membership = current_user.user_teams.find_or_initialize_by(team: @team)
|
||||
membership.role = "member" if membership.new_record?
|
||||
Teams::StaffAssignment.call(team: @team, user: current_user, membership: membership)
|
||||
redirect_to public_team_details_path(@team), notice: t("flash.teams.now_staff")
|
||||
rescue Teams::StaffAssignmentError, Teams::EntitlementError => e
|
||||
redirect_to public_team_details_path(@team), alert: e.message
|
||||
end
|
||||
|
||||
def clear_self_staff
|
||||
require_club_owner_for_team!(@team)
|
||||
membership = current_user.user_teams.find_by(team: @team)
|
||||
membership&.update!(staff_kind: nil)
|
||||
redirect_to public_team_details_path(@team), notice: t("flash.teams.staff_role_removed")
|
||||
end
|
||||
|
||||
def create_invitation
|
||||
require_club_owner_for_team!(@team)
|
||||
@entitlements = @team.entitlements
|
||||
staff_kind = "transmission"
|
||||
@entitlements.assert_can_invite!(staff_kind: staff_kind)
|
||||
|
||||
email = params[:email]&.downcase&.strip
|
||||
Teams::StaffEmailValidator.assert_available!(team: @team, email: email, staff_kind: staff_kind)
|
||||
token = TeamInvitation.generate_token
|
||||
invitation = @team.team_invitations.create!(
|
||||
email: email,
|
||||
token_digest: Digest::SHA256.hexdigest(token),
|
||||
role: "member",
|
||||
staff_kind: staff_kind,
|
||||
expires_at: 7.days.from_now
|
||||
)
|
||||
invite_url = public_invitation_url(token: token)
|
||||
flash[:invite_url] = invite_url
|
||||
|
||||
begin
|
||||
Teams::InvitationMailer.transmission_invite(
|
||||
team: @team,
|
||||
invitation: invitation,
|
||||
invite_url: invite_url,
|
||||
invited_by: current_user
|
||||
).deliver_now
|
||||
flash[:notice] = t("flash.teams.invite_email_sent", email: email)
|
||||
rescue StandardError => e
|
||||
Rails.logger.error("[invite_email] #{e.class}: #{e.message}")
|
||||
flash[:alert] = t("flash.teams.invite_email_failed", email: email)
|
||||
end
|
||||
|
||||
redirect_to public_team_details_path(@team, anchor: "invito-generato")
|
||||
rescue Teams::EntitlementError, Teams::StaffAssignmentError => e
|
||||
redirect_to public_team_details_path(@team, anchor: "invita-trasmissione"), alert: e.message
|
||||
end
|
||||
|
||||
def remove_member
|
||||
require_club_owner_for_team!(@team)
|
||||
ut = @team.user_teams.find_by!(user_id: params[:user_id], role: "member")
|
||||
ut.destroy!
|
||||
redirect_to public_team_details_path(@team), notice: t("flash.teams.access_revoked")
|
||||
end
|
||||
|
||||
def destroy_invitation
|
||||
require_club_owner_for_team!(@team)
|
||||
inv = @team.team_invitations.pending.find(params[:invitation_id])
|
||||
inv.destroy!
|
||||
redirect_to public_team_details_path(@team), notice: t("flash.teams.invitation_canceled")
|
||||
end
|
||||
|
||||
def youtube_connect
|
||||
redirect_to public_club_youtube_connect_path(
|
||||
@team.club_id,
|
||||
return_app: params[:return_app]
|
||||
)
|
||||
end
|
||||
|
||||
def youtube_disconnect
|
||||
require_club_owner_for_team!(@team)
|
||||
@team.club.youtube_credential&.destroy!
|
||||
redirect_to public_club_path(@team.club), notice: t("flash.teams.youtube_disconnected")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def load_team_details!
|
||||
@club = @team.club
|
||||
@can_manage = @club.owned_by?(current_user)
|
||||
@entitlements = @team.entitlements
|
||||
@roster_by_category = @team.roster_by_category
|
||||
if @can_manage
|
||||
@roster_member = @team.roster_members.build(
|
||||
category: params[:category].presence_in(TeamRosterMember::CATEGORIES) || "player"
|
||||
)
|
||||
end
|
||||
@recordings = @team.recordings.not_deleted
|
||||
.where(status: %w[ready processing])
|
||||
.includes(stream_session: :match)
|
||||
.order(recorded_at: :desc, created_at: :desc)
|
||||
.limit(10)
|
||||
@owner_membership = current_user.user_teams.find_by(team: @team)
|
||||
@staff_memberships = @team.user_teams.includes(:user)
|
||||
.where("user_teams.role = 'member' OR (user_teams.staff_kind IS NOT NULL)")
|
||||
@pending_invitations = @team.team_invitations.pending.order(created_at: :desc)
|
||||
end
|
||||
|
||||
def set_club
|
||||
@club = current_user.owned_clubs.find(params[:club_id])
|
||||
end
|
||||
|
||||
def set_team
|
||||
@team = current_user.manageable_teams.find(params[:id])
|
||||
end
|
||||
|
||||
def attach_team_photo(team)
|
||||
file = params.dig(:team, :photo_file)
|
||||
team.photo_file.attach(file) if file.present?
|
||||
end
|
||||
|
||||
def team_params
|
||||
p = params.require(:team).permit(:name, :sport, :sport_key, :description, :logo_url, :primary_color, :secondary_color, :slug, :roster_public)
|
||||
if p[:sport].present? && p[:sport_key].blank?
|
||||
p[:sport_key] = p.delete(:sport)
|
||||
elsif p[:sport_key].present?
|
||||
p.delete(:sport)
|
||||
end
|
||||
p[:primary_color] = p[:primary_color].presence
|
||||
p[:secondary_color] = p[:secondary_color].presence
|
||||
if p[:primary_color].present?
|
||||
p[:primary_color] = normalize_hex_color(p[:primary_color], p[:primary_color])
|
||||
end
|
||||
if p[:secondary_color].present?
|
||||
p[:secondary_color] = normalize_hex_color(p[:secondary_color], p[:secondary_color])
|
||||
end
|
||||
p
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,29 @@
|
||||
module Public
|
||||
class TournamentAssignmentsController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_tournament
|
||||
|
||||
def destroy
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
unless @tournament.writable?
|
||||
redirect_to public_tournament_path(@tournament, tab: "dirette"),
|
||||
alert: t("flash.tournaments.archived_locked")
|
||||
return
|
||||
end
|
||||
assignment = @tournament.broadcast_assignments.find(params[:assignment_id])
|
||||
Tournaments::RevokeAssignment.call(assignment: assignment)
|
||||
redirect_to public_tournament_path(@tournament, tab: "dirette"),
|
||||
notice: t("flash.tournaments.assignment_revoked")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_tournament
|
||||
@tournament = Tournament.find(params[:id])
|
||||
@club = @tournament.club
|
||||
require_club_owner!(@club)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
module Public
|
||||
class TournamentGroupsController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_tournament
|
||||
|
||||
def create
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
position = @tournament.groups.maximum(:position).to_i + 1
|
||||
name = params.dig(:tournament_group, :name).presence || "Girone #{('A'.ord + position).chr}"
|
||||
@tournament.groups.create!(name: name, position: position)
|
||||
redirect_to public_tournament_path(@tournament, tab: "struttura"), notice: t("flash.tournaments.group_added")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
end
|
||||
|
||||
def destroy
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
@tournament.groups.find(params[:group_id]).destroy!
|
||||
redirect_to public_tournament_path(@tournament, tab: "struttura"), notice: t("flash.tournaments.group_removed")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_tournament
|
||||
@tournament = Tournament.find(params[:id])
|
||||
@club = @tournament.club
|
||||
require_club_owner!(@club)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,136 @@
|
||||
module Public
|
||||
class TournamentInvitationsController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_tournament
|
||||
|
||||
def create
|
||||
if params[:intent] == "save"
|
||||
save_draft
|
||||
return
|
||||
end
|
||||
|
||||
match_ids = Array(params[:match_ids]).reject(&:blank?)
|
||||
scope_kind = if match_ids.any?
|
||||
"matches"
|
||||
elsif params[:whole_court].present? || params[:scope_kind].to_s == "court_day"
|
||||
"court_day"
|
||||
else
|
||||
raise ArgumentError, t("tournaments.hub.stream_plan_need_selection")
|
||||
end
|
||||
persist_draft! unless calendar_invite?
|
||||
invitation, token = Tournaments::Invite.call(
|
||||
tournament: @tournament,
|
||||
email: params[:email],
|
||||
scope_kind: scope_kind,
|
||||
match_ids: match_ids,
|
||||
court: params[:court],
|
||||
on_date: params[:on_date].presence,
|
||||
invited_by: current_user,
|
||||
note: params[:note]
|
||||
)
|
||||
invite_url = public_invitation_url(token: token)
|
||||
flash[:invite_url] = invite_url unless calendar_invite?
|
||||
body_html = Tournaments::ComposeInviteEmail.call(
|
||||
html: draft_html,
|
||||
invite_url: invite_url,
|
||||
expires_on: I18n.l(invitation.expires_at.to_date, format: :long)
|
||||
)
|
||||
invitation.update!(email_html: body_html)
|
||||
begin
|
||||
Tournaments::InvitationMailer.transmission_invite(
|
||||
tournament: @tournament,
|
||||
invitation: invitation,
|
||||
invite_url: invite_url,
|
||||
invited_by: current_user,
|
||||
body_html: body_html
|
||||
).deliver_now
|
||||
flash[:notice] = t("flash.tournaments.invite_email_sent", email: invitation.email)
|
||||
rescue StandardError => e
|
||||
Rails.logger.error("[tournament_invite] #{e.class}: #{e.message}")
|
||||
flash[:alert] = t("flash.tournaments.invite_email_failed", email: invitation.email)
|
||||
end
|
||||
redirect_to public_tournament_path(@tournament, tab: invite_return_tab, anchor: calendar_invite? ? nil : "invito-generato")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
rescue ActiveRecord::RecordInvalid, ArgumentError => e
|
||||
redirect_to public_tournament_path(@tournament, tab: invite_return_tab), alert: e.message
|
||||
end
|
||||
|
||||
def save_draft
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
persist_draft!
|
||||
redirect_to public_tournament_path(@tournament, tab: "dirette"),
|
||||
notice: t("flash.tournaments.invite_draft_saved")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
redirect_to public_tournament_path(@tournament, tab: "dirette"), alert: e.message
|
||||
end
|
||||
|
||||
def upload_image
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
file = params[:file]
|
||||
unless file.respond_to?(:content_type) && file.content_type.to_s.in?(%w[image/png image/jpeg image/webp image/gif])
|
||||
return render json: { error: t("tournaments.hub.invite_image_invalid") }, status: :unprocessable_entity
|
||||
end
|
||||
if file.size > 2.megabytes
|
||||
return render json: { error: t("tournaments.hub.invite_image_too_big") }, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
@tournament.invite_email_images.attach(file)
|
||||
blob = @tournament.invite_email_images.blobs.last
|
||||
render json: { url: url_for(blob) }
|
||||
rescue Tournaments::EntitlementError => e
|
||||
render json: { error: e.message }, status: :forbidden
|
||||
end
|
||||
|
||||
def destroy
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
invitation = @tournament.broadcast_invitations.find(params[:invitation_id])
|
||||
invitation.destroy!
|
||||
redirect_to public_tournament_path(@tournament, tab: invite_return_tab), notice: t("flash.tournaments.invite_canceled")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_tournament
|
||||
@tournament = Tournament.find(params[:id])
|
||||
@club = @tournament.club
|
||||
require_club_owner!(@club)
|
||||
end
|
||||
|
||||
def persist_draft!
|
||||
@tournament.update!(
|
||||
invite_draft_html: Tournaments::ComposeInviteEmail.sanitize_html(draft_html),
|
||||
invite_draft_note: params[:note].to_s.strip.presence,
|
||||
invite_draft_email: params[:email].to_s.strip.presence,
|
||||
invite_draft_saved_at: Time.current
|
||||
)
|
||||
end
|
||||
|
||||
def draft_html
|
||||
html = params[:email_html].to_s
|
||||
stripped = ActionController::Base.helpers.strip_tags(html).to_s.gsub(/\s+/, "")
|
||||
return html if stripped.present?
|
||||
|
||||
stored = @tournament.invite_draft_html.to_s
|
||||
if ActionController::Base.helpers.strip_tags(stored).to_s.gsub(/\s+/, "").present?
|
||||
return stored
|
||||
end
|
||||
|
||||
Tournaments::ComposeInviteEmail.default_html(tournament: @tournament, invited_by: current_user)
|
||||
end
|
||||
|
||||
def calendar_invite?
|
||||
params[:from].to_s == "calendar" || invite_return_tab == "calendario"
|
||||
end
|
||||
|
||||
def invite_return_tab
|
||||
tab = params[:tab].to_s
|
||||
tab = "dirette" if tab == "delega"
|
||||
tab.presence_in(%w[calendario dirette]) || "dirette"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,113 @@
|
||||
module Public
|
||||
class TournamentMatchesController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_tournament
|
||||
|
||||
def create
|
||||
Tournaments::ScheduleMatch.call(tournament: @tournament, attrs: match_params)
|
||||
redirect_to public_tournament_path(@tournament, tab: "calendario"), notice: t("flash.tournaments.match_scheduled")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
redirect_to public_tournament_path(@tournament, tab: "calendario"), alert: e.record.errors.full_messages.join(", ")
|
||||
end
|
||||
|
||||
def update
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
match = @tournament.matches.find(params[:match_id])
|
||||
attrs = match_params
|
||||
if match.result_recorded?
|
||||
attrs = attrs.except(:home_participant_id, :away_participant_id)
|
||||
end
|
||||
match.update!(attrs)
|
||||
schedule_changed = match.previous_changes.keys.intersect?(%w[scheduled_at court location])
|
||||
recorded = record_result_if_present!(match)
|
||||
notice = if recorded && !schedule_changed
|
||||
t("flash.tournaments.result_saved")
|
||||
else
|
||||
t("flash.tournaments.match_updated")
|
||||
end
|
||||
redirect_to public_tournament_path(@tournament, tab: hub_tab), notice: notice
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
redirect_to public_tournament_path(@tournament, tab: "calendario"), alert: e.record.errors.full_messages.join(", ")
|
||||
end
|
||||
|
||||
def swap
|
||||
match = @tournament.matches.find(params[:match_id])
|
||||
Tournaments::SwapSides.call(match: match)
|
||||
respond_to do |format|
|
||||
format.json { render json: { ok: true, matchup_label: match.reload.matchup_label } }
|
||||
format.html { redirect_to public_tournament_path(@tournament, tab: "calendario"), notice: t("flash.tournaments.sides_swapped") }
|
||||
end
|
||||
rescue Tournaments::EntitlementError => e
|
||||
respond_to do |format|
|
||||
format.json { render json: { ok: false, error: e.message }, status: :unprocessable_entity }
|
||||
format.html { redirect_to public_club_billing_path(@club), alert: e.message }
|
||||
end
|
||||
rescue Tournaments::SwapSides::LiveBroadcastError => e
|
||||
respond_to do |format|
|
||||
format.json { render json: { ok: false, error: e.message }, status: :unprocessable_entity }
|
||||
format.html { redirect_to public_tournament_path(@tournament, tab: "calendario"), alert: e.message }
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
match = @tournament.matches.find(params[:match_id])
|
||||
unless match.deletable?
|
||||
redirect_to public_tournament_path(@tournament, tab: "calendario"),
|
||||
alert: t("flash.matches.close_live_before_delete")
|
||||
return
|
||||
end
|
||||
|
||||
match.destroy!
|
||||
redirect_to public_tournament_path(@tournament, tab: "calendario"), notice: t("flash.tournaments.match_deleted")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_tournament
|
||||
@tournament = Tournament.find(params[:id])
|
||||
@club = @tournament.club
|
||||
require_club_owner!(@club)
|
||||
end
|
||||
|
||||
def record_result_if_present!(match)
|
||||
home = params[:home_score]
|
||||
away = params[:away_score]
|
||||
return false if home.blank? || away.blank?
|
||||
|
||||
Tournaments::RecordResult.call(match: match, home_score: home, away_score: away, source: "manual")
|
||||
true
|
||||
end
|
||||
|
||||
def match_params
|
||||
p = params.require(:match).permit(
|
||||
:home_participant_id, :away_participant_id, :tournament_group_id,
|
||||
:tournament_round_id, :court, :location, :scheduled_at
|
||||
)
|
||||
%i[home_participant_id away_participant_id].each do |key|
|
||||
p[key] = p[key].presence if p.key?(key)
|
||||
end
|
||||
p[:scheduled_at] = parse_scheduled_at(p[:scheduled_at]) if p[:scheduled_at].present?
|
||||
p
|
||||
end
|
||||
|
||||
def parse_scheduled_at(value)
|
||||
raw = value.to_s.strip
|
||||
return nil if raw.blank?
|
||||
|
||||
Time.zone.strptime(raw, "%Y-%m-%dT%H:%M")
|
||||
rescue ArgumentError
|
||||
Time.zone.parse(raw)
|
||||
end
|
||||
|
||||
def hub_tab
|
||||
params[:tab].to_s.presence_in(%w[squadre struttura calendario dirette tabellone]) || "calendario"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,81 @@
|
||||
module Public
|
||||
class TournamentPagesController < SiteBaseController
|
||||
include Public::LiveHelper
|
||||
|
||||
layout "marketing_live"
|
||||
|
||||
def index
|
||||
@tournaments = Tournament
|
||||
.visible_to_public
|
||||
.with_attached_logo_file
|
||||
.includes(:club)
|
||||
.order(starts_on: :desc, name: :asc)
|
||||
end
|
||||
|
||||
def show
|
||||
@tournament = Tournament.find_by!(slug: params[:slug])
|
||||
unless @tournament.published? || owner_access?
|
||||
raise ActiveRecord::RecordNotFound
|
||||
end
|
||||
|
||||
@club = @tournament.club
|
||||
@owner_preview = !@tournament.published? && owner_access?
|
||||
@owner_manage = owner_access?
|
||||
@tab = params[:tab].to_s.presence_in(%w[risultati tabellone]) || "risultati"
|
||||
load_public_content!
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def owner_access?
|
||||
logged_in? && @tournament.club.owned_by?(current_user)
|
||||
end
|
||||
|
||||
def load_public_content!
|
||||
@online_paths = fetch_online_paths
|
||||
|
||||
@matches = @tournament.matches
|
||||
.includes(
|
||||
:tournament_group,
|
||||
:tournament_round,
|
||||
:stream_sessions,
|
||||
home_participant: { logo_file_attachment: :blob },
|
||||
away_participant: { logo_file_attachment: :blob }
|
||||
)
|
||||
.order(Arel.sql("scheduled_at ASC NULLS LAST"), created_at: :asc)
|
||||
|
||||
broadcasting = StreamSession
|
||||
.broadcasting
|
||||
.includes(:score_state, match: [:home_participant, :away_participant, { team: :club }])
|
||||
.where(match_id: @tournament.matches.select(:id))
|
||||
.order(Arel.sql("started_at DESC NULLS LAST"), created_at: :desc)
|
||||
.to_a
|
||||
@live_by_match_id = {}
|
||||
broadcasting.each { |session| @live_by_match_id[session.match_id] ||= session }
|
||||
@live_sessions = broadcasting.select(&:public_watchable?)
|
||||
|
||||
@recordings = Recording.ready.publicly_listed
|
||||
.joins(stream_session: :match)
|
||||
.where(matches: { tournament_id: @tournament.id })
|
||||
.includes(stream_session: { match: [:home_participant, :away_participant] })
|
||||
.order(recorded_at: :desc)
|
||||
@recording_by_match_id = {}
|
||||
@recordings.each do |rec|
|
||||
match_id = rec.stream_session.match_id
|
||||
@recording_by_match_id[match_id] ||= rec
|
||||
end
|
||||
|
||||
@groups = @tournament.groups.order(:position)
|
||||
@standings_by_group = @groups.index_with { |group| Tournaments::Standings.call(group) }
|
||||
@rounds = @tournament.rounds.order(:position)
|
||||
@matches_by_round = @matches.select { |match| match.tournament_round_id.present? }
|
||||
.group_by(&:tournament_round_id)
|
||||
end
|
||||
|
||||
def fetch_online_paths
|
||||
Mediamtx::Client.new.online_path_names
|
||||
rescue Mediamtx::Client::Error, Errno::ECONNREFUSED, SocketError
|
||||
[]
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,51 @@
|
||||
module Public
|
||||
class TournamentParticipantsController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_tournament
|
||||
|
||||
def create
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
@tournament.participants.create!(participant_params)
|
||||
redirect_to public_tournament_path(@tournament, tab: "squadre"), notice: t("flash.tournaments.participant_added")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
redirect_to public_tournament_path(@tournament, tab: "squadre"), alert: e.record.errors.full_messages.join(", ")
|
||||
end
|
||||
|
||||
def update
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
participant = @tournament.participants.find(params[:participant_id])
|
||||
participant.update!(participant_params)
|
||||
file = params.dig(:tournament_participant, :logo_file)
|
||||
participant.logo_file.attach(file) if file.present?
|
||||
redirect_to public_tournament_path(@tournament, tab: "squadre"), notice: t("flash.tournaments.participant_updated")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
redirect_to public_tournament_path(@tournament, tab: "squadre"), alert: e.record.errors.full_messages.join(", ")
|
||||
end
|
||||
|
||||
def destroy
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
@tournament.participants.find(params[:participant_id]).destroy!
|
||||
redirect_to public_tournament_path(@tournament, tab: "squadre"), notice: t("flash.tournaments.participant_removed")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_tournament
|
||||
@tournament = Tournament.find(params[:id])
|
||||
@club = @tournament.club
|
||||
require_club_owner!(@club)
|
||||
end
|
||||
|
||||
def participant_params
|
||||
permitted = params.require(:tournament_participant).permit(:name, :group_id, :primary_color, :logo_url, :source_team_id)
|
||||
permitted[:group_id] = permitted[:group_id].presence if permitted.key?(:group_id)
|
||||
permitted
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
module Public
|
||||
class TournamentResultsController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_tournament
|
||||
|
||||
def create
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
match = @tournament.matches.find(params[:match_id])
|
||||
Tournaments::RecordResult.call(
|
||||
match: match,
|
||||
home_score: params[:home_score],
|
||||
away_score: params[:away_score],
|
||||
source: "manual",
|
||||
walkover: params[:walkover].presence
|
||||
)
|
||||
redirect_to public_tournament_path(@tournament, tab: params[:tab].presence || "calendario"),
|
||||
notice: t("flash.tournaments.result_saved")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
redirect_to public_tournament_path(@tournament, tab: "calendario"), alert: e.record.errors.full_messages.join(", ")
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_tournament
|
||||
@tournament = Tournament.find(params[:id])
|
||||
@club = @tournament.club
|
||||
require_club_owner!(@club)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,190 @@
|
||||
module Public
|
||||
class TournamentsController < WebBaseController
|
||||
before_action :require_login!
|
||||
before_action :set_club, only: %i[index new create]
|
||||
before_action :set_tournament, except: %i[index new create]
|
||||
before_action :require_owner!
|
||||
before_action :require_writable!, only: %i[update generate_group_matches propose_knockout]
|
||||
|
||||
def index
|
||||
@tournaments = @club.tournaments.order(starts_on: :desc)
|
||||
@can_create = Tournaments::Entitlements.new(@club).premium_full?
|
||||
end
|
||||
|
||||
def new
|
||||
assert_full!
|
||||
return if performed?
|
||||
|
||||
@tournament = @club.tournaments.build(
|
||||
sport_key: Sports::Catalog.normalize_key(@club.sport),
|
||||
starts_on: Date.current,
|
||||
ends_on: Date.current + 1,
|
||||
format_kind: "mixed",
|
||||
courts: ["Campo 1", "Campo 2"],
|
||||
knockout_size: 4
|
||||
)
|
||||
end
|
||||
|
||||
def create
|
||||
@tournament = Tournaments::Create.call(club: @club, attrs: tournament_params)
|
||||
redirect_to public_tournament_path(@tournament), notice: t("flash.tournaments.created")
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
@tournament = e.record
|
||||
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def show
|
||||
if params[:tab] == "delega"
|
||||
redirect_to public_tournament_path(@tournament, tab: "dirette")
|
||||
return
|
||||
end
|
||||
|
||||
load_hub!
|
||||
end
|
||||
|
||||
def update
|
||||
attrs = tournament_params
|
||||
file = attrs.delete(:logo_file)
|
||||
@tournament.assign_attributes(attrs)
|
||||
@tournament.logo_file.attach(file) if file.present?
|
||||
@tournament.save!
|
||||
redirect_to public_tournament_path(@tournament, tab: hub_tab || params[:tab]), notice: t("flash.tournaments.updated")
|
||||
rescue ActiveRecord::RecordInvalid => e
|
||||
load_hub!
|
||||
flash.now[:alert] = e.record.errors.full_messages.join(", ")
|
||||
render :show, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def publish
|
||||
assert_full!
|
||||
return if performed?
|
||||
|
||||
@tournament.update!(status: "published")
|
||||
redirect_to public_tournament_path(@tournament), notice: t("flash.tournaments.published")
|
||||
end
|
||||
|
||||
def unpublish
|
||||
assert_full!
|
||||
return if performed?
|
||||
|
||||
@tournament.update!(status: "draft")
|
||||
redirect_to public_tournament_path(@tournament), notice: t("flash.tournaments.unpublished")
|
||||
end
|
||||
|
||||
def archive
|
||||
assert_full!
|
||||
return if performed?
|
||||
|
||||
@tournament.update!(status: "archived")
|
||||
redirect_to public_tournament_path(@tournament), notice: t("flash.tournaments.archived")
|
||||
end
|
||||
|
||||
def destroy
|
||||
Tournaments::Destroy.call(tournament: @tournament)
|
||||
redirect_to public_club_tournaments_path(@club), notice: t("flash.tournaments.deleted")
|
||||
rescue Tournaments::Destroy::LiveBroadcastError => e
|
||||
redirect_to public_tournament_path(@tournament), alert: e.message
|
||||
end
|
||||
|
||||
def generate_group_matches
|
||||
created = Tournaments::GenerateGroupMatches.call(tournament: @tournament)
|
||||
redirect_to public_tournament_path(@tournament, tab: "calendario"),
|
||||
notice: t("flash.tournaments.group_matches_created", count: created.size)
|
||||
rescue Tournaments::EntitlementError, ActiveRecord::RecordInvalid => e
|
||||
redirect_to public_tournament_path(@tournament, tab: "calendario"), alert: e.message
|
||||
end
|
||||
|
||||
def propose_knockout
|
||||
updated = Tournaments::ProposeKnockout.call(@tournament)
|
||||
redirect_to public_tournament_path(@tournament, tab: "tabellone"),
|
||||
notice: t("flash.tournaments.knockout_proposed", count: updated.size)
|
||||
rescue Tournaments::EntitlementError, ActiveRecord::RecordInvalid => e
|
||||
redirect_to public_tournament_path(@tournament, tab: "tabellone"), alert: e.message
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_club
|
||||
@club = Club.find(params[:club_id] || params[:id])
|
||||
end
|
||||
|
||||
def set_tournament
|
||||
@tournament = Tournament.find(params[:id])
|
||||
@club = @tournament.club
|
||||
end
|
||||
|
||||
def require_owner!
|
||||
require_club_owner!(@club)
|
||||
end
|
||||
|
||||
def assert_full!
|
||||
Tournaments::Entitlements.new(@club).assert_writable!
|
||||
rescue Tournaments::EntitlementError => e
|
||||
redirect_to public_club_billing_path(@club), alert: e.message
|
||||
end
|
||||
|
||||
def require_writable!
|
||||
assert_full!
|
||||
return if performed?
|
||||
return if @tournament.writable?
|
||||
|
||||
redirect_to public_tournament_path(@tournament), alert: t("flash.tournaments.archived_locked")
|
||||
end
|
||||
|
||||
def load_hub!
|
||||
@tab = hub_tab || "squadre"
|
||||
@participants = @tournament.participants.with_attached_logo_file.includes(:group, :source_team).order(:position, :name)
|
||||
@groups = @tournament.groups.order(:position)
|
||||
@rounds = @tournament.rounds.order(:position)
|
||||
@matches = @tournament.matches.includes(
|
||||
{ home_participant: { logo_file_attachment: :blob } },
|
||||
{ away_participant: { logo_file_attachment: :blob } },
|
||||
:tournament_group, :tournament_round, :stream_sessions,
|
||||
{ broadcast_assignments: :user }
|
||||
).order(:scheduled_at)
|
||||
@invitations = @tournament.broadcast_invitations.order(created_at: :desc)
|
||||
@pending_invites_by_match_id = pending_invites_by_match_id
|
||||
@standings_by_group = @groups.index_with { |group| Tournaments::Standings.call(group) }
|
||||
@overlap_warnings = overlap_warnings
|
||||
@writable = @tournament.writable? && Tournaments::Entitlements.new(@club).premium_full?
|
||||
end
|
||||
|
||||
def hub_tab
|
||||
raw = params[:tab].to_s
|
||||
raw = "dirette" if raw == "delega"
|
||||
raw.presence_in(%w[squadre struttura calendario dirette tabellone])
|
||||
end
|
||||
|
||||
def pending_invites_by_match_id
|
||||
pending = @tournament.broadcast_invitations.pending.to_a
|
||||
map = Hash.new { |h, k| h[k] = [] }
|
||||
@matches.each do |match|
|
||||
pending.each do |invitation|
|
||||
map[match.id] << invitation if invitation.covers_match?(match)
|
||||
end
|
||||
end
|
||||
map
|
||||
end
|
||||
|
||||
def overlap_warnings
|
||||
limit = @tournament.concurrent_limit
|
||||
return [] unless limit
|
||||
|
||||
@matches.group_by { |m| m.scheduled_at&.strftime("%Y-%m-%d %H:%M") }.filter_map do |slot, list|
|
||||
next if slot.blank? || list.size <= limit
|
||||
|
||||
t("tournaments.hub.overlap_warning", slot: slot, count: list.size, limit: limit)
|
||||
end
|
||||
end
|
||||
|
||||
def tournament_params
|
||||
params.require(:tournament).permit(
|
||||
:name, :sport_key, :venue, :starts_on, :ends_on, :format_kind,
|
||||
:description, :knockout_size, :courts, :logo_file
|
||||
)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,21 @@
|
||||
module Public
|
||||
class WebBaseController < SiteBaseController
|
||||
protect_from_forgery with: :exception
|
||||
|
||||
private
|
||||
|
||||
def require_login!
|
||||
return if logged_in?
|
||||
|
||||
redirect_to public_login_path, alert: t("flash.web_base.login_required")
|
||||
end
|
||||
|
||||
def require_club_owner!(club)
|
||||
redirect_to public_prezzi_path, alert: t("flash.web_base.access_denied") unless club.owned_by?(current_user)
|
||||
end
|
||||
|
||||
def require_club_owner_for_team!(team)
|
||||
redirect_to public_prezzi_path, alert: t("flash.web_base.access_denied") unless team.club&.owned_by?(current_user)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,53 @@
|
||||
module Webhooks
|
||||
class MediamtxController < ApplicationController
|
||||
skip_before_action :authenticate_request!
|
||||
|
||||
before_action :verify_signature!
|
||||
|
||||
def connect
|
||||
handle_event("connect")
|
||||
end
|
||||
|
||||
def disconnect
|
||||
handle_event("disconnect")
|
||||
end
|
||||
|
||||
def ready
|
||||
handle_event("ready")
|
||||
end
|
||||
|
||||
def validate_publish
|
||||
session_id = params[:session_id] || extract_session_id(params[:path])
|
||||
token = params[:token]
|
||||
session = StreamSession.find_by(id: session_id)
|
||||
|
||||
valid = session && session.publish_token == token && !session.ended?
|
||||
render json: { valid: valid }, status: valid ? :ok : :forbidden
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def handle_event(event)
|
||||
session_id = params[:session_id].presence || extract_session_id(params[:path])
|
||||
Webhooks::MediamtxHandler.new(
|
||||
event: event,
|
||||
session_id: session_id,
|
||||
metadata: params.permit!.to_h.except("controller", "action")
|
||||
).call
|
||||
head :ok
|
||||
end
|
||||
|
||||
def extract_session_id(path)
|
||||
path.to_s[%r{match_([0-9a-f-]+)}, 1]
|
||||
end
|
||||
|
||||
def verify_signature!
|
||||
signature = request.headers["X-MediaMTX-Signature"]
|
||||
payload = request.raw_post.presence || request.query_string
|
||||
return if Webhooks::Signature.valid?(payload, signature)
|
||||
return if Rails.env.development? && signature.blank?
|
||||
|
||||
head :unauthorized
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
module Webhooks
|
||||
class StripeController < ActionController::API
|
||||
def create
|
||||
payload = request.body.read
|
||||
sig_header = request.env["HTTP_STRIPE_SIGNATURE"]
|
||||
|
||||
unless MatchLiveTv.stripe_webhook_secret.present?
|
||||
Rails.logger.info("[Stripe webhook] ignored — STRIPE_WEBHOOK_SECRET not set")
|
||||
return head :ok
|
||||
end
|
||||
|
||||
event = ::Stripe::Webhook.construct_event(
|
||||
payload, sig_header, MatchLiveTv.stripe_webhook_secret
|
||||
)
|
||||
|
||||
Billing::Stripe::WebhookHandler.call(event)
|
||||
|
||||
head :ok
|
||||
rescue JSON::ParserError, ::Stripe::SignatureVerificationError => e
|
||||
Rails.logger.warn("[Stripe webhook] #{e.message}")
|
||||
head :bad_request
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def stripe_object_from_hash(hash)
|
||||
OpenStruct.new(hash.transform_keys(&:to_s).transform_values do |v|
|
||||
v.is_a?(Hash) ? stripe_object_from_hash(v) : v
|
||||
end)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,49 @@
|
||||
# Callback OAuth YouTube (HTML). Non usare Api::V1 — ActionController::API non renderizza le view.
|
||||
class YoutubeOauthCallbackController < ActionController::Base
|
||||
def show
|
||||
return redirect_to_oauth_error("Codice OAuth mancante") if params[:code].blank?
|
||||
|
||||
ctx = Youtube::OauthState.verify!(params[:state])
|
||||
tokens = Youtube::OauthExchange.call(params[:code])
|
||||
|
||||
if ctx[:kind] == :platform
|
||||
@refresh_token = tokens[:refresh_token]
|
||||
@channel_title = tokens[:channel_title]
|
||||
return render "admin/youtube/platform_token", layout: false
|
||||
end
|
||||
|
||||
user = User.find(ctx[:user_id])
|
||||
club = Club.find(ctx[:club_id])
|
||||
unless club.owned_by?(user)
|
||||
return redirect_to_oauth_error("Solo il titolare della società può collegare il canale YouTube")
|
||||
end
|
||||
|
||||
cred = club.youtube_credential || club.build_youtube_credential
|
||||
cred.update!(
|
||||
access_token: tokens[:access_token],
|
||||
refresh_token: tokens[:refresh_token] || cred.refresh_token,
|
||||
expires_at: Time.current + tokens[:expires_in].seconds,
|
||||
channel_id: tokens[:channel_id],
|
||||
channel_title: tokens[:channel_title]
|
||||
)
|
||||
|
||||
if ctx[:return_app]
|
||||
redirect_to "matchlivetv://youtube-connected?club_id=#{club.id}", allow_other_host: true
|
||||
else
|
||||
redirect_to "#{public_base_url}/clubs/#{club.id}?youtube=connected", allow_other_host: true
|
||||
end
|
||||
rescue ArgumentError, Youtube::BroadcastService::Error => e
|
||||
redirect_to_oauth_error(e.message)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def public_base_url
|
||||
MatchLiveTv.app_public_url.chomp("/")
|
||||
end
|
||||
|
||||
def redirect_to_oauth_error(message)
|
||||
redirect_to "#{public_base_url}/prezzi?youtube_error=#{ERB::Util.url_encode(message)}",
|
||||
allow_other_host: true
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,11 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Sports
|
||||
class BoardType
|
||||
ALL = %w[volley basket timed racket timer generic].freeze
|
||||
|
||||
def self.valid?(value)
|
||||
ALL.include?(value.to_s)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,94 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Sports
|
||||
class Catalog
|
||||
LEGACY_SPORT_MAP = {
|
||||
"volleyball" => "pallavolo"
|
||||
}.freeze
|
||||
|
||||
class << self
|
||||
def all
|
||||
@all ||= load_entries
|
||||
end
|
||||
|
||||
def keys
|
||||
all.keys
|
||||
end
|
||||
|
||||
def find(key)
|
||||
normalized = normalize_key(key)
|
||||
entry = all[normalized]
|
||||
raise KeyError, "Sport sconosciuto: #{key}" unless entry
|
||||
|
||||
entry.merge(key: normalized)
|
||||
end
|
||||
|
||||
def find_optional(key)
|
||||
normalized = normalize_key(key)
|
||||
entry = all[normalized]
|
||||
return nil unless entry
|
||||
|
||||
entry.merge(key: normalized)
|
||||
end
|
||||
|
||||
def board_for(key)
|
||||
find(key)[:board]
|
||||
end
|
||||
|
||||
def overlay_for(key)
|
||||
find(key)[:overlay]
|
||||
end
|
||||
|
||||
def allowed_overlays_for(key)
|
||||
find(key)[:allowed_overlays]
|
||||
end
|
||||
|
||||
def default_rules_for(key)
|
||||
deep_stringify_keys(find(key)[:default_rules] || {})
|
||||
end
|
||||
|
||||
def normalize_key(key)
|
||||
raw = key.to_s.strip
|
||||
return "pallavolo" if raw.blank?
|
||||
|
||||
LEGACY_SPORT_MAP.fetch(raw, raw)
|
||||
end
|
||||
|
||||
def as_api_list
|
||||
all.map do |key, entry|
|
||||
{
|
||||
key: key,
|
||||
label: entry[:label],
|
||||
board: entry[:board],
|
||||
overlay: entry[:overlay],
|
||||
allowed_overlays: entry[:allowed_overlays],
|
||||
default_rules: entry[:default_rules] || {}
|
||||
}
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def load_entries
|
||||
path = Rails.root.join("config/sports.yml")
|
||||
raw = YAML.safe_load(File.read(path), permitted_classes: [], aliases: true) || {}
|
||||
raw.transform_keys(&:to_s).transform_values do |entry|
|
||||
entry.deep_symbolize_keys
|
||||
end.freeze
|
||||
end
|
||||
|
||||
def deep_stringify_keys(value)
|
||||
case value
|
||||
when Hash
|
||||
value.each_with_object({}) do |(k, v), h|
|
||||
h[k.to_s] = deep_stringify_keys(v)
|
||||
end
|
||||
when Array
|
||||
value.map { |v| deep_stringify_keys(v) }
|
||||
else
|
||||
value
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,11 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Sports
|
||||
class OverlayKind
|
||||
ALL = %w[none volley basket timed racket].freeze
|
||||
|
||||
def self.valid?(value)
|
||||
ALL.include?(value.to_s)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,25 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Sports
|
||||
class PlayerRoles
|
||||
BY_BOARD = {
|
||||
"volley" => %w[Schiacciatore Opposto Centrale Palleggiatore Libero Universale],
|
||||
"basket" => ["Playmaker", "Guardia", "Ala", "Ala forte", "Centro"],
|
||||
"racket" => %w[Giocatore],
|
||||
"timed" => %w[Portiere Difensore Centrocampista Attaccante],
|
||||
"generic" => %w[Giocatore],
|
||||
"timer" => %w[Giocatore]
|
||||
}.freeze
|
||||
|
||||
class << self
|
||||
def for_team(team)
|
||||
board = team.effective_board_type
|
||||
BY_BOARD[board] || BY_BOARD["generic"]
|
||||
end
|
||||
|
||||
def for_board(board)
|
||||
BY_BOARD[board.to_s] || BY_BOARD["generic"]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,38 @@
|
||||
# frozen_string_literal: true
|
||||
|
||||
module Sports
|
||||
class RulesSchema
|
||||
INTEGER_RULES = {
|
||||
"volley" => %w[sets_to_win points_per_set points_deciding_set min_point_lead],
|
||||
"racket" => %w[sets_to_win points_per_set points_deciding_set min_point_lead],
|
||||
"basket" => %w[periods period_duration_secs overtime_duration_secs],
|
||||
"timed" => %w[periods period_duration_secs overtime_duration_secs],
|
||||
"timer" => [],
|
||||
"generic" => []
|
||||
}.freeze
|
||||
|
||||
def self.validate!(board_type, rules)
|
||||
board = board_type.to_s
|
||||
return if board == "generic" || board == "timer"
|
||||
|
||||
hash = rules.is_a?(Hash) ? rules : {}
|
||||
INTEGER_RULES.fetch(board, []).each do |key|
|
||||
val = hash[key] || hash[key.to_sym]
|
||||
next if val.blank?
|
||||
|
||||
unless val.is_a?(Integer) || val.to_s.match?(/\A\d+\z/)
|
||||
raise ArgumentError, "#{key} non valido"
|
||||
end
|
||||
int_val = val.to_i
|
||||
raise ArgumentError, "#{key} deve essere positivo" if int_val < 1
|
||||
end
|
||||
end
|
||||
|
||||
def self.validate(board_type, rules)
|
||||
validate!(board_type, rules)
|
||||
true
|
||||
rescue ArgumentError
|
||||
false
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,195 @@
|
||||
module AdminHelper
|
||||
def format_euros(cents, precision: 2)
|
||||
return I18n.t("admin.common.dash") if cents.nil?
|
||||
|
||||
format("%.*f €", precision, cents.to_f / 100.0)
|
||||
end
|
||||
|
||||
def format_hours(hours)
|
||||
return I18n.t("admin.common.dash") if hours.nil? || hours.to_f <= 0
|
||||
|
||||
total_minutes = (hours.to_f * 60).round
|
||||
format_duration_minutes(total_minutes)
|
||||
end
|
||||
|
||||
def admin_month_label(month)
|
||||
I18n.l(month, format: "%B %Y")
|
||||
end
|
||||
|
||||
def format_bytes(bytes)
|
||||
return "—" if bytes.nil?
|
||||
|
||||
units = %w[B KB MB GB TB]
|
||||
size = bytes.to_f
|
||||
unit = units.shift
|
||||
while size >= 1024 && units.any?
|
||||
size /= 1024
|
||||
unit = units.shift
|
||||
end
|
||||
"#{size.round(size >= 10 ? 0 : 1)} #{unit}"
|
||||
end
|
||||
|
||||
def format_duration_minutes(minutes)
|
||||
return "0 min" if minutes.to_i <= 0
|
||||
|
||||
hours = minutes / 60
|
||||
mins = minutes % 60
|
||||
hours.positive? ? "#{hours}h #{mins}m" : "#{mins} min"
|
||||
end
|
||||
|
||||
def admin_session_watch_links(session)
|
||||
links = []
|
||||
if session.matchlivetv_platform?
|
||||
links << { label: I18n.t("admin.common.live_page"), url: session.watch_page_url }
|
||||
end
|
||||
youtube = session.youtube_watch_url
|
||||
links << { label: "YouTube", url: youtube } if youtube.present?
|
||||
links
|
||||
end
|
||||
|
||||
def admin_session_ingest_badge_class(role_or_node)
|
||||
role = role_or_node.respond_to?(:role) ? role_or_node.role : role_or_node
|
||||
case role.to_s
|
||||
when "home" then "badge--ingest-home"
|
||||
when "lab" then "badge--ingest-lab"
|
||||
when "cloud" then "badge--ingest-cloud"
|
||||
else "badge--paused"
|
||||
end
|
||||
end
|
||||
|
||||
def admin_session_ingest_role_label(role_or_node)
|
||||
role = role_or_node.respond_to?(:role) ? role_or_node.role : role_or_node
|
||||
I18n.t("admin.sessions.ingest.role.#{role}", default: role.to_s.humanize)
|
||||
end
|
||||
|
||||
def admin_session_status_badge_class(status)
|
||||
case status.to_s
|
||||
when "live" then "badge--live"
|
||||
when "connecting", "reconnecting" then "badge--connecting"
|
||||
when "paused", "idle" then "badge--paused"
|
||||
when "ended" then "badge--ended"
|
||||
when "error" then "badge--error"
|
||||
else "badge--paused"
|
||||
end
|
||||
end
|
||||
|
||||
def admin_datetime(time, with_seconds: false)
|
||||
return I18n.t("admin.common.dash") if time.blank?
|
||||
|
||||
format = with_seconds ? "%d/%m/%Y %H:%M:%S" : "%d/%m/%Y %H:%M"
|
||||
time.in_time_zone.strftime(format)
|
||||
end
|
||||
|
||||
def admin_session_duration_label(session)
|
||||
secs = session.total_duration_secs.to_i
|
||||
if secs <= 0 && session.started_at
|
||||
end_time = session.ended_at || (session.terminal? ? session.updated_at : Time.current)
|
||||
secs = (end_time - session.started_at).to_i if end_time
|
||||
end
|
||||
return I18n.t("admin.common.dash") if secs <= 0
|
||||
|
||||
hours = secs / 3600
|
||||
mins = (secs % 3600) / 60
|
||||
rem = secs % 60
|
||||
if hours.positive?
|
||||
format("%dh %02dm %02ds", hours, mins, rem)
|
||||
elsif mins.positive?
|
||||
format("%dm %02ds", mins, rem)
|
||||
else
|
||||
"#{rem}s"
|
||||
end
|
||||
end
|
||||
|
||||
def admin_session_client_os_label(session)
|
||||
case session.client_os.to_s
|
||||
when "android" then "Android"
|
||||
when "ios" then "iOS"
|
||||
else I18n.t("admin.common.dash")
|
||||
end
|
||||
end
|
||||
|
||||
def admin_session_client_summary(session)
|
||||
parts = []
|
||||
parts << admin_session_client_os_label(session) if session.client_os.present?
|
||||
if session.app_version.present?
|
||||
ver = session.app_version
|
||||
ver = "#{ver} (#{session.app_build})" if session.app_build.present?
|
||||
parts << "app #{ver}"
|
||||
end
|
||||
device = [session.device_manufacturer, session.device_model].compact_blank.join(" ")
|
||||
parts << device if device.present?
|
||||
parts << "OS #{session.os_version}" if session.os_version.present?
|
||||
parts << session.carrier if session.carrier.present?
|
||||
parts.presence&.join(" · ") || I18n.t("admin.common.dash")
|
||||
end
|
||||
|
||||
def admin_format_event_meta(metadata)
|
||||
return content_tag(:span, I18n.t("admin.common.dash"), class: "muted") if metadata.blank?
|
||||
|
||||
pairs = metadata.to_h
|
||||
return content_tag(:span, I18n.t("admin.common.dash"), class: "muted") if pairs.empty?
|
||||
|
||||
content_tag(:dl, class: "admin-event-meta") do
|
||||
safe_join(
|
||||
pairs.map do |key, value|
|
||||
content_tag(:div, class: "admin-event-meta__row") do
|
||||
content_tag(:dt, key.to_s) +
|
||||
content_tag(:dd, admin_event_meta_value(value))
|
||||
end
|
||||
end
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
def admin_event_meta_value(value)
|
||||
case value
|
||||
when Hash, Array
|
||||
content_tag(:code, value.to_json)
|
||||
when TrueClass, FalseClass
|
||||
value ? "true" : "false"
|
||||
when NilClass
|
||||
I18n.t("admin.common.dash")
|
||||
else
|
||||
value.to_s
|
||||
end
|
||||
end
|
||||
|
||||
def admin_regia_expires_label(iso_time)
|
||||
return if iso_time.blank?
|
||||
|
||||
Time.zone.parse(iso_time).strftime("%d/%m/%Y %H:%M")
|
||||
rescue ArgumentError, TypeError
|
||||
nil
|
||||
end
|
||||
|
||||
def announcement_status_badge(item)
|
||||
case item.status
|
||||
when "published" then item.severity == "critical" ? "live" : "ready"
|
||||
when "archived" then "paused"
|
||||
else "connecting"
|
||||
end
|
||||
end
|
||||
|
||||
def announcement_window_label(item)
|
||||
start_label = item.starts_at&.in_time_zone&.strftime("%d/%m %H:%M")
|
||||
end_label = item.ends_at&.in_time_zone&.strftime("%d/%m %H:%M")
|
||||
if start_label && end_label
|
||||
"#{start_label} → #{end_label}"
|
||||
elsif start_label
|
||||
I18n.t("admin.announcements.window.from", time: start_label)
|
||||
elsif end_label
|
||||
I18n.t("admin.announcements.window.until", time: end_label)
|
||||
else
|
||||
I18n.t("admin.announcements.window.always")
|
||||
end
|
||||
end
|
||||
|
||||
def announcement_channels_label(item)
|
||||
labels = item.selected_channels.map { |key| I18n.t("admin.announcements.channels.#{key}") }
|
||||
labels.presence&.join(" · ") || I18n.t("admin.common.dash")
|
||||
end
|
||||
|
||||
def admin_concurrency_violation_lookback_count
|
||||
@admin_concurrency_violation_lookback_count ||= StreamConcurrencyViolation.lookback.count
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,66 @@
|
||||
module ApplicationHelper
|
||||
PLAN_ICONS = {
|
||||
"free" => "fa-solid fa-seedling",
|
||||
"premium_light" => "fa-solid fa-rocket",
|
||||
"premium_full" => "fa-solid fa-crown"
|
||||
}.freeze
|
||||
|
||||
def plan_icon_class(plan)
|
||||
PLAN_ICONS[plan.slug] || "fa-solid fa-circle"
|
||||
end
|
||||
|
||||
# Data/ora nel fuso dell'app (Europe/Rome) e nella lingua corrente.
|
||||
def l_local(date_or_time, format: :long)
|
||||
return nil if date_or_time.blank?
|
||||
|
||||
value = date_or_time.respond_to?(:in_time_zone) ? date_or_time.in_time_zone : date_or_time
|
||||
I18n.l(value, format: format)
|
||||
end
|
||||
|
||||
def og_locale_tag
|
||||
{
|
||||
it: "it_IT",
|
||||
en: "en_US",
|
||||
fr: "fr_FR",
|
||||
de: "de_DE",
|
||||
es: "es_ES"
|
||||
}.fetch(I18n.locale.to_sym, "it_IT")
|
||||
end
|
||||
|
||||
def html_lang
|
||||
I18n.locale.to_s
|
||||
end
|
||||
|
||||
def confirm_dialog_i18n_json
|
||||
{
|
||||
eyebrow: t("common.confirm_eyebrow"),
|
||||
title: t("common.confirm_title"),
|
||||
deleteTitle: t("common.delete_title"),
|
||||
confirmOk: t("common.confirm_ok"),
|
||||
deleteOk: t("common.delete_ok"),
|
||||
cancel: t("common.cancel"),
|
||||
multiDeleteTitle: t("common.multi_delete_title"),
|
||||
multiDeleteMessage: t("common.multi_delete_message"),
|
||||
deleteYoutubeTitle: t("common.delete_youtube_title"),
|
||||
deleteYoutubeMessage: t("common.delete_youtube_message"),
|
||||
deleteYoutubeOk: t("common.delete_youtube_ok"),
|
||||
deleteSiteTitle: t("common.delete_site_title"),
|
||||
deleteSiteMessageWithYoutube: t("common.delete_site_message_with_youtube"),
|
||||
deleteSiteMessageOnly: t("common.delete_site_message_only"),
|
||||
deleteSiteOk: t("common.delete_site_ok"),
|
||||
choiceSiteLabel: t("common.choice_site_label"),
|
||||
choiceSiteHintWithYoutube: t("common.choice_site_hint_with_youtube"),
|
||||
choiceSiteHintOnly: t("common.choice_site_hint_only"),
|
||||
choiceYoutubeLabel: t("common.choice_youtube_label"),
|
||||
choiceYoutubeHintWithSite: t("common.choice_youtube_hint_with_site"),
|
||||
choiceYoutubeHintOnly: t("common.choice_youtube_hint_only"),
|
||||
choiceBothLabel: t("common.choice_both_label"),
|
||||
choiceBothHint: t("common.choice_both_hint")
|
||||
}.to_json
|
||||
end
|
||||
|
||||
def sport_catalog_options(selected = nil)
|
||||
options = Sports::Catalog.as_api_list.map { |entry| [entry[:label], entry[:key]] }
|
||||
options_for_select(options, Sports::Catalog.normalize_key(selected))
|
||||
end
|
||||
end
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user