-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSettingsViewController.m
More file actions
1198 lines (1033 loc) · 64.6 KB
/
Copy pathSettingsViewController.m
File metadata and controls
1198 lines (1033 loc) · 64.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
// SettingsViewController.m
// EZCompleteUI v1.4
//
// Changes from v1.3:
// - Replaced "Donate via PayPal" button and method with "Legal & Policies"
// button that opens EZPoliciesViewController (Terms / Privacy / Refund).
// - Added #import for EZPoliciesViewController.
// - donate method removed (app now has a coin store; donation button obsolete).
#import "SettingsViewController.h"
#import "MemoriesViewController.h"
#import "TextToSpeechViewController.h"
#import "ElevenLabsCloneViewController.h"
#import "SupportRequestViewController.h"
#import "LoginViewController.h"
#import "EZCoinStoreViewController.h"
#import "EZPoliciesViewController.h"
#import "EZKeyVault.h"
#import "EZAuthManager.h"
#import "EZEntitlementManager.h"
#import "helpers.h"
#import <objc/runtime.h>
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#import <SafariServices/SafariServices.h>
static const void * kEZCloneNameKey = &kEZCloneNameKey;
static const void * kEZPickerPurposeKey = &kEZPickerPurposeKey;
static NSString * const kHelperTemperatureDefaultsKey = @"helperTemperature";
// Placeholder shown in a key field once a key has been saved
static NSString * const kAPIKeyMaskedPlaceholder = @"API key saved — tap to replace";
static NSString * const kELKeyMaskedPlaceholder = @"API key saved — tap to replace";
// PayPal sandbox plan ID — replace with live Plan ID before release
static NSString * const kPayPalPlanID = @"P-1HW38522AL709604TNHUUASA";
static NSString *const kSupabaseAnonKey = @"sb_publishable_AzEVhLuIj1nSMwZvIgKw7A__Y3Ghdtl";
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - Private interface
// ─────────────────────────────────────────────────────────────────────────────
@interface SettingsViewController () <UITextFieldDelegate, UITextViewDelegate,
UIDocumentPickerDelegate,
SFSafariViewControllerDelegate>
// ── Scroll container ──────────────────────────────────────────────────────────
@property (nonatomic, strong) UIScrollView *scrollView;
// ── Subscription ──────────────────────────────────────────────────────────────
@property (nonatomic, strong) UILabel *subscriptionStatusLabel;
@property (nonatomic, strong) UILabel *coinBalanceLabel;
// ── OpenAI fields ─────────────────────────────────────────────────────────────
@property (nonatomic, strong) UITextField *apiKeyField;
@property (nonatomic, assign) BOOL apiKeyMasked;
// ── System prompt ─────────────────────────────────────────────────────────────
@property (nonatomic, strong) UITextView *systemMsgView;
@property (nonatomic, assign) CGFloat systemMsgViewHeight;
// ── Sliders ───────────────────────────────────────────────────────────────────
@property (nonatomic, strong) UISlider *tempSlider;
@property (nonatomic, strong) UISlider *helperTempSlider;
@property (nonatomic, strong) UISlider *freqSlider;
@property (nonatomic, strong) UILabel *tempLabel;
@property (nonatomic, strong) UILabel *helperTempLabel;
@property (nonatomic, strong) UILabel *freqLabel;
// ── Web search ────────────────────────────────────────────────────────────────
@property (nonatomic, strong) UITextField *webLocationField;
@property (nonatomic, strong) UISwitch *webSearchSwitch;
// ── ElevenLabs TTS ────────────────────────────────────────────────────────────
@property (nonatomic, strong) UITextField *elKeyField;
@property (nonatomic, assign) BOOL elKeyMasked;
@property (nonatomic, strong) UITextField *elVoiceField;
// ── ElevenLabs Voice Cloning ──────────────────────────────────────────────────
@property (nonatomic, strong) NSMutableArray<NSDictionary *> *clonedVoices;
@property (nonatomic, strong) UILabel *cloneStatusLabel;
// ── Sora video ────────────────────────────────────────────────────────────────
@property (nonatomic, strong) UITextField *soraModelField;
@property (nonatomic, strong) UITextField *soraSizeField;
@property (nonatomic, strong) UISlider *soraDurationSlider;
@property (nonatomic, strong) UILabel *soraDurationLabel;
@end
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - Implementation
// ─────────────────────────────────────────────────────────────────────────────
@implementation SettingsViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Settings";
self.view.backgroundColor = [UIColor systemBackgroundColor];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self
action:@selector(saveAndClose)];
self.clonedVoices = [NSMutableArray array];
[self setupUI];
[self loadSettings];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(keyboardShow:)
name:UIKeyboardWillShowNotification object:nil];
[nc addObserver:self selector:@selector(keyboardHide:)
name:UIKeyboardWillHideNotification object:nil];
[nc addObserver:self selector:@selector(keyboardShow:)
name:UIKeyboardWillChangeFrameNotification object:nil];
[nc addObserver:self selector:@selector(refreshSubscriptionDisplay)
name:@"EZSubscriptionUpdated" object:nil];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(dismissKeyboard)];
tap.cancelsTouchesInView = NO;
[self.scrollView addGestureRecognizer:tap];
EZLog(EZLogLevelInfo, @"SETTINGS", @"Settings opened");
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self refreshSubscriptionDisplay];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)dismissKeyboard {
[self.view endEditing:YES];
}
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - Keyboard handling
// ─────────────────────────────────────────────────────────────────────────────
- (void)keyboardShow:(NSNotification *)notification {
CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardFrame.size.height, 0);
self.scrollView.contentInset = insets;
self.scrollView.scrollIndicatorInsets = insets;
}
- (void)keyboardHide:(NSNotification *)notification {
self.scrollView.contentInset = UIEdgeInsetsZero;
self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - API Key field masking
// ─────────────────────────────────────────────────────────────────────────────
- (void)apiKeyFieldTapped:(UITapGestureRecognizer *)tap {
UITextField *field = (UITextField *)tap.view;
if (field == self.apiKeyField && self.apiKeyMasked) {
[self unmaskKeyField:field maskedFlag:&_apiKeyMasked];
} else if (field == self.elKeyField && self.elKeyMasked) {
[self unmaskKeyField:field maskedFlag:&_elKeyMasked];
}
}
- (void)unmaskKeyField:(UITextField *)field maskedFlag:(BOOL *)flag {
*flag = NO;
field.text = @"";
field.placeholder = @"Enter new key";
field.textColor = [UIColor labelColor];
field.backgroundColor = [UIColor systemBackgroundColor];
field.layer.borderWidth = 0;
[field becomeFirstResponder];
}
- (void)maskKeyField:(UITextField *)field placeholder:(NSString *)placeholder {
field.text = @"";
field.placeholder = placeholder;
field.textColor = [UIColor secondaryLabelColor];
}
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - UI Setup
// ─────────────────────────────────────────────────────────────────────────────
- (void)setupUI {
self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.scrollView];
CGFloat w = self.view.frame.size.width - 40;
CGFloat y = 20;
// ── App Version ──────────────────────────────────────────────────────────
NSDictionary *infoPlist = [NSBundle mainBundle].infoDictionary;
NSString *appVersion = infoPlist[@"CFBundleShortVersionString"] ?: @"?";
NSString *buildNumber = infoPlist[@"CFBundleVersion"] ?: @"?";
UILabel *versionLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, y, w, 20)];
versionLabel.text = [NSString stringWithFormat:@"EZCompleteUI v%@ (build %@)",
appVersion, buildNumber];
versionLabel.font = [UIFont systemFontOfSize:12];
versionLabel.textColor = [UIColor tertiaryLabelColor];
versionLabel.textAlignment = NSTextAlignmentCenter;
[self.scrollView addSubview:versionLabel];
y += 30;
// ── Subscription ─────────────────────────────────────────────────────────
[self addSection:@"💎 Subscription" y:&y];
self.subscriptionStatusLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, y, w, 20)];
self.subscriptionStatusLabel.font = [UIFont systemFontOfSize:13];
self.subscriptionStatusLabel.textColor = [UIColor secondaryLabelColor];
self.subscriptionStatusLabel.text = @"Loading...";
[self.scrollView addSubview:self.subscriptionStatusLabel];
y += 26;
self.coinBalanceLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, y, w, 20)];
self.coinBalanceLabel.font = [UIFont systemFontOfSize:13];
self.coinBalanceLabel.textColor = [UIColor secondaryLabelColor];
self.coinBalanceLabel.text = @"";
[self.scrollView addSubview:self.coinBalanceLabel];
y += 30;
[self addButton:@"💎 Subscribe / Manage Subscription"
color:[UIColor systemBlueColor]
action:@selector(openSubscribePage)
y:&y w:w];
[self addButton:@"🔄 Restore / Refresh Subscription"
color:[UIColor systemGreenColor]
action:@selector(refreshSubscription)
y:&y w:w];
[self addButton:@"🚪 Sign Out"
color:[UIColor systemGrayColor]
action:@selector(signOut)
y:&y w:w];
// ── OpenAI ───────────────────────────────────────────────────────────────
[self addSection:@"🤖 OpenAI" y:&y];
[self addLabel:@"API Key:" y:&y];
self.apiKeyField = [[UITextField alloc] initWithFrame:CGRectMake(20, y, w, 40)];
self.apiKeyField.borderStyle = UITextBorderStyleRoundedRect;
self.apiKeyField.placeholder = @"sk-...";
self.apiKeyField.delegate = self;
self.apiKeyField.returnKeyType = UIReturnKeyDone;
self.apiKeyField.font = [UIFont systemFontOfSize:14];
self.apiKeyField.secureTextEntry = YES;
UITapGestureRecognizer *apiTap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(apiKeyFieldTapped:)];
[self.apiKeyField addGestureRecognizer:apiTap];
[self.scrollView addSubview:self.apiKeyField];
y += 50;
// ── System Prompt ─────────────────────────────────────────────────────────
[self addLabel:@"System Message:" y:&y];
CGFloat minTextViewHeight = 80.0;
self.systemMsgView = [[UITextView alloc] initWithFrame:CGRectMake(20, y, w, minTextViewHeight)];
self.systemMsgView.font = [UIFont systemFontOfSize:14];
self.systemMsgView.delegate = self;
self.systemMsgView.layer.cornerRadius = 8;
self.systemMsgView.layer.borderWidth = 1.0;
self.systemMsgView.layer.borderColor = [UIColor systemGray4Color].CGColor;
self.systemMsgView.backgroundColor = [UIColor secondarySystemBackgroundColor];
self.systemMsgView.textContainerInset = UIEdgeInsetsMake(8, 6, 8, 6);
self.systemMsgView.scrollEnabled = NO;
self.systemMsgViewHeight = minTextViewHeight;
[self.scrollView addSubview:self.systemMsgView];
y += minTextViewHeight + 10;
// ── Sliders ───────────────────────────────────────────────────────────────
self.tempLabel = [self addLabel:@"Temperature: 0.70" y:&y];
self.tempSlider = [self addSlider:w y:&y min:0 max:2];
self.helperTempLabel = [self addLabel:@"Helper Temperature: 0.20" y:&y];
self.helperTempSlider = [self addSlider:w y:&y min:0 max:0.5f];
self.freqLabel = [self addLabel:@"Freq Penalty: 0.00" y:&y];
self.freqSlider = [self addSlider:w y:&y min:-2 max:2];
// ── Web Search ────────────────────────────────────────────────────────────
[self addSection:@"🌐 Web Search" y:&y];
[self addLabel:@"Enable web search by default:" y:&y];
self.webSearchSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(w - 30, y - 28, 51, 31)];
[self.scrollView addSubview:self.webSearchSwitch];
[self addLabel:@"Location hint (optional city):" y:&y];
self.webLocationField = [self addField:w y:&y placeholder:@"e.g. Miami, FL"];
// ── ElevenLabs TTS ────────────────────────────────────────────────────────
[self addSection:@"🎙 ElevenLabs TTS" y:&y];
[self addLabel:@"API Key:" y:&y];
self.elKeyField = [[UITextField alloc] initWithFrame:CGRectMake(20, y, w, 40)];
self.elKeyField.borderStyle = UITextBorderStyleRoundedRect;
self.elKeyField.placeholder = @"ElevenLabs API key";
self.elKeyField.delegate = self;
self.elKeyField.returnKeyType = UIReturnKeyDone;
self.elKeyField.font = [UIFont systemFontOfSize:14];
self.elKeyField.secureTextEntry = YES;
UITapGestureRecognizer *elTap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(apiKeyFieldTapped:)];
[self.elKeyField addGestureRecognizer:elTap];
[self.scrollView addSubview:self.elKeyField];
y += 50;
[self addLabel:@"Voice ID (preset or cloned):" y:&y];
self.elVoiceField = [self addField:w - 95 y:&y placeholder:@"Voice ID"];
UIButton *getVoicesBtn = [UIButton buttonWithType:UIButtonTypeSystem];
getVoicesBtn.frame = CGRectMake(w - 84, y - 50, 84, 40);
[getVoicesBtn setTitle:@"Get Voices" forState:UIControlStateNormal];
getVoicesBtn.backgroundColor = [UIColor systemTealColor];
getVoicesBtn.layer.cornerRadius = 8;
[getVoicesBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[getVoicesBtn addTarget:self action:@selector(fetchVoices)
forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:getVoicesBtn];
[self addButton:@"🔊 Open Text to Speech"
color:[UIColor systemCyanColor]
action:@selector(openTextToSpeech)
y:&y w:w];
// ── ElevenLabs Voice Cloning ──────────────────────────────────────────────
[self addSection:@"🎤 Voice Cloning (ElevenLabs)" y:&y];
[self addLabel:@"Upload an audio sample to create a custom voice clone." y:&y];
[self addButton:@"🎤 Voice Cloning & Management"
color:[UIColor systemPurpleColor]
action:@selector(openElevenLabsCloneVC)
y:&y w:w];
self.cloneStatusLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, y, w, 30)];
self.cloneStatusLabel.font = [UIFont systemFontOfSize:13];
self.cloneStatusLabel.textColor = [UIColor secondaryLabelColor];
self.cloneStatusLabel.text = @"";
[self.scrollView addSubview:self.cloneStatusLabel];
y += 35;
// ── Sora Text-to-Video ────────────────────────────────────────────────────
[self addSection:@"🎬 Sora Text-to-Video" y:&y];
[self addLabel:@"Model:" y:&y];
self.soraModelField = [self addField:w y:&y placeholder:@"sora-2"];
self.soraModelField.userInteractionEnabled = NO;
UIButton *soraModelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
soraModelBtn.frame = CGRectMake(w - 74, y - 50, 84, 40);
[soraModelBtn setTitle:@"Choose" forState:UIControlStateNormal];
[soraModelBtn addTarget:self action:@selector(pickSoraModel)
forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:soraModelBtn];
[self addLabel:@"Resolution:" y:&y];
self.soraSizeField = [self addField:w y:&y placeholder:@"1280x720"];
self.soraSizeField.userInteractionEnabled = NO;
UIButton *soraResBtn = [UIButton buttonWithType:UIButtonTypeSystem];
soraResBtn.frame = CGRectMake(w - 74, y - 50, 84, 40);
[soraResBtn setTitle:@"Choose" forState:UIControlStateNormal];
[soraResBtn addTarget:self action:@selector(pickSoraResolution)
forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:soraResBtn];
self.soraDurationLabel = [self addLabel:
@"Duration: 4s (sora-2: 4/8/12/16s • sora-2-pro: 5/10/15/20s)" y:&y];
self.soraDurationSlider = [self addSlider:w y:&y min:1 max:20];
[self.soraDurationSlider addTarget:self action:@selector(updateVideoLabels)
forControlEvents:UIControlEventValueChanged];
// ── AI Memory ─────────────────────────────────────────────────────────────
[self addSection:@"🧠 AI Memory" y:&y];
y += 8;
[self addButton:@"📖 View / Edit Memories"
color:[UIColor systemGreenColor]
action:@selector(openMemoriesViewer)
y:&y w:w];
[self addButton:@"Clear All Memories"
color:[UIColor systemOrangeColor]
action:@selector(confirmClearMemories)
y:&y w:w];
[self addButton:@"View Helper Stats"
color:[UIColor systemIndigoColor]
action:@selector(showHelperStats)
y:&y w:w];
[self addButton:@"📄 Legal & Policies"
color:[UIColor systemIndigoColor]
action:@selector(openPolicies)
y:&y w:w];
[self addButton:@"📬 Support & Feedback"
color:[UIColor systemTealColor]
action:@selector(openSupportRequest)
y:&y w:w];
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, y + 30);
}
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - Subscription
// ─────────────────────────────────────────────────────────────────────────────
- (void)refreshSubscriptionDisplay {
[[EZEntitlementManager shared] refreshBalanceWithCompletion:^(NSInteger balance) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *tier = [EZEntitlementManager shared].currentTier;
BOOL isActive = ![tier isEqualToString:@"none"] && balance >= 0;
if (isActive && ![tier isEqualToString:@"none"]) {
self.subscriptionStatusLabel.text = [NSString stringWithFormat:
@"✅ Active — %@ plan", tier.capitalizedString];
self.subscriptionStatusLabel.textColor = [UIColor systemGreenColor];
self.coinBalanceLabel.text = [NSString stringWithFormat:
@"🪙 Coin balance: %ld", (long)balance];
} else {
self.subscriptionStatusLabel.text = @"❌ No active subscription";
self.subscriptionStatusLabel.textColor = [UIColor systemRedColor];
self.coinBalanceLabel.text = @"Subscribe below to get started";
}
});
}];
}
- (void)openSubscribePage {
[self openCoinStore:NO featureName:nil];
}
- (void)openCoinStore:(BOOL)showLowCoinsWarning featureName:(NSString * _Nullable)featureName {
NSString *token = [EZAuthManager shared].accessToken;
if (!token) {
[self showAlert:@"Not logged in" message:@"Please sign in first."];
return;
}
EZCoinStoreViewController *store = [[EZCoinStoreViewController alloc] init];
store.showLowCoinsWarning = showLowCoinsWarning;
store.triggeringFeatureName = featureName;
UINavigationController *nav = [[UINavigationController alloc]
initWithRootViewController:store];
nav.modalPresentationStyle = UIModalPresentationFormSheet;
// Refresh subscription display when store closes
__weak typeof(self) weakSelf = self;
nav.presentationController.delegate = (id<UIAdaptivePresentationControllerDelegate>)weakSelf;
[self presentViewController:nav animated:YES completion:nil];
}
- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
[self refreshSubscriptionDisplay];
[[NSNotificationCenter defaultCenter]
postNotificationName:@"EZSubscriptionUpdated" object:nil];
});
}
- (void)presentationControllerDidDismiss:(UIPresentationController *)presentationController {
// Called when EZCoinStoreViewController is dismissed — refresh balance
[self refreshSubscriptionDisplay];
}
- (void)refreshSubscription {
self.subscriptionStatusLabel.text = @"Checking...";
self.subscriptionStatusLabel.textColor = [UIColor secondaryLabelColor];
[self refreshSubscriptionDisplay];
}
- (void)signOut {
UIAlertController *confirm = [UIAlertController
alertControllerWithTitle:@"Sign Out?"
message:@"You will need to sign in again to use EZCompleteUI."
preferredStyle:UIAlertControllerStyleAlert];
[confirm addAction:[UIAlertAction actionWithTitle:@"Sign Out"
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction *a) {
[[EZAuthManager shared] signOut];
[self dismissViewControllerAnimated:YES completion:^{
UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
LoginViewController *loginVC = [[LoginViewController alloc] init];
[UIView transitionWithView:window
duration:0.3
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{ window.rootViewController = loginVC; }
completion:nil];
}];
}]];
[confirm addAction:[UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:confirm animated:YES completion:nil];
}
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - UITextViewDelegate (system prompt auto-expand)
// ─────────────────────────────────────────────────────────────────────────────
- (void)textViewDidChange:(UITextView *)textView {
if (textView != self.systemMsgView) return;
[self resizeSystemMsgView];
}
- (void)resizeSystemMsgView {
CGFloat w = self.view.frame.size.width - 40;
CGFloat minH = 80.0;
CGSize sizeThatFits = [self.systemMsgView sizeThatFits:CGSizeMake(w, CGFLOAT_MAX)];
CGFloat newH = MAX(minH, sizeThatFits.height);
if (ABS(newH - self.systemMsgViewHeight) < 1.0) return;
CGFloat delta = newH - self.systemMsgViewHeight;
self.systemMsgViewHeight = newH;
CGRect tvFrame = self.systemMsgView.frame;
tvFrame.size.height = newH;
self.systemMsgView.frame = tvFrame;
CGFloat tvBottom = CGRectGetMaxY(tvFrame);
for (UIView *sub in self.scrollView.subviews) {
if (sub == self.systemMsgView) continue;
if (sub.frame.origin.y >= tvBottom - delta - 1) {
CGRect f = sub.frame;
f.origin.y += delta;
sub.frame = f;
}
}
CGSize cs = self.scrollView.contentSize;
cs.height += delta;
self.scrollView.contentSize = cs;
}
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - UI Helper Methods
// ─────────────────────────────────────────────────────────────────────────────
- (void)addSection:(NSString *)title y:(CGFloat *)y {
*y += 10;
UILabel *label = [[UILabel alloc] initWithFrame:
CGRectMake(20, *y, self.view.frame.size.width - 40, 28)];
label.text = title;
label.font = [UIFont boldSystemFontOfSize:15];
label.textColor = [UIColor systemBlueColor];
[self.scrollView addSubview:label];
*y += 34;
}
- (UILabel *)addLabel:(NSString *)text y:(CGFloat *)y {
UILabel *label = [[UILabel alloc] initWithFrame:
CGRectMake(20, *y, self.view.frame.size.width - 40, 20)];
label.text = text;
label.font = [UIFont systemFontOfSize:13];
label.textColor = [UIColor secondaryLabelColor];
label.numberOfLines = 0;
[self.scrollView addSubview:label];
*y += 22;
return label;
}
- (UITextField *)addField:(CGFloat)width y:(CGFloat *)y placeholder:(NSString *)placeholder {
UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(20, *y, width, 40)];
field.borderStyle = UITextBorderStyleRoundedRect;
field.placeholder = placeholder;
field.delegate = self;
field.returnKeyType = UIReturnKeyDone;
field.font = [UIFont systemFontOfSize:14];
[self.scrollView addSubview:field];
*y += 50;
return field;
}
- (UISlider *)addSlider:(CGFloat)width y:(CGFloat *)y min:(float)minVal max:(float)maxVal {
UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(20, *y, width, 30)];
slider.minimumValue = minVal;
slider.maximumValue = maxVal;
[slider addTarget:self action:@selector(updateLabels)
forControlEvents:UIControlEventValueChanged];
[self.scrollView addSubview:slider];
*y += 45;
return slider;
}
- (void)addButton:(NSString *)title color:(UIColor *)color action:(SEL)action
y:(CGFloat *)y w:(CGFloat)width {
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(20, *y, width, 44);
button.backgroundColor = color;
button.tintColor = [UIColor whiteColor];
button.layer.cornerRadius = 10;
[button setTitle:title forState:UIControlStateNormal];
[button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
*y += 55;
}
- (void)updateLabels {
self.tempLabel.text = [NSString stringWithFormat:@"Temperature: %.2f",
self.tempSlider.value];
self.helperTempLabel.text = [NSString stringWithFormat:@"Helper Temperature: %.2f",
self.helperTempSlider.value];
self.freqLabel.text = [NSString stringWithFormat:@"Freq Penalty: %.2f",
self.freqSlider.value];
}
- (void)updateVideoLabels {
NSString *model = self.soraModelField.text ?: @"sora-2";
BOOL isPro = [model isEqualToString:@"sora-2-pro"];
NSInteger raw = (NSInteger)self.soraDurationSlider.value;
NSArray<NSNumber *> *validDurations = isPro
? @[@5, @10, @15, @20]
: @[@4, @8, @12, @16];
NSInteger snapped = validDurations.firstObject.integerValue;
NSInteger bestDiff = NSIntegerMax;
for (NSNumber *v in validDurations) {
NSInteger diff = ABS(raw - v.integerValue);
if (diff < bestDiff) { bestDiff = diff; snapped = v.integerValue; }
}
NSString *hint = isPro ? @"(5/10/15/20s)" : @"(4/8/12/16s)";
self.soraDurationLabel.text = [NSString stringWithFormat:@"Duration: %lds %@",
(long)snapped, hint];
}
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - Sora Model / Resolution Pickers
// ─────────────────────────────────────────────────────────────────────────────
- (void)pickSoraModel {
UIAlertController *sheet = [UIAlertController
alertControllerWithTitle:@"Sora Model"
message:nil
preferredStyle:UIAlertControllerStyleActionSheet];
NSDictionary *descriptions = @{
@"sora-2": @"Fast, flexible — 4/8/12/16s",
@"sora-2-pro": @"High fidelity — 5/10/15/20s"
};
for (NSString *model in @[@"sora-2", @"sora-2-pro"]) {
NSString *title = [NSString stringWithFormat:@"%@ (%@)", model, descriptions[model]];
[sheet addAction:[UIAlertAction actionWithTitle:title
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *a) {
self.soraModelField.text = model;
[self updateVideoLabels];
}]];
}
[sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:sheet animated:YES completion:nil];
}
- (void)pickSoraResolution {
UIAlertController *sheet = [UIAlertController
alertControllerWithTitle:@"Video Size"
message:nil
preferredStyle:UIAlertControllerStyleActionSheet];
NSDictionary *descriptions = @{
@"1280x720": @"Landscape 720p (recommended)",
@"1792x1024": @"Landscape wide (cinematic)",
@"720x1280": @"Portrait 720p (social/reels)",
@"1024x1792": @"Portrait tall (stories)"
};
for (NSString *res in @[@"1280x720", @"1792x1024", @"720x1280", @"1024x1792"]) {
NSString *title = [NSString stringWithFormat:@"%@ — %@", res, descriptions[res]];
[sheet addAction:[UIAlertAction actionWithTitle:title
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *a) {
self.soraSizeField.text = res;
}]];
}
[sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:sheet animated:YES completion:nil];
}
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - ElevenLabs Voice Fetching
// ─────────────────────────────────────────────────────────────────────────────
- (NSString *)resolvedElevenLabsKey {
if (self.elKeyMasked) {
return [EZKeyVault loadKeyForIdentifier:EZVaultKeyElevenLabs] ?: @"";
}
return self.elKeyField.text ?: @"";
}
- (void)fetchVoices {
NSString *key = [self resolvedElevenLabsKey];
if (key.length == 0) return;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:@"https://api.elevenlabs.io/v1/voices"]];
[request setValue:key forHTTPHeaderField:@"xi-api-key"];
[[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!data || error) return;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:0 error:nil];
NSArray *voices = json[@"voices"];
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertController *sheet = [UIAlertController
alertControllerWithTitle:@"Select Voice"
message:nil
preferredStyle:UIAlertControllerStyleActionSheet];
for (NSDictionary *voice in voices) {
[sheet addAction:[UIAlertAction actionWithTitle:voice[@"name"]
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *a) {
self.elVoiceField.text = voice[@"voice_id"];
}]];
}
[sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel
handler:nil]];
[self presentViewController:sheet animated:YES completion:nil];
});
}] resume];
}
// ─────────────────────────────────────────────────────────────────────────────
// MARK: - ElevenLabs Voice Cloning
// ─────────────────────────────────────────────────────────────────────────────
- (void)createInstantClone {
NSString *key = [self resolvedElevenLabsKey];
if (key.length == 0) {
[self showAlert:@"ElevenLabs Key Required"
message:@"Enter your ElevenLabs API key before creating a voice clone."];
return;
}
UIAlertController *namePrompt = [UIAlertController
alertControllerWithTitle:@"Name Your Clone"
message:@"Enter a display name for this voice."
preferredStyle:UIAlertControllerStyleAlert];
[namePrompt addTextFieldWithConfigurationHandler:^(UITextField *tf) {
tf.placeholder = @"e.g. My Voice";
}];
[namePrompt addAction:[UIAlertAction actionWithTitle:@"Next"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *a) {
NSString *name = namePrompt.textFields.firstObject.text;
if (!name.length) name = @"My Clone";
[self presentAudioPickerForCloneName:name];
}]];
[namePrompt addAction:[UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:namePrompt animated:YES completion:nil];
}
- (void)presentAudioPickerForCloneName:(NSString *)cloneName {
objc_setAssociatedObject(self, kEZCloneNameKey, cloneName, OBJC_ASSOCIATION_COPY_NONATOMIC);
NSArray *audioTypes = @[
UTTypeAudio, UTTypeMP3, UTTypeMPEG4Audio,
[UTType typeWithIdentifier:@"public.ogg-audio"],
[UTType typeWithIdentifier:@"com.microsoft.waveform-audio"]
];
UIDocumentPickerViewController *picker = [[UIDocumentPickerViewController alloc]
initForOpeningContentTypes:audioTypes asCopy:YES];
picker.delegate = self;
objc_setAssociatedObject(picker, kEZPickerPurposeKey,
@"voiceClone", OBJC_ASSOCIATION_COPY_NONATOMIC);
[self presentViewController:picker animated:YES completion:nil];
}
- (void)documentPicker:(UIDocumentPickerViewController *)controller
didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
NSString *purpose = objc_getAssociatedObject(controller, kEZPickerPurposeKey);
if (![purpose isEqualToString:@"voiceClone"]) return;
NSURL *audioFile = urls.firstObject;
if (!audioFile) return;
NSString *cloneName = objc_getAssociatedObject(self, kEZCloneNameKey) ?: @"My Clone";
[self updateCloneStatus:@"Uploading audio sample..."];
[self uploadAudioForClone:cloneName fileURL:audioFile];
}
- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
[self updateCloneStatus:@""];
}
- (void)uploadAudioForClone:(NSString *)cloneName fileURL:(NSURL *)fileURL {
NSData *audioData = [NSData dataWithContentsOfURL:fileURL];
if (!audioData) {
[self updateCloneStatus:@"Error: could not read audio file."];
return;
}
NSString *elKey = [self resolvedElevenLabsKey];
NSString *boundary = [NSString stringWithFormat:@"Boundary-%@",
[[NSUUID UUID] UUIDString]];
NSURL *cloneURL = [NSURL URLWithString:@"https://api.elevenlabs.io/v1/voices/add"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:cloneURL];
request.HTTPMethod = @"POST";
request.timeoutInterval = 120;
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]
forHTTPHeaderField:@"Content-Type"];
[request setValue:elKey forHTTPHeaderField:@"xi-api-key"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"name\"\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[cloneName dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"description\"\r\n\r\n"
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Created via EZCompleteUI" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:
@"Content-Disposition: form-data; name=\"files\"; filename=\"%@\"\r\n",
fileURL.lastPathComponent] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: audio/mpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:audioData];
[body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary]
dataUsingEncoding:NSUTF8StringEncoding]];
request.HTTPBody = body;
[[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
[self updateCloneStatus:@"Upload failed — check your connection."];
return;
}
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:0 error:nil];
NSString *voiceID = json[@"voice_id"];
id detailObj = json[@"detail"];
NSString *errorMsg = @"";
if ([detailObj isKindOfClass:[NSString class]]) {
errorMsg = detailObj;
} else if ([detailObj isKindOfClass:[NSArray class]]) {
NSDictionary *first = [detailObj firstObject];
if ([first isKindOfClass:[NSDictionary class]] && first[@"msg"]) {
errorMsg = first[@"msg"];
} else {
errorMsg = @"Invalid file or parameters.";
}
} else if (json[@"message"]) {
errorMsg = json[@"message"];
}
if ([voiceID isKindOfClass:[NSString class]] && voiceID.length > 0) {
dispatch_async(dispatch_get_main_queue(), ^{
self.elVoiceField.text = voiceID;
[self updateCloneStatus:[NSString stringWithFormat:
@"✅ Clone '%@' created!", cloneName]];
});
} else {
NSString *finalStatus = (errorMsg.length > 0)
? [NSString stringWithFormat:@"Failed: %@", errorMsg]
: @"Clone creation failed.";
[self updateCloneStatus:finalStatus];
}
}] resume];
}
- (void)updateCloneStatus:(NSString *)statusMessage {
dispatch_async(dispatch_get_main_queue(), ^{
self.cloneStatusLabel.text = statusMessage;
});
}
- (void)showClonedVoices {
NSString *key = [self resolvedElevenLabsKey];
if (key.length == 0) {
[self showAlert:@"ElevenLabs Key Required"
message:@"Enter your ElevenLabs API key first."];
return;
}
[self updateCloneStatus:@"Loading cloned voices..."];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:@"https://api.elevenlabs.io/v1/voices"]];
[request setValue:key forHTTPHeaderField:@"xi-api-key"];
[[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!data || error) {
[self updateCloneStatus:@"Failed to load voices."];
return;
}
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:0 error:nil];
NSArray *voices = json[@"voices"];
NSMutableArray<NSDictionary *> *cloned = [NSMutableArray array];
for (NSDictionary *voice in voices) {
if ([[voice[@"category"] description] isEqualToString:@"cloned"]) {
[cloned addObject:voice];
}
}
dispatch_async(dispatch_get_main_queue(), ^{
[self updateCloneStatus:@""];
if (cloned.count == 0) {
[self showAlert:@"No Cloned Voices"
message:@"You haven't created any voice clones yet."];
return;
}
UIAlertController *sheet = [UIAlertController
alertControllerWithTitle:@"My Cloned Voices"
message:@"Tap a voice to select it, or swipe to delete."
preferredStyle:UIAlertControllerStyleActionSheet];
for (NSDictionary *v in cloned) {
[sheet addAction:[UIAlertAction actionWithTitle:v[@"name"]
style:UIAlertActionStyleDefault
handler:^(UIAlertAction *a) {
self.elVoiceField.text = v[@"voice_id"];
}]];
}
[sheet addAction:[UIAlertAction actionWithTitle:@"🗑 Delete a Clone..."
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction *a) {
[self showDeleteCloneSheet:cloned];
}]];
[sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:sheet animated:YES completion:nil];
});
}] resume];
}
- (void)showDeleteCloneSheet:(NSArray<NSDictionary *> *)voices {
UIAlertController *sheet = [UIAlertController
alertControllerWithTitle:@"Delete Voice Clone"
message:@"This permanently deletes the voice from ElevenLabs."
preferredStyle:UIAlertControllerStyleActionSheet];
for (NSDictionary *voice in voices) {
NSString *name = voice[@"name"] ?: @"Unnamed";
NSString *voiceID = voice[@"voice_id"];
[sheet addAction:[UIAlertAction actionWithTitle:name
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction *a) {
[self confirmDeleteVoice:voiceID name:name];
}]];
}
[sheet addAction:[UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:sheet animated:YES completion:nil];
}
- (void)confirmDeleteVoice:(NSString *)voiceID name:(NSString *)voiceName {
UIAlertController *confirm = [UIAlertController
alertControllerWithTitle:[NSString stringWithFormat:@"Delete \"%@\"?", voiceName]
message:@"This cannot be undone."
preferredStyle:UIAlertControllerStyleAlert];
[confirm addAction:[UIAlertAction actionWithTitle:@"Delete"
style:UIAlertActionStyleDestructive
handler:^(UIAlertAction *a) {
[self deleteVoiceFromAPI:voiceID name:voiceName];
}]];
[confirm addAction:[UIAlertAction actionWithTitle:@"Cancel"
style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:confirm animated:YES completion:nil];
}
- (void)deleteVoiceFromAPI:(NSString *)voiceID name:(NSString *)voiceName {
NSString *urlString = [NSString stringWithFormat:
@"https://api.elevenlabs.io/v1/voices/%@", voiceID];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:urlString]];
request.HTTPMethod = @"DELETE";
[request setValue:[self resolvedElevenLabsKey] forHTTPHeaderField:@"xi-api-key"];
EZLogf(EZLogLevelInfo, @"SETTINGS", @"Deleting voice: %@ (%@)", voiceName, voiceID);
[self updateCloneStatus:[NSString stringWithFormat:@"Deleting %@...", voiceName]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *http = (NSHTTPURLResponse *)response;
if (http.statusCode == 200 || http.statusCode == 204) {
dispatch_async(dispatch_get_main_queue(), ^{
if ([self.elVoiceField.text isEqualToString:voiceID]) {
self.elVoiceField.text = @"";
}