This repository was archived by the owner on Sep 24, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 272
Expand file tree
/
Copy pathIRCClient.m
More file actions
13297 lines (10073 loc) · 340 KB
/
IRCClient.m
File metadata and controls
13297 lines (10073 loc) · 340 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
/* *********************************************************************
* _____ _ _
* |_ _|____ _| |_ _ _ __ _| |
* | |/ _ \ \/ / __| | | |/ _` | |
* | | __/> <| |_| |_| | (_| | |
* |_|\___/_/\_\\__|\__,_|\__,_|_|
*
* * Copyright (c) 2008 - 2010 Satoshi Nakagawa <psychs AT limechat DOT net>
* * Copyright (c) 2010 - 2020 Codeux Software, LLC & respective contributors.
* Please see Acknowledgements.pdf for additional information.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Textual, "Codeux Software, LLC", nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*********************************************************************** */
/* A portion of this source file contains copyrighted work derived from one or more
3rd-party, open source projects. The use of this work is hereby acknowledged. */
/* This source file contains work that originated from the Chat Core
framework of the Colloquy project. The source in question is in relation
to the handling of SASL authentication requests. The license of the
Chat Core project is as follows:
This document can be found mirrored at the author's website:
<http://colloquy.info/project/browser/trunk/Resources/BSD%20License.txt>
No actual copyright is presented in the license file or the actual
source file in which this work was obtained so the work is assumed to
be Copyright © 2000 - 2012 the Colloquy IRC Client
------- License -------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import <objc/message.h>
#import "NSObjectHelperPrivate.h"
#import "NSStringHelper.h"
#import "GCDAsyncSocketExtensions.h"
#import "TPCApplicationInfo.h"
#import "TPCPathInfo.h"
#import "TPCPreferencesLocalPrivate.h"
#import "TPCPreferencesUserDefaults.h"
#import "TPCResourceManager.h"
#import "TPCThemeController.h"
#import "TPCTheme.h"
#import "THOPluginDispatcherPrivate.h"
#import "THOPluginManagerPrivate.h"
#import "THOPluginProtocol.h"
#import "TLOEncryptionManagerPrivate.h"
#import "TLOFileLoggerPrivate.h"
#import "TLOInputHistoryPrivate.h"
#import "TLOLocalization.h"
#import "TLONotificationControllerPrivate.h"
#import "TLOpenLink.h"
#import "TLOSoundPlayer.h"
#import "TLOSpeechSynthesizerPrivate.h"
#import "TLOSpokenNotificationPrivate.h"
#import "TLOTimer.h"
#import "TXGlobalModelsPrivate.h"
#import "TXMasterControllerPrivate.h"
#import "TXMenuControllerPrivate.h"
#import "TXWindowControllerPrivate.h"
#import "TVCDockIconPrivate.h"
#import "TVCLogControllerPrivate.h"
#import "TVCLogControllerInlineMediaServicePrivate.h"
#import "TVCLogControllerOperationQueuePrivate.h"
#import "TVCLogRenderer.h"
#import "TVCLogViewPrivate.h"
#import "TVCMainWindowPrivate.h"
#import "TVCMainWindowTextViewPrivate.h"
#import "TVCServerListPrivate.h"
#import "TDCAlert.h"
#import "TDCChannelBanListSheetPrivate.h"
#import "TDCFileTransferDialogPrivate.h"
#import "TDCFileTransferDialogTransferControllerPrivate.h"
#import "TDCServerChannelListDialogPrivate.h"
#import "TDCServerHighlightListSheetPrivate.h"
#import "IRC.h"
#import "IRCAddressBook.h"
#import "IRCAddressBookMatchCachePrivate.h"
#import "IRCAddressBookUserTrackingPrivate.h"
#import "IRCChannelConfig.h"
#import "IRCChannelModePrivate.h"
#import "IRCChannelUserPrivate.h"
#import "IRCChannelPrivate.h"
#import "IRCClientConfigPrivate.h"
#import "IRCClientRequestedCommandsPrivate.h"
#import "IRCColorFormatPrivate.h"
#import "IRCConnectionPrivate.h"
#import "IRCConnectionConfig.h"
#import "IRCConnectionErrors.h"
#import "IRCExtrasPrivate.h"
#import "IRCHighlightLogEntryPrivate.h"
#import "IRCHighlightMatchCondition.h"
#import "IRCISupportInfoPrivate.h"
#import "IRCMessagePrivate.h"
#import "IRCMessageBatchPrivate.h"
#import "IRCModeInfo.h"
#import "IRCNumerics.h"
#import "IRCSendingMessage.h"
#import "IRCServerPrivate.h"
#import "IRCTimerCommandPrivate.h"
#import "IRCTreeItemPrivate.h"
#import "IRCUserPrivate.h"
#import "IRCUserRelationsPrivate.h"
#import "IRCWorldPrivate.h"
#import "IRCClientPrivate.h"
NS_ASSUME_NONNULL_BEGIN
#define _autojoinDelayedWarningInterval 90 // max delay after identification is 10 so keep this above that
#define _autojoinDelayedWarningMaxCount 3
#define _isonCheckInterval 30
#define _pingInterval 270
#define _pongCheckInterval 30
#define _reconnectInterval 20
#define _retryInterval 240
#define _timeoutInterval 360
#define _whoCheckInterval 120
NSString * const IRCClientConfigurationWasUpdatedNotification = @"IRCClientConfigurationWasUpdatedNotification";
NSString * const IRCClientChannelListWasModifiedNotification = @"IRCClientChannelListWasModifiedNotification";
NSString * const IRCClientWillConnectNotification = @"IRCClientWillConnectNotification";
NSString * const IRCClientDidConnectNotification = @"IRCClientDidConnectNotification";
NSString * const IRCClientWillSendQuitNotification = @"IRCClientWillSendQuitNotification";
NSString * const IRCClientWillDisconnectNotification = @"IRCClientWillDisconnectNotification";
NSString * const IRCClientDidDisconnectNotification = @"IRCClientDidDisconnectNotification";
NSString * const IRCClientUserNicknameChangedNotification = @"IRCClientUserNicknameChangedNotification";
@interface IRCClient ()
// Properties that are public in IRCClient.h
@property (nonatomic, copy, readwrite) IRCClientConfig *config;
@property (nonatomic, copy, readwrite, nullable) IRCServer *server;
@property (nonatomic, strong, readwrite) IRCISupportInfo *supportInfo;
@property (nonatomic, assign, readwrite) BOOL isAutojoined;
@property (nonatomic, assign, readwrite) BOOL isAutojoining;
@property (nonatomic, assign, readwrite) BOOL isConnecting;
@property (nonatomic, assign, readwrite) BOOL isConnected;
@property (nonatomic, assign, readwrite) BOOL isConnectedToZNC;
@property (nonatomic, assign, readwrite) BOOL isLoggedIn;
@property (nonatomic, assign, readwrite) BOOL isQuitting;
@property (nonatomic, assign, readwrite) BOOL isDisconnecting;
@property (nonatomic, assign, readwrite) BOOL isReconnecting;
@property (nonatomic, assign, readwrite) BOOL isSecured;
@property (nonatomic, assign, readwrite) BOOL userIsAway;
@property (nonatomic, assign, readwrite) BOOL userIsIRCop;
@property (nonatomic, assign, readwrite) BOOL userIsIdentifiedWithNickServ;
@property (nonatomic, assign, readwrite) BOOL isWaitingForNickServ;
@property (nonatomic, assign, readwrite) BOOL serverHasNickServ;
@property (nonatomic, assign, readwrite) NSTimeInterval lastMessageReceived;
@property (nonatomic, assign, readwrite) NSTimeInterval lastMessageServerTime;
@property (nonatomic, assign, readwrite) ClientIRCv3SupportedCapability capabilities;
@property (nonatomic, copy, readwrite) NSArray<IRCHighlightLogEntry *> *cachedHighlights;
@property (nonatomic, copy, readwrite, nullable) NSString *userHostmask;
@property (nonatomic, copy, readwrite) NSString *userNickname;
@property (nonatomic, copy, readwrite) NSString *serverAddress;
@property (nonatomic, copy, readwrite, nullable) NSString *preAwayUserNickname;
@property (nonatomic, assign, readwrite) NSUInteger logFileSessionCount;
// Properties private
@property (nonatomic, assign) BOOL configurationIsStale;
@property (nonatomic, strong, nullable) IRCConnection *socket;
@property (nonatomic, strong) IRCMessageBatchMessageContainer *batchMessages;
@property (nonatomic, strong, nullable) TLOFileLogger *logFile;
@property (nonatomic, strong) TLOTimer *autojoinTimer;
@property (nonatomic, strong) TLOTimer *autojoinNextJoinTimer;
@property (nonatomic, strong) TLOTimer *autojoinDelayedWarningTimer;
@property (nonatomic, strong) TLOTimer *isonTimer;
@property (nonatomic, strong) TLOTimer *pongTimer;
@property (nonatomic, strong) TLOTimer *reconnectTimer;
@property (nonatomic, strong) TLOTimer *retryTimer;
@property (nonatomic, strong) TLOTimer *whoTimer;
@property (nonatomic, assign) BOOL capabilityNegotiationIsPaused;
@property (nonatomic, assign) BOOL invokingISONCommandForFirstTime;
@property (nonatomic, assign) BOOL invokingBatchedISONCommand;
@property (nonatomic, assign) BOOL isTerminating; // Is being destroyed
@property (nonatomic, assign) BOOL inWhoisResponse;
@property (nonatomic, assign) BOOL inWhowasResponse;
@property (nonatomic, assign) BOOL reconnectEnabled;
@property (nonatomic, assign) BOOL reconnectEnabledBecauseOfSleepMode;
@property (nonatomic, assign) BOOL timeoutWarningShownToUser;
@property (nonatomic, assign) BOOL zncBouncerIsSendingCertificateInfo;
@property (nonatomic, assign) BOOL zncBouncerIsPlayingBackHistory;
@property (nonatomic, strong) NSMutableArray<NSNumber *> *capabilitiesPending;
@property (nonatomic, assign) NSUInteger connectDelay;
@property (nonatomic, assign) NSUInteger lastServerSelected;
@property (nonatomic, assign) NSUInteger lastWhoRequestChannelListIndex;
@property (nonatomic, assign) NSUInteger successfulConnects;
@property (nonatomic, assign) NSUInteger tryingNicknameNumber;
@property (nonatomic, assign) NSUInteger autojoinDelayedWarningCount;
@property (nonatomic, copy, nullable) NSString *tryingNicknameSentNickname;
@property (nonatomic, strong) NSMutableArray<IRCChannel *> *channelListPrivate;
@property (nonatomic, strong) NSMutableArray<NSString *> *onlineNicknames;
@property (nonatomic, strong, nullable) NSMutableArray<IRCChannel *> *channelsToAutojoin;
@property (nonatomic, strong) IRCAddressBookMatchCache *addressBookMatchCache;
@property (nonatomic, strong) IRCAddressBookUserTrackingContainer *trackedUsers;
@property (nonatomic, strong) IRCClientRequestedCommands *requestedCommands;
@property (nonatomic, strong) NSMutableDictionary<NSString *, IRCTimedCommand *> *timedCommands;
@property (nonatomic, strong) NSMutableDictionary<NSString *, IRCUser *> *userListPrivate;
@property (nonatomic, strong, nullable) NSMutableString *zncBouncerCertificateChainDataMutable;
@property (nonatomic, copy, nullable) NSString *temporaryServerAddressOverride;
@property (nonatomic, assign) uint16_t temporaryServerPortOverride;
@property (readonly) BOOL isBrokenIRCd_aka_Twitch;
@property (readonly) BOOL monitorAwayStatus;
@property (readonly) BOOL supportsAdvancedTracking;
@property (readonly, copy) NSArray<NSString *> *nickServSupportedNeedIdentificationTokens;
@property (readonly, copy) NSArray<NSString *> *nickServSupportedSuccessfulIdentificationTokens;
@property (nonatomic, strong, nullable) IRCChannel *rawDataLogQuery;
@property (nonatomic, strong, nullable) IRCChannel *hiddenCommandResponsesQuery;
@end
@implementation IRCClient
#pragma mark -
#pragma mark Initialization
- (instancetype)init
{
[self doesNotRecognizeSelector:_cmd];
return nil;
}
- (instancetype)initWithConfigDictionary:(NSDictionary<NSString *, id> *)dic
{
NSParameterAssert(dic != nil);
IRCClientConfig *config = [[IRCClientConfig alloc] initWithDictionary:dic];
return [self initWithConfig:config];
}
- (instancetype)initWithConfig:(IRCClientConfig *)config
{
NSParameterAssert(config != nil);
if ((self = [super init])) {
self.config = config;
[self writePasswordsToKeychain];
[self prepareInitialState];
return self;
}
return nil;
}
- (void)prepareInitialState
{
self.batchMessages = [IRCMessageBatchMessageContainer new];
self.supportInfo = [[IRCISupportInfo alloc] initWithClient:self];
self.connectType = IRCClientConnectModeNormal;
self.disconnectType = IRCClientDisconnectModeNormal;
self.cachedHighlights = @[];
self.capabilitiesPending = [NSMutableArray array];
self.channelListPrivate = [NSMutableArray array];
self.timedCommands = [NSMutableDictionary dictionary];
self.userListPrivate = [NSMutableDictionary dictionary];
self.addressBookMatchCache = [[IRCAddressBookMatchCache alloc] initWithClient:self];
self.trackedUsers = [[IRCAddressBookUserTrackingContainer alloc] initWithClient:self];
self.onlineNicknames = [NSMutableArray array];
self.requestedCommands = [IRCClientRequestedCommands new];
self.lastMessageServerTime = self.config.lastMessageServerTime;
self.lastServerSelected = NSNotFound;
self.autojoinTimer =
[TLOTimer timerWithActionBlock:^(TLOTimer *sender) {
[self onAutojoinTimer];
}];
self.autojoinNextJoinTimer =
[TLOTimer timerWithActionBlock:^(TLOTimer *sender) {
[self onAutojoinNextJoinTimer];
}];
self.autojoinDelayedWarningTimer =
[TLOTimer timerWithActionBlock:^(TLOTimer *sender) {
[self onAutojoinDelayedWarningTimer];
}];
self.isonTimer =
[TLOTimer timerWithActionBlock:^(TLOTimer *sender) {
[self onISONTimer];
}];
self.reconnectTimer =
[TLOTimer timerWithActionBlock:^(TLOTimer *sender) {
[self onReconnectTimer];
}];
self.retryTimer =
[TLOTimer timerWithActionBlock:^(TLOTimer *sender) {
[self onRetryTimer];
}];
self.pongTimer =
[TLOTimer timerWithActionBlock:^(TLOTimer *sender) {
[self onPongTimer];
}];
self.whoTimer =
[TLOTimer timerWithActionBlock:^(TLOTimer *sender) {
[self onWhoTimer];
}];
[RZNotificationCenter() addObserver:self selector:@selector(willDestroyChannel:) name:IRCWorldWillDestroyChannelNotification object:nil];
}
- (void)dealloc
{
[RZNotificationCenter() removeObserver:self];
[self.autojoinTimer stop];
[self.autojoinNextJoinTimer stop];
[self.autojoinDelayedWarningTimer stop];
[self.isonTimer stop];
[self.pongTimer stop];
[self.reconnectTimer stop];
[self.retryTimer stop];
[self.whoTimer stop];
self.autojoinTimer = nil;
self.autojoinNextJoinTimer = nil;
self.autojoinDelayedWarningTimer = nil;
self.isonTimer = nil;
self.pongTimer = nil;
self.reconnectTimer = nil;
self.retryTimer = nil;
self.whoTimer = nil;
self.addressBookMatchCache = nil;
self.batchMessages = nil;
self.cachedHighlights = nil;
self.channelListPrivate = nil;
self.channelsToAutojoin = nil;
self.logFile = nil;
self.socket = nil;
self.supportInfo = nil;
self.timedCommands = nil;
self.trackedUsers = nil;
self.requestedCommands = nil;
self.userListPrivate = nil;
[self cancelPerformRequests];
}
- (void)updateConfig:(IRCClientConfig *)config
{
[self updateConfig:config updateSelection:YES];
}
- (void)updateConfig:(IRCClientConfig *)config updateSelection:(BOOL)updateSelection
{
NSParameterAssert(config != nil);
if (self.isTerminating) {
return;
}
IRCClientConfig *currentConfig = self.config;
if ([currentConfig isEqual:config]) {
return;
}
if ([currentConfig.uniqueIdentifier isEqualToString:config.uniqueIdentifier] == NO) {
LogToConsoleError("Tried to load configuration for incorrect client");
return;
}
self.config = config;
/* Update channel list */
{
NSMutableArray<IRCChannel *> *channelListOld = [self.channelList mutableCopy];
NSMutableArray<IRCChannel *> *channelListNew = [NSMutableArray array];
NSMutableArray<NSString *> *channelListNewNames = [NSMutableArray array];
NSArray *channelConfigurations = self.config.channelList;
for (IRCChannelConfig *channelConfig in channelConfigurations) {
/* Block duplicate channel names by maintaining array of names */
NSString *channelName = channelConfig.channelName;
if ([channelListNewNames containsObject:channelName] == NO) {
[channelListNewNames addObject:channelName];
} else {
continue;
}
/* Check whether the channel exists in the current list of channels */
/* If it does not exist, then create it. Otherwise, update it. */
IRCChannel *channel = [self findChannel:channelConfig.channelName inList:channelListOld];
if (channel == nil) {
channel = [worldController() createChannelWithConfig:channelConfig onClient:self add:NO adjust:NO reload:NO];
} else {
[channel updateConfig:channelConfig fireChangedNotification:NO updateStoredChannelList:NO];
[channelListOld removeObjectIdenticalTo:channel];
}
[channelListNew addObject:channel];
}
/* Any channels left in the old array can be destroyed
or if they are not a channel, then they can be reinserted
because we do not care about private messages being updated
above so they must be reinserted here. */
for (IRCChannel *channel in channelListOld) {
if (channel.isChannel == NO) {
[channelListNew addObject:channel];
} else {
[worldController() destroyChannel:channel reload:NO];
}
}
/* Save updated channel list then safe its contents */
self.channelList = channelListNew;
}
/* Update server list */
{
/* To update the server list, we first make a map of all existing
servers in a dictionary with the key as the identifier and the
object is the server itself. */
NSArray *serverListOld = currentConfig.serverList;
NSMutableDictionary<NSString *, IRCServer *> *serverListOldMap =
[[NSMutableDictionary alloc] initWithCapacity:serverListOld.count];
for (IRCServer *server in serverListOld) {
serverListOldMap[server.uniqueIdentifier] = server;
}
/* We then make a map of the new server list */
NSArray *serverListNew = self.config.serverList;
NSMutableDictionary<NSString *, IRCServer *> *serverListNewMap =
[[NSMutableDictionary alloc] initWithCapacity:serverListNew.count];
for (IRCServer *server in serverListNew) {
serverListNewMap[server.uniqueIdentifier] = server;
}
/* Record information about the current server (if any). */
IRCServer *serverInUse = self.server;
NSString *uniqueIdentifierInUse = serverInUse.uniqueIdentifier;
/* Enumerate old server list */
/* If an old server no longer appears in the new list of identifiers,
then we destroy its keychain items. If the server is the active server,
then we mark the keychain items to be destroyed later, incase they
need to be reused by IRCClient. */
[serverListOldMap enumerateKeysAndObjectsUsingBlock:^(NSString *uniqueIdentifier, IRCServer *server, BOOL *stop) {
if ([serverListNewMap containsKey:uniqueIdentifier]) {
return;
}
if ([uniqueIdentifier isEqualToString:uniqueIdentifierInUse]) {
serverInUse.destroyKeychainItemsDuringDealloc = YES;
} else {
[server destroyServerPasswordKeychainItem];
}
}];
/* Enumerate new server list */
/* All servers in the new server list have their keychain item written. */
if (serverListNew.count == 0) {
self.lastServerSelected = NSNotFound;
} else {
[serverListNewMap enumerateKeysAndObjectsUsingBlock:^(NSString *uniqueIdentifier, IRCServer *server, BOOL *stop) {
[server writeServerPasswordToKeychain];
}];
}
}
/* -reloadItem will drop the views and reload them. */
/* We need to remember the selection because of this. */
if (updateSelection) {
[self reloadServerListItems];
}
/* Update navigation list */
[menuController() populateNavigationChannelList];
/* Write passwords to keychain */
[self writePasswordsToKeychain];
[self destroyServerPasswordKeychainItemAfterMigration];
/* Update main window title */
[mainWindow() updateTitleFor:self];
/* Rebuild list of users that are ignored and/or tracked */
[self clearAddressBookCache];
[self populateISONTrackedUsersList];
/* Post notification */
[RZNotificationCenter() postNotificationName:IRCClientConfigurationWasUpdatedNotification object:self];
}
- (void)reloadServerListItems
{
mainWindow().ignoreOutlineViewSelectionChanges = YES;
[mainWindowServerList() beginUpdates];
[mainWindowServerList() reloadItem:self reloadChildren:YES];
[mainWindowServerList() endUpdates];
[mainWindow() adjustSelection];
mainWindow().ignoreOutlineViewSelectionChanges = NO;
}
- (void)writePasswordsToKeychain
{
[self.config writeNicknamePasswordToKeychain];
[self.config writeProxyPasswordToKeychain];
}
- (void)destroyServerPasswordKeychainItemAfterMigration
{
[self.config destroyServerPasswordKeychainItemAfterMigration];
}
- (void)updateStoredConfiguration
{
if (self.configurationIsStale == NO) {
return;
}
IRCClientConfigMutable *configMutable = [self.config mutableCopy];
configMutable.lastMessageServerTime = self.lastMessageServerTime;
configMutable.sidebarItemExpanded = self.sidebarItemIsExpanded;
self.config = configMutable;
}
- (void)updateStoredChannelList
{
/* Rebuild list of channel configurations */
NSMutableArray<IRCChannelConfig *> *channelList = [NSMutableArray array];
for (IRCChannel *channel in self.channelList) {
if (channel.isUtility) {
continue;
}
if (channel.isChannel == NO && [TPCPreferences rememberServerListQueryStates] == NO) {
continue;
}
[channelList addObject:channel.config];
}
/* Save list */
IRCClientConfigMutable *mutableConfig = [self.config mutableCopy];
mutableConfig.channelList = channelList;
self.config = mutableConfig;
/* Post notification */
[RZNotificationCenter() postNotificationName:IRCClientChannelListWasModifiedNotification object:self];
}
- (NSDictionary<NSString *, id> *)configurationDictionary
{
[self updateStoredConfiguration];
return [self.config dictionaryValue];
}
- (void)prepareForApplicationTermination
{
self.isTerminating = YES;
LogToConsoleTerminationProgress("Preparing client: <%{public}@>", self.uniqueIdentifier);
LogToConsoleTerminationProgress("[%{public}@] Closing dialogs", self.uniqueIdentifier);
[self closeDialogs];
if (self.isConnecting || self.isConnected) {
LogToConsoleTerminationProgress("[%{public}@] Performing disconnect", self.uniqueIdentifier);
__weak IRCClient *weakSelf = self;
self.disconnectCallback = ^{
[weakSelf prepareForApplicationTerminationPostflight];
};
[self quit];
return;
}
[self prepareForApplicationTerminationPostflight];
}
- (void)prepareForApplicationTerminationPostflight
{
LogToConsoleTerminationProgress("[%{public}@] Closing log file", self.uniqueIdentifier);
[self closeLogFile];
LogToConsoleTerminationProgress("[%{public}@] Removing unspoken messages from speech synthesizer", self.uniqueIdentifier);
[self clearEventsToSpeak];
LogToConsoleTerminationProgress("[%{public}@] Emptying Address Book cache", self.uniqueIdentifier);
[self clearAddressBookCache];
LogToConsoleTerminationProgress("[%{public}@] Removing all tracked users", self.uniqueIdentifier);
[self clearTrackedUsers];
LogToConsoleTerminationProgress("[%{public}@] Preparing channels: %{public}ld", self.uniqueIdentifier, self.channelCount);
for (IRCChannel *c in self.channelList) {
[c prepareForApplicationTermination];
}
LogToConsoleTerminationProgress("[%{public}@] Preparing view controller: <%{public}@>",
self.uniqueIdentifier, self.viewController.uniqueIdentifier);
[self.viewController prepareForApplicationTermination];
LogToConsoleTerminationProgress("[%{public}@] Decrementing client count", self.uniqueIdentifier);
masterController().terminatingClientCount -= 1;
}
- (void)prepareForPermanentDestruction
{
self.isTerminating = YES;
// [self disconnect]; // Disconnect is called by IRCWorld for us
[self closeDialogs];
[self closeLogFile];
[self clearEventsToSpeak];
[self clearAddressBookCache];
[self clearTrackedUsers];
[self.config destroyNicknamePasswordKeychainItem];
[self.config destroyProxyPasswordKeychainItem];
[self destroyServerPasswordsKeychainItems];
for (IRCChannel *c in self.channelList) {
[c prepareForPermanentDestruction];
}
[[mainWindow() inputHistoryManager] destroy:self];
[self.viewController prepareForPermanentDestruction];
}
- (void)closeDialogs
{
TDCServerChannelListDialog *channelListDialog = [self channelListDialog];
if (channelListDialog) {
[channelListDialog close];
}
NSArray *openWindows =
[windowController() windowsFromWindowList:@[@"TDCChannelInviteSheet",
@"TDCServerChangeNicknameSheet",
@"TDCServerHighlightListSheet",
@"TDCServerPropertiesSheet"]];
for (TDCSheetBase <TDCClientPrototype> *windowObject in openWindows) {
if ([windowObject.clientId isEqualToString:self.uniqueIdentifier]) {
[windowObject close];
}
}
}
- (void)preferencesChanged
{
for (IRCChannel *c in self.channelList) {
[c preferencesChanged];
}
if (self.monitorAwayStatus == NO) {
[self resetAwayStatusForUsers];
}
}
- (void)willDestroyChannel:(NSNotification *)notification
{
IRCChannel *channel = notification.object;
if (channel.associatedClient != self) {
return;
}
[self zncPlaybackClearChannel:channel];
if (self.hiddenCommandResponsesQuery == channel) {
self.hiddenCommandResponsesQuery = channel;
}
if (self.rawDataLogQuery == channel) {
self.rawDataLogQuery = nil;
}
}
- (id)copyWithZone:(nullable NSZone *)zone
{
/* Implement this method to allow client to be
used as a dictionary key. */
return self;
}
#pragma mark -
#pragma mark Servers
- (void)enumerateServers:(void (NS_NOESCAPE ^)(IRCServer *server, NSUInteger index, BOOL *stop))block
{
[self.config.serverList enumerateObjectsUsingBlock:block];
}
- (void)writeServerPasswordsToKeychain
{
[self enumerateServers:^(IRCServer *server, NSUInteger index, BOOL *stop) {
[server writeServerPasswordToKeychain];
}];
}
- (void)destroyServerPasswordsKeychainItems
{
[self enumerateServers:^(IRCServer *server, NSUInteger index, BOOL *stop) {
[server destroyServerPasswordKeychainItem];
}];
}
#pragma mark -
#pragma mark Properties
- (NSString *)description
{
return [NSString stringWithFormat:@"<IRCClient [%@]: %@>", self.networkNameAlt, self.serverAddress];
}
- (NSString *)uniqueIdentifier
{
return self.config.uniqueIdentifier;
}
- (NSString *)name
{
return self.config.connectionName;
}
- (nullable NSString *)networkName
{
return self.supportInfo.networkNameFormatted;
}
- (NSString *)networkNameAlt
{
NSString *networkName = self.networkName;
if (networkName) {
return networkName;
}
return self.config.connectionName;
}
- (nullable NSString *)serverAddress
{
NSString *serverAddress = self.supportInfo.serverAddress;
if (serverAddress) {
return serverAddress;
}
NSString *serverAddressOnSocket = self.socket.config.serverAddress;
if (serverAddressOnSocket) {
return serverAddressOnSocket;
}
return self.server.serverAddress;
}
- (NSString *)userNickname
{
NSString *userNickname = self->_userNickname;
if (userNickname) {
return userNickname;
}
return self.config.nickname;
}
#if TEXTUAL_BUILT_WITH_ADVANCED_ENCRYPTION == 1
- (NSString *)encryptionAccountNameForLocalUser
{
return [sharedEncryptionManager() accountNameForUser:self.userNickname onClient:self];
}
- (NSString *)encryptionAccountNameForUser:(NSString *)nickname
{
NSParameterAssert(nickname != nil);
return [sharedEncryptionManager() accountNameForUser:nickname onClient:self];
}
#endif
- (TDCFileTransferDialog *)fileTransferController
{
return [TXSharedApplication sharedFileTransferDialog];
}
- (BOOL)isReconnecting
{
return self.reconnectTimer.timerIsActive;
}
- (void)setSidebarItemIsExpanded:(BOOL)sidebarItemIsExpanded
{
/* This is a non-critical property that can be saved periodically */
if (self->_sidebarItemIsExpanded != sidebarItemIsExpanded) {
self->_sidebarItemIsExpanded = sidebarItemIsExpanded;
self.configurationIsStale = YES;
[worldController() savePeriodically];
}
}
- (void)setLastMessageServerTime:(NSTimeInterval)lastMessageServerTime
{
/* This is a non-critical property that can be saved periodically */
if (self->_lastMessageServerTime != lastMessageServerTime) {
self->_lastMessageServerTime = lastMessageServerTime;
self.configurationIsStale = YES;
[worldController() savePeriodically];
}
}
- (BOOL)isSecured
{
if (self.socket) {
return self.socket.isSecured;
}
return NO;
}
- (nullable NSData *)zncBouncerCertificateChainData
{
/* If the data is still being processed, then return
nil so that partial data is not returned. */
if (self.isConnectedToZNC == NO ||
self.zncBouncerIsSendingCertificateInfo ||
self.zncBouncerCertificateChainDataMutable == nil)
{
return nil;
}
return [self.zncBouncerCertificateChainDataMutable dataUsingEncoding:NSASCIIStringEncoding];
}
- (BOOL)isBrokenIRCd_aka_Twitch
{
return [self.serverAddress hasSuffix:@".twitch.tv"];
}
- (BOOL)supportsAdvancedTracking
{
return ([self isCapabilityEnabled:ClientIRCv3SupportedCapabilityMonitorCommand] ||
[self isCapabilityEnabled:ClientIRCv3SupportedCapabilityWatchCommand]);
}
- (BOOL)monitorAwayStatus
{
return ([self isCapabilityEnabled:ClientIRCv3SupportedCapabilityAwayNotify] ||
[TPCPreferences trackUserAwayStatusMaximumChannelSize] > 0);
}
- (nullable TVCLogLine *)lastLine
{
return self.viewController.lastLine;
}
#pragma mark -
#pragma mark Standalone Utilities
- (BOOL)messageIsFromMyself:(IRCMessage *)message
{
NSParameterAssert(message != nil);
return [self nicknameIsMyself:message.senderNickname];
}
- (BOOL)nicknameIsMyself:(NSString *)nickname
{
NSParameterAssert(nickname != nil);
return [self.userNickname isEqualToStringIgnoringCase:nickname];
}
- (BOOL)stringIsNickname:(NSString *)string
{
NSParameterAssert(string != nil);
return ([string isHostmaskNicknameOn:self] && [string isChannelNameOn:self] == NO);
}