Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Storage quotas per user (#413)

Murtaza Nasire02fa3f0601f
diff --git a/docs/admin-guide/system-settings.md b/docs/admin-guide/system-settings.md
index 0c75d0bd..4426c8a3 100644
--- a/docs/admin-guide/system-settings.md
+++ b/docs/admin-guide/system-settings.md
@@ -14,6 +14,10 @@ Setting a character limit (like 50,000 characters) creates a ceiling on API cons
The sweet spot depends on your use case. For typical meetings under an hour, 50,000 characters usually captures everything. For longer sessions, you might increase this limit or train users to split recordings. Monitor your API costs and user feedback to find the right balance.
+## Default Storage Quota
+
+**`default_storage_quota_mb`** (default 0, no limit) is the storage quota given to accounts created from now on, by an administrator, by registration or by SSO. Existing accounts keep their own quota, which is set per user in Edit User. See [Storage Quotas](user-management.md#storage-quotas).
+
## Maximum File Size
Two separate caps apply depending on file type:
diff --git a/docs/admin-guide/user-management.md b/docs/admin-guide/user-management.md
index 635cc891..0604e855 100644
--- a/docs/admin-guide/user-management.md
+++ b/docs/admin-guide/user-management.md
@@ -60,6 +60,23 @@ Transcription budgets are set in minutes with a minimum of 10 minutes. The budge
- **OpenAI Transcribe**: $0.003-$0.006 per minute depending on model
- **Self-hosted ASR**: $0 (no external API costs)
+### Storage Quotas
+
+Limit how much audio and video each user keeps on the server. Set **Storage quota (MB)** when creating or editing a user; leave it empty for no limit. The Edit User dialog and the users table show the storage in use against the quota, and so does the users table in [System Statistics](statistics.md#users).
+
+**What counts**: the size of the user's own recordings whose audio is kept, including archived recordings and recordings protected from auto-deletion. Recordings with their audio removed do not count, and a recording shared with someone counts for its owner only.
+
+**When the quota is reached**:
+
+- **Uploads** from the browser, the API, the share target, the ASR Voice Recorder app and sliced uploads are refused when the file would go over the quota. The user sees how much is used and how large the file is. The API answers `507` with the code `storage_quota_exceeded`.
+- **Recordings made in the app** cannot start once the quota is reached. A recording already in progress is always kept, even if it goes over the quota.
+- **The watch folder** leaves a file that does not fit where it is and tells the user once, in their notifications. The file is added on a later scan once there is room.
+- **Merging** recordings that keeps the originals needs room for the merged copy; a merge that deletes the originals is always allowed.
+
+Users see their storage, and the quota when there is one, under **Account → Account Statistics**. They free space by deleting recordings or by removing their audio.
+
+**Default for new accounts**: the System Setting `default_storage_quota_mb` gives every account created afterwards a quota (0 means no limit). It applies to accounts created by an administrator, by registration and by SSO; existing accounts keep their own quota.
+
## Managing Existing Users
Each user row includes action buttons that give you complete control over that account. The edit button opens a modal where you can update their username or email address. This is useful when people change names, switch email providers, or when you need to correct initial entry mistakes.
diff --git a/docs/user-guide/api-reference.md b/docs/user-guide/api-reference.md
index 7fc5080b..c9f38e0d 100644
--- a/docs/user-guide/api-reference.md
+++ b/docs/user-guide/api-reference.md
@@ -248,10 +248,17 @@ Returns the authenticated user's profile, preferences, and group memberships. Us
"role": "admin",
"joined_at": "2024-01-10T08:00:00Z"
}
- ]
+ ],
+ "storage": {
+ "used_bytes": 244862976,
+ "quota_bytes": 314572800,
+ "available_bytes": 69709824
+ }
}
```
+`storage.quota_bytes` and `storage.available_bytes` are `null` when the user has no storage quota.
+
---
## Recordings
@@ -315,6 +322,21 @@ The meeting date is chosen in this order: `meeting_date`, a date in the file nam
`ignored` lists the tags and folder the upload dropped because you cannot use them.
+An upload that would go over the user's storage quota is refused with `507 Insufficient Storage`:
+
+```json
+{
+ "error": "This upload would exceed your storage quota: 233.5 MB of 300.0 MB used, and the file is 80.0 MB.",
+ "code": "storage_quota_exceeded",
+ "used_bytes": 244862976,
+ "quota_bytes": 314572800,
+ "file_bytes": 83886080,
+ "available_bytes": 69709824
+}
+```
+
+`GET /api/v1/users/me` reports the same figures under `storage`, and `/api/v1/capabilities` lists `storage_quota`.
+
**Example:**
```bash
diff --git a/src/api/admin.py b/src/api/admin.py
index 748afa89..f8b743cd 100644
--- a/src/api/admin.py
+++ b/src/api/admin.py
@@ -19,6 +19,7 @@ from src.services.retention import is_recording_exempt_from_deletion, get_retent
from src.services.embeddings import EMBEDDINGS_AVAILABLE, process_recording_chunks
from src.services.token_tracking import token_tracker
from src.services.transcription_tracking import transcription_tracker
+from src.services.storage_quota import default_quota_mb
from src.config.startup import get_file_monitor_functions
# Create blueprint
@@ -174,6 +175,7 @@ def admin_get_users():
'can_share_publicly': user.can_share_publicly,
'recordings_count': recordings_count,
'storage_used': storage_used,
+ 'storage_quota_mb': user.storage_quota_mb,
'monthly_token_budget': user.monthly_token_budget,
'current_token_usage': current_usage,
'token_usage_percentage': round(usage_percentage, 1),
@@ -213,6 +215,11 @@ def admin_add_user():
if User.find_by_email(email):
return jsonify({'error': 'Email already exists'}), 400
+ try:
+ storage_quota = _quota_mb(data['storage_quota_mb']) if 'storage_quota_mb' in data else default_quota_mb()
+ except (TypeError, ValueError):
+ return jsonify({'error': 'The storage quota must be a positive number of MB.'}), 400
+
# Create new user
hashed_password = bcrypt.generate_password_hash(data['password']).decode('utf-8')
new_user = User(
@@ -221,7 +228,8 @@ def admin_add_user():
password=hashed_password,
is_admin=data.get('is_admin', False),
monthly_token_budget=data.get('monthly_token_budget'),
- monthly_transcription_budget=data.get('monthly_transcription_budget')
+ monthly_transcription_budget=data.get('monthly_transcription_budget'),
+ storage_quota_mb=storage_quota,
)
db.session.add(new_user)
@@ -234,6 +242,7 @@ def admin_add_user():
'is_admin': new_user.is_admin,
'recordings_count': 0,
'storage_used': 0,
+ 'storage_quota_mb': new_user.storage_quota_mb,
'monthly_token_budget': new_user.monthly_token_budget,
'current_token_usage': 0,
'token_usage_percentage': 0,
@@ -309,6 +318,12 @@ def admin_update_user(user_id):
else:
user.monthly_transcription_budget = int(budget)
+ if 'storage_quota_mb' in data:
+ try:
+ user.storage_quota_mb = _quota_mb(data['storage_quota_mb'])
+ except (TypeError, ValueError):
+ return jsonify({'error': 'The storage quota must be a positive number of MB.'}), 400
+
db.session.commit()
# Get recordings count and storage used
@@ -331,6 +346,7 @@ def admin_update_user(user_id):
'can_share_publicly': user.can_share_publicly,
'recordings_count': recordings_count,
'storage_used': storage_used,
+ 'storage_quota_mb': user.storage_quota_mb,
'monthly_token_budget': user.monthly_token_budget,
'current_token_usage': current_usage,
'token_usage_percentage': round(usage_percentage, 1),
@@ -420,6 +436,16 @@ def admin_toggle_admin(user_id):
+def _quota_mb(value):
+ """A storage quota from the admin form: a positive number of MB, or no limit."""
+ if value in (None, '', 0, '0'):
+ return None
+ value = int(value)
+ if value < 0:
+ raise ValueError('storage_quota_mb must be positive')
+ return value
+
+
@admin_bp.route('/admin/stats', methods=['GET'])
@login_required
def admin_get_stats():
diff --git a/src/api/api_v1.py b/src/api/api_v1.py
index b3f017dc..82a92a17 100644
--- a/src/api/api_v1.py
+++ b/src/api/api_v1.py
@@ -321,7 +321,7 @@ OPENAPI_SPEC = {
"get": {
"tags": ["Users"],
"summary": "Get current user profile",
- "description": "Returns the authenticated user's profile (id, username, email, name, role flags, preferences) and group memberships.",
+ "description": "Returns the authenticated user's profile (id, username, email, name, role flags, preferences), group memberships, and storage (used_bytes, quota_bytes, available_bytes; quota_bytes is null when there is no quota).",
"responses": {"200": {"description": "User profile object"}}
}
},
@@ -482,7 +482,7 @@ OPENAPI_SPEC = {
}
}
},
- "responses": {"202": {"description": "Upload accepted and queued"}}
+ "responses": {"202": {"description": "Upload accepted and queued"}, "507": {"description": "The upload would exceed the user's storage quota (code storage_quota_exceeded, with used_bytes, quota_bytes and file_bytes)"}}
}
},
"/integrations/asr-voice-recorder/upload": {
@@ -918,6 +918,7 @@ def get_current_token():
# ships; a missing key means false.
CAPABILITY_FEATURES = {
'token_scopes': True,
+ 'storage_quota': True,
'changes_feed': True,
'etags': True,
'webhook_signature_v2': True,
@@ -1005,9 +1006,19 @@ def get_current_user():
'diarize': _effective_diarize(),
},
'group_memberships': memberships,
+ # Storage used and the quota, NULL when there is none (#413). An upload
+ # over the quota is refused with 507 and code storage_quota_exceeded.
+ 'storage': _storage_usage_for_api(current_user),
})
+def _storage_usage_for_api(user):
+ from src.services.storage_quota import usage
+ u = usage(user)
+ return {'used_bytes': u['used_bytes'], 'quota_bytes': u['quota_bytes'],
+ 'available_bytes': u['available_bytes']}
+
+
# =============================================================================
# Recordings List with Enhanced Filtering
# =============================================================================
diff --git a/src/api/auth.py b/src/api/auth.py
index db0f9344..bea56815 100644
--- a/src/api/auth.py
+++ b/src/api/auth.py
@@ -211,6 +211,8 @@ def register():
password=hashed_password,
email_verified=email_verified
)
+ from src.services.storage_quota import default_quota_mb
+ user.storage_quota_mb = default_quota_mb()
db.session.add(user)
db.session.commit()
@@ -612,6 +614,23 @@ def reset_password(token):
return render_template('auth/reset_password.html', title='Reset Password', token=token)
+def _storage_usage(user):
+ try:
+ from src.services.storage_quota import usage
+ return usage(user)
+ except Exception as e:
+ current_app.logger.warning(f"Could not read storage usage for user {user.id}: {e}")
+ return None
+
+
+@auth_bp.route('/api/account/storage', methods=['GET'])
+@login_required
+def account_storage():
+ """The signed-in user's storage use and quota (#413)."""
+ from src.services.storage_quota import usage
+ return jsonify(usage(current_user))
+
+
@auth_bp.route('/account', methods=['GET', 'POST'])
@login_required
def account():
@@ -860,6 +879,7 @@ def account():
return render_template('account.html',
title='Account',
+ storage_usage=_storage_usage(current_user),
default_summary_prompt_text=default_summary_prompt_text,
default_title_prompt_text=default_title_prompt_text,
use_asr_endpoint=USE_ASR_ENDPOINT,
diff --git a/src/api/recording_sessions.py b/src/api/recording_sessions.py
index abb38622..ed59ffca 100644
--- a/src/api/recording_sessions.py
+++ b/src/api/recording_sessions.py
@@ -390,6 +390,14 @@ def create_session():
'quota_bytes': _max_bytes_per_user(),
}), 507 # Insufficient Storage
+ # Storage quota (#413). A sliced upload must fit. A recording can start
+ # only below the quota, and is then accepted whatever its length.
+ from src.services.storage_quota import check_room, StorageQuotaExceeded
+ try:
+ check_room(current_user, total_bytes or 0)
+ except StorageQuotaExceeded as quota_error:
+ return quota_error.response()
+
session = RecordingSession(
user_id=current_user.id,
mime_type=mime_type,
diff --git a/src/api/recordings.py b/src/api/recordings.py
index a8db96c2..be4477ee 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -824,6 +824,17 @@ def merge_recordings_endpoint():
else:
notes_source_id = _UNSET
+ # Storage quota (#413): keeping the originals adds a copy of their audio.
+ if not delete_originals:
+ from src.services.storage_quota import check_room, StorageQuotaExceeded
+ merged_bytes = db.session.query(db.func.coalesce(db.func.sum(Recording.file_size), 0)).filter(
+ Recording.id.in_([int(i) for i in recording_ids if str(i).isdigit()]),
+ Recording.user_id == current_user.id, Recording.audio_deleted_at.is_(None)).scalar() or 0
+ try:
+ check_room(current_user, int(merged_bytes))
+ except StorageQuotaExceeded as quota_error:
+ return quota_error.response()
+
try:
recording = create_merge_recording(
current_user,
@@ -2128,7 +2139,7 @@ def share_target():
data = resp.get_json(silent=True) or {}
if status >= 400 or not data.get('id'):
current_app.logger.warning(f"share-target ingest failed ({status}): {data.get('error')}")
- error = 'too_large' if status == 413 else 'save_failed'
+ error = {413: 'too_large', 507: 'storage_quota'}.get(status, 'save_failed')
return redirect(url_for('recordings.index') + f'?share_target_error={error}')
return redirect(url_for('recordings.index') + f"?share_target=ok&recording_id={data['id']}")
@@ -2273,6 +2284,20 @@ def ingest_uploaded_recording(
):
raise RequestEntityTooLarge()
+ # Storage quota (#413). A recording made in this browser was checked
+ # when it started and is not refused at the end, so it is never lost;
+ # only a signed-in browser can say so, never an API token.
+ from src.services.storage_quota import check_room, StorageQuotaExceeded
+ from src.utils.token_auth import current_api_token
+ recorded_in_app = (str(form.get('from_recorder', '')).lower() == 'true'
+ and current_api_token() is None)
+ if not recorded_in_app:
+ try:
+ check_room(owner, original_file_size)
+ except StorageQuotaExceeded as quota_error:
+ current_app.logger.info(f"Upload refused for user {owner.id}: {quota_error}")
+ return quota_error.response()
+
file.save(filepath)
current_app.logger.info(f"File saved to {filepath}")
diff --git a/src/auth/sso.py b/src/auth/sso.py
index 2e13d914..b381a649 100644
--- a/src/auth/sso.py
+++ b/src/auth/sso.py
@@ -229,6 +229,8 @@ def create_or_update_sso_user(userinfo: Dict[str, str]) -> User:
sso_subject=subject,
name=name_value,
)
+ from src.services.storage_quota import default_quota_mb
+ user.storage_quota_mb = default_quota_mb()
db.session.add(user)
db.session.commit()
return user
diff --git a/src/file_monitor.py b/src/file_monitor.py
index 99b49563..c8877602 100644
--- a/src/file_monitor.py
+++ b/src/file_monitor.py
@@ -66,7 +66,10 @@ class FileMonitor:
self._valid_users = {} # Maps user_id to username
self._username_to_id = {} # Maps username to user_id
self._last_user_cache_update = 0
-
+
+ # Files left in the folder for the storage quota, logged once (#413)
+ self._quota_skipped = set()
+
def start(self):
"""Start the file monitoring in a background thread."""
if self.running:
@@ -349,6 +352,22 @@ class FileMonitor:
# Derive original filename by removing .processing suffix
original_filename = processing_path.name.replace('.processing', '')
+
+ # Storage quota (#413): a file that does not fit stays in the
+ # folder untouched and is tried again on later scans; the user
+ # gets one notification, resolved when there is room.
+ from src.services.storage_quota import check_room, StorageQuotaExceeded, raise_notice
+ try:
+ check_room(user, processing_path.stat().st_size)
+ except StorageQuotaExceeded as quota_error:
+ original_path = processing_path.with_name(original_filename)
+ processing_path.rename(original_path)
+ if str(original_path) not in self._quota_skipped:
+ self._quota_skipped.add(str(original_path))
+ self.logger.info(f"Left {original_path} in the watch folder: {quota_error}")
+ raise_notice(user, quota_error, original_filename)
+ return
+ self._quota_skipped.discard(str(processing_path.with_name(original_filename)))
safe_filename = secure_filename(original_filename)
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
new_filename = f"auto_{timestamp}_{safe_filename}"
diff --git a/src/init_db.py b/src/init_db.py
index 197ffe1f..83f03d07 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -397,6 +397,10 @@ def _run_migrations(app, engine):
if add_column_if_not_exists(engine, 'user', 'monthly_transcription_budget', 'INTEGER'):
app.logger.info("Added monthly_transcription_budget column to user table")
+ # Storage quota in megabytes (#413)
+ if add_column_if_not_exists(engine, 'user', 'storage_quota_mb', 'INTEGER'):
+ app.logger.info("Added storage_quota_mb column to user table")
+
# Naming templates feature
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")
@@ -855,6 +859,15 @@ def _run_migrations(app, engine):
)
app.logger.info("Initialized default transcript_length_limit setting")
+ if not SystemSetting.query.filter_by(key='default_storage_quota_mb').first():
+ SystemSetting.set_setting(
+ key='default_storage_quota_mb',
+ value='0',
+ description='Storage quota in megabytes (MB) given to new accounts. 0 means no limit. Existing accounts keep their own quota, set in Edit User.',
+ setting_type='integer'
+ )
+ app.logger.info("Initialized default default_storage_quota_mb setting")
+
if not SystemSetting.query.filter_by(key='max_file_size_mb').first():
SystemSetting.set_setting(
key='max_file_size_mb',
diff --git a/src/models/user.py b/src/models/user.py
index ae38529c..fb66fb0b 100644
--- a/src/models/user.py
+++ b/src/models/user.py
@@ -54,6 +54,9 @@ class User(db.Model, UserMixin):
# Transcription budget in seconds (None = unlimited)
monthly_transcription_budget = db.Column(db.Integer, nullable=True)
+ # Storage quota in megabytes (None = unlimited, #413)
+ storage_quota_mb = db.Column(db.Integer, nullable=True)
+
# Email verification fields
email_verified = db.Column(db.Boolean, default=False)
email_verification_token = db.Column(db.String(200), nullable=True, index=True)
diff --git a/src/services/admin_stats.py b/src/services/admin_stats.py
index e9ee659a..d52db7b8 100644
--- a/src/services/admin_stats.py
+++ b/src/services/admin_stats.py
@@ -224,6 +224,8 @@ def build_overview(days=30, today=None):
tb, sb = u.monthly_token_budget, u.monthly_transcription_budget
users.append({
'id': u.id, 'username': u.username, 'recordings': n, 'storage': size,
+ 'storage_quota': u.storage_quota_mb * 1024 * 1024 if u.storage_quota_mb else None,
+ 'storage_pct': round(size / (u.storage_quota_mb * 1024 * 1024) * 100, 1) if u.storage_quota_mb else None,
'last_recording_at': last.isoformat() + 'Z' if last else None,
'tokens_month': tokens, 'token_budget': tb,
'token_pct': round(tokens / tb * 100, 1) if tb else None,
diff --git a/src/services/storage_quota.py b/src/services/storage_quota.py
new file mode 100644
index 00000000..586e438b
--- /dev/null
+++ b/src/services/storage_quota.py
@@ -0,0 +1,126 @@
+"""Per-user storage quotas (#413).
+
+A user's storage is the size of their own recordings whose audio is still
+kept, the same figure the admin pages show: recordings with their audio
+removed do not count, archived and deletion-exempt ones do, and a recording
+shared with someone counts for its owner only. `user.storage_quota_mb` is the
+limit in megabytes (MiB); NULL means no limit.
+
+Uploads are refused when they would go over the limit. A recording made in
+the app is checked when it starts, never when it ends, so a recording in
+progress is never lost to the quota.
+"""
+
+import logging
+
+from src.database import db
+
+logger = logging.getLogger(__name__)
+
+MB = 1024 * 1024
+KIND_STORAGE_QUOTA_REACHED = 'storage.quota_reached'
+
+
+def _mb(n):
+ return f'{n / MB:,.1f} MB'
+
+
+class StorageQuotaExceeded(Exception):
+ def __init__(self, used_bytes, quota_bytes, file_bytes=0):
+ self.used_bytes, self.quota_bytes, self.file_bytes = used_bytes, quota_bytes, file_bytes
+ super().__init__(f"Storage quota exceeded: {used_bytes} used + {file_bytes} new > {quota_bytes}")
+
+ def to_dict(self):
+ return {
+ 'error': (f'This upload would exceed your storage quota: {_mb(self.used_bytes)} of '
+ f'{_mb(self.quota_bytes)} used, and the file is {_mb(self.file_bytes)}.'
+ if self.file_bytes else
+ f'Your storage quota is full: {_mb(self.used_bytes)} of {_mb(self.quota_bytes)} used.'),
+ 'code': 'storage_quota_exceeded',
+ 'used_bytes': self.used_bytes,
+ 'quota_bytes': self.quota_bytes,
+ 'file_bytes': self.file_bytes,
+ 'available_bytes': max(self.quota_bytes - self.used_bytes, 0),
+ }
+
+ def response(self):
+ from flask import jsonify
+ # 507 Insufficient Storage, as recording sessions return for their
+ # in-progress cap.
+ return jsonify(self.to_dict()), 507
+
+
+def storage_used(user_id):
+ from src.models import Recording
+ return int(db.session.query(db.func.coalesce(db.func.sum(Recording.file_size), 0))
+ .filter(Recording.user_id == user_id, Recording.audio_deleted_at.is_(None)).scalar() or 0)
+
+
+def quota_bytes(user):
+ mb = getattr(user, 'storage_quota_mb', None)
+ return int(mb) * MB if mb else None
+
+
+def usage(user):
+ """Used bytes, quota and percentage, for the account page and the API."""
+ used = storage_used(user.id)
+ quota = quota_bytes(user)
+ return {
+ 'used_bytes': used,
+ 'quota_bytes': quota,
+ 'quota_mb': getattr(user, 'storage_quota_mb', None),
+ 'available_bytes': max(quota - used, 0) if quota else None,
+ 'percentage': round(used / quota * 100, 1) if quota else None,
+ }
+
+
+def check_room(user, file_bytes=0):
+ """Raise StorageQuotaExceeded when `file_bytes` more would go over the quota.
+
+ With file_bytes=0 it asks whether anything new may start at all, which is
+ the check for a recording about to begin: refused at or over the quota.
+ """
+ quota = quota_bytes(user)
+ if quota is None:
+ return
+ used = storage_used(user.id)
+ over = used >= quota if not file_bytes else used + int(file_bytes) > quota
+ if over:
+ raise StorageQuotaExceeded(used, quota, int(file_bytes or 0))
+ resolve_notice(user)
+
+
+def raise_notice(user, exc, filename=None):
+ """Tell the user a file was left out, once: the notice is a condition,
+ resolved when there is room again."""
+ try:
+ from src.services.notifications import notify
+ notify(KIND_STORAGE_QUOTA_REACHED, 'notifications.storageQuotaReached',
+ user_ids=[user.id], level='warning', link='/account',
+ params={'used_mb': exc.used_bytes // MB, 'quota_mb': exc.quota_bytes // MB,
+ 'filename': filename or ''},
+ dedupe_key=f'{KIND_STORAGE_QUOTA_REACHED}:{user.id}')
+ except Exception as e:
+ logger.warning('Could not raise the storage quota notification for user %s: %s', user.id, e)
+
+
+def resolve_notice(user):
+ try:
+ from src.models import Notification
+ if not Notification.query.filter_by(user_id=user.id, dedupe_key=f'{KIND_STORAGE_QUOTA_REACHED}:{user.id}',
+ resolved_at=None).first():
+ return
+ from src.services.notifications import resolve
+ resolve(f'{KIND_STORAGE_QUOTA_REACHED}:{user.id}', user_ids=[user.id])
+ except Exception as e:
+ logger.debug('Could not resolve the storage quota notification for user %s: %s', user.id, e)
+
+
+def default_quota_mb():
+ """The admin's default for new accounts (System Settings), or None."""
+ try:
+ from src.models import SystemSetting
+ value = int(SystemSetting.get_setting('default_storage_quota_mb', 0) or 0)
+ return value if value > 0 else None
+ except Exception:
+ return None
diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.js
index ca96ce1d..ece2680f 100644
--- a/static/js/modules/composables/audio.js
+++ b/static/js/modules/composables/audio.js
@@ -540,7 +540,33 @@ export function useAudio(state, utils) {
// existing server session after a page reload: a fresh MediaRecorder keeps
// POSTing chunks to the same session id, and its header chunk starts a new
// segment that the server-side assembly concatenates onto the prior audio.
+ // Storage quota (#413): a new recording starts only below the quota, and
+ // once started it is kept whatever its length. A failed check never
+ // blocks the recorder.
+ const hasStorageRoom = async () => {
+ try {
+ const response = await fetch('/api/account/storage', { credentials: 'same-origin' });
+ if (!response.ok) return true;
+ const usage = await response.json();
+ if (!usage.quota_bytes || usage.used_bytes < usage.quota_bytes) return true;
+ const message = (utils.t && utils.t('storageQuota.recordingBlocked', {
+ used: formatFileSize(usage.used_bytes), quota: formatFileSize(usage.quota_bytes),
+ })) || 'Your storage is full. Delete recordings or remove their audio before recording again.';
+ setGlobalError(message);
+ return false;
+ } catch (e) {
+ return true;
+ }
+ };
+
const startRecordingInternal = async (mode, resumeContext = null) => {
+ if (!resumeContext && !(incognitoMode && incognitoMode.value) && !(await hasStorageRoom())) {
+ if (pendingDisplayStream) {
+ pendingDisplayStream.getTracks().forEach(track => track.stop());
+ pendingDisplayStream = null;
+ }
+ return;
+ }
try {
recordingMode.value = mode;
recordingVideoActive.value = false;
diff --git a/static/js/modules/composables/upload.js b/static/js/modules/composables/upload.js
index 4fa19ddf..224ff71e 100644
--- a/static/js/modules/composables/upload.js
+++ b/static/js/modules/composables/upload.js
@@ -25,6 +25,7 @@ function getFriendlyError(errorMessage, t) {
// generic 413 pattern below; the proxy rejects the request body before
// Speakr sees it, so enabling chunking on the Speakr side will not help.
{ patterns: ['request entity too large', 'request body is too large', '413 request entity too large'], title: _t('errors.uploadBlockedByProxyTitle'), guidance: _t('errors.uploadBlockedByProxyGuidance') },
+ { patterns: ['storage quota', 'storage is full'], title: _t('storageQuota.title'), guidance: _t('storageQuota.guidance') },
{ patterns: ['maximum content size limit', 'file too large', 'payload too large', 'exceeded', 'content too large'], title: _t('errors.fileTooLargeTitle'), guidance: _t('errors.enableChunkingGuidance') },
{ patterns: ['timed out', 'timeout', 'deadline exceeded'], title: _t('errors.processingTimeout'), guidance: _t('errors.splitAudioGuidance') },
{ patterns: ['401', 'unauthorized', 'invalid api key', 'authentication failed', 'incorrect api key'], title: _t('errors.authenticationError'), guidance: _t('errors.checkApiKeyGuidance') },
@@ -573,6 +574,9 @@ export function useUpload(state, utils) {
try {
const formData = new FormData();
if (!sliced) formData.append('file', fileItem.file);
+ // A recording made here was checked against the storage quota
+ // when it started, so the server keeps it whatever its size (#413).
+ if (fileItem.fromInProgressRecording) formData.append('from_recorder', 'true');
// Send file's lastModified timestamp for meeting_date
if (fileItem.file.lastModified) {
@@ -733,6 +737,13 @@ export function useUpload(state, utils) {
} else if (!String(xhr.status).startsWith('2')) {
let errorMsg = parsed.error || `Upload failed with status ${xhr.status}`;
if (xhr.status === 413) errorMsg = parsed.error || `File too large. Max: ${parsed.max_size_mb?.toFixed(0) || maxFileSizeMB.value} MB.`;
+ if (parsed.code === 'storage_quota_exceeded' && t) {
+ const quotaMsg = t('storageQuota.uploadRefused', {
+ used: formatFileSize(parsed.used_bytes), quota: formatFileSize(parsed.quota_bytes),
+ file: formatFileSize(parsed.file_bytes),
+ });
+ if (quotaMsg && quotaMsg !== 'storageQuota.uploadRefused') errorMsg = quotaMsg;
+ }
const err = new Error(errorMsg);
if (isCsrfRejection(xhr.status, parsed.error || '')) {
err.isCsrfRejection = true;
diff --git a/static/locales/de.json b/static/locales/de.json
index 74bfb003..1876eae6 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -111,7 +111,12 @@
"contextualSpeakerLabellingHelp": "Sprecher werden anhand des Gesprächskontexts zugeordnet, da Ihre Transkriptions-Engine keine Stimmprofile liefert. Das kann recht ungenau sein, abhängig davon, wie viel das Gespräch darüber verrät, wer spricht, und wie gut Ihr Modell die Sprecher trennt. Für die genaueste, stimmbasierte Sprecherzuordnung wird der WhisperX-ASR-Container empfohlen.",
"timezone": "Zeitzone",
"timezoneAutomatic": "Automatisch (dieses Gerät)",
- "timezoneHelp": "Wird für Datumsangaben in Titeln aus Namensvorlagen verwendet. Datumsangaben auf den Seiten folgen immer diesem Gerät."
+ "timezoneHelp": "Wird für Datumsangaben in Titeln aus Namensvorlagen verwendet. Datumsangaben auf den Seiten folgen immer diesem Gerät.",
+ "storage": "Speicher",
+ "storageOfQuota": "{{used}} von {{quota}}",
+ "storageNoLimit": "{{used}} belegt, keine Begrenzung",
+ "storageFull": "Ihr Speicher ist voll. Uploads und neue Aufnahmen werden abgelehnt, bis Sie Aufnahmen löschen oder deren Audio entfernen.",
+ "storageHelp": "Zählt das Audio und Video, das Sie behalten. Aufnahmen mit entferntem Audio zählen nicht."
},
"accountTabs": {
"about": "Über",
@@ -428,7 +433,12 @@
"transcription": "Transkription"
},
"cacheLine": "Prompt-Cache: {{reads}} Tokens aus dem Cache gelesen, {{writes}} geschrieben, in diesem Zeitraum"
- }
+ },
+ "storageQuota": "Speicherkontingent (MB)",
+ "storageQuotaPlaceholder": "Keine Begrenzung",
+ "storageQuotaNewPlaceholder": "Standard aus den Systemeinstellungen",
+ "storageQuotaHelp": "Uploads, die das Kontingent überschreiten würden, werden abgelehnt. Aufnahmen mit entferntem Audio zählen nicht. Leer lassen für keine Begrenzung.",
+ "storageUsedLabel": "Belegter Speicher"
},
"apiTokens": {
"activeTokens": "Aktive Token",
@@ -917,7 +927,8 @@
"uploadFailedWithStatus": "Upload mit Status {{status}} fehlgeschlagen",
"uploadTimedOut": "Upload-Zeitüberschreitung",
"validationError": "Validierungsfehler",
- "waitAndRetryGuidance": "Einige Minuten warten und erneut versuchen"
+ "waitAndRetryGuidance": "Einige Minuten warten und erneut versuchen",
+ "shareTarget_storage_quota": "Die geteilte Datei wurde nicht gespeichert, weil Ihr Speicher voll ist."
},
"eventExtraction": {
"description": "Wenn aktiviert, identifiziert die KI Meetings, Termine und Fristen in Ihren Aufnahmen und erstellt herunterladbare Kalenderereignisse.",
@@ -1589,7 +1600,8 @@
"dismiss": "Ausblenden",
"empty": "Nichts erfordert Ihre Aufmerksamkeit.",
"view": "Ansehen",
- "voiceEmbeddingChanged": "Der Transkriptionsdienst liefert Stimm-Embeddings eines anderen Modells. Stimmprofile werden je Modell getrennt geführt: Profile des vorherigen Modells passen nicht zu neuen Aufnahmen und kehren zurück, wenn Sie das vorherige Backend wiederherstellen; Profile für das neue Modell entstehen, sobald Sie Sprecher benennen."
+ "voiceEmbeddingChanged": "Der Transkriptionsdienst liefert Stimm-Embeddings eines anderen Modells. Stimmprofile werden je Modell getrennt geführt: Profile des vorherigen Modells passen nicht zu neuen Aufnahmen und kehren zurück, wenn Sie das vorherige Backend wiederherstellen; Profile für das neue Modell entstehen, sobald Sie Sprecher benennen.",
+ "storageQuotaReached": "{{filename}} wurde im überwachten Ordner belassen, weil Ihr Speicher voll ist ({{used_mb}} MB von {{quota_mb}} MB). Die Datei wird hinzugefügt, sobald Platz ist."
},
"preferences": {
"description": "Einstellungen zu Anzeige und Editor-Verhalten. Diese werden in deinem Konto gespeichert und gelten geräteübergreifend.",
@@ -2249,5 +2261,11 @@
"secretBannerTitle": "Geheimnis jetzt kopieren — es wird nicht erneut angezeigt",
"secretBannerHint": "Signieren Sie jede Empfänger-Anfrage: HMAC-SHA256 des Rohkörpers mit diesem Geheimnis. Header: Speakr-Signature: sha256=<hex>",
"copy": "Kopieren"
+ },
+ "storageQuota": {
+ "title": "Speicher voll",
+ "guidance": "Löschen Sie Aufnahmen oder entfernen Sie deren Audio, oder bitten Sie einen Administrator um ein größeres Kontingent.",
+ "uploadRefused": "Diese Datei passt nicht in Ihren Speicher: {{used}} von {{quota}} belegt, die Datei hat {{file}}.",
+ "recordingBlocked": "Ihr Speicher ist voll ({{used}} von {{quota}}). Löschen Sie Aufnahmen oder entfernen Sie deren Audio, bevor Sie erneut aufnehmen."
}
}
diff --git a/static/locales/en.json b/static/locales/en.json
index 48938c24..32c5dd35 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -111,7 +111,12 @@
"contextualSpeakerLabellingHelp": "Speakers are matched from the conversation context because your transcription engine does not provide voice fingerprints. This can be quite inaccurate, depending on how much the conversation reveals about who is speaking and how well your model separates speakers. For the most accurate, voice-based speaker matching, the WhisperX ASR container is recommended.",
"timezone": "Timezone",
"timezoneAutomatic": "Automatic (this device)",
- "timezoneHelp": "Used for dates in titles from naming templates. Dates shown on pages always follow this device."
+ "timezoneHelp": "Used for dates in titles from naming templates. Dates shown on pages always follow this device.",
+ "storage": "Storage",
+ "storageOfQuota": "{{used}} of {{quota}}",
+ "storageNoLimit": "{{used}} used, no limit",
+ "storageFull": "Your storage is full. Uploads and new recordings are refused until you delete recordings or remove their audio.",
+ "storageHelp": "Counts the audio and video you keep. Recordings with their audio removed do not count."
},
"accountTabs": {
"about": "About",
@@ -428,7 +433,12 @@
"transcription": "Transcription"
},
"cacheLine": "Prompt cache: {{reads}} tokens read from the cache, {{writes}} written, in this period"
- }
+ },
+ "storageQuota": "Storage quota (MB)",
+ "storageQuotaPlaceholder": "No limit",
+ "storageQuotaNewPlaceholder": "Default from System Settings",
+ "storageQuotaHelp": "Uploads that would go over the quota are refused. Recordings with their audio removed do not count. Leave empty for no limit.",
+ "storageUsedLabel": "Storage used"
},
"apiTokens": {
"activeTokens": "Active Tokens",
@@ -917,7 +927,8 @@
"uploadFailedWithStatus": "Upload failed with status {{status}}",
"uploadTimedOut": "Upload timed out",
"validationError": "Validation error",
- "waitAndRetryGuidance": "Wait a few minutes and try again"
+ "waitAndRetryGuidance": "Wait a few minutes and try again",
+ "shareTarget_storage_quota": "The shared file was not saved because your storage is full."
},
"eventExtraction": {
"description": "When enabled, the AI will identify meetings, appointments, and deadlines mentioned in your recordings and create downloadable calendar events.",
@@ -1589,7 +1600,8 @@
"dismiss": "Dismiss",
"empty": "Nothing needs your attention.",
"view": "View",
- "voiceEmbeddingChanged": "The transcription service is returning voice embeddings from a different model. Voice profiles are kept separately for each model: profiles from the previous model will not match new recordings and come back if you restore the previous backend, and profiles for the new model are learned as you name speakers."
+ "voiceEmbeddingChanged": "The transcription service is returning voice embeddings from a different model. Voice profiles are kept separately for each model: profiles from the previous model will not match new recordings and come back if you restore the previous backend, and profiles for the new model are learned as you name speakers.",
+ "storageQuotaReached": "{{filename}} was left in the watch folder because your storage is full ({{used_mb}} MB of {{quota_mb}} MB). It is added once there is room."
},
"preferences": {
"description": "Display and editor behaviour preferences. These settings are saved to your account and apply across devices.",
@@ -2249,5 +2261,11 @@
"secretBannerTitle": "Copy this secret now — it will not be shown again",
"secretBannerHint": "Sign every receiver request: HMAC-SHA256 of the raw body using this secret. Header: Speakr-Signature: sha256=<hex>",
"copy": "Copy"
+ },
+ "storageQuota": {
+ "title": "Storage full",
+ "guidance": "Delete recordings or remove their audio, or ask an administrator for a larger quota.",
+ "uploadRefused": "This file does not fit in your storage: {{used}} of {{quota}} used, and the file is {{file}}.",
+ "recordingBlocked": "Your storage is full ({{used}} of {{quota}}). Delete recordings or remove their audio before recording again."
}
}
diff --git a/static/locales/es.json b/static/locales/es.json
index 6298e33d..3eac82c5 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -111,7 +111,12 @@
"contextualSpeakerLabellingHelp": "Los hablantes se identifican a partir del contexto de la conversación porque su motor de transcripción no proporciona huellas de voz. Esto puede ser bastante impreciso, según cuánto revele la conversación sobre quién habla y con qué precisión su modelo separa a los hablantes. Para la coincidencia de hablantes más precisa, basada en la voz, se recomienda el contenedor WhisperX ASR.",
"timezone": "Zona horaria",
"timezoneAutomatic": "Automática (este dispositivo)",
- "timezoneHelp": "Se usa para las fechas de los títulos creados con plantillas de nombres. Las fechas mostradas en las páginas siguen siempre este dispositivo."
+ "timezoneHelp": "Se usa para las fechas de los títulos creados con plantillas de nombres. Las fechas mostradas en las páginas siguen siempre este dispositivo.",
+ "storage": "Almacenamiento",
+ "storageOfQuota": "{{used}} de {{quota}}",
+ "storageNoLimit": "{{used}} usados, sin límite",
+ "storageFull": "Su almacenamiento está lleno. Las subidas y las grabaciones nuevas se rechazan hasta que elimine grabaciones o quite su audio.",
+ "storageHelp": "Cuenta el audio y el vídeo que conserva. Las grabaciones sin audio no cuentan."
},
"accountTabs": {
"about": "Acerca de",
@@ -428,7 +433,12 @@
"transcription": "Transcripción"
},
"cacheLine": "Caché de prompts: {{reads}} tokens leídos de la caché y {{writes}} escritos en este periodo"
- }
+ },
+ "storageQuota": "Cuota de almacenamiento (MB)",
+ "storageQuotaPlaceholder": "Sin límite",
+ "storageQuotaNewPlaceholder": "Valor predeterminado de la configuración del sistema",
+ "storageQuotaHelp": "Se rechazan las subidas que superarían la cuota. Las grabaciones sin audio no cuentan. Déjelo vacío para no poner límite.",
+ "storageUsedLabel": "Almacenamiento usado"
},
"apiTokens": {
"activeTokens": "Tokens activos",
@@ -917,7 +927,8 @@
"uploadFailedWithStatus": "La subida falló con el estado {{status}}",
"uploadTimedOut": "Se agotó el tiempo de subida",
"validationError": "Error de validación",
- "waitAndRetryGuidance": "Espere unos minutos y vuelva a intentarlo"
+ "waitAndRetryGuidance": "Espere unos minutos y vuelva a intentarlo",
+ "shareTarget_storage_quota": "El archivo compartido no se guardó porque su almacenamiento está lleno."
},
"eventExtraction": {
"description": "Cuando está habilitado, la IA identificará reuniones, citas y plazos mencionados en tus grabaciones y creará eventos de calendario descargables.",
@@ -1589,7 +1600,8 @@
"dismiss": "Descartar",
"empty": "No hay nada que requiera su atención.",
"view": "Ver",
- "voiceEmbeddingChanged": "El servicio de transcripción devuelve embeddings de voz de otro modelo. Los perfiles de voz se guardan por separado para cada modelo: los del modelo anterior no coincidirán con las grabaciones nuevas y vuelven si restaura el backend anterior, y los del modelo nuevo se aprenden a medida que nombra a los hablantes."
+ "voiceEmbeddingChanged": "El servicio de transcripción devuelve embeddings de voz de otro modelo. Los perfiles de voz se guardan por separado para cada modelo: los del modelo anterior no coincidirán con las grabaciones nuevas y vuelven si restaura el backend anterior, y los del modelo nuevo se aprenden a medida que nombra a los hablantes.",
+ "storageQuotaReached": "{{filename}} se dejó en la carpeta vigilada porque su almacenamiento está lleno ({{used_mb}} MB de {{quota_mb}} MB). Se añadirá cuando haya espacio."
},
"preferences": {
"description": "Preferencias de visualización y comportamiento del editor. Estos ajustes se guardan en tu cuenta y se aplican en todos los dispositivos.",
@@ -2249,5 +2261,11 @@
"secretBannerTitle": "Copie este secreto ahora — no se mostrará otra vez",
"secretBannerHint": "Firme cada solicitud del receptor: HMAC-SHA256 del cuerpo crudo usando este secreto. Cabecera: Speakr-Signature: sha256=<hex>",
"copy": "Copiar"
+ },
+ "storageQuota": {
+ "title": "Almacenamiento lleno",
+ "guidance": "Elimine grabaciones o quite su audio, o pida a un administrador una cuota mayor.",
+ "uploadRefused": "Este archivo no cabe en su almacenamiento: {{used}} de {{quota}} usados, y el archivo ocupa {{file}}.",
+ "recordingBlocked": "Su almacenamiento está lleno ({{used}} de {{quota}}). Elimine grabaciones o quite su audio antes de volver a grabar."
}
}
diff --git a/static/locales/fr.json b/static/locales/fr.json
index 029e1c48..1b99bb7d 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -111,7 +111,12 @@
"contextualSpeakerLabellingHelp": "Les locuteurs sont identifiés à partir du contexte de la conversation, car votre moteur de transcription ne fournit pas d'empreintes vocales. Cela peut être assez imprécis, selon ce que la conversation révèle sur l'identité des locuteurs et la capacité de votre modèle à les distinguer. Pour la correspondance de locuteurs la plus précise, basée sur la voix, le conteneur WhisperX ASR est recommandé.",
"timezone": "Fuseau horaire",
"timezoneAutomatic": "Automatique (cet appareil)",
- "timezoneHelp": "Utilisé pour les dates des titres issus des modèles de nommage. Les dates affichées dans les pages suivent toujours cet appareil."
+ "timezoneHelp": "Utilisé pour les dates des titres issus des modèles de nommage. Les dates affichées dans les pages suivent toujours cet appareil.",
+ "storage": "Stockage",
+ "storageOfQuota": "{{used}} sur {{quota}}",
+ "storageNoLimit": "{{used}} utilisés, aucune limite",
+ "storageFull": "Votre stockage est plein. Les envois et les nouveaux enregistrements sont refusés jusqu'à ce que vous supprimiez des enregistrements ou leur audio.",
+ "storageHelp": "Compte l'audio et la vidéo que vous conservez. Les enregistrements dont l'audio a été supprimé ne comptent pas."
},
"accountTabs": {
"about": "À Propos",
@@ -428,7 +433,12 @@
"transcription": "Transcription"
},
"cacheLine": "Cache de prompts : {{reads}} tokens lus depuis le cache, {{writes}} écrits, sur cette période"
- }
+ },
+ "storageQuota": "Quota de stockage (Mo)",
+ "storageQuotaPlaceholder": "Aucune limite",
+ "storageQuotaNewPlaceholder": "Valeur par défaut des paramètres système",
+ "storageQuotaHelp": "Les envois qui dépasseraient le quota sont refusés. Les enregistrements dont l'audio a été supprimé ne comptent pas. Laissez vide pour aucune limite.",
+ "storageUsedLabel": "Stockage utilisé"
},
"apiTokens": {
"activeTokens": "Jetons actifs",
@@ -917,7 +927,8 @@
"uploadFailedWithStatus": "Échec de l’envoi avec le statut {{status}}",
"uploadTimedOut": "Délai d’envoi dépassé",
"validationError": "Erreur de validation",
- "waitAndRetryGuidance": "Patientez quelques minutes et réessayez"
+ "waitAndRetryGuidance": "Patientez quelques minutes et réessayez",
+ "shareTarget_storage_quota": "Le fichier partagé n'a pas été enregistré, car votre stockage est plein."
},
"eventExtraction": {
"description": "Lorsqu'activé, l'IA identifiera les réunions, rendez-vous et échéances mentionnés dans vos enregistrements et créera des événements de calendrier téléchargeables.",
@@ -1589,7 +1600,8 @@
"dismiss": "Masquer",
"empty": "Rien ne requiert votre attention.",
"view": "Afficher",
- "voiceEmbeddingChanged": "Le service de transcription renvoie des empreintes vocales d’un autre modèle. Les profils vocaux sont conservés séparément pour chaque modèle : ceux du modèle précédent ne correspondront pas aux nouveaux enregistrements et reviennent si vous rétablissez le backend précédent, et ceux du nouveau modèle se construisent à mesure que vous nommez les intervenants."
+ "voiceEmbeddingChanged": "Le service de transcription renvoie des empreintes vocales d’un autre modèle. Les profils vocaux sont conservés séparément pour chaque modèle : ceux du modèle précédent ne correspondront pas aux nouveaux enregistrements et reviennent si vous rétablissez le backend précédent, et ceux du nouveau modèle se construisent à mesure que vous nommez les intervenants.",
+ "storageQuotaReached": "{{filename}} a été laissé dans le dossier surveillé, car votre stockage est plein ({{used_mb}} Mo sur {{quota_mb}} Mo). Il sera ajouté dès qu'il y aura de la place."
},
"preferences": {
"description": "Préférences d'affichage et de comportement de l'éditeur. Ces paramètres sont enregistrés sur votre compte et s'appliquent à tous les appareils.",
@@ -2249,5 +2261,11 @@
"secretBannerTitle": "Copiez ce secret maintenant — il ne sera plus affiché",
"secretBannerHint": "Signez chaque requête du récepteur : HMAC-SHA256 du corps brut avec ce secret. En-tête : Speakr-Signature: sha256=<hex>",
"copy": "Copier"
+ },
+ "storageQuota": {
+ "title": "Stockage plein",
+ "guidance": "Supprimez des enregistrements ou leur audio, ou demandez un quota plus grand à un administrateur.",
+ "uploadRefused": "Ce fichier ne tient pas dans votre stockage : {{used}} sur {{quota}} utilisés, et le fichier fait {{file}}.",
+ "recordingBlocked": "Votre stockage est plein ({{used}} sur {{quota}}). Supprimez des enregistrements ou leur audio avant d'enregistrer à nouveau."
}
}
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index 6c41054d..7c2d9b6e 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -111,7 +111,12 @@
"contextualSpeakerLabellingHelp": "Os falantes são identificados a partir do contexto da conversa porque o seu mecanismo de transcrição não fornece impressões de voz. Isso pode ser bastante impreciso, dependendo de quanto a conversa revela sobre quem está falando e de quão bem o seu modelo separa os falantes. Para a correspondência de falantes mais precisa, baseada em voz, recomenda-se o contêiner WhisperX ASR.",
"timezone": "Fuso horário",
"timezoneAutomatic": "Automático (este dispositivo)",
- "timezoneHelp": "Usado para as datas nos títulos criados por modelos de nome. As datas exibidas nas páginas sempre seguem este dispositivo."
+ "timezoneHelp": "Usado para as datas nos títulos criados por modelos de nome. As datas exibidas nas páginas sempre seguem este dispositivo.",
+ "storage": "Armazenamento",
+ "storageOfQuota": "{{used}} de {{quota}}",
+ "storageNoLimit": "{{used}} usados, sem limite",
+ "storageFull": "Seu armazenamento está cheio. Envios e novas gravações são recusados até você excluir gravações ou remover o áudio delas.",
+ "storageHelp": "Conta o áudio e o vídeo que você mantém. Gravações com o áudio removido não contam."
},
"accountTabs": {
"about": "Sobre",
@@ -428,7 +433,12 @@
"transcription": "Transcrição"
},
"cacheLine": "Cache de prompts: {{reads}} tokens lidos do cache e {{writes}} gravados neste período"
- }
+ },
+ "storageQuota": "Cota de armazenamento (MB)",
+ "storageQuotaPlaceholder": "Sem limite",
+ "storageQuotaNewPlaceholder": "Padrão das configurações do sistema",
+ "storageQuotaHelp": "Envios que ultrapassariam a cota são recusados. Gravações com o áudio removido não contam. Deixe vazio para não ter limite.",
+ "storageUsedLabel": "Armazenamento usado"
},
"apiTokens": {
"activeTokens": "Tokens Ativos",
@@ -917,7 +927,8 @@
"uploadFailedWithStatus": "Falha no envio com status {{status}}",
"uploadTimedOut": "Tempo limite de envio excedido",
"validationError": "Erro de validação",
- "waitAndRetryGuidance": "Aguarde alguns minutos e tente novamente"
+ "waitAndRetryGuidance": "Aguarde alguns minutos e tente novamente",
+ "shareTarget_storage_quota": "O arquivo compartilhado não foi salvo porque seu armazenamento está cheio."
},
"eventExtraction": {
"description": "Quando ativado, a IA identificará reuniões, compromissos e prazos mencionados em suas gravações e criará eventos de calendário para inserir na agenda.",
@@ -1589,7 +1600,8 @@
"dismiss": "Dispensar",
"empty": "Nada requer sua atenção.",
"view": "Ver",
- "voiceEmbeddingChanged": "O serviço de transcrição está retornando embeddings de voz de outro modelo. Os perfis de voz são mantidos separadamente para cada modelo: os do modelo anterior não corresponderão às novas gravações e voltam se você restaurar o backend anterior, e os do novo modelo são aprendidos conforme você nomeia os oradores."
+ "voiceEmbeddingChanged": "O serviço de transcrição está retornando embeddings de voz de outro modelo. Os perfis de voz são mantidos separadamente para cada modelo: os do modelo anterior não corresponderão às novas gravações e voltam se você restaurar o backend anterior, e os do novo modelo são aprendidos conforme você nomeia os oradores.",
+ "storageQuotaReached": "{{filename}} ficou na pasta monitorada porque seu armazenamento está cheio ({{used_mb}} MB de {{quota_mb}} MB). Ele será adicionado quando houver espaço."
},
"preferences": {
"description": "Preferências de exibição e comportamento do editor. Estas configurações ficam salvas em sua conta e se aplicam a todos os dispositivos.",
@@ -2249,5 +2261,11 @@
"secretBannerTitle": "Copie este segredo agora — não será mostrado de novo",
"secretBannerHint": "Assine cada requisição do receptor: HMAC-SHA256 do corpo bruto usando este segredo. Cabeçalho: Speakr-Signature: sha256=<hex>",
"copy": "Copiar"
+ },
+ "storageQuota": {
+ "title": "Armazenamento cheio",
+ "guidance": "Exclua gravações ou remova o áudio delas, ou peça a um administrador uma cota maior.",
+ "uploadRefused": "Este arquivo não cabe no seu armazenamento: {{used}} de {{quota}} usados, e o arquivo tem {{file}}.",
+ "recordingBlocked": "Seu armazenamento está cheio ({{used}} de {{quota}}). Exclua gravações ou remova o áudio delas antes de gravar novamente."
}
}
diff --git a/static/locales/ru.json b/static/locales/ru.json
index 51132d21..46991d78 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -111,7 +111,12 @@
"contextualSpeakerLabellingHelp": "Говорящие определяются по контексту разговора, поскольку ваш движок транскрипции не предоставляет голосовые отпечатки. Это может быть довольно неточным в зависимости от того, насколько разговор раскрывает, кто говорит, и насколько хорошо ваша модель разделяет говорящих. Для наиболее точного сопоставления говорящих на основе голоса рекомендуется контейнер WhisperX ASR.",
"timezone": "Часовой пояс",
"timezoneAutomatic": "Автоматически (это устройство)",
- "timezoneHelp": "Используется для дат в названиях, созданных по шаблонам. Даты на страницах всегда отображаются по этому устройству."
+ "timezoneHelp": "Используется для дат в названиях, созданных по шаблонам. Даты на страницах всегда отображаются по этому устройству.",
+ "storage": "Хранилище",
+ "storageOfQuota": "{{used}} из {{quota}}",
+ "storageNoLimit": "Использовано {{used}}, без ограничения",
+ "storageFull": "Хранилище заполнено. Загрузки и новые записи отклоняются, пока вы не удалите записи или их аудио.",
+ "storageHelp": "Учитываются сохранённые аудио и видео. Записи с удалённым аудио не учитываются."
},
"accountTabs": {
"about": "О продукте",
@@ -428,7 +433,12 @@
"transcription": "Транскрибация"
},
"cacheLine": "Кэш промптов: прочитано {{reads}} токенов, записано {{writes}} за этот период"
- }
+ },
+ "storageQuota": "Квота хранилища (МБ)",
+ "storageQuotaPlaceholder": "Без ограничения",
+ "storageQuotaNewPlaceholder": "По умолчанию из системных настроек",
+ "storageQuotaHelp": "Загрузки сверх квоты отклоняются. Записи с удалённым аудио не учитываются. Оставьте пустым, чтобы не ограничивать.",
+ "storageUsedLabel": "Использовано"
},
"apiTokens": {
"activeTokens": "Активные токены",
@@ -917,7 +927,8 @@
"uploadFailedWithStatus": "Загрузка не удалась со статусом {{status}}",
"uploadTimedOut": "Истекло время загрузки",
"validationError": "Ошибка проверки",
- "waitAndRetryGuidance": "Подождите несколько минут и повторите"
+ "waitAndRetryGuidance": "Подождите несколько минут и повторите",
+ "shareTarget_storage_quota": "Файл не сохранён, потому что хранилище заполнено."
},
"eventExtraction": {
"description": "При включении ИИ будет определять встречи, назначения и дедлайны, упомянутые в ваших записях, и создавать загружаемые календарные события.",
@@ -1589,7 +1600,8 @@
"dismiss": "Скрыть",
"empty": "Ничего не требует вашего внимания.",
"view": "Открыть",
- "voiceEmbeddingChanged": "Сервис транскрипции возвращает голосовые эмбеддинги другой модели. Голосовые профили хранятся отдельно для каждой модели: профили прежней модели не совпадут с новыми записями и вернутся, если восстановить прежний бэкенд, а профили новой модели формируются по мере того, как вы называете спикеров."
+ "voiceEmbeddingChanged": "Сервис транскрипции возвращает голосовые эмбеддинги другой модели. Голосовые профили хранятся отдельно для каждой модели: профили прежней модели не совпадут с новыми записями и вернутся, если восстановить прежний бэкенд, а профили новой модели формируются по мере того, как вы называете спикеров.",
+ "storageQuotaReached": "{{filename}} оставлен в папке наблюдения, потому что хранилище заполнено ({{used_mb}} МБ из {{quota_mb}} МБ). Файл будет добавлен, когда появится место."
},
"preferences": {
"description": "Настройки отображения и поведения редактора. Эти параметры сохраняются в вашей учётной записи и применяются на всех устройствах.",
@@ -2249,5 +2261,11 @@
"secretBannerTitle": "Скопируйте этот секрет сейчас — он больше не будет показан",
"secretBannerHint": "Подписывайте каждый запрос получателя: HMAC-SHA256 от исходного тела с этим секретом. Заголовок: Speakr-Signature: sha256=<hex>",
"copy": "Копировать"
+ },
+ "storageQuota": {
+ "title": "Хранилище заполнено",
+ "guidance": "Удалите записи или их аудио либо попросите администратора увеличить квоту.",
+ "uploadRefused": "Файл не помещается в хранилище: использовано {{used}} из {{quota}}, размер файла {{file}}.",
+ "recordingBlocked": "Хранилище заполнено ({{used}} из {{quota}}). Удалите записи или их аудио, прежде чем записывать снова."
}
}
diff --git a/static/locales/zh.json b/static/locales/zh.json
index d295b651..c11f11d1 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -111,7 +111,12 @@
"contextualSpeakerLabellingHelp": "由于您的转录引擎不提供声纹,说话人是根据对话上下文进行匹配的。这可能相当不准确,取决于对话在多大程度上透露了谁在说话,以及您的模型区分说话人的效果。若需最准确的基于语音的说话人匹配,建议使用 WhisperX ASR 容器。",
"timezone": "时区",
"timezoneAutomatic": "自动(此设备)",
- "timezoneHelp": "用于命名模板生成的标题中的日期。页面上显示的日期始终跟随此设备。"
+ "timezoneHelp": "用于命名模板生成的标题中的日期。页面上显示的日期始终跟随此设备。",
+ "storage": "存储",
+ "storageOfQuota": "{{used}} / {{quota}}",
+ "storageNoLimit": "已用 {{used}},不限制",
+ "storageFull": "您的存储已满。在删除录音或删除其音频之前,上传和新录音都会被拒绝。",
+ "storageHelp": "计入您保留的音频和视频。已删除音频的录音不计入。"
},
"accountTabs": {
"about": "关于",
@@ -428,7 +433,12 @@
"transcription": "转录"
},
"cacheLine": "提示缓存:本周期从缓存读取 {{reads}} 个令牌,写入 {{writes}} 个"
- }
+ },
+ "storageQuota": "存储配额(MB)",
+ "storageQuotaPlaceholder": "不限制",
+ "storageQuotaNewPlaceholder": "使用系统设置中的默认值",
+ "storageQuotaHelp": "超出配额的上传会被拒绝。已删除音频的录音不计入。留空表示不限制。",
+ "storageUsedLabel": "已用存储"
},
"apiTokens": {
"activeTokens": "活跃令牌",
@@ -917,7 +927,8 @@
"uploadFailedWithStatus": "上传失败,状态:{{status}}",
"uploadTimedOut": "上传超时",
"validationError": "验证错误",
- "waitAndRetryGuidance": "请等待几分钟后再重试"
+ "waitAndRetryGuidance": "请等待几分钟后再重试",
+ "shareTarget_storage_quota": "由于存储已满,共享的文件未保存。"
},
"eventExtraction": {
"description": "启用后,AI将识别录音中提到的会议、约会和截止日期,并创建可下载的日历事件。",
@@ -1589,7 +1600,8 @@
"dismiss": "忽略",
"empty": "暂无需要处理的事项。",
"view": "查看",
- "voiceEmbeddingChanged": "转录服务返回的是另一个模型的声纹特征。声纹档案按模型分别保存:旧模型的档案不会匹配新录音,恢复先前的后端后即可重新使用;新模型的档案会在您为发言人命名时逐步建立。"
+ "voiceEmbeddingChanged": "转录服务返回的是另一个模型的声纹特征。声纹档案按模型分别保存:旧模型的档案不会匹配新录音,恢复先前的后端后即可重新使用;新模型的档案会在您为发言人命名时逐步建立。",
+ "storageQuotaReached": "由于存储已满(已用 {{used_mb}} MB,共 {{quota_mb}} MB),{{filename}} 仍留在监控文件夹中,有空间后会自动添加。"
},
"preferences": {
"description": "显示与编辑器行为偏好。这些设置保存在您的账户中,并在所有设备上生效。",
@@ -2249,5 +2261,11 @@
"secretBannerTitle": "立即复制此密钥 — 不会再次显示",
"secretBannerHint": "用此密钥对每个接收方请求进行签名: 原始正文的 HMAC-SHA256。请求头: Speakr-Signature: sha256=<hex>",
"copy": "复制"
+ },
+ "storageQuota": {
+ "title": "存储已满",
+ "guidance": "请删除录音或删除其音频,或请管理员提高配额。",
+ "uploadRefused": "此文件超出您的存储空间:已用 {{used}},共 {{quota}},文件大小 {{file}}。",
+ "recordingBlocked": "您的存储已满(已用 {{used}},共 {{quota}})。请先删除录音或删除其音频再录音。"
}
}
diff --git a/templates/account.html b/templates/account.html
index e66211ed..2b699c99 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -608,6 +608,30 @@
<span class="block text-sm text-[var(--text-muted)]" data-i18n="account.failedRecordings">Failed</span>
</div>
</div>
+ {# Storage used, against the quota when there is one (#413) #}
+ {% if storage_usage %}
+ {% macro size(n) %}{% if n >= 1073741824 %}{{ '%.1f'|format(n / 1073741824) }} GB{% else %}{{ '%.1f'|format(n / 1048576) }} MB{% endif %}{% endmacro %}
+ {% set pct = storage_usage.percentage %}
+ <div class="mt-4 p-4 bg-[var(--bg-secondary)] rounded-lg border border-[var(--border-primary)] shadow-sm" id="account-storage">
+ <div class="flex items-baseline justify-between gap-3 text-sm">
+ <span class="font-medium text-[var(--text-secondary)]" data-i18n="account.storage">Storage</span>
+ {% if storage_usage.quota_bytes %}
+ <span class="text-[var(--text-primary)] tabular-nums" data-i18n="account.storageOfQuota" data-i18n-params='{"used": "{{ size(storage_usage.used_bytes)|trim }}", "quota": "{{ size(storage_usage.quota_bytes)|trim }}"}'>{{ size(storage_usage.used_bytes)|trim }} of {{ size(storage_usage.quota_bytes)|trim }}</span>
+ {% else %}
+ <span class="text-[var(--text-primary)] tabular-nums" data-i18n="account.storageNoLimit" data-i18n-params='{"used": "{{ size(storage_usage.used_bytes)|trim }}"}'>{{ size(storage_usage.used_bytes)|trim }} used, no limit</span>
+ {% endif %}
+ </div>
+ {% if storage_usage.quota_bytes %}
+ <div class="w-full bg-[var(--bg-tertiary)] rounded-full h-2 mt-2">
+ <div class="h-2 rounded-full {% if pct >= 100 %}bg-[var(--text-danger-strong)]{% elif pct >= 80 %}bg-[var(--text-warn-strong)]{% else %}bg-[var(--text-success-strong)]{% endif %}" style="width: {{ [pct, 100]|min }}%"></div>
+ </div>
+ {% if pct >= 100 %}
+ <p class="text-xs text-[var(--text-danger-strong)] mt-2" data-i18n="account.storageFull">Your storage is full. Uploads and new recordings are refused until you delete recordings or remove their audio.</p>
+ {% endif %}
+ {% endif %}
+ <p class="text-xs text-[var(--text-muted)] mt-2" data-i18n="account.storageHelp">Counts the audio and video you keep. Recordings with their audio removed do not count.</p>
+ </div>
+ {% endif %}
</div>
</div>
diff --git a/templates/admin.html b/templates/admin.html
index db057779..3b9bf45d 100644
--- a/templates/admin.html
+++ b/templates/admin.html
@@ -269,7 +269,9 @@
</button>
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ user.recordings_count }</td>
- <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">${ formatFileSize(user.storage_used) }</td>
+ <td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">
+ ${ formatFileSize(user.storage_used) }<span v-if="user.storage_quota_mb" class="text-xs" :class="storagePctClass(storagePct(user)) || 'text-[var(--text-muted)]'"> / ${ formatFileSize(user.storage_quota_mb * 1048576) }</span>
+ </td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-[var(--text-secondary)]">
<div class="flex space-x-2">
<button @click="editUser(user)" class="text-[var(--text-accent)] hover:text-[var(--text-accent-hover)]" :title="t('buttons.editUser')">
@@ -522,12 +524,17 @@
<tr v-for="u in sortedStatsUsers" :key="u.id" class="border-t border-[var(--border-primary)] first:border-t-0">
<td class="py-2 px-3 font-medium text-[var(--text-primary)] whitespace-nowrap">
<span v-text="u.username"></span>
- <i v-if="(u.token_pct || 0) >= 80 || (u.minutes_pct || 0) >= 80" class="fas fa-exclamation-triangle ml-1.5"
- :class="(u.token_pct || 0) >= 100 || (u.minutes_pct || 0) >= 100 ? 'text-[var(--text-danger-strong)]' : 'text-[var(--text-warn-strong)]'"
+ <i v-if="(u.token_pct || 0) >= 80 || (u.minutes_pct || 0) >= 80 || (u.storage_pct || 0) >= 80" class="fas fa-exclamation-triangle ml-1.5"
+ :class="(u.token_pct || 0) >= 100 || (u.minutes_pct || 0) >= 100 || (u.storage_pct || 0) >= 100 ? 'text-[var(--text-danger-strong)]' : 'text-[var(--text-warn-strong)]'"
:title="t('adminDashboard.statsPage.nearBudget')"></i>
</td>
<td class="py-2 px-3 text-right tabular-nums" v-text="u.recordings.toLocaleString()"></td>
- <td class="py-2 px-3 text-right tabular-nums whitespace-nowrap" v-text="formatFileSize(u.storage)"></td>
+ <td class="py-2 px-3 text-right min-w-[7rem]">
+ <span class="tabular-nums whitespace-nowrap" v-text="formatFileSize(u.storage)"></span><span v-if="u.storage_quota" class="text-xs text-[var(--text-muted)] whitespace-nowrap"> / <span v-text="formatFileSize(u.storage_quota)"></span></span>
+ <div v-if="u.storage_quota" class="w-full bg-[var(--bg-secondary)] rounded-full h-1 mt-1">
+ <div class="h-1 rounded-full" :class="budgetBarClass(u.storage_pct)" :style="{ width: Math.min(u.storage_pct || 0, 100) + '%' }"></div>
+ </div>
+ </td>
<td class="py-2 px-3 whitespace-nowrap text-[var(--text-secondary)]" v-text="u.last_recording_at ? formatDay(u.last_recording_at.slice(0, 10)) : '—'"></td>
<td class="py-2 px-3 text-right min-w-[8rem]">
<span class="tabular-nums" v-text="formatCompact(u.tokens_month)"></span><span v-if="u.token_budget" class="text-xs text-[var(--text-muted)]"> / <span v-text="formatCompact(u.token_budget)"></span></span>
@@ -1366,6 +1373,12 @@ Summarization Instructions:
<input v-model.number="newUser.monthlyTranscriptionBudgetMinutes" type="number" min="10" step="10" :placeholder="t('adminDashboard.transcriptionBudgetPlaceholder')" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
<p class="text-xs text-[var(--text-muted)] mt-1">${t('adminDashboard.transcriptionBudgetHelp')}</p>
</div>
+ <!-- Storage quota (#413). Left empty, the default from System Settings applies. -->
+ <div class="mb-4">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.storageQuota')}</label>
+ <input v-model.number="newUser.storageQuotaMb" type="number" min="1" step="100" :placeholder="t('adminDashboard.storageQuotaNewPlaceholder')" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <p class="text-xs text-[var(--text-muted)] mt-1">${t('adminDashboard.storageQuotaHelp')}</p>
+ </div>
</div>
<div class="modal-footer">
<button type="button" @click="showAddUserModal = false" class="btn btn--ghost">${t('buttons.cancel')}</button>
@@ -1431,6 +1444,21 @@ Summarization Instructions:
</div>
</div>
</div>
+ <!-- Storage quota (#413) -->
+ <div class="mb-4">
+ <label class="block text-sm font-medium text-[var(--text-secondary)] mb-1">${t('adminDashboard.storageQuota')}</label>
+ <input v-model.number="editingUser.storage_quota_mb" type="number" min="1" step="100" :placeholder="t('adminDashboard.storageQuotaPlaceholder')" class="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--border-focus)] bg-[var(--bg-input)] text-[var(--text-primary)]">
+ <p class="text-xs text-[var(--text-muted)] mt-1">${t('adminDashboard.storageQuotaHelp')}</p>
+ <div class="mt-2">
+ <div class="flex justify-between text-xs text-[var(--text-muted)] mb-1">
+ <span>${t('adminDashboard.storageUsedLabel')}: ${ formatFileSize(editingUser.storage_used || 0) }</span>
+ <span v-if="editingUser.storage_quota_mb" :class="storagePctClass(storagePct(editingUser))">${ storagePct(editingUser) }%</span>
+ </div>
+ <div v-if="editingUser.storage_quota_mb" class="w-full bg-[var(--bg-tertiary)] rounded-full h-2">
+ <div class="h-2 rounded-full" :class="budgetBarClass(storagePct(editingUser))" :style="{width: Math.min(storagePct(editingUser), 100) + '%'}"></div>
+ </div>
+ </div>
+ </div>
</div>
<div class="modal-footer">
<button type="button" @click="showEditUserModal = false" class="btn btn--ghost">Cancel</button>
@@ -2224,7 +2252,8 @@ Summarization Instructions:
confirmPassword: '',
isAdmin: false,
monthlyTokenBudget: null,
- monthlyTranscriptionBudgetMinutes: null
+ monthlyTranscriptionBudgetMinutes: null,
+ storageQuotaMb: null
});
const editingUser = ref(null);
const userToDelete = ref(null);
@@ -2422,6 +2451,7 @@ Summarization Instructions:
'transcript_length_limit',
'max_file_size_mb',
'max_audio_only_video_size_mb',
+ 'default_storage_quota_mb',
'asr_timeout_seconds',
'default_timezone',
'admin_default_summary_prompt',
@@ -2567,6 +2597,10 @@ Summarization Instructions:
return (typeof x === 'string' ? x.localeCompare(y) : x - y) * dir;
});
});
+ // Storage used against a quota in MB, as a percentage (#413).
+ const storagePct = (u) => u && u.storage_quota_mb
+ ? Math.round((u.storage_used || 0) / (u.storage_quota_mb * 1048576) * 1000) / 10 : 0;
+ const storagePctClass = (pct) => pct >= 100 ? 'text-[var(--text-danger-strong)]' : (pct >= 80 ? 'text-[var(--text-warn-strong)]' : '');
const budgetBarClass = (pct) => pct >= 100 ? 'bg-[var(--text-danger-strong)]'
: (pct >= 80 ? 'bg-[var(--text-warn-strong)]' : 'bg-[var(--text-success-strong)]');
@@ -2848,7 +2882,9 @@ Summarization Instructions:
password: newUser.value.password,
is_admin: newUser.value.isAdmin,
monthly_token_budget: newUser.value.monthlyTokenBudget || null,
- monthly_transcription_budget: newUser.value.monthlyTranscriptionBudgetMinutes ? newUser.value.monthlyTranscriptionBudgetMinutes * 60 : null
+ monthly_transcription_budget: newUser.value.monthlyTranscriptionBudgetMinutes ? newUser.value.monthlyTranscriptionBudgetMinutes * 60 : null,
+ // Left empty, the server applies the default for new accounts.
+ ...(newUser.value.storageQuotaMb ? { storage_quota_mb: newUser.value.storageQuotaMb } : {})
})
});
@@ -2865,7 +2901,8 @@ Summarization Instructions:
confirmPassword: '',
isAdmin: false,
monthlyTokenBudget: null,
- monthlyTranscriptionBudgetMinutes: null
+ monthlyTranscriptionBudgetMinutes: null,
+ storageQuotaMb: null
};
showAddUserModal.value = false;
@@ -2896,7 +2933,8 @@ Summarization Instructions:
email: editingUser.value.email,
is_admin: editingUser.value.is_admin,
monthly_token_budget: editingUser.value.monthly_token_budget || null,
- monthly_transcription_budget: transcriptionBudgetSeconds
+ monthly_transcription_budget: transcriptionBudgetSeconds,
+ storage_quota_mb: editingUser.value.storage_quota_mb || null
};
// Only include password if it was changed
@@ -4021,7 +4059,7 @@ Summarization Instructions:
stats,
voiceEmbedding, voiceEmbeddingBusy, checkVoiceEmbedding, rebaselineVoiceEmbedding,
statsDays, overview, overviewLoading, overviewCards, statusRows,
- userColumns, statsSort, sortUsersBy, sortedStatsUsers, budgetBarClass,
+ userColumns, statsSort, sortUsersBy, sortedStatsUsers, budgetBarClass, storagePct, storagePctClass,
formatCompact, formatCost, formatModelCost, formatSeconds, formatDay,
settings,
displayedSettings,
diff --git a/tests/test_storage_quota.py b/tests/test_storage_quota.py
new file mode 100644
index 00000000..f60bfa5e
--- /dev/null
+++ b/tests/test_storage_quota.py
@@ -0,0 +1,242 @@
+"""Per-user storage quotas (#413).
+
+Storage is the size of a user's own recordings whose audio is kept. Uploads
+that would go over the quota are refused with 507 and a JSON body; a
+recording made in the app is checked when it starts and kept at the end; the
+watch folder leaves a file that does not fit where it is and tells the user
+once. Admins set the quota, with a default for new accounts.
+
+SHARED-DB: users, tokens, recordings and notifications are removed afterwards.
+"""
+
+import io
+import os
+import secrets
+import sys
+import tempfile
+import uuid
+from datetime import datetime
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import APIToken, Notification, Recording, SystemSetting, User
+from src.services import storage_quota as sq
+from src.utils.token_auth import hash_token
+from tests.test_cov_recordings_write import _do_upload, _upload_mocks
+from tests.test_recording_sessions import _login
+
+app.config["WTF_CSRF_ENABLED"] = False
+MB = 1024 * 1024
+
+
+def world():
+ made = {"users": []}
+
+ def user(quota_mb=None, admin=False):
+ s = secrets.token_hex(4)
+ u = User(username=f"q_{s}", email=f"q_{s}@local.test", password="x", is_admin=admin,
+ storage_quota_mb=quota_mb)
+ db.session.add(u)
+ db.session.commit()
+ made["users"].append(u.id)
+ return u
+
+ def rec(u, size, removed=False):
+ r = Recording(user_id=u.id, title="r", status="COMPLETED", original_filename="r.mp3", file_size=size,
+ audio_deleted_at=datetime.utcnow() if removed else None)
+ db.session.add(r)
+ db.session.commit()
+ return r
+
+ with app.app_context():
+ made.update(user=user, rec=rec)
+ yield made
+ db.session.rollback()
+ for uid in made["users"]:
+ Notification.query.filter_by(user_id=uid).delete()
+ APIToken.query.filter_by(user_id=uid).delete()
+ Recording.query.filter_by(user_id=uid).delete()
+ User.query.filter_by(id=uid).delete()
+ db.session.commit()
+
+
+def _staging():
+ return os.path.join(app.config["UPLOAD_FOLDER"], f"stg_{uuid.uuid4().hex[:6]}")
+
+
+# ----------------------------------------------------------------- the service
+
+def test_usage_counts_kept_audio_of_own_recordings(world):
+ u = world["user"](quota_mb=10)
+ world["rec"](u, 3 * MB)
+ world["rec"](u, 4 * MB, removed=True) # audio removed: not counted
+ other = world["user"]()
+ world["rec"](other, 9 * MB)
+ usage = sq.usage(u)
+ assert usage["used_bytes"] == 3 * MB and usage["quota_bytes"] == 10 * MB
+ assert usage["available_bytes"] == 7 * MB and usage["percentage"] == 30.0
+ assert sq.usage(other)["quota_bytes"] is None
+
+
+def test_check_room(world):
+ u = world["user"](quota_mb=10)
+ world["rec"](u, 8 * MB)
+ sq.check_room(u, 2 * MB) # exactly fits
+ with pytest.raises(sq.StorageQuotaExceeded) as e:
+ sq.check_room(u, 2 * MB + 1)
+ assert e.value.to_dict()["available_bytes"] == 2 * MB
+ world["rec"](u, 2 * MB)
+ with pytest.raises(sq.StorageQuotaExceeded):
+ sq.check_room(u) # at the quota, nothing new may start
+ sq.check_room(world["user"](), 10 ** 12) # no quota, no limit
+
+
+# ----------------------------------------------------------------- uploads
+
+def test_an_upload_over_the_quota_is_refused_and_nothing_is_stored(world):
+ u = world["user"](quota_mb=1)
+ client = app.test_client()
+ _login(client, u)
+ with _upload_mocks(_staging()) as (storage, enqueue):
+ resp = _do_upload(client, payload=b"\x00" * (MB + 1))
+ assert resp.status_code == 507
+ body = resp.get_json()
+ assert body["code"] == "storage_quota_exceeded" and body["quota_bytes"] == MB and body["file_bytes"] == MB + 1
+ assert Recording.query.filter_by(user_id=u.id).count() == 0
+ assert not storage.uploaded and not enqueue.called
+
+
+def test_an_upload_that_fits_is_accepted(world):
+ u = world["user"](quota_mb=1)
+ client = app.test_client()
+ _login(client, u)
+ with _upload_mocks(_staging()):
+ assert _do_upload(client, payload=b"\x00" * 4096).status_code == 202
+
+
+def test_a_recording_made_in_the_app_is_kept_at_the_end(world):
+ u = world["user"](quota_mb=1)
+ world["rec"](u, MB) # already full
+ client = app.test_client()
+ _login(client, u)
+ with _upload_mocks(_staging()):
+ assert _do_upload(client, payload=b"\x00" * 4096, from_recorder="true").status_code == 202
+
+
+def test_an_api_token_cannot_claim_a_recording_was_made_in_the_app(world):
+ u = world["user"](quota_mb=1)
+ world["rec"](u, MB)
+ plain = f"tok-{secrets.token_urlsafe(12)}"
+ db.session.add(APIToken(user_id=u.id, token_hash=hash_token(plain), name="t"))
+ db.session.commit()
+ with _upload_mocks(_staging()), app.test_client() as c:
+ resp = c.post("/api/v1/recordings/upload", headers={"Authorization": f"Bearer {plain}"},
+ data={"file": (io.BytesIO(b"\x00" * 4096), "a.mp3"), "from_recorder": "true"},
+ content_type="multipart/form-data")
+ assert resp.status_code == 507 and resp.get_json()["code"] == "storage_quota_exceeded"
+
+
+def test_a_session_cannot_open_at_the_quota(world):
+ u = world["user"](quota_mb=1)
+ world["rec"](u, MB)
+ client = app.test_client()
+ _login(client, u)
+ assert client.post("/upload/session", json={"mime_type": "audio/webm"}).status_code == 507
+ assert client.post("/upload/session", json={"filename": "a.mp4", "total_bytes": 10}).status_code == 507
+
+
+def test_a_sliced_upload_must_fit(world):
+ u = world["user"](quota_mb=1)
+ client = app.test_client()
+ _login(client, u)
+ assert client.post("/upload/session", json={"filename": "a.mp4", "total_bytes": MB + 1}).status_code == 507
+ ok = client.post("/upload/session", json={"filename": "a.mp4", "total_bytes": 100})
+ assert ok.status_code == 201
+ client.post(f"/upload/session/{ok.get_json()['session_id']}/abort")
+
+
+def test_a_merge_that_keeps_the_originals_needs_room(world):
+ u = world["user"](quota_mb=10)
+ a, b = world["rec"](u, 3 * MB), world["rec"](u, 3 * MB)
+ client = app.test_client()
+ _login(client, u)
+ resp = client.post("/api/recordings/merge", json={"recording_ids": [a.id, b.id]})
+ assert resp.status_code == 507
+
+
+# ----------------------------------------------------------------- watch folder
+
+def test_the_watch_folder_leaves_a_file_that_does_not_fit(world):
+ from src.file_monitor import FileMonitor
+ u = world["user"](quota_mb=1)
+ world["rec"](u, MB)
+ folder = Path(tempfile.mkdtemp())
+ locked = folder / "meeting.mp3.processing"
+ locked.write_bytes(b"\x00" * 4096)
+ monitor = FileMonitor(str(folder), check_interval=30)
+ monitor._process_file(locked, u.id)
+ assert (folder / "meeting.mp3").exists() and not locked.exists()
+ assert Recording.query.filter_by(user_id=u.id).count() == 1
+ notes = Notification.query.filter_by(user_id=u.id, kind=sq.KIND_STORAGE_QUOTA_REACHED).all()
+ assert len(notes) == 1 and notes[0].params["filename"] == "meeting.mp3"
+ # Room again: the notice is resolved on the next check that fits.
+ u.storage_quota_mb = 100
+ db.session.commit()
+ sq.check_room(u, 4096)
+ assert db.session.get(Notification, notes[0].id).resolved_at is not None
+
+
+# ----------------------------------------------------------------- admin and display
+
+def test_admins_set_and_clear_the_quota(world):
+ admin = world["user"](admin=True)
+ target = world["user"]()
+ client = app.test_client()
+ _login(client, admin)
+ assert client.put(f"/admin/users/{target.id}", json={"storage_quota_mb": 500}).get_json()["storage_quota_mb"] == 500
+ assert client.put(f"/admin/users/{target.id}", json={"storage_quota_mb": -1}).status_code == 400
+ assert client.put(f"/admin/users/{target.id}", json={"storage_quota_mb": None}).get_json()["storage_quota_mb"] is None
+
+
+def test_new_accounts_get_the_default_quota(world):
+ admin = world["user"](admin=True)
+ client = app.test_client()
+ _login(client, admin)
+ old = SystemSetting.get_setting("default_storage_quota_mb", 0)
+ SystemSetting.set_setting("default_storage_quota_mb", "250", setting_type="integer")
+ try:
+ s = secrets.token_hex(4)
+ made = client.post("/admin/users", json={"username": f"n_{s}", "email": f"n_{s}@local.test", "password": "Passw0rd!x"})
+ assert made.status_code == 201, made.data
+ world["users"].append(made.get_json()["id"])
+ assert made.get_json()["storage_quota_mb"] == 250
+ s = secrets.token_hex(4)
+ own = client.post("/admin/users", json={"username": f"n_{s}", "email": f"n_{s}@local.test",
+ "password": "Passw0rd!x", "storage_quota_mb": 40})
+ world["users"].append(own.get_json()["id"])
+ assert own.get_json()["storage_quota_mb"] == 40
+ finally:
+ SystemSetting.set_setting("default_storage_quota_mb", str(old or 0), setting_type="integer")
+
+
+def test_users_see_their_usage(world):
+ u = world["user"](quota_mb=10)
+ world["rec"](u, 2 * MB)
+ client = app.test_client()
+ _login(client, u)
+ body = client.get("/api/account/storage").get_json()
+ assert body["used_bytes"] == 2 * MB and body["quota_bytes"] == 10 * MB
+ page = client.get("/account")
+ assert page.status_code == 200 and b'id="account-storage"' in page.data
+ plain = f"tok-{secrets.token_urlsafe(12)}"
+ db.session.add(APIToken(user_id=u.id, token_hash=hash_token(plain), name="t"))
+ db.session.commit()
+ with app.test_client() as c:
+ me = c.get("/api/v1/users/me", headers={"Authorization": f"Bearer {plain}"}).get_json()
+ assert me["storage"] == {"used_bytes": 2 * MB, "quota_bytes": 10 * MB, "available_bytes": 8 * MB}