-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathusers.py
More file actions
1053 lines (791 loc) · 32.3 KB
/
users.py
File metadata and controls
1053 lines (791 loc) · 32.3 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 datetime import datetime, timezone
from typing import Optional
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter, transactional
from ._client import db, document_id_from_seed
from models.users import Subscription, PlanLimits, PlanType, SubscriptionStatus
from utils.subscription import get_default_basic_subscription
import logging
logger = logging.getLogger(__name__)
def is_exists_user(uid: str):
user_ref = db.collection('users').document(uid)
if not user_ref.get().exists:
return False
return True
def get_user_profile(uid: str) -> dict:
"""Gets the full user profile document."""
user_ref = db.collection('users').document(uid)
user_doc = user_ref.get()
if user_doc.exists:
return user_doc.to_dict()
return {}
def get_user_store_recording_permission(uid: str):
user_ref = db.collection('users').document(uid)
user_data = user_ref.get().to_dict()
return user_data.get('store_recording_permission', False)
def set_user_store_recording_permission(uid: str, value: bool):
user_ref = db.collection('users').document(uid)
user_ref.update({'store_recording_permission': value})
def get_user_private_cloud_sync_enabled(uid: str) -> bool:
"""Check if user has private cloud sync enabled."""
user_ref = db.collection('users').document(uid)
user_data = user_ref.get().to_dict()
return user_data.get('private_cloud_sync_enabled', True)
def set_user_private_cloud_sync_enabled(uid: str, value: bool):
"""Enable or disable private cloud sync for a user."""
user_ref = db.collection('users').document(uid)
user_ref.update({'private_cloud_sync_enabled': value})
def create_person(uid: str, data: dict):
people_ref = db.collection('users').document(uid).collection('people')
people_ref.document(data['id']).set(data)
return data
def get_person(uid: str, person_id: str):
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_doc = person_ref.get()
if not person_doc.exists:
return None
person_data = person_doc.to_dict()
person_data.setdefault('id', person_doc.id)
return person_data
def get_people(uid: str):
people_ref = db.collection('users').document(uid).collection('people')
result = []
for person in people_ref.stream():
data = person.to_dict()
data.setdefault('id', person.id)
result.append(data)
return result
def get_person_by_name(uid: str, name: str):
people_ref = db.collection('users').document(uid).collection('people')
query = people_ref.where(filter=FieldFilter('name', '==', name)).limit(1)
docs = list(query.stream())
if docs:
data = docs[0].to_dict()
data.setdefault('id', docs[0].id)
return data
return None
def get_people_by_ids(uid: str, person_ids: list[str]):
"""Fetch people docs by ID using db.get_all().
Note: db.get_all() returns results in arbitrary order (Firestore behavior).
Callers must not assume the result order matches person_ids order.
"""
if not person_ids:
return []
people_ref = db.collection('users').document(uid).collection('people')
# Use document ID fetches instead of where("id", "in", ...) to handle
# legacy docs that may not have a stored 'id' field.
doc_refs = [people_ref.document(pid) for pid in person_ids]
all_people = []
for doc in db.get_all(doc_refs):
if doc.exists:
data = doc.to_dict()
data.setdefault('id', doc.id)
all_people.append(data)
return all_people
def update_person(uid: str, person_id: str, name: str):
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_ref.update({'name': name})
def delete_person(uid: str, person_id: str):
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_ref.delete()
@transactional
def _add_sample_transaction(transaction, person_ref, sample_path, transcript, max_samples):
"""Transaction to atomically add sample and transcript."""
snapshot = person_ref.get(transaction=transaction)
if not snapshot.exists:
return False
person_data = snapshot.to_dict()
samples = person_data.get('speech_samples', [])
if len(samples) >= max_samples:
return False
samples.append(sample_path)
update_data = {
'speech_samples': samples,
'updated_at': datetime.now(timezone.utc),
}
if transcript is not None:
transcripts = person_data.get('speech_sample_transcripts', [])
# Ensure transcript array alignment with samples:
# If we're adding a transcript but existing samples don't have transcripts,
# pad with empty strings for the existing samples first (Dart expects non-null)
existing_sample_count = len(samples) - 1 # samples already has new one appended
if len(transcripts) < existing_sample_count:
# Pad with empty strings for each existing sample without a transcript
transcripts.extend([''] * (existing_sample_count - len(transcripts)))
transcripts.append(transcript)
update_data['speech_sample_transcripts'] = transcripts
update_data['speech_samples_version'] = 3
transaction.update(person_ref, update_data)
return True
def add_person_speech_sample(
uid: str, person_id: str, sample_path: str, transcript: Optional[str] = None, max_samples: int = 5
) -> bool:
"""
Append speech sample path to person's speech_samples list.
Limits to max_samples to prevent unlimited growth.
Uses Firestore transaction to ensure atomic read-modify-write,
preventing array drift from concurrent updates.
Args:
uid: User ID
person_id: Person ID
sample_path: GCS path to the speech sample
transcript: Optional transcript text for the sample
max_samples: Maximum number of samples to keep (default 5)
Returns:
True if sample was added, False if limit reached or person not found
"""
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
transaction = db.transaction()
return _add_sample_transaction(transaction, person_ref, sample_path, transcript, max_samples)
def get_person_speech_samples_count(uid: str, person_id: str) -> int:
"""Get the count of speech samples for a person."""
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_doc = person_ref.get()
if not person_doc.exists:
return 0
person_data = person_doc.to_dict()
return len(person_data.get('speech_samples', []))
def remove_person_speech_sample(uid: str, person_id: str, sample_path: str) -> bool:
"""
Remove a speech sample path from person's speech_samples list.
Also removes the corresponding transcript at the same index to keep arrays in sync.
Args:
uid: User ID
person_id: Person ID
sample_path: GCS path to remove
Returns:
True if removed, False if person or sample not found
"""
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_doc = person_ref.get()
if not person_doc.exists:
return False
person_data = person_doc.to_dict()
samples = person_data.get('speech_samples', [])
transcripts = person_data.get('speech_sample_transcripts', [])
# Find index of sample to remove
try:
idx = samples.index(sample_path)
except ValueError:
return False # Sample not found
# Remove from both arrays by index
samples.pop(idx)
if idx < len(transcripts):
transcripts.pop(idx)
person_ref.update(
{
'speech_samples': samples,
'speech_sample_transcripts': transcripts,
'updated_at': datetime.now(timezone.utc),
}
)
return True
def set_person_speaker_embedding(uid: str, person_id: str, embedding: list) -> bool:
"""
Store speaker embedding for a person.
Args:
uid: User ID
person_id: Person ID
embedding: List of floats representing the speaker embedding
Returns:
True if stored successfully, False if person not found
"""
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_doc = person_ref.get()
if not person_doc.exists:
return False
person_ref.update(
{
'speaker_embedding': embedding,
'updated_at': datetime.now(timezone.utc),
}
)
return True
def get_person_speaker_embedding(uid: str, person_id: str) -> Optional[list]:
"""
Get speaker embedding for a person.
Args:
uid: User ID
person_id: Person ID
Returns:
List of floats representing the embedding, or None if not found
"""
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_doc = person_ref.get()
if not person_doc.exists:
return None
person_data = person_doc.to_dict()
return person_data.get('speaker_embedding')
def set_person_speech_sample_transcript(uid: str, person_id: str, sample_index: int, transcript: str) -> bool:
"""
Update transcript at a specific index in the speech_sample_transcripts array.
Args:
uid: User ID
person_id: Person ID
sample_index: Index of the sample/transcript to update
transcript: The transcript text to set
Returns:
True if updated successfully, False if person not found or index out of bounds
"""
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_doc = person_ref.get()
if not person_doc.exists:
return False
person_data = person_doc.to_dict()
samples = person_data.get('speech_samples', [])
transcripts = person_data.get('speech_sample_transcripts', [])
# Validate index
if sample_index < 0 or sample_index >= len(samples):
return False
# Extend transcripts array if needed
while len(transcripts) < len(samples):
transcripts.append('')
transcripts[sample_index] = transcript
person_ref.update(
{
'speech_sample_transcripts': transcripts,
'updated_at': datetime.now(timezone.utc),
}
)
return True
def update_person_speech_samples_after_migration(
uid: str,
person_id: str,
samples: list,
transcripts: list,
version: int,
speaker_embedding: Optional[list] = None,
) -> bool:
"""
Replace all samples/transcripts/embedding and set version atomically.
Used after v1 to v2 migration to update all related fields together.
Args:
uid: User ID
person_id: Person ID
samples: List of sample paths (may have dropped invalid samples)
transcripts: List of transcript strings (parallel array with samples)
version: Version number to set (typically 2)
speaker_embedding: Optional new speaker embedding, or None to clear
Returns:
True if updated successfully, False if person not found
"""
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_doc = person_ref.get()
if not person_doc.exists:
return False
update_data = {
'speech_samples': samples,
'speech_sample_transcripts': transcripts,
'speech_samples_version': version,
'updated_at': datetime.now(timezone.utc),
}
# Set or clear speaker embedding
if speaker_embedding is not None:
update_data['speaker_embedding'] = speaker_embedding
else:
update_data['speaker_embedding'] = firestore.DELETE_FIELD
person_ref.update(update_data)
return True
def clear_person_speaker_embedding(uid: str, person_id: str) -> bool:
"""
Clear speaker embedding for a person.
Used when all samples are dropped during migration.
Args:
uid: User ID
person_id: Person ID
Returns:
True if cleared successfully, False if person not found
"""
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_doc = person_ref.get()
if not person_doc.exists:
return False
person_ref.update(
{
'speaker_embedding': firestore.DELETE_FIELD,
'updated_at': datetime.now(timezone.utc),
}
)
return True
def update_person_speech_samples_version(uid: str, person_id: str, version: int) -> bool:
"""
Update just the speech_samples_version field.
Args:
uid: User ID
person_id: Person ID
version: Version number to set
Returns:
True if updated successfully, False if person not found
"""
person_ref = db.collection('users').document(uid).collection('people').document(person_id)
person_doc = person_ref.get()
if not person_doc.exists:
return False
person_ref.update(
{
'speech_samples_version': version,
'updated_at': datetime.now(timezone.utc),
}
)
return True
def delete_user_data(uid: str):
user_ref = db.collection('users').document(uid)
if not user_ref.get().exists:
return {'status': 'error', 'message': 'User not found'}
subcollections_to_delete = ['conversations', 'messages', 'chat_sessions', 'people', 'memories', 'files']
batch_size = 450
for cname in subcollections_to_delete:
logger.info(f"Deleting subcollection: {cname} for user {uid}")
collection_ref = user_ref.collection(cname)
while True:
docs_query = collection_ref.limit(batch_size)
docs = list(docs_query.stream())
if not docs:
# docs might not exists, try using {parent path / id}
logger.info(f"No more documents to delete in {collection_ref.parent.path}/{collection_ref.id}")
break
batch = db.batch()
for doc in docs:
logger.info(f"Deleting document: {doc.reference.path}")
batch.delete(doc.reference)
batch.commit()
if len(docs) < batch_size:
logger.info(f"Processed all documents in {collection_ref.path}")
break
# delete the user document itself
logger.info(f"Deleting user document: {uid}")
user_ref.delete()
return {'status': 'ok', 'message': 'Account deleted successfully'}
# **************************************
# ************* Analytics **************
# **************************************
def set_conversation_summary_rating_score(uid: str, conversation_id: str, value: int):
doc_id = document_id_from_seed('memory_summary' + conversation_id)
db.collection('analytics').document(doc_id).set(
{
'id': doc_id,
'memory_id': conversation_id,
'uid': uid,
'value': value,
'created_at': datetime.now(timezone.utc),
'type': 'memory_summary',
}
)
def get_conversation_summary_rating_score(conversation_id: str):
doc_id = document_id_from_seed('memory_summary' + conversation_id)
doc_ref = db.collection('analytics').document(doc_id)
doc = doc_ref.get()
if doc.exists:
return doc.to_dict()
return None
def get_all_ratings(rating_type: str = 'memory_summary'):
ratings = db.collection('analytics').where('type', '==', rating_type).stream()
return [rating.to_dict() for rating in ratings]
def set_chat_message_rating_score(uid: str, message_id: str, value: int, reason: str = None):
"""
Store chat message rating/feedback.
Args:
uid: User ID
message_id: Message ID being rated
value: Rating value (1 = thumbs up, -1 = thumbs down, 0 = neutral/removed)
reason: Optional reason for thumbs down (e.g. 'too_verbose', 'incorrect_or_hallucination',
'not_helpful_or_irrelevant', 'didnt_follow_instructions', 'other')
"""
doc_id = document_id_from_seed('chat_message' + message_id)
data = {
'id': doc_id,
'message_id': message_id,
'uid': uid,
'value': value,
'created_at': datetime.now(timezone.utc),
'type': 'chat_message',
}
if reason:
data['reason'] = reason
db.collection('analytics').document(doc_id).set(data)
# **************************************
# ************** Payments **************
# **************************************
def get_stripe_connect_account_id(uid: str):
user_ref = db.collection('users').document(uid)
user_data = user_ref.get().to_dict()
return user_data.get('stripe_account_id', None)
def set_stripe_connect_account_id(uid: str, account_id: str):
user_ref = db.collection('users').document(uid)
user_ref.update({'stripe_account_id': account_id})
def set_paypal_payment_details(uid: str, data: dict):
user_ref = db.collection('users').document(uid)
user_ref.update({'paypal_details': data})
def get_paypal_payment_details(uid: str):
user_ref = db.collection('users').document(uid)
user_data = user_ref.get().to_dict()
return user_data.get('paypal_details', None)
def set_default_payment_method(uid: str, payment_method_id: str):
user_ref = db.collection('users').document(uid)
user_ref.update({'default_payment_method': payment_method_id})
def get_default_payment_method(uid: str):
user_ref = db.collection('users').document(uid)
user_data = user_ref.get().to_dict()
return user_data.get('default_payment_method', None)
def get_stripe_customer_id(uid: str) -> Optional[str]:
"""Get the Stripe customer ID for a user."""
user_ref = db.collection('users').document(uid)
user_doc = user_ref.get()
if user_doc.exists:
user_data = user_doc.to_dict()
return user_data.get('stripe_customer_id')
return None
def set_stripe_customer_id(uid: str, customer_id: str):
user_ref = db.collection('users').document(uid)
user_ref.update({'stripe_customer_id': customer_id})
def get_user_by_stripe_customer_id(customer_id: str):
users_ref = db.collection('users')
query = users_ref.where(filter=FieldFilter('stripe_customer_id', '==', customer_id)).limit(1)
docs = list(query.stream())
if docs:
user_dict = docs[0].to_dict()
user_dict['uid'] = docs[0].id
return user_dict
return None
def update_user_subscription(uid: str, subscription_data: dict):
"""Updates the user's subscription information, removing dynamic fields before storing."""
subscription_data_to_store = subscription_data.copy()
subscription_data_to_store.pop('features', None)
subscription_data_to_store.pop('limits', None)
user_ref = db.collection('users').document(uid)
user_ref.update({'subscription': subscription_data_to_store})
# **************************************
# ********* Data Protection ************
# **************************************
def get_data_protection_level(uid: str) -> str:
"""
Get the user's data protection level.
Args:
uid: User ID
Returns:
'enhanced' or 'e2ee'. Defaults to 'enhanced'.
"""
user_ref = db.collection('users').document(uid)
user_doc = user_ref.get()
if user_doc.exists:
user_data = user_doc.to_dict()
return user_data.get('data_protection_level', 'enhanced')
return 'enhanced'
def set_data_protection_level(uid: str, level: str) -> None:
"""
Set the user's data protection level.
Args:
uid: User ID
level: 'enhanced', or 'e2ee'
"""
if level not in ['enhanced', 'e2ee']:
raise ValueError("Invalid data protection level. Only 'enhanced' or 'e2ee' are supported.")
user_ref = db.collection('users').document(uid)
user_ref.set({'data_protection_level': level}, merge=True)
def set_migration_status(uid: str, target_level: str):
"""Sets the migration status on the user's profile."""
user_ref = db.collection('users').document(uid)
migration_status = {'target_level': target_level, 'status': 'in_progress', 'started_at': datetime.now(timezone.utc)}
user_ref.set({'migration_status': migration_status}, merge=True)
def finalize_migration(uid: str, target_level: str):
"""Atomically sets the new protection level and removes the migration status field."""
user_ref = db.collection('users').document(uid)
user_ref.update({'data_protection_level': target_level, 'migration_status': firestore.DELETE_FIELD})
# **************************************
# ************* Language ***************
# **************************************
def get_user_language_preference(uid: str) -> str:
"""
Get the user's preferred language.
Args:
uid: User ID
Returns:
Language code (e.g., 'en', 'vi') or empty string if not set
"""
user_ref = db.collection('users').document(uid)
user_doc = user_ref.get()
if user_doc.exists:
user_data = user_doc.to_dict()
return user_data.get('language', '')
return '' # Return empty string if not set
def set_user_language_preference(uid: str, language: str) -> None:
"""
Set the user's preferred language.
Args:
uid: User ID
language: Language code (e.g., 'en', 'vi')
"""
user_ref = db.collection('users').document(uid)
user_ref.set({'language': language}, merge=True)
def get_user_onboarding_state(uid: str) -> dict:
"""Get the user's onboarding state from Firestore."""
user_ref = db.collection('users').document(uid)
user_doc = user_ref.get()
if user_doc.exists:
user_data = user_doc.to_dict()
return user_data.get('onboarding', {})
return {}
def set_user_onboarding_state(uid: str, onboarding_data: dict) -> None:
"""Update the user's onboarding state in Firestore (merge with existing)."""
user_ref = db.collection('users').document(uid)
user_ref.set({'onboarding': onboarding_data}, merge=True)
def get_user_subscription(uid: str) -> Subscription:
"""Gets the user's subscription, creating a default free one if it doesn't exist."""
user_ref = db.collection('users').document(uid)
user_doc = user_ref.get(['subscription'])
if user_doc.exists:
user_data = user_doc.to_dict()
if 'subscription' in user_data:
sub_data = user_data['subscription']
# Handle migration for old 'free' plan identifier
if sub_data.get('plan') == 'free':
sub_data['plan'] = PlanType.basic.value
update_user_subscription(uid, sub_data)
return Subscription(**sub_data)
# If subscription doesn't exist for the user, create and return a default free plan.
default_subscription = get_default_basic_subscription()
# Strip dynamic fields before storing
sub_to_store = default_subscription.dict()
sub_to_store.pop('features', None)
sub_to_store.pop('limits', None)
user_ref.set({'subscription': sub_to_store}, merge=True)
return default_subscription
def get_user_training_data_opt_in(uid: str) -> Optional[dict]:
"""Get user's training data opt-in status."""
user_ref = db.collection('users').document(uid)
user_data = user_ref.get().to_dict()
return user_data.get('training_data_opt_in', None)
def set_user_training_data_opt_in(uid: str, status: str):
"""Set user's training data opt-in status. Status can be: pending_review, approved, rejected"""
user_ref = db.collection('users').document(uid)
user_ref.update(
{
'training_data_opt_in': {
'status': status,
'requested_at': datetime.now(timezone.utc),
}
}
)
def get_user_valid_subscription(uid: str) -> Optional[Subscription]:
"""
Gets the user's subscription if it is currently valid for use.
A subscription is considered valid if:
- It's a basic (free) plan with 'active' status.
- It's a paid plan with a 'current_period_end' that has not passed yet.
This allows users to use the service until the end of the billing period
they paid for, even after cancelling.
Returns the Subscription object if valid, otherwise None.
"""
subscription = get_user_subscription(uid)
# Basic (free) plans are only valid if their status is active.
if subscription.plan == PlanType.basic:
return subscription if subscription.status == SubscriptionStatus.active else None
# For paid plans (e.g., unlimited), validity is determined by the period end.
if subscription.current_period_end:
period_end_dt = datetime.fromtimestamp(subscription.current_period_end, tz=timezone.utc)
if period_end_dt >= datetime.now(timezone.utc):
return subscription
# Fallback to default basic subscription
return get_default_basic_subscription()
# **************************************
# ******** Task Integrations ***********
# **************************************
def get_task_integrations(uid: str) -> dict:
"""
Get all task integration connections for a user.
Args:
uid: User ID
Returns:
Dictionary with app_key as keys and connection details as values
"""
user_ref = db.collection('users').document(uid)
integrations_ref = user_ref.collection('task_integrations')
integrations = {}
for doc in integrations_ref.stream():
integrations[doc.id] = doc.to_dict()
return integrations
def get_task_integration(uid: str, app_key: str) -> Optional[dict]:
"""
Get a specific task integration connection.
Args:
uid: User ID
app_key: Task integration app key (e.g., 'asana', 'todoist')
Returns:
Connection details or None if not found
"""
user_ref = db.collection('users').document(uid)
integration_ref = user_ref.collection('task_integrations').document(app_key)
doc = integration_ref.get()
if doc.exists:
return doc.to_dict()
return None
def set_task_integration(uid: str, app_key: str, data: dict) -> None:
"""
Save or update a task integration connection.
Args:
uid: User ID
app_key: Task integration app key (e.g., 'asana', 'todoist')
data: Connection details to save
"""
user_ref = db.collection('users').document(uid)
integration_ref = user_ref.collection('task_integrations').document(app_key)
# Add timestamp
data['updated_at'] = datetime.now(timezone.utc)
if not integration_ref.get().exists:
data['created_at'] = datetime.now(timezone.utc)
integration_ref.set(data, merge=True)
def delete_task_integration(uid: str, app_key: str) -> bool:
"""
Delete a task integration connection.
Also clears default_task_integration if it matches the deleted app.
Args:
uid: User ID
app_key: Task integration app key
Returns:
True if deleted, False if not found
"""
user_ref = db.collection('users').document(uid)
integration_ref = user_ref.collection('task_integrations').document(app_key)
if not integration_ref.get().exists:
return False
# Check if this is the default integration
user_doc = user_ref.get()
is_default = False
if user_doc.exists:
user_data = user_doc.to_dict()
is_default = user_data.get('default_task_integration') == app_key
# Delete integration
integration_ref.delete()
# Clear default if needed
if is_default:
user_ref.update({'default_task_integration': firestore.DELETE_FIELD})
return True
def get_default_task_integration(uid: str) -> Optional[str]:
"""
Get the user's default task integration app.
Args:
uid: User ID
Returns:
App key of default integration or None
"""
user_ref = db.collection('users').document(uid)
user_doc = user_ref.get()
if user_doc.exists:
user_data = user_doc.to_dict()
return user_data.get('default_task_integration')
return None
def set_default_task_integration(uid: str, app_key: str) -> None:
"""
Set the user's default task integration app.
Args:
uid: User ID
app_key: Task integration app key to set as default
"""
user_ref = db.collection('users').document(uid)
user_ref.set({'default_task_integration': app_key}, merge=True)
# **************************************
# ******** Integrations ********
# **************************************
def get_integration(uid: str, app_key: str) -> Optional[dict]:
"""
Get a specific integration connection.
Args:
uid: User ID
app_key: Integration app key (e.g., 'google_calendar', 'whoop')
Returns:
Connection details or None if not found
"""
user_ref = db.collection('users').document(uid)
integration_ref = user_ref.collection('integrations').document(app_key)
doc = integration_ref.get()
if doc.exists:
return doc.to_dict()
return None
def set_integration(uid: str, app_key: str, data: dict) -> None:
"""
Save or update an integration connection.
Args:
uid: User ID
app_key: Integration app key (e.g., 'google_calendar', 'whoop')
data: Connection details to save
"""
user_ref = db.collection('users').document(uid)
integration_ref = user_ref.collection('integrations').document(app_key)
# Add timestamp
data['updated_at'] = datetime.now(timezone.utc)
if not integration_ref.get().exists:
data['created_at'] = datetime.now(timezone.utc)
integration_ref.set(data, merge=True)
def delete_integration(uid: str, app_key: str) -> bool:
"""
Delete an integration connection.
Args:
uid: User ID
app_key: Integration app key
Returns:
True if deleted, False if not found
"""
user_ref = db.collection('users').document(uid)
integration_ref = user_ref.collection('integrations').document(app_key)
if not integration_ref.get().exists:
return False
integration_ref.delete()
return True
# Legacy function names for backward compatibility
def get_calendar_integration(uid: str, app_key: str) -> Optional[dict]:
"""Legacy function name - use get_integration instead."""
return get_integration(uid, app_key)
def set_calendar_integration(uid: str, app_key: str, data: dict) -> None:
"""Legacy function name - use set_integration instead."""
return set_integration(uid, app_key, data)
def delete_calendar_integration(uid: str, app_key: str) -> bool:
"""Legacy function name - use delete_integration instead."""
return delete_integration(uid, app_key)
# **************************************
# ***** Transcription Preferences ******
# **************************************
def get_user_transcription_preferences(uid: str) -> dict:
"""
Get the user's transcription preferences.
Returns:
dict with 'single_language_mode' (bool), 'vocabulary' (List[str]), and 'language' (str)