Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
feat: opt-in email notification when a transcription finishes or fails (#386)
Murtaza Nasir763e73c5dde0
diff --git a/config/env.email.example b/config/env.email.exampleindex 80590f7d..625d0c99 100644--- a/config/env.email.example+++ b/config/env.email.example@@ -51,6 +51,19 @@ [email protected]# Default: SpeakrSMTP_FROM_NAME=Speakr+###############################################################################+# Links in Outgoing Email+###############################################################################++# External URL where users reach this Speakr instance, with no trailing path.+# Verification and password-reset mail is sent while handling a request, so it+# can work out its own address. Notification mail is sent from a background+# worker with no request to look at, so it cannot. Set this and a "finished+# transcribing" email carries a link straight to the recording; leave it unset+# and the same email is still sent, just without the link.+# Example: https://speakr.example.com+# APP_BASE_URL=+################################################################################ Provider-Specific Examples###############################################################################diff --git a/docs/admin-guide/email-setup.md b/docs/admin-guide/email-setup.mdindex 84871b21..8b42821c 100644--- a/docs/admin-guide/email-setup.md+++ b/docs/admin-guide/email-setup.md@@ -8,6 +8,7 @@ Email features in Speakr are completely opt-in. When configured, they provide:- **Email Verification**: Require new users to verify their email address before accessing the system- **Password Reset**: Allow users to reset forgotten passwords via email+- **Processing Notifications**: Let each user opt in to a message when one of their recordings finishes transcribing, or failsBoth features work independently of domain restrictions—you can use email verification even with open registration (`ALLOW_REGISTRATION=true`) and no domain restrictions.@@ -53,6 +54,38 @@ Restart Speakr after updating environment variables.| `SMTP_USE_SSL` | `false` | Use SSL encryption (port 465) || `SMTP_FROM_ADDRESS` | `[email protected]` | Email address shown in "From" field || `SMTP_FROM_NAME` | `Speakr` | Display name shown alongside from address |+| `APP_BASE_URL` | (none) | External URL of this instance, used for links in notification email |++### Processing Notifications++Once SMTP works, each user can turn on "Email me when a transcription finishes"+under Account, Preferences. It is off by default, so upgrading an existing+instance does not start mailing anyone. The message is sent when a transcription+completes and when one fails permanently. Summaries do not send mail, since a+summary is quick and follows a transcript the user has already been told about.++Two things suppress the mail regardless of the user's preference. SMTP has to be+configured, and the address has to be one Speakr can deliver to: an SSO account+whose provider withheld an address is given a synthetic `@placeholder.local` one,+and mailing that on every finished recording would bounce repeatedly and put the+sending domain's reputation at risk. The toggle is hidden for those accounts+rather than shown and quietly ignored.++Set `APP_BASE_URL` to the address your users reach Speakr on, with no trailing+path:++```bash+APP_BASE_URL=https://speakr.example.com+```++Verification and reset mail work out their own URL because they are sent while+handling a request. A notification is sent from a background worker, which has+no request to look at, so without this variable the mail goes out without a link+to the recording rather than with a broken one.++Note that each recording sends its own message, so a bulk upload of fifty files+produces fifty emails. The setting is most useful for long recordings the user+does not want to wait on.### Understanding the Two Verification Modesdiff --git a/docs/admin-guide/webhooks.md b/docs/admin-guide/webhooks.mdindex 6c0ad769..ab9093dc 100644--- a/docs/admin-guide/webhooks.md+++ b/docs/admin-guide/webhooks.md@@ -14,7 +14,7 @@ or programmatically via the `/api/v1/webhooks` API.|---|---|---|| `recording.created` | A recording row is created (upload arrived) | `recording_id`, `title`, `file_size`, `original_filename` || `recording.transcription.started` | Worker picks up a transcribe or reprocess-transcription job and the audio file is on disk | `recording_id`, `title` |-| `recording.transcription.completed` | Transcription job finished successfully | `recording_id`, `title`, `language`, `audio_duration_seconds`, `transcription_duration_seconds` |+| `recording.transcription.completed` | Transcription job finished successfully | `recording_id`, `title`, `audio_duration_seconds`, `transcription_duration_seconds` || `recording.transcription.failed` | Transcription failed permanently (retries exhausted) | `recording_id`, `title`, `error` || `recording.summary.completed` | Summary generated successfully | `recording_id`, `title`, `summarization_duration_seconds` || `recording.summary.failed` | Summary failed permanently | `recording_id`, `title`, `error` |@@ -48,8 +48,8 @@ Every delivery is a `POST` with a JSON body shaped like:"data": {"recording_id": 9173,"title": "Q3 planning",- "language": "en",- "audio_duration_seconds": 3624.7+ "audio_duration_seconds": 3624.7,+ "transcription_duration_seconds": 212}}```diff --git a/src/api/api_v1.py b/src/api/api_v1.pyindex a319d826..6cf0f7fe 100644--- a/src/api/api_v1.py+++ b/src/api/api_v1.py@@ -786,6 +786,7 @@ def get_current_user():'auto_summarization': bool(current_user.auto_summarization),'show_timestamps_simple_view': bool(current_user.show_timestamps_simple_view),'editor_autosave': bool(current_user.editor_autosave),+ 'notify_email_on_completion': bool(current_user.notify_email_on_completion),'diarize': bool(current_user.diarize),},'group_memberships': memberships,diff --git a/src/api/auth.py b/src/api/auth.pyindex 5216bc87..5b37f624 100644--- a/src/api/auth.py+++ b/src/api/auth.py@@ -35,6 +35,7 @@ from src.services.email import (is_email_verification_enabled,is_email_verification_required,is_smtp_configured,+ can_email_user,send_verification_email,send_password_reset_email,verify_email_token,@@ -147,6 +148,16 @@ def is_registration_domain_allowed(email: str) -> bool:return domain in allowed+def _email_notifications_available(user) -> bool:+ """Whether to offer this user the completion-email toggle (#386).++ Offering a switch that cannot do anything is worse than hiding it, so the+ account page asks the same question the sender will ask: is SMTP set up,+ and is this user's address one we can actually deliver to.+ """+ return can_email_user(user)++# --- Routes ---@auth_bp.route('/register', methods=['GET', 'POST'])@@ -609,6 +620,12 @@ def account():elif 'preferences_form' in request.form:current_user.show_timestamps_simple_view = 'show_timestamps_simple_view' in request.formcurrent_user.editor_autosave = 'editor_autosave' in request.form+ # Only honour the notification toggle when the form actually+ # rendered it. The checkbox is hidden when Speakr cannot mail this+ # user, and an absent checkbox must not silently clear a+ # preference they set while SMTP was working.+ if 'email_notifications_shown' in request.form:+ current_user.notify_email_on_completion = 'notify_email_on_completion' in request.form# Audio player position — only update if the field is# actually present in the submission. The Preferences tab# (which doesn't expose the radio) submits without this@@ -825,6 +842,7 @@ def account():has_password=bool(current_user.password),password_login_disabled=password_login_disabled,speaker_embeddings_enabled=connector_supports_speaker_embeddings,+ email_notifications_available=_email_notifications_available(current_user),contextual_labelling_available=contextual_labelling_available,auto_speaker_labelling=current_user.auto_speaker_labelling,auto_speaker_labelling_threshold=current_user.auto_speaker_labelling_threshold or 'medium',diff --git a/src/init_db.py b/src/init_db.pyindex 8d7fc14a..09595124 100644--- a/src/init_db.py+++ b/src/init_db.py@@ -356,6 +356,11 @@ def _run_migrations(app, engine):if add_column_if_not_exists(engine, 'user', 'default_naming_template_id', 'INTEGER'):app.logger.info("Added default_naming_template_id column to user table")+ # Email notification preference (#386). Defaults off, so an upgrade+ # never starts mailing anyone who did not ask for it.+ if add_column_if_not_exists(engine, 'user', 'notify_email_on_completion', 'BOOLEAN DEFAULT 0'):+ app.logger.info("Added notify_email_on_completion column to user table")+# Email verification fieldsemail_verified_added = add_column_if_not_exists(engine, 'user', 'email_verified', 'BOOLEAN DEFAULT 0')if email_verified_added:diff --git a/src/models/user.py b/src/models/user.pyindex 236c39ed..639041c7 100644--- a/src/models/user.py+++ b/src/models/user.py@@ -57,6 +57,11 @@ class User(db.Model, UserMixin):password_reset_token = db.Column(db.String(200), nullable=True, index=True)password_reset_sent_at = db.Column(db.DateTime, nullable=True)+ # Email notifications for finished processing (#386). Opt-in: mail nobody+ # asked for is worse than no mail at all, so this defaults off and the+ # sender additionally requires working SMTP and a deliverable address.+ notify_email_on_completion = db.Column(db.Boolean, default=False)+# Auto speaker labelling settingsauto_speaker_labelling = db.Column(db.Boolean, default=False) # Enable auto-labelling when voice confidence exceeds thresholdauto_speaker_labelling_threshold = db.Column(db.String(10), nullable=True, default='medium') # 'low', 'medium', 'high'diff --git a/src/services/email.py b/src/services/email.pyindex ca6766d9..8bd8dab8 100644--- a/src/services/email.py+++ b/src/services/email.py@@ -449,3 +449,190 @@ def can_resend_password_reset(user) -> tuple[bool, Optional[int]]:remaining = (cooldown - time_since_last).secondsreturn False, remaining+++# --- Processing notifications (#386) -------------------------------------+#+# Unlike verification and password reset, these are sent from a job-queue+# worker thread with no request context, so `url_for(_external=True)` is not+# available: it needs SERVER_NAME, which Speakr does not set. The deep link+# therefore comes from APP_BASE_URL, and when that is unset the mail is sent+# without a link rather than with a broken one.++# An SSO login whose provider withheld an address gets a synthetic one (see+# src/auth/sso.py). Mailing it would hard-bounce on every finished recording,+# which is a good way to get a sending domain blocked.+_UNDELIVERABLE_EMAIL_SUFFIXES = ('@placeholder.local',)+++def get_app_base_url() -> Optional[str]:+ """External base URL of this instance, e.g. https://speakr.example.com."""+ base = (os.environ.get('APP_BASE_URL') or '').split('#')[0].strip()+ return base.rstrip('/') or None+++def _recording_url(recording_id: int) -> Optional[str]:+ base = get_app_base_url()+ return f'{base}/recordings/{recording_id}' if base else None+++def can_email_user(user) -> bool:+ """Whether Speakr is able to send this user mail at all.++ Kept separate from the user's preference so that "they asked for it" and+ "we can actually deliver it" stay distinct in the logs.+ """+ if not is_smtp_configured():+ return False+ email = (getattr(user, 'email', '') or '').strip().lower()+ if not email or '@' not in email:+ return False+ return not email.endswith(_UNDELIVERABLE_EMAIL_SUFFIXES)+++def wants_completion_email(user) -> bool:+ """Whether this user has opted in and can be reached."""+ return bool(getattr(user, 'notify_email_on_completion', False)) and can_email_user(user)+++def _button_html(url: str, label: str) -> str:+ if not url:+ return ''+ return f"""+<div style="text-align: center; margin: 32px 0;">+ <a href="{url}" style="display: inline-block; background-color: #2563eb; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-weight: 600; font-size: 16px;">{label}</a>+</div>+"""+++def _detail_rows_html(rows) -> str:+ """A small label/value table, matching the body type scale."""+ cells = ''.join(f"""+ <tr>+ <td style="padding: 6px 16px 6px 0; color: #6b7280; font-size: 14px; white-space: nowrap; vertical-align: top;">{label}</td>+ <td style="padding: 6px 0; color: #374151; font-size: 14px;">{value}</td>+ </tr>""" for label, value in rows)+ return f"""+<table role="presentation" cellspacing="0" cellpadding="0" border="0" style="margin: 24px 0; background-color: #f8f9fa; border-radius: 8px; padding: 8px 16px;">+ {cells}+</table>+"""+++def _format_duration(seconds) -> Optional[str]:+ try:+ total = int(round(float(seconds)))+ except (TypeError, ValueError):+ return None+ if total <= 0:+ return None+ hours, rem = divmod(total, 3600)+ minutes, secs = divmod(rem, 60)+ if hours:+ return f'{hours}h {minutes}m'+ if minutes:+ return f'{minutes}m {secs}s'+ return f'{secs}s'+++def send_transcription_complete_email(user, recording) -> bool:+ """Tell a user their recording finished transcribing.++ Returns True only if a message was actually handed to the SMTP server.+ """+ if not wants_completion_email(user):+ return False++ title = (getattr(recording, 'title', None) or 'Untitled recording').strip()+ url = _recording_url(recording.id)+ subject = f'Transcription ready: {title}'++ rows = [('Recording', title)]+ duration = _format_duration(getattr(recording, 'audio_duration_seconds', None))+ if duration:+ rows.append(('Length', duration))+ took = _format_duration(getattr(recording, 'transcription_duration_seconds', None))+ if took:+ rows.append(('Transcribed in', took))++ content_html = f"""+<h2 style="color: #1f2937; margin: 0 0 24px 0; font-size: 24px; font-weight: 600;">Your transcription is ready</h2>++<p style="color: #374151; margin: 0 0 16px 0; font-size: 16px;">Hi {user.username},</p>++<p style="color: #374151; margin: 0 0 8px 0; font-size: 16px;">+ Speakr has finished transcribing <strong>{title}</strong>. It is waiting for you in your library.+</p>++{_detail_rows_html(rows)}+{_button_html(url, 'Open recording')}++<div style="margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb;">+ <p style="color: #9ca3af; font-size: 13px; margin: 0;">+ You are receiving this because you turned on email notifications in your Speakr account settings. You can turn them off there at any time.+ </p>+</div>+"""++ detail_lines = '\n'.join(f'{label}: {value}' for label, value in rows)+ link_line = f'\nOpen it here: {url}\n' if url else ''+ content_text = f"""Hi {user.username},++Speakr has finished transcribing "{title}". It is waiting for you in your library.++{detail_lines}+{link_line}+You are receiving this because you turned on email notifications in your Speakr+account settings. You can turn them off there at any time."""++ html_body, text_body = _get_email_template(content_html, content_text, subject)+ return _send_email(user.email, subject, html_body, text_body)+++def send_transcription_failed_email(user, recording, error: str = None) -> bool:+ """Tell a user their recording could not be transcribed."""+ if not wants_completion_email(user):+ return False++ title = (getattr(recording, 'title', None) or 'Untitled recording').strip()+ url = _recording_url(recording.id)+ subject = f'Transcription failed: {title}'++ # The worker's error text can carry an upstream URL or key, so it is+ # summarised rather than forwarded in full.+ reason = (error or '').strip().splitlines()[0][:200] if error else ''+ reason_html = f"""+<p style="color: #6b7280; font-size: 14px; margin: 0 0 24px 0; padding: 12px 16px; background-color: #f8f9fa; border-left: 3px solid #d1d5db; border-radius: 4px;">{reason}</p>+""" if reason else ''++ content_html = f"""+<h2 style="color: #1f2937; margin: 0 0 24px 0; font-size: 24px; font-weight: 600;">A transcription did not finish</h2>++<p style="color: #374151; margin: 0 0 16px 0; font-size: 16px;">Hi {user.username},</p>++<p style="color: #374151; margin: 0 0 24px 0; font-size: 16px;">+ Speakr was not able to transcribe <strong>{title}</strong>. The recording itself is safe and you can retry it from your library.+</p>++{reason_html}+{_button_html(url, 'Open recording')}++<div style="margin-top: 32px; padding-top: 24px; border-top: 1px solid #e5e7eb;">+ <p style="color: #9ca3af; font-size: 13px; margin: 0;">+ You are receiving this because you turned on email notifications in your Speakr account settings. You can turn them off there at any time.+ </p>+</div>+"""++ reason_text = f'\nReason: {reason}\n' if reason else ''+ link_line = f'\nOpen it here: {url}\n' if url else ''+ content_text = f"""Hi {user.username},++Speakr was not able to transcribe "{title}". The recording itself is safe and you+can retry it from your library.+{reason_text}{link_line}+You are receiving this because you turned on email notifications in your Speakr+account settings. You can turn them off there at any time."""++ html_body, text_body = _get_email_template(content_html, content_text, subject)+ return _send_email(user.email, subject, html_body, text_body)diff --git a/src/services/job_queue.py b/src/services/job_queue.pyindex f18d9d51..40c8c096 100644--- a/src/services/job_queue.py+++ b/src/services/job_queue.py@@ -366,6 +366,14 @@ class FairJobQueue:except Exception as e:logger.warning(f"Webhook emit on job {job_id} completion failed: {e}")+ # Email notification (#386), independent of webhooks so a user+ # can have one without the other. Also best-effort: an SMTP+ # server that is down must not fail a completed job.+ try:+ self._emit_completion_email(job_type, recording_id)+ except Exception as e:+ logger.warning(f"Completion email for job {job_id} failed: {e}")+except Exception as e:error_str = str(e)logger.error(f"Job {job_id} failed: {e}", exc_info=True)@@ -416,6 +424,11 @@ class FairJobQueue:except Exception as e:logger.warning(f"Webhook emit on job {job_id} failure failed: {e}")+ try:+ self._emit_failure_email(job_type, recording_id, error_str)+ except Exception as e:+ logger.warning(f"Failure email for job {job_id} failed: {e}")+db.session.commit()def _run_transcription(self, job, recording, params):@@ -824,13 +837,20 @@ class FairJobQueue:recording = db.session.get(Recording, recording_id)if not recording:return+ # audio_duration_seconds read `recording.audio_duration`, which is+ # not a column on Recording, so getattr's default made it None and+ # the None-filter below dropped the key. Subscribers have never+ # received it despite it being documented since #275. `language`+ # was dropped outright for the same reason: there is no per-recording+ # language anywhere. The nearest thing, User.transcription_language,+ # is a live preference rather than a property of this recording, so+ # sending it would report today's setting for last month's audio.data = {'recording_id': recording.id,'title': recording.title,- 'language': getattr(recording, 'transcription_language', None),- 'audio_duration_seconds': getattr(recording, 'audio_duration', None),- 'transcription_duration_seconds': getattr(recording, 'transcription_duration_seconds', None),- 'summarization_duration_seconds': getattr(recording, 'summarization_duration_seconds', None),+ 'audio_duration_seconds': recording.audio_duration_seconds,+ 'transcription_duration_seconds': recording.transcription_duration_seconds,+ 'summarization_duration_seconds': recording.summarization_duration_seconds,}emit_webhook_event(user_id=recording.user_id,@@ -838,6 +858,41 @@ class FairJobQueue:data={k: v for k, v in data.items() if v is not None},)+ # Only transcription reaches the inbox. A summary finishing is not an+ # event a user waits on the way they wait on a transcript, and mailing+ # both would double the volume for no extra signal.+ _EMAIL_JOB_TYPES = ('transcribe', 'reprocess_transcription')++ def _load_recording_and_owner(self, recording_id: int):+ from src.database import db+ from src.models import Recording, User+ recording = db.session.get(Recording, recording_id)+ if not recording:+ return None, None+ return recording, db.session.get(User, recording.user_id)++ def _emit_completion_email(self, job_type: str, recording_id: int):+ if job_type not in self._EMAIL_JOB_TYPES:+ return+ with self._app_context():+ from src.services.email import send_transcription_complete_email+ recording, owner = self._load_recording_and_owner(recording_id)+ if not recording or not owner:+ return+ if send_transcription_complete_email(owner, recording):+ logger.info(f"Sent completion email for recording {recording_id} to user {owner.id}")++ def _emit_failure_email(self, job_type: str, recording_id: int, error: str):+ if job_type not in self._EMAIL_JOB_TYPES:+ return+ with self._app_context():+ from src.services.email import send_transcription_failed_email+ recording, owner = self._load_recording_and_owner(recording_id)+ if not recording or not owner:+ return+ if send_transcription_failed_email(owner, recording, error):+ logger.info(f"Sent failure email for recording {recording_id} to user {owner.id}")+def _emit_failure_webhook(self, job_type: str, recording_id: int, error: str):event_type = self._FAILURE_EVENT_MAP.get(job_type)if not event_type:diff --git a/static/locales/de.json b/static/locales/de.jsonindex cb54c076..0aa9bca3 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -1822,6 +1822,9 @@"filenameDateRegex": "Eigenes Muster (regulärer Ausdruck)","filenameDateRegexHelp": "Muss die benannten Gruppen year, month und day enthalten; hour und minute sind optional. Beispiel: (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})","filenameDatesSection": "Aufnahmedatum aus dem Dateinamen",+ "notifications": "Benachrichtigungen",+ "notifyEmailOnCompletion": "E-Mail senden, wenn eine Transkription fertig ist",+ "notifyEmailOnCompletionHelp": "Sendet eine Nachricht an Ihre Kontoadresse, wenn eine Aufnahme fertig transkribiert wurde oder wenn sie fehlschlägt. Zusammenfassungen sind nicht enthalten. Nützlich für lange Aufnahmen, auf die Sie nicht warten möchten; weniger nützlich, wenn Sie viele Dateien auf einmal hochladen, da jede eine eigene Nachricht sendet.","parseFilenameDates": "Aufnahmedatum aus dem Dateinamen lesen","parseFilenameDatesHelp": "Wenn ein hochgeladener Dateiname ein Datum enthält (z. B. 20260716_meeting.mp3), wird es als Aufnahmedatum verwendet statt der Zeitstempel der Datei. Dateien ohne passendes Datum behalten das bisherige Verhalten.","showTimestampsSimpleView": "Zeitstempel in der einfachen Ansicht anzeigen",diff --git a/static/locales/en.json b/static/locales/en.jsonindex cff200cd..e11a246b 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -1304,6 +1304,9 @@"filenameDateRegex": "Custom pattern (regular expression)","filenameDateRegexHelp": "Must contain named groups year, month and day; hour and minute are optional. Example: (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})","filenameDatesSection": "Meeting date from filename",+ "notifications": "Notifications",+ "notifyEmailOnCompletion": "Email me when a transcription finishes",+ "notifyEmailOnCompletionHelp": "Sends a message to your account address when a recording finishes transcribing, and when one fails. Summaries are not included. Useful for long recordings you do not want to sit and wait for; less so if you upload many files at once, since each one sends its own message.","parseFilenameDates": "Parse meeting date from filename","parseFilenameDatesHelp": "When an uploaded filename contains a date (for example 20260716_meeting.mp3), use it as the meeting date instead of the file's timestamps. Files without a matching date keep the current behaviour.","showTimestampsSimpleView": "Show timestamps in simple view",diff --git a/static/locales/es.json b/static/locales/es.jsonindex 18bec5a7..6a0cf693 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -1822,6 +1822,9 @@"filenameDateRegex": "Patrón personalizado (expresión regular)","filenameDateRegexHelp": "Debe contener los grupos con nombre year, month y day; hour y minute son opcionales. Ejemplo: (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})","filenameDatesSection": "Fecha de reunión desde el nombre de archivo",+ "notifications": "Notificaciones",+ "notifyEmailOnCompletion": "Enviarme un correo cuando termine una transcripción",+ "notifyEmailOnCompletionHelp": "Envía un mensaje a la dirección de su cuenta cuando una grabación termina de transcribirse y cuando falla. No incluye los resúmenes. Resulta útil para grabaciones largas que no quiere esperar; menos si sube muchos archivos a la vez, ya que cada uno envía su propio mensaje.","parseFilenameDates": "Extraer la fecha de reunión del nombre de archivo","parseFilenameDatesHelp": "Cuando un nombre de archivo subido contiene una fecha (por ejemplo 20260716_meeting.mp3), se usa como fecha de reunión en lugar de las marcas de tiempo del archivo. Los archivos sin fecha coincidente mantienen el comportamiento actual.","showTimestampsSimpleView": "Mostrar marcas de tiempo en la vista simple",diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex 84091044..8cd15d16 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -1822,6 +1822,9 @@"filenameDateRegex": "Motif personnalisé (expression régulière)","filenameDateRegexHelp": "Doit contenir les groupes nommés year, month et day ; hour et minute sont facultatifs. Exemple : (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})","filenameDatesSection": "Date de réunion depuis le nom de fichier",+ "notifications": "Notifications",+ "notifyEmailOnCompletion": "M'envoyer un e-mail à la fin d'une transcription",+ "notifyEmailOnCompletionHelp": "Envoie un message à l'adresse de votre compte lorsqu'un enregistrement finit d'être transcrit, ainsi qu'en cas d'échec. Les résumés ne sont pas inclus. Utile pour les longs enregistrements que vous ne souhaitez pas attendre ; moins si vous importez de nombreux fichiers à la fois, chacun envoyant son propre message.","parseFilenameDates": "Extraire la date de réunion du nom de fichier","parseFilenameDatesHelp": "Lorsqu'un nom de fichier importé contient une date (par exemple 20260716_meeting.mp3), elle est utilisée comme date de réunion à la place des horodatages du fichier. Les fichiers sans date correspondante conservent le comportement actuel.","showTimestampsSimpleView": "Afficher les horodatages dans la vue simple",diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.jsonindex fcd838ea..d1bda3d0 100644--- a/static/locales/pt-BR.json+++ b/static/locales/pt-BR.json@@ -1801,6 +1801,9 @@"filenameDateRegex": "Padrão personalizado (expressão regular)","filenameDateRegexHelp": "Deve conter os grupos nomeados year, month e day; hour e minute são opcionais. Exemplo: (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})","filenameDatesSection": "Data da reunião a partir do nome do arquivo",+ "notifications": "Notificações",+ "notifyEmailOnCompletion": "Enviar um e-mail quando uma transcrição terminar",+ "notifyEmailOnCompletionHelp": "Envia uma mensagem para o endereço da sua conta quando uma gravação termina de ser transcrita e quando falha. Os resumos não são incluídos. Útil para gravações longas que você não quer esperar; menos se você enviar muitos arquivos de uma vez, já que cada um envia a própria mensagem.","parseFilenameDates": "Extrair a data da reunião do nome do arquivo","parseFilenameDatesHelp": "Quando um nome de arquivo enviado contém uma data (por exemplo 20260716_meeting.mp3), ela é usada como data da reunião em vez dos carimbos de data do arquivo. Arquivos sem data correspondente mantêm o comportamento atual.","showTimestampsSimpleView": "Mostrar marcações de tempo na visualização simples",diff --git a/static/locales/ru.json b/static/locales/ru.jsonindex 369f7d5c..1516db17 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -1822,6 +1822,9 @@"filenameDateRegex": "Свой шаблон (регулярное выражение)","filenameDateRegexHelp": "Должно содержать именованные группы year, month и day; hour и minute необязательны. Пример: (?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})","filenameDatesSection": "Дата встречи из имени файла",+ "notifications": "Уведомления",+ "notifyEmailOnCompletion": "Присылать письмо, когда расшифровка завершена",+ "notifyEmailOnCompletionHelp": "Отправляет сообщение на адрес вашей учётной записи, когда расшифровка записи завершена, а также когда она не удалась. Сводки не включаются. Полезно для длинных записей, которых вы не хотите ждать; менее полезно при загрузке многих файлов сразу, так как каждый отправляет собственное сообщение.","parseFilenameDates": "Извлекать дату встречи из имени файла","parseFilenameDatesHelp": "Если имя загруженного файла содержит дату (например, 20260716_meeting.mp3), она используется как дата встречи вместо временных меток файла. Файлы без подходящей даты сохраняют текущее поведение.","showTimestampsSimpleView": "Показывать временные метки в простом виде",diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 3414eb5b..888d0369 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -1822,6 +1822,9 @@"filenameDateRegex": "自定义模式(正则表达式)","filenameDateRegexHelp": "必须包含命名分组 year、month 和 day;hour 和 minute 可选。示例:(?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})","filenameDatesSection": "从文件名解析会议日期",+ "notifications": "通知",+ "notifyEmailOnCompletion": "转录完成时给我发送邮件",+ "notifyEmailOnCompletionHelp": "当一段录音转录完成或失败时,向您的账户邮箱发送一封邮件。不包含摘要。适用于您不想一直等待的长录音;如果一次上传大量文件则不太适合,因为每个文件都会单独发送一封邮件。","parseFilenameDates": "从文件名解析会议日期","parseFilenameDatesHelp": "当上传的文件名包含日期(例如 20260716_meeting.mp3)时,将其用作会议日期,而不是文件的时间戳。没有匹配日期的文件保持当前行为。","showTimestampsSimpleView": "在简单视图中显示时间戳",diff --git a/templates/account.html b/templates/account.htmlindex 729f79dc..c0c49f40 100644--- a/templates/account.html+++ b/templates/account.html@@ -1105,6 +1105,18 @@</span></label>+ {% if email_notifications_available %}+ <h3 class="text-sm font-semibold text-[var(--text-secondary)] uppercase tracking-wide pt-4" data-i18n="preferences.notifications">Notifications</h3>+ <input type="hidden" name="email_notifications_shown" value="1">+ <label class="flex items-start gap-3 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-md cursor-pointer hover:bg-[var(--bg-accent-hover)]">+ <input type="checkbox" id="prefNotifyEmailOnCompletion" name="notify_email_on_completion" {% if current_user.notify_email_on_completion %}checked{% endif %} class="mt-1 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)] bg-[var(--bg-input)]">+ <span class="flex-1">+ <span class="block text-sm font-medium text-[var(--text-primary)]" data-i18n="preferences.notifyEmailOnCompletion">Email me when a transcription finishes</span>+ <span class="block text-xs text-[var(--text-muted)] mt-0.5" data-i18n="preferences.notifyEmailOnCompletionHelp">Sends a message to your account address when a recording finishes transcribing, and when one fails. Summaries are not included. Useful for long recordings you do not want to sit and wait for; less so if you upload many files at once, since each one sends its own message.</span>+ </span>+ </label>+ {% endif %}+<h3 class="text-sm font-semibold text-[var(--text-secondary)] uppercase tracking-wide pt-4" data-i18n="preferences.transcriptEditor">Transcript editor</h3><label class="flex items-start gap-3 p-3 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-md cursor-pointer hover:bg-[var(--bg-accent-hover)]"><input type="checkbox" id="prefEditorAutosave" name="editor_autosave" {% if current_user.editor_autosave %}checked{% endif %} class="mt-1 h-4 w-4 text-[var(--text-accent)] border-[var(--border-secondary)] rounded focus:ring-[var(--border-focus)] bg-[var(--bg-input)]">diff --git a/tests/test_completion_email.py b/tests/test_completion_email.pynew file mode 100644index 00000000..cdf977e7--- /dev/null+++ b/tests/test_completion_email.py@@ -0,0 +1,224 @@+"""Email notifications when a transcription finishes (#386).++The sender has three gates that must all pass: the user asked for it, Speakr+can actually deliver to them, and the job that finished was a transcription.+Each is tested for both directions, because the failure that matters here is+mailing somebody who did not ask rather than failing to mail somebody who did.+"""++import os+from unittest.mock import patch++import pytest++from src.app import app+from src.database import db+from src.models import User, Recording+from src.services import email as email_service+++def smtp_configured():+ """Pretend SMTP is set up without touching a real server."""+ with patch.object(email_service, 'is_smtp_configured', return_value=True):+ yield+++def user_factory():+ created = []++ def _make(**kwargs):+ with app.app_context():+ suffix = len(created)+ user = User(+ username=kwargs.pop('username', f'notify_user_{suffix}_{os.getpid()}'),+ email=kwargs.pop('email', f'notify{suffix}_{os.getpid()}@example.com'),+ password='x',+ **kwargs,+ )+ db.session.add(user)+ db.session.commit()+ created.append(user.id)+ return user++ yield _make++ with app.app_context():+ for uid in created:+ u = db.session.get(User, uid)+ if u:+ db.session.delete(u)+ db.session.commit()+++def _recording(user_id, **kwargs):+ return Recording(+ user_id=user_id,+ title=kwargs.pop('title', 'Quarterly planning call'),+ audio_path='/tmp/does-not-matter.wav',+ **kwargs,+ )+++# --- the "can we reach them" gate ---------------------------------------++def test_no_smtp_means_no_mail(user_factory):+ user = user_factory(notify_email_on_completion=True)+ with app.app_context(), patch.object(email_service, 'is_smtp_configured', return_value=False):+ assert email_service.can_email_user(user) is False+ assert email_service.wants_completion_email(user) is False+++def test_sso_placeholder_address_is_never_mailed(user_factory, smtp_configured):+ """An SSO login whose provider withheld an address gets a synthetic one.++ Mailing it would hard-bounce on every finished recording, which is how a+ sending domain gets blocked. See issue #377 for where these come from.+ """+ user = user_factory(email='[email protected]', notify_email_on_completion=True)+ with app.app_context():+ assert email_service.can_email_user(user) is False+ assert email_service.wants_completion_email(user) is False+++def test_deliverable_address_with_opt_in_is_mailable(user_factory, smtp_configured):+ user = user_factory(notify_email_on_completion=True)+ with app.app_context():+ assert email_service.wants_completion_email(user) is True+++# --- the "did they ask for it" gate -------------------------------------++def test_opt_out_is_the_default(user_factory, smtp_configured):+ """The column defaults off, so an upgrade mails nobody."""+ user = user_factory()+ with app.app_context():+ assert bool(user.notify_email_on_completion) is False+ assert email_service.wants_completion_email(user) is False+++def test_completion_mail_is_not_sent_to_a_user_who_opted_out(user_factory, smtp_configured):+ user = user_factory(notify_email_on_completion=False)+ with app.app_context(), patch.object(email_service, '_send_email') as send:+ sent = email_service.send_transcription_complete_email(user, _recording(user.id))+ assert sent is False+ send.assert_not_called()+++# --- content -------------------------------------------------------------++def test_completion_mail_addresses_the_user_and_names_the_recording(user_factory, smtp_configured):+ user = user_factory(notify_email_on_completion=True)+ with app.app_context(), patch.object(email_service, '_send_email', return_value=True) as send:+ rec = _recording(user.id, title='Quarterly planning call')+ rec.id = 4242+ assert email_service.send_transcription_complete_email(user, rec) is True++ to_email, subject, html, text = send.call_args[0]+ assert to_email == user.email+ assert 'Quarterly planning call' in subject+ assert 'Quarterly planning call' in html+ assert 'Quarterly planning call' in text+ assert user.username in html and user.username in text+ # Both alternatives must carry the opt-out route, or the mail is spam.+ assert 'account settings' in html and 'account settings' in text+++def test_link_is_omitted_rather_than_broken_without_a_base_url(user_factory, smtp_configured):+ """No APP_BASE_URL means no deep link. A wrong link is worse than none."""+ user = user_factory(notify_email_on_completion=True)+ with app.app_context(), patch.dict(os.environ, {'APP_BASE_URL': ''}, clear=False), \+ patch.object(email_service, '_send_email', return_value=True) as send:+ rec = _recording(user.id)+ rec.id = 7+ email_service.send_transcription_complete_email(user, rec)+ _, _, html, text = send.call_args[0]+ assert '/recordings/7' not in html+ assert 'Open recording' not in html+ assert 'Open it here' not in text+++def test_base_url_produces_a_deep_link_to_the_recording(user_factory, smtp_configured):+ user = user_factory(notify_email_on_completion=True)+ with app.app_context(), \+ patch.dict(os.environ, {'APP_BASE_URL': 'https://speakr.example.com/'}, clear=False), \+ patch.object(email_service, '_send_email', return_value=True) as send:+ rec = _recording(user.id)+ rec.id = 7+ email_service.send_transcription_complete_email(user, rec)+ _, _, html, text = send.call_args[0]+ # Trailing slash on the configured base must not double up.+ assert 'https://speakr.example.com/recordings/7' in html+ assert 'https://speakr.example.com/recordings/7' in text+ assert '//recordings' not in html+++def test_failure_mail_summarises_the_error_without_forwarding_it_whole(user_factory, smtp_configured):+ """Worker errors can carry an upstream URL or key, so only the first line+ goes out, truncated."""+ user = user_factory(notify_email_on_completion=True)+ with app.app_context(), patch.object(email_service, '_send_email', return_value=True) as send:+ rec = _recording(user.id)+ rec.id = 9+ error = 'Connection refused to http://internal:9000\nTraceback...\nsecret=abcdef'+ assert email_service.send_transcription_failed_email(user, rec, error) is True+ _, subject, html, text = send.call_args[0]+ assert 'failed' in subject.lower()+ assert 'Connection refused' in html+ assert 'secret=abcdef' not in html+ assert 'Traceback' not in html+ assert 'secret=abcdef' not in text+++def test_a_very_long_error_is_truncated(user_factory, smtp_configured):+ user = user_factory(notify_email_on_completion=True)+ with app.app_context(), patch.object(email_service, '_send_email', return_value=True) as send:+ rec = _recording(user.id)+ rec.id = 9+ email_service.send_transcription_failed_email(user, rec, 'x' * 5000)+ _, _, html, _ = send.call_args[0]+ assert 'x' * 201 not in html+++def test_duration_is_rendered_for_humans():+ assert email_service._format_duration(45) == '45s'+ assert email_service._format_duration(125) == '2m 5s'+ assert email_service._format_duration(3725) == '1h 2m'+ # Absent or nonsensical values drop the row rather than printing "None".+ assert email_service._format_duration(None) is None+ assert email_service._format_duration(0) is None+ assert email_service._format_duration('not a number') is None+++def test_a_recording_without_a_title_still_produces_a_sane_subject(user_factory, smtp_configured):+ user = user_factory(notify_email_on_completion=True)+ with app.app_context(), patch.object(email_service, '_send_email', return_value=True) as send:+ rec = _recording(user.id, title=None)+ rec.id = 11+ email_service.send_transcription_complete_email(user, rec)+ _, subject, _, _ = send.call_args[0]+ assert 'None' not in subject+ assert 'Untitled recording' in subject+++# --- the "which job" gate ------------------------------------------------+[email protected]('job_type,should_mail', [+ ('transcribe', True),+ ('reprocess_transcription', True),+ ('summarize', False),+ ('reprocess_summary', False),+ ('stitch', False),+])+def test_only_transcription_jobs_reach_the_inbox(job_type, should_mail):+ from src.services.job_queue import job_queue+ with app.app_context(), patch('src.services.email.send_transcription_complete_email') as send:+ job_queue.init_app(app)+ with patch.object(job_queue, '_load_recording_and_owner', return_value=(None, None)):+ job_queue._emit_completion_email(job_type, 1)+ # A non-transcription job must return before it even looks the+ # recording up, so the send is unreachable either way; what this+ # pins is that summaries never acquire a mail path by accident.+ assert send.call_count == 0+ assert (job_type in job_queue._EMAIL_JOB_TYPES) is should_maildiff --git a/tests/test_webhooks.py b/tests/test_webhooks.pyindex 4ddaffe6..7e48a1d5 100644--- a/tests/test_webhooks.py+++ b/tests/test_webhooks.py@@ -1194,3 +1194,43 @@ def teardown_module(module):db.session.delete(w)db.session.delete(u)db.session.commit()+++def test_completion_payload_carries_the_documented_duration_fields():+ """The completion payload promised `audio_duration_seconds` from #275 but+ read `recording.audio_duration`, which is not a column. getattr's default+ made it None and the None-filter dropped the key, so no subscriber has+ ever received it. This pins the real attribute names against the model.+ """+ from unittest.mock import patch+ from src.app import app+ from src.models import Recording+ from src.services.job_queue import job_queue++ model_columns = {c.name for c in Recording.__table__.columns}+ for field in ('audio_duration_seconds', 'transcription_duration_seconds',+ 'summarization_duration_seconds'):+ assert field in model_columns, f'{field} is not a Recording column'++ class _Rec:+ id = 5150+ user_id = 7+ title = 'Q3 planning'+ audio_duration_seconds = 3624.7+ transcription_duration_seconds = 212+ summarization_duration_seconds = None++ with app.app_context():+ job_queue.init_app(app)+ with patch('src.services.webhook_dispatch.emit_webhook_event') as emit, \+ patch('src.database.db.session.get', return_value=_Rec()):+ job_queue._emit_completion_webhook('transcribe', 5150)++ assert emit.call_count == 1+ data = emit.call_args.kwargs['data']+ assert data['audio_duration_seconds'] == 3624.7+ assert data['transcription_duration_seconds'] == 212+ # None-valued keys are still filtered out.+ assert 'summarization_duration_seconds' not in data+ # `language` was removed: there is no per-recording language to send.+ assert 'language' not in data