Redesign UI as light-themed week-grid calendar matching Skylight-style device
- Replace scrolling event list + photo background with a Sun–Sat week grid plus a "Next Week" preview column; Prev/Next navigation and per-member filter - Add [Name] event title prefix convention for color-coded family member cards (Ludwig/Dad=blue, Michelle/Mom=pink, Jason=green, Daniel=yellow) - /api/calendar now accepts ?start=YYYY-MM-DD, returns bucketed week payload with member/color metadata; fetches 14 days to populate Next Week column - Drop rotating background photo and dad joke from the display (endpoints kept) - Update README with new UI overview, prefix convention, and API docs Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
124
app.py
124
app.py
@@ -1,7 +1,8 @@
|
||||
from flask import Flask, render_template, jsonify
|
||||
from flask import Flask, render_template, jsonify, request
|
||||
import requests
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
from datetime import datetime, timedelta, date
|
||||
from icalendar import Calendar
|
||||
from config import Config
|
||||
@@ -13,7 +14,7 @@ app.config.from_object(Config)
|
||||
|
||||
# Cache for API responses to avoid rate limiting
|
||||
weather_cache = {'data': None, 'timestamp': None}
|
||||
calendar_cache = {'data': None, 'timestamp': None}
|
||||
calendar_cache = {'data': None, 'timestamp': None, 'key': None}
|
||||
joke_cache = {'data': None, 'timestamp': None}
|
||||
|
||||
|
||||
@@ -94,35 +95,84 @@ def get_weather():
|
||||
return jsonify({'error': 'Unable to fetch weather data'}), 500
|
||||
|
||||
|
||||
MEMBER_PREFIX_RE = re.compile(r'^\s*\[([^\]]+)\]\s*(.*)')
|
||||
|
||||
|
||||
def parse_member_and_title(summary, family_members):
|
||||
"""Split a "[Alias] Title" event summary into (member_dict, clean_title)."""
|
||||
match = MEMBER_PREFIX_RE.match(summary)
|
||||
if not match:
|
||||
return None, summary
|
||||
|
||||
alias = match.group(1).strip().lower()
|
||||
title = match.group(2).strip() or summary
|
||||
for member in family_members:
|
||||
if alias in member['aliases']:
|
||||
return member, title
|
||||
return None, title
|
||||
|
||||
|
||||
def week_start_for(d):
|
||||
"""Return the Sunday on/before date d (Sunday-starting week)."""
|
||||
return d - timedelta(days=(d.weekday() + 1) % 7)
|
||||
|
||||
|
||||
def empty_week_payload(week_start_date, members):
|
||||
days = []
|
||||
for i in range(7):
|
||||
d = week_start_date + timedelta(days=i)
|
||||
days.append({'date': d.isoformat(), 'weekday': d.strftime('%A'), 'events': []})
|
||||
next_week_start = week_start_date + timedelta(days=7)
|
||||
next_week_end = next_week_start + timedelta(days=6)
|
||||
return {
|
||||
'week_start': week_start_date.isoformat(),
|
||||
'week_end': (week_start_date + timedelta(days=6)).isoformat(),
|
||||
'days': days,
|
||||
'next_week': {'start': next_week_start.isoformat(), 'end': next_week_end.isoformat(), 'count': 0, 'events': []},
|
||||
'members': members,
|
||||
}
|
||||
|
||||
|
||||
@app.route('/api/calendar')
|
||||
def get_calendar():
|
||||
"""Fetch Google Calendar events from iCal feed."""
|
||||
"""Fetch Google Calendar events from iCal feed for a Sunday-starting week."""
|
||||
global calendar_cache
|
||||
|
||||
# Check cache - use timezone-aware datetime
|
||||
nz_tz = pytz.timezone('Pacific/Auckland')
|
||||
now = datetime.now(nz_tz)
|
||||
if (calendar_cache['data'] and calendar_cache['timestamp'] and
|
||||
|
||||
start_param = request.args.get('start')
|
||||
if start_param:
|
||||
try:
|
||||
week_start_date = week_start_for(datetime.strptime(start_param, '%Y-%m-%d').date())
|
||||
except ValueError:
|
||||
week_start_date = week_start_for(now.date())
|
||||
else:
|
||||
week_start_date = week_start_for(now.date())
|
||||
|
||||
family_members = app.config['FAMILY_MEMBERS']
|
||||
default_member = app.config['DEFAULT_MEMBER']
|
||||
members_for_filter = family_members + [default_member]
|
||||
|
||||
cache_key = week_start_date.isoformat()
|
||||
if (calendar_cache.get('key') == cache_key and calendar_cache['data'] and calendar_cache['timestamp'] and
|
||||
(now - calendar_cache['timestamp']).total_seconds() < app.config['CALENDAR_UPDATE_INTERVAL']):
|
||||
return jsonify(calendar_cache['data'])
|
||||
|
||||
try:
|
||||
# Fetch iCal feed
|
||||
ical_url = app.config.get('GOOGLE_CALENDAR_ICAL_URL')
|
||||
if not ical_url:
|
||||
return jsonify([])
|
||||
return jsonify(empty_week_payload(week_start_date, members_for_filter))
|
||||
|
||||
response = requests.get(ical_url, timeout=10)
|
||||
response.raise_for_status()
|
||||
|
||||
# Parse iCal data
|
||||
cal = Calendar.from_ical(response.content)
|
||||
|
||||
# Use recurring_ical_events to get all events in the date range (including recurring ones)
|
||||
cutoff_date = now + timedelta(days=app.config['CALENDAR_DAYS_AHEAD'])
|
||||
|
||||
# Get all events between now and cutoff_date
|
||||
recurring_events = recurring_ical_events.of(cal).between(now, cutoff_date)
|
||||
# Fetch this week + next week, so the "Next Week" preview column has data.
|
||||
range_start = nz_tz.localize(datetime.combine(week_start_date, datetime.min.time()))
|
||||
range_end = range_start + timedelta(days=14)
|
||||
recurring_events = recurring_ical_events.of(cal).between(range_start, range_end)
|
||||
|
||||
events = []
|
||||
for component in recurring_events:
|
||||
@@ -131,23 +181,18 @@ def get_calendar():
|
||||
summary = str(component.get('summary', 'No Title'))
|
||||
|
||||
if dtstart and dtstart.dt:
|
||||
# Handle both datetime and date objects
|
||||
if isinstance(dtstart.dt, datetime):
|
||||
event_start = dtstart.dt
|
||||
# Make sure event_start is timezone-aware
|
||||
if event_start.tzinfo is None:
|
||||
event_start = nz_tz.localize(event_start)
|
||||
elif isinstance(dtstart.dt, date):
|
||||
# For date-only events, create a timezone-aware datetime
|
||||
event_start = nz_tz.localize(datetime.combine(dtstart.dt, datetime.min.time()))
|
||||
else:
|
||||
continue
|
||||
|
||||
# Handle end time
|
||||
if dtend and dtend.dt:
|
||||
if isinstance(dtend.dt, datetime):
|
||||
event_end = dtend.dt
|
||||
# Make sure event_end is timezone-aware
|
||||
if event_end.tzinfo is None:
|
||||
event_end = nz_tz.localize(event_end)
|
||||
elif isinstance(dtend.dt, date):
|
||||
@@ -157,24 +202,53 @@ def get_calendar():
|
||||
else:
|
||||
event_end = event_start + timedelta(hours=1)
|
||||
|
||||
member, title = parse_member_and_title(summary, family_members)
|
||||
member_info = member or default_member
|
||||
|
||||
events.append({
|
||||
'title': summary,
|
||||
'title': title,
|
||||
'start': event_start.isoformat(),
|
||||
'end': event_end.isoformat(),
|
||||
'location': str(component.get('location', ''))
|
||||
'location': str(component.get('location', '')),
|
||||
'member': member_info['key'],
|
||||
'member_name': member_info['name'],
|
||||
'color': member_info['color'],
|
||||
'bg': member_info['bg'],
|
||||
})
|
||||
|
||||
# Sort events by start time
|
||||
events.sort(key=lambda x: x['start'])
|
||||
|
||||
calendar_cache = {'data': events, 'timestamp': now}
|
||||
return jsonify(events)
|
||||
days = []
|
||||
for i in range(7):
|
||||
d = week_start_date + timedelta(days=i)
|
||||
day_events = [e for e in events if datetime.fromisoformat(e['start']).date() == d]
|
||||
days.append({'date': d.isoformat(), 'weekday': d.strftime('%A'), 'events': day_events})
|
||||
|
||||
next_week_start = week_start_date + timedelta(days=7)
|
||||
next_week_end = next_week_start + timedelta(days=6)
|
||||
next_week_events = [e for e in events if datetime.fromisoformat(e['start']).date() >= next_week_start]
|
||||
|
||||
result = {
|
||||
'week_start': week_start_date.isoformat(),
|
||||
'week_end': (week_start_date + timedelta(days=6)).isoformat(),
|
||||
'days': days,
|
||||
'next_week': {
|
||||
'start': next_week_start.isoformat(),
|
||||
'end': next_week_end.isoformat(),
|
||||
'count': len(next_week_events),
|
||||
'events': next_week_events[:5],
|
||||
},
|
||||
'members': members_for_filter,
|
||||
}
|
||||
|
||||
calendar_cache = {'data': result, 'timestamp': now, 'key': cache_key}
|
||||
return jsonify(result)
|
||||
|
||||
except Exception as e:
|
||||
app.logger.error(f"Error fetching calendar: {str(e)}")
|
||||
if calendar_cache['data']:
|
||||
if calendar_cache.get('data') and calendar_cache.get('key') == cache_key:
|
||||
return jsonify(calendar_cache['data'])
|
||||
return jsonify([])
|
||||
return jsonify(empty_week_payload(week_start_date, members_for_filter))
|
||||
|
||||
|
||||
@app.route('/api/background')
|
||||
|
||||
Reference in New Issue
Block a user