add club auto broadcast

tz
Raz 1 year ago
parent 17ea4c185b
commit 98acbc77e0
  1. 10
      tournaments/models/tournament.py
  2. 224
      tournaments/templates/tournaments/broadcast/broadcasted_auto_event.html
  3. 2
      tournaments/urls.py
  4. 42
      tournaments/views.py

@ -451,6 +451,8 @@ class Tournament(models.Model):
'matches': [], 'matches': [],
'group_stages': group_stages_dicts, 'group_stages': group_stages_dicts,
'summons': team_summons_dicts, 'summons': team_summons_dicts,
'event_title' : self.broadcast_event_display_name(),
'tournament_title' : self.broadcast_display_name(),
'rankings' : [] 'rankings' : []
} }
else: else:
@ -459,6 +461,8 @@ class Tournament(models.Model):
'matches': live_matches_dicts, 'matches': live_matches_dicts,
'group_stages': [], 'group_stages': [],
'summons': team_summons_dicts, 'summons': team_summons_dicts,
'event_title' : self.broadcast_event_display_name(),
'tournament_title' : self.broadcast_display_name(),
'rankings' : [] 'rankings' : []
} }
elif self.end_date is not None: elif self.end_date is not None:
@ -468,6 +472,8 @@ class Tournament(models.Model):
'matches': live_matches_dicts, 'matches': live_matches_dicts,
'group_stages': [], 'group_stages': [],
'summons': [], 'summons': [],
'event_title' : self.broadcast_event_display_name(),
'tournament_title' : self.broadcast_display_name(),
'rankings' : team_rankings_dicts 'rankings' : team_rankings_dicts
} }
else: # we want to display the broadcasted content else: # we want to display the broadcasted content
@ -476,7 +482,9 @@ class Tournament(models.Model):
'matches': live_matches_dicts, 'matches': live_matches_dicts,
'group_stages': group_stages_dicts, 'group_stages': group_stages_dicts,
'summons': [], 'summons': [],
'rankings' : [] 'rankings' : [],
'event_title' : self.broadcast_event_display_name(),
'tournament_title' : self.broadcast_display_name(),
} }
def broadcasted_matches_and_group_stages(self): def broadcasted_matches_and_group_stages(self):

@ -0,0 +1,224 @@
<!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,
active: 1,
prefixTitle: '',
eventTitle: '',
title: '',
retrieveDataForActiveTournament() {
const activeTournamentId = this.tournamentIds[this.activeTournamentIndex];
fetch(`/tournament/${activeTournamentId}/broadcast/json/`)
.then(res => res.json())
.then((data) => {
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;
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;
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 {
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 my-block" 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 my-block" 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 my-block" 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 my-block" 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>

@ -8,6 +8,7 @@ urlpatterns = [
path("clubs/", views.clubs, name="clubs"), path("clubs/", views.clubs, name="clubs"),
path("clubs/<str:club_id>/", views.club, name="club"), path("clubs/<str:club_id>/", views.club, name="club"),
path("c/<str:broadcast_code>", views.club_broadcast, name="club-broadcast"), path("c/<str:broadcast_code>", views.club_broadcast, name="club-broadcast"),
path("c/<str:broadcast_code>/go", views.club_broadcast_auto, name="club-broadcast-auto"),
path("tournament/<str:tournament_id>/", path("tournament/<str:tournament_id>/",
include([ include([
path('', views.tournament, name='tournament'), path('', views.tournament, name='tournament'),
@ -29,6 +30,7 @@ urlpatterns = [
path('broadcast/rankings/', views.tournament_broadcast_rankings, name='broadcasted-rankings'), path('broadcast/rankings/', views.tournament_broadcast_rankings, name='broadcasted-rankings'),
]) ])
), ),
path("event/<str:event_id>/broadcast/auto/", views.automatic_broadcast_event, name='automatic-broadcast-event'),
path('players/', views.players, name='players'), path('players/', views.players, name='players'),
path('activate/<uidb64>/<token>/', views.activate, name='activate'), path('activate/<uidb64>/<token>/', views.activate, name='activate'),
path('download/', views.download, name='download'), path('download/', views.download, name='download'),

@ -30,7 +30,8 @@ import os
from .forms import SimpleForm from .forms import SimpleForm
from django.core.mail import EmailMessage from django.core.mail import EmailMessage
from datetime import timedelta
from django.utils import timezone
def index(request): def index(request):
@ -147,9 +148,9 @@ def tournament(request, tournament_id):
group_stages = tournament.groupstage_set.order_by('index') group_stages = tournament.groupstage_set.order_by('index')
print(len(match_groups)) #print(len(match_groups))
print(len(rounds)) #print(len(rounds))
print(len(group_stages)) #print(len(group_stages))
if tournament.display_matches() or tournament.display_group_stages(): if tournament.display_matches() or tournament.display_group_stages():
return render(request, 'tournaments/matches.html', { return render(request, 'tournaments/matches.html', {
@ -211,6 +212,14 @@ def automatic_broadcast(request, tournament_id):
'qr_code_options': qr_code_options(), 'qr_code_options': qr_code_options(),
}) })
def automatic_broadcast_event(request, event_id):
event = get_object_or_404(Event, pk=event_id)
tournaments = Tournament.objects.filter(event=event)
tournament_ids = [str(tournament.id) for tournament in tournaments]
return render(request, 'tournaments/broadcast/broadcasted_auto_event.html', {
'tournament_ids': tournament_ids,
})
def qr_code_url(request, tournament_id): def qr_code_url(request, tournament_id):
qr_code_url = reverse('tournament', args=[tournament_id]) qr_code_url = reverse('tournament', args=[tournament_id])
return request.build_absolute_uri(qr_code_url) return request.build_absolute_uri(qr_code_url)
@ -314,6 +323,31 @@ def club_broadcast(request, broadcast_code):
'tournaments': tournaments, 'tournaments': tournaments,
}) })
def club_broadcast_auto(request, broadcast_code):
club = get_object_or_404(Club, broadcast_code=broadcast_code)
q_not_deleted = Q(is_deleted=False, event__club=club)
now = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
recent_time_window = now - timedelta(hours=4)
tournaments = Tournament.objects.filter(
q_not_deleted,
(
Q(end_date__isnull=True) | # Include ongoing tournaments
Q(start_date__lt=now + timedelta(days=3)) # Include tournaments starting in the next 3 days
),
Q(is_private=False) # Exclude private tournaments
).filter(
Q(end_date__gte=recent_time_window) | # Include tournaments that just finished in the last 4 hours
Q(end_date__isnull=True) # Ensure ongoing tournaments are included
)
tournament_ids = [str(tournament.id) for tournament in tournaments]
#print(tournament_ids)
return render(request, 'tournaments/broadcast/broadcasted_auto_event.html', {
'tournament_ids': tournament_ids,
})
def download(request): def download(request):
return render(request, 'tournaments/download.html') return render(request, 'tournaments/download.html')

Loading…
Cancel
Save