Remove Broadcasted Auto Event Template

apikeys
Razmig Sarkissian 2 months ago
parent 39beecd9cd
commit 586de4431f
  1. 263
      tournaments/templates/tournaments/broadcast/broadcasted_auto_event.html
  2. 79
      tournaments/views.py

@ -1,263 +0,0 @@
<!DOCTYPE html>
<html>
{% load static %}
{% load qr_code %}
<head>
{% include 'tournaments/broadcast/base_head.html' %}
<script src="{% static 'tournaments/js/alpine.min.js' %}" defer></script>
<title>Broadcast</title>
<!-- Matomo -->
<script>
var _paq = window._paq = window._paq || [];
/* tracker methods like "setCustomDimension" should be called before "trackPageView" */
_paq.push(["setDocumentTitle", document.domain + "/" + document.title]);
_paq.push(["setDoNotTrack", true]);
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function() {
var u="//matomo.padelclub.app/";
_paq.push(['setTrackerUrl', u+'matomo.php']);
_paq.push(['setSiteId', '1']);
var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
})();
</script>
<!-- End Matomo Code -->
</head>
<body>
<div x-data="{
tournamentIds: {{ tournament_ids|safe }},
activeTournamentIndex: 0,
paginatedMatches: null,
paginatedGroupStages: null,
paginatedSummons: null,
paginatedRankings: null,
has_sponsors: {{ tournament.has_sponsors|lower }},
active: 1,
hide_weight: {{ tournament.hide_weight|lower }},
prefixTitle: '',
eventTitle: '',
title: '',
retrieveDataForActiveTournament() {
const activeTournamentId = this.tournamentIds[this.activeTournamentIndex];
fetch(`/tournament/${activeTournamentId}/broadcast/json/`)
.then(res => res.json())
.then((data) => {
const hasContent = data.matches.length > 0 || data.group_stages.length > 0 || data.summons.length > 0 || data.rankings.length > 0;
if (!hasContent) {
console.warn(`Tournament ${activeTournamentId} has no content, skipping.`);
// Move to the next tournament and retry fetching data
this.activeTournamentIndex = (this.activeTournamentIndex + 1) % this.tournamentIds.length;
this.retrieveDataForActiveTournament(); // Recursively fetch the next tournament
if (this.activeTournamentIndex === this.tournamentIds.length - 1) {
this.prefixTitle = ''
this.eventTitle = '{{ club_name }}'
this.title = 'Aucun tournoi en cours'
}
return;
}
console.log('Fetched Data:', data); // Add this to debug the fetch result
this.paginatedMatches = this.paginate(data.matches, 8);
this.paginatedGroupStages = this.paginate(data.group_stages, 4);
this.paginatedSummons = this.paginateSummons(data.summons);
this.paginatedRankings = this.paginateRankings(data.rankings);
this.setPrefixTitle();
this.eventTitle = data.event_title
this.title = data.tournament_title
if (this.active > this.pageCount()) {
this.active = 1;
}
})
.catch((error) => {
console.error('Error fetching data:', error); // Handle fetch errors
});
},
paginateSummons(array) {
let pageSize = 16
if (window.innerHeight <= 720) {
pageSize = 12;
if (this.has_sponsors) {
pageSize = 10
}
} else if (window.innerHeight <= 1080) {
if (this.has_sponsors) {
pageSize = 12
}
}
pages = this.paginate(array, pageSize);
const splitGroups = [];
pages.forEach(group => {
const firstHalf = group.slice(0, pageSize / 2);
const secondHalf = group.slice(pageSize / 2);
if (secondHalf.length > 0) {
splitGroups.push([firstHalf, secondHalf]);
} else {
splitGroups.push([firstHalf]);
}
});
return splitGroups;
},
paginateRankings(array) {
let pageSize = 16
if (window.innerHeight <= 720) {
pageSize = 12;
if (this.has_sponsors) {
pageSize = 10
}
} else if (window.innerHeight <= 1080) {
if (this.has_sponsors) {
pageSize = 12
}
}
pages = this.paginate(array, pageSize);
const splitGroups = [];
pages.forEach(group => {
const firstHalf = group.slice(0, pageSize / 2);
const secondHalf = group.slice(pageSize / 2);
if (secondHalf.length > 0) {
splitGroups.push([firstHalf, secondHalf]);
} else {
splitGroups.push([firstHalf]);
}
});
return splitGroups;
},
paginate(array, pageSize) {
let paginatedArray = [];
for (let i = 0; i < array.length; i += pageSize) {
paginatedArray.push(array.slice(i, i + pageSize));
}
return paginatedArray;
},
loop() {
console.log('Loop function is called');
this.retrieveDataForActiveTournament();
if (this.pageCount() === 0 && this.tournamentIds.length > 0) {
console.warn(`Tournament ${this.tournamentIds[this.activeTournamentIndex]} has no pages, skipping to next.`);
this.skipToNextTournament();
}
setInterval(() => {
// After fetching the data, check if the current tournament has no pages
if (this.pageCount() === 0 && this.tournamentIds.length > 0) {
console.warn(`Tournament ${this.tournamentIds[this.activeTournamentIndex]} has no pages, skipping to next.`);
this.skipToNextTournament();
} else if (this.active === this.pageCount()) {
this.active = 1;
// Move to the next tournament
this.skipToNextTournament();
} else {
this.active += 1;
}
this.setPrefixTitle();
}, 15000);
},
skipToNextTournament() {
this.activeTournamentIndex = (this.activeTournamentIndex + 1) % this.tournamentIds.length;
this.retrieveDataForActiveTournament(); // Fetch data for the new tournament
},
pageCount() {
// Safely handle null or undefined values
const totalCount = (this.paginatedMatches?.length || 0) +
(this.paginatedGroupStages?.length || 0) +
(this.paginatedSummons?.length || 0) +
(this.paginatedRankings?.length || 0);
return totalCount;
},
setPrefixTitle() {
if (this.active < 1 + this.paginatedSummons.length) {
this.prefixTitle = 'Convocations';
} else if (this.active < 1 + this.paginatedSummons.length + this.paginatedMatches.length) {
this.prefixTitle = 'Matchs';
} else if (this.active < 1 + this.paginatedSummons.length + this.paginatedMatches.length + this.paginatedGroupStages.length) {
this.prefixTitle = 'Poules';
} else if (paginatedRankings.length > 0) {
this.prefixTitle = 'Classement';
}
}
}" x-init="loop()">
<header>
<div id="header">
<div class="left-content bubble">
<img src="{% static 'tournaments/images/PadelClub_logo_512.png' %}" alt="logo" class="logo">
<div class="left-margin">
<h1 class="club" x-text="eventTitle"></h1>
<h1 class="event">
<span x-text="prefixTitle"></span>
<span x-text="title"></span>
</h1>
</div >
</div>
{% if qr_code_options %}
<div class="right-content">{% qr_from_text qr_code_url options=qr_code_options %}</div>
{% endif %}
</div>
</header>
<div class="wrapper">
<main>
<div class="grid-x">
<template x-for="i in paginatedSummons.length">
<template x-for="column in paginatedSummons[i-1]">
<div class="cell medium-6 large-6 topblock" x-show="active === i">
{% include 'tournaments/broadcast/broadcasted_summon.html' %}
</div>
</template>
</template>
<template x-for="i in paginatedMatches.length" >
<template x-for="match in paginatedMatches[i-1]" >
<div class="cell medium-6 large-3" x-show="active === i + paginatedSummons.length">
{% include 'tournaments/broadcast/broadcasted_match.html' %}
</div>
</template>
</template>
<template x-for="i in paginatedGroupStages.length">
<template x-for="group_stage in paginatedGroupStages[i-1]">
<div class="cell medium-6 large-3" x-show="active === i + paginatedSummons.length + paginatedMatches.length">
{% include 'tournaments/broadcast/broadcasted_group_stage.html' %}
</div>
</template>
</template>
<template x-for="i in paginatedRankings.length">
<template x-for="column in paginatedRankings[i-1]">
<div class="cell medium-6 large-6 topblock padding10" x-show="active === i + paginatedSummons.length + paginatedMatches.length + paginatedGroupStages.length">
{% include 'tournaments/broadcast/broadcasted_ranking.html' %}
</div>
</template>
</template>
</div>
</main>
</div>
</div>
</body>
</html>

@ -532,11 +532,29 @@ def automatic_broadcast(request, tournament_id):
def automatic_broadcast_event(request, event_id):
event = get_object_or_404(Event, pk=event_id)
tournaments = Tournament.objects.filter(event=event).order_by('start_date')
now = timezone.now()
# Filter tournaments that have broadcast content
tournaments_with_content = []
for tournament in tournaments:
# Initial time windows
past_cutoff = now - timedelta(hours=4)
future_cutoff = now + timedelta(hours=4)
# Get recent/current tournaments (started but not too old)
recent_tournaments = Tournament.objects.filter(
event=event,
start_date__gte=past_cutoff,
start_date__lte=now
).order_by('start_date')
# Get near-future tournaments
future_tournaments = Tournament.objects.filter(
event=event,
start_date__gt=now,
start_date__lte=future_cutoff
).order_by('start_date')
# Filter recent tournaments that have content
recent_with_content = []
for tournament in recent_tournaments:
try:
content = tournament.broadcast_content()
has_content = (
@ -546,12 +564,59 @@ def automatic_broadcast_event(request, event_id):
len(content.get('rankings', [])) > 0
)
if has_content:
tournaments_with_content.append(tournament)
recent_with_content.append(tournament)
except:
# Skip tournaments that error when getting content
continue
tournament_ids = [str(tournament.id) for tournament in tournaments_with_content]
tournaments_to_display = recent_with_content[:]
# If we have 0 or 1 recent tournaments, extend the search
if len(recent_with_content) <= 1:
needed = 2 - len(recent_with_content)
# First, try to add future tournaments (within 4 hours)
added_from_future = 0
for tournament in future_tournaments:
if added_from_future >= needed:
break
tournaments_to_display.append(tournament)
added_from_future += 1
# If still not enough, extend past search (beyond 4 hours)
if len(tournaments_to_display) < 2:
extended_past_tournaments = Tournament.objects.filter(
event=event,
start_date__lt=past_cutoff # Older than 4 hours ago
).order_by('-start_date') # Most recent first
still_needed = 2 - len(tournaments_to_display)
for tournament in extended_past_tournaments[:still_needed]:
# Check if this past tournament has content
try:
content = tournament.broadcast_content()
has_content = (
len(content.get('matches', [])) > 0 or
len(content.get('group_stages', [])) > 0 or
len(content.get('summons', [])) > 0 or
len(content.get('rankings', [])) > 0
)
if has_content:
tournaments_to_display.append(tournament)
except:
continue
# If still not enough, extend future search (beyond 4 hours)
if len(tournaments_to_display) < 2:
extended_future_tournaments = Tournament.objects.filter(
event=event,
start_date__gt=future_cutoff # More than 4 hours in the future
).order_by('start_date')
still_needed = 2 - len(tournaments_to_display)
for tournament in extended_future_tournaments[:still_needed]:
tournaments_to_display.append(tournament)
tournament_ids = [str(tournament.id) for tournament in tournaments_to_display]
# Create QR code URL for the event broadcast
qr_code_url_val = reverse('automatic-broadcast-event', args=[event_id])

Loading…
Cancel
Save