Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Events: attendees and reminders in API v1, floating wall-clock times, valid ICS attendees and folding (mailr spec G5)
Murtaza Nasirdd891ce38a1b
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.mdindex e590743c..55d6b37d 100644--- a/docs/user-guide/api-reference.md+++ b/docs/user-guide/api-reference.md@@ -1272,7 +1272,7 @@ GET /api/v1/recordings/{id}/events**Scope:** `read`-Returns calendar events extracted from the recording.+Returns calendar events extracted from the recording. The `events` in [Get Recording Details](#get-recording-details) are the same objects.**Response:**@@ -1281,16 +1281,28 @@ Returns calendar events extracted from the recording."events": [{"id": 1,+ "recording_id": 412,"title": "Follow-up Meeting",- "start_datetime": "2024-01-22T10:00:00Z",- "end_datetime": "2024-01-22T11:00:00Z",+ "start_datetime": "2024-01-22T10:00:00",+ "end_datetime": "2024-01-22T11:00:00",+ "floating": true,"description": "Discuss project progress",- "location": "Conference Room A"+ "location": "Conference Room A",+ "attendees": [+ {"name": "Dana Lee", "email": null},+ {"name": "Priya Shah", "email": "[email protected]"}+ ],+ "reminder_minutes": 15,+ "created_at": "2024-01-15T10:05:00"}]}```+- `floating: true`: `start_datetime` and `end_datetime` are wall-clock times as said in the recording, without a time zone. Show them as they are, in the user's own zone.+- `attendees` are objects: a name, an address, or both. A name the transcript gave without an address has `email: null`.+- Before v0.10.11-alpha, `attendees` in the recording details were plain strings.+### Download Events as ICS```http@@ -1299,7 +1311,7 @@ GET /api/v1/recordings/{id}/events/ics**Scope:** `read`-Returns an ICS file containing all events from the recording.+Returns an ICS file containing all events from the recording. Times are floating (no zone). Attendees with an address are `ATTENDEE` entries; names without an address are listed at the end of the description. `reminder_minutes` becomes an alarm.---diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex 40730deb..6eaf508e 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -1518,7 +1518,7 @@ def get_recording(recording_id):'folder_id': recording.folder_id,'folder': {'id': recording.folder.id, 'name': recording.folder.name} if recording.folder else None,'deletion_exempt': recording.deletion_exempt,- 'events': [e.to_dict() for e in recording.events] if hasattr(recording, 'events') else [],+ 'events': [e.api_dict() for e in recording.events] if hasattr(recording, 'events') else [],'error_message': recording.error_message if recording.status == 'FAILED' else None,'tags': [{'id': t.id, 'name': t.name, 'color': t.color} for t in recording.tags],'duplicate_info': recording.get_duplicate_info(),@@ -3064,16 +3064,7 @@ def get_recording_events(recording_id):events = Event.query.filter_by(recording_id=recording_id).all()- return jsonify({- 'events': [{- 'id': e.id,- 'title': e.title,- 'start_datetime': e.start_datetime.isoformat() if e.start_datetime else None,- 'end_datetime': e.end_datetime.isoformat() if e.end_datetime else None,- 'description': e.description,- 'location': e.location- } for e in events]- })+ return jsonify({'events': [e.api_dict() for e in events]})@api_v1_bp.route('/recordings/<int:recording_id>/events/ics', methods=['GET'])diff --git a/src/models/events.py b/src/models/events.pyindex d967b687..872670d9 100644--- a/src/models/events.py+++ b/src/models/events.py@@ -6,9 +6,13 @@ that are extracted from transcriptions."""import json+import refrom datetime import datetime+from src.database import db+_ADDRESS = re.compile(r'[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}')+class Event(db.Model):"""Calendar events extracted from transcripts."""@@ -41,3 +45,45 @@ class Event(db.Model):'reminder_minutes': self.reminder_minutes,'created_at': self.created_at.isoformat() if self.created_at else None}++ def attendee_list(self):+ """Attendees as [{'name', 'email'}] (mailr spec G5).++ A string becomes a name, or an email when it looks like an address;+ an object keeps its name and email; anything else is dropped.+ """+ try:+ raw = json.loads(self.attendees) if self.attendees else []+ except (TypeError, ValueError):+ return []+ if not isinstance(raw, list):+ return []+ people = []+ for item in raw:+ if isinstance(item, str):+ text = item.strip()+ if not text:+ continue+ match = _ADDRESS.search(text)+ if match:+ name = text.replace(match.group(0), '').strip(' <>()"\'') or None+ people.append({'name': name, 'email': match.group(0)})+ else:+ people.append({'name': text, 'email': None})+ elif isinstance(item, dict):+ name = item.get('name') if isinstance(item.get('name'), str) else None+ email = item.get('email') if isinstance(item.get('email'), str) else None+ if name or email:+ people.append({'name': (name or '').strip() or None, 'email': (email or '').strip() or None})+ return people++ def api_dict(self):+ """The API v1 shape: to_dict with attendees as objects and floating.++ start_datetime and end_datetime are the wall-clock times the+ extraction produced, without a zone (floating: true).+ """+ data = self.to_dict()+ data['attendees'] = self.attendee_list()+ data['floating'] = True+ return datadiff --git a/src/services/calendar.py b/src/services/calendar.pyindex a495912c..fc69f582 100644--- a/src/services/calendar.py+++ b/src/services/calendar.py@@ -44,25 +44,26 @@ def generate_ics_content(event):end_time = event.start_datetime + timedelta(hours=1)lines.append(f'DTEND:{format_ical_date(end_time)}')- # Add title and description+ # Add title and description. Attendees without an address are listed in+ # the description; ATTENDEE needs a real mailto: address.lines.append(f'SUMMARY:{escape_ical_text(event.title)}')- if event.description:- lines.append(f'DESCRIPTION:{escape_ical_text(event.description)}')+ people = event.attendee_list() if hasattr(event, 'attendee_list') else []+ unaddressed = [p['name'] for p in people if p['name'] and not p['email']]+ description = event.description or ''+ if unaddressed:+ description = (description + '\n\n' if description else '') + 'Attendees: ' + ', '.join(unaddressed)+ if description:+ lines.append(f'DESCRIPTION:{escape_ical_text(description)}')# Add location if availableif event.location:lines.append(f'LOCATION:{escape_ical_text(event.location)}')- # Add attendees if available- if event.attendees:- try:- attendees_list = json.loads(event.attendees)- for attendee in attendees_list:- if attendee:- lines.append(f'ATTENDEE:CN={escape_ical_text(attendee)}:mailto:{attendee.replace(" ", ".").lower()}@example.com')- except:- pass+ for person in people:+ if person['email']:+ name = (person['name'] or person['email']).replace('"', "'")+ lines.append(f'ATTENDEE;CN="{name}":mailto:{person["email"]}')# Add reminder/alarm if specifiedif event.reminder_minutes and event.reminder_minutes > 0:@@ -82,7 +83,26 @@ def generate_ics_content(event):'END:VCALENDAR'])- return '\r\n'.join(lines)+ return '\r\n'.join(fold_ical_line(line) for line in lines)+++def fold_ical_line(line, limit=75):+ """Fold a content line at 75 octets (RFC 5545 section 3.1), never inside a+ UTF-8 character; continuation lines start with one space."""+ data = line.encode('utf-8')+ if len(data) <= limit:+ return line+ parts, current, size = [], '', 0+ for ch in line:+ width = len(ch.encode('utf-8'))+ room = limit if not parts else limit - 1+ if size + width > room:+ parts.append(current)+ current, size = '', 0+ current += ch+ size += width+ parts.append(current)+ return '\r\n '.join(parts)@@ -95,6 +115,7 @@ def escape_ical_text(text):text = text.replace('\\', '\\\\')text = text.replace(',', '\\,')text = text.replace(';', '\\;')+ text = text.replace('\r\n', '\n').replace('\r', '\n')text = text.replace('\n', '\\n')return textdiff --git a/src/tasks/processing.py b/src/tasks/processing.pyindex 4f88b9ed..b9a47b1e 100644--- a/src/tasks/processing.py+++ b/src/tasks/processing.py@@ -1133,6 +1133,14 @@ You must respond with valid JSON format only."""f"{event_data.get('end_datetime')!r}: {parse_err!r}")+ # Event times are floating wall-clock times: keep what the+ # model wrote and drop any zone, so SQLite and PostgreSQL+ # store the same value (mailr spec G5, open question 1).+ if start_dt is not None and start_dt.tzinfo is not None:+ start_dt = start_dt.replace(tzinfo=None)+ if end_dt is not None and end_dt.tzinfo is not None:+ end_dt = end_dt.replace(tzinfo=None)+# Create event recordevent = Event(recording_id=recording_id,diff --git a/tests/test_api_v1_events.py b/tests/test_api_v1_events.pynew file mode 100644index 00000000..2bca3ba6--- /dev/null+++ b/tests/test_api_v1_events.py@@ -0,0 +1,130 @@+"""Extracted events in API v1 and ICS (mailr spec G5).++The events route returns attendees (as {name, email}) and the reminder, the+same objects as the detail; event times are floating wall-clock times. The+ICS output escapes text, folds long lines, lists real attendee addresses and+carries the reminder.++SHARED-DB: the user, token, recording and events are removed afterwards.+"""++import json+import os+import re+import secrets+import sys+from datetime import datetime++import pytest++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, Event, Recording, User+from src.utils.token_auth import hash_token++ATTENDEES = ["Dana Lee", "[email protected]", "Priya Shah <[email protected]>",+ {"name": "Lee", "email": "[email protected]"}, {"name": "Kim"}, 42, "", {"phone": "1"}]+++def world():+ with app.app_context():+ s = secrets.token_hex(4)+ u = User(username=f"ev_{s}", email=f"ev_{s}@local.test", password="x")+ db.session.add(u)+ db.session.commit()+ rec = Recording(user_id=u.id, title="Sync", status="COMPLETED", original_filename="s.wav")+ db.session.add(rec)+ db.session.commit()+ ev = Event(recording_id=rec.id, title="Budget review, Q4; draft",+ description="Bring the numbers.\nAnd the slides; all of them. " + "Long text " * 12,+ start_datetime=datetime(2026, 10, 9, 15, 0), end_datetime=datetime(2026, 10, 9, 16, 0),+ location="Room 4, Building B", attendees=json.dumps(ATTENDEES), reminder_minutes=30)+ plain = f"tok-{secrets.token_urlsafe(16)}"+ db.session.add_all([ev, APIToken(user_id=u.id, token_hash=hash_token(plain), name="ev")])+ db.session.commit()+ ids = dict(user=u.id, rec=rec.id, event=ev.id, token=plain)+ yield ids+ with app.app_context():+ Event.query.filter_by(recording_id=ids["rec"]).delete()+ Recording.query.filter_by(id=ids["rec"]).delete()+ APIToken.query.filter_by(user_id=ids["user"]).delete()+ User.query.filter_by(id=ids["user"]).delete()+ db.session.commit()+++def _get(world, path):+ with app.test_client() as c:+ return c.get(path, headers={"Authorization": f"Bearer {world['token']}"})+++def test_the_events_route_returns_attendees_and_reminder(world):+ events = _get(world, f"/api/v1/recordings/{world['rec']}/events").get_json()["events"]+ ev = events[0]+ assert ev["reminder_minutes"] == 30 and ev["floating"] is True and ev["recording_id"] == world["rec"]+ assert ev["start_datetime"] == "2026-10-09T15:00:00"+ assert ev["attendees"] == [+ {"name": "Dana Lee", "email": None},+ {"name": None, "email": "[email protected]"},+ {"name": "Priya Shah", "email": "[email protected]"},+ {"name": "Lee", "email": "[email protected]"},+ {"name": "Kim", "email": None},+ ]+++def test_the_detail_embeds_identical_events(world):+ events = _get(world, f"/api/v1/recordings/{world['rec']}/events").get_json()["events"]+ detail = _get(world, f"/api/v1/recordings/{world['rec']}").get_json()["events"]+ assert detail == events+++def _unfold(text):+ assert "\r\n" in text+ for raw in text.split("\r\n"):+ assert len(raw.encode("utf-8")) <= 75, raw+ return re.sub(r"\r\n[ \t]", "", text).split("\r\n")+++def _unescape(value):+ return re.sub(r"\\([\\,;nN])", lambda m: "\n" if m.group(1) in "nN" else m.group(1), value)+++def test_ics_escapes_folds_and_lists_attendees(world):+ resp = _get(world, f"/api/v1/recordings/{world['rec']}/events/ics")+ assert resp.status_code == 200+ lines = _unfold(resp.get_data(as_text=True))+ props = {}+ for line in lines:+ name_params, _, value = line.partition(":")+ props.setdefault(name_params.split(";")[0], []).append((name_params, value))+ assert _unescape(props["SUMMARY"][0][1]) == "Budget review, Q4; draft"+ assert _unescape(props["LOCATION"][0][1]) == "Room 4, Building B"+ description = _unescape(props["DESCRIPTION"][0][1])+ assert description.startswith("Bring the numbers.\nAnd the slides; all of them.")+ assert description.endswith("Attendees: Dana Lee, Kim")+ attendees = sorted(v for k, v in props["ATTENDEE"])+ assert attendees == ["mailto:[email protected]", "mailto:[email protected]", "mailto:[email protected]"]+ assert not any("example.com" in v for _, v in props["ATTENDEE"])+ assert any(k.startswith('ATTENDEE;CN="Priya Shah"') for k, _ in props["ATTENDEE"])+ assert props["DTSTAMP"][0][1].endswith("Z") and props["DTSTART"][0][1] == "20261009T150000"+ assert props["TRIGGER"][0][1] == "-PT30M"+++def test_extraction_keeps_the_wall_clock_time(world):+ from unittest.mock import MagicMock, patch+ import src.tasks.processing as proc+ reply = json.dumps({"events": [{"title": "Call", "start_datetime": "2026-11-02T09:30:00-05:00",+ "end_datetime": "2026-11-02T10:00:00Z"}]})+ with app.app_context():+ Event.query.filter_by(recording_id=world["rec"]).delete()+ r = db.session.get(Recording, world["rec"])+ r.transcription = "Speaker 1: let us meet on Monday at nine thirty."+ db.session.get(User, world["user"]).extract_events = True+ db.session.commit()+ completion = MagicMock(choices=[MagicMock(message=MagicMock(content=reply, reasoning=None))])+ with patch.object(proc, "client", MagicMock()), patch.object(proc, "call_llm_completion", return_value=completion), \+ patch("src.services.webhook_dispatch.emit_webhook_event"):+ proc.extract_events_from_transcript(world["rec"], r.transcription, r.summary or "")+ ev = Event.query.filter_by(recording_id=world["rec"]).one()+ assert ev.start_datetime == datetime(2026, 11, 2, 9, 30) and ev.end_datetime == datetime(2026, 11, 2, 10, 0)