Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Date fixes (#412 audit): search date filters use the viewer's calendar days and keep the last day of date_to and lastmonth; Inquire filter dates no longer 'Invalid Date'; a date-only meeting_date edit keeps the time of day; watch-folder and file-time dates stored as UTC; one combined ICS builder with a UTC DTSTAMP; API v1 date_to includes the whole day; new token expiry shown in local time
Murtaza Nasir4d4c8b164efe
diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex 33ace045..0fa350cf 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -872,17 +872,23 @@ def list_recordings():# 'all' = no status filter# Date filters+ # Aware values are converted to the naive-UTC storage convention; a bare+ # date_to includes that whole day (#412 B8).+ from src.utils.dates import to_utc_naiveif date_from:try:- from_date = datetime.fromisoformat(date_from.replace('Z', '+00:00'))+ from_date = to_utc_naive(datetime.fromisoformat(date_from.replace('Z', '+00:00')))query = query.filter(Recording.created_at >= from_date)except ValueError:passif date_to:try:- to_date = datetime.fromisoformat(date_to.replace('Z', '+00:00'))- query = query.filter(Recording.created_at <= to_date)+ to_date = to_utc_naive(datetime.fromisoformat(date_to.replace('Z', '+00:00')))+ if len(date_to.strip()) == 10:+ query = query.filter(Recording.created_at < to_date + timedelta(days=1))+ else:+ query = query.filter(Recording.created_at <= to_date)except ValueError:pass@@ -2585,28 +2591,13 @@ def download_events_ics(recording_id):if not events:return jsonify({'error': 'No events found'}), 404- # Generate combined ICS- ics_lines = ['BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Speakr//Events//EN']-- for event in events:- ics_lines.append('BEGIN:VEVENT')- ics_lines.append(f'UID:{event.id}@speakr')- ics_lines.append(f'SUMMARY:{event.title}')- if event.start_datetime:- ics_lines.append(f'DTSTART:{event.start_datetime.strftime("%Y%m%dT%H%M%S")}')- if event.end_datetime:- ics_lines.append(f'DTEND:{event.end_datetime.strftime("%Y%m%dT%H%M%S")}')- if event.description:- ics_lines.append(f'DESCRIPTION:{event.description}')- if event.location:- ics_lines.append(f'LOCATION:{event.location}')- ics_lines.append('END:VEVENT')-- ics_lines.append('END:VCALENDAR')+ # Same builder as the web download (#412).+ from src.services.calendar import generate_combined_ics+ ics_text = generate_combined_ics(events)from flask import Responsereturn Response(- '\r\n'.join(ics_lines),+ ics_text,mimetype='text/calendar',headers={'Content-Disposition': f'attachment; filename=events-{recording_id}.ics'})diff --git a/src/api/events.py b/src/api/events.pyindex 57359951..68f39102 100644--- a/src/api/events.py+++ b/src/api/events.py@@ -108,31 +108,9 @@ def download_all_events_ics(recording_id):if not events:return jsonify({'error': 'No events found for this recording'}), 404- # Generate combined ICS content- ics_lines = []- ics_lines.append("BEGIN:VCALENDAR")- ics_lines.append("VERSION:2.0")- ics_lines.append("PRODID:-//Speakr//Event Export//EN")- ics_lines.append("CALSCALE:GREGORIAN")- ics_lines.append("METHOD:PUBLISH")-- # Add each event- for event in events:- # Get the individual event's ICS content and extract just the VEVENT portion- individual_ics = generate_ics_content(event)- # Extract VEVENT block from individual ICS- lines = individual_ics.split('\n')- in_event = False- for line in lines:- if line.startswith('BEGIN:VEVENT'):- in_event = True- if in_event:- ics_lines.append(line)- if line.startswith('END:VEVENT'):- in_event = False-- ics_lines.append("END:VCALENDAR")- ics_content = '\r\n'.join(ics_lines)+ # Same builder as the API v1 download (#412).+ from src.services.calendar import generate_combined_ics+ ics_content = generate_combined_ics(events)# Create response with ICS fileresponse = make_response(ics_content)diff --git a/src/api/inquire.py b/src/api/inquire.pyindex c0838539..7ab3b9ac 100644--- a/src/api/inquire.py+++ b/src/api/inquire.py@@ -889,7 +889,7 @@ def get_available_filters():return jsonify({'tags': [tag.to_dict() for tag in all_tags],'speakers': speaker_names,- 'recordings': [{'id': r.id, 'title': r.title, 'meeting_date': f"{r.meeting_date.isoformat()}T00:00:00" if r.meeting_date else None} for r in recordings]+ 'recordings': [{'id': r.id, 'title': r.title, 'meeting_date': r.meeting_date.isoformat() if r.meeting_date else None} for r in recordings]})except Exception as e:diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 0e27d6d9..6b45cb62 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -12,7 +12,7 @@ import timeimport threadingimport subprocessimport uuid-from datetime import datetime, timedelta, timezone+from datetime import date, datetime, timedelta, timezonefrom src.services.llm_settings import get_temperaturefrom src.services.job_queue import job_queuefrom flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify, send_file, Response, current_app, make_response@@ -1699,158 +1699,78 @@ def get_recordings_paginated():text_query = re.sub(r'tag:\S+', '', text_query, flags=re.IGNORECASE)text_query = re.sub(r'speaker:\S+', '', text_query, flags=re.IGNORECASE).strip()- # Apply date filters+ # Apply date filters (#412). Each filter is a range of local calendar+ # days in the viewer's timezone (sent by the browser, else the account+ # zone), converted to UTC because meeting_date / created_at are stored+ # as naive UTC. Ranges are half-open [start, end): the last day is+ # included up to midnight (date_to and lastmonth dropped it before).+ from src.utils.timezones import local_day_start_utc, now_local, request_timezone+ _zone = request_timezone(request.args.get('tz'), current_user)+ _today = now_local(_zone).date()++ def _days(first, after_last=None):+ start_utc = local_day_start_utc(first, _zone)+ end_utc = local_day_start_utc(after_last, _zone) if after_last else None+ meeting = [Recording.meeting_date >= start_utc]+ created = [Recording.created_at >= start_utc]+ if end_utc is not None:+ meeting.append(Recording.meeting_date < end_utc)+ created.append(Recording.created_at < end_utc)+ return db.or_(db.and_(*meeting),+ db.and_(Recording.meeting_date.is_(None), *created))++ def _month_start(year, month):+ return date(year, month, 1)++ def _next_month(d):+ return date(d.year + (d.month == 12), d.month % 12 + 1, 1)+for date_filter in date_filters:if date_filter == 'today':- today = datetime.now().date()- stmt = stmt.where(- db.or_(- db.func.date(Recording.meeting_date) == today,- db.and_(- Recording.meeting_date.is_(None),- db.func.date(Recording.created_at) == today- )- )- )+ stmt = stmt.where(_days(_today, _today + timedelta(days=1)))elif date_filter == 'yesterday':- yesterday = datetime.now().date() - timedelta(days=1)- stmt = stmt.where(- db.or_(- db.func.date(Recording.meeting_date) == yesterday,- db.and_(- Recording.meeting_date.is_(None),- db.func.date(Recording.created_at) == yesterday- )- )- )+ stmt = stmt.where(_days(_today - timedelta(days=1), _today))elif date_filter == 'thisweek':- today = datetime.now().date()- start_of_week = today - timedelta(days=today.weekday())- stmt = stmt.where(- db.or_(- Recording.meeting_date >= start_of_week,- db.and_(- Recording.meeting_date.is_(None),- db.func.date(Recording.created_at) >= start_of_week- )- )- )+ stmt = stmt.where(_days(_today - timedelta(days=_today.weekday())))elif date_filter == 'lastweek':- today = datetime.now().date()- end_of_last_week = today - timedelta(days=today.weekday())- start_of_last_week = end_of_last_week - timedelta(days=7)- stmt = stmt.where(- db.or_(- db.and_(- Recording.meeting_date >= start_of_last_week,- Recording.meeting_date < end_of_last_week- ),- db.and_(- Recording.meeting_date.is_(None),- db.func.date(Recording.created_at) >= start_of_last_week,- db.func.date(Recording.created_at) < end_of_last_week- )- )- )+ this_week = _today - timedelta(days=_today.weekday())+ stmt = stmt.where(_days(this_week - timedelta(days=7), this_week))elif date_filter == 'thismonth':- today = datetime.now().date()- start_of_month = today.replace(day=1)- stmt = stmt.where(- db.or_(- Recording.meeting_date >= start_of_month,- db.and_(- Recording.meeting_date.is_(None),- db.func.date(Recording.created_at) >= start_of_month- )- )- )+ stmt = stmt.where(_days(_today.replace(day=1)))elif date_filter == 'lastmonth':- today = datetime.now().date()- first_day_this_month = today.replace(day=1)- last_day_last_month = first_day_this_month - timedelta(days=1)- first_day_last_month = last_day_last_month.replace(day=1)- stmt = stmt.where(- db.or_(- db.and_(- Recording.meeting_date >= first_day_last_month,- Recording.meeting_date <= last_day_last_month- ),- db.and_(- Recording.meeting_date.is_(None),- db.func.date(Recording.created_at) >= first_day_last_month,- db.func.date(Recording.created_at) <= last_day_last_month- )- )- )+ this_month = _today.replace(day=1)+ last_month = (this_month - timedelta(days=1)).replace(day=1)+ stmt = stmt.where(_days(last_month, this_month))elif re.match(r'^\d{4}-\d{2}-\d{2}$', date_filter):- # Specific date format YYYY-MM-DD- target_date = datetime.strptime(date_filter, '%Y-%m-%d').date()- stmt = stmt.where(- db.or_(- db.func.date(Recording.meeting_date) == target_date,- db.and_(- Recording.meeting_date.is_(None),- db.func.date(Recording.created_at) == target_date- )- )- )+ try:+ target = datetime.strptime(date_filter, '%Y-%m-%d').date()+ stmt = stmt.where(_days(target, target + timedelta(days=1)))+ except ValueError:+ passelif re.match(r'^\d{4}-\d{2}$', date_filter):- # Month format YYYY-MMyear, month = map(int, date_filter.split('-'))- stmt = stmt.where(- db.or_(- db.and_(- db.extract('year', Recording.meeting_date) == year,- db.extract('month', Recording.meeting_date) == month- ),- db.and_(- Recording.meeting_date.is_(None),- db.extract('year', Recording.created_at) == year,- db.extract('month', Recording.created_at) == month- )- )- )+ if 1 <= month <= 12:+ first = _month_start(year, month)+ stmt = stmt.where(_days(first, _next_month(first)))elif re.match(r'^\d{4}$', date_filter):- # Year format YYYYyear = int(date_filter)- stmt = stmt.where(- db.or_(- db.extract('year', Recording.meeting_date) == year,- db.and_(- Recording.meeting_date.is_(None),- db.extract('year', Recording.created_at) == year- )- )- )+ stmt = stmt.where(_days(date(year, 1, 1), date(year + 1, 1, 1)))- # Apply date range filters+ # Apply date range filters (date_to includes that whole day)if date_from_filters and date_from_filters[0]:try:date_from = datetime.strptime(date_from_filters[0], '%Y-%m-%d').date()- stmt = stmt.where(- db.or_(- Recording.meeting_date >= date_from,- db.and_(- Recording.meeting_date.is_(None),- db.func.date(Recording.created_at) >= date_from- )- )- )+ stmt = stmt.where(_days(date_from))except ValueError:pass # Invalid date format, ignoreif date_to_filters and date_to_filters[0]:try:date_to = datetime.strptime(date_to_filters[0], '%Y-%m-%d').date()- stmt = stmt.where(- db.or_(- Recording.meeting_date <= date_to,- db.and_(- Recording.meeting_date.is_(None),- db.func.date(Recording.created_at) <= date_to- )- )- )+ end_utc = local_day_start_utc(date_to + timedelta(days=1), _zone)+ stmt = stmt.where(db.or_(+ Recording.meeting_date < end_utc,+ db.and_(Recording.meeting_date.is_(None), Recording.created_at < end_utc)))except ValueError:pass # Invalid date format, ignore@@ -2098,18 +2018,16 @@ def save_metadata():# Try to parse as full ISO datetime first. meeting_date is# stored as naive UTC (like created_at), so convert any# zone-aware input to UTC before storing.- try:+ if re.match(r'^\d{4}-\d{2}-\d{2}$', date_str.strip()):+ # Date only: keep the existing time of day, else noon UTC+ # so the calendar day reads the same in every timezone.+ # (Python 3.11 parses a bare date as midnight UTC, which+ # showed as the previous day west of UTC, #412 B5.)+ parsed_date = datetime.strptime(date_str.strip(), '%Y-%m-%d')+ existing_time = recording.meeting_date.time() if recording.meeting_date else datetime.min.time().replace(hour=12)+ recording.meeting_date = datetime.combine(parsed_date.date(), existing_time)+ else:recording.meeting_date = to_utc_naive(datetime.fromisoformat(date_str.replace('Z', '+00:00')))- except (ValueError, AttributeError):- # Fall back to date-only format, preserve existing time if available- parsed_date = datetime.strptime(date_str, '%Y-%m-%d')- if recording.meeting_date:- # Preserve existing time- existing_time = recording.meeting_date.time()- recording.meeting_date = datetime.combine(parsed_date.date(), existing_time)- else:- # No existing time, use the parsed date with midnight time- recording.meeting_date = parsed_dateelse:recording.meeting_date = Noneexcept (ValueError, TypeError) as e:diff --git a/src/file_monitor.py b/src/file_monitor.pyindex 09eb5b66..1811d1e3 100644--- a/src/file_monitor.py+++ b/src/file_monitor.py@@ -462,7 +462,9 @@ class FileMonitor:# Try to extract creation date from file metadata, fall back to current timeif not meeting_date:- meeting_date = get_creation_date(str(final_path))+ # Normalised to naive UTC like the upload path (#412 B6).+ from src.utils.dates import to_utc_naive+ meeting_date = to_utc_naive(get_creation_date(str(final_path)))if meeting_date:self.logger.info(f"Using file metadata creation date: {meeting_date}")else:diff --git a/src/services/calendar.py b/src/services/calendar.pyindex 9266b436..a495912c 100644--- a/src/services/calendar.py+++ b/src/services/calendar.py@@ -30,7 +30,7 @@ def generate_ics_content(event):'METHOD:PUBLISH','BEGIN:VEVENT',f'UID:{uid}',- f'DTSTAMP:{format_ical_date(datetime.utcnow())}',+ f'DTSTAMP:{format_ical_date(datetime.utcnow())}Z', # UTC, as RFC 5545 requires]# Add event details@@ -100,3 +100,24 @@ def escape_ical_text(text):+++def generate_combined_ics(events):+ """One calendar file with several events (web download and API v1).++ Each VEVENT comes from generate_ics_content, so escaping, DTSTAMP and the+ default one-hour end are the same in both downloads (#412).+ """+ lines = ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Speakr//Event Export//EN",+ "CALSCALE:GREGORIAN", "METHOD:PUBLISH"]+ for event in events:+ in_event = False+ for line in generate_ics_content(event).replace("\r\n", "\n").split("\n"):+ if line.startswith("BEGIN:VEVENT"):+ in_event = True+ if in_event:+ lines.append(line)+ if line.startswith("END:VEVENT"):+ in_event = False+ lines.append("END:VCALENDAR")+ return "\r\n".join(lines)diff --git a/src/utils/ffprobe.py b/src/utils/ffprobe.pyindex a37e37d3..8f6dbac5 100644--- a/src/utils/ffprobe.py+++ b/src/utils/ffprobe.py@@ -579,7 +579,9 @@ def _get_file_mtime(filename: str) -> Optional[datetime]:try:stat_info = os.stat(filename)- return datetime.fromtimestamp(stat_info.st_mtime)+ # Naive UTC, the storage convention (was server-local time, #412 B6).+ from datetime import timezone as _tz+ return datetime.fromtimestamp(stat_info.st_mtime, tz=_tz.utc).replace(tzinfo=None)except (OSError, ValueError) as e:logger.warning(f"Failed to get file mtime for {filename}: {e}")return Nonediff --git a/src/utils/timezones.py b/src/utils/timezones.pyindex bccad26f..45b08ca6 100644--- a/src/utils/timezones.py+++ b/src/utils/timezones.py@@ -63,6 +63,18 @@ def to_user_local(dt, user):return to_local(dt, user_timezone(user))+def local_day_start_utc(day, zone_name):+ """Midnight at the start of a local calendar day, as naive UTC (for queries)."""+ from datetime import time as _time+ start = datetime.combine(day, _time.min).replace(tzinfo=ZoneInfo(zone_name))+ return start.astimezone(timezone.utc).replace(tzinfo=None)+++def request_timezone(value, user):+ """The zone for an interactive request: the browser's if valid, else the user's."""+ return value if is_valid_timezone(value) else user_timezone(user)++def now_local(zone_name):"""The current wall-clock time in zone_name (naive)."""return to_local(datetime.utcnow(), zone_name)diff --git a/static/js/modules/composables/recordings.js b/static/js/modules/composables/recordings.jsindex b77c977c..5eea2300 100644--- a/static/js/modules/composables/recordings.js+++ b/static/js/modules/composables/recordings.js@@ -34,6 +34,12 @@ export function useRecordings(state, utils, reprocessComposable) {Object.entries(params).forEach(([k, v]) => {if (v !== undefined && v !== null && v !== '') qs.set(k, String(v));});+ // Date searches ("date:today", date_from/date_to) use this browser's+ // calendar days (#412).+ try {+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;+ if (zone) qs.set('tz', zone);+ } catch (e) { /* the account timezone applies */ }const response = await fetch(`/api/recordings?${qs.toString()}`);const data = await response.json();if (!response.ok) throw new Error(data.error || 'Failed to load recordings');diff --git a/templates/account.html b/templates/account.htmlindex 3ee837cd..ba8d2922 100644--- a/templates/account.html+++ b/templates/account.html@@ -6190,7 +6190,12 @@ curl "https://your-speakr-instance.com/api/recordings?token=YOUR_TOKEN_HERE"</cofunction formatTokenDate(dateString) {if (!dateString) return 'Never';- const date = new Date(dateString);+ // Naive UTC from the server: read as UTC, show in local time (#412).+ let s = dateString;+ if (typeof s === 'string' && /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(?:Z|[+-]\d{2}:?\d{2})$/.test(s)) {+ s = s.replace(' ', 'T') + 'Z';+ }+ const date = new Date(s);return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();}diff --git a/tests/test_date_fixes.py b/tests/test_date_fixes.pynew file mode 100644index 00000000..af992be4--- /dev/null+++ b/tests/test_date_fixes.py@@ -0,0 +1,201 @@+"""Date handling fixes from the #412 audit (search, Inquire, edits, watch folder, ICS, API v1).++Dates are stored as naive UTC. These tests pin how calendar-day questions are+answered in the viewer's timezone and that no end day is dropped.++SHARED-DB: users, recordings, events and tokens are removed afterwards.+"""++import os+import re+import secrets+import sys+import tempfile+from datetime import date, datetime, timedelta+from types import SimpleNamespace+from unittest.mock import patch++import pytest+from flask import g, has_app_context+from flask.testing import FlaskClient++sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++from src.app import app, db+from src.models import APIToken, Recording, User+from src.services.calendar import generate_combined_ics, generate_ics_content+from src.utils.token_auth import hash_token++app.config["WTF_CSRF_ENABLED"] = False+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+++class _Client(FlaskClient):+ def open(self, *args, **kwargs):+ if has_app_context():+ g.pop('_login_user', None)+ return super().open(*args, **kwargs)+++def world():+ """A user with two recordings either side of a Tokyo midnight."""+ with app.app_context():+ n = f"dates_{secrets.token_hex(4)}"+ u = User(username=n, email=f"{n}@local.test", password="x")+ db.session.add(u)+ db.session.commit()+ # 2026-03-04 23:30 UTC = 2026-03-05 08:30 in Tokyo+ a = Recording(user_id=u.id, title="Morning Tokyo", status="COMPLETED", original_filename="a.wav",+ meeting_date=datetime(2026, 3, 4, 23, 30))+ # 2026-03-04 10:00 UTC = 2026-03-04 19:00 in Tokyo+ b = Recording(user_id=u.id, title="Evening Tokyo", status="COMPLETED", original_filename="b.wav",+ meeting_date=datetime(2026, 3, 4, 10, 0))+ plain = f"test-token-{secrets.token_urlsafe(16)}"+ t = APIToken(user_id=u.id, token_hash=hash_token(plain), name="dates")+ db.session.add_all([a, b, t])+ db.session.commit()+ ids = dict(user=u.id, a=a.id, b=b.id, token=t.id)+ yield ids, plain+ with app.app_context():+ for model, key in ((APIToken, "token"), (Recording, "a"), (Recording, "b"), (User, "user")):+ obj = db.session.get(model, ids[key])+ if obj is not None:+ db.session.delete(obj)+ db.session.commit()+++def _search(ids, q, tz="Asia/Tokyo"):+ c = _Client(app, app.response_class, use_cookies=True)+ with c.session_transaction() as sess:+ sess["_user_id"] = str(ids["user"])+ with patch("src.utils.timezones.now_local", return_value=datetime(2026, 3, 5, 12, 0)):+ resp = c.get("/api/recordings", query_string={"q": q, "tz": tz, "per_page": 100})+ assert resp.status_code == 200, resp.get_data(as_text=True)[:300]+ return {r["title"] for r in resp.get_json()["recordings"]}+++# ---------------------------------------------------- search (T9, B4)++def test_today_and_yesterday_are_the_viewers_calendar_days(world):+ ids, _ = world+ assert _search(ids, "date:today") == {"Morning Tokyo"}+ assert _search(ids, "date:yesterday") == {"Evening Tokyo"}+++def test_a_specific_day_is_the_viewers_calendar_day(world):+ ids, _ = world+ assert _search(ids, "date:2026-03-05") == {"Morning Tokyo"}+ assert _search(ids, "date:2026-03-04", tz="UTC") == {"Morning Tokyo", "Evening Tokyo"}+++def test_date_to_includes_the_whole_last_day(world):+ ids, _ = world+ # Before: meeting_date <= 2026-03-05 (midnight) dropped the 08:30 recording.+ assert _search(ids, "date_from:2026-03-05 date_to:2026-03-05") == {"Morning Tokyo"}+++def test_last_month_includes_its_last_day(world):+ ids, _ = world+ with app.app_context():+ r = db.session.get(Recording, ids["a"])+ r.meeting_date = datetime(2026, 2, 28, 20, 0) # 28 Feb 20:00 UTC, last day of Feb in UTC+ db.session.commit()+ with patch("src.utils.timezones.now_local", return_value=datetime(2026, 3, 10, 12, 0)):+ c = _Client(app, app.response_class, use_cookies=True)+ with c.session_transaction() as sess:+ sess["_user_id"] = str(ids["user"])+ resp = c.get("/api/recordings", query_string={"q": "date:lastmonth", "tz": "UTC"})+ assert "Morning Tokyo" in {r["title"] for r in resp.get_json()["recordings"]}+++# ------------------------------------------------------- B1: Inquire filters++def test_inquire_filter_dates_are_plain_iso(world):+ ids, _ = world+ c = _Client(app, app.response_class, use_cookies=True)+ with c.session_transaction() as sess:+ sess["_user_id"] = str(ids["user"])+ resp = c.get("/api/inquire/available_filters")+ if resp.status_code == 404:+ pytest.skip("Inquire mode disabled in this environment")+ dates = [r["meeting_date"] for r in resp.get_json()["recordings"] if r["id"] in (ids["a"], ids["b"])]+ assert dates and all(re.match(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$", d) for d in dates)+++# --------------------------------------------- B5: date-only meeting_date edit++def test_a_date_only_edit_keeps_the_time_of_day(world):+ ids, _ = world+ c = _Client(app, app.response_class, use_cookies=True)+ with c.session_transaction() as sess:+ sess["_user_id"] = str(ids["user"])+ with patch("src.api.recordings.export_recording"):+ resp = c.post("/save", json={"id": ids["b"], "meeting_date": "2026-03-10"})+ assert resp.status_code == 200, resp.get_data(as_text=True)[:300]+ with app.app_context():+ assert db.session.get(Recording, ids["b"]).meeting_date == datetime(2026, 3, 10, 10, 0)+++# ----------------------------------------------------- B6: file times in UTC++def test_file_mtime_is_naive_utc_whatever_the_server_zone():+ from src.utils import ffprobe+ with tempfile.NamedTemporaryFile() as f:+ os.utime(f.name, (1772668800, 1772668800)) # 2026-03-05 00:00:00 UTC+ old = os.environ.get("TZ")+ os.environ["TZ"] = "Asia/Tokyo"+ import time+ time.tzset()+ try:+ fn = getattr(ffprobe, "_get_file_mtime", None) or getattr(ffprobe, "get_file_mtime")+ assert fn(f.name) == datetime(2026, 3, 5, 0, 0)+ finally:+ if old is None:+ os.environ.pop("TZ", None)+ else:+ os.environ["TZ"] = old+ time.tzset()+++# ------------------------------------------------------------ B7: ICS++def _event(i, title):+ return SimpleNamespace(id=i, title=title, description="Plan, review; decide", location=None,+ start_datetime=datetime(2026, 3, 9, 9, 0), end_datetime=None,+ attendees=None, reminder_minutes=None)+++def test_ics_stamp_is_utc_and_both_downloads_share_one_builder():+ single = generate_ics_content(_event(1, "Review"))+ assert re.search(r"^DTSTAMP:\d{8}T\d{6}Z\r?$", single, re.M)+ combined = generate_combined_ics([_event(1, "Review"), _event(2, "Launch, v2")])+ assert combined.count("BEGIN:VEVENT") == 2 and combined.startswith("BEGIN:VCALENDAR")+ assert "SUMMARY:Launch\\, v2" in combined # escaped as in the single download+ assert "DTEND:20260309T100000" in combined # default one-hour end+ v1 = open(os.path.join(ROOT, "src", "api", "api_v1.py"), encoding="utf-8").read()+ assert "generate_combined_ics" in v1 and "ics_lines" not in v1+++# ------------------------------------------------- B8: API v1 date filters++def test_v1_date_to_includes_the_whole_day(world):+ ids, plain = world+ with app.app_context():+ for key, created in (("a", datetime(2026, 3, 5, 18, 0)), ("b", datetime(2026, 3, 6, 1, 0))):+ db.session.get(Recording, ids[key]).created_at = created+ db.session.commit()+ with app.test_client() as c:+ resp = c.get("/api/v1/recordings", query_string={"date_from": "2026-03-05", "date_to": "2026-03-05", "per_page": 100},+ headers={"Authorization": f"Bearer {plain}"})+ assert resp.status_code == 200, resp.get_data(as_text=True)[:300]+ titles = {r["title"] for r in resp.get_json()["recordings"]}+ assert "Morning Tokyo" in titles and "Evening Tokyo" not in titles+++# ----------------------------------------------- B3: token expiry display++def test_token_expiry_is_read_as_utc():+ html = open(os.path.join(ROOT, "templates", "account.html"), encoding="utf-8").read()+ body = html[html.index("function formatTokenDate"):][:600]+ assert "+ 'Z'" in body