forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusers.py
More file actions
2432 lines (1975 loc) · 98.6 KB
/
Copy pathusers.py
File metadata and controls
2432 lines (1975 loc) · 98.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import re
import uuid
from typing import Annotated, List, Dict, Any, Literal, Union, Optional
import hashlib
import os
import asyncio
import pytz
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, field_validator, model_validator
from database import (
conversations as conversations_db,
memories as memories_db,
chat as chat_db,
user_usage as user_usage_db,
notifications as notification_db,
daily_summaries as daily_summaries_db,
llm_usage as llm_usage_db,
users as users_db,
)
from database._client import get_customer_firestore_client
from database.sync_jobs import release_job_run_lock, try_acquire_job_run_lock
from services.users.data_export import iter_user_data_export
from services.users.account_deletion import background_wipe_user_data, start_account_deletion
from database.app_review_config import should_hide_subscription_ui
from database.webhook_health import record_dev_webhook_success
from database.conversations import get_in_progress_conversation, get_conversation
from database.redis_db import (
cache_user_geolocation,
get_cached_user_geolocation,
set_user_webhook_db,
get_user_webhook_db,
disable_user_webhook_db,
enable_user_webhook_db,
user_webhook_status_db,
set_user_preferred_app,
set_user_data_protection_level,
get_generic_cache,
set_generic_cache,
get_daily_summary_uid,
store_daily_summary_to_uid,
remove_daily_summary_to_uid,
)
from utils.chat_rating_triage import extract_rating_triage_fields, normalize_rating_reason
from database.users import (
claim_deletion_wipe_for_task,
get_user_transcription_preferences,
resolve_deletion_wipe_job_id,
set_user_transcription_preferences,
)
from config.stt_provider_policy import supports_live_multilingual_mode
from models.users import AvailableLanguage, AvailableLanguagesResponse
from utils.user_language import PRIMARY_LANGUAGE_OPTIONS, normalize_user_language
from utils.feedback import record_chat_message_feedback
from database.users import *
from models.conversation import Conversation
from models.geolocation import Geolocation, GeolocationInput, validated_geolocation_or_none
from utils.conversations.factory import deserialize_conversation, deserialize_conversations
from models.other import Person, CreatePerson
from typing import Optional
from models.user_usage import UserUsageResponse, UsagePeriod
from datetime import datetime, time, timedelta
from models.users import (
TranscriptionAllowanceSnapshot,
ChatUsageQuota,
ChatQuotaUnit,
WebhookType,
webhook_url_from_setting,
UserSubscriptionResponse,
Subscription,
SubscriptionPlan,
SubscriptionStatus,
PlanLimits,
PlanType,
PricingOption,
PhoneCallQuota,
TrialMetadata,
LocationContextConsentResponse,
LocationContextConsentUpdate,
)
from utils.phone_calls import get_quota_snapshot as get_phone_call_quota_snapshot
from utils.apps import get_available_app_by_id
from utils.subscription import (
resolve_transcription_allowance,
request_has_llm_byok_key,
enforce_chat_quota,
get_chat_quota_snapshot,
get_basic_plan_limits,
get_default_basic_subscription,
get_paid_plan_definitions,
get_plan_display_name,
get_plan_limits,
plan_uses_overage,
get_plan_features,
get_monthly_usage_for_subscription,
is_trial_paywalled,
neo_grandfather_until,
reconcile_basic_plan_with_stripe,
filter_plans_for_user,
should_show_new_plans,
adapt_plans_for_legacy_client,
wire_plan_for_client,
legacy_plan_features,
clear_trial_paywall_cache,
get_trial_metadata,
)
from database import user_usage as user_usage_db
from utils import stripe as stripe_utils
from utils.cloud_tasks import (
AccountDeletionTaskAuthentication,
get_account_deletion_tasks_max_attempts,
verify_account_deletion_cloud_tasks_oidc,
)
from utils.executors import cleanup_executor, db_executor, llm_executor, run_blocking
from utils.log_sanitizer import sanitize
from utils.llm.followup import followup_question_prompt
from utils.notifications import send_notification, send_training_data_submitted_notification
from utils.llm.external_integrations import generate_comprehensive_daily_summary
from utils.other.notifications import (
DAILY_SUMMARY_DECLINE_LOCKED,
generate_daily_summary_on_demand,
local_day_bounds_utc,
)
from models.notification_message import NotificationMessage
from models.daily_summary import DailySummariesResponse, DailySummaryResponse
from utils.memory.learned_today import memories_learned_payload, memory_review_card_block
from utils.other import endpoints as auth
from utils.other.storage import (
delete_all_conversation_recordings,
get_speech_sample_signed_urls,
delete_user_person_speech_samples,
delete_user_person_speech_sample,
)
from utils.webhooks import button_event_webhook, webhook_first_time_setup
from utils.byok import (
get_byok_key,
has_byok_keys,
invalidate_byok_state_cache,
peppered_fingerprint,
)
import logging
logger = logging.getLogger(__name__)
router = APIRouter()
class MigrationRequest(BaseModel):
type: str
id: str
target_level: str
class MigrationTargetRequest(BaseModel):
target_level: str
class BatchMigrationRequest(BaseModel):
requests: List[MigrationRequest]
class MigrationStatusResponse(BaseModel):
status: str
message: Optional[str] = None
class MigrationRequestsResponse(BaseModel):
needs_migration: List[Dict[str, Any]] = Field(default_factory=list)
class UserStatusResponse(BaseModel):
status: str
message: Optional[str] = None
class UserProfileResponse(BaseModel):
model_config = ConfigDict(extra='allow')
uid: str
email: Optional[str] = None
name: Optional[str] = None
time_zone: Optional[str] = None
created_at: Optional[datetime] = None
motivation: Optional[str] = None
use_case: Optional[str] = None
job: Optional[str] = None
company: Optional[str] = None
data_protection_level: Optional[str] = None
migration_status: Optional[Dict[str, Any]] = None
class UserWebhooksStatusResponse(BaseModel):
audio_bytes: bool
memory_created: bool
realtime_transcript: bool
day_summary: bool
button_event: bool = False
class UserWebhookUrlResponse(BaseModel):
url: Optional[str] = None
class UserDataExportResponse(BaseModel):
profile: Dict[str, Any] = Field(default_factory=dict)
conversations: List[Dict[str, Any]] = Field(default_factory=list)
conversation_photo_manifest: List[Dict[str, Any]] = Field(default_factory=list)
frame_requests: List[Dict[str, Any]] = Field(default_factory=list)
frame_vision_receipts: List[Dict[str, Any]] = Field(default_factory=list)
conversation_keyframe_jobs: List[Dict[str, Any]] = Field(default_factory=list)
memories: List[Dict[str, Any]] = Field(default_factory=list)
memory_review_data: Dict[str, List[Dict[str, Any]]] = Field(default_factory=dict)
memory_ledger_data: Dict[str, List[Dict[str, Any]]] = Field(default_factory=dict)
jit_data: Dict[str, List[Dict[str, Any]]] = Field(default_factory=dict)
people: List[Dict[str, Any]] = Field(default_factory=list)
action_items: List[Dict[str, Any]] = Field(default_factory=list)
task_data: Dict[str, List[Dict[str, Any]]] = Field(default_factory=dict)
chat_messages: List[Dict[str, Any]] = Field(default_factory=list)
class StoreRecordingPermissionResponse(BaseModel):
store_recording_permission: bool
class PrivateCloudSyncResponse(BaseModel):
private_cloud_sync_enabled: bool
class OnboardingStateResponse(BaseModel):
completed: bool = False
acquisition_source: str = ''
device_onboarding_completed: bool = False
class UserLanguageResponse(BaseModel):
language: Optional[str] = None
class UserLanguageUpdateResponse(UserStatusResponse):
single_language_mode: bool
class MemorySummaryRatingResponse(BaseModel):
has_rating: bool
rating: Optional[int] = None
class TrainingDataOptInResponse(BaseModel):
opted_in: bool
status: Optional[str] = None
def _location_context_consent_response(consent) -> LocationContextConsentResponse:
return LocationContextConsentResponse(
enabled=bool(consent and consent.is_active()),
expires_at=consent.expires_at if consent and consent.is_active() else None,
)
class DailySummaryTestResponse(UserStatusResponse):
summary_id: str
conversations_count: int
@router.get('/v1/users/profile', tags=['v1'], response_model=UserProfileResponse)
def get_user_profile_endpoint(uid: str = Depends(auth.get_current_user_uid)):
"""Gets the full user profile, including data protection and migration status."""
profile = get_user_profile(uid)
if not profile:
raise HTTPException(status_code=410, detail="User not found")
profile.setdefault('uid', uid)
return profile
class DeleteAccountRequest(BaseModel):
reason: Optional[str] = None
reason_details: Optional[str] = None
@router.delete('/v1/users/delete-account', tags=['v1'], response_model=UserStatusResponse)
def delete_account(
request: DeleteAccountRequest = DeleteAccountRequest(),
uid: str = Depends(auth.get_current_user_uid),
):
try:
return start_account_deletion(uid, reason=request.reason, reason_details=request.reason_details)
except Exception as e:
logger.info(f'delete_account {sanitize(str(e))}')
raise HTTPException(status_code=500, detail='Could not delete account. Please try again.')
# response_model omitted: include_in_schema=False Cloud Tasks handler; JSONResponse
# status codes drive queue retry/ack behavior.
@router.post('/v1/users/account-deletion-wipes/run', include_in_schema=False)
async def run_account_deletion_wipe(
request: Request,
task_authentication: AccountDeletionTaskAuthentication = Depends(verify_account_deletion_cloud_tasks_oidc),
):
try:
payload = await request.json()
if not isinstance(payload, dict):
raise ValueError('payload must be a JSON object')
if 'job_id' not in payload:
raise ValueError('job_id must be a non-empty string')
wipe_job_id = payload['job_id']
if not isinstance(wipe_job_id, str) or not wipe_job_id:
raise ValueError('job_id must be a non-empty string')
resolution_fn = resolve_deletion_wipe_job_id
resolution_arg = wipe_job_id
except Exception as e:
logger.error(f'account_deletion handler: invalid payload, dropping task: {sanitize(str(e))}')
return JSONResponse(status_code=200, content={'status': 'dropped', 'reason': 'invalid_payload'})
try:
resolution = await run_blocking(db_executor, resolution_fn, resolution_arg)
except Exception as e:
logger.error(f'account_deletion handler: job resolution failed, will retry: {sanitize(str(e))}')
return JSONResponse(status_code=500, content={'status': 'retry'})
resolution_outcome = resolution.get('outcome') if isinstance(resolution, dict) else None
uid = resolution.get('uid') if isinstance(resolution, dict) else None
if resolution_outcome != 'resolved' or not isinstance(uid, str) or not uid:
logger.warning('account_deletion handler: dropping task resolution=%s', resolution_outcome)
return JSONResponse(
status_code=200, content={'status': 'dropped', 'reason': resolution_outcome or 'invalid_job'}
)
lock_key = f'account-deletion:{uid}'
lock_token = await run_blocking(db_executor, try_acquire_job_run_lock, lock_key)
if not lock_token:
logger.warning(f'account_deletion handler: run-lock held for {uid}, deferring')
return JSONResponse(status_code=409, content={'status': 'locked'})
release_lock = True
try:
claim_status = await run_blocking(db_executor, claim_deletion_wipe_for_task, uid)
if claim_status == 'completed':
return JSONResponse(status_code=200, content={'status': 'acked', 'job_status': 'completed'})
if claim_status == 'running':
return JSONResponse(status_code=409, content={'status': 'running'})
if claim_status != 'claimed':
logger.warning(f'account_deletion handler: non-actionable task for {uid}, claim_status={claim_status}')
return JSONResponse(status_code=200, content={'status': 'dropped', 'reason': claim_status})
max_attempts = get_account_deletion_tasks_max_attempts()
terminal = task_authentication.retry_count >= max_attempts - 1
ok = await run_blocking(
cleanup_executor,
background_wipe_user_data,
uid,
task_authentication.retry_count,
terminal,
)
if ok:
return JSONResponse(status_code=200, content={'status': 'done'})
if terminal:
logger.error(
f'account_deletion handler: final attempt {task_authentication.retry_count + 1} failed for {uid}'
)
return JSONResponse(status_code=200, content={'status': 'failed_final'})
logger.warning(
f'account_deletion handler: attempt {task_authentication.retry_count + 1} failed for {uid}, will retry'
)
return JSONResponse(status_code=500, content={'status': 'retry'})
except asyncio.CancelledError:
release_lock = False
logger.warning(f'account_deletion handler cancelled for {uid}; preserving run-lock until TTL')
raise
finally:
if release_lock:
await run_blocking(db_executor, release_job_run_lock, lock_key, lock_token)
@router.patch('/v1/users/geolocation', tags=['v1'], response_model=UserStatusResponse)
def set_user_geolocation(geolocation: GeolocationInput, uid: str = Depends(auth.get_current_user_uid)):
validated_geolocation = validated_geolocation_or_none(geolocation)
if validated_geolocation is None:
# Preserve the released endpoint's success-shaped input contract while
# ensuring out-of-range coordinates cannot enter the cache or any provider path.
return {'status': 'ok', 'message': 'Location ignored because its coordinates are invalid.'}
last_location_data = get_cached_user_geolocation(uid)
if last_location_data:
try:
last_location = Geolocation(**last_location_data)
last_lat = round(last_location.latitude, 4)
last_lon = round(last_location.longitude, 4)
new_lat = round(validated_geolocation.latitude, 4)
new_lon = round(validated_geolocation.longitude, 4)
# Only update if location has changed up to 4 decimal places
if last_lat == new_lat and last_lon == new_lon:
return {'status': 'ok', 'message': 'Location not changed significantly.'}
cache_user_geolocation(uid, validated_geolocation.model_dump())
except Exception as e:
logger.error(f"Error processing geolocation update, caching new location anyway. Error: {e}")
cache_user_geolocation(uid, validated_geolocation.model_dump())
else:
# No previous location, so cache the new one
cache_user_geolocation(uid, validated_geolocation.model_dump())
return {'status': 'ok'}
# ***********************************************
# ************* DEVELOPER WEBHOOKS **************
# ***********************************************
class SetUserWebhookUrlRequest(BaseModel):
url: str
@router.post('/v1/users/developer/webhook/{wtype}', tags=['v1'], response_model=UserStatusResponse)
def set_user_webhook_endpoint(
wtype: WebhookType, data: SetUserWebhookUrlRequest, uid: str = Depends(auth.get_current_user_uid)
):
url = data.url
set_user_webhook_db(uid, wtype, url)
if not webhook_url_from_setting(wtype, url):
disable_user_webhook_db(uid, wtype)
else:
enable_user_webhook_db(uid, wtype)
record_dev_webhook_success(uid, wtype)
return {'status': 'ok'}
@router.get('/v1/users/developer/webhook/{wtype}', tags=['v1'], response_model=UserWebhookUrlResponse)
def get_user_webhook_endpoint(wtype: WebhookType, uid: str = Depends(auth.get_current_user_uid)):
return {'url': get_user_webhook_db(uid, wtype)}
@router.post('/v1/users/developer/webhook/{wtype}/disable', tags=['v1'], response_model=UserStatusResponse)
def disable_user_webhook_endpoint(wtype: WebhookType, uid: str = Depends(auth.get_current_user_uid)):
disable_user_webhook_db(uid, wtype)
return {'status': 'ok'}
@router.post('/v1/users/developer/webhook/{wtype}/enable', tags=['v1'], response_model=UserStatusResponse)
def enable_user_webhook_endpoint(wtype: WebhookType, uid: str = Depends(auth.get_current_user_uid)):
enable_user_webhook_db(uid, wtype)
record_dev_webhook_success(uid, wtype.value)
return {'status': 'ok'}
class ButtonEventRequest(BaseModel):
button_event: Literal['single_tap', 'double_tap', 'long_tap']
device_id: str = Field(min_length=1, max_length=128)
event_id: uuid.UUID = Field(description='Stable id for the physical gesture across retries')
timestamp: AwareDatetime
session_id: Optional[str] = Field(default=None, min_length=1, max_length=128)
@router.post('/v1/users/developer/button-event', tags=['v1'], response_model=UserStatusResponse)
async def post_developer_button_event(body: ButtonEventRequest, uid: str = Depends(auth.get_current_user_uid)):
"""App → backend forward of an opt-in hardware button gesture (#11719)."""
await button_event_webhook(
uid,
button_event=body.button_event,
device_id=body.device_id,
event_id=str(body.event_id),
timestamp=body.timestamp.isoformat(),
session_id=body.session_id,
)
return {'status': 'ok'}
@router.get('/v1/users/developer/webhooks/status', tags=['v1'], response_model=UserWebhooksStatusResponse)
def get_user_webhooks_status(uid: str = Depends(auth.get_current_user_uid)):
# This only happens the first time because the user_webhook_status_db function will return None for existing users
audio_bytes = user_webhook_status_db(uid, WebhookType.audio_bytes)
if audio_bytes is None:
audio_bytes = webhook_first_time_setup(uid, WebhookType.audio_bytes)
memory_created = user_webhook_status_db(uid, WebhookType.memory_created)
if memory_created is None:
memory_created = webhook_first_time_setup(uid, WebhookType.memory_created)
realtime_transcript = user_webhook_status_db(uid, WebhookType.realtime_transcript)
if realtime_transcript is None:
realtime_transcript = webhook_first_time_setup(uid, WebhookType.realtime_transcript)
day_summary = user_webhook_status_db(uid, WebhookType.day_summary)
if day_summary is None:
day_summary = webhook_first_time_setup(uid, WebhookType.day_summary)
button_event = user_webhook_status_db(uid, WebhookType.button_event)
if button_event is None:
button_event = webhook_first_time_setup(uid, WebhookType.button_event)
return {
'audio_bytes': audio_bytes,
'memory_created': memory_created,
'realtime_transcript': realtime_transcript,
'day_summary': day_summary,
'button_event': button_event,
}
# *************************************************
# ************* RECORDING PERMISSION **************
# *************************************************
@router.post('/v1/users/store-recording-permission', tags=['v1'], response_model=UserStatusResponse)
def store_recording_permission(value: bool, uid: str = Depends(auth.get_current_user_uid)):
set_user_store_recording_permission(uid, value)
return {'status': 'ok'}
@router.get('/v1/users/store-recording-permission', tags=['v1'], response_model=StoreRecordingPermissionResponse)
def get_store_recording_permission(uid: str = Depends(auth.get_current_user_uid)):
return {'store_recording_permission': get_user_store_recording_permission(uid)}
@router.delete('/v1/users/store-recording-permission', tags=['v1'], response_model=UserStatusResponse)
def delete_permission_and_recordings(uid: str = Depends(auth.get_current_user_uid)):
set_user_store_recording_permission(uid, False)
delete_all_conversation_recordings(uid)
return {'status': 'ok'}
# *************************************************
# ************* ONBOARDING STATE ******************
# *************************************************
@router.get('/v1/users/onboarding', tags=['v1'], response_model=OnboardingStateResponse)
def get_onboarding_state(uid: str = Depends(auth.get_current_user_uid)):
"""Get the user's onboarding state (completed status, acquisition source, etc.)."""
state = get_user_onboarding_state(uid)
# The client-visible state remains backward compatible, while the backend
# issues a separate short-lived admission consumed by the listen runtime.
# A client cannot create this marker by setting the websocket flag.
ensure_backend_onboarding_admission(uid)
return {
'completed': state.get('completed', False),
'acquisition_source': state.get('acquisition_source', ''),
'device_onboarding_completed': state.get('device_onboarding_completed', False),
}
class OnboardingStateUpdate(BaseModel):
completed: Optional[bool] = None
acquisition_source: Optional[str] = None
device_onboarding_completed: Optional[bool] = None
@router.patch('/v1/users/onboarding', tags=['v1'], response_model=UserStatusResponse)
def update_onboarding_state(data: OnboardingStateUpdate, uid: str = Depends(auth.get_current_user_uid)):
"""Update the user's onboarding state."""
current_state = get_user_onboarding_state(uid)
if data.completed is not None:
current_state['completed'] = data.completed
if data.acquisition_source is not None:
current_state['acquisition_source'] = data.acquisition_source
if data.device_onboarding_completed is not None:
current_state['device_onboarding_completed'] = data.device_onboarding_completed
set_user_onboarding_state(uid, current_state)
return {'status': 'ok'}
# *************************************************
# ************* PRIVATE CLOUD SYNC ****************
# *************************************************
@router.post('/v1/users/private-cloud-sync', tags=['v1'], response_model=UserStatusResponse)
def set_private_cloud_sync(value: bool, uid: str = Depends(auth.get_current_user_uid)):
set_user_private_cloud_sync_enabled(uid, value)
return {'status': 'ok'}
@router.get('/v1/users/private-cloud-sync', tags=['v1'], response_model=PrivateCloudSyncResponse)
def get_private_cloud_sync(uid: str = Depends(auth.get_current_user_uid)):
return {'private_cloud_sync_enabled': get_user_private_cloud_sync_enabled(uid)}
# ****************************************
# ************* PEOPLE CRUD **************
# ****************************************
# Person photo deferred — see models.other.Person (no photo field / storage yet).
@router.post('/v1/users/people', tags=['v1'], response_model=Person)
def get_or_create_person(data: CreatePerson, uid: str = Depends(auth.get_current_user_uid)):
"""Create a new person or return existing one with same name (idempotent by name).
This enables backward compatibility: old apps can call this API and get the
same person that backend already created, preventing duplicates.
"""
# Check if person with same name already exists
existing_person = get_person_by_name(uid, data.name)
if existing_person:
return existing_person
# Create new person
person_data = {
'id': str(uuid.uuid4()),
'name': data.name,
'created_at': datetime.now(timezone.utc),
'updated_at': datetime.now(timezone.utc),
}
result = create_person(uid, person_data)
return result
@router.get('/v1/users/people/{person_id}', tags=['v1'], response_model=Person)
def get_single_person(
person_id: str, include_speech_samples: bool = False, uid: str = Depends(auth.get_current_user_uid)
):
person = get_person(uid, person_id)
if not person:
raise HTTPException(status_code=404, detail="Person not found")
if include_speech_samples:
# Convert stored GCS paths to signed URLs
stored_paths = person.get('speech_samples', [])
person['speech_samples'] = get_speech_sample_signed_urls(stored_paths)
return person
@router.get('/v1/users/people', tags=['v1'], response_model=List[Person])
def get_all_people(include_speech_samples: bool = True, uid: str = Depends(auth.get_current_user_uid)):
logger.info(f'get_all_people {include_speech_samples}')
people = get_people(uid)
if include_speech_samples:
# Convert GCS paths to signed URLs for each person
for i, person in enumerate(people):
stored_paths = person.get('speech_samples', [])
people[i]['speech_samples'] = get_speech_sample_signed_urls(stored_paths)
return people
@router.patch('/v1/users/people/{person_id}/name', tags=['v1'], response_model=UserStatusResponse)
def update_person_name(
person_id: str,
value: str, # = Field(min_length=2, max_length=40),
uid: str = Depends(auth.get_current_user_uid),
):
if not update_person(uid, person_id, value):
raise HTTPException(status_code=404, detail="Person not found")
return {'status': 'ok'}
@router.delete('/v1/users/people/{person_id}', tags=['v1'], status_code=204)
def delete_person_endpoint(person_id: str, uid: str = Depends(auth.get_current_user_uid)):
delete_person(uid, person_id)
delete_user_person_speech_samples(uid, person_id)
@router.delete(
'/v1/users/people/{person_id}/speech-samples/{sample_index}',
tags=['v1'],
response_model=UserStatusResponse,
)
def delete_person_speech_sample_endpoint(
person_id: str,
sample_index: int,
uid: str = Depends(auth.get_current_user_uid),
):
"""Delete a specific speech sample for a person by index."""
person = get_person(uid, person_id)
if not person:
raise HTTPException(status_code=404, detail="Person not found")
speech_samples = person.get('speech_samples', [])
if sample_index < 0 or sample_index >= len(speech_samples):
raise HTTPException(status_code=404, detail="Sample not found")
path_to_delete = speech_samples[sample_index]
# Extract filename from path for GCS deletion
filename = path_to_delete.split('/')[-1]
# Delete from GCS
delete_user_person_speech_sample(uid, person_id, filename)
# Remove from Firestore
from database.users import remove_person_speech_sample
remove_person_speech_sample(uid, person_id, path_to_delete)
return {'status': 'ok'}
# **********************************************************
# ************* RANDOM JOAN SPECIFIC FEATURES **************
# **********************************************************
class FollowupQuestionResponse(BaseModel):
"""Response for the Joan follow-up question endpoint (a generated prompt)."""
result: str = Field(description='Generated follow-up question prompt text.')
@router.delete('/v1/joan/{memory_id}/followup-question', tags=['v1'], response_model=FollowupQuestionResponse)
def delete_person_endpoint(memory_id: str, uid: str = Depends(auth.get_current_user_uid)):
if memory_id == '0':
memory = get_in_progress_conversation(uid)
if not memory:
raise HTTPException(status_code=400, detail='No memory in progres')
else:
memory = get_conversation(uid, memory_id)
if not memory:
raise HTTPException(status_code=404, detail='Conversation not found')
if memory.get('is_locked', False):
raise HTTPException(status_code=402, detail='A paid plan is required to access this conversation.')
memory = deserialize_conversation(memory)
return {'result': followup_question_prompt(uid, memory.transcript_segments)}
# **************************************
# ************* Analytics **************
# **************************************
@router.post('/v1/users/analytics/memory_summary', tags=['v1'], response_model=UserStatusResponse)
def set_memory_summary_rating(
memory_id: str,
value: int, # 0, 1, -1 (shown)
uid: str = Depends(auth.get_current_user_uid),
):
# The conversation-summary rating UI has been unreachable since 2025-04-11
# (bbfe540bc4 / PR #2178) while field builds kept writing ~1,105 impression
# rows/day. No-op the server first so every client version stops writing —
# including into the unified feedback ledger, which would otherwise record
# a "rating" that no user action produced.
return {'status': 'ok'}
@router.get(
'/v1/users/analytics/memory_summary',
tags=['v1'],
response_model=MemorySummaryRatingResponse,
dependencies=[Depends(auth.get_current_user_uid)],
)
def get_memory_summary_rating(memory_id: str):
rating = get_conversation_summary_rating_score(memory_id)
if not rating:
return {'has_rating': False}
return {'has_rating': rating.get('value', -1) != -1, 'rating': rating.get('value', -1)}
@router.post('/v1/users/analytics/chat_message', tags=['v1'], response_model=UserStatusResponse)
def set_chat_message_analytics(
message_id: str,
value: int,
reason: str = None, # Reason for thumbs down (e.g. 'too_verbose', 'incorrect_or_hallucination')
uid: str = Depends(auth.get_current_user_uid),
):
"""
Submit feedback rating for a chat message.
Args:
message_id: ID of the message being rated
value: Rating value (1 = thumbs up, -1 = thumbs down, 0 = user cleared)
reason: Optional reason for thumbs down. Enum keys only.
"""
rating_value = None if value == 0 else value
snapshot = chat_db.update_message_rating(uid, message_id, rating_value) or {}
triage = extract_rating_triage_fields(snapshot)
normalized_reason = normalize_rating_reason(reason)
set_chat_message_rating_score(
uid,
message_id,
value,
reason=normalized_reason,
platform='mobile',
notification_kind=triage.get('notification_kind'),
app_id=triage.get('app_id'),
)
# Unified feedback ledger — the daily thumbs-down report reads from here.
record_chat_message_feedback(uid, message_id, value, reason=normalized_reason, platform='mobile')
# Try to submit feedback to LangSmith if the message has a run_id
try:
from utils.observability import submit_langsmith_feedback
# Look up the message to get langsmith_run_id
message_result = chat_db.get_message(uid, message_id)
if message_result:
message, _ = message_result
langsmith_run_id = getattr(message, 'langsmith_run_id', None)
if not langsmith_run_id and isinstance(message, dict):
langsmith_run_id = message.get('langsmith_run_id')
if langsmith_run_id:
# Map value to score: 1 (thumbs up) -> 1.0, -1 (thumbs down) -> 0.0
score = 1.0 if value == 1 else (0.0 if value == -1 else 0.5)
# Build comment from reason if provided
comment = reason if reason else None
# Submit feedback to LangSmith (non-blocking, errors are logged)
submit_langsmith_feedback(
run_id=langsmith_run_id,
score=score,
key="chat_message_rating",
comment=comment,
)
except Exception as e:
# Don't fail the request if LangSmith feedback fails
logger.error(f"⚠️ LangSmith feedback submission error (non-fatal): {e}")
return {'status': 'ok'}
# ***************************************
# ************* Language ****************
# ***************************************
@router.get('/v1/users/available-languages', tags=['v1'], response_model=AvailableLanguagesResponse)
def get_available_languages(uid: str = Depends(auth.get_current_user_uid)):
"""Primary-language options for the picker, in render order."""
return {'languages': [{'code': code, 'name': name} for code, name in PRIMARY_LANGUAGE_OPTIONS]}
@router.get('/v1/users/language', tags=['v1'], response_model=UserLanguageResponse)
def get_user_language(uid: str = Depends(auth.get_current_user_uid)):
"""Get the user's preferred language."""
language = get_user_language_preference(uid)
return {'language': language or None}
class SetUserLanguageRequest(BaseModel):
language: str
@router.patch('/v1/users/language', tags=['v1'], response_model=UserLanguageUpdateResponse)
def set_user_language(data: SetUserLanguageRequest, uid: str = Depends(auth.get_current_user_uid)):
"""Set the user's preferred language (e.g., 'en', 'vi', etc.)."""
language = normalize_user_language(data.language)
if not language:
raise HTTPException(status_code=400, detail="A supported language code is required")
set_user_language_preference(uid, language)
single_language_mode = not supports_live_multilingual_mode(language)
set_user_transcription_preferences(uid, single_language_mode=single_language_mode)
return {'status': 'ok', 'single_language_mode': single_language_mode}
# *************************************************
# ********** Transcription Preferences ************
# *************************************************
class TranscriptionPreferencesResponse(BaseModel):
single_language_mode: bool = False
vocabulary: List[str] = Field(default_factory=list)
language: str = ''
uses_custom_stt: bool = False
custom_stt_since: Optional[datetime] = None
class TranscriptionPreferencesUpdate(BaseModel):
single_language_mode: Optional[bool] = None
vocabulary: Optional[List[str]] = None
@router.get('/v1/users/transcription-preferences', tags=['v1'], response_model=TranscriptionPreferencesResponse)
def get_transcription_preferences_endpoint(uid: str = Depends(auth.get_current_user_uid)):
"""Get user's transcription preferences (single language mode, vocabulary)."""
prefs = get_user_transcription_preferences(uid)
return prefs
@router.patch('/v1/users/transcription-preferences', tags=['v1'], response_model=UserStatusResponse)
def update_transcription_preferences_endpoint(
data: TranscriptionPreferencesUpdate, uid: str = Depends(auth.get_current_user_uid)
):
"""
Update user's transcription preferences.
- single_language_mode: If True, uses exact language for higher accuracy but disables translation
- vocabulary: List of custom keywords/terms (max 100) for better transcription accuracy
"""
set_user_transcription_preferences(uid, single_language_mode=data.single_language_mode, vocabulary=data.vocabulary)
return {'status': 'ok'}
# **************************************
# ********* Data Protection ************
# **************************************
@router.post('/v1/users/migration/requests', tags=['v1'], response_model=MigrationStatusResponse)
def handle_migration_requests(
request: Union[MigrationRequest, MigrationTargetRequest], uid: str = Depends(auth.get_current_user_uid)
):
"""
Handles data migration requests.
- If 'id' and 'type' are present, it migrates a single object.
- Otherwise, it initiates the data migration process for a 'target_level'.
"""
if isinstance(request, MigrationRequest):
# This is for migrating a single object
if request.type == 'conversation':
try:
conversations_db.migrate_conversations_level_batch(uid, [request.id], request.target_level)
return {'status': 'ok'}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to migrate conversation {request.id}: {e}")
elif request.type == 'memory':
try:
memories_db.migrate_memories_level_batch(uid, [request.id], request.target_level)
return {'status': 'ok'}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to migrate memory {request.id}: {e}")
elif request.type == 'chat':
try:
chat_db.migrate_chats_level_batch(uid, [request.id], request.target_level)
return {'status': 'ok'}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to migrate chat message {request.id}: {e}")
else:
raise HTTPException(status_code=400, detail=f"Unknown object type for migration: {request.type}")
elif isinstance(request, MigrationTargetRequest):
# This is for starting the migration process
if request.target_level != 'enhanced':
raise HTTPException(
status_code=400, detail="Invalid target_level. Only migration to 'enhanced' is supported."
)
set_migration_status(uid, request.target_level)
return {'status': 'ok', 'message': 'Migration status set.'}
@router.get('/v1/users/migration/requests', tags=['v1'], response_model=MigrationRequestsResponse)
def get_migration_requests(target_level: str, uid: str = Depends(auth.get_current_user_uid)):
"""Checks which documents need to be migrated to the target level."""
if target_level != 'enhanced':
raise HTTPException(status_code=400, detail="Invalid target_level. Only migration to 'enhanced' is supported.")
conversations_to_migrate = conversations_db.get_conversations_to_migrate(uid, target_level)
memories_to_migrate = memories_db.get_memories_to_migrate(uid, target_level)
chats_to_migrate = chat_db.get_chats_to_migrate(uid, target_level)
needs_migration = conversations_to_migrate + memories_to_migrate + chats_to_migrate
return {"needs_migration": needs_migration}
@router.post('/v1/users/migration/batch-requests', tags=['v1'], response_model=MigrationStatusResponse)
def handle_batch_migration_requests(
batch_request: BatchMigrationRequest, uid: str = Depends(auth.get_current_user_uid)
):
"""Migrates a batch of data objects to the target protection level."""
errors = []
# Group requests by type and target_level
grouped_requests: Dict[tuple[str, str], List[str]] = {}
for req in batch_request.requests:
key = (req.type, req.target_level)
if key not in grouped_requests:
grouped_requests[key] = []
grouped_requests[key].append(req.id)
for (req_type, target_level), ids in grouped_requests.items():
try:
if req_type == 'conversation':
conversations_db.migrate_conversations_level_batch(uid, ids, target_level)
elif req_type == 'memory':
memories_db.migrate_memories_level_batch(uid, ids, target_level)
elif req_type == 'chat':
chat_db.migrate_chats_level_batch(uid, ids, target_level)
else:
errors.append(f"Unknown object type for migration: {req_type}")
except Exception as e:
error_detail = f"Failed to migrate batch of type {req_type}: {e}"
logger.info(error_detail)
errors.append(error_detail)
if errors:
raise HTTPException(status_code=500, detail={"message": "Some objects failed to migrate.", "errors": errors})
return {'status': 'ok'}
@router.post(
'/v1/users/migration/requests/data-protection-level/finalize',
tags=['v1'],
response_model=MigrationStatusResponse,
)
def finalize_migration_request(request: MigrationTargetRequest, uid: str = Depends(auth.get_current_user_uid)):
"""Finalizes the migration by setting the user's global protection level."""
if request.target_level != 'enhanced':
raise HTTPException(status_code=400, detail="Invalid target_level. Only migration to 'enhanced' is supported.")
finalize_migration(uid, request.target_level)
set_user_data_protection_level(uid, request.target_level)
return {'status': 'ok'}
@router.put('/v1/users/preferences/app', tags=['v1'], response_model=UserStatusResponse)
def set_preferred_app_for_user(