Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Join several files into one recording from the upload dialog
Murtaza Nasir56b74e702099
diff --git a/README.md b/README.mdindex f5a375fb..30a142cc 100644--- a/README.md+++ b/README.md@@ -216,7 +216,7 @@ Complete documentation is available at **[murtaza-nasir.github.io/speakr](https:**"Archived" now means something you choose: an archived recording leaves the main list and nothing is deleted.** Archive a recording from the icon next to inbox and star, or several at once from the selection bar; search still finds archived recordings, and the Archived toggle below the search bar shows only them. Archiving is personal, so archiving a recording shared with you hides it from your list only (#394). The state Speakr previously called "Archived", where audio retention deleted the media and kept the transcript, is now called **Audio removed** and has its own quick filter. You can also put a single recording into that state yourself with **Delete audio, keep transcript** (for a video, **Delete video, keep transcript**). If you used the old Archived toggle to find recordings whose audio retention removed, use the Audio removed filter instead.-The recording header groups its actions: inbox, star and archive; folder and tags; a Reprocess menu and Identify Speakers; then share and a ⋯ menu with both deletes. The Identify Speakers dialog is rebuilt for recordings with many detected speakers: speakers sorted by speaking time, short fragments grouped and mergeable, a filter to one speaker's segments, name suggestions from your saved speakers, and a sample button per speaker (#395). AI title instructions are configurable per tag, folder, user and deployment, with the same precedence as the summary prompt (#400). Voice matching is rebuilt: a profile is now a set of samples forming one or more voice variants per person, corrections and removed samples undo themselves completely, profiles are kept separately for each embedding model, short or unlike samples are kept out, and match thresholds calibrate themselves from your data. OpenASR can now return speaker embeddings for voice profiles (#380). Also fixed: SQLAlchemy 2.1 would have broken every PostgreSQL connection on the next image build (#401, fixed by @jjsmackay), the installed desktop app could not be dragged (#402, @jjsmackay), actions behind a proxy that strips the Referer header now report why they fail (#388), and deleting a recording through API v1 now removes its media file. Database columns migrate automatically; no configuration changes are required. **Full release notes on the [GitHub release page](https://github.com/murtaza-nasir/speakr/releases/tag/v0.10.7-alpha).**+Several files can now be joined into one recording directly in the upload dialog: choose **One recording**, check the order, and the audio is joined and transcribed once. The recording header groups its actions: inbox, star and archive; folder and tags; a Reprocess menu and Identify Speakers; then share and a ⋯ menu with both deletes. The Identify Speakers dialog is rebuilt for recordings with many detected speakers: speakers sorted by speaking time, short fragments grouped and mergeable, a filter to one speaker's segments, name suggestions from your saved speakers, and a sample button per speaker (#395). AI title instructions are configurable per tag, folder, user and deployment, with the same precedence as the summary prompt (#400). Voice matching is rebuilt: a profile is now a set of samples forming one or more voice variants per person, corrections and removed samples undo themselves completely, profiles are kept separately for each embedding model, short or unlike samples are kept out, and match thresholds calibrate themselves from your data. OpenASR can now return speaker embeddings for voice profiles (#380). Also fixed: SQLAlchemy 2.1 would have broken every PostgreSQL connection on the next image build (#401, fixed by @jjsmackay), the installed desktop app could not be dragged (#402, @jjsmackay), actions behind a proxy that strips the Referer header now report why they fail (#388), and deleting a recording through API v1 now removes its media file. Database columns migrate automatically; no configuration changes are required. **Full release notes on the [GitHub release page](https://github.com/murtaza-nasir/speakr/releases/tag/v0.10.7-alpha).**### v0.10.6-alpha (previous release)diff --git a/docs/features.md b/docs/features.mdindex 40cef292..88e9e6df 100644--- a/docs/features.md+++ b/docs/features.md@@ -20,6 +20,10 @@ A per-recording Stats tab shows total length, speaker count, conversation turns,An opt-in mode (`ENABLE_SERVER_RECORDING_CHUNKS`) streams in-app recording chunks to the server as you record instead of buffering them in browser memory, raising the practical recording ceiling to hours-long sessions and letting you resume a recording after a page reload. See the [Recording guide](user-guide/recording.md#server-side-recording-sessions-long-recordings) and [admin setup](admin-guide/recording-sessions.md).+### Joining Files at Upload++When a recorder or phone splits a meeting into several files, the upload dialog can join them into one recording: choose **One recording** above the file list, check the order (by modified time and name, adjustable by dragging or with the arrows), and upload. Speakr joins the audio once every file has arrived and transcribes it a single time. See [Joining Several Files into One Recording](user-guide/recording.md#joining-several-files-into-one-recording).+### Sliced File UploadsUploads of files larger than 16 MB are sent as fixed-size slices through the same session endpoints and reassembled server-side, so a reverse proxy with a request-body limit below the file size (Cloudflare caps bodies at 100 MB on most plans) no longer blocks large uploads. This needs no configuration; see [Recording Sessions](admin-guide/recording-sessions.md#sliced-uploads-of-files-on-disk).diff --git a/docs/user-guide/recording.md b/docs/user-guide/recording.mdindex db20a62e..91c6e790 100644--- a/docs/user-guide/recording.md+++ b/docs/user-guide/recording.md@@ -260,6 +260,16 @@ If a selected tag, folder, or your account default summary prompt contains `{{naThe sticky modal footer holds **Cancel** (dismisses without uploading) and **Upload N files** (begins transcription immediately with your selected settings). The recording appears in your library with a processing indicator while transcription runs in the background. If you started a recording from inside the modal and the upload completes, Speakr auto-navigates to the new recording's detail view; bulk drag-drop uploads of multiple files leave you on whatever you were viewing.+### Joining Several Files into One Recording++A recorder or phone often splits a long meeting into several files. When two or more files are in the upload list, a switch above the list offers **Separate recordings** (the default, one recording per file) or **One recording**. With **One recording** selected:++- The files are numbered in the order they are joined. Speakr sorts them by each file's modified time, then by name with numbers compared as numbers, so `part2` comes before `part10`. Drag a file, or use its up and down arrows, to change the order.+- The total length is shown once every file's duration is known, and an optional title field names the joined recording. Left blank, the title is generated as for any upload.+- The upload button reads **Upload and join N files**. Folder, tags, language, speaker counts, hotwords and prompt variables apply to the joined recording.++Each file is uploaded and checked as usual. Once the last one arrives, Speakr joins the audio in order and transcribes the result once, so you get one continuous transcript and summary without transcribing the pieces separately. The meeting date is the earliest of the files' dates. As with merging, if any file is a video, the joined recording keeps the audio only. If one file fails to upload, the others are discarded and a message names the file, so you can add the files again and retry. Up to 20 files can be joined, and joining is not available in incognito mode.+If incognito mode is enabled at the server, a toggle in the upload modal lets you process recordings without saving them to your account. Incognito uploads accept one file at a time. In-app recordings made with incognito on are captured entirely in the browser — even when server-side chunk streaming is enabled, no audio reaches the server until you explicitly process the recording — so the 200 MB in-browser recording cap applies to them.### Mobile Upload Experience@@ -316,7 +326,7 @@ This is an opt-in feature that is off by default. If you don't see it, ask yourWhen a call drops or a meeting freezes, you can end up with two separate recordings of what was really one session. Merging combines several recordings, in the order you choose, into a single new recording that is transcribed, diarized, and summarized from scratch — so you get one continuous transcript and summary instead of several partial ones. The audio is combined; if any source is a video, the merged recording keeps the audio only.-There are two ways to start a merge:+If the pieces are still files on your computer, join them while uploading instead (see [Joining Several Files into One Recording](#joining-several-files-into-one-recording)): the upload transcribes them once, where merging transcribes each recording first and then the merged one. There are two ways to start a merge of existing recordings:- **From the sidebar.** Use the "select multiple" button, tick two or more recordings, and choose **Merge**. A dialog opens where you can reorder the sources with the up and down arrows, add more recordings from a searchable list, set a title, and optionally delete the originals once the merged recording is created.- **From the recording view.** After you finish an in-app recording, the **Upload Recording & Notes** button has a small arrow on its right edge. Its menu offers **Merge with an existing recording**, which lets you append the recording you just made onto one or more existing recordings — the common case being an interrupted recording you had to restart. The new recording is added to the end by default, since it continues the earlier one.diff --git a/src/api/recording_sessions.py b/src/api/recording_sessions.pyindex 8da8985d..fb76dd19 100644--- a/src/api/recording_sessions.py+++ b/src/api/recording_sessions.py@@ -794,6 +794,21 @@ def _replay_sliced_upload_response(session):"""existing = (db.session.get(Recording, session.finalized_recording_id)if session.finalized_recording_id else None)+ if existing is None and not session.finalized_recording_id:+ # A file uploaded as part of a join finalizes without a recording of+ # its own; the retry carries the same join fields.+ from src.services.upload_join import parse_join_fields, joined_recording, received_count, JoinError+ try:+ join = parse_join_fields(request.form)+ except JoinError:+ join = None+ if join:+ group, index, count = join+ existing = joined_recording(current_user.id, group)+ if existing is None:+ return jsonify({'join_pending': True, 'join_group': group, 'join_index': index,+ 'received': received_count(current_user.id, group),+ 'total': count, 'idempotent_replay': True}), 202if existing is None or existing.user_id != current_user.id:return jsonify({'error': 'Session was already finalized and its recording no longer exists',diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 9fa5a377..bee47a6f 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -2408,6 +2408,20 @@ def ingest_uploaded_recording(if not original_filename:return jsonify({'error': 'No file selected'}), 400+ # Joining several files into one recording (upload dialog). A retry+ # of a part whose group was already joined gets that recording.+ from src.services.upload_join import parse_join_fields, joined_recording, JoinError+ try:+ join = parse_join_fields(form)+ except JoinError as e:+ return jsonify({'error': str(e)}), 400+ if join:+ already = joined_recording(owner.id, join[0])+ if already is not None:+ response_data = already.to_dict(viewer_user=owner)+ response_data['idempotent_replay'] = True+ return jsonify(response_data), success_status+safe_filename = secure_filename(original_filename)storage = get_storage_service()staging_dir = storage.get_staging_dir()@@ -2925,6 +2939,16 @@ def ingest_uploaded_recording(meeting_date = nowcurrent_app.logger.debug("No file date available, using current time")+ if join:+ return _ingest_join_part(+ owner, join, filepath, storage, now,+ original_filename=original_filename, file_size=final_file_size,+ mime_type=mime_type, duration=audio_duration_seconds, meeting_date=meeting_date,+ title=user_title, notes=notes, folder=selected_folder, tags=selected_tags,+ prompt_variables=prompt_variables, transcribe_params=resolved_params,+ duplicate_warning=duplicate_warning, success_status=success_status,+ )+recording = Recording(audio_path=None,original_filename=original_filename,@@ -3051,6 +3075,59 @@ def ingest_uploaded_recording(return jsonify({'error': 'An unexpected error occurred during upload.'}), 500+def _ingest_join_part(owner, join, filepath, storage, now, *, original_filename, file_size,+ mime_type, duration, meeting_date, title, notes, folder, tags,+ prompt_variables, transcribe_params, duplicate_warning, success_status):+ """Store one file of a join; the file that completes the group creates the recording."""+ from src.services.upload_join import (+ store_part, claim_group, create_joined_recording, joined_recording, received_count)+ group, index, count = join+ store_part(owner, join, filepath, original_filename=original_filename, file_size=file_size,+ mime_type=mime_type, duration=duration, meeting_date=meeting_date,+ storage=storage, now=now)++ parts = claim_group(owner.id, group, count)+ if parts is None:+ recording = joined_recording(owner.id, group)+ if recording is not None:+ response_data = recording.to_dict(viewer_user=owner)+ else:+ response_data = {'join_pending': True, 'join_group': group, 'join_index': index,+ 'received': received_count(owner.id, group), 'total': count}+ if duplicate_warning:+ response_data['duplicate_warning'] = duplicate_warning+ return jsonify(response_data), success_status++ recording = create_joined_recording(+ owner, parts, title=title, notes=notes, folder=folder, tags=tags,+ prompt_variables=prompt_variables, transcribe_params=transcribe_params)+ current_app.logger.info(f"Joined {count} uploaded files into recording {recording.id}")+ try:+ from src.services.webhook_dispatch import emit_webhook_event+ emit_webhook_event(+ user_id=owner.id,+ event_type='recording.created',+ data={'recording_id': recording.id, 'title': recording.title,+ 'file_size': recording.file_size, 'original_filename': recording.original_filename},+ )+ except Exception as e:+ current_app.logger.warning(f"Webhook emit (recording.created) failed: {e}")+ response_data = recording.to_dict(viewer_user=owner)+ response_data['joined_parts'] = count+ if duplicate_warning:+ response_data['duplicate_warning'] = duplicate_warning+ return jsonify(response_data), success_status+++@recordings_bp.route('/upload/join/<string:group>', methods=['DELETE'])+@login_required+def discard_upload_join(group):+ """Discard the uploaded parts of a join the dialog gave up on."""+ from src.services.upload_join import discard_group+ removed = discard_group(current_user.id, group)+ return jsonify({'success': True, 'removed': removed})++@recordings_bp.route('/api/recordings/incognito', methods=['POST'])@login_requireddef upload_incognito():diff --git a/src/config/startup.py b/src/config/startup.pyindex 7131a395..24694a8c 100644--- a/src/config/startup.py+++ b/src/config/startup.py@@ -256,6 +256,12 @@ def initialize_recording_session_cleanup(app):reaped = cleanup_expired_sessions(app=app)if reaped:app.logger.info(f"Recording-session cleanup reaped {reaped} session(s)")+ # Parts of an upload join that never completed.+ with app.app_context():+ from src.services.upload_join import cleanup_stale_parts+ removed = cleanup_stale_parts()+ if removed:+ app.logger.info(f"Upload-join cleanup removed {removed} stale part(s)")except Exception as e:app.logger.error(f"Recording-session cleanup error: {e}", exc_info=True)# Don't tight-loop on failurediff --git a/src/models/__init__.py b/src/models/__init__.pyindex 1ddda8d8..6270c543 100644--- a/src/models/__init__.py+++ b/src/models/__init__.py@@ -37,6 +37,7 @@ from .notification import ()from .processing_job import ProcessingJobfrom .recording_session import RecordingSession, RECORDING_SESSION_KINDS, RECORDING_SESSION_STATUSES+from .upload_join import UploadJoinPartfrom .token_usage import TokenUsagefrom .transcription_usage import TranscriptionUsagefrom .webhook import (@@ -86,6 +87,7 @@ __all__ = ['KIND_VOICE_EMBEDDING_CHANGED','ProcessingJob','RecordingSession',+ 'UploadJoinPart','RECORDING_SESSION_KINDS','RECORDING_SESSION_STATUSES','TokenUsage',diff --git a/src/models/upload_join.py b/src/models/upload_join.pynew file mode 100644index 00000000..4ed264d6--- /dev/null+++ b/src/models/upload_join.py@@ -0,0 +1,38 @@+"""Files uploaded to be joined into one recording.++The upload dialog can join several files into one recording. Each file goes+through the normal upload pipeline (size limits, conversion, duplicate check)+and is stored as a part here instead of as a recording, so nothing that is+not yet a recording can appear in lists, search or statistics. When every+part of a group has arrived, one recording is created and the merge job+joins the parts' audio (see services/upload_join.py).++A part's row outlives its media by a day, so a retried upload of a part whose+group was already joined is answered with the joined recording.+"""++from datetime import datetime++from src.database import db+++class UploadJoinPart(db.Model):+ __tablename__ = 'upload_join_part'+ __table_args__ = (+ db.UniqueConstraint('user_id', 'group_id', 'part_index', name='uq_upload_join_part'),+ )++ id = db.Column(db.Integer, primary_key=True)+ user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False, index=True)+ group_id = db.Column(db.String(64), nullable=False, index=True)+ part_index = db.Column(db.Integer, nullable=False) # 0-based position in the joined recording+ part_count = db.Column(db.Integer, nullable=False)+ audio_path = db.Column(db.String(500), nullable=True) # storage locator; None once joined+ original_filename = db.Column(db.String(500), nullable=True)+ file_size = db.Column(db.BigInteger, nullable=True)+ mime_type = db.Column(db.String(100), nullable=True)+ audio_duration_seconds = db.Column(db.Float, nullable=True)+ meeting_date = db.Column(db.DateTime, nullable=True)+ claimed_at = db.Column(db.DateTime, nullable=True) # set once, when the group is joined+ recording_id = db.Column(db.Integer, db.ForeignKey('recording.id', ondelete='SET NULL'), nullable=True)+ created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)diff --git a/src/services/recording_merge.py b/src/services/recording_merge.pyindex 607ccdb3..23dd009b 100644--- a/src/services/recording_merge.py+++ b/src/services/recording_merge.py@@ -289,23 +289,37 @@ def run_merge_job(recording, params):Raises MergeError on failure so the worker can flip the recording to FAILED."""source_ids = (params or {}).get('source_ids') or []+ part_ids = (params or {}).get('part_ids') or []delete_originals = bool((params or {}).get('delete_originals', False))- if len(source_ids) < 2:+ if len(source_ids) < 2 and len(part_ids) < 2:raise MergeError("Merge job is missing its source recordings.")storage = get_storage_service()# Re-fetch and re-validate sources at run time (they may have changed since- # the request was made).+ # the request was made). Files joined at upload arrive as UploadJoinParts+ # claimed for this recording, not as recordings.sources = []- for rid in source_ids:- rec = db.session.get(Recording, rid)- if not rec or rec.user_id != recording.user_id:- raise MergeError("A source recording is no longer available.")- if not rec.audio_path or not storage.exists(rec.audio_path):- raise MergeError("Audio for a source recording is unavailable.")- sources.append(rec)+ parts = []+ if part_ids:+ from src.models.upload_join import UploadJoinPart+ for pid in part_ids:+ part = db.session.get(UploadJoinPart, pid)+ if not part or part.user_id != recording.user_id or part.recording_id != recording.id:+ raise MergeError("An uploaded file to join is no longer available.")+ if not part.audio_path or not storage.exists(part.audio_path):+ raise MergeError("Audio for an uploaded file to join is unavailable.")+ parts.append(part)+ else:+ for rid in source_ids:+ rec = db.session.get(Recording, rid)+ if not rec or rec.user_id != recording.user_id:+ raise MergeError("A source recording is no longer available.")+ if not rec.audio_path or not storage.exists(rec.audio_path):+ raise MergeError("Audio for a source recording is unavailable.")+ sources.append(rec)+ locators = [p.audio_path for p in parts] or [r.audio_path for r in sources]now = datetime.utcnow()upload_folder = current_app.config['UPLOAD_FOLDER']@@ -317,8 +331,8 @@ def run_merge_job(recording, params):try:with ExitStack() as stack:local_paths = []- for rec in sources:- materialized = stack.enter_context(storage.materialize(rec.audio_path))+ for locator in locators:+ materialized = stack.enter_context(storage.materialize(locator))local_paths.append(materialized.local_path)_concat_audio(local_paths, staging_path)@@ -360,6 +374,9 @@ def run_merge_job(recording, params):raise MergeError("Failed to store the merged recording.")# Delete originals only after the merged audio is safely stored.+ if parts:+ from src.services.upload_join import release_parts_media+ release_parts_media(parts, storage)if delete_originals:for rec in sources:try:@@ -372,8 +389,10 @@ def run_merge_job(recording, params):# the merged file honors all of the owner's tag/folder/account preferences# (speaker-count hints, hotwords, initial prompt, transcription model) and# therefore diarization + auto speaker labelling behave identically (#323).+ # A join at upload carries the params its upload resolved, which include+ # the dialog's language, speaker count, hotwords and model.from src.services.transcription_defaults import resolve_transcription_params- job_params = resolve_transcription_params(recording)+ job_params = (params or {}).get('transcribe_params') or resolve_transcription_params(recording)job_queue.enqueue(user_id=recording.user_id,recording_id=recording.id,diff --git a/src/services/upload_join.py b/src/services/upload_join.pynew file mode 100644index 00000000..2a918702--- /dev/null+++ b/src/services/upload_join.py@@ -0,0 +1,248 @@+"""Joining several uploaded files into one recording.++The upload dialog sends each file with ``join_group`` (an id the browser+picks), ``join_index`` (its 0-based position) and ``join_count``. Each file+runs through the normal upload pipeline and is stored as an UploadJoinPart.+The request that completes the group claims every part in one conditional+UPDATE, so parallel or retried uploads can never join a group twice, creates+the recording from that request's upload options, and queues the existing+``merge`` job with the parts. The merge job joins the audio and queues one+transcription with the options the upload resolved.++Parts of a group that never completes (a closed tab, a failed part) are+removed by the hourly cleanup after PART_TTL_HOURS, or at once when the+dialog discards the group.+"""++import os+import re+from datetime import datetime, timedelta++from flask import current_app+from sqlalchemy.exc import OperationalError++from src.database import db+from src.models import Recording, RecordingTag+from src.models.upload_join import UploadJoinPart++MAX_JOIN_PARTS = 20+PART_TTL_HOURS = 24+_GROUP_RE = re.compile(r'^[A-Za-z0-9_-]{8,64}$')+++class JoinError(ValueError):+ """An invalid join request. The message is safe to show."""+++def parse_join_fields(form):+ """(group, index, count) from an upload form, None for a normal upload."""+ group = (form.get('join_group') or '').strip()+ if not group:+ return None+ if not _GROUP_RE.match(group):+ raise JoinError('Invalid join group.')+ try:+ index = int(form.get('join_index', ''))+ count = int(form.get('join_count', ''))+ except (TypeError, ValueError):+ raise JoinError('join_index and join_count must be integers.')+ if not 2 <= count <= MAX_JOIN_PARTS:+ raise JoinError(f'A joined recording takes between 2 and {MAX_JOIN_PARTS} files.')+ if not 0 <= index < count:+ raise JoinError('join_index is out of range.')+ return group, index, count+++def joined_recording(user_id, group):+ """The recording a group was already joined into, or None."""+ part = (UploadJoinPart.query+ .filter_by(user_id=user_id, group_id=group)+ .filter(UploadJoinPart.claimed_at.isnot(None))+ .first())+ if part is None or part.recording_id is None:+ return None+ return db.session.get(Recording, part.recording_id)+++def received_count(user_id, group):+ return UploadJoinPart.query.filter_by(user_id=user_id, group_id=group).count()+++def store_part(owner, join, filepath, *, original_filename, file_size, mime_type,+ duration, meeting_date, storage, now=None):+ """Store one uploaded part; a retried upload of the same part replaces it. Commits."""+ group, index, count = join+ now = now or datetime.utcnow()+ part = UploadJoinPart.query.filter_by(user_id=owner.id, group_id=group, part_index=index).first()+ previous_locator = None+ if part is None:+ part = UploadJoinPart(user_id=owner.id, group_id=group, part_index=index, part_count=count)+ db.session.add(part)+ db.session.flush()+ else:+ previous_locator = part.audio_path++ key = storage.build_recording_key(original_filename, f'join-{part.id}', now=now)+ stored = storage.upload_local_file(filepath, key, content_type=mime_type, delete_source=True)+ part.audio_path = stored.locator+ part.part_count = count+ part.original_filename = original_filename+ part.file_size = file_size+ part.mime_type = mime_type+ part.audio_duration_seconds = duration+ part.meeting_date = meeting_date+ part.created_at = now+ db.session.commit()++ if previous_locator and previous_locator != part.audio_path:+ try:+ storage.delete(previous_locator, missing_ok=True)+ except Exception as e:+ current_app.logger.warning(f"Could not delete replaced join part media {previous_locator}: {e}")+ return part+++def claim_group(user_id, group, count):+ """Claim a complete group for joining; its parts in order, or None.++ None when parts are missing or another request claimed the group first.+ The claim is not committed: the caller creates the recording in the same+ transaction, so a failure there releases the claim.+ """+ parts = (UploadJoinPart.query+ .filter_by(user_id=user_id, group_id=group)+ .filter(UploadJoinPart.claimed_at.is_(None))+ .order_by(UploadJoinPart.part_index)+ .all())+ if [p.part_index for p in parts] != list(range(count)):+ return None+ if any(p.part_count != count or not p.audio_path for p in parts):+ return None+ try:+ claimed = (UploadJoinPart.query+ .filter_by(user_id=user_id, group_id=group)+ .filter(UploadJoinPart.claimed_at.is_(None))+ .update({'claimed_at': datetime.utcnow()}, synchronize_session=False))+ except OperationalError as e:+ # SQLite refuses a write that races another writer; the other+ # request is completing this group.+ db.session.rollback()+ current_app.logger.info(f"Join group {group} is being claimed by another request: {e}")+ return None+ if claimed != count:+ db.session.rollback()+ return None+ return parts+++def _joined_filename(first_name):+ stem = os.path.splitext(os.path.basename(first_name or 'recording'))[0] or 'recording'+ return f"{stem}.m4a"+++def create_joined_recording(owner, parts, *, title=None, notes=None, folder=None, tags=(),+ prompt_variables=None, transcribe_params=None):+ """Create the recording for a claimed group and queue the merge job. Commits."""+ from src.services.job_queue import job_queue+ from src.utils.titles import resolve_upload_title++ now = datetime.utcnow()+ original_filename = _joined_filename(parts[0].original_filename)+ meeting_dates = [p.meeting_date for p in parts if p.meeting_date]+ durations = [p.audio_duration_seconds for p in parts]+ recording = Recording(+ audio_path=None,+ original_filename=original_filename,+ title=resolve_upload_title(title, original_filename),+ file_size=sum(p.file_size or 0 for p in parts),+ status='QUEUED',+ meeting_date=min(meeting_dates) if meeting_dates else now,+ user_id=owner.id,+ mime_type='audio/mp4',+ audio_duration_seconds=sum(durations) if all(d for d in durations) else None,+ notes=notes,+ folder_id=folder.id if folder else None,+ processing_source='upload',+ prompt_variables=prompt_variables,+ keep_audio_only=True, # the merge produces audio only+ )+ db.session.add(recording)+ db.session.flush()+ for order, tag in enumerate(tags, 1):+ db.session.add(RecordingTag(recording_id=recording.id, tag_id=tag.id, order=order, added_at=now))+ for p in parts:+ p.recording_id = recording.id+ db.session.commit()++ try:+ job_queue.enqueue(+ user_id=owner.id,+ recording_id=recording.id,+ job_type='merge',+ params={'part_ids': [p.id for p in parts], 'transcribe_params': transcribe_params},+ is_new_upload=True,+ )+ except Exception as e:+ current_app.logger.error(f"Join enqueue failed for recording {recording.id}: {e}")+ recording.status = 'FAILED'+ recording.error_message = f"Processing failed: {e}"+ db.session.commit()+ return recording+++def _delete_media(storage, part):+ if part.audio_path:+ try:+ storage.delete(part.audio_path, missing_ok=True)+ except Exception as e:+ current_app.logger.warning(f"Could not delete join part media {part.audio_path}: {e}")+ return False+ part.audio_path = None+ return True+++def release_parts_media(parts, storage):+ """After a successful join: drop the parts' media, keep the rows. Commits."""+ for p in parts:+ _delete_media(storage, p)+ db.session.commit()+++def discard_group(user_id, group, storage=None):+ """Remove a group's unjoined parts, for a join the dialog gave up. Commits."""+ if storage is None:+ from src.services.storage import get_storage_service+ storage = get_storage_service()+ parts = (UploadJoinPart.query+ .filter_by(user_id=user_id, group_id=group)+ .filter(UploadJoinPart.claimed_at.is_(None))+ .all())+ for p in parts:+ _delete_media(storage, p)+ db.session.delete(p)+ db.session.commit()+ return len(parts)+++def cleanup_stale_parts(max_age_hours=PART_TTL_HOURS, storage=None):+ """Remove parts older than the TTL; returns how many rows were removed.++ Unjoined parts lose media and row. A joined part keeps its media while+ its recording is still being merged, and is otherwise removed too.+ """+ if storage is None:+ from src.services.storage import get_storage_service+ storage = get_storage_service()+ cutoff = datetime.utcnow() - timedelta(hours=max_age_hours)+ removed = 0+ for p in UploadJoinPart.query.filter(UploadJoinPart.created_at < cutoff).all():+ if p.claimed_at is not None and p.audio_path:+ rec = db.session.get(Recording, p.recording_id) if p.recording_id else None+ if rec is not None and rec.status == 'QUEUED' and not rec.audio_path:+ continue # still waiting for its merge+ if not _delete_media(storage, p):+ continue+ db.session.delete(p)+ removed += 1+ db.session.commit()+ return removeddiff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.jsindex 2293eecf..426665b7 100644--- a/static/js/modules/composables/upload.js+++ b/static/js/modules/composables/upload.js@@ -9,6 +9,10 @@ import * as RecordingDB from '../db/recording-persistence.js';import { getUploadCsrfToken, isCsrfRejection } from '../csrf.js';import { shouldSliceUpload, uploadFileInSlices } from '../db/sliced-file-upload.js';import { computeUploadTimeout } from '../utils/upload-timeout.js';+import {+ sortQueuedForJoin, moveQueuedItem, placeQueuedItem, totalJoinDuration,+ newJoinGroupId, isVideoFileName, MAX_JOIN_FILES,+} from '../utils/upload-join.js';// Parse error message and return friendly error infofunction getFriendlyError(errorMessage, t) {@@ -62,6 +66,70 @@ export function useUpload(state, utils) {const { setGlobalError, showToast, formatFileSize, onChatComplete, t } = utils;+ // --- Join several files into one recording ------------------------------+ // Offered once two or more files are queued. The queue order is the join+ // order; turning the switch on sorts the files by modified time and name.+ const joinMode = ref(false);+ const joinTitle = ref('');+ const joinDragClientId = ref(null);+ const joinQueuedItems = computed(() => uploadQueue.value.filter(item => item.status === 'queued'));+ const joinAvailable = computed(() =>+ joinQueuedItems.value.length >= 2+ && joinQueuedItems.value.length <= MAX_JOIN_FILES+ && !(incognitoMode && incognitoMode.value));+ const joinActive = computed(() => joinMode.value && joinAvailable.value);+ const joinTotalDuration = computed(() => totalJoinDuration(joinQueuedItems.value));+ const joinHasVideo = computed(() => joinQueuedItems.value.some(item => isVideoFileName(item.file?.name)));++ const setJoinMode = (on) => {+ joinMode.value = !!on;+ if (on) uploadQueue.value = sortQueuedForJoin(uploadQueue.value);+ };+ const moveJoinItem = (clientId, delta) => {+ uploadQueue.value = moveQueuedItem(uploadQueue.value, clientId, delta);+ };+ const handleJoinDragStart = (clientId, event) => {+ joinDragClientId.value = clientId;+ if (event?.dataTransfer) {+ event.dataTransfer.effectAllowed = 'move';+ event.dataTransfer.setData('text/plain', clientId);+ }+ };+ const handleJoinDrop = (targetIndex) => {+ if (joinDragClientId.value) {+ uploadQueue.value = placeQueuedItem(uploadQueue.value, joinDragClientId.value, targetIndex);+ }+ joinDragClientId.value = null;+ };+ const handleJoinDragEnd = () => { joinDragClientId.value = null; };++ // One part failed: stop the others and discard what the server holds, so+ // the user retries the whole join with the files they still have.+ const failJoinGroup = async (failedItem, message) => {+ const group = failedItem.join.group;+ for (const item of uploadQueue.value) {+ if (item === failedItem || !item.join || item.join.group !== group) continue;+ if (['ready', 'uploading', 'completed'].includes(item.status)) {+ item.joinCancelled = true;+ item.status = 'failed';+ item.error = message;+ item.progress = 0;+ if (item._xhr) {+ try { item._xhr.abort(); } catch (_) { /* already finished */ }+ }+ }+ }+ try {+ const token = await getUploadCsrfToken();+ await fetch(`/upload/join/${encodeURIComponent(group)}`, {+ method: 'DELETE',+ headers: token ? { 'X-CSRFToken': token } : {},+ });+ } catch (e) {+ console.warn('[Upload] Could not discard the uploaded parts of a failed join:', e);+ }+ };+// Probe a File for its audio/video duration without uploading it.// Uses a hidden <audio> or <video> element with preload="metadata"// so the browser only reads the container headers, not the whole@@ -393,6 +461,20 @@ export function useUpload(state, utils) {showUploadDisclaimerModal.value = true;return;}+ // Joining: every queued file becomes one part of the same group, in+ // queue order.+ if (joinActive.value) {+ const items = joinQueuedItems.value;+ const group = newJoinGroupId();+ const title = joinTitle.value.trim();+ items.forEach((item, index) => {+ item.join = { group, index, count: items.length, title };+ item.displayName = `${item.file.name} · ${index + 1}/${items.length}`;+ });+ }+ joinMode.value = false;+ joinTitle.value = '';+// Update all queued files with current tags and ASR options// AND change their status to 'ready' so they move to upload progress immediatelyfor (const item of uploadQueue.value) {@@ -477,6 +559,10 @@ export function useUpload(state, utils) {*/const uploadSingleFile = async (fileItem) => {await acquireUploadSlot();+ if (fileItem.joinCancelled) {+ releaseUploadSlot();+ return;+ }fileItem.status = 'uploading';fileItem.progress = 5;@@ -499,6 +585,13 @@ export function useUpload(state, utils) {formData.append('notes', fileItem.notes);}+ if (fileItem.join) {+ formData.append('join_group', fileItem.join.group);+ formData.append('join_index', String(fileItem.join.index));+ formData.append('join_count', String(fileItem.join.count));+ if (fileItem.join.title) formData.append('title', fileItem.join.title);+ }+// Add tags if selectedconst tagsToUse = fileItem.tags || selectedTags.value || [];tagsToUse.forEach((tag, index) => {@@ -622,7 +715,7 @@ export function useUpload(state, utils) {return;}- if (xhr.status === 202 && parsed.id) {+ if (xhr.status === 202 && (parsed.id || parsed.join_pending)) {resolve(parsed);} else if (!String(xhr.status).startsWith('2')) {let errorMsg = parsed.error || `Upload failed with status ${xhr.status}`;@@ -681,6 +774,27 @@ export function useUpload(state, utils) {}}+ // One part of a join is stored; the part that completes the group+ // gets the recording back.+ if (data.join_pending) {+ fileItem.status = 'completed';+ fileItem.progress = 100;+ return;+ }+ if (fileItem.join) {+ // From here one entry stands for the joined recording.+ const group = fileItem.join.group;+ uploadQueue.value = uploadQueue.value.filter(item =>+ item === fileItem || !(item.join && item.join.group === group));+ fileItem.displayName = data.title || fileItem.displayName;+ if (recordings.value.some(r => r.id === data.id)) {+ fileItem.status = 'pending';+ fileItem.recordingId = data.id;+ fileItem.progress = 100;+ return;+ }+ }+// Upload succeeded - recording is now on the serverconsole.log(`File ${fileItem.file.name} uploaded. Recording ID: ${data.id}. Server will process via job queue.`);fileItem.status = 'pending';@@ -757,10 +871,21 @@ export function useUpload(state, utils) {}} catch (error) {+ if (fileItem.joinCancelled) {+ // Stopped because another part of its join failed.+ fileItem.status = 'failed';+ return;+ }console.error(`Upload Error for ${fileItem.file.name} (Client ID: ${fileItem.clientId}):`, error);fileItem.status = 'failed';fileItem.error = error.message;fileItem.progress = 0;+ if (fileItem.join) {+ const message = t('upload.joinFailed', { name: fileItem.file.name });+ await failJoinGroup(fileItem, message);+ setGlobalError(`${message} ${error.message}`);+ return;+ }// Show friendly error messageconst friendlyErr = getFriendlyError(error.message, t);@@ -1235,6 +1360,19 @@ export function useUpload(state, utils) {};return {+ // Join several files into one recording+ joinMode,+ joinTitle,+ joinAvailable,+ joinActive,+ joinTotalDuration,+ joinHasVideo,+ joinDragClientId,+ setJoinMode,+ moveJoinItem,+ handleJoinDragStart,+ handleJoinDrop,+ handleJoinDragEnd,resurfaceFailedUploads,handleDragOver,handleDragLeave,diff --git a/static/js/modules/db/sliced-file-upload.js b/static/js/modules/db/sliced-file-upload.jsindex e17aa42f..6359a1ae 100644--- a/static/js/modules/db/sliced-file-upload.js+++ b/static/js/modules/db/sliced-file-upload.js@@ -389,7 +389,7 @@ async function finalize(sessionId, formData, tokenRef, options) {throw transportError;}const body = parseJson(result.text);- if (result.status >= 200 && result.status < 300 && body?.id) return body;+ if (result.status >= 200 && result.status < 300 && (body?.id || body?.join_pending)) return body;if (isCsrfRejection(result.status, result.text) && attempt === 1) {tokenRef.token = await getUploadCsrfToken();continue;diff --git a/static/js/modules/utils/upload-join.js b/static/js/modules/utils/upload-join.jsnew file mode 100644index 00000000..0125499a--- /dev/null+++ b/static/js/modules/utils/upload-join.js@@ -0,0 +1,81 @@+/**+ * Joining several uploaded files into one recording: ordering and totals+ * for the upload dialog. Pure functions over upload-queue items+ * ({ clientId, status, file, duration }), so they can be tested alone.+ */++export const MAX_JOIN_FILES = 20;++const VIDEO_EXT = /\.(mp4|mov|mkv|avi|webm|m4v|wmv|flv|ts|mts|mpeg|mpg|ogv|vob|asf)$/i;++export function isVideoFileName(name) {+ return VIDEO_EXT.test(name || '');+}++const nameCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });++/**+ * The order files are joined in by default: by the file's modified time,+ * then by name with numbers compared as numbers ("part2" before "part10").+ * Recorders and phones that split a long meeting number and timestamp the+ * pieces, so this is usually already right.+ */+export function compareForJoin(a, b) {+ const ta = a.file?.lastModified || 0;+ const tb = b.file?.lastModified || 0;+ if (ta !== tb) return ta - tb;+ return nameCollator.compare(a.file?.name || '', b.file?.name || '');+}++/**+ * Reorder the queued (not yet uploaded) items of `queue` into join order,+ * leaving every other item where it is. Returns a new array.+ */+export function sortQueuedForJoin(queue) {+ const queued = queue.filter(item => item.status === 'queued').sort(compareForJoin);+ let next = 0;+ return queue.map(item => (item.status === 'queued' ? queued[next++] : item));+}++/**+ * Move the queued item `clientId` by `delta` places among the queued items+ * (other items keep their positions). Returns a new array, or the same one+ * when the move is not possible.+ */+export function moveQueuedItem(queue, clientId, delta) {+ const slots = [];+ queue.forEach((item, i) => { if (item.status === 'queued') slots.push(i); });+ const from = slots.findIndex(i => queue[i].clientId === clientId);+ const to = from + delta;+ if (from < 0 || to < 0 || to >= slots.length) return queue;+ return placeQueuedItem(queue, clientId, to);+}++/**+ * Put the queued item `clientId` at position `to` among the queued items+ * (a drop from drag and drop). Returns a new array.+ */+export function placeQueuedItem(queue, clientId, to) {+ const slots = [];+ queue.forEach((item, i) => { if (item.status === 'queued') slots.push(i); });+ const queued = slots.map(i => queue[i]);+ const from = queued.findIndex(item => item.clientId === clientId);+ if (from < 0 || to < 0 || to >= queued.length || from === to) return queue;+ const [moved] = queued.splice(from, 1);+ queued.splice(to, 0, moved);+ const result = queue.slice();+ slots.forEach((slot, n) => { result[slot] = queued[n]; });+ return result;+}++/** Total duration in seconds, or null while any file's duration is unknown. */+export function totalJoinDuration(items) {+ if (!items.length || items.some(item => !item.duration)) return null;+ return items.reduce((sum, item) => sum + item.duration, 0);+}++/** An id for one join; the server accepts 8-64 of [A-Za-z0-9_-]. */+export function newJoinGroupId() {+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID().replace(/-/g, '');+ return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;+}diff --git a/static/js/modules/utils/upload-join.test.js b/static/js/modules/utils/upload-join.test.jsnew file mode 100644index 00000000..dab6518c--- /dev/null+++ b/static/js/modules/utils/upload-join.test.js@@ -0,0 +1,72 @@+import { describe, it, expect } from 'vitest';+import {+ compareForJoin, sortQueuedForJoin, moveQueuedItem, placeQueuedItem,+ totalJoinDuration, newJoinGroupId, isVideoFileName,+} from './upload-join.js';++const item = (clientId, name, lastModified, status = 'queued', duration = null) =>+ ({ clientId, status, duration, file: { name, lastModified } });++const ids = (queue) => queue.map(i => i.clientId);++describe('compareForJoin', () => {+ it('orders by modified time first', () => {+ const a = item('a', 'z.mp3', 1), b = item('b', 'a.mp3', 2);+ expect([b, a].sort(compareForJoin).map(i => i.clientId)).toEqual(['a', 'b']);+ });+ it('breaks ties by name with numbers compared as numbers', () => {+ const q = [item('10', 'part10.m4a', 5), item('2', 'part2.m4a', 5), item('1', 'Part1.m4a', 5)];+ expect(q.sort(compareForJoin).map(i => i.clientId)).toEqual(['1', '2', '10']);+ });+});++describe('sortQueuedForJoin', () => {+ it('sorts only the queued items and leaves the others in place', () => {+ const q = [item('late', 'b.mp3', 9), item('up', 'x.mp3', 0, 'uploading'), item('early', 'a.mp3', 1)];+ expect(ids(sortQueuedForJoin(q))).toEqual(['early', 'up', 'late']);+ });+});++describe('moveQueuedItem', () => {+ const q = [item('a', 'a', 1), item('busy', 'x', 0, 'ready'), item('b', 'b', 2), item('c', 'c', 3)];+ it('moves among queued items, skipping others', () => {+ expect(ids(moveQueuedItem(q, 'b', -1))).toEqual(['b', 'busy', 'a', 'c']);+ expect(ids(moveQueuedItem(q, 'a', 1))).toEqual(['b', 'busy', 'a', 'c']);+ });+ it('does nothing past either end or for unknown items', () => {+ expect(moveQueuedItem(q, 'a', -1)).toBe(q);+ expect(moveQueuedItem(q, 'c', 1)).toBe(q);+ expect(moveQueuedItem(q, 'nope', 1)).toBe(q);+ });+});++describe('placeQueuedItem', () => {+ it('drops an item at a position among the queued items', () => {+ const q = [item('a', 'a', 1), item('b', 'b', 2), item('c', 'c', 3)];+ expect(ids(placeQueuedItem(q, 'c', 0))).toEqual(['c', 'a', 'b']);+ expect(ids(placeQueuedItem(q, 'a', 2))).toEqual(['b', 'c', 'a']);+ expect(placeQueuedItem(q, 'a', 0)).toBe(q);+ });+});++describe('totalJoinDuration', () => {+ it('sums known durations', () => {+ expect(totalJoinDuration([item('a', 'a', 1, 'queued', 60), item('b', 'b', 2, 'queued', 30.5)])).toBe(90.5);+ });+ it('is null while any duration is unknown or for no items', () => {+ expect(totalJoinDuration([item('a', 'a', 1, 'queued', 60), item('b', 'b', 2)])).toBeNull();+ expect(totalJoinDuration([])).toBeNull();+ });+});++describe('newJoinGroupId and isVideoFileName', () => {+ it('makes ids the server accepts', () => {+ for (let i = 0; i < 20; i++) expect(newJoinGroupId()).toMatch(/^[A-Za-z0-9_-]{8,64}$/);+ expect(newJoinGroupId()).not.toBe(newJoinGroupId());+ });+ it('recognises video extensions', () => {+ expect(isVideoFileName('talk.MP4')).toBe(true);+ expect(isVideoFileName('talk.m4a')).toBe(false);+ expect(isVideoFileName(undefined)).toBe(false);+ });+});diff --git a/static/locales/de.json b/static/locales/de.jsonindex 290b6fbf..73512428 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -2111,7 +2111,19 @@"largeVideoNotice": "Großes Videodatei. Upload wird fortgesetzt; Transkription dauert ggf. länger und nutzt das Chunking auf dem Server.","options": "Optionen","transcriptionOptions": "Transkriptionsoptionen",- "uploadAndAddMore": "Hochladen & weitere hinzufügen"+ "uploadAndAddMore": "Hochladen & weitere hinzufügen",+ "joinModeLabel": "Wie diese Dateien hinzugefügt werden",+ "joinSeparate": "Einzelne Aufnahmen",+ "joinOne": "Eine Aufnahme",+ "joinMoveUp": "Nach oben",+ "joinMoveDown": "Nach unten",+ "joinSummary": "{{count}} Dateien werden in dieser Reihenfolge zusammengefügt, insgesamt {{duration}}. Ziehen Sie eine Datei oder nutzen Sie die Pfeile, um die Reihenfolge zu ändern.",+ "joinSummaryNoDuration": "{{count}} Dateien werden in dieser Reihenfolge zusammengefügt. Ziehen Sie eine Datei oder nutzen Sie die Pfeile, um die Reihenfolge zu ändern.",+ "joinTitle": "Titel der zusammengefügten Aufnahme",+ "joinTitlePlaceholder": "Leer lassen, um einen Titel zu erzeugen",+ "joinVideoHint": "Die zusammengefügte Aufnahme behält nur den Ton.",+ "uploadAndJoin": "{{count}} Dateien hochladen und zusammenfügen",+ "joinFailed": "Das Zusammenfügen wurde abgebrochen, weil {{name}} nicht hochgeladen wurde. Fügen Sie die Dateien erneut hinzu, um es noch einmal zu versuchen."},"uploadProgress": {"title": "Upload-Fortschritt"diff --git a/static/locales/en.json b/static/locales/en.jsonindex 76282adc..1f9c6107 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -2111,7 +2111,19 @@"largeVideoNotice": "Large video file. Upload will proceed; transcription may take longer and uses chunking on the server.","options": "Options","transcriptionOptions": "Transcription Options",- "uploadAndAddMore": "Upload & Add More"+ "uploadAndAddMore": "Upload & Add More",+ "joinModeLabel": "How to add these files",+ "joinSeparate": "Separate recordings",+ "joinOne": "One recording",+ "joinMoveUp": "Move up",+ "joinMoveDown": "Move down",+ "joinSummary": "{{count}} files are joined in this order, {{duration}} in total. Drag a file or use the arrows to change the order.",+ "joinSummaryNoDuration": "{{count}} files are joined in this order. Drag a file or use the arrows to change the order.",+ "joinTitle": "Title of the joined recording",+ "joinTitlePlaceholder": "Leave blank to generate a title",+ "joinVideoHint": "The joined recording keeps the audio only.",+ "uploadAndJoin": "Upload and join {{count}} files",+ "joinFailed": "Joining stopped because {{name}} did not upload. Add the files again to retry."},"uploadProgress": {"title": "Upload Progress"diff --git a/static/locales/es.json b/static/locales/es.jsonindex 225cc74e..55c1dabe 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -2111,7 +2111,19 @@"largeVideoNotice": "Archivo de vídeo grande. La subida continuará; la transcripción puede tardar más y usa el troceado en el servidor.","options": "Opciones","transcriptionOptions": "Opciones de transcripción",- "uploadAndAddMore": "Subir y añadir más"+ "uploadAndAddMore": "Subir y añadir más",+ "joinModeLabel": "Cómo añadir estos archivos",+ "joinSeparate": "Grabaciones separadas",+ "joinOne": "Una grabación",+ "joinMoveUp": "Subir",+ "joinMoveDown": "Bajar",+ "joinSummary": "Los {{count}} archivos se unen en este orden, {{duration}} en total. Arrastre un archivo o use las flechas para cambiar el orden.",+ "joinSummaryNoDuration": "Los {{count}} archivos se unen en este orden. Arrastre un archivo o use las flechas para cambiar el orden.",+ "joinTitle": "Título de la grabación unida",+ "joinTitlePlaceholder": "Déjelo en blanco para generar un título",+ "joinVideoHint": "La grabación unida conserva solo el audio.",+ "uploadAndJoin": "Subir y unir {{count}} archivos",+ "joinFailed": "La unión se detuvo porque {{name}} no se subió. Vuelva a añadir los archivos para intentarlo de nuevo."},"uploadProgress": {"title": "Progreso de Carga"diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex feb419e7..21f9d292 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -2111,7 +2111,19 @@"largeVideoNotice": "Fichier vidéo volumineux. L’envoi va se poursuivre ; la transcription peut être plus longue et utilise le découpage côté serveur.","options": "Options","transcriptionOptions": "Options de transcription",- "uploadAndAddMore": "Téléverser et ajouter plus"+ "uploadAndAddMore": "Téléverser et ajouter plus",+ "joinModeLabel": "Comment ajouter ces fichiers",+ "joinSeparate": "Enregistrements séparés",+ "joinOne": "Un seul enregistrement",+ "joinMoveUp": "Monter",+ "joinMoveDown": "Descendre",+ "joinSummary": "Les {{count}} fichiers sont assemblés dans cet ordre, {{duration}} au total. Faites glisser un fichier ou utilisez les flèches pour changer l’ordre.",+ "joinSummaryNoDuration": "Les {{count}} fichiers sont assemblés dans cet ordre. Faites glisser un fichier ou utilisez les flèches pour changer l’ordre.",+ "joinTitle": "Titre de l’enregistrement assemblé",+ "joinTitlePlaceholder": "Laissez vide pour générer un titre",+ "joinVideoHint": "L’enregistrement assemblé ne conserve que l’audio.",+ "uploadAndJoin": "Téléverser et assembler {{count}} fichiers",+ "joinFailed": "L’assemblage a été interrompu, car {{name}} n’a pas été téléversé. Ajoutez de nouveau les fichiers pour réessayer."},"uploadProgress": {"title": "Progression du Téléchargement"diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.jsonindex ae4fd53d..231468c4 100644--- a/static/locales/pt-BR.json+++ b/static/locales/pt-BR.json@@ -2111,7 +2111,19 @@"largeVideoNotice": "Arquivo de vídeo grande. O envio será concluído; a transcrição pode demorar mais e usa o particionamento no servidor.","options": "Opções","transcriptionOptions": "Opções de transcrição",- "uploadAndAddMore": "Enviar e adicionar mais"+ "uploadAndAddMore": "Enviar e adicionar mais",+ "joinModeLabel": "Como adicionar estes arquivos",+ "joinSeparate": "Gravações separadas",+ "joinOne": "Uma gravação",+ "joinMoveUp": "Mover para cima",+ "joinMoveDown": "Mover para baixo",+ "joinSummary": "Os {{count}} arquivos são unidos nesta ordem, {{duration}} no total. Arraste um arquivo ou use as setas para mudar a ordem.",+ "joinSummaryNoDuration": "Os {{count}} arquivos são unidos nesta ordem. Arraste um arquivo ou use as setas para mudar a ordem.",+ "joinTitle": "Título da gravação unida",+ "joinTitlePlaceholder": "Deixe em branco para gerar um título",+ "joinVideoHint": "A gravação unida mantém apenas o áudio.",+ "uploadAndJoin": "Enviar e unir {{count}} arquivos",+ "joinFailed": "A união foi interrompida porque {{name}} não foi enviado. Adicione os arquivos novamente para tentar outra vez."},"uploadProgress": {"title": "Progresso do Envio"diff --git a/static/locales/ru.json b/static/locales/ru.jsonindex 4c31a8e8..856a8788 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -2111,7 +2111,19 @@"largeVideoNotice": "Большой видеофайл. Загрузка продолжится; транскрибация может занять больше времени и использует разбивку на сервере.","options": "Параметры","transcriptionOptions": "Параметры транскрипции",- "uploadAndAddMore": "Загрузить и добавить ещё"+ "uploadAndAddMore": "Загрузить и добавить ещё",+ "joinModeLabel": "Как добавить эти файлы",+ "joinSeparate": "Отдельные записи",+ "joinOne": "Одна запись",+ "joinMoveUp": "Выше",+ "joinMoveDown": "Ниже",+ "joinSummary": "Файлов: {{count}}, они объединяются в этом порядке, всего {{duration}}. Перетащите файл или используйте стрелки, чтобы изменить порядок.",+ "joinSummaryNoDuration": "Файлов: {{count}}, они объединяются в этом порядке. Перетащите файл или используйте стрелки, чтобы изменить порядок.",+ "joinTitle": "Название объединённой записи",+ "joinTitlePlaceholder": "Оставьте пустым, чтобы создать название автоматически",+ "joinVideoHint": "В объединённой записи сохраняется только звук.",+ "uploadAndJoin": "Загрузить и объединить файлы: {{count}}",+ "joinFailed": "Объединение остановлено: файл {{name}} не загрузился. Добавьте файлы ещё раз, чтобы повторить."},"uploadProgress": {"title": "Прогресс загрузки"diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 161633d4..b3d7d12e 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -2111,7 +2111,19 @@"largeVideoNotice": "视频文件较大。上传将继续;转录可能耗时更长,并依赖服务器端的分块处理。","options": "选项","transcriptionOptions": "转录选项",- "uploadAndAddMore": "上传并继续添加"+ "uploadAndAddMore": "上传并继续添加",+ "joinModeLabel": "如何添加这些文件",+ "joinSeparate": "分别作为录音",+ "joinOne": "合并为一个录音",+ "joinMoveUp": "上移",+ "joinMoveDown": "下移",+ "joinSummary": "{{count}} 个文件将按此顺序合并,共 {{duration}}。拖动文件或使用箭头可调整顺序。",+ "joinSummaryNoDuration": "{{count}} 个文件将按此顺序合并。拖动文件或使用箭头可调整顺序。",+ "joinTitle": "合并后录音的标题",+ "joinTitlePlaceholder": "留空将自动生成标题",+ "joinVideoHint": "合并后的录音仅保留音频。",+ "uploadAndJoin": "上传并合并 {{count}} 个文件",+ "joinFailed": "由于 {{name}} 未能上传,合并已停止。请重新添加这些文件后再试。"},"uploadProgress": {"title": "上传进度"diff --git a/templates/components/upload-view.html b/templates/components/upload-view.htmlindex eacca34d..70d66215 100644--- a/templates/components/upload-view.html+++ b/templates/components/upload-view.html@@ -39,17 +39,42 @@<!-- Queued Files Display --><div v-if="pendingQueueFiles.length > 0" class="mt-3">- <div class="flex items-center justify-between mb-1.5">+ <div class="flex items-center justify-between gap-2 mb-1.5 flex-wrap"><h4 class="text-xs font-medium text-[var(--text-secondary)]"><i class="fas fa-list mr-1"></i>${ t('upload.filesToUpload') } (${pendingQueueFiles.length})</h4>+ <!-- Join switch: shown once two or more files are queued.+ Separate recordings is the default. -->+ <div v-if="joinAvailable" class="inline-flex rounded-md border border-[var(--border-secondary)] overflow-hidden text-[11px]"+ role="radiogroup" :aria-label="t('upload.joinModeLabel')">+ <button type="button" role="radio" :aria-checked="!joinActive"+ @click="setJoinMode(false)"+ :class="['px-2 py-1 transition-colors', !joinActive ? 'bg-[var(--bg-accent)] text-[var(--text-accent)] font-medium' : 'text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)]']">+ <i class="fas fa-clone mr-1"></i><span v-text="t('upload.joinSeparate')"></span>+ </button>+ <button type="button" role="radio" :aria-checked="joinActive"+ @click="setJoinMode(true)"+ :class="['px-2 py-1 border-l border-[var(--border-secondary)] transition-colors', joinActive ? 'bg-[var(--bg-accent)] text-[var(--text-accent)] font-medium' : 'text-[var(--text-muted)] hover:bg-[var(--bg-tertiary)]']">+ <i class="fas fa-object-group mr-1"></i><span v-text="t('upload.joinOne')"></span>+ </button>+ </div></div>- <div class="space-y-1 max-h-32 overflow-y-auto">- <div v-for="item in pendingQueueFiles" :key="item.clientId"- class="flex flex-col gap-0.5 px-2 py-1.5 bg-[var(--bg-tertiary)] rounded border border-[var(--border-secondary)]">+ <div :class="['space-y-1 overflow-y-auto', joinActive ? 'max-h-56' : 'max-h-32']">+ <div v-for="(item, index) in pendingQueueFiles" :key="item.clientId"+ :draggable="joinActive"+ @dragstart="joinActive && handleJoinDragStart(item.clientId, $event)"+ @dragover.prevent+ @drop.prevent="joinActive && handleJoinDrop(index)"+ @dragend="handleJoinDragEnd"+ :class="['flex flex-col gap-0.5 px-2 py-1.5 bg-[var(--bg-tertiary)] rounded border border-[var(--border-secondary)]',+ joinActive && joinDragClientId === item.clientId ? 'opacity-50' : '']"><div class="flex items-center justify-between"><div class="flex items-center gap-1.5 min-w-0 flex-1">+ <template v-if="joinActive">+ <i class="fas fa-grip-vertical text-[10px] text-[var(--text-muted)] cursor-grab flex-shrink-0" aria-hidden="true"></i>+ <span class="text-[10px] font-semibold text-[var(--text-accent)] w-4 text-right flex-shrink-0" v-text="index + 1"></span>+ </template><!-- File-type icon: video files get avideo glyph so users instantly seewhich queue items are video at a@@ -71,6 +96,18 @@(${ formatFileSize(item.file.size) }<span v-if="item.duration">, ${ formatDuration(item.duration) }</span>)</span></div>+ <template v-if="joinActive">+ <button type="button" @click="moveJoinItem(item.clientId, -1)" :disabled="index === 0"+ class="ml-1 p-0.5 text-[var(--text-muted)] hover:text-[var(--text-accent)] disabled:opacity-30 transition-colors flex-shrink-0"+ :title="t('upload.joinMoveUp')" :aria-label="t('upload.joinMoveUp')">+ <i class="fas fa-arrow-up text-[10px]"></i>+ </button>+ <button type="button" @click="moveJoinItem(item.clientId, 1)" :disabled="index === pendingQueueFiles.length - 1"+ class="p-0.5 text-[var(--text-muted)] hover:text-[var(--text-accent)] disabled:opacity-30 transition-colors flex-shrink-0"+ :title="t('upload.joinMoveDown')" :aria-label="t('upload.joinMoveDown')">+ <i class="fas fa-arrow-down text-[10px]"></i>+ </button>+ </template><button @click="removeFromQueue(item.clientId)"class="ml-1.5 p-0.5 text-[var(--text-muted)] hover:text-red-500 transition-colors flex-shrink-0"title="Remove from queue">@@ -106,6 +143,25 @@</div></div>+ <!-- Join summary: order, total length, title of the joined recording -->+ <div v-if="joinActive" class="mt-2 space-y-1.5">+ <p class="text-[11px] text-[var(--text-muted)]">+ <i class="fas fa-object-group mr-1"></i>+ <span v-if="joinTotalDuration" v-text="t('upload.joinSummary', { count: pendingQueueFiles.length, duration: formatDuration(joinTotalDuration) })"></span>+ <span v-else v-text="t('upload.joinSummaryNoDuration', { count: pendingQueueFiles.length })"></span>+ </p>+ <label class="block">+ <span class="text-[11px] font-medium text-[var(--text-secondary)]" v-text="t('upload.joinTitle')"></span>+ <input type="text" v-model="joinTitle" maxlength="200"+ :placeholder="t('upload.joinTitlePlaceholder')"+ class="mt-0.5 w-full px-2 py-1 text-xs rounded border border-[var(--border-secondary)] bg-[var(--bg-input)] text-[var(--text-primary)] focus:outline-none focus:ring-1 focus:ring-[var(--ring-focus)]">+ </label>+ <p v-if="joinHasVideo" class="flex items-start gap-1.5 text-[11px] leading-snug text-sky-700 dark:text-sky-400">+ <i class="fas fa-video-slash text-xs mt-0.5 flex-shrink-0"></i>+ <span v-text="t('upload.joinVideoHint')"></span>+ </p>+ </div>+<!-- Incognito Mode Toggle (only shown if feature is enabled via ENABLE_INCOGNITO_MODE env var) --><div v-if="enableIncognitoMode" class="mt-3"><button @click="incognitoMode = !incognitoMode"@@ -639,7 +695,7 @@<!-- Normal Upload Buttons (when not in incognito mode or feature disabled) --><div v-if="!incognitoMode || !enableIncognitoMode" class="flex items-center gap-2"><!-- Queue the files but keep the modal open for more -->- <button @click="startUpload"+ <button v-if="!joinActive" @click="startUpload":disabled="pendingQueueFiles.length === 0"class="btn btn--ghost"><i class="fas fa-plus"></i>@@ -651,6 +707,7 @@class="btn btn--primary"><i class="fas fa-cloud-upload-alt"></i><span v-if="pendingQueueFiles.length === 0">${ t('upload.title') || 'Upload' }</span>+ <span v-else-if="joinActive" v-text="t('upload.uploadAndJoin', { count: pendingQueueFiles.length })"></span><span v-else v-text="t('upload.uploadNFiles', { count: pendingQueueFiles.length })"></span></button></div>diff --git a/tests/test_upload_join.py b/tests/test_upload_join.pynew file mode 100644index 00000000..309651bc--- /dev/null+++ b/tests/test_upload_join.py@@ -0,0 +1,442 @@+"""Joining several uploaded files into one recording.++The upload dialog sends each file with join_group / join_index / join_count.+Each file is stored as a part; the file that completes the group creates one+recording and queues the merge job, which joins the parts' audio and queues+a single transcription with the upload's options.++SHARED-DB: every test uses its own users and removes what it created.+"""++import io+import json+import os+import shutil+import subprocess+import sys+import uuid+from contextlib import contextmanager+from datetime import datetime, timedelta+from unittest.mock import MagicMock, patch++import pytest+from flask import g+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 User, Recording, Tag, Folder, RecordingTag, ProcessingJob+from src.models.upload_join import UploadJoinPart+from src.services import upload_join as uj++app.config["WTF_CSRF_ENABLED"] = False+++class _Client(FlaskClient):+ def open(self, *args, **kwargs):+ g.pop('_login_user', None)+ return super().open(*args, **kwargs)+++_users = []+++def ctx(tmp_path):+ with app.app_context():+ yield tmp_path+ db.session.rollback()+ for uid in _users:+ UploadJoinPart.query.filter_by(user_id=uid).delete()+ rec_ids = [r.id for r in Recording.query.filter_by(user_id=uid).all()]+ if rec_ids:+ RecordingTag.query.filter(RecordingTag.recording_id.in_(rec_ids)).delete(synchronize_session=False)+ ProcessingJob.query.filter(ProcessingJob.recording_id.in_(rec_ids)).delete(synchronize_session=False)+ Recording.query.filter(Recording.id.in_(rec_ids)).delete(synchronize_session=False)+ Tag.query.filter_by(user_id=uid).delete()+ Folder.query.filter_by(user_id=uid).delete()+ db.session.commit()+ _users.clear()+++def _user():+ s = uuid.uuid4().hex[:8]+ u = User(username=f"uj_{s}", email=f"uj_{s}@local.test", password="x")+ db.session.add(u)+ db.session.commit()+ _users.append(u.id)+ return u+++def _client(user):+ c = _Client(app, app.response_class)+ with c.session_transaction() as sess:+ sess["_user_id"] = str(user.id)+ sess["_fresh"] = True+ return c+++class _Stored:+ def __init__(self, locator):+ self.locator = locator+ self.key = locator+++class _FakeStorage:+ """Upload-side fake: records stored and deleted locators, moves nothing."""++ def __init__(self, staging):+ self.staging = str(staging)+ self.stored = []+ self.deleted = []++ def get_staging_dir(self):+ os.makedirs(self.staging, exist_ok=True)+ return self.staging++ def build_recording_key(self, original_filename, recording_id=None, *, now=None):+ return f"recordings/test/{recording_id}/{uuid.uuid4().hex[:6]}_{original_filename}"++ def upload_local_file(self, local_path, key, *, content_type=None, delete_source=False):+ self.stored.append(key)+ return _Stored(f"local://{key}")++ def delete(self, locator, missing_ok=True):+ self.deleted.append(locator)+ return True++ def exists(self, locator):+ return locator not in self.deleted+++@contextmanager+def _upload_mocks(staging, durations=None):+ storage = _FakeStorage(staging)+ durations = list(durations or [])++ def _convert(filepath, **kwargs):+ r = MagicMock()+ r.output_path = filepath+ r.was_converted = r.was_compressed = False+ return r++ def _duration(path, timeout=30):+ return durations.pop(0) if durations else 60.0++ with patch("src.api.recordings.get_storage_service", return_value=storage), \+ patch("src.api.recordings.get_codec_info",+ return_value={"has_video": False, "audio_codec": "mp3", "duration": 60.0}), \+ patch("src.api.recordings.convert_if_needed", side_effect=_convert), \+ patch("src.api.recordings.get_duration", side_effect=_duration), \+ patch("src.api.recordings.get_creation_date", return_value=None), \+ patch("src.services.webhook_dispatch.emit_webhook_event") as webhook, \+ patch("src.services.job_queue.job_queue.enqueue", return_value=1) as enqueue:+ yield storage, enqueue, webhook+++def _part(client, group, index, count, name=None, payload=None, **form):+ data = {"join_group": group, "join_index": str(index), "join_count": str(count)}+ data.update(form)+ data["file"] = (io.BytesIO(payload or os.urandom(2048)), name or f"meeting_part{index + 1}.mp3")+ return client.post("/upload", data=data, content_type="multipart/form-data")+++def _group():+ return uuid.uuid4().hex+++# ------------------------------------------------------------ the join++def test_three_files_become_one_recording_with_the_upload_options(ctx):+ user = _user()+ tag = Tag(name=f"t_{uuid.uuid4().hex[:6]}", user_id=user.id)+ folder = Folder(name=f"f_{uuid.uuid4().hex[:6]}", user_id=user.id)+ db.session.add_all([tag, folder])+ db.session.commit()+ c, group = _client(user), _group()+ form = {"tag_ids[0]": str(tag.id), "folder_id": str(folder.id), "language": "de", "notes": "agenda"}+ stamps = [1_700_000_300_000, 1_700_000_100_000, 1_700_000_200_000] # ms, part 2 is the earliest++ with _upload_mocks(ctx, durations=[600.0, 300.0, 120.0]) as (storage, enqueue, webhook):+ bodies = [_part(c, group, i, 3, file_last_modified=str(stamps[i]), **form) for i in range(3)]++ assert [b.status_code for b in bodies] == [202, 202, 202]+ first, second, last = (b.get_json() for b in bodies)+ assert first == {"join_pending": True, "join_group": group, "join_index": 0, "received": 1, "total": 3}+ assert second["received"] == 2 and second["join_pending"]+ assert last["joined_parts"] == 3 and last["id"]++ rec = db.session.get(Recording, last["id"])+ assert rec.status == "QUEUED" and rec.audio_path is None+ assert rec.original_filename == "meeting_part1.m4a"+ assert rec.folder_id == folder.id and [t.id for t in rec.tags] == [tag.id]+ assert rec.notes == "agenda"+ assert rec.audio_duration_seconds == pytest.approx(1020.0)+ assert rec.meeting_date == datetime.utcfromtimestamp(stamps[1] / 1000)++ parts = UploadJoinPart.query.filter_by(user_id=user.id, group_id=group).order_by(UploadJoinPart.part_index).all()+ assert all(p.claimed_at and p.recording_id == rec.id for p in parts)+ jobs = [call.kwargs for call in enqueue.call_args_list]+ assert [j["job_type"] for j in jobs] == ["merge"]+ assert jobs[0]["params"]["part_ids"] == [p.id for p in parts]+ assert jobs[0]["params"]["transcribe_params"]["language"] == "de"+ assert [call.kwargs["event_type"] for call in webhook.call_args_list] == ["recording.created"]+ assert Recording.query.filter_by(user_id=user.id).count() == 1+++def test_parts_may_arrive_in_any_order(ctx):+ user = _user()+ c, group = _client(user), _group()+ with _upload_mocks(ctx) as (storage, enqueue, _):+ for i in (2, 0, 1):+ r = _part(c, group, i, 3)+ body = r.get_json()+ assert body["joined_parts"] == 3+ params = enqueue.call_args.kwargs["params"]+ order = [db.session.get(UploadJoinPart, pid).part_index for pid in params["part_ids"]]+ assert order == [0, 1, 2]+++def test_a_user_title_is_kept(ctx):+ user = _user()+ c, group = _client(user), _group()+ with _upload_mocks(ctx):+ _part(c, group, 0, 2, title="Board meeting")+ body = _part(c, group, 1, 2, title="Board meeting").get_json()+ assert db.session.get(Recording, body["id"]).title == "Board meeting"+++# ------------------------------------------------------------ retries and races++def test_retrying_a_part_after_the_join_returns_the_same_recording(ctx):+ user = _user()+ c, group = _client(user), _group()+ with _upload_mocks(ctx) as (storage, enqueue, _):+ _part(c, group, 0, 2)+ joined = _part(c, group, 1, 2).get_json()+ again = _part(c, group, 1, 2).get_json()+ assert again["id"] == joined["id"] and again["idempotent_replay"] is True+ assert Recording.query.filter_by(user_id=user.id).count() == 1+ assert enqueue.call_count == 1+++def test_retrying_a_part_before_the_join_replaces_it(ctx):+ user = _user()+ c, group = _client(user), _group()+ with _upload_mocks(ctx) as (storage, enqueue, _):+ _part(c, group, 0, 3)+ first_locator = UploadJoinPart.query.filter_by(user_id=user.id, group_id=group).one().audio_path+ body = _part(c, group, 0, 3).get_json()+ assert body["received"] == 1+ part = UploadJoinPart.query.filter_by(user_id=user.id, group_id=group).one()+ assert part.audio_path != first_locator and first_locator in storage.deleted+++def test_a_group_is_claimed_once(ctx):+ user = _user()+ c, group = _client(user), _group()+ with _upload_mocks(ctx):+ _part(c, group, 0, 2)+ # Store the last part without letting the request claim the group.+ with patch("src.services.upload_join.claim_group", return_value=None):+ _part(c, group, 1, 2)+ assert uj.claim_group(user.id, group, 2) is not None+ db.session.commit()+ assert uj.claim_group(user.id, group, 2) is None+++def test_join_groups_belong_to_one_user(ctx):+ alice, bob = _user(), _user()+ group = _group()+ with _upload_mocks(ctx):+ _part(_client(alice), group, 0, 2)+ body = _part(_client(bob), group, 1, 2).get_json()+ assert body["join_pending"] and body["received"] == 1+ assert Recording.query.filter(Recording.user_id.in_([alice.id, bob.id])).count() == 0++[email protected]("fields", [+ {"join_group": "short", "join_index": "0", "join_count": "2"},+ {"join_group": "has spaces in it", "join_index": "0", "join_count": "2"},+ {"join_group": "abcdefgh12", "join_index": "0", "join_count": "1"},+ {"join_group": "abcdefgh12", "join_index": "0", "join_count": "21"},+ {"join_group": "abcdefgh12", "join_index": "2", "join_count": "2"},+ {"join_group": "abcdefgh12", "join_index": "x", "join_count": "2"},+])+def test_invalid_join_fields_are_rejected(ctx, fields):+ user = _user()+ data = dict(fields)+ data["file"] = (io.BytesIO(b"\x00" * 64), "a.mp3")+ with _upload_mocks(ctx):+ r = _client(user).post("/upload", data=data, content_type="multipart/form-data")+ assert r.status_code == 400+ assert UploadJoinPart.query.filter_by(user_id=user.id).count() == 0+++# ------------------------------------------------------------ giving up and cleanup++def test_discarding_a_join_removes_its_parts(ctx):+ user = _user()+ c, group = _client(user), _group()+ with _upload_mocks(ctx):+ _part(c, group, 0, 3)+ _part(c, group, 1, 3)+ storage = _FakeStorage(ctx)+ with patch("src.services.storage.get_storage_service", return_value=storage):+ r = c.delete(f"/upload/join/{group}")+ assert r.get_json() == {"success": True, "removed": 2}+ assert UploadJoinPart.query.filter_by(user_id=user.id).count() == 0+ assert len(storage.deleted) == 2+++def test_cleanup_removes_stale_parts_but_waits_for_a_pending_merge(ctx):+ user = _user()+ old = datetime.utcnow() - timedelta(hours=30)+ waiting = Recording(user_id=user.id, title="w", status="QUEUED", audio_path=None, original_filename="w.m4a")+ done = Recording(user_id=user.id, title="d", status="COMPLETED", audio_path="local://d", original_filename="d.m4a")+ db.session.add_all([waiting, done])+ db.session.flush()+ rows = [+ UploadJoinPart(user_id=user.id, group_id="abandoned1", part_index=0, part_count=2,+ audio_path="local://a", created_at=old),+ UploadJoinPart(user_id=user.id, group_id="waiting123", part_index=0, part_count=2,+ audio_path="local://w", created_at=old, claimed_at=old, recording_id=waiting.id),+ UploadJoinPart(user_id=user.id, group_id="finished12", part_index=0, part_count=2,+ audio_path=None, created_at=old, claimed_at=old, recording_id=done.id),+ UploadJoinPart(user_id=user.id, group_id="fresh12345", part_index=0, part_count=2,+ audio_path="local://f"),+ ]+ db.session.add_all(rows)+ db.session.commit()+ storage = _FakeStorage(ctx)+ removed = uj.cleanup_stale_parts(storage=storage)+ assert removed >= 2+ left = {p.group_id for p in UploadJoinPart.query.filter_by(user_id=user.id).all()}+ assert left == {"waiting123", "fresh12345"}+ assert storage.deleted == ["local://a"]+++# ------------------------------------------------------------ the merge job++class _MergeStorage(_FakeStorage):+ def __init__(self, staging, paths=None):+ super().__init__(staging)+ self.paths = paths or {}++ @contextmanager+ def materialize(self, locator):+ m = MagicMock()+ m.local_path = self.paths.get(locator, "/nonexistent")+ yield m+++def _claimed_group(user, n=2, locators=None):+ group = _group()+ parts = []+ for i in range(n):+ p = UploadJoinPart(user_id=user.id, group_id=group, part_index=i, part_count=n,+ audio_path=(locators or [f"local://p{i}"] * n)[i], original_filename=f"p{i}.wav",+ file_size=10, audio_duration_seconds=1.0)+ db.session.add(p)+ parts.append(p)+ db.session.commit()+ assert uj.claim_group(user.id, group, n) is not None+ with patch("src.services.job_queue.job_queue.enqueue", return_value=1) as enqueue:+ rec = uj.create_joined_recording(user, parts, transcribe_params={"language": "fr"})+ return rec, parts, enqueue.call_args.kwargs["params"]+++def test_merge_job_joins_parts_and_queues_one_transcription(ctx):+ from src.services import recording_merge+ user = _user()+ rec, parts, params = _claimed_group(user)+ storage = _MergeStorage(ctx)++ def _fake_concat(inputs, output):+ assert len(inputs) == 2+ with open(output, "wb") as f:+ f.write(b"\x00" * 1024)++ with patch("src.services.recording_merge.get_storage_service", return_value=storage), \+ patch("src.services.recording_merge._concat_audio", side_effect=_fake_concat), \+ patch("src.services.recording_merge.job_queue.enqueue", return_value=1) as enqueue:+ recording_merge.run_merge_job(rec, params)++ db.session.expire_all()+ rec = db.session.get(Recording, rec.id)+ assert rec.audio_path and rec.file_size == 1024+ assert all(db.session.get(UploadJoinPart, p.id).audio_path is None for p in parts)+ assert sorted(storage.deleted) == ["local://p0", "local://p1"]+ assert enqueue.call_args.kwargs["job_type"] == "transcribe"+ assert enqueue.call_args.kwargs["params"] == {"language": "fr"}+++def test_merge_job_refuses_parts_of_another_recording(ctx):+ from src.services import recording_merge+ user = _user()+ rec_a, _, params_a = _claimed_group(user)+ rec_b, _, _ = _claimed_group(user)+ with patch("src.services.recording_merge.get_storage_service", return_value=_MergeStorage(ctx)):+ with pytest.raises(recording_merge.MergeError):+ recording_merge.run_merge_job(rec_b, params_a)++[email protected](shutil.which("ffmpeg") is None, reason="ffmpeg not installed")+def test_merge_job_really_joins_the_audio(ctx):+ """End to end through ffmpeg: two tones become one file as long as both."""+ from src.services import recording_merge+ from src.utils.ffprobe import get_duration+ paths = {}+ for i, (freq, secs) in enumerate([(440, 1.0), (660, 2.0)]):+ path = os.path.join(str(ctx), f"tone{i}.wav")+ subprocess.run(["ffmpeg", "-loglevel", "error", "-y", "-f", "lavfi",+ "-i", f"sine=frequency={freq}:duration={secs}", path], check=True)+ paths[f"local://tone{i}"] = path+ user = _user()+ rec, _, params = _claimed_group(user, locators=list(paths))+ storage = _MergeStorage(ctx, paths)+ kept = {}++ def _keep(local_path, key, *, content_type=None, delete_source=False):+ dest = os.path.join(str(ctx), "joined.m4a")+ shutil.copy(local_path, dest)+ kept["path"] = dest+ return _Stored(f"local://{key}")++ storage.upload_local_file = _keep+ with patch("src.services.recording_merge.get_storage_service", return_value=storage), \+ patch("src.services.recording_merge.job_queue.enqueue", return_value=1):+ recording_merge.run_merge_job(rec, params)+ assert get_duration(kept["path"]) == pytest.approx(3.0, abs=0.2)+++# ------------------------------------------------------------ sliced uploads++def test_a_lost_response_for_a_sliced_part_is_answered_on_retry(ctx):+ """A large part goes up in slices; if the finalize response is lost, the+ retry is answered with the join's state, not a 409."""+ from src.models import RecordingSession+ user = _user()+ c, group = _client(user), _group()+ session = RecordingSession(user_id=user.id, kind='sliced_upload', status='finalized',+ upload_filename='p0.wav', mime_type='audio/wav',+ finalized_at=datetime.utcnow(), finalized_recording_id=None)+ db.session.add(session)+ db.session.commit()+ try:+ form = {"join_group": group, "join_index": "0", "join_count": "2"}+ with _upload_mocks(ctx):+ db.session.add(UploadJoinPart(user_id=user.id, group_id=group, part_index=0, part_count=2,+ audio_path="local://p0"))+ db.session.commit()+ body = c.post(f"/upload/session/{session.id}/finalize-upload", data=form).get_json()+ assert body["join_pending"] and body["received"] == 1 and body["idempotent_replay"]++ with _upload_mocks(ctx):+ joined = _part(c, group, 1, 2).get_json()+ again = c.post(f"/upload/session/{session.id}/finalize-upload", data=form).get_json()+ assert again["id"] == joined["id"] and again["idempotent_replay"] is True+ finally:+ db.session.delete(db.session.get(RecordingSession, session.id))+ db.session.commit()