Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Keep non-ASCII titles in the transcript download filename
Ceasycf748f6cb489
diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 769a1df7..cf7e83f0 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -19,6 +19,7 @@ from werkzeug.utils import secure_filenamefrom werkzeug.exceptions import RequestEntityTooLargefrom sqlalchemy import selectfrom email.utils import encode_rfc2231+from urllib.parse import quotefrom src.database import dbfrom src.models import *@@ -327,9 +328,21 @@ def download_transcript_with_template(recording_id):else:# Plain text transcriptionfilename = f"{recording.title or 'transcript'}.{ext}"- filename = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', filename)+ # Strip only what is illegal in a filename; keep non-ASCII titles intact+ # and advertise them through RFC 5987 filename* (same approach as the+ # summary/chat/notes downloads below).+ filename = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '', filename)+ filename = re.sub(r'\s+', ' ', filename).strip() or f'transcript-{recording_id}.{ext}'response.headers['Content-Type'] = content_type- response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'+ try:+ filename.encode('ascii')+ response.headers['Content-Disposition'] = f'attachment; filename="{filename}"'+ except UnicodeEncodeError:+ ascii_fallback = f'transcript-{recording_id}.{ext}'+ response.headers['Content-Disposition'] = (+ f'attachment; filename="{ascii_fallback}"; '+ + "filename*=UTF-8''" + quote(filename, safe='')+ )return responsediff --git a/static/js/modules/composables/chat.js b/static/js/modules/composables/chat.jsindex 47dbe87e..947db048 100644--- a/static/js/modules/composables/chat.js+++ b/static/js/modules/composables/chat.js@@ -3,6 +3,8 @@* Handles AI chat functionality with streaming responses*/+import { filenameFromContentDisposition } from '../utils/content-disposition.js';+export function useChat(state, utils) {const {showChat, isChatMaximized, chatMessages, chatInput,@@ -297,19 +299,7 @@ export function useChat(state, utils) {a.href = url;const contentDisposition = response.headers.get('Content-Disposition');- let filename = 'chat.docx';- if (contentDisposition) {- const utf8Match = /filename\*=utf-8''(.+)/.exec(contentDisposition);- if (utf8Match) {- filename = decodeURIComponent(utf8Match[1]);- } else {- const regularMatch = /filename="(.+)"/.exec(contentDisposition);- if (regularMatch) {- filename = regularMatch[1];- }- }- }- a.download = filename;+ a.download = filenameFromContentDisposition(contentDisposition, 'chat.docx');document.body.appendChild(a);a.click();diff --git a/static/js/modules/composables/ui.js b/static/js/modules/composables/ui.jsindex d73340b7..09c61173 100644--- a/static/js/modules/composables/ui.js+++ b/static/js/modules/composables/ui.js@@ -3,6 +3,8 @@* Handles dark mode, color schemes, sidebar, and other UI state*/+import { filenameFromContentDisposition } from '../utils/content-disposition.js';+export function useUI(state, utils, processedTranscription) {const {isDarkMode, currentColorScheme, colorSchemes, isSidebarCollapsed,@@ -1602,19 +1604,7 @@ export function useUI(state, utils, processedTranscription) {a.href = url;const contentDisposition = response.headers.get('Content-Disposition');- let filename = 'summary.docx';- if (contentDisposition) {- const utf8Match = /filename\*=utf-8''(.+)/.exec(contentDisposition);- if (utf8Match) {- filename = decodeURIComponent(utf8Match[1]);- } else {- const regularMatch = /filename="(.+)"/.exec(contentDisposition);- if (regularMatch) {- filename = regularMatch[1];- }- }- }- a.download = filename;+ a.download = filenameFromContentDisposition(contentDisposition, 'summary.docx');document.body.appendChild(a);a.click();@@ -1769,13 +1759,7 @@ export function useUI(state, utils, processedTranscription) {const blob = await response.blob();const contentDisposition = response.headers.get('content-disposition');- let filename = `transcript.${fmt}`;- if (contentDisposition) {- const matches = contentDisposition.match(/filename="([^"]+)"/);- if (matches && matches[1]) {- filename = matches[1];- }- }+ const filename = filenameFromContentDisposition(contentDisposition, `transcript.${fmt}`);const downloadUrl = URL.createObjectURL(blob);const a = document.createElement('a');@@ -1810,13 +1794,7 @@ export function useUI(state, utils, processedTranscription) {const blob = await response.blob();const contentDisposition = response.headers.get('content-disposition');- let filename = `transcript.${fmt}`;- if (contentDisposition) {- const matches = contentDisposition.match(/filename="([^"]+)"/);- if (matches && matches[1]) {- filename = matches[1];- }- }+ const filename = filenameFromContentDisposition(contentDisposition, `transcript.${fmt}`);const downloadUrl = URL.createObjectURL(blob);const a = document.createElement('a');diff --git a/static/js/modules/utils/content-disposition.js b/static/js/modules/utils/content-disposition.jsnew file mode 100644index 00000000..783e929b--- /dev/null+++ b/static/js/modules/utils/content-disposition.js@@ -0,0 +1,38 @@+/**+ * Content-Disposition helpers.+ *+ * Downloads that go through fetch() + blob have to pull the filename out of the+ * header themselves. Servers send non-ASCII names as RFC 5987 `filename*`+ * (percent-encoded UTF-8), usually next to an ASCII-only `filename=` fallback,+ * so `filename*` has to be preferred or unicode titles silently degrade to the+ * fallback.+ */++/**+ * Extract the download filename from a Content-Disposition header.+ *+ * @param {string|null|undefined} header - raw Content-Disposition value+ * @param {string} fallback - name to use when the header carries none+ * @returns {string} the filename to hand to `a.download`+ */+export function filenameFromContentDisposition(header, fallback) {+ if (!header) return fallback;++ const utf8Match = /filename\*=\s*UTF-8''([^;]+)/i.exec(header);+ if (utf8Match) {+ try {+ const decoded = decodeURIComponent(utf8Match[1].trim());+ if (decoded) return decoded;+ } catch (e) {+ // Malformed percent-encoding: fall through to the ASCII parameter.+ }+ }++ const asciiMatch = /filename="([^"]+)"/.exec(header);+ if (asciiMatch && asciiMatch[1]) return asciiMatch[1];++ const bareMatch = /filename=([^;"\s]+)/.exec(header);+ if (bareMatch && bareMatch[1]) return bareMatch[1];++ return fallback;+}diff --git a/static/js/modules/utils/content-disposition.test.js b/static/js/modules/utils/content-disposition.test.jsnew file mode 100644index 00000000..42faa177--- /dev/null+++ b/static/js/modules/utils/content-disposition.test.js@@ -0,0 +1,55 @@+/**+ * Unit tests for filenameFromContentDisposition in content-disposition.js.+ *+ * The helper prefers the RFC 5987 `filename*` parameter (percent-encoded UTF-8)+ * over the ASCII `filename=` fallback, so downloads fetched as blobs keep+ * non-ASCII titles instead of degrading to the fallback name.+ */++import { describe, it, expect } from 'vitest';+import { filenameFromContentDisposition } from './content-disposition.js';++describe('filenameFromContentDisposition', () => {+ it('returns the fallback when there is no header', () => {+ expect(filenameFromContentDisposition(null, 'transcript.md')).toBe('transcript.md');+ expect(filenameFromContentDisposition(undefined, 'transcript.md')).toBe('transcript.md');+ expect(filenameFromContentDisposition('', 'transcript.md')).toBe('transcript.md');+ });++ it('reads a plain ASCII filename', () => {+ expect(filenameFromContentDisposition(+ 'attachment; filename="meeting notes.md"', 'transcript.md',+ )).toBe('meeting notes.md');+ });++ it('prefers filename* over the ASCII fallback', () => {+ const header = 'attachment; filename="transcript-46.md"; '+ + "filename*=UTF-8''%D0%92%D0%BD%D1%83%D1%82%D1%80%D0%B5%D0%BD%D0%BD%D0%B8%D0%B9.md";+ expect(filenameFromContentDisposition(header, 'transcript.md')).toBe('Внутренний.md');+ });++ it('accepts a lowercase charset label', () => {+ const header = "attachment; filename*=utf-8''%E4%BC%9A%E8%AD%B0.txt";+ expect(filenameFromContentDisposition(header, 'transcript.txt')).toBe('会議.txt');+ });++ it('stops filename* at the parameter separator', () => {+ const header = "attachment; filename*=UTF-8''report.md; foo=bar";+ expect(filenameFromContentDisposition(header, 'transcript.md')).toBe('report.md');+ });++ it('falls back to the ASCII name when filename* is malformed', () => {+ const header = 'attachment; filename="transcript-46.md"; filename*=UTF-8\'\'%E0%A4%A';+ expect(filenameFromContentDisposition(header, 'transcript.md')).toBe('transcript-46.md');+ });++ it('reads an unquoted filename parameter', () => {+ expect(filenameFromContentDisposition(+ 'attachment; filename=notes.txt', 'transcript.txt',+ )).toBe('notes.txt');+ });++ it('returns the fallback when the header carries no filename', () => {+ expect(filenameFromContentDisposition('attachment', 'transcript.md')).toBe('transcript.md');+ });+});diff --git a/tests/test_cov_recordings_read.py b/tests/test_cov_recordings_read.pyindex b5d466b5..1b3cef22 100644--- a/tests/test_cov_recordings_read.py+++ b/tests/test_cov_recordings_read.py@@ -1480,6 +1480,65 @@ def test_download_transcript_explicit_template_id(owner):assert "DEF " not in body+# --- /download/transcript : filename encoding ----------------------------- #++def test_download_transcript_ascii_title_plain_filename(owner):+ """An ASCII title is sent as a plain `filename=` parameter, unchanged."""+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u, transcription="body", title="Weekly sync").id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/transcript")+ assert resp.status_code == 200+ cd = resp.headers["Content-Disposition"]+ assert 'filename="Weekly sync.txt"' in cd+ assert "filename*" not in cd+++def test_download_transcript_unicode_title_uses_rfc5987(owner):+ """A non-ASCII title survives in `filename*` next to an ASCII fallback.++ Regression test: the filename used to be run through+ `re.sub(r'[^a-zA-Z0-9_\\-\\.]', '_', filename)`, which turned a Cyrillic (or+ Chinese, Greek, accented Latin) title into a row of underscores.+ """+ from urllib.parse import unquote++ title = "Внутренний созвон"+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u, transcription="body", title=title).id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/transcript")+ assert resp.status_code == 200+ cd = resp.headers["Content-Disposition"]+ # ASCII fallback for clients that ignore filename*.+ assert f'filename="transcript-{rid}.txt"' in cd+ # The real name rides along percent-encoded, and decodes back verbatim.+ marker = "filename*=UTF-8''"+ assert marker in cd+ assert unquote(cd.split(marker, 1)[1]) == f"{title}.txt"+ assert "___" not in cd+++def test_download_transcript_strips_path_illegal_characters(owner):+ """Characters illegal in a filename are dropped, the rest is kept."""+ with _db():+ u = db.session.get(User, owner)+ rid = make_recording(u, transcription="body", title='a/b:c"d|e?f*g').id++ c = new_client()+ login(c, owner)+ resp = c.get(f"/recording/{rid}/download/transcript")+ assert resp.status_code == 200+ cd = resp.headers["Content-Disposition"]+ assert 'filename="abcdefg.txt"' in cd++# --- /download/summary : content-presence guard (line 303) ---------------- #def test_download_summary_empty_400(owner):