Aggiunge copertina sponsor custom solo Premium Full, con override in wizard e slate sui nodi di streaming.

Permette upload da portale e app con ereditarietà partita→squadra→società, generazione MP4 via ffmpeg e distribuzione su home lab e nodi CPX per pause e assenza segnale.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-19 23:47:17 +02:00
co-authored by Cursor
parent a51d5e8da5
commit 41d4235258
62 changed files with 1487 additions and 20 deletions
@@ -2,6 +2,7 @@ module Api
module V1
class MatchesController < BaseController
include Api::UrlHelper
include Api::CoverJson
include BrandingAttachments
before_action :set_team, only: %i[index create]
@@ -21,6 +22,7 @@ module Api
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
@@ -34,6 +36,7 @@ module Api
normalize_opponent_color!(attrs)
@match.update!(attrs)
attach_opponent_logo(@match)
attach_match_cover(@match)
render json: match_json(@match)
end
@@ -98,6 +101,11 @@ module Api
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
@@ -123,6 +131,7 @@ module Api
home_logo_url: api_absolute_url(team.effective_logo_url),
opponent_primary_color: match.effective_opponent_primary_color,
opponent_logo_url: api_absolute_url(match.opponent_logo_url),
**match_cover_json(match),
active_session_id: active&.id,
active_session_status: active&.status,
stream_completed: match.stream_completed?,
@@ -137,7 +137,8 @@ module Api
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?
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|
@@ -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
@@ -8,6 +8,26 @@ module BrandingAttachments
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!
record.cover_slate.purge if record.cover_slate.attached?
record.cover_image.attach(file)
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/)
@@ -64,17 +64,26 @@ module Public
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 => e
@entitlements = @club.teams.first&.entitlements
flash.now[:alert] = e.message
render :edit, status: :unprocessable_entity
end
def billing
@@ -51,6 +51,7 @@ module Public
@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
@@ -42,19 +42,28 @@ module Public
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 => e
@club = @team.club
@entitlements = @team.entitlements
flash.now[:alert] = e.message
render :edit, status: :unprocessable_entity
end
def invite
@@ -0,0 +1,19 @@
class GenerateCoverSlateJob < ApplicationJob
queue_as :default
def self.enqueue_for(record)
return unless record&.cover_image&.attached?
queue = record.is_a?(Match) ? :critical : :default
set(queue: queue).perform_later(record.class.name, record.id)
end
def perform(class_name, record_id)
record = class_name.constantize.find_by(id: record_id)
return unless record&.cover_image&.attached?
Streams::GenerateCoverSlate.call(record)
rescue Streams::GenerateCoverSlate::Error => e
Rails.logger.warn("[GenerateCoverSlateJob] #{class_name}##{record_id} #{e.message}")
end
end
+1
View File
@@ -1,5 +1,6 @@
class Club < ApplicationRecord
include Brandable
include Coverable
include ClubBillingProfile
has_many :club_memberships, dependent: :destroy
+50
View File
@@ -0,0 +1,50 @@
module Coverable
extend ActiveSupport::Concern
COVER_IMAGE_TYPES = %w[image/png image/jpeg image/webp].freeze
MAX_COVER_BYTES = 5.megabytes
included do
has_one_attached :cover_image
has_one_attached :cover_slate
validate :cover_image_file_type, if: -> { cover_image.attached? && cover_image.blob&.new_record? }
validate :cover_image_file_size, if: -> { cover_image.attached? && cover_image.blob&.new_record? }
end
def cover_image_attached?
cover_image.attached?
end
def cover_url
return unless cover_image.attached?
Rails.application.routes.url_helpers.rails_blob_path(cover_image, only_path: true)
end
def effective_cover_url
if cover_image.attached?
cover_url
else
cover_parent&.effective_cover_url
end
end
private
def cover_parent
nil
end
def cover_image_file_type
return if cover_image.content_type.in?(COVER_IMAGE_TYPES)
errors.add(:cover_image, I18n.t("coverable.errors.invalid_type"))
end
def cover_image_file_size
return if cover_image.byte_size <= MAX_COVER_BYTES
errors.add(:cover_image, I18n.t("coverable.errors.too_large"))
end
end
+6
View File
@@ -1,4 +1,6 @@
class Match < ApplicationRecord
include Coverable
belongs_to :team
has_many :stream_sessions, dependent: :destroy
@@ -174,4 +176,8 @@ class Match < ApplicationRecord
rescue ArgumentError => e
errors.add(:scoring_rules, e.message)
end
def cover_parent
nil
end
end
+4
View File
@@ -84,6 +84,10 @@ class Plan < ApplicationRecord
feature("youtube_enabled") == true
end
def custom_cover_enabled?
feature("custom_cover") == true
end
def premium?
slug.in?(PREMIUM_SLUGS)
end
+5
View File
@@ -1,5 +1,6 @@
class Team < ApplicationRecord
include Brandable
include Coverable
belongs_to :club
has_many :user_teams, dependent: :destroy
@@ -99,6 +100,10 @@ class Team < ApplicationRecord
club
end
def cover_parent
club
end
def assign_slug
self.slug = Teams::GenerateSlug.call(self) if slug.blank?
end
+9 -3
View File
@@ -28,7 +28,7 @@ module Mediamtx
overridePublisher: true
)
body[:alwaysAvailable] = true
body[:alwaysAvailableFile] = slate_file_path
body[:alwaysAvailableFile] = slate_file_path(session)
# YouTube: telefono → MediaMTX; relay copy verso RTMPS in sidekiq.
response = @conn.post("/v3/config/paths/add/#{CGI.escape(path)}", body)
unless response.success?
@@ -81,7 +81,7 @@ module Mediamtx
return true if always_available_remembered?(path, enabled: enabled)
body = if enabled
{ alwaysAvailable: true, alwaysAvailableFile: slate_file_path }
{ alwaysAvailable: true, alwaysAvailableFile: slate_file_path(session) }
else
{ alwaysAvailable: false }
end
@@ -173,7 +173,13 @@ module Mediamtx
SCRIPT
end
def slate_file_path
def slate_file_path(session)
return default_slate_file_path if session.blank?
Streams::SlateDistributor.slate_path_for_session(session)
end
def default_slate_file_path
ENV.fetch("MEDIAMTX_SLATE_FILE", "/slates/offline.mp4")
end
+2
View File
@@ -37,6 +37,8 @@ module Sessions
session.stream_node = Streams::NodeRegistry.allocate!
session.save!
Scoring::Engine.ensure_score_for(session)
Streams::CoverSlateEnsurer.ensure_for!(@match)
Streams::SlateDistributor.ensure_for!(session)
Mediamtx::Client.for_session(session).create_path(session)
log_event(
session,
@@ -0,0 +1,66 @@
module Streams
# Catena effective cover: partita → squadra → società → default Match Live TV.
class CoverResolver
Result = Struct.new(:record, :source, :cover_url, :slate_local_path, keyword_init: true)
DEFAULT_COVER_URL = "/images/copertina-canale.png".freeze
def initialize(match)
@match = match
@team = match.team
@club = @team.club
@entitlements = @team.entitlements
end
def effective_cover_url
resolve&.cover_url || default_cover_url
end
def cover_source
resolve&.source || "default"
end
def resolve
return nil unless @entitlements.can_use_custom_cover?
candidates.each do |record, source|
next unless record.cover_image.attached?
next unless record.cover_slate.attached?
path = CoverSlatePaths.local_path_for(record)
next if path.blank?
return Result.new(
record: record,
source: source,
cover_url: blob_path(record.cover_image),
slate_local_path: path
)
end
nil
end
def default_cover_url
DEFAULT_COVER_URL
end
def default_slate_path
ENV.fetch("MEDIAMTX_SLATE_FILE", "/slates/offline.mp4")
end
private
def candidates
[
[@match, "match"],
[@team, "team"],
[@club, "club"]
]
end
def blob_path(attachment)
Rails.application.routes.url_helpers.rails_blob_path(attachment, only_path: true)
end
end
end
@@ -0,0 +1,35 @@
module Streams
# Garantisce che la slate MP4 esista per il record effettivo della partita (sync al go-live).
class CoverSlateEnsurer
def self.ensure_for!(match)
new(match).ensure!
end
def initialize(match)
@match = match
@resolver = CoverResolver.new(match)
end
def ensure!
result = @resolver.resolve
return unless result
record = result.record
return if slate_ready?(record)
GenerateCoverSlate.call(record)
rescue GenerateCoverSlate::Error => e
Rails.logger.warn("[CoverSlateEnsurer] match=#{@match.id} #{e.message}")
nil
end
private
def slate_ready?(record)
return false unless record.cover_slate.attached?
path = CoverSlatePaths.local_path_for(record)
path.present? && File.exist?(path)
end
end
end
@@ -0,0 +1,30 @@
module Streams
class CoverSlatePaths
def self.slates_custom_root
ENV.fetch("MEDIAMTX_SLATES_CUSTOM_DIR", "/slates/custom")
end
def self.filename_for(record)
return nil unless record.cover_slate.attached?
digest = record.cover_slate.blob.checksum
prefix = record.class.name.underscore
"#{prefix}-#{record.id}-#{digest}.mp4"
end
def self.expected_path(record)
name = filename_for(record)
return nil if name.blank?
File.join(slates_custom_root, name)
end
def self.local_path_for(record)
path = expected_path(record)
return nil if path.blank?
return path if File.exist?(path)
nil
end
end
end
@@ -0,0 +1,121 @@
require "open3"
module Streams
# Converte cover_image in MP4 slate (H.264 720p + AAC mono), allineato a infra/scripts/generate_slate.sh.
class GenerateCoverSlate
class Error < StandardError; end
SLATE_DURATION_SECS = 30
VIDEO_FILTER = "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2:color=0x0a0a0e".freeze
def self.call(record)
new(record).call
end
def initialize(record)
@record = record
end
def call
return @record unless @record.cover_image.attached?
@image_temp = download_cover_image
@mp4_temp = encode_slate(@image_temp)
attach_slate(@mp4_temp)
write_to_slates_dir(@mp4_temp)
@record
rescue Error
raise
rescue StandardError => e
raise Error, e.message
ensure
cleanup_tempfiles
end
private
def download_cover_image
ext = extension_for(@record.cover_image.content_type)
path = temp_path("cover-in", ext)
@record.cover_image.blob.open(tmpdir: Dir.tmpdir) do |file|
FileUtils.cp(file.path, path)
end
path
end
def encode_slate(image_path)
out = temp_path("cover-slate", ".mp4")
cmd = ffmpeg_args(image_path, out)
stdout, stderr, status = Open3.capture3(*cmd)
unless status.success? && File.exist?(out) && File.size(out).positive?
detail = stderr.to_s.strip.presence || stdout.to_s.strip
raise Error, "ffmpeg slate failed: #{detail}"
end
out
end
def ffmpeg_args(input, output)
[
"ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error",
"-loop", "1", "-framerate", "30", "-i", input,
"-f", "lavfi", "-i", "anullsrc=r=48000:cl=mono",
"-filter:v", VIDEO_FILTER,
"-map", "0:v", "-map", "1:a",
"-t", SLATE_DURATION_SECS.to_s,
"-c:v", "libx264", "-pix_fmt", "yuv420p", "-profile:v", "baseline", "-level", "3.1",
"-x264-params", "keyint=30:min-keyint=30:scenecut=0:bframes=0",
"-g", "30", "-keyint_min", "30", "-force_key_frames", "expr:gte(t,n_forced*1)",
"-preset", "fast",
"-c:a", "aac", "-b:a", "128k", "-ac", "1", "-shortest", "-y", output
]
end
def attach_slate(mp4_path)
@record.cover_slate.purge if @record.cover_slate.attached?
File.open(mp4_path, "rb") do |io|
@record.cover_slate.attach(
io: io,
filename: slate_filename,
content_type: "video/mp4"
)
end
@record.reload
end
def write_to_slates_dir(mp4_path)
dest = CoverSlatePaths.expected_path(@record)
return unless dest
FileUtils.mkdir_p(File.dirname(dest))
FileUtils.cp(mp4_path, dest)
rescue Errno::EACCES, Errno::EROFS => e
Rails.logger.info("[GenerateCoverSlate] skip disk copy #{dest}: #{e.class}")
end
def slate_filename
"#{@record.class.name.underscore}-#{@record.id}.mp4"
end
def extension_for(content_type)
case content_type
when "image/png" then ".png"
when "image/webp" then ".webp"
else ".jpg"
end
end
def temp_path(prefix, ext)
path = File.join(Dir.tmpdir, "#{prefix}-#{@record.class.name}-#{@record.id}-#{SecureRandom.hex(4)}#{ext}")
@tempfiles ||= []
@tempfiles << path
path
end
def cleanup_tempfiles
Array(@tempfiles).each do |path|
FileUtils.rm_f(path)
end
end
end
end
@@ -0,0 +1,101 @@
module Streams
# Assicura che la slate MP4 custom sia sul nodo assegnato (home/lab locale, CPX via agent).
class SlateDistributor
class Error < StandardError; end
def self.slate_path_for_session(session)
new(session).mediamtx_slate_path
end
def self.ensure_for!(session)
new(session).ensure!
end
def initialize(session)
@session = session
@match = session.match
@node = session.stream_node
@resolver = CoverResolver.new(@match)
end
def mediamtx_slate_path
ensure! unless defined?(@mediamtx_path)
@mediamtx_path
end
def ensure!
result = @resolver.resolve
unless result
@mediamtx_path = default_slate_path
return @mediamtx_path
end
host_path = result.slate_local_path
filename = File.basename(host_path)
mediamtx_path = "#{CoverSlatePaths.slates_custom_root}/#{filename}"
if cloud_node?
push_to_agent!(filename, result.record, host_path)
else
verify_local_slate!(host_path)
end
@mediamtx_path = mediamtx_path
rescue Error => e
Rails.logger.warn("[SlateDistributor] session=#{@session.id} #{e.message}")
@mediamtx_path = default_slate_path
end
private
def cloud_node?
@node&.role == "cloud" && agent_url.present?
end
def agent_url
ENV["STREAM_NODE_RELAY_AGENT_URL"].presence || @node&.relay_agent_url
end
def agent_secret
ENV["STREAM_NODE_AGENT_SECRET"].presence || "mediamtx_webhook_dev_secret"
end
def push_to_agent!(filename, record, host_path)
bytes = read_slate_bytes(record, host_path)
raise Error, "slate bytes missing for #{filename}" if bytes.blank?
uri = URI.parse("#{agent_url.chomp('/')}/slates/#{CGI.escape(filename)}")
http = Net::HTTP.new(uri.host, uri.port)
http.open_timeout = 5
http.read_timeout = 120
req = Net::HTTP::Put.new(uri)
req["Authorization"] = "Bearer #{agent_secret}" if agent_secret.present?
req["Content-Type"] = "video/mp4"
req.body = bytes
res = http.request(req)
return if res.is_a?(Net::HTTPSuccess)
raise Error, "agent PUT /slates/#{filename} HTTP #{res.code} #{res.body.to_s.truncate(200)}"
end
def read_slate_bytes(record, host_path)
return File.binread(host_path) if host_path.present? && File.exist?(host_path)
return unless record.cover_slate.attached?
record.cover_slate.blob.open(tmpdir: Dir.tmpdir) do |file|
return File.binread(file.path)
end
end
def verify_local_slate!(host_path)
return if host_path.present? && File.exist?(host_path)
raise Error, "slate missing on disk: #{host_path}"
end
def default_slate_path
ENV.fetch("MEDIAMTX_SLATE_FILE", "/slates/offline.mp4")
end
end
end
+16 -1
View File
@@ -35,6 +35,20 @@ module Teams
active? && plan.phone_download_enabled?
end
def can_use_custom_cover?
premium_full? && plan.custom_cover_enabled?
end
def assert_can_upload_cover!
unless can_use_custom_cover?
raise EntitlementError.new(
"La copertina sponsor personalizzata richiede Premium Full",
code: "premium_full_required",
billing_url: billing_url
)
end
end
def max_staff_transmission
plan.max_staff_transmission
end
@@ -225,7 +239,8 @@ module Teams
recording_retention_days: recording_retention_days,
phone_download_enabled: phone_download_enabled?,
youtube_enabled: youtube_enabled?,
youtube_mode: plan.youtube_mode
youtube_mode: plan.youtube_mode,
custom_cover_enabled: can_use_custom_cover?
}
end
@@ -10,6 +10,9 @@
<%= label_tag "club[sport]", t("club.sport_label") %>
<%= select_tag "club[sport]", sport_catalog_options(@club.sport) %>
<%= render "shared/branding_fields", record: @club, legend: t("club.branding_legend") %>
<%= render "shared/cover_fields",
record: @club,
can_upload: @entitlements&.can_use_custom_cover? %>
<%= render "shared/billing_profile_fields", record: @club %>
<%= submit_tag t("club.edit.save"), class: "btn btn-primary" %>
<% end %>
+1 -1
View File
@@ -46,7 +46,7 @@
</div>
<% else %>
<div class="live-player-wrap">
<video id="player" controls playsinline muted autoplay poster="/images/copertina-canale.png"></video>
<video id="player" controls playsinline muted autoplay poster="<%= @cover_poster_url %>"></video>
<%= render "public/live/player_overlays", match: @match, session: @session %>
<button type="button" id="play-hint" class="live-play-hint" hidden>
<%= t("live.show.play_hint") %>
@@ -25,6 +25,10 @@
</div>
<%= render "shared/branding_fields", record: @team, show_inherit_hint: true, legend: t("team.edit.branding_legend") %>
<%= render "shared/cover_fields",
record: @team,
show_inherit_hint: true,
can_upload: @entitlements&.can_use_custom_cover? %>
<%= label_tag "team[slug]", t("team.edit.slug_label") %>
<p class="branding-hint" style="margin-top:0">
@@ -0,0 +1,55 @@
<% record = local_assigns[:record] %>
<% show_inherit_hint = local_assigns[:show_inherit_hint] %>
<% can_upload = local_assigns.fetch(:can_upload, false) %>
<% cover_src = record.effective_cover_url.presence || Streams::CoverResolver::DEFAULT_COVER_URL %>
<fieldset class="branding-fields cover-fields">
<legend><%= t("club.branding.cover_legend") %></legend>
<% if show_inherit_hint %>
<p class="branding-hint"><%= t("club.branding.cover_inherit_hint") %></p>
<% end %>
<p class="branding-hint"><%= t("club.branding.cover_hint") %></p>
<div class="branding-logo-block cover-preview-block">
<%= label_tag "branding[cover_image]", t("club.branding.cover_file_label") %>
<div class="branding-logo-preview branding-cover-preview" data-branding-cover-preview>
<%= image_tag cover_src,
alt: t("club.branding.cover_preview_alt"),
class: "branding-cover-preview__img",
data: { branding_cover_img: true } %>
</div>
<% if can_upload %>
<%= file_field_tag "branding[cover_image]",
accept: "image/png,image/jpeg,image/webp",
data: { branding_cover_file: true },
class: "branding-file-input" %>
<% if record.cover_image_attached? %>
<label class="checkbox-label cover-remove-label">
<%= check_box_tag "remove_cover", "1", false, id: "remove_cover_#{record.model_name.param_key}" %>
<%= t("club.branding.cover_remove_label") %>
</label>
<% end %>
<% else %>
<p class="muted"><%= t("club.branding.cover_requires_full") %></p>
<%= link_to t("club.branding.cover_see_plans"), public_prezzi_path, class: "btn btn-secondary btn-sm" %>
<% end %>
</div>
</fieldset>
<script>
(function () {
var input = document.querySelector("[data-branding-cover-file]");
var img = document.querySelector("[data-branding-cover-img]");
if (!input || !img) return;
input.addEventListener("change", function () {
var file = input.files && input.files[0];
if (!file) return;
var reader = new FileReader();
reader.onload = function (e) { img.src = e.target.result; };
reader.readAsDataURL(file);
});
})();
</script>