added gitea activity for fun

This commit is contained in:
Joren de Graaf
2026-10-03 17:11:31 +02:00
parent 184e9d18f3
commit c0eda95f26
78 changed files with 11461 additions and 8 deletions
+8
View File
@@ -113,6 +113,7 @@ def configure_fasting(
'fasting_start_time': fasting_start_time,
'fasting_duration_minutes': fasting_duration_minutes,
'tracking_started_at': now if enabled else None,
'last_phase_notification_at': now,
},
)
if created:
@@ -121,9 +122,16 @@ def configure_fasting(
return settings
was_enabled = settings.enabled
schedule_changed = (
settings.fasting_start_time != fasting_start_time
or settings.fasting_duration_minutes != fasting_duration_minutes
or was_enabled != enabled
)
settings.fasting_start_time = fasting_start_time
settings.fasting_duration_minutes = fasting_duration_minutes
settings.enabled = enabled
if schedule_changed:
settings.last_phase_notification_at = now
if enabled and settings.tracking_started_at is None:
settings.tracking_started_at = now
settings.save()
@@ -0,0 +1,43 @@
"""Deliver the latest fasting phase transition once per tracked schedule."""
import logging
from django.db import transaction
from django.utils import timezone
from planner.models import FastingSettings
from planner.services.fasting import current_fasting_phase
from planner.services.notifications import NotificationError, send_notification
logger = logging.getLogger(__name__)
def notify_fasting_phase_changes(now=None):
now = now or timezone.now()
delivered = 0
for settings_id in FastingSettings.objects.filter(enabled=True).values_list('pk', flat=True):
with transaction.atomic():
settings = FastingSettings.objects.select_for_update().select_related('user').get(pk=settings_id)
if not settings.enabled:
continue
phase = current_fasting_phase(settings, now)
boundary = phase.cycle_start
cursor = settings.last_phase_notification_at
if cursor is None:
# Existing configurations start at the current phase without a catch-up alert.
settings.last_phase_notification_at = now
settings.save(update_fields=['last_phase_notification_at'])
continue
if boundary <= cursor or boundary > now:
continue
title = 'Fasting started' if phase.is_fasting else 'Eating window started'
message = 'Your fasting window has started.' if phase.is_fasting else 'Your eating window is open.'
try:
sent = send_notification(settings.user, title, message)
except NotificationError:
logger.warning('Could not deliver fasting phase notification for user %s.', settings.user_id)
continue
settings.last_phase_notification_at = boundary
settings.save(update_fields=['last_phase_notification_at'])
delivered += int(sent)
return delivered
+87
View File
@@ -0,0 +1,87 @@
"""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="")}',
}
+41
View File
@@ -0,0 +1,41 @@
from datetime import datetime, time, timedelta
from django.utils import timezone
from planner.models import UserSettings, WaterIntakeEntry
from planner.timezones import timezone_for_user
def hydration_context(user, now=None):
zone = timezone_for_user(user)
today = timezone.localtime(now or timezone.now(), zone).date()
start = today - timedelta(days=today.weekday())
week_start = timezone.make_aware(datetime.combine(start, time.min), zone)
week_end = timezone.make_aware(datetime.combine(start + timedelta(days=7), time.min), zone)
goal = UserSettings.objects.get_or_create(user=user)[0].daily_water_goal_ml
entries = WaterIntakeEntry.objects.filter(user=user, recorded_at__gte=week_start, recorded_at__lt=week_end)
totals = {start + timedelta(days=i): 0 for i in range(7)}
for entry in entries:
totals[timezone.localtime(entry.recorded_at, zone).date()] += entry.amount_ml
total = totals[today]
last = entries.filter(
recorded_at__gte=timezone.make_aware(datetime.combine(today, time.min), zone),
recorded_at__lt=timezone.make_aware(datetime.combine(today + timedelta(days=1), time.min), zone),
).order_by('-recorded_at', '-pk').first()
percent = round(total * 100 / goal)
visual = min(100, percent)
days = []
for day, amount in totals.items():
state = 'none' if amount == 0 else ('goal' if amount >= goal else 'partial')
days.append({'date': day, 'label': day.strftime('%a')[0], 'total': amount,
'state': state, 'state_label': {'none': 'no water logged', 'partial': 'partial goal', 'goal': 'goal met'}[state],
'today': day == today})
return {'hydration_total': total, 'hydration_goal': goal, 'hydration_percent': percent,
'hydration_visual': visual, 'hydration_fill_y': 168 - round(visual * 1.22),
'hydration_fill_height': round(visual * 1.22), 'hydration_last': last,
'hydration_last_time': timezone.localtime(last.recorded_at, zone).strftime('%H:%M') if last else None,
'hydration_zone': zone, 'hydration_days': days,
'hydration_markers': [
{'y': 46, 'value': goal}, {'y': 77, 'value': round(goal * .75)},
{'y': 107, 'value': round(goal * .5)}, {'y': 138, 'value': round(goal * .25)},
]}
+37
View File
@@ -0,0 +1,37 @@
import socket
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from planner.models import UserSettings
class NotificationError(Exception):
"""A delivery error safe to display without exposing the topic URL."""
def send_ntfy_notification(url, title, message, timeout=10):
request = Request(
url,
data=message.encode('utf-8'),
headers={'Content-Type': 'text/plain; charset=utf-8', 'Title': title},
method='POST',
)
try:
with urlopen(request, timeout=timeout) as response:
status = response.getcode()
except HTTPError as error:
raise NotificationError(f'ntfy server responded with HTTP {error.code}.') from error
except (TimeoutError, socket.timeout):
raise NotificationError('Connection to the ntfy server timed out.') from None
except (URLError, OSError):
raise NotificationError('Could not connect to the ntfy server.') from None
if not 200 <= status < 300:
raise NotificationError(f'ntfy server responded with HTTP {status}.')
def send_notification(user, title, message):
preferences = UserSettings.objects.filter(user=user).first()
if not preferences or not preferences.ntfy_enabled or not preferences.ntfy_url:
return False
send_ntfy_notification(preferences.ntfy_url, title, message)
return True