Compare commits

...
3 Commits
Author SHA1 Message Date
eminuxandCursor 0702cb699c Rendi affidabile pausa con slate e conferma i controlli laterali.
Evita buchi HLS/YouTube in pausa (path slate ricreata, reload player, no patch recording inutili) e richiede conferma su tasti laterali app/regia.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 12:44:23 +02:00
eminuxandCursor e09b3ffcf8 Corregge validazione upload copertina e generazione slate al go-live.
Rifiuta file troppo grandi o non-immagine via Marcel prima di attach, e genera la slate in sync anche quando cover_image esiste ma cover_slate non è ancora pronta.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 09:51:33 +02:00
eminuxandCursor 41d4235258 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>
2026-08-19 23:47:17 +02:00
85 changed files with 2709 additions and 97 deletions
@@ -2,6 +2,7 @@ module Api
module V1
class BaseController < ApplicationController
rescue_from Teams::EntitlementError, with: :render_entitlement_error
rescue_from BrandingAttachments::CoverUploadError, with: :render_cover_upload_error
rescue_from Youtube::BroadcastService::Error, with: :render_youtube_error
private
@@ -20,6 +21,10 @@ module Api
billing_url: error.billing_url
}, status: :forbidden
end
def render_cover_upload_error(error)
render json: { error: error.message, error_code: "cover_upload_invalid" }, status: :unprocessable_entity
end
end
end
end
@@ -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,48 @@ 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!
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/)
@@ -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, BrandingAttachments::CoverUploadError => 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, BrandingAttachments::CoverUploadError => e
@club = @team.club
@entitlements = @team.entitlements
flash.now[:alert] = e.message
render :edit, status: :unprocessable_entity
end
def invite
@@ -52,6 +52,18 @@ module Public
muteError: t("regia.js.mute_error"),
closeError: t("regia.js.close_error"),
closeConfirm: t("regia.js.close_confirm"),
pauseConfirmTitle: t("regia.js.pause_confirm_title"),
pauseConfirmBody: t("regia.js.pause_confirm_body"),
resumeConfirmTitle: t("regia.js.resume_confirm_title"),
resumeConfirmBody: t("regia.js.resume_confirm_body"),
muteConfirmTitle: t("regia.js.mute_confirm_title"),
muteConfirmBody: t("regia.js.mute_confirm_body"),
unmuteConfirmTitle: t("regia.js.unmute_confirm_title"),
unmuteConfirmBody: t("regia.js.unmute_confirm_body"),
advancePeriodTitle: t("regia.js.advance_period_title"),
advancePeriodBody: t("regia.js.advance_period_body"),
confirmAction: t("regia.modal.confirm_action"),
stopConfirmTitle: t("regia.js.stop_confirm_title"),
linkUnavailable: t("regia.js.link_unavailable"),
linkCopied: t("regia.js.link_copied"),
copyPrompt: t("regia.js.copy_prompt"),
@@ -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? }
validate :cover_image_file_size, if: -> { cover_image.attached? }
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
+51 -4
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?
@@ -74,14 +74,55 @@ module Mediamtx
set_always_available(session, enabled: true)
end
# Slate alwaysAvailable: copertina sullo stesso path quando il telefono è offline.
# Garantisce path config + slate: se MediaMTX ha perso la config (restart → all_others),
# in pausa non resterebbe nessuno stream verso HLS/YouTube.
def ensure_path_with_slate!(session)
path = session.mediamtx_path_name
response = @conn.get("/v3/config/paths/get/#{CGI.escape(path)}")
missing = response.status == 404 ||
(response.body.is_a?(Hash) && response.body["error"].present?)
if missing
forget_always_available(path)
begin
create_path(session)
rescue Error
# Path creato in parallelo o già presente: forza solo la slate.
forget_always_available(path)
set_always_available(session, enabled: true)
end
return true
end
conf = response.body.is_a?(Hash) ? response.body : {}
desired = slate_file_path(session)
if conf["alwaysAvailable"] == true && conf["alwaysAvailableFile"].to_s == desired.to_s
remember_always_available(path, enabled: true)
return true
end
forget_always_available(path)
set_always_available(session, enabled: true)
end
# Spegnere record solo se attivo: ogni PATCH path ricarica MediaMTX e distrugge i muxer HLS.
def disable_recording_if_active!(session)
path = session.mediamtx_path_name
response = @conn.get("/v3/config/paths/get/#{CGI.escape(path)}")
return true unless response.success?
return true unless response.body.is_a?(Hash) && response.body["record"] == true
set_path_recording(session, enabled: false)
end
# Slate alwaysAvailable: copertina sullo stesso path quando il telefono è offline.
# Resta accesa anche con publisher in onda (MediaMTX usa il publisher se presente).
def set_always_available(session, enabled:)
path = session.mediamtx_path_name
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 +214,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
@@ -79,9 +79,8 @@ module Mediamtx
end
def restore_slate_path!(session)
return if session.platform == "matchlivetv"
Client.for_session(session).set_always_available(session, enabled: true)
# Anche su matchlivetv: dopo restart MediaMTX la path può cadere su all_others senza slate.
Client.for_session(session).ensure_path_with_slate!(session)
rescue Client::Error => e
Rails.logger.warn("[PublisherSync] enable slate session=#{session.id}: #{e.message}")
end
@@ -146,6 +145,14 @@ module Mediamtx
nil
end
def self.remember_recording_off!(session_id)
redis = Redis.new(url: ENV.fetch("REDIS_URL", "redis://localhost:6379/0"))
redis.set("mediamtx:recording:#{session_id}", "0", ex: 48.hours.to_i)
redis.set(format("mediamtx:recording:patched_at:%s", session_id), Time.current.to_i, ex: 48.hours.to_i)
rescue Redis::BaseError
nil
end
def recording_state_key(session_id)
"mediamtx:recording:#{session_id}"
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,
+5 -3
View File
@@ -7,11 +7,13 @@ module Sessions
def call
cancel_timeout_job
@session.pause! if @session.may_pause?
Mediamtx::PublisherSync.forget_recording_state!(@session.id)
begin
mtx = Mediamtx::Client.for_session(@session)
mtx.set_path_recording(@session, enabled: false)
mtx.set_always_available(@session, enabled: true)
# Ricrea/riallinea slate prima di spegnere l'RTMP del telefono.
mtx.ensure_path_with_slate!(@session)
# PATCH recording solo se era attivo (evita kill muxer HLS a ogni pausa).
mtx.disable_recording_if_active!(@session)
Mediamtx::PublisherSync.remember_recording_off!(@session.id)
rescue Mediamtx::Client::Error => e
Rails.logger.warn("[Sessions::Pause] MediaMTX: #{e.message}")
end
@@ -0,0 +1,77 @@
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
# Restituisce il record con cover_image nella catena anche se la slate non è ancora su disco.
# Usato da CoverSlateEnsurer per sapere cosa generare al go-live.
def pending_cover_record
return nil unless @entitlements.can_use_custom_cover?
candidates.each do |record, _source|
return record if record.cover_image.attached?
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,39 @@
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!
record = find_pending_cover_record
return unless 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
# Cerca il record con cover_image nella catena di ereditarietà,
# anche se la slate non è ancora pronta (a differenza di resolve che richiede la slate su disco).
def find_pending_cover_record
@resolver.pending_cover_record
end
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,35 @@
module Streams
class CoverSlatePaths
def self.slates_custom_root
ENV.fetch("MEDIAMTX_SLATES_CUSTOM_DIR", "/slates/custom")
end
# ActiveStorage checksum is base64 e può contenere "/", "+", "=" — non usabile come path.
def self.safe_digest(checksum)
checksum.to_s.tr("+/", "-_").delete("=")
end
def self.filename_for(record)
return nil unless record.cover_slate.attached?
digest = safe_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,104 @@
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 = CoverSlatePaths.filename_for(result.record)
raise Error, "slate filename missing" if filename.blank?
# Path completo (non File.basename): il checksum AS può contenere "/" e spezzerebbe il path.
mediamtx_path = CoverSlatePaths.expected_path(result.record)
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 %>
+3 -2
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") %>
@@ -219,7 +219,8 @@
}
function onEnterPause() {
nudgePlayback();
// Camera → slate cambia risoluzione/codec: senza reload HLS.js resta spesso bloccato.
hardReloadPlayer();
}
function hardReloadPlayer() {
+1 -1
View File
@@ -165,4 +165,4 @@
</div>
</div>
<script src="/regia.js?v=19"></script>
<script src="/regia.js?v=20"></script>
@@ -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>
+1 -1
View File
@@ -21,7 +21,7 @@ module MatchLiveTv
end
def hls_public_url
ENV.fetch("HLS_PUBLIC_URL", "http://localhost:8888")
ENV.fetch("HLS_PUBLIC_URL") { "#{app_public_url.chomp('/')}/hls" }
end
def mediamtx_hls_url
+1 -1
View File
@@ -57,7 +57,7 @@ de:
username_label: Benutzername
password_label: Passwort
submit: Anmelden
initial_credentials_html: "Anfangs-Zugangsdaten: <code>admin</code> / <code>admin</code>. Ändere das Passwort nach der ersten Anmeldung."
initial_credentials_html: "Anfangs-Zugangsdaten: <code>admin</code> / <code>AdminPass123</code>. Ändere das Passwort nach der ersten Anmeldung."
passwords:
edit:
title: Passwort ändern
+1 -1
View File
@@ -57,7 +57,7 @@ en:
username_label: Username
password_label: Password
submit: Log in
initial_credentials_html: "Initial credentials: <code>admin</code> / <code>admin</code>. Change the password after the first login."
initial_credentials_html: "Initial credentials: <code>admin</code> / <code>AdminPass123</code>. Change the password after the first login."
passwords:
edit:
title: Change password
+1 -1
View File
@@ -57,7 +57,7 @@ es:
username_label: Usuario
password_label: Contraseña
submit: Acceder
initial_credentials_html: "Credenciales iniciales: <code>admin</code> / <code>admin</code>. Cambia la contraseña después del primer acceso."
initial_credentials_html: "Credenciales iniciales: <code>admin</code> / <code>AdminPass123</code>. Cambia la contraseña después del primer acceso."
passwords:
edit:
title: Cambiar contraseña
+1 -1
View File
@@ -57,7 +57,7 @@ fr:
username_label: Nom d'utilisateur
password_label: Mot de passe
submit: Se connecter
initial_credentials_html: "Identifiants initiaux : <code>admin</code> / <code>admin</code>. Changez le mot de passe après la première connexion."
initial_credentials_html: "Identifiants initiaux : <code>admin</code> / <code>AdminPass123</code>. Changez le mot de passe après la première connexion."
passwords:
edit:
title: Changer le mot de passe
+1 -1
View File
@@ -61,7 +61,7 @@ it:
username_label: Username
password_label: Password
submit: Accedi
initial_credentials_html: "Credenziali iniziali: <code>admin</code> / <code>admin</code>. Cambia la password dopo il primo accesso."
initial_credentials_html: "Credenziali iniziali: <code>admin</code> / <code>AdminPass123</code>. Cambia la password dopo il primo accesso."
passwords:
edit:
title: Cambia password
+12
View File
@@ -491,6 +491,7 @@ de:
modal:
set_won_title: Satz gewonnen
confirm: Satz beenden
confirm_action: Bestätigen
cancel: Abbrechen
board:
next_period: Nächstes Viertel
@@ -530,6 +531,17 @@ de:
mute_error: Fehler beim Stummschalten
close_error: Fehler beim Beenden
close_confirm: Übertragung endgültig beenden?
pause_confirm_title: Livestream pausieren?
pause_confirm_body: Das Cover bleibt on air, bis du fortsetzt.
resume_confirm_title: Livestream fortsetzen?
resume_confirm_body: Die Kamera geht wieder on air statt des Covers.
mute_confirm_title: Audio stummschalten?
mute_confirm_body: Das Mikrofon wird nicht mehr an den Stream gesendet, bis du es wieder aktivierst.
unmute_confirm_title: Audio wieder aktivieren?
unmute_confirm_body: Das Mikrofon ist wieder aktiv im Stream.
advance_period_title: Zum nächsten Abschnitt wechseln?
advance_period_body: Die Anzeigetafel wechselt zum nächsten Abschnitt und der aktuelle Stand wird gespeichert.
stop_confirm_title: Livestream beenden?
link_unavailable: Link nicht verfügbar
link_copied: Link kopiert
copy_prompt: "Link kopieren:"
+20
View File
@@ -33,6 +33,14 @@ en:
quick_colors: Quick colors
header_preview_label: Header preview
name_placeholder: Club / team name
cover_legend: Live cover (sponsors)
cover_inherit_hint: Leave blank to use the club cover, otherwise the default Match Live TV cover.
cover_hint: "16:9 image recommended (PNG, JPEG or WebP, max 5 MB). Shown to viewers and YouTube when paused or offline."
cover_file_label: Cover image
cover_preview_alt: Live cover preview
cover_remove_label: Remove custom cover
cover_requires_full: Custom sponsor covers are available on the Premium Full plan.
cover_see_plans: See plans
dashboard:
title: "%{name} — Club"
plan_label: "Plan:"
@@ -486,6 +494,7 @@ en:
modal:
set_won_title: Set won
confirm: Close set
confirm_action: Confirm
cancel: Cancel
board:
next_period: Next quarter
@@ -525,6 +534,17 @@ en:
mute_error: Error muting audio
close_error: Error closing
close_confirm: Permanently close the live stream?
pause_confirm_title: Pause the live stream?
pause_confirm_body: The cover slate will stay on air until you resume.
resume_confirm_title: Resume the live stream?
resume_confirm_body: The camera will go back on air instead of the cover slate.
mute_confirm_title: Mute audio?
mute_confirm_body: The microphone will not be sent to the stream until you unmute.
unmute_confirm_title: Unmute audio?
unmute_confirm_body: The microphone will be active on the stream again.
advance_period_title: Advance to the next period?
advance_period_body: The scoreboard will move to the next period and the current period score will be saved.
stop_confirm_title: End the live stream?
link_unavailable: Link not available
link_copied: Link copied
copy_prompt: "Copy the link:"
+12
View File
@@ -491,6 +491,7 @@ es:
modal:
set_won_title: Set ganado
confirm: Cerrar set
confirm_action: Confirmar
cancel: Cancelar
board:
next_period: Siguiente cuarto
@@ -530,6 +531,17 @@ es:
mute_error: Error al silenciar el audio
close_error: Error al cerrar
close_confirm: "¿Cerrar definitivamente la retransmisión?"
pause_confirm_title: "¿Pausar el directo?"
pause_confirm_body: La portada seguirá en antena hasta que lo reanudes.
resume_confirm_title: "¿Reanudar el directo?"
resume_confirm_body: La cámara volverá a antena en lugar de la portada.
mute_confirm_title: "¿Silenciar el audio?"
mute_confirm_body: El micrófono no se enviará al stream hasta que lo reactives.
unmute_confirm_title: "¿Reactivar el audio?"
unmute_confirm_body: El micrófono volverá a estar activo en el stream.
advance_period_title: "¿Pasar al periodo siguiente?"
advance_period_body: El marcador pasará al siguiente periodo y se guardará el marcador del periodo actual.
stop_confirm_title: "¿Terminar el directo?"
link_unavailable: Enlace no disponible
link_copied: Enlace copiado
copy_prompt: "Copia el enlace:"
+12
View File
@@ -491,6 +491,7 @@ fr:
modal:
set_won_title: Set gagné
confirm: Terminer le set
confirm_action: Confirmer
cancel: Annuler
board:
next_period: Quart-temps suivant
@@ -530,6 +531,17 @@ fr:
mute_error: Erreur lors de la coupure audio
close_error: Erreur de clôture
close_confirm: Clôturer définitivement le direct ?
pause_confirm_title: Mettre le direct en pause ?
pause_confirm_body: La couverture restera à l'antenne jusqu'à la reprise.
resume_confirm_title: Reprendre le direct ?
resume_confirm_body: La caméra reviendra à l'antenne à la place de la couverture.
mute_confirm_title: Couper l'audio ?
mute_confirm_body: Le micro ne sera plus envoyé au flux tant que vous ne le réactivez pas.
unmute_confirm_title: Réactiver l'audio ?
unmute_confirm_body: Le micro sera à nouveau actif sur le flux.
advance_period_title: Passer à la période suivante ?
advance_period_body: Le tableau passera à la période suivante et le score de la période en cours sera enregistré.
stop_confirm_title: Terminer le direct ?
link_unavailable: Lien non disponible
link_copied: Lien copié
copy_prompt: "Copiez le lien :"
+20
View File
@@ -33,6 +33,14 @@ it:
quick_colors: Colori rapidi
header_preview_label: Anteprima intestazione
name_placeholder: Nome società / squadra
cover_legend: Copertina diretta (sponsor)
cover_inherit_hint: Lascia vuoto per usare la copertina della società, altrimenti quella standard Match Live TV.
cover_hint: "Immagine 16:9 consigliata (PNG, JPEG o WebP, max 5 MB). In pausa o senza segnale la vedranno spettatori e YouTube."
cover_file_label: Immagine copertina
cover_preview_alt: Anteprima copertina diretta
cover_remove_label: Rimuovi copertina personalizzata
cover_requires_full: La copertina sponsor personalizzata è disponibile con il piano Premium Full.
cover_see_plans: Vedi piani
dashboard:
title: "%{name} — Società"
plan_label: "Piano:"
@@ -507,6 +515,7 @@ it:
modal:
set_won_title: Set vinto
confirm: Chiudi set
confirm_action: Conferma
cancel: Annulla
board:
next_period: Prossimo quarto
@@ -546,6 +555,17 @@ it:
mute_error: Errore silenziamento audio
close_error: Errore chiusura
close_confirm: Chiudere definitivamente la diretta?
pause_confirm_title: Mettere in pausa?
pause_confirm_body: La diretta passerà alla copertina finché non la riprendi.
resume_confirm_title: Riprendere la diretta?
resume_confirm_body: La telecamera tornerà in onda al posto della copertina.
mute_confirm_title: Silenziare l'audio?
mute_confirm_body: Il microfono non verrà inviato allo stream finché non lo riattivi.
unmute_confirm_title: Riattivare l'audio?
unmute_confirm_body: Il microfono tornerà attivo sullo stream.
advance_period_title: Passare al periodo successivo?
advance_period_body: Il tabellone passerà al periodo successivo e il punteggio del periodo corrente sarà salvato.
stop_confirm_title: Terminare la diretta?
link_unavailable: Link non disponibile
link_copied: Link copiato
copy_prompt: "Copia il link:"
+5
View File
@@ -0,0 +1,5 @@
en:
coverable:
errors:
invalid_type: "must be PNG, JPEG or WebP"
too_large: "exceeds the maximum size of 5 MB"
+5
View File
@@ -0,0 +1,5 @@
it:
coverable:
errors:
invalid_type: "deve essere PNG, JPEG o WebP"
too_large: "supera la dimensione massima di 5 MB"
+2 -1
View File
@@ -44,7 +44,8 @@ seed_plan!("premium_full", "Premium Full", {
"recording_days" => 90,
"phone_download_enabled" => true,
"youtube_enabled" => true,
"youtube_mode" => "team"
"youtube_mode" => "team",
"custom_cover" => true
}, stripe_price_id: ENV["STRIPE_PREMIUM_FULL_PRICE_ID"].presence || ENV["STRIPE_PREMIUM_PRICE_ID"].presence)
Subscription.joins(:plan).where(plans: { slug: "premium_full" }).find_each do |sub|
+19 -1
View File
@@ -449,7 +449,25 @@ body.nav-menu-open { overflow: hidden; }
border-radius: 10px;
object-fit: contain;
}
.branding-logo-preview__placeholder { color: #777; font-size: 0.88rem; text-align: center; }
.branding-cover-preview {
min-height: 140px;
}
.branding-cover-preview__img {
max-width: 100%;
max-height: 180px;
width: auto;
height: auto;
border-radius: 8px;
object-fit: contain;
}
.cover-remove-label {
display: flex;
align-items: center;
gap: 8px;
margin-top: 10px;
font-size: 0.9rem;
color: #aaa;
}
.branding-file-input { margin-bottom: 0 !important; }
.branding-url-input { margin-bottom: 14px; }
.branding-color-row {
+72 -13
View File
@@ -33,6 +33,18 @@
muteError: "Errore silenziamento audio",
closeError: "Errore chiusura",
closeConfirm: "Chiudere definitivamente la diretta?",
pauseConfirmTitle: "Mettere in pausa?",
pauseConfirmBody: "La diretta passerà alla copertina finché non la riprendi.",
resumeConfirmTitle: "Riprendere la diretta?",
resumeConfirmBody: "La telecamera tornerà in onda al posto della copertina.",
muteConfirmTitle: "Silenziare l'audio?",
muteConfirmBody: "Il microfono non verrà inviato allo stream finché non lo riattivi.",
unmuteConfirmTitle: "Riattivare l'audio?",
unmuteConfirmBody: "Il microfono tornerà attivo sullo stream.",
advancePeriodTitle: "Passare al periodo successivo?",
advancePeriodBody: "Il tabellone passerà al periodo successivo e il punteggio del periodo corrente sarà salvato.",
confirmAction: "Conferma",
stopConfirmTitle: "Terminare la diretta?",
linkUnavailable: "Link non disponibile",
linkCopied: "Link copiato",
copyPrompt: "Copia il link:",
@@ -389,13 +401,18 @@
if (cfg.board === "volley" || cfg.board === "racket") {
if (data.set_won && action !== "close_set") {
const winner = data.winner === "home" ? cfg.homeName : cfg.awayName;
openModal(I18N.setWonTitle, fillTemplate(I18N.setWonBodyTemplate, { winner }), () => postScore("close_set"));
openModal(I18N.setWonTitle, fillTemplate(I18N.setWonBodyTemplate, { winner }), () => postScore("close_set"), I18N.closeSetTitle);
}
}
if (data.match_won) {
const winner = data.winner === "home" ? cfg.homeName : cfg.awayName;
openModal(I18N.matchWonTitle, fillTemplate(I18N.matchWonBodyTemplate, { winner }), () => stopStream());
}
if (data.match_won) {
const winner = data.winner === "home" ? cfg.homeName : cfg.awayName;
openModal(
I18N.matchWonTitle,
fillTemplate(I18N.matchWonBodyTemplate, { winner }),
() => performStopStream(),
I18N.confirmAction
);
}
} catch (e) {
if (prevHome != null && els.homePoints) els.homePoints.textContent = prevHome;
const awayEl = document.getElementById("away-points");
@@ -406,9 +423,12 @@
}
}
function openModal(title, body, onConfirm) {
function openModal(title, body, onConfirm, confirmLabel) {
els.modalTitle.textContent = title;
els.modalBody.textContent = body;
if (els.modalConfirm) {
els.modalConfirm.textContent = confirmLabel || I18N.confirmAction;
}
els.modal.classList.add("open");
pendingAction = onConfirm;
}
@@ -440,7 +460,9 @@
btn.addEventListener("click", () => {
const action = btn.dataset.action;
if (action === "close_set") {
openModal(I18N.closeSetTitle, I18N.closeSetConfirm, () => postScore("close_set"));
openModal(I18N.closeSetTitle, I18N.closeSetConfirm, () => postScore("close_set"), I18N.closeSetTitle);
} else if (action === "advance_period") {
openModal(I18N.advancePeriodTitle, I18N.advancePeriodBody, () => handleAction("advance_period"));
} else {
handleAction(action);
}
@@ -689,9 +711,8 @@
toast(audioMuted ? I18N.muted : I18N.unmuted);
}
async function stopStream() {
const ok = confirm(I18N.closeConfirm);
if (!ok) return null;
async function performStopStream() {
if (!cfg.stopUrl) return null;
const res = await fetch(cfg.stopUrl, { method: "POST", headers: { Accept: "application/json" } });
if (!res.ok) throw new Error(I18N.closeError);
const data = await res.json();
@@ -701,9 +722,47 @@
return data;
}
els.btnPause?.addEventListener("click", () => togglePauseStream().catch((e) => toast(e.message)));
els.btnAudioMute?.addEventListener("click", () => toggleMuteAudio().catch((e) => toast(e.message)));
document.getElementById("btn-stop")?.addEventListener("click", () => stopStream().catch((e) => toast(e.message)));
function requestStopStream() {
openModal(I18N.stopConfirmTitle, I18N.closeConfirm, () => performStopStream(), I18N.confirmAction);
}
function requestPauseToggle() {
if (streamPaused) {
openModal(I18N.resumeConfirmTitle, I18N.resumeConfirmBody, async () => {
await togglePauseStream();
return null;
});
} else {
openModal(I18N.pauseConfirmTitle, I18N.pauseConfirmBody, async () => {
await togglePauseStream();
return null;
});
}
}
function requestMuteToggle() {
if (audioMuted) {
openModal(I18N.unmuteConfirmTitle, I18N.unmuteConfirmBody, async () => {
await toggleMuteAudio();
return null;
});
} else {
openModal(I18N.muteConfirmTitle, I18N.muteConfirmBody, async () => {
await toggleMuteAudio();
return null;
});
}
}
async function stopStream() {
// Compatibilità: conferma via modal (non window.confirm).
requestStopStream();
return null;
}
els.btnPause?.addEventListener("click", () => requestPauseToggle());
els.btnAudioMute?.addEventListener("click", () => requestMuteToggle());
document.getElementById("btn-stop")?.addEventListener("click", () => requestStopStream());
let minQualityBusy = false;
@@ -0,0 +1,34 @@
require "rails_helper"
RSpec.describe GenerateCoverSlateJob do
let!(:club) { Club.create!(name: "Club", sport: "volleyball", primary_color: "#e53935", secondary_color: "#ffffff") }
let!(:team) { club.teams.create!(name: "Team", sport: "volleyball") }
let!(:match) { team.matches.create!(opponent_name: "Opp", sport: "volleyball") }
before do
load Rails.root.join("db/seeds/plans.rb")
match.cover_image.attach(
io: StringIO.new("img"),
filename: "c.png",
content_type: "image/png"
)
end
it "usa coda critical per Match" do
expect(described_class).to receive(:set).with(queue: :critical).and_return(described_class)
expect(described_class).to receive(:perform_later).with("Match", match.id)
described_class.enqueue_for(match)
end
it "usa coda default per Club" do
club.cover_image.attach(io: StringIO.new("img"), filename: "c.png", content_type: "image/png")
expect(described_class).to receive(:set).with(queue: :default).and_return(described_class)
expect(described_class).to receive(:perform_later).with("Club", club.id)
described_class.enqueue_for(club)
end
it "invoca GenerateCoverSlate al perform" do
expect(Streams::GenerateCoverSlate).to receive(:call).with(match)
described_class.perform_now("Match", match.id)
end
end
@@ -0,0 +1,50 @@
require "rails_helper"
RSpec.describe Mediamtx::Client do
let!(:user) { User.create!(email: "mtx@test.it", name: "U", password: "Password123", role: "coach") }
let!(:club) { Club.create!(name: "Club", sport: "volleyball", primary_color: "#e53935", secondary_color: "#ffffff") }
let!(:team) { club.teams.create!(name: "Team", sport: "volleyball") }
let!(:match) { team.matches.create!(opponent_name: "Opp", sport: "volleyball") }
let!(:node) do
StreamNode.create!(
slug: "stream-home",
hostname: "home",
role: "home",
status: "ready",
provider: "local",
rtmp_base_url: "rtmp://localhost:1935",
hls_base_url: "http://localhost:8888",
api_base_url: "http://mediamtx:9997",
max_publishers: 6,
max_relays: 6
)
end
let!(:session) do
StreamSession.create!(match: match, user: user, platform: "matchlivetv", status: "idle", stream_node: node)
end
before do
load Rails.root.join("db/seeds/plans.rb")
Billing::AssignPlan.call(club: club, plan_slug: "premium_full")
end
it "usa SlateDistributor per alwaysAvailableFile" do
custom = "/slates/custom/club-test.mp4"
allow(Streams::SlateDistributor).to receive(:slate_path_for_session).with(session).and_return(custom)
conn = instance_double(Faraday::Connection)
response = instance_double(Faraday::Response, success?: true, status: 200, body: {})
allow(Faraday).to receive(:new).and_return(conn)
allow(conn).to receive(:post).and_return(response)
allow(conn).to receive(:get)
allow(Redis).to receive(:new).and_return(instance_double(Redis, get: nil, set: true))
client = described_class.new(base_url: "http://mediamtx:9997")
client.create_path(session)
expect(conn).to have_received(:post).with(
"/v3/config/paths/add/live%2Fmatch_#{session.id}",
hash_including(alwaysAvailableFile: custom)
)
end
end
@@ -27,6 +27,8 @@ RSpec.describe Mediamtx::PublisherSync do
allow(Mediamtx::PublisherOnline).to receive(:active?).and_return(true)
allow_any_instance_of(described_class).to receive(:redis).and_return(redis)
allow(client).to receive(:set_path_recording)
allow(client).to receive(:ensure_path_with_slate!)
allow(client).to receive(:set_always_available)
end
it "abilita la registrazione quando il publisher è online e la sessione è live" do
@@ -0,0 +1,71 @@
require "rails_helper"
RSpec.describe Streams::CoverResolver do
let!(:club) { Club.create!(name: "Club", sport: "volleyball", primary_color: "#e53935", secondary_color: "#ffffff") }
let!(:team) { club.teams.create!(name: "Team", sport: "volleyball") }
let!(:match) { team.matches.create!(opponent_name: "Opp", sport: "volleyball") }
before do
load Rails.root.join("db/seeds/plans.rb")
Billing::AssignPlan.call(club: club, plan_slug: "free")
end
def attach_ready_cover(record, name)
record.cover_image.attach(
io: StringIO.new("fake-image"),
filename: "#{name}.png",
content_type: "image/png"
)
record.cover_slate.attach(
io: StringIO.new("fake-mp4"),
filename: "#{name}.mp4",
content_type: "video/mp4"
)
path = Streams::CoverSlatePaths.expected_path(record)
FileUtils.mkdir_p(File.dirname(path))
File.write(path, "fake mp4")
path
end
it "restituisce default senza Premium Full" do
resolver = described_class.new(match)
expect(resolver.cover_source).to eq("default")
expect(resolver.effective_cover_url).to eq("/images/copertina-canale.png")
end
context "con Premium Full" do
before { Billing::AssignPlan.call(club: club, plan_slug: "premium_full") }
it "preferisce partita, poi squadra, poi società" do
attach_ready_cover(club, "club")
attach_ready_cover(team, "team")
attach_ready_cover(match, "match")
resolver = described_class.new(match)
expect(resolver.cover_source).to eq("match")
end
it "eredita dalla squadra se la partita non ha override" do
attach_ready_cover(club, "club")
attach_ready_cover(team, "team")
resolver = described_class.new(match)
expect(resolver.cover_source).to eq("team")
end
it "eredita dalla società se mancano squadra e partita" do
attach_ready_cover(club, "club")
resolver = described_class.new(match)
expect(resolver.cover_source).to eq("club")
end
it "ignora cover_image senza slate MP4 pronta su disco" do
attach_ready_cover(team, "team")
match.cover_image.attach(io: StringIO.new("img"), filename: "m.png", content_type: "image/png")
resolver = described_class.new(match)
expect(resolver.cover_source).to eq("team")
end
end
end
@@ -0,0 +1,38 @@
require "rails_helper"
RSpec.describe Streams::CoverSlateEnsurer do
let!(:club) { Club.create!(name: "Club", sport: "volleyball", primary_color: "#e53935", secondary_color: "#ffffff") }
let!(:team) { club.teams.create!(name: "Team", sport: "volleyball") }
let!(:match) { team.matches.create!(opponent_name: "Opp", sport: "volleyball") }
before do
load Rails.root.join("db/seeds/plans.rb")
Billing::AssignPlan.call(club: club, plan_slug: "premium_full")
match.cover_image.attach(
io: StringIO.new("img"),
filename: "c.png",
content_type: "image/png"
)
end
it "genera in sync se manca cover_slate" do
expect(Streams::GenerateCoverSlate).to receive(:call).with(match).and_return(match)
described_class.ensure_for!(match)
end
it "non rigenera se slate pronta su disco" do
match.cover_slate.attach(
io: StringIO.new("mp4"),
filename: "s.mp4",
content_type: "video/mp4"
)
path = Streams::CoverSlatePaths.expected_path(match)
FileUtils.mkdir_p(File.dirname(path))
File.write(path, "fake")
expect(Streams::GenerateCoverSlate).not_to receive(:call)
described_class.ensure_for!(match)
ensure
FileUtils.rm_f(path) if defined?(path) && path
end
end
@@ -0,0 +1,50 @@
require "rails_helper"
RSpec.describe Streams::GenerateCoverSlate do
let!(:club) { Club.create!(name: "Club", sport: "volleyball", primary_color: "#e53935", secondary_color: "#ffffff") }
before do
load Rails.root.join("db/seeds/plans.rb")
Billing::AssignPlan.call(club: club, plan_slug: "premium_full")
club.cover_image.attach(
io: StringIO.new("fake-image"),
filename: "cover.png",
content_type: "image/png"
)
end
it "genera cover_slate e scrive su disco se ffmpeg ok" do
mp4 = Tempfile.new(["slate", ".mp4"])
mp4.write("fake mp4")
mp4.flush
allow(Open3).to receive(:capture3).and_return(["", "", instance_double(Process::Status, success?: true)])
allow(File).to receive(:exist?).and_call_original
allow(File).to receive(:exist?).with(mp4.path).and_return(true)
allow(File).to receive(:size).with(mp4.path).and_return(8)
service = described_class.new(club)
allow(service).to receive(:encode_slate).and_return(mp4.path)
allow(service).to receive(:download_cover_image).and_return("/tmp/in.png")
slates_dir = Rails.root.join("tmp/slates-custom-test")
FileUtils.mkdir_p(slates_dir)
allow(Streams::CoverSlatePaths).to receive(:slates_custom_root).and_return(slates_dir.to_s)
service.call
expect(club.reload.cover_slate).to be_attached
expect(club.cover_slate.content_type).to eq("video/mp4")
ensure
mp4.close!
FileUtils.rm_rf(slates_dir) if defined?(slates_dir)
end
it "solleva Error se ffmpeg fallisce" do
allow(Open3).to receive(:capture3).and_return(["", "boom", instance_double(Process::Status, success?: false)])
expect {
described_class.new(club).send(:encode_slate, "/tmp/in.png")
}.to raise_error(Streams::GenerateCoverSlate::Error, /ffmpeg slate failed/)
end
end
@@ -0,0 +1,79 @@
require "rails_helper"
RSpec.describe Streams::SlateDistributor do
let!(:user) { User.create!(email: "u@test.it", name: "U", password: "Password123", role: "coach") }
let!(:club) { Club.create!(name: "Club", sport: "volleyball", primary_color: "#e53935", secondary_color: "#ffffff") }
let!(:team) { club.teams.create!(name: "Team", sport: "volleyball") }
let!(:match) { team.matches.create!(opponent_name: "Opp", sport: "volleyball") }
let!(:node) do
StreamNode.create!(
slug: "stream-home",
hostname: "home",
role: "home",
status: "ready",
provider: "local",
rtmp_base_url: "rtmp://localhost:1935",
hls_base_url: "http://localhost:8888",
api_base_url: "http://mediamtx:9997",
max_publishers: 6,
max_relays: 6
)
end
let!(:session) do
StreamSession.create!(match: match, user: user, platform: "matchlivetv", status: "idle", stream_node: node)
end
before do
load Rails.root.join("db/seeds/plans.rb")
Billing::AssignPlan.call(club: club, plan_slug: "premium_full")
end
def attach_ready_cover(record)
record.cover_image.attach(io: StringIO.new("img"), filename: "c.png", content_type: "image/png")
record.cover_slate.attach(io: StringIO.new("mp4"), filename: "s.mp4", content_type: "video/mp4")
path = Streams::CoverSlatePaths.expected_path(record)
FileUtils.mkdir_p(File.dirname(path))
File.write(path, "fake mp4")
path
end
it "usa slate default senza copertina custom" do
expect(described_class.slate_path_for_session(session)).to eq("/slates/offline.mp4")
end
it "usa path custom su nodo home quando la slate è su disco" do
attach_ready_cover(club)
custom = Streams::CoverSlatePaths.expected_path(club)
expect(described_class.slate_path_for_session(session)).to eq(custom)
end
it "pusha sul relay agent per nodi cloud" do
cloud = StreamNode.create!(
slug: "ingest-01",
hostname: "ingest-01",
role: "cloud",
status: "ready",
provider: "hetzner",
rtmp_base_url: "rtmp://ingest-01.test:1935",
hls_base_url: "http://localhost:8888",
api_base_url: "http://203.0.113.9:9997",
max_publishers: 4,
max_relays: 4,
metadata: { "public_ip" => "203.0.113.9" }
)
session.update!(stream_node: cloud)
attach_ready_cover(club)
http = instance_double(Net::HTTP)
response = instance_double(Net::HTTPResponse, body: "{}", code: "201")
allow(response).to receive(:is_a?).with(Net::HTTPSuccess).and_return(true)
allow(Net::HTTP).to receive(:new).and_return(http)
allow(http).to receive(:open_timeout=)
allow(http).to receive(:read_timeout=)
allow(http).to receive(:request).and_return(response)
path = described_class.slate_path_for_session(session)
expect(path).to eq(Streams::CoverSlatePaths.expected_path(club))
expect(http).to have_received(:request)
end
end
@@ -0,0 +1,30 @@
require "rails_helper"
RSpec.describe Teams::Entitlements do
let!(:club) { Club.create!(name: "Club", sport: "volleyball", primary_color: "#e53935", secondary_color: "#ffffff") }
let!(:team) { club.teams.create!(name: "Team", sport: "volleyball") }
before do
load Rails.root.join("db/seeds/plans.rb")
Billing::AssignPlan.call(club: club, plan_slug: "free")
end
it "non consente copertina custom su free" do
ent = described_class.new(team)
expect(ent.can_use_custom_cover?).to eq(false)
expect { ent.assert_can_upload_cover! }.to raise_error(Teams::EntitlementError, /Premium Full/)
end
it "consente copertina custom su premium full" do
Billing::AssignPlan.call(club: club, plan_slug: "premium_full")
ent = described_class.new(team)
expect(ent.can_use_custom_cover?).to eq(true)
expect { ent.assert_can_upload_cover! }.not_to raise_error
end
it "espone custom_cover_enabled in as_json" do
Billing::AssignPlan.call(club: club, plan_slug: "premium_full")
ent = described_class.new(team)
expect(ent.as_json[:custom_cover_enabled]).to eq(true)
end
end
+4 -2
View File
@@ -99,7 +99,7 @@ services:
HCLOUD_SSH_KEY: ${HCLOUD_SSH_KEY:-matchlivetv-stream-hetzner}
HCLOUD_NETWORK_ID: ${HCLOUD_NETWORK_ID:-}
HCLOUD_USER_DATA_FILE: /opt/matchlivetv/infra/stream-node/cloud-init.yaml
HLS_PUBLIC_URL: ${HLS_PUBLIC_URL:-http://localhost:8888}
HLS_PUBLIC_URL: ${HLS_PUBLIC_URL:-http://localhost:3000/hls}
APP_PUBLIC_URL: ${APP_PUBLIC_URL:-http://localhost:3000}
PRIVACY_CONTACT_EMAIL: ${PRIVACY_CONTACT_EMAIL:-privacy@matchlivetv.it}
SUPPORT_CONTACT_EMAIL: ${SUPPORT_CONTACT_EMAIL:-}
@@ -170,6 +170,7 @@ services:
- ${MATCHLIVETV_VIDEOS_ROOT:-/media/videos/matchlivetv}/recordings:/recordings
- ${MATCHLIVETV_VIDEOS_ROOT:-/media/videos/matchlivetv}/active_storage:/app/storage
- ${MATCHLIVETV_VIDEOS_ROOT:-/media/videos/matchlivetv}/log:/app/log
- ./slates:/slates
- ${HCLOUD_USER_DATA_HOST_DIR:-./stream-node}:/opt/matchlivetv/infra/stream-node:ro
healthcheck:
test: ["CMD", "curl", "-f", "http://127.0.0.1:3000/up"]
@@ -250,7 +251,7 @@ services:
RAILS_INTERNAL_URL: http://rails:3000
MEDIAMTX_HLS_URL: http://mediamtx:8888
MEDIAMTX_INTERNAL_RTMP_URL: rtmp://mediamtx:1935
HLS_PUBLIC_URL: ${HLS_PUBLIC_URL:-http://localhost:8888}
HLS_PUBLIC_URL: ${HLS_PUBLIC_URL:-http://localhost:3000/hls}
APP_PUBLIC_URL: ${APP_PUBLIC_URL:-http://localhost:3000}
MAILER_FROM: ${MAILER_FROM:-Match Live TV <noreply@matchlivetv.it>}
SMTP_ADDRESS: ${SMTP_ADDRESS:-}
@@ -299,6 +300,7 @@ services:
- ${MATCHLIVETV_VIDEOS_ROOT:-/media/videos/matchlivetv}/recordings:/recordings
- ${MATCHLIVETV_VIDEOS_ROOT:-/media/videos/matchlivetv}/active_storage:/app/storage
- ${MATCHLIVETV_VIDEOS_ROOT:-/media/videos/matchlivetv}/log:/app/log
- ./slates:/slates
- ${HCLOUD_USER_DATA_HOST_DIR:-./stream-node}:/opt/matchlivetv/infra/stream-node:ro
garage:
+2
View File
@@ -160,6 +160,7 @@ services:
- ../backend:/app
- recordings:/recordings
- bundle_cache:/usr/local/bundle
- ./slates:/slates
- ./stream-node:/opt/matchlivetv/infra/stream-node:ro
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/up"]
@@ -238,6 +239,7 @@ services:
- ../backend:/app
- recordings:/recordings
- bundle_cache:/usr/local/bundle
- ./slates:/slates
- ./stream-node:/opt/matchlivetv/infra/stream-node:ro
# Worker ffmpeg per il secondo MediaMTX (nodo lab locale, RTMP host :11935).
View File
+26 -1
View File
@@ -56,6 +56,7 @@ write_files:
STREAM_NODE_AGENT_LISTEN=0.0.0.0:9100
STREAM_NODE_LOCAL_HLS_URL=http://127.0.0.1:8888
STREAM_NODE_RELAY_LOG_DIR=/var/log
STREAM_NODE_SLATES_DIR=/slates/custom
- path: /opt/stream-node/relay-agent.py
permissions: "0755"
content: |
@@ -77,6 +78,7 @@ write_files:
LISTEN = os.environ.get("STREAM_NODE_AGENT_LISTEN", "0.0.0.0:9100")
HLS_BASE = os.environ.get("STREAM_NODE_LOCAL_HLS_URL", "http://127.0.0.1:8888").rstrip("/")
LOG_DIR = os.environ.get("STREAM_NODE_RELAY_LOG_DIR", "/var/log")
SLATES_DIR = os.environ.get("STREAM_NODE_SLATES_DIR", "/slates/custom")
_lock = threading.Lock()
# session_id -> {"pid": int, "path": str, "proc": Popen}
@@ -250,6 +252,29 @@ write_files:
_stop_session(session_id)
self._json(200, {"stopped": True, "session_id": session_id})
def do_PUT(self) -> None:
if not _authorized(self):
self._json(401, {"error": "unauthorized"})
return
parsed = urlparse(self.path)
if not parsed.path.startswith("/slates/"):
self._json(404, {"error": "not found"})
return
name = parsed.path.split("/slates/", 1)[1].strip("/")
if not name or "/" in name or ".." in name:
self._json(400, {"error": "invalid slate name"})
return
length = int(self.headers.get("Content-Length") or 0)
if length <= 0:
self._json(400, {"error": "empty body"})
return
data = self.rfile.read(length)
os.makedirs(SLATES_DIR, exist_ok=True)
dest = os.path.join(SLATES_DIR, name)
with open(dest, "wb") as out:
out.write(data)
self._json(201, {"path": dest, "bytes": len(data), "name": name})
def main() -> None:
host, port_s = LISTEN.rsplit(":", 1)
@@ -265,7 +290,7 @@ write_files:
content: |
#!/bin/bash
set -euo pipefail
mkdir -p /recordings /slates /var/log
mkdir -p /recordings /slates/custom /var/log
systemctl enable --now docker
for i in $(seq 1 60); do
if docker info >/dev/null 2>&1; then break; fi
+24
View File
@@ -16,6 +16,7 @@ SECRET = os.environ.get("STREAM_NODE_AGENT_SECRET", "")
LISTEN = os.environ.get("STREAM_NODE_AGENT_LISTEN", "0.0.0.0:9100")
HLS_BASE = os.environ.get("STREAM_NODE_LOCAL_HLS_URL", "http://127.0.0.1:8888").rstrip("/")
LOG_DIR = os.environ.get("STREAM_NODE_RELAY_LOG_DIR", "/var/log")
SLATES_DIR = os.environ.get("STREAM_NODE_SLATES_DIR", "/slates/custom")
_lock = threading.Lock()
# session_id -> {"pid": int, "path": str, "proc": Popen}
@@ -189,6 +190,29 @@ class Handler(BaseHTTPRequestHandler):
_stop_session(session_id)
self._json(200, {"stopped": True, "session_id": session_id})
def do_PUT(self) -> None:
if not _authorized(self):
self._json(401, {"error": "unauthorized"})
return
parsed = urlparse(self.path)
if not parsed.path.startswith("/slates/"):
self._json(404, {"error": "not found"})
return
name = parsed.path.split("/slates/", 1)[1].strip("/")
if not name or "/" in name or ".." in name:
self._json(400, {"error": "invalid slate name"})
return
length = int(self.headers.get("Content-Length") or 0)
if length <= 0:
self._json(400, {"error": "empty body"})
return
data = self.rfile.read(length)
os.makedirs(SLATES_DIR, exist_ok=True)
dest = os.path.join(SLATES_DIR, name)
with open(dest, "wb") as out:
out.write(data)
self._json(201, {"path": dest, "bytes": len(data), "name": name})
def main() -> None:
host, port_s = LISTEN.rsplit(":", 1)
@@ -0,0 +1,308 @@
package com.matchlivetv.match_live_tv
import android.content.Intent
import android.os.SystemClock
import android.view.KeyEvent
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.UiObject2
import androidx.test.uiautomator.Until
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* E2E emulatore: login wizard partita upload copertina sponsor salva.
* Richiede backend locale su http://10.0.2.2:3000 (variante collaudoDebug).
*/
@RunWith(AndroidJUnit4::class)
class E2ECoverUploadTest {
private lateinit var device: UiDevice
private val ctx by lazy { InstrumentationRegistry.getInstrumentation().targetContext }
private val pkg by lazy { ctx.packageName }
private fun s(id: Int): String = ctx.getString(id)
private fun su(id: Int): String = s(id).uppercase()
@Before
fun setUp() {
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
grantRuntimePermissions()
launchApp()
}
@Test
fun wizard_uploadsMatchCover_andShowsMatchSource() {
loginIfNeeded()
waitForAnyText(su(R.string.matches_new), "NUOVA PARTITA", "NEW MATCH", timeoutMs = 60_000)
openMatchWizardViaQuickStart()
waitForText(s(R.string.wizard_step_title_match), timeoutMs = 45_000)
scrollUntilVisible(s(R.string.wizard_match_cover_title))
tapClickableText(s(R.string.wizard_match_cover_change))
pickFirstPhotoFromPicker()
waitForTextContains(
s(R.string.wizard_match_cover_source_match),
"Questa partita",
"This match",
timeoutMs = 20_000,
)
tapClickableText(s(R.string.wizard_action_next))
waitForText(s(R.string.wizard_step_title_transmission), timeoutMs = 45_000)
assertTrue(
"Wizard non ha salvato la copertina (step trasmissione non raggiunto)",
device.hasObject(By.text(s(R.string.wizard_step_title_transmission))),
)
}
private fun waitForTextContains(vararg needles: String, timeoutMs: Long) {
val deadline = SystemClock.elapsedRealtime() + timeoutMs
while (SystemClock.elapsedRealtime() < deadline) {
for (needle in needles) {
if (device.hasObject(By.textContains(needle))) return
}
SystemClock.sleep(250)
}
error("Nessun testo contenente: ${needles.joinToString()}")
}
private fun loginIfNeeded() {
waitForAnyText(
s(R.string.login_email),
su(R.string.login_submit),
su(R.string.matches_new),
timeoutMs = 45_000,
)
if (hasMatchList()) return
val email = InstrumentationRegistry.getArguments().getString("email") ?: "dir@test.com"
val password = InstrumentationRegistry.getArguments().getString("password") ?: "TestPass123!"
repeat(3) {
val emailField = waitForRes("login_email")
val passwordField = waitForRes("login_password")
pasteIntoField(emailField, email)
pasteIntoField(passwordField, password)
device.pressKeyCode(KeyEvent.KEYCODE_ENTER)
device.waitForIdle()
SystemClock.sleep(1500)
tapLoginSubmit()
SystemClock.sleep(4000)
if (hasMatchList()) return
}
error("Login fallito")
}
private fun openMatchWizardViaQuickStart() {
tapClickableText(su(R.string.matches_new))
waitForText(s(R.string.sheet_quick_option), timeoutMs = 15_000)
tapClickableText(s(R.string.sheet_quick_option))
}
private fun pickFirstPhotoFromPicker() {
val pickerPkg = "com.google.android.photopicker"
val deadline = SystemClock.elapsedRealtime() + 25_000
while (SystemClock.elapsedRealtime() < deadline) {
if (device.hasObject(By.pkg(pickerPkg))) break
SystemClock.sleep(400)
}
if (!device.hasObject(By.pkg(pickerPkg))) {
error("Photo picker non aperto")
}
SystemClock.sleep(1500)
if (device.hasObject(By.textContains("cover_test"))) {
tapClickableTextContains("cover_test")
} else {
val thumb = device.findObjects(By.pkg(pickerPkg).clickable(true))
.filter {
val b = it.visibleBounds
b.top >= 1200 && b.width() >= 250
}
.minByOrNull { it.visibleBounds.top }
if (thumb != null) {
thumb.click()
} else {
device.click(device.displayWidth / 6, 1450)
}
}
device.waitForIdle()
SystemClock.sleep(1000)
if (device.hasObject(By.text("Fine"))) {
tapClickableText("Fine")
} else if (device.hasObject(By.text("Done"))) {
tapClickableText("Done")
} else {
device.click((device.displayWidth * 0.85).toInt(), (device.displayHeight * 0.92).toInt())
}
waitForWizardReturn()
}
private fun waitForWizardReturn() {
device.wait(Until.hasObject(By.pkg(pkg)), 15_000)
device.waitForIdle()
SystemClock.sleep(800)
confirmPickerIfNeeded()
}
private fun tapClickableTextContains(needle: String) {
val label = device.findObject(By.textContains(needle))
?: error("Testo non trovato: $needle")
var node: UiObject2? = label
repeat(8) {
val current = node ?: return@repeat
if (current.isClickable) {
current.click()
device.waitForIdle()
return
}
node = current.parent
}
label.click()
device.waitForIdle()
}
private fun confirmPickerIfNeeded() {
val confirmLabels = listOf("Done", "Fatto", "OK", "Select", "Seleziona")
for (label in confirmLabels) {
val btn = device.findObject(By.text(label).clickable(true))
if (btn != null) {
btn.click()
device.waitForIdle()
return
}
}
}
private fun scrollUntilVisible(text: String) {
repeat(8) {
if (device.hasObject(By.text(text))) return
scrollDown(1)
}
waitForText(text, timeoutMs = 10_000)
}
private fun grantRuntimePermissions() {
listOf(
"android.permission.CAMERA",
"android.permission.RECORD_AUDIO",
"android.permission.POST_NOTIFICATIONS",
"android.permission.READ_MEDIA_IMAGES",
"android.permission.READ_EXTERNAL_STORAGE",
).forEach { permission ->
device.executeShellCommand("pm grant $pkg $permission")
}
}
private fun launchApp() {
val intent = ctx.packageManager.getLaunchIntentForPackage(pkg)?.apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
} ?: error("Launch intent mancante per $pkg")
ctx.startActivity(intent)
device.wait(Until.hasObject(By.pkg(pkg).depth(0)), 15_000)
}
private fun hasMatchList(): Boolean =
device.hasObject(By.text(su(R.string.matches_new))) ||
device.hasObject(By.text("NUOVA PARTITA")) ||
device.hasObject(By.text("NEW MATCH"))
private fun waitForRes(tag: String): UiObject2 {
val obj = device.wait(Until.findObject(By.res(tag)), 10_000)
?: device.wait(Until.findObject(By.res("$pkg:id/$tag")), 2_000)
?: error("Nodo non trovato: $tag")
return obj
}
private fun tapLoginSubmit() {
val btn = device.wait(Until.findObject(By.res("login_submit")), 3_000)
?: device.wait(Until.findObject(By.res("$pkg:id/login_submit")), 1_000)
if (btn != null) {
val bounds = btn.visibleBounds
device.click(bounds.centerX(), bounds.centerY())
device.waitForIdle()
return
}
val nodes = device.findObjects(By.text(su(R.string.login_submit))) +
device.findObjects(By.text("ACCEDI")) +
device.findObjects(By.text("LOG IN"))
val target = nodes.lastOrNull { it.isClickable } ?: nodes.lastOrNull()
target?.click()
device.waitForIdle()
}
private fun pasteIntoField(field: UiObject2, value: String) {
field.click()
device.waitForIdle()
field.clear()
field.text = value
device.waitForIdle()
}
private fun waitForText(text: String, timeoutMs: Long): UiObject2 {
val obj = device.wait(Until.findObject(By.text(text)), timeoutMs)
assertNotNull("Testo non trovato entro ${timeoutMs}ms: $text", obj)
return obj!!
}
private fun waitForAnyText(vararg texts: String, timeoutMs: Long) {
val deadline = SystemClock.elapsedRealtime() + timeoutMs
while (SystemClock.elapsedRealtime() < deadline) {
for (text in texts) {
if (device.hasObject(By.text(text))) return
}
SystemClock.sleep(250)
}
error("Nessuno dei testi trovato: ${texts.joinToString()}")
}
private fun tapClickableText(text: String) {
repeat(8) {
val clickable = device.findObject(By.text(text).clickable(true))
val label = clickable ?: device.findObject(By.text(text))
if (label != null) {
val b = label.visibleBounds
if (b.height() >= 16 && b.bottom <= device.displayHeight && b.top >= 0) {
var node: UiObject2? = label
for (i in 0 until 6) {
val current = node ?: break
if (current.isClickable) {
current.click()
device.waitForIdle()
return
}
node = current.parent
}
label.click()
device.waitForIdle()
return
}
}
scrollDown(1)
device.waitForIdle()
}
error("Testo non cliccabile visibile: $text")
}
private fun scrollDown(steps: Int = 2) {
val centerX = device.displayWidth / 2
val startY = (device.displayHeight * 0.75).toInt()
val endY = (device.displayHeight * 0.25).toInt()
repeat(steps) {
device.swipe(centerX, startY, centerX, endY, 24)
device.waitForIdle()
SystemClock.sleep(300)
}
}
}
@@ -0,0 +1,258 @@
package com.matchlivetv.match_live_tv
import android.content.Intent
import android.os.SystemClock
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.UiObject2
import androidx.test.uiautomator.Until
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
/**
* E2E: in diretta, ogni tasto laterale critico apre un dialog di conferma
* e Annulla non esegue l'azione.
*/
@RunWith(AndroidJUnit4::class)
class E2ESideConfirmDialogTest {
private lateinit var device: UiDevice
private val ctx by lazy { InstrumentationRegistry.getInstrumentation().targetContext }
private val pkg by lazy { ctx.packageName }
private fun s(id: Int): String = ctx.getString(id)
private fun su(id: Int): String = s(id).uppercase()
@Before
fun setUp() {
device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
grantRuntimePermissions()
launchApp()
}
@Test
fun sideButtons_showConfirmDialog_andCancel() {
ensureLoggedIn()
openMatchWizardViaQuickStart()
waitForText(s(R.string.wizard_step_title_match), timeoutMs = 45_000)
scrollDown()
tapClickableText(s(R.string.wizard_action_next))
waitForText(s(R.string.wizard_step_title_transmission), timeoutMs = 45_000)
skipToNetworkAndStart()
waitForAnyText(
s(R.string.broadcast_status_live),
s(R.string.broadcast_status_connecting),
s(R.string.broadcast_status_paused),
timeoutMs = 90_000,
)
SystemClock.sleep(2_000)
assertConfirmThenCancel(
contentDesc = s(R.string.broadcast_pause_cd),
dialogTitle = s(R.string.broadcast_pause_title),
)
assertConfirmThenCancel(
contentDesc = s(R.string.broadcast_mute_cd),
dialogTitle = s(R.string.broadcast_mute_title),
)
assertConfirmThenCancel(
contentDesc = s(R.string.broadcast_share_regia_cd),
dialogTitle = s(R.string.broadcast_share_regia_title),
)
assertConfirmThenCancel(
contentDesc = s(R.string.broadcast_terminate_cd),
dialogTitle = s(R.string.broadcast_terminate_title),
)
// Dopo Annulla su termina, la diretta deve essere ancora aperta.
assertTrue(
"La diretta non deve chiudersi dopo Annulla su termina",
device.hasObject(By.desc(s(R.string.broadcast_pause_cd))) ||
device.hasObject(By.desc(s(R.string.broadcast_resume_cd))) ||
device.hasObject(By.text(s(R.string.broadcast_status_live))) ||
device.hasObject(By.text(s(R.string.broadcast_status_connecting))) ||
device.hasObject(By.text(s(R.string.broadcast_status_paused))),
)
}
private fun assertConfirmThenCancel(contentDesc: String, dialogTitle: String) {
val btn = device.wait(Until.findObject(By.desc(contentDesc)), 15_000)
?: error("Pulsante laterale non trovato: $contentDesc")
btn.click()
device.waitForIdle()
val title = device.wait(Until.findObject(By.text(dialogTitle)), 8_000)
assertTrue("Dialog conferma assente per $contentDesc (atteso: $dialogTitle)", title != null)
tapClickableText(s(R.string.action_cancel))
SystemClock.sleep(600)
assertFalse(
"Dialog ancora aperto dopo Annulla: $dialogTitle",
device.hasObject(By.text(dialogTitle)),
)
}
private fun skipToNetworkAndStart() {
val onNetworkStep = {
device.hasObject(By.text(s(R.string.wizard_network_test_start_label))) ||
device.hasObject(By.text("AVVIA TEST RETE"))
}
repeat(5) {
if (onNetworkStep()) return@repeat
runCatching { tapClickableText(s(R.string.wizard_action_next)) }
scrollUp()
SystemClock.sleep(800)
}
waitForAnyText(s(R.string.wizard_network_test_start_label), "AVVIA TEST RETE", timeoutMs = 45_000)
tapClickableText(s(R.string.wizard_network_test_start_label))
waitForText(s(R.string.wizard_action_start), timeoutMs = 45_000)
waitUntilEnabled(s(R.string.wizard_action_start), timeoutMs = 30_000)
tapClickableText(s(R.string.wizard_action_start))
}
private fun ensureLoggedIn() {
waitForAnyText(
s(R.string.login_email),
su(R.string.login_submit),
su(R.string.matches_new),
timeoutMs = 45_000,
)
if (hasMatchList()) return
fillLogin()
tapLoginSubmit()
SystemClock.sleep(3_000)
waitForAnyText(su(R.string.matches_new), timeoutMs = 60_000)
}
private fun fillLogin() {
val email = device.findObject(By.clazz("android.widget.EditText"))
?: error("Campo email non trovato")
pasteIntoField(email, "dir@test.com")
val fields = device.findObjects(By.clazz("android.widget.EditText"))
val password = fields.getOrNull(1) ?: error("Campo password non trovato")
pasteIntoField(password, "TestPass123!")
}
private fun tapLoginSubmit() {
tapClickableText(su(R.string.login_submit))
}
private fun openMatchWizardViaQuickStart() {
tapClickableText(su(R.string.matches_new))
waitForText(s(R.string.sheet_quick_option), timeoutMs = 15_000)
tapClickableText(s(R.string.sheet_quick_option))
}
private fun grantRuntimePermissions() {
listOf(
"android.permission.CAMERA",
"android.permission.RECORD_AUDIO",
"android.permission.POST_NOTIFICATIONS",
).forEach { permission ->
device.executeShellCommand("pm grant $pkg $permission")
}
}
private fun launchApp() {
val intent = ctx.packageManager.getLaunchIntentForPackage(pkg)?.apply {
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
} ?: error("Launch intent mancante per $pkg")
ctx.startActivity(intent)
device.wait(Until.hasObject(By.pkg(pkg).depth(0)), 15_000)
}
private fun hasMatchList(): Boolean =
device.hasObject(By.text(su(R.string.matches_new)))
private fun pasteIntoField(field: UiObject2, value: String) {
field.click()
device.waitForIdle()
field.clear()
field.text = value
device.waitForIdle()
}
private fun waitForText(text: String, timeoutMs: Long): UiObject2 {
val obj = device.wait(Until.findObject(By.text(text)), timeoutMs)
?: error("Testo non trovato entro ${timeoutMs}ms: $text")
return obj
}
private fun waitForAnyText(vararg texts: String, timeoutMs: Long) {
val deadline = SystemClock.elapsedRealtime() + timeoutMs
while (SystemClock.elapsedRealtime() < deadline) {
for (text in texts) {
if (device.hasObject(By.text(text))) return
}
SystemClock.sleep(250)
}
error("Nessuno dei testi trovato: ${texts.joinToString()}")
}
private fun tapClickableText(text: String) {
repeat(6) {
val clickable = device.findObject(By.text(text).clickable(true))
val label = clickable ?: device.findObject(By.text(text))
if (label != null) {
var node: UiObject2? = label
for (i in 0 until 6) {
val current = node ?: break
if (current.isClickable) {
current.click()
device.waitForIdle()
return
}
node = current.parent
}
label.click()
device.waitForIdle()
return
}
scrollDown(1)
device.waitForIdle()
}
error("Testo non cliccabile visibile: $text")
}
private fun waitUntilEnabled(text: String, timeoutMs: Long) {
val deadline = SystemClock.elapsedRealtime() + timeoutMs
while (SystemClock.elapsedRealtime() < deadline) {
val label = device.findObject(By.text(text))
if (label != null) {
var node: UiObject2? = label
for (i in 0 until 6) {
val current = node ?: break
if (current.isClickable && current.isEnabled) return
node = current.parent
}
}
SystemClock.sleep(500)
}
error("Pulsante non abilitato entro timeout: $text")
}
private fun scrollDown(steps: Int = 2) {
val centerX = device.displayWidth / 2
val startY = (device.displayHeight * 0.75).toInt()
val endY = (device.displayHeight * 0.25).toInt()
repeat(steps) {
device.swipe(centerX, startY, centerX, endY, 24)
device.waitForIdle()
SystemClock.sleep(300)
}
}
private fun scrollUp(steps: Int = 1) {
val centerX = device.displayWidth / 2
val startY = (device.displayHeight * 0.35).toInt()
val endY = (device.displayHeight * 0.75).toInt()
repeat(steps) {
device.swipe(centerX, startY, centerX, endY, 24)
device.waitForIdle()
SystemClock.sleep(300)
}
}
}
@@ -85,6 +85,7 @@ data class TeamDto(
@Json(name = "phone_download_enabled") val phoneDownloadEnabled: Boolean? = false,
@Json(name = "billing_url") val billingUrl: String? = null,
@Json(name = "staff_manage_url") val staffManageUrl: String? = null,
@Json(name = "custom_cover_enabled") val customCoverEnabled: Boolean? = false,
@Json(name = "logo_url") val logoUrl: String? = null,
@Json(name = "primary_color") val primaryColor: String? = null,
@Json(name = "secondary_color") val secondaryColor: String? = null,
@@ -111,6 +112,7 @@ data class TeamDto(
phoneDownloadEnabled = phoneDownloadEnabled ?: false,
billingUrl = billingUrl,
staffManageUrl = staffManageUrl,
customCoverEnabled = customCoverEnabled ?: false,
)
}
@@ -140,6 +142,9 @@ data class MatchDto(
@Json(name = "home_logo_url") val homeLogoUrl: String? = null,
@Json(name = "opponent_primary_color") val opponentPrimaryColor: String? = null,
@Json(name = "opponent_logo_url") val opponentLogoUrl: String? = null,
@Json(name = "effective_cover_url") val effectiveCoverUrl: String? = null,
@Json(name = "cover_source") val coverSource: String? = null,
@Json(name = "custom_cover_enabled") val customCoverEnabled: Boolean? = null,
) {
fun toDomain() = Match(
id = id,
@@ -165,6 +170,9 @@ data class MatchDto(
homeLogoUrl = homeLogoUrl,
opponentPrimaryColor = opponentPrimaryColor,
opponentLogoUrl = opponentLogoUrl,
effectiveCoverUrl = effectiveCoverUrl,
coverSource = coverSource ?: "default",
customCoverEnabled = customCoverEnabled ?: false,
)
}
@@ -91,6 +91,8 @@ interface MatchLiveApi {
@Part("match[scoring_rules][points_deciding_set]") pointsDecidingSet: okhttp3.RequestBody?,
@Part("match[scoring_rules][min_point_lead]") minPointLead: okhttp3.RequestBody?,
@Part opponentLogoFile: MultipartBody.Part?,
@Part coverImage: MultipartBody.Part?,
@Part("remove_cover") removeCover: okhttp3.RequestBody?,
): MatchDto
@DELETE("matches/{matchId}")
@@ -122,6 +122,8 @@ class MatchRepository(
sportKey: String? = null,
overlayKind: String? = null,
opponentLogoUri: Uri? = null,
coverImageUri: Uri? = null,
removeCover: Boolean = false,
): Match {
val body = UpdateMatchBodyFull(
opponentName = opponentName,
@@ -134,7 +136,7 @@ class MatchRepository(
opponentPrimaryColor = opponentPrimaryColor,
scoringRules = scoringRules?.toMap().takeIf { !it.isNullOrEmpty() },
)
if (opponentLogoUri != null) {
if (opponentLogoUri != null || coverImageUri != null || removeCover) {
return api.updateMatchMultipart(
matchId = matchId,
opponentName = MultipartBodies.textPart(opponentName),
@@ -146,7 +148,13 @@ class MatchRepository(
pointsPerSet = scoringRules?.pointsPerSet?.let { MultipartBodies.textPart(it.toString()) },
pointsDecidingSet = scoringRules?.pointsDecidingSet?.let { MultipartBodies.textPart(it.toString()) },
minPointLead = scoringRules?.minPointLead?.let { MultipartBodies.textPart(it.toString()) },
opponentLogoFile = MultipartBodies.logoPart(appContext, opponentLogoUri, "opponent_logo_file"),
opponentLogoFile = opponentLogoUri?.let {
MultipartBodies.logoPart(appContext, it, "opponent_logo_file")
},
coverImage = coverImageUri?.let {
MultipartBodies.logoPart(appContext, it, "cover_image")
},
removeCover = if (removeCover) MultipartBodies.textPart("1") else null,
).toDomain()
}
return api.updateMatch(
@@ -43,6 +43,7 @@ data class Team(
val phoneDownloadEnabled: Boolean = false,
val billingUrl: String? = null,
val staffManageUrl: String? = null,
val customCoverEnabled: Boolean = false,
) {
val canUseYoutube: Boolean get() = youtubeEnabled
val isYoutubeReady: Boolean get() = youtubeSelectable
@@ -100,6 +101,9 @@ data class Match(
val homeLogoUrl: String? = null,
val opponentPrimaryColor: String? = null,
val opponentLogoUrl: String? = null,
val effectiveCoverUrl: String? = null,
val coverSource: String = "default",
val customCoverEnabled: Boolean = false,
) {
val hasActiveSession: Boolean get() = activeSessionId != null
@@ -123,7 +123,7 @@ fun BroadcastControlsOverlay(
onSelectMinQuality: (String) -> Unit = {},
modifier: Modifier = Modifier,
) {
var showTerminateConfirm by remember { mutableStateOf(false) }
var pendingConfirm by remember { mutableStateOf<SideConfirmAction?>(null) }
var showMinQualityPicker by remember { mutableStateOf(false) }
val autoLabel = stringResource(R.string.broadcast_min_quality_auto)
@@ -140,25 +140,21 @@ fun BroadcastControlsOverlay(
)
}
if (showTerminateConfirm) {
AlertDialog(
onDismissRequest = { showTerminateConfirm = false },
containerColor = MatchColors.SurfaceElevated,
title = { Text(stringResource(R.string.broadcast_terminate_title)) },
text = { Text(stringResource(R.string.broadcast_terminate_message)) },
confirmButton = {
TextButton(
onClick = {
showTerminateConfirm = false
onTerminate()
},
) {
Text(stringResource(R.string.broadcast_terminate_confirm), color = MatchColors.PrimaryRed)
}
},
dismissButton = {
TextButton(onClick = { showTerminateConfirm = false }) {
Text(stringResource(R.string.action_cancel), color = MatchColors.TextSecondary)
pendingConfirm?.let { action ->
SideActionConfirmDialog(
action = action,
isPaused = isPaused,
audioMuted = audioMuted,
onDismiss = { pendingConfirm = null },
onConfirm = {
pendingConfirm = null
when (action) {
SideConfirmAction.SHARE_LIVE -> onShareLive()
SideConfirmAction.SHARE_REGIA -> onShareRegia()
SideConfirmAction.ADVANCE_PERIOD -> onAdvancePeriod?.invoke()
SideConfirmAction.PAUSE_OR_RESUME -> onPauseOrResume()
SideConfirmAction.TOGGLE_MUTE -> onToggleAudioMute()
SideConfirmAction.TERMINATE -> onTerminate()
}
},
)
@@ -216,13 +212,13 @@ fun BroadcastControlsOverlay(
SideIconButton(
icon = Icons.Default.Share,
contentDescription = stringResource(R.string.broadcast_share_live_cd),
onClick = onShareLive,
onClick = { pendingConfirm = SideConfirmAction.SHARE_LIVE },
enabled = shareLiveEnabled,
)
SideIconButton(
icon = Icons.Default.Videocam,
contentDescription = stringResource(R.string.broadcast_share_regia_cd),
onClick = onShareRegia,
onClick = { pendingConfirm = SideConfirmAction.SHARE_REGIA },
)
SideIconButton(
icon = Icons.Default.Tune,
@@ -240,7 +236,7 @@ fun BroadcastControlsOverlay(
SideIconButton(
icon = Icons.Default.SkipNext,
contentDescription = stringResource(R.string.broadcast_next_period_cd),
onClick = onAdvancePeriod,
onClick = { pendingConfirm = SideConfirmAction.ADVANCE_PERIOD },
)
}
}
@@ -258,7 +254,7 @@ fun BroadcastControlsOverlay(
} else {
stringResource(R.string.broadcast_pause_cd)
},
onClick = onPauseOrResume,
onClick = { pendingConfirm = SideConfirmAction.PAUSE_OR_RESUME },
highlighted = isPaused,
)
SideIconButton(
@@ -268,13 +264,13 @@ fun BroadcastControlsOverlay(
} else {
stringResource(R.string.broadcast_mute_cd)
},
onClick = onToggleAudioMute,
onClick = { pendingConfirm = SideConfirmAction.TOGGLE_MUTE },
highlighted = audioMuted,
)
SideIconButton(
icon = Icons.Default.Stop,
contentDescription = stringResource(R.string.broadcast_terminate_cd),
onClick = { showTerminateConfirm = true },
onClick = { pendingConfirm = SideConfirmAction.TERMINATE },
danger = true,
)
}
@@ -770,6 +766,94 @@ private fun MinQualityOptionChip(
}
}
@Composable
private fun SideActionConfirmDialog(
action: SideConfirmAction,
isPaused: Boolean,
audioMuted: Boolean,
onDismiss: () -> Unit,
onConfirm: () -> Unit,
) {
val title: String
val message: String
val confirmLabel: String
val confirmColor: Color
when (action) {
SideConfirmAction.SHARE_LIVE -> {
title = stringResource(R.string.broadcast_share_live_title)
message = stringResource(R.string.broadcast_share_live_message)
confirmLabel = stringResource(R.string.action_confirm)
confirmColor = Color.White
}
SideConfirmAction.SHARE_REGIA -> {
title = stringResource(R.string.broadcast_share_regia_title)
message = stringResource(R.string.broadcast_share_regia_message)
confirmLabel = stringResource(R.string.action_confirm)
confirmColor = Color.White
}
SideConfirmAction.ADVANCE_PERIOD -> {
title = stringResource(R.string.broadcast_advance_period_title)
message = stringResource(R.string.broadcast_advance_period_message)
confirmLabel = stringResource(R.string.action_confirm)
confirmColor = Color.White
}
SideConfirmAction.PAUSE_OR_RESUME -> {
if (isPaused) {
title = stringResource(R.string.broadcast_resume_title)
message = stringResource(R.string.broadcast_resume_message)
} else {
title = stringResource(R.string.broadcast_pause_title)
message = stringResource(R.string.broadcast_pause_message)
}
confirmLabel = stringResource(R.string.action_confirm)
confirmColor = Color.White
}
SideConfirmAction.TOGGLE_MUTE -> {
if (audioMuted) {
title = stringResource(R.string.broadcast_unmute_title)
message = stringResource(R.string.broadcast_unmute_message)
} else {
title = stringResource(R.string.broadcast_mute_title)
message = stringResource(R.string.broadcast_mute_message)
}
confirmLabel = stringResource(R.string.action_confirm)
confirmColor = Color.White
}
SideConfirmAction.TERMINATE -> {
title = stringResource(R.string.broadcast_terminate_title)
message = stringResource(R.string.broadcast_terminate_message)
confirmLabel = stringResource(R.string.broadcast_terminate_confirm)
confirmColor = MatchColors.PrimaryRed
}
}
AlertDialog(
onDismissRequest = onDismiss,
containerColor = MatchColors.SurfaceElevated,
title = { Text(title) },
text = { Text(message) },
confirmButton = {
TextButton(onClick = onConfirm) {
Text(confirmLabel, color = confirmColor)
}
},
dismissButton = {
TextButton(onClick = onDismiss) {
Text(stringResource(R.string.action_cancel), color = MatchColors.TextSecondary)
}
},
)
}
private enum class SideConfirmAction {
SHARE_LIVE,
SHARE_REGIA,
ADVANCE_PERIOD,
PAUSE_OR_RESUME,
TOGGLE_MUTE,
TERMINATE,
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SideIconButton(
@@ -14,6 +14,7 @@ import kotlin.coroutines.resume
enum class ScoreDialogKind {
SET_WON,
CLOSE_SET,
CLOSE_SET_ANYWAY,
MATCH_WON,
}
@@ -78,6 +79,9 @@ fun ScoreDialogRouter(
onDismiss = host::resolve,
)
}
ScoreDialogKind.CLOSE_SET -> {
CloseSetConfirmDialog(onDismiss = host::resolve)
}
ScoreDialogKind.CLOSE_SET_ANYWAY -> {
CloseSetAnywayDialog(onDismiss = host::resolve)
}
@@ -136,10 +140,16 @@ class LiveScoreActions(
awayPoints = score.awayPoints,
currentSet = score.currentSet,
)
if (winner == null) {
val ok = dialogHost.show(ScoreDialogState(kind = ScoreDialogKind.CLOSE_SET_ANYWAY))
if (!ok) return
}
val ok = dialogHost.show(
ScoreDialogState(
kind = if (winner == null) {
ScoreDialogKind.CLOSE_SET_ANYWAY
} else {
ScoreDialogKind.CLOSE_SET
},
),
)
if (!ok) return
scoreController.closeSet()
afterCloseSet(onStopStream)
}
@@ -38,6 +38,28 @@ fun SetWonDialog(
)
}
@Composable
fun CloseSetConfirmDialog(onDismiss: (confirmed: Boolean) -> Unit) {
AlertDialog(
onDismissRequest = { onDismiss(false) },
containerColor = MatchColors.Surface,
title = { Text(stringResource(R.string.score_action_close_set)) },
text = {
Text(stringResource(R.string.broadcast_close_set_confirm_message))
},
confirmButton = {
FilledTonalButton(onClick = { onDismiss(true) }) {
Text(stringResource(R.string.score_action_close_set), color = Color.Black)
}
},
dismissButton = {
TextButton(onClick = { onDismiss(false) }) {
Text(stringResource(R.string.action_cancel))
}
},
)
}
@Composable
fun CloseSetAnywayDialog(onDismiss: (confirmed: Boolean) -> Unit) {
AlertDialog(
@@ -0,0 +1,105 @@
package com.matchlivetv.match_live_tv.ui.wizard
import android.net.Uri
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.matchlivetv.match_live_tv.R
import com.matchlivetv.match_live_tv.core.resolveMediaUrl
import com.matchlivetv.match_live_tv.ui.components.MatchPrimaryButton
import com.matchlivetv.match_live_tv.ui.components.MatchSecondaryButton
import com.matchlivetv.match_live_tv.ui.theme.MatchColors
@Composable
fun coverSourceLabel(source: String): String = when (source) {
"match" -> stringResource(R.string.wizard_match_cover_source_match)
"team" -> stringResource(R.string.wizard_match_cover_source_team)
"club" -> stringResource(R.string.wizard_match_cover_source_club)
else -> stringResource(R.string.wizard_match_cover_source_default)
}
@Composable
fun MatchCoverSection(
effectiveCoverUrl: String?,
coverSource: String,
customCoverEnabled: Boolean,
localCoverUri: Uri?,
hasMatchOverride: Boolean,
onPickCover: () -> Unit,
onClearOverride: () -> Unit,
modifier: Modifier = Modifier,
) {
val previewModel = localCoverUri ?: resolveMediaUrl(effectiveCoverUrl)
Column(modifier.fillMaxWidth()) {
Text(
stringResource(R.string.wizard_match_cover_title),
style = MaterialTheme.typography.labelLarge,
color = MatchColors.TextSecondary,
)
Text(
stringResource(R.string.wizard_match_cover_source_label, coverSourceLabel(coverSource)),
style = MaterialTheme.typography.bodyMedium,
color = MatchColors.TextSecondary,
modifier = Modifier.padding(top = 4.dp),
)
Box(
Modifier
.fillMaxWidth()
.padding(top = 12.dp)
.aspectRatio(16f / 9f)
.clip(RoundedCornerShape(12.dp))
.background(MatchColors.Surface),
) {
if (previewModel != null) {
AsyncImage(
model = previewModel,
contentDescription = stringResource(R.string.wizard_match_cover_preview_cd),
modifier = Modifier.fillMaxWidth(),
contentScale = ContentScale.Crop,
)
}
}
Text(
stringResource(R.string.wizard_match_cover_hint),
style = MaterialTheme.typography.bodyMedium,
color = MatchColors.TextSecondary,
modifier = Modifier.padding(top = 8.dp),
)
if (customCoverEnabled) {
MatchPrimaryButton(
label = stringResource(R.string.wizard_match_cover_change),
onClick = onPickCover,
modifier = Modifier.fillMaxWidth().padding(top = 12.dp),
)
if (hasMatchOverride || localCoverUri != null) {
MatchSecondaryButton(
label = stringResource(R.string.wizard_match_cover_reset),
onClick = onClearOverride,
modifier = Modifier.fillMaxWidth().padding(top = 8.dp),
)
}
} else {
Text(
stringResource(R.string.wizard_match_cover_premium_required),
style = MaterialTheme.typography.bodyMedium,
color = MatchColors.TextSecondary,
modifier = Modifier.padding(top = 12.dp),
)
}
}
}
@@ -105,6 +105,11 @@ fun StepMatchScreen(
}
var homeLogoUri by remember { mutableStateOf<Uri?>(null) }
var opponentLogoUri by remember { mutableStateOf<Uri?>(null) }
var coverImageUri by remember { mutableStateOf<Uri?>(null) }
var removeCover by remember { mutableStateOf(false) }
var effectiveCoverUrl by remember { mutableStateOf(match.effectiveCoverUrl) }
var coverSource by remember { mutableStateOf(match.coverSource) }
var customCoverEnabled by remember { mutableStateOf(match.customCoverEnabled) }
LaunchedEffect(match.teamId) {
runCatching { container.matchRepository.fetchTeam(match.teamId) }
@@ -113,10 +118,20 @@ fun StepMatchScreen(
if (team != null) {
homePrimaryColor = normalizeHexColor(team.primaryColor ?: match.homePrimaryColor)
homeLogoUrl = team.logoUrl ?: match.homeLogoUrl
if (!match.customCoverEnabled) {
customCoverEnabled = team.customCoverEnabled
}
}
}
}
val pickCover = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia(),
) { uri ->
coverImageUri = uri
removeCover = false
}
val pickHomeLogo = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia(),
) { uri -> homeLogoUri = uri }
@@ -230,6 +245,24 @@ fun StepMatchScreen(
onClearLogo = { opponentLogoUri = null },
)
Spacer(Modifier.height(16.dp))
MatchCoverSection(
effectiveCoverUrl = effectiveCoverUrl,
coverSource = when {
coverImageUri != null -> "match"
else -> coverSource
},
customCoverEnabled = customCoverEnabled,
localCoverUri = coverImageUri,
hasMatchOverride = match.coverSource == "match",
onPickCover = {
pickCover.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
},
onClearOverride = {
coverImageUri = null
removeCover = true
},
)
Spacer(Modifier.height(16.dp))
MatchOutlinedField(
value = location,
onValueChange = { location = it },
@@ -500,9 +533,13 @@ fun StepMatchScreen(
""
},
opponentLogoUri = opponentLogoUri,
coverImageUri = coverImageUri,
removeCover = removeCover,
)
}.onSuccess { updated ->
container.wizardSession.match = updated
effectiveCoverUrl = updated.effectiveCoverUrl
coverSource = updated.coverSource
onNext()
}.onFailure {
onError(it.message ?: saveGenericError)
@@ -12,6 +12,7 @@
<string name="action_logout">Abmelden</string>
<string name="action_login">Anmelden</string>
<string name="action_cancel">Abbrechen</string>
<string name="action_confirm">Bestätigen</string>
<string name="action_save">Speichern</string>
<string name="login_email">E-Mail</string>
<string name="login_password">Passwort</string>
@@ -64,6 +65,17 @@
<string name="wizard_match_location_label">Ort</string>
<string name="wizard_match_category_label">Liga (optional)</string>
<string name="wizard_match_category_hint">Z. B. Serie C, Sommerturnier — wird in Beschreibung und Overlay verwendet.</string>
<string name="wizard_match_cover_title">Pausenbild</string>
<string name="wizard_match_cover_source_label">Quelle: %1$s</string>
<string name="wizard_match_cover_source_default">Match Live TV</string>
<string name="wizard_match_cover_source_club">Verein</string>
<string name="wizard_match_cover_source_team">Team</string>
<string name="wizard_match_cover_source_match">Dieses Spiel</string>
<string name="wizard_match_cover_hint">Wird bei Pause oder ohne Signal angezeigt, bis der Stream weitergeht.</string>
<string name="wizard_match_cover_change">Bild für dieses Spiel ändern</string>
<string name="wizard_match_cover_reset">Standardbild verwenden</string>
<string name="wizard_match_cover_premium_required">Individuelles Sponsor-Bild mit Premium Full</string>
<string name="wizard_match_cover_preview_cd">Bildvorschau</string>
<string name="wizard_match_scheduled_label">Geplant für</string>
<string name="wizard_match_custom_overlay_label">Individuelles Video-Overlay</string>
<string name="wizard_match_custom_rules_label">Individuelle Punkteregeln</string>
@@ -161,6 +173,21 @@
<string name="broadcast_terminate_title">Livestream beenden?</string>
<string name="broadcast_terminate_message">Der Stream wird für alle Zuschauer beendet.</string>
<string name="broadcast_terminate_confirm">BEENDEN</string>
<string name="broadcast_pause_title">Livestream pausieren?</string>
<string name="broadcast_pause_message">Das Cover bleibt on air, bis du fortsetzt.</string>
<string name="broadcast_resume_title">Livestream fortsetzen?</string>
<string name="broadcast_resume_message">Die Kamera geht wieder on air statt des Covers.</string>
<string name="broadcast_mute_title">Audio stummschalten?</string>
<string name="broadcast_mute_message">Das Mikrofon wird nicht mehr an den Stream gesendet, bis du es wieder aktivierst.</string>
<string name="broadcast_unmute_title">Audio wieder aktivieren?</string>
<string name="broadcast_unmute_message">Das Mikrofon ist wieder aktiv im Stream.</string>
<string name="broadcast_advance_period_title">Zum nächsten Abschnitt wechseln?</string>
<string name="broadcast_advance_period_message">Die Anzeigetafel wechselt zum nächsten Abschnitt und der aktuelle Stand wird gespeichert.</string>
<string name="broadcast_share_live_title">Livestream teilen?</string>
<string name="broadcast_share_live_message">Es öffnet sich das Teilen-Menü mit dem öffentlichen Live-Link.</string>
<string name="broadcast_share_regia_title">Regie-Link teilen?</string>
<string name="broadcast_share_regia_message">Es öffnet sich das Teilen-Menü mit dem Link zur Fernsteuerung des Spielstands.</string>
<string name="broadcast_close_set_confirm_message">Bestätigst du das Beenden des aktuellen Satzes?</string>
<string name="broadcast_hide_controls_cd">Steuerung ausblenden</string>
<string name="broadcast_show_controls_cd">Steuerung einblenden</string>
<string name="broadcast_share_live_cd">Livestream teilen</string>
@@ -12,6 +12,7 @@
<string name="action_logout">Log out</string>
<string name="action_login">Log in</string>
<string name="action_cancel">Cancel</string>
<string name="action_confirm">Confirm</string>
<string name="action_save">Save</string>
<string name="login_email">Email</string>
<string name="login_password">Password</string>
@@ -64,6 +65,17 @@
<string name="wizard_match_location_label">Location</string>
<string name="wizard_match_category_label">Category (optional)</string>
<string name="wizard_match_category_hint">E.g. Serie C, summer tournament — we\'ll use it in the description and overlay.</string>
<string name="wizard_match_cover_title">Pause cover</string>
<string name="wizard_match_cover_source_label">Source: %1$s</string>
<string name="wizard_match_cover_source_default">Match Live TV</string>
<string name="wizard_match_cover_source_club">Club</string>
<string name="wizard_match_cover_source_team">Team</string>
<string name="wizard_match_cover_source_match">This match</string>
<string name="wizard_match_cover_hint">Shown while paused or offline until the stream resumes.</string>
<string name="wizard_match_cover_change">Change cover for this match</string>
<string name="wizard_match_cover_reset">Use default cover</string>
<string name="wizard_match_cover_premium_required">Custom sponsor cover requires Premium Full</string>
<string name="wizard_match_cover_preview_cd">Cover preview</string>
<string name="wizard_match_scheduled_label">Scheduled for</string>
<string name="wizard_match_custom_overlay_label">Custom video overlay</string>
<string name="wizard_match_custom_rules_label">Custom scoring rules</string>
@@ -161,6 +173,21 @@
<string name="broadcast_terminate_title">End the live stream?</string>
<string name="broadcast_terminate_message">The stream will be closed for all viewers.</string>
<string name="broadcast_terminate_confirm">END</string>
<string name="broadcast_pause_title">Pause the live stream?</string>
<string name="broadcast_pause_message">The cover slate will stay on air until you resume.</string>
<string name="broadcast_resume_title">Resume the live stream?</string>
<string name="broadcast_resume_message">The camera will go back on air instead of the cover slate.</string>
<string name="broadcast_mute_title">Mute audio?</string>
<string name="broadcast_mute_message">The microphone will not be sent to the stream until you unmute.</string>
<string name="broadcast_unmute_title">Unmute audio?</string>
<string name="broadcast_unmute_message">The microphone will be active on the stream again.</string>
<string name="broadcast_advance_period_title">Advance to the next period?</string>
<string name="broadcast_advance_period_message">The scoreboard will move to the next period and the current period score will be saved.</string>
<string name="broadcast_share_live_title">Share the live stream?</string>
<string name="broadcast_share_live_message">This opens the share sheet with the public live link.</string>
<string name="broadcast_share_regia_title">Share the control room link?</string>
<string name="broadcast_share_regia_message">This opens the share sheet with the remote scoring link.</string>
<string name="broadcast_close_set_confirm_message">Confirm closing the current set?</string>
<string name="broadcast_hide_controls_cd">Hide controls</string>
<string name="broadcast_show_controls_cd">Show controls</string>
<string name="broadcast_share_live_cd">Share live stream</string>
@@ -12,6 +12,7 @@
<string name="action_logout">Salir</string>
<string name="action_login">Acceder</string>
<string name="action_cancel">Cancelar</string>
<string name="action_confirm">Confirmar</string>
<string name="action_save">Guardar</string>
<string name="login_email">Email</string>
<string name="login_password">Contraseña</string>
@@ -64,6 +65,17 @@
<string name="wizard_match_location_label">Lugar</string>
<string name="wizard_match_category_label">Categoría (opcional)</string>
<string name="wizard_match_category_hint">Ej. Serie C, torneo de verano — lo usaremos en la descripción y el overlay.</string>
<string name="wizard_match_cover_title">Imagen de pausa</string>
<string name="wizard_match_cover_source_label">Origen: %1$s</string>
<string name="wizard_match_cover_source_default">Match Live TV</string>
<string name="wizard_match_cover_source_club">Club</string>
<string name="wizard_match_cover_source_team">Equipo</string>
<string name="wizard_match_cover_source_match">Este partido</string>
<string name="wizard_match_cover_hint">Se muestra en pausa o sin señal hasta que retome la transmisión.</string>
<string name="wizard_match_cover_change">Cambiar imagen para este partido</string>
<string name="wizard_match_cover_reset">Usar imagen predeterminada</string>
<string name="wizard_match_cover_premium_required">Imagen de patrocinio personalizada con Premium Full</string>
<string name="wizard_match_cover_preview_cd">Vista previa de la imagen</string>
<string name="wizard_match_scheduled_label">Programado para</string>
<string name="wizard_match_custom_overlay_label">Overlay de vídeo personalizado</string>
<string name="wizard_match_custom_rules_label">Reglas de puntuación personalizadas</string>
@@ -161,6 +173,21 @@
<string name="broadcast_terminate_title">¿Terminar el directo?</string>
<string name="broadcast_terminate_message">El streaming se cerrará para todos los espectadores.</string>
<string name="broadcast_terminate_confirm">TERMINAR</string>
<string name="broadcast_pause_title">¿Pausar el directo?</string>
<string name="broadcast_pause_message">La portada seguirá en antena hasta que lo reanudes.</string>
<string name="broadcast_resume_title">¿Reanudar el directo?</string>
<string name="broadcast_resume_message">La cámara volverá a antena en lugar de la portada.</string>
<string name="broadcast_mute_title">¿Silenciar el audio?</string>
<string name="broadcast_mute_message">El micrófono no se enviará al stream hasta que lo reactives.</string>
<string name="broadcast_unmute_title">¿Reactivar el audio?</string>
<string name="broadcast_unmute_message">El micrófono volverá a estar activo en el stream.</string>
<string name="broadcast_advance_period_title">¿Pasar al periodo siguiente?</string>
<string name="broadcast_advance_period_message">El marcador pasará al siguiente periodo y se guardará el marcador del periodo actual.</string>
<string name="broadcast_share_live_title">¿Compartir el directo?</string>
<string name="broadcast_share_live_message">Se abrirá el menú de compartir con el enlace público del directo.</string>
<string name="broadcast_share_regia_title">¿Compartir el enlace de regie?</string>
<string name="broadcast_share_regia_message">Se abrirá el menú de compartir con el enlace para gestionar el marcador a distancia.</string>
<string name="broadcast_close_set_confirm_message">¿Confirmas el cierre del set actual?</string>
<string name="broadcast_hide_controls_cd">Ocultar controles</string>
<string name="broadcast_show_controls_cd">Mostrar controles</string>
<string name="broadcast_share_live_cd">Compartir directo</string>
@@ -12,6 +12,7 @@
<string name="action_logout">Déconnexion</string>
<string name="action_login">Connexion</string>
<string name="action_cancel">Annuler</string>
<string name="action_confirm">Confirmer</string>
<string name="action_save">Enregistrer</string>
<string name="login_email">E-mail</string>
<string name="login_password">Mot de passe</string>
@@ -64,6 +65,17 @@
<string name="wizard_match_location_label">Lieu</string>
<string name="wizard_match_category_label">Championnat (facultatif)</string>
<string name="wizard_match_category_hint">Ex. Serie C, tournoi d\'été — utilisé dans la description et l\'overlay.</string>
<string name="wizard_match_cover_title">Image de pause</string>
<string name="wizard_match_cover_source_label">Source : %1$s</string>
<string name="wizard_match_cover_source_default">Match Live TV</string>
<string name="wizard_match_cover_source_club">Club</string>
<string name="wizard_match_cover_source_team">Équipe</string>
<string name="wizard_match_cover_source_match">Ce match</string>
<string name="wizard_match_cover_hint">Affichée en pause ou sans signal jusqu\'à la reprise du direct.</string>
<string name="wizard_match_cover_change">Changer l\'image pour ce match</string>
<string name="wizard_match_cover_reset">Utiliser l\'image par défaut</string>
<string name="wizard_match_cover_premium_required">Image sponsor personnalisée avec Premium Full</string>
<string name="wizard_match_cover_preview_cd">Aperçu de l\'image</string>
<string name="wizard_match_scheduled_label">Programmé pour</string>
<string name="wizard_match_custom_overlay_label">Overlay vidéo personnalisé</string>
<string name="wizard_match_custom_rules_label">Règles de score personnalisées</string>
@@ -161,6 +173,21 @@
<string name="broadcast_terminate_title">Terminer le direct ?</string>
<string name="broadcast_terminate_message">Le streaming sera fermé pour tous les spectateurs.</string>
<string name="broadcast_terminate_confirm">TERMINER</string>
<string name="broadcast_pause_title">Mettre le direct en pause ?</string>
<string name="broadcast_pause_message">La couverture restera à l\'antenne jusqu\'à la reprise.</string>
<string name="broadcast_resume_title">Reprendre le direct ?</string>
<string name="broadcast_resume_message">La caméra reviendra à l\'antenne à la place de la couverture.</string>
<string name="broadcast_mute_title">Couper l\'audio ?</string>
<string name="broadcast_mute_message">Le micro ne sera plus envoyé au flux tant que vous ne le réactivez pas.</string>
<string name="broadcast_unmute_title">Réactiver l\'audio ?</string>
<string name="broadcast_unmute_message">Le micro sera à nouveau actif sur le flux.</string>
<string name="broadcast_advance_period_title">Passer à la période suivante ?</string>
<string name="broadcast_advance_period_message">Le tableau passera à la période suivante et le score de la période en cours sera enregistré.</string>
<string name="broadcast_share_live_title">Partager le direct ?</string>
<string name="broadcast_share_live_message">Cela ouvre le menu de partage avec le lien public du direct.</string>
<string name="broadcast_share_regia_title">Partager le lien régie ?</string>
<string name="broadcast_share_regia_message">Cela ouvre le menu de partage avec le lien de scoring distant.</string>
<string name="broadcast_close_set_confirm_message">Confirmez la clôture du set en cours ?</string>
<string name="broadcast_hide_controls_cd">Masquer les commandes</string>
<string name="broadcast_show_controls_cd">Afficher les commandes</string>
<string name="broadcast_share_live_cd">Partager le direct</string>
@@ -13,6 +13,7 @@
<string name="action_logout">Esci</string>
<string name="action_login">Accedi</string>
<string name="action_cancel">Annulla</string>
<string name="action_confirm">Conferma</string>
<string name="action_save">Salva</string>
<string name="login_email">Email</string>
<string name="login_password">Password</string>
@@ -65,6 +66,17 @@
<string name="wizard_match_location_label">Luogo</string>
<string name="wizard_match_category_label">Campionato (facoltativo)</string>
<string name="wizard_match_category_hint">Es. Serie C, torneo estivo — lo useremo in descrizione e overlay.</string>
<string name="wizard_match_cover_title">Copertina in pausa</string>
<string name="wizard_match_cover_source_label">Origine: %1$s</string>
<string name="wizard_match_cover_source_default">Match Live TV</string>
<string name="wizard_match_cover_source_club">Società</string>
<string name="wizard_match_cover_source_team">Squadra</string>
<string name="wizard_match_cover_source_match">Questa partita</string>
<string name="wizard_match_cover_hint">Mostrata in pausa o senza segnale finché non riparte la diretta.</string>
<string name="wizard_match_cover_change">Cambia copertina per questa partita</string>
<string name="wizard_match_cover_reset">Usa quella predefinita</string>
<string name="wizard_match_cover_premium_required">Copertina sponsor personalizzata con Premium Full</string>
<string name="wizard_match_cover_preview_cd">Anteprima copertina</string>
<string name="wizard_match_scheduled_label">Programmata per</string>
<string name="wizard_match_custom_overlay_label">Overlay video personalizzato</string>
<string name="wizard_match_custom_rules_label">Regole punteggio personalizzate</string>
@@ -162,6 +174,21 @@
<string name="broadcast_terminate_title">Terminare la diretta?</string>
<string name="broadcast_terminate_message">Lo streaming verrà chiuso per tutti gli spettatori.</string>
<string name="broadcast_terminate_confirm">TERMINA</string>
<string name="broadcast_pause_title">Mettere in pausa?</string>
<string name="broadcast_pause_message">La diretta passerà alla copertina finché non la riprendi.</string>
<string name="broadcast_resume_title">Riprendere la diretta?</string>
<string name="broadcast_resume_message">La telecamera tornerà in onda al posto della copertina.</string>
<string name="broadcast_mute_title">Silenziare l\'audio?</string>
<string name="broadcast_mute_message">Il microfono non verrà inviato allo stream finché non lo riattivi.</string>
<string name="broadcast_unmute_title">Riattivare l\'audio?</string>
<string name="broadcast_unmute_message">Il microfono tornerà attivo sullo stream.</string>
<string name="broadcast_advance_period_title">Passare al periodo successivo?</string>
<string name="broadcast_advance_period_message">Il tabellone passerà al periodo successivo e il punteggio del periodo corrente sarà salvato.</string>
<string name="broadcast_share_live_title">Condividere la diretta?</string>
<string name="broadcast_share_live_message">Aprirai il menu di condivisione con il link pubblico della diretta.</string>
<string name="broadcast_share_regia_title">Condividere il link regia?</string>
<string name="broadcast_share_regia_message">Aprirai il menu di condivisione con il link per gestire il punteggio da remoto.</string>
<string name="broadcast_close_set_confirm_message">Confermi la chiusura del set corrente?</string>
<string name="broadcast_hide_controls_cd">Nascondi controlli</string>
<string name="broadcast_show_controls_cd">Mostra controlli</string>
<string name="broadcast_share_live_cd">Condividi diretta</string>
@@ -57,6 +57,7 @@
713E0129656649FC8630FDC6 /* LivePreviewView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46CE696CAB994E2C8E399776 /* LivePreviewView.swift */; };
7575030B9AEB4DEBAD986A23 /* MatchColors.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2996990D08341ABA52BE287 /* MatchColors.swift */; };
777B73E69F8A4DC6A8E7C1DF /* StepMatchScreen.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAB037B1369B454D84F6850D /* StepMatchScreen.swift */; };
A1B2C3D4E5F60718293A4B5D /* MatchCoverSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2C3D4E5F60718293A4B5D6E /* MatchCoverSection.swift */; };
8723E1F8443A46B3AF49E8A3 /* ScoreState.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA08E23008964D02AB59377E /* ScoreState.swift */; };
8C8FEABCD83C422BA5A5DEA3 /* MatchLiveTv/Resources/de.lproj in Resources */ = {isa = PBXBuildFile; fileRef = EEFE07D4B6FD44199A5B9C25 /* MatchLiveTv/Resources/de.lproj */; };
9391C9EA0B834DC8956483DF /* ActionCableClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 98526C26B2584F55AADF0FFF /* ActionCableClient.swift */; };
@@ -194,6 +195,7 @@
E860A0E35362427DA84F8972 /* BroadcastControlsOverlay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = BroadcastControlsOverlay.swift; path = MatchLiveTv/UI/Broadcast/BroadcastControlsOverlay.swift; sourceTree = "<group>"; };
EA08E23008964D02AB59377E /* ScoreState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = ScoreState.swift; path = MatchLiveTv/Domain/ScoreState.swift; sourceTree = "<group>"; };
EAB037B1369B454D84F6850D /* StepMatchScreen.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = StepMatchScreen.swift; path = MatchLiveTv/UI/Wizard/StepMatchScreen.swift; sourceTree = "<group>"; };
B2C3D4E5F60718293A4B5D6E /* MatchCoverSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = MatchCoverSection.swift; path = MatchLiveTv/UI/Wizard/MatchCoverSection.swift; sourceTree = "<group>"; };
EE0A49E8D59947448DAA7851 /* AuthRepository.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AuthRepository.swift; path = MatchLiveTv/Data/Repository/AuthRepository.swift; sourceTree = "<group>"; };
EEFE07D4B6FD44199A5B9C25 /* MatchLiveTv/Resources/de.lproj */ = {isa = PBXFileReference; lastKnownFileType = folder; path = MatchLiveTv/Resources/de.lproj; sourceTree = "<group>"; };
F438E7E164F44C7B856C4808 /* LiveBroadcastCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = LiveBroadcastCoordinator.swift; path = MatchLiveTv/Streaming/LiveBroadcastCoordinator.swift; sourceTree = "<group>"; };
@@ -324,6 +326,7 @@
2B5C00419D09442FA8ED60F3 /* ShareSheet.swift */,
D2996990D08341ABA52BE287 /* MatchColors.swift */,
EAB037B1369B454D84F6850D /* StepMatchScreen.swift */,
B2C3D4E5F60718293A4B5D6E /* MatchCoverSection.swift */,
1079231B9A4E446AA9AD6C0A /* StepNetworkTestScreen.swift */,
7EC0179FE6BC4323B1F9E1D3 /* StepTransmissionScreen.swift */,
6FBBE0F1399840FFA0E7EF2E /* TeamBrandingEditor.swift */,
@@ -502,6 +505,7 @@
1A82C6F343F54284AFA8FECE /* ShareSheet.swift in Sources */,
7575030B9AEB4DEBAD986A23 /* MatchColors.swift in Sources */,
777B73E69F8A4DC6A8E7C1DF /* StepMatchScreen.swift in Sources */,
A1B2C3D4E5F60718293A4B5D /* MatchCoverSection.swift in Sources */,
F67C0C88237F41DE8EDF6CB8 /* StepNetworkTestScreen.swift in Sources */,
2B8E5D9945364094B74165DE /* StepTransmissionScreen.swift in Sources */,
45776A6A76D04EF5A0C0D187 /* TeamBrandingEditor.swift in Sources */,
@@ -74,6 +74,7 @@ enum L10n {
private static let table: [String: [String: String]] = [
"it": [
"action.cancel": "Annulla",
"action.confirm": "Conferma",
"action.delete": "Elimina",
"action.exit": "Esci",
"action.login": "Accedi",
@@ -174,6 +175,21 @@ enum L10n {
"broadcast.terminate.confirm": "TERMINA",
"broadcast.terminate.message": "Lo streaming verrà chiuso per tutti gli spettatori.",
"broadcast.terminate.title": "Terminare la diretta?",
"broadcast.pause.title": "Mettere in pausa?",
"broadcast.pause.message": "La diretta passerà alla copertina finché non la riprendi.",
"broadcast.resume.title": "Riprendere la diretta?",
"broadcast.resume.message": "La telecamera tornerà in onda al posto della copertina.",
"broadcast.mute.title": "Silenziare l'audio?",
"broadcast.mute.message": "Il microfono non verrà inviato allo stream finché non lo riattivi.",
"broadcast.unmute.title": "Riattivare l'audio?",
"broadcast.unmute.message": "Il microfono tornerà attivo sullo stream.",
"broadcast.advance.period.title": "Passare al periodo successivo?",
"broadcast.advance.period.message": "Il tabellone passerà al periodo successivo e il punteggio del periodo corrente sarà salvato.",
"broadcast.share.live.title": "Condividere la diretta?",
"broadcast.share.live.message": "Aprirai il menu di condivisione con il link pubblico della diretta.",
"broadcast.share.regia.title": "Condividere il link regia?",
"broadcast.share.regia.message": "Aprirai il menu di condivisione con il link per gestire il punteggio da remoto.",
"broadcast.close.set.confirm.message": "Confermi la chiusura del set corrente?",
"broadcast.tooltip.add.point": "Aggiungi punto %1$@",
"broadcast.tooltip.plus.side": "+%1$d %2$@",
"broadcast.tooltip.remove.point": "Togli punto %1$@",
@@ -323,6 +339,16 @@ enum L10n {
"wizard.error.youtube.unavailable": "YouTube non disponibile per questa squadra",
"wizard.match.away.team.label": "Squadra avversaria",
"wizard.match.category.hint": "Es. Serie C, torneo estivo — lo useremo in descrizione e overlay.",
"wizard.match.cover.title": "Copertina in pausa",
"wizard.match.cover.source.label": "Origine: %1$@",
"wizard.match.cover.source.default": "Match Live TV",
"wizard.match.cover.source.club": "Società",
"wizard.match.cover.source.team": "Squadra",
"wizard.match.cover.source.match": "Questa partita",
"wizard.match.cover.hint": "Mostrata in pausa o senza segnale finché non riparte la diretta.",
"wizard.match.cover.change": "Cambia copertina per questa partita",
"wizard.match.cover.reset": "Usa quella predefinita",
"wizard.match.cover.premium.required": "Copertina sponsor personalizzata con Premium Full",
"wizard.match.category.label": "Campionato (facoltativo)",
"wizard.match.custom.overlay.label": "Overlay video personalizzato",
"wizard.match.custom.rules.label": "Regole punteggio personalizzate",
@@ -379,6 +405,7 @@ enum L10n {
],
"en": [
"action.cancel": "Cancel",
"action.confirm": "Confirm",
"action.delete": "Delete",
"action.exit": "Exit",
"action.login": "Log in",
@@ -479,6 +506,21 @@ enum L10n {
"broadcast.terminate.confirm": "END",
"broadcast.terminate.message": "The stream will be closed for all viewers.",
"broadcast.terminate.title": "End the live stream?",
"broadcast.pause.title": "Pause the live stream?",
"broadcast.pause.message": "The cover slate will stay on air until you resume.",
"broadcast.resume.title": "Resume the live stream?",
"broadcast.resume.message": "The camera will go back on air instead of the cover slate.",
"broadcast.mute.title": "Mute audio?",
"broadcast.mute.message": "The microphone will not be sent to the stream until you unmute.",
"broadcast.unmute.title": "Unmute audio?",
"broadcast.unmute.message": "The microphone will be active on the stream again.",
"broadcast.advance.period.title": "Advance to the next period?",
"broadcast.advance.period.message": "The scoreboard will move to the next period and the current period score will be saved.",
"broadcast.share.live.title": "Share the live stream?",
"broadcast.share.live.message": "This opens the share sheet with the public live link.",
"broadcast.share.regia.title": "Share the control room link?",
"broadcast.share.regia.message": "This opens the share sheet with the remote scoring link.",
"broadcast.close.set.confirm.message": "Confirm closing the current set?",
"broadcast.tooltip.add.point": "Add point %1$@",
"broadcast.tooltip.plus.side": "+%1$d %2$@",
"broadcast.tooltip.remove.point": "Remove point %1$@",
@@ -628,6 +670,16 @@ enum L10n {
"wizard.error.youtube.unavailable": "YouTube not available for this team",
"wizard.match.away.team.label": "Away team",
"wizard.match.category.hint": "E.g. Serie C, summer tournament — we'll use it in the description and overlay.",
"wizard.match.cover.title": "Pause cover",
"wizard.match.cover.source.label": "Source: %1$@",
"wizard.match.cover.source.default": "Match Live TV",
"wizard.match.cover.source.club": "Club",
"wizard.match.cover.source.team": "Team",
"wizard.match.cover.source.match": "This match",
"wizard.match.cover.hint": "Shown while paused or offline until the stream resumes.",
"wizard.match.cover.change": "Change cover for this match",
"wizard.match.cover.reset": "Use default cover",
"wizard.match.cover.premium.required": "Custom sponsor cover requires Premium Full",
"wizard.match.category.label": "Category (optional)",
"wizard.match.custom.overlay.label": "Custom video overlay",
"wizard.match.custom.rules.label": "Custom scoring rules",
@@ -684,6 +736,7 @@ enum L10n {
],
"fr": [
"action.cancel": "Annuler",
"action.confirm": "Confirmer",
"action.delete": "Supprimer",
"action.exit": "Quitter",
"action.login": "Connexion",
@@ -784,6 +837,21 @@ enum L10n {
"broadcast.terminate.confirm": "TERMINER",
"broadcast.terminate.message": "Le streaming sera fermé pour tous les spectateurs.",
"broadcast.terminate.title": "Terminer le direct ?",
"broadcast.pause.title": "Mettre le direct en pause ?",
"broadcast.pause.message": "La couverture restera à l'antenne jusqu'à la reprise.",
"broadcast.resume.title": "Reprendre le direct ?",
"broadcast.resume.message": "La caméra reviendra à l'antenne à la place de la couverture.",
"broadcast.mute.title": "Couper l'audio ?",
"broadcast.mute.message": "Le micro ne sera plus envoyé au flux tant que vous ne le réactivez pas.",
"broadcast.unmute.title": "Réactiver l'audio ?",
"broadcast.unmute.message": "Le micro sera à nouveau actif sur le flux.",
"broadcast.advance.period.title": "Passer à la période suivante ?",
"broadcast.advance.period.message": "Le tableau passera à la période suivante et le score de la période en cours sera enregistré.",
"broadcast.share.live.title": "Partager le direct ?",
"broadcast.share.live.message": "Cela ouvre le menu de partage avec le lien public du direct.",
"broadcast.share.regia.title": "Partager le lien régie ?",
"broadcast.share.regia.message": "Cela ouvre le menu de partage avec le lien de scoring distant.",
"broadcast.close.set.confirm.message": "Confirmez la clôture du set en cours ?",
"broadcast.tooltip.add.point": "Ajouter un point %1$@",
"broadcast.tooltip.plus.side": "+%1$d %2$@",
"broadcast.tooltip.remove.point": "Retirer un point %1$@",
@@ -933,6 +1001,16 @@ enum L10n {
"wizard.error.youtube.unavailable": "YouTube non disponible pour cette équipe",
"wizard.match.away.team.label": "Équipe adverse",
"wizard.match.category.hint": "Ex. Serie C, tournoi d'été — utilisé dans la description et l'overlay.",
"wizard.match.cover.title": "Image de pause",
"wizard.match.cover.source.label": "Source : %1$@",
"wizard.match.cover.source.default": "Match Live TV",
"wizard.match.cover.source.club": "Club",
"wizard.match.cover.source.team": "Équipe",
"wizard.match.cover.source.match": "Ce match",
"wizard.match.cover.hint": "Affichée en pause ou sans signal jusqu'à la reprise du direct.",
"wizard.match.cover.change": "Changer l'image pour ce match",
"wizard.match.cover.reset": "Utiliser l'image par défaut",
"wizard.match.cover.premium.required": "Image sponsor personnalisée avec Premium Full",
"wizard.match.category.label": "Championnat (facultatif)",
"wizard.match.custom.overlay.label": "Overlay vidéo personnalisé",
"wizard.match.custom.rules.label": "Règles de score personnalisées",
@@ -989,6 +1067,7 @@ enum L10n {
],
"de": [
"action.cancel": "Abbrechen",
"action.confirm": "Bestätigen",
"action.delete": "Löschen",
"action.exit": "Beenden",
"action.login": "Anmelden",
@@ -1089,6 +1168,21 @@ enum L10n {
"broadcast.terminate.confirm": "BEENDEN",
"broadcast.terminate.message": "Der Stream wird für alle Zuschauer beendet.",
"broadcast.terminate.title": "Livestream beenden?",
"broadcast.pause.title": "Livestream pausieren?",
"broadcast.pause.message": "Das Cover bleibt on air, bis du fortsetzt.",
"broadcast.resume.title": "Livestream fortsetzen?",
"broadcast.resume.message": "Die Kamera geht wieder on air statt des Covers.",
"broadcast.mute.title": "Audio stummschalten?",
"broadcast.mute.message": "Das Mikrofon wird nicht mehr an den Stream gesendet, bis du es wieder aktivierst.",
"broadcast.unmute.title": "Audio wieder aktivieren?",
"broadcast.unmute.message": "Das Mikrofon ist wieder aktiv im Stream.",
"broadcast.advance.period.title": "Zum nächsten Abschnitt wechseln?",
"broadcast.advance.period.message": "Die Anzeigetafel wechselt zum nächsten Abschnitt und der aktuelle Stand wird gespeichert.",
"broadcast.share.live.title": "Livestream teilen?",
"broadcast.share.live.message": "Es öffnet sich das Teilen-Menü mit dem öffentlichen Live-Link.",
"broadcast.share.regia.title": "Regie-Link teilen?",
"broadcast.share.regia.message": "Es öffnet sich das Teilen-Menü mit dem Link zur Fernsteuerung des Spielstands.",
"broadcast.close.set.confirm.message": "Bestätigst du das Beenden des aktuellen Satzes?",
"broadcast.tooltip.add.point": "Punkt hinzufügen %1$@",
"broadcast.tooltip.plus.side": "+%1$d %2$@",
"broadcast.tooltip.remove.point": "Punkt entfernen %1$@",
@@ -1238,6 +1332,16 @@ enum L10n {
"wizard.error.youtube.unavailable": "YouTube für dieses Team nicht verfügbar",
"wizard.match.away.team.label": "Gastteam",
"wizard.match.category.hint": "Z. B. Serie C, Sommerturnier — wird in Beschreibung und Overlay verwendet.",
"wizard.match.cover.title": "Pausenbild",
"wizard.match.cover.source.label": "Quelle: %1$@",
"wizard.match.cover.source.default": "Match Live TV",
"wizard.match.cover.source.club": "Verein",
"wizard.match.cover.source.team": "Team",
"wizard.match.cover.source.match": "Dieses Spiel",
"wizard.match.cover.hint": "Wird bei Pause oder ohne Signal angezeigt, bis der Stream weitergeht.",
"wizard.match.cover.change": "Bild für dieses Spiel ändern",
"wizard.match.cover.reset": "Standardbild verwenden",
"wizard.match.cover.premium.required": "Individuelles Sponsor-Bild mit Premium Full",
"wizard.match.category.label": "Liga (optional)",
"wizard.match.custom.overlay.label": "Individuelles Video-Overlay",
"wizard.match.custom.rules.label": "Individuelle Punkteregeln",
@@ -1294,6 +1398,7 @@ enum L10n {
],
"es": [
"action.cancel": "Cancelar",
"action.confirm": "Confirmar",
"action.delete": "Eliminar",
"action.exit": "Salir",
"action.login": "Acceder",
@@ -1394,6 +1499,21 @@ enum L10n {
"broadcast.terminate.confirm": "TERMINAR",
"broadcast.terminate.message": "El streaming se cerrará para todos los espectadores.",
"broadcast.terminate.title": "¿Terminar el directo?",
"broadcast.pause.title": "¿Pausar el directo?",
"broadcast.pause.message": "La portada seguirá en antena hasta que lo reanudes.",
"broadcast.resume.title": "¿Reanudar el directo?",
"broadcast.resume.message": "La cámara volverá a antena en lugar de la portada.",
"broadcast.mute.title": "¿Silenciar el audio?",
"broadcast.mute.message": "El micrófono no se enviará al stream hasta que lo reactives.",
"broadcast.unmute.title": "¿Reactivar el audio?",
"broadcast.unmute.message": "El micrófono volverá a estar activo en el stream.",
"broadcast.advance.period.title": "¿Pasar al periodo siguiente?",
"broadcast.advance.period.message": "El marcador pasará al siguiente periodo y se guardará el marcador del periodo actual.",
"broadcast.share.live.title": "¿Compartir el directo?",
"broadcast.share.live.message": "Se abrirá el menú de compartir con el enlace público del directo.",
"broadcast.share.regia.title": "¿Compartir el enlace de regie?",
"broadcast.share.regia.message": "Se abrirá el menú de compartir con el enlace para gestionar el marcador a distancia.",
"broadcast.close.set.confirm.message": "¿Confirmas el cierre del set actual?",
"broadcast.tooltip.add.point": "Añadir punto %1$@",
"broadcast.tooltip.plus.side": "+%1$d %2$@",
"broadcast.tooltip.remove.point": "Quitar punto %1$@",
@@ -1543,6 +1663,16 @@ enum L10n {
"wizard.error.youtube.unavailable": "YouTube no disponible para este equipo",
"wizard.match.away.team.label": "Equipo visitante",
"wizard.match.category.hint": "Ej. Serie C, torneo de verano — lo usaremos en la descripción y el overlay.",
"wizard.match.cover.title": "Imagen de pausa",
"wizard.match.cover.source.label": "Origen: %1$@",
"wizard.match.cover.source.default": "Match Live TV",
"wizard.match.cover.source.club": "Club",
"wizard.match.cover.source.team": "Equipo",
"wizard.match.cover.source.match": "Este partido",
"wizard.match.cover.hint": "Se muestra en pausa o sin señal hasta que retome la transmisión.",
"wizard.match.cover.change": "Cambiar imagen para este partido",
"wizard.match.cover.reset": "Usar imagen predeterminada",
"wizard.match.cover.premium.required": "Imagen de patrocinio personalizada con Premium Full",
"wizard.match.category.label": "Categoría (opcional)",
"wizard.match.custom.overlay.label": "Overlay de vídeo personalizado",
"wizard.match.custom.rules.label": "Reglas de puntuación personalizadas",
+10 -2
View File
@@ -101,6 +101,7 @@ struct TeamDto: Decodable {
let phoneDownloadEnabled: Bool?
let billingUrl: String?
let staffManageUrl: String?
let customCoverEnabled: Bool?
let logoUrl: String?
let primaryColor: String?
let secondaryColor: String?
@@ -127,7 +128,8 @@ struct TeamDto: Decodable {
recordingsEnabled: recordingsEnabled ?? false,
phoneDownloadEnabled: phoneDownloadEnabled ?? false,
billingUrl: billingUrl,
staffManageUrl: staffManageUrl
staffManageUrl: staffManageUrl,
customCoverEnabled: customCoverEnabled ?? false
)
}
}
@@ -157,6 +159,9 @@ struct MatchDto: Decodable {
let homeLogoUrl: String?
let opponentPrimaryColor: String?
let opponentLogoUrl: String?
let effectiveCoverUrl: String?
let coverSource: String?
let customCoverEnabled: Bool?
func toDomain() -> Match {
Match(
@@ -182,7 +187,10 @@ struct MatchDto: Decodable {
homeSecondaryColor: homeSecondaryColor,
homeLogoUrl: homeLogoUrl,
opponentPrimaryColor: opponentPrimaryColor,
opponentLogoUrl: opponentLogoUrl
opponentLogoUrl: opponentLogoUrl,
effectiveCoverUrl: effectiveCoverUrl,
coverSource: coverSource ?? "default",
customCoverEnabled: customCoverEnabled ?? false
)
}
}
@@ -101,7 +101,9 @@ final class MatchRepository {
scoringRules: ScoringRules?,
sportKey: String? = nil,
overlayKind: String? = nil,
opponentLogoImage: UIImage? = nil
opponentLogoImage: UIImage? = nil,
coverImage: UIImage? = nil,
removeCover: Bool = false
) async throws -> Match {
let rulesMap = scoringRules?.toMap(setsToWin: setsToWin)
let body = UpdateMatchBodyFull(
@@ -115,7 +117,8 @@ final class MatchRepository {
opponentPrimaryColor: opponentPrimaryColor,
scoringRules: rulesMap
)
if let opponentLogoImage, let data = opponentLogoImage.pngData() {
let needsMultipart = opponentLogoImage != nil || coverImage != nil || removeCover
if needsMultipart {
var fields: [MultipartField] = [
.text("match[opponent_name]", opponentName),
.text("match[sets_to_win]", "\(setsToWin)"),
@@ -129,7 +132,15 @@ final class MatchRepository {
fields.append(.text("match[scoring_rules][points_deciding_set]", "\(rules.pointsDecidingSet)"))
fields.append(.text("match[scoring_rules][min_point_lead]", "\(rules.minPointLead)"))
}
fields.append(.file("opponent_logo_file", data, filename: "opponent.png", mime: "image/png"))
if let opponentLogoImage, let data = opponentLogoImage.pngData() {
fields.append(.file("opponent_logo_file", data, filename: "opponent.png", mime: "image/png"))
}
if let coverImage, let data = coverImage.pngData() {
fields.append(.file("cover_image", data, filename: "cover.png", mime: "image/png"))
}
if removeCover {
fields.append(.text("remove_cover", "1"))
}
return try await api.updateMatchMultipart(id: matchId, fields: fields).toDomain()
}
return try await api.updateMatch(id: matchId, body: UpdateMatchRequestFull(match: body)).toDomain()
@@ -44,6 +44,7 @@ struct Team: Identifiable, Equatable, Sendable {
let phoneDownloadEnabled: Bool
let billingUrl: String?
let staffManageUrl: String?
let customCoverEnabled: Bool
var canUseYoutube: Bool { youtubeEnabled }
var isYoutubeReady: Bool { youtubeSelectable }
@@ -95,6 +96,9 @@ struct Match: Identifiable, Equatable, Sendable {
let homeLogoUrl: String?
let opponentPrimaryColor: String?
let opponentLogoUrl: String?
let effectiveCoverUrl: String?
let coverSource: String
let customCoverEnabled: Bool
var hasActiveSession: Bool { activeSessionId != nil }
@@ -4,6 +4,15 @@ private let sideToolbarWidth: CGFloat = 44
private let iconButtonSize: CGFloat = 36
private let scoreButtonHeight: CGFloat = 32
private enum SideConfirmAction {
case shareLive
case shareRegia
case advancePeriod
case pauseOrResume
case toggleMute
case terminate
}
struct BroadcastControlsOverlay: View {
let controlsVisible: Bool
let onToggleControls: () -> Void
@@ -46,7 +55,7 @@ struct BroadcastControlsOverlay: View {
var sessionQualityPreset: String = "720p_30_2.5mbps"
var onSelectMinQuality: (String) -> Void = { _ in }
@State private var showTerminateConfirm = false
@State private var pendingConfirm: SideConfirmAction?
@State private var showMinQualityPicker = false
var body: some View {
@@ -118,11 +127,62 @@ struct BroadcastControlsOverlay: View {
)
}
}
.alert(L10n.t("broadcast.terminate.title"), isPresented: $showTerminateConfirm) {
Button(L10n.t("action.cancel"), role: .cancel) {}
Button(L10n.t("broadcast.terminate.confirm"), role: .destructive, action: onTerminate)
} message: {
Text(L10n.t("broadcast.terminate.message"))
.alert(
sideConfirmTitle,
isPresented: Binding(
get: { pendingConfirm != nil },
set: { if !$0 { pendingConfirm = nil } }
)
) {
Button(L10n.t("action.cancel"), role: .cancel) { pendingConfirm = nil }
if pendingConfirm == .terminate {
Button(L10n.t("broadcast.terminate.confirm"), role: .destructive, action: performPendingConfirm)
} else {
Button(L10n.t("action.confirm"), action: performPendingConfirm)
}
} message: {
Text(sideConfirmMessage)
}
}
private var sideConfirmTitle: String {
switch pendingConfirm {
case .shareLive: return L10n.t("broadcast.share.live.title")
case .shareRegia: return L10n.t("broadcast.share.regia.title")
case .advancePeriod: return L10n.t("broadcast.advance.period.title")
case .pauseOrResume:
return isPaused ? L10n.t("broadcast.resume.title") : L10n.t("broadcast.pause.title")
case .toggleMute:
return audioMuted ? L10n.t("broadcast.unmute.title") : L10n.t("broadcast.mute.title")
case .terminate: return L10n.t("broadcast.terminate.title")
case .none: return ""
}
}
private var sideConfirmMessage: String {
switch pendingConfirm {
case .shareLive: return L10n.t("broadcast.share.live.message")
case .shareRegia: return L10n.t("broadcast.share.regia.message")
case .advancePeriod: return L10n.t("broadcast.advance.period.message")
case .pauseOrResume:
return isPaused ? L10n.t("broadcast.resume.message") : L10n.t("broadcast.pause.message")
case .toggleMute:
return audioMuted ? L10n.t("broadcast.unmute.message") : L10n.t("broadcast.mute.message")
case .terminate: return L10n.t("broadcast.terminate.message")
case .none: return ""
}
}
private func performPendingConfirm() {
guard let action = pendingConfirm else { return }
pendingConfirm = nil
switch action {
case .shareLive: onShareLive()
case .shareRegia: onShareRegia()
case .advancePeriod: onAdvancePeriod?()
case .pauseOrResume: onPauseOrResume()
case .toggleMute: onToggleAudioMute()
case .terminate: onTerminate()
}
}
@@ -131,13 +191,13 @@ struct BroadcastControlsOverlay: View {
SideIconButton(
systemName: "square.and.arrow.up",
accessibilityLabel: L10n.t("broadcast.share.live.cd"),
action: onShareLive,
action: { pendingConfirm = .shareLive },
enabled: shareLiveEnabled
)
SideIconButton(
systemName: "video.fill",
accessibilityLabel: L10n.t("broadcast.share.regia.cd"),
action: onShareRegia
action: { pendingConfirm = .shareRegia }
)
SideIconButton(
systemName: "slider.horizontal.3",
@@ -151,11 +211,11 @@ struct BroadcastControlsOverlay: View {
action: onCloseSet
)
}
if let onAdvancePeriod {
if onAdvancePeriod != nil {
SideIconButton(
systemName: "forward.end.fill",
accessibilityLabel: L10n.t("broadcast.next.period.cd"),
action: onAdvancePeriod
action: { pendingConfirm = .advancePeriod }
)
}
}
@@ -168,19 +228,19 @@ struct BroadcastControlsOverlay: View {
SideIconButton(
systemName: isPaused ? "play.fill" : "pause.fill",
accessibilityLabel: isPaused ? L10n.t("broadcast.resume.cd") : L10n.t("broadcast.pause.cd"),
action: onPauseOrResume,
action: { pendingConfirm = .pauseOrResume },
highlighted: isPaused
)
SideIconButton(
systemName: audioMuted ? "speaker.slash.fill" : "speaker.wave.2.fill",
accessibilityLabel: audioMuted ? L10n.t("broadcast.unmute.cd") : L10n.t("broadcast.mute.cd"),
action: onToggleAudioMute,
action: { pendingConfirm = .toggleMute },
highlighted: audioMuted
)
SideIconButton(
systemName: "stop.fill",
accessibilityLabel: L10n.t("broadcast.terminate.cd"),
action: { showTerminateConfirm = true },
action: { pendingConfirm = .terminate },
danger: true
)
}
@@ -3,6 +3,7 @@ import SwiftUI
enum ScoreDialogKind {
case setWon
case closeSet
case closeSetAnyway
case matchWon
}
@@ -92,10 +93,10 @@ final class LiveScoreActions {
awayPoints: score.awayPoints,
currentSet: score.currentSet
)
if winner == nil {
let ok = await dialogHost.show(ScoreDialogState(kind: .closeSetAnyway))
if !ok { return }
}
let ok = await dialogHost.show(
ScoreDialogState(kind: winner == nil ? .closeSetAnyway : .closeSet)
)
if !ok { return }
guard await scoreController.closeSetAsync() else { return }
onScoreboardChanged()
await afterCloseSet()
@@ -149,6 +150,13 @@ struct ScoreDialogRouter: View {
primaryButton: .default(Text(L10n.t("score.action.close.set"))) { host.resolve(true) },
secondaryButton: .cancel(Text(L10n.t("score.action.continue.scoring"))) { host.resolve(false) }
)
case .closeSet:
return Alert(
title: Text(L10n.t("score.action.close.set")),
message: Text(L10n.t("broadcast.close.set.confirm.message")),
primaryButton: .default(Text(L10n.t("score.action.close.set"))) { host.resolve(true) },
secondaryButton: .cancel(Text(L10n.t("action.cancel"))) { host.resolve(false) }
)
case .closeSetAnyway:
return Alert(
title: Text(L10n.t("score.action.close.set")),
@@ -0,0 +1,97 @@
import PhotosUI
import SwiftUI
struct MatchCoverSection: View {
let effectiveCoverUrl: String?
let coverSource: String
let customCoverEnabled: Bool
@Binding var localCoverImage: UIImage?
let hasMatchOverride: Bool
let onClearOverride: () -> Void
@State private var coverPickerItem: PhotosPickerItem?
private var sourceLabel: String {
switch coverSource {
case "match": return L10n.t("wizard.match.cover.source.match")
case "team": return L10n.t("wizard.match.cover.source.team")
case "club": return L10n.t("wizard.match.cover.source.club")
default: return L10n.t("wizard.match.cover.source.default")
}
}
var body: some View {
VStack(alignment: .leading, spacing: 0) {
Text(L10n.t("wizard.match.cover.title"))
.font(MatchTypography.labelLarge)
.foregroundStyle(MatchColors.textSecondary)
Text(L10n.t("wizard.match.cover.source.label", sourceLabel))
.font(MatchTypography.bodyMedium)
.foregroundStyle(MatchColors.textSecondary)
.padding(.top, 4)
Group {
if let localCoverImage {
Image(uiImage: localCoverImage)
.resizable()
.scaledToFill()
} else if let urlString = MediaUrl.resolve(effectiveCoverUrl), let url = URL(string: urlString) {
AsyncImage(url: url) { phase in
switch phase {
case .success(let image):
image.resizable().scaledToFill()
default:
Color.clear
}
}
} else {
Color.clear
}
}
.frame(maxWidth: .infinity)
.aspectRatio(16 / 9, contentMode: .fit)
.clipShape(RoundedRectangle(cornerRadius: 12))
.background(MatchColors.surface)
.padding(.top, 12)
Text(L10n.t("wizard.match.cover.hint"))
.font(MatchTypography.bodyMedium)
.foregroundStyle(MatchColors.textSecondary)
.padding(.top, 8)
if customCoverEnabled {
PhotosPicker(selection: $coverPickerItem, matching: .images) {
Text(L10n.t("wizard.match.cover.change"))
.font(MatchTypography.labelLarge)
.frame(maxWidth: .infinity)
.frame(height: 52)
.overlay(RoundedRectangle(cornerRadius: 8).stroke(MatchColors.outline, lineWidth: 1))
}
.buttonStyle(.plain)
.padding(.top, 12)
if hasMatchOverride || localCoverImage != nil {
MatchSecondaryButton(
label: L10n.t("wizard.match.cover.reset"),
action: onClearOverride
)
.padding(.top, 8)
}
} else {
Text(L10n.t("wizard.match.cover.premium.required"))
.font(MatchTypography.bodyMedium)
.foregroundStyle(MatchColors.textSecondary)
.padding(.top, 12)
}
}
.onChange(of: coverPickerItem) { item in
guard let item else { return }
Task {
if let data = try? await item.loadTransferable(type: Data.self),
let image = UIImage(data: data) {
await MainActor.run { localCoverImage = image }
}
}
}
}
}
@@ -53,6 +53,11 @@ struct StepMatchScreen: View {
@State private var opponentPrimaryColor: String
@State private var homeLogoImage: UIImage?
@State private var opponentLogoImage: UIImage?
@State private var coverImage: UIImage?
@State private var removeCover = false
@State private var effectiveCoverUrl: String?
@State private var coverSource: String
@State private var customCoverEnabled: Bool
@State private var saving = false
@State private var sports: [SportOption] = []
@State private var customRules = false
@@ -84,6 +89,9 @@ struct StepMatchScreen: View {
_opponentLogoUrl = State(initialValue: match.opponentLogoUrl)
_homePrimaryColor = State(initialValue: ColorHex.normalizeHexColor(match.homePrimaryColor))
_opponentPrimaryColor = State(initialValue: ColorHex.normalizeHexColor(match.opponentPrimaryColor, fallback: WizardDefaults.opponentColor))
_effectiveCoverUrl = State(initialValue: match.effectiveCoverUrl)
_coverSource = State(initialValue: match.coverSource)
_customCoverEnabled = State(initialValue: match.customCoverEnabled)
_setsToWin = State(initialValue: min(max(match.setsToWin, 2), 3))
_pointsPerSet = State(initialValue: rules?.pointsPerSet ?? WizardDefaults.pointsPerSet)
_pointsDecidingSet = State(initialValue: rules?.pointsDecidingSet ?? WizardDefaults.pointsDecidingSet)
@@ -150,6 +158,19 @@ struct StepMatchScreen: View {
)
.padding(.bottom, 16)
MatchCoverSection(
effectiveCoverUrl: effectiveCoverUrl,
coverSource: coverImage != nil ? "match" : coverSource,
customCoverEnabled: customCoverEnabled,
localCoverImage: $coverImage,
hasMatchOverride: match.coverSource == "match",
onClearOverride: {
coverImage = nil
removeCover = true
}
)
.padding(.bottom, 16)
WizardOutlinedField(label: L10n.t("wizard.match.location.label"), text: $location)
.padding(.bottom, 12)
@@ -213,9 +234,12 @@ struct StepMatchScreen: View {
.task(id: match.id) {
if let cached = container.wizardSession.team {
applyHomeTeam(cached)
} else if let team = await container.matchRepository.fetchTeam(teamId: match.teamId) {
} else if let team = await container.matchRepository.fetchTeam(teamId: match.teamId) {
container.wizardSession.team = team
applyHomeTeam(team)
if !match.customCoverEnabled {
customCoverEnabled = team.customCoverEnabled
}
}
if let loaded = try? await container.matchRepository.fetchSports() {
sports = loaded
@@ -228,6 +252,9 @@ struct StepMatchScreen: View {
selectedOverlay = defaultOverlay
}
}
.onChange(of: coverImage) { image in
if image != nil { removeCover = false }
}
.onChange(of: customOverlay) { enabled in
if !enabled {
selectedOverlay = defaultOverlay
@@ -414,9 +441,13 @@ struct StepMatchScreen: View {
scoringRules: resolvedRules,
sportKey: effectiveSportKey,
overlayKind: overlayKind,
opponentLogoImage: opponentLogoImage
opponentLogoImage: opponentLogoImage,
coverImage: coverImage,
removeCover: removeCover
)
container.wizardSession.match = updated
effectiveCoverUrl = updated.effectiveCoverUrl
coverSource = updated.coverSource
onNext()
} catch {
if let message = UserFacingError.message(for: error) {
@@ -26,7 +26,10 @@ final class MatchScoringRulesTests: XCTestCase {
homeSecondaryColor: nil,
homeLogoUrl: nil,
opponentPrimaryColor: "#1E3A8A",
opponentLogoUrl: nil
opponentLogoUrl: nil,
effectiveCoverUrl: nil,
coverSource: "default",
customCoverEnabled: false
)
}
@@ -87,7 +90,10 @@ final class MatchScoringRulesTests: XCTestCase {
homeSecondaryColor: nil,
homeLogoUrl: nil,
opponentPrimaryColor: nil,
opponentLogoUrl: nil
opponentLogoUrl: nil,
effectiveCoverUrl: nil,
coverSource: "default",
customCoverEnabled: false
)
XCTAssertFalse(MatchScoringContext(match: basket).usesSetLogic)
}