"""Fetch and shape a Gitea user's contribution heatmap for the dashboard.""" from datetime import datetime, timedelta, timezone as utc_timezone import json from urllib.error import HTTPError, URLError from urllib.parse import quote from urllib.request import Request, urlopen from django.conf import settings from django.core.cache import cache from django.utils import timezone HEATMAP_CACHE_SECONDS = 15 * 60 def fetch_heatmap(): username = settings.GITEA_USERNAME if not username: return None key = f'gitea-heatmap:{settings.GITEA_BASE_URL}:{username}' cached = cache.get(key) if cached is not None: return cached url = f'{settings.GITEA_BASE_URL}/api/v1/users/{quote(username, safe="")}/heatmap' headers = {'Accept': 'application/json'} if settings.GITEA_TOKEN: headers['Authorization'] = f'token {settings.GITEA_TOKEN}' try: with urlopen(Request(url, headers=headers), timeout=4) as response: data = json.load(response) except (HTTPError, URLError, TimeoutError, OSError, ValueError): return None if not isinstance(data, list): return None cache.set(key, data, HEATMAP_CACHE_SECONDS) return data def activity_level(count): if count <= 0: return 0 if count == 1: return 1 if count <= 3: return 2 if count <= 6: return 3 return 4 def activity_context(today=None): """Return 53 Sunday-first weeks ending in the current week.""" today = today or timezone.localdate() data = fetch_heatmap() if data is None: return {'activity_unavailable': True} counts = {} for item in data: try: day = datetime.fromtimestamp(item['timestamp'], utc_timezone.utc).date() count = max(0, int(item['contributions'])) except (KeyError, TypeError, ValueError, OverflowError, OSError): continue counts[day] = count first = today - timedelta(days=364) first -= timedelta(days=(first.weekday() + 1) % 7) weeks = [] total = 0 for week_number in range(53): week_start = first + timedelta(days=week_number * 7) week = [] for weekday in range(7): day = week_start + timedelta(days=weekday) count = counts.get(day, 0) if day <= today else 0 if day <= today and day >= today - timedelta(days=364): total += count week.append({ 'date': day, 'count': count, 'level': activity_level(count), 'future': day > today, }) month = week_start.strftime('%b') if week_number == 0 or week_start.month != (week_start - timedelta(days=7)).month else '' weeks.append({'days': week, 'month': month}) return { 'activity_weeks': weeks, 'activity_total': total, 'activity_username': settings.GITEA_USERNAME, 'activity_profile_url': f'{settings.GITEA_BASE_URL}/{quote(settings.GITEA_USERNAME, safe="")}', }