/
OTRXMPPManager.m
1033 lines (843 loc) · 37.7 KB
/
OTRXMPPManager.m
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
//
// OTRXMPPManager.m
// Off the Record
//
// Created by Chris Ballinger on 9/7/11.
// Copyright (c) 2011 Chris Ballinger. All rights reserved.
//
// This file is part of ChatSecure.
//
// ChatSecure is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ChatSecure is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ChatSecure. If not, see <http://www.gnu.org/licenses/>.
#import "OTRXMPPManager.h"
#import "GCDAsyncSocket.h"
#import "XMPP.h"
#import "XMPPReconnect.h"
#import "XMPPCapabilitiesCoreDataStorage.h"
#import "XMPPRosterCoreDataStorage.h"
#import "XMPPvCardAvatarModule.h"
#import "XMPPMessage+XEP_0184.h"
#import "XMPPMessage+XEP_0085.h"
#import "NSXMLElement+XEP_0203.h"
#import "XMPPMessageDeliveryReceipts.h"
#import "Strings.h"
#import "OTRXMPPManagedPresenceSubscriptionRequest.h"
#import "OTRYapDatabaseRosterStorage.h"
#import "OTRLog.h"
#import <CFNetwork/CFNetwork.h>
#import "OTRSettingsManager.h"
#import "OTRConstants.h"
#import "OTRProtocolManager.h"
#include <stdlib.h>
#import "XMPPXFacebookPlatformAuthentication.h"
#import "XMPPXOAuth2Google.h"
#import "OTRConstants.h"
#import "OTRUtilities.h"
#import "OTRDatabaseManager.h"
#import "YapDatabaseConnection.h"
#import "OTRXMPPBuddy.h"
#import "OTRXMPPAccount.h"
#import "OTRMessage.h"
#import "OTRAccount.h"
#import "OTRXMPPPresenceSubscriptionRequest.h"
#import "OTRvCardYapDatabaseStorage.h"
#import "OTRFacebookOAuthXMPPAccount.h"
#import "FBAccessTokenData.h"
NSString *const OTRXMPPRegisterSucceededNotificationName = @"OTRXMPPRegisterSucceededNotificationName";
NSString *const OTRXMPPRegisterFailedNotificationName = @"OTRXMPPRegisterFailedNotificationName";
static NSString *const kOTRXMPPErrorDomain = @"kOTRXMPPErrorDomain";
NSTimeInterval const kOTRChatStatePausedTimeout = 5;
NSTimeInterval const kOTRChatStateInactiveTimeout = 120;
@interface OTRXMPPManager()
@property (nonatomic, strong) OTRXMPPAccount *account;
@property (nonatomic) OTRProtocolConnectionStatus connectionStatus;
@property (nonatomic, strong) XMPPStream *xmppStream;
@property (nonatomic, strong) XMPPReconnect *xmppReconnect;
@property (nonatomic, strong) XMPPRoster *xmppRoster;
@property (nonatomic, strong) XMPPvCardTempModule *xmppvCardTempModule;
@property (nonatomic, strong) XMPPvCardAvatarModule *xmppvCardAvatarModule;
@property (nonatomic, strong) XMPPCapabilities *xmppCapabilities;
@property (nonatomic, strong) NSString *password;
@property (nonatomic, strong) XMPPJID *JID;
@property (nonatomic, strong) XMPPCapabilitiesCoreDataStorage *xmppCapabilitiesStorage;
@property (nonatomic, strong) OTRYapDatabaseRosterStorage * xmppRosterStorage;
@property (nonatomic, strong) OTRCertificatePinning * certificatePinningModule;
@property (nonatomic, readwrite) BOOL isXmppConnected;
@property (nonatomic, strong) NSMutableDictionary * buddyTimers;
@property (nonatomic) dispatch_queue_t workQueue;
@property (nonatomic) BOOL isRegisteringNewAccount;
@property (nonatomic, strong) YapDatabaseConnection *databaseConnection;
- (void)setupStream;
- (void)teardownStream;
- (void)goOnline;
- (void)goOffline;
- (void)failedToConnect:(NSError *)error;
@end
@implementation OTRXMPPManager
- (id)init
{
if (self = [super init]) {
NSString * queueLabel = [NSString stringWithFormat:@"%@.work.%@",[self class],self];
self.workQueue = dispatch_queue_create([queueLabel UTF8String], 0);
self.connectionStatus = OTRProtocolConnectionStatusDisconnected;
self.buddyTimers = [NSMutableDictionary dictionary];
self.databaseConnection = [OTRDatabaseManager sharedInstance].readWriteDatabaseConnection;
}
return self;
}
- (id) initWithAccount:(OTRAccount *)newAccount {
if(self = [self init])
{
NSAssert([newAccount isKindOfClass:[OTRXMPPAccount class]], @"Must have XMPP account");
self.isRegisteringNewAccount = NO;
self.account = (OTRXMPPAccount *)newAccount;
// Setup the XMPP stream
[self setupStream];
self.buddyTimers = [NSMutableDictionary dictionary];
}
return self;
}
- (void)dealloc
{
[self teardownStream];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Private
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)setupStream
{
NSAssert(_xmppStream == nil, @"Method setupStream invoked multiple times");
if (self.account.accountType == OTRAccountTypeFacebook) {
self.xmppStream = [[XMPPStream alloc] initWithFacebookAppId:FACEBOOK_APP_ID];
} else {
self.xmppStream = [[XMPPStream alloc] init];
}
//Used to fetch correct account from XMPPStream in delegate methods especailly
self.xmppStream.tag = self.account.uniqueId;
self.xmppStream.startTLSPolicy = XMPPStreamStartTLSPolicyRequired;
[self.certificatePinningModule activate:self.xmppStream];
XMPPMessageDeliveryReceipts * deliveryReceiptsMoodule = [[XMPPMessageDeliveryReceipts alloc] init];
deliveryReceiptsMoodule.autoSendMessageDeliveryReceipts = YES;
deliveryReceiptsMoodule.autoSendMessageDeliveryRequests = YES;
[deliveryReceiptsMoodule activate:self.xmppStream];
#if !TARGET_IPHONE_SIMULATOR
{
// Want xmpp to run in the background?
//
// P.S. - The simulator doesn't support backgrounding yet.
// When you try to set the associated property on the simulator, it simply fails.
// And when you background an app on the simulator,
// it just queues network traffic til the app is foregrounded again.
// We are patiently waiting for a fix from Apple.
// If you do enableBackgroundingOnSocket on the simulator,
// you will simply see an error message from the xmpp stack when it fails to set the property.
self.xmppStream.enableBackgroundingOnSocket = YES;
}
#endif
// Setup reconnect
//
// The XMPPReconnect module monitors for "accidental disconnections" and
// automatically reconnects the stream for you.
// There's a bunch more information in the XMPPReconnect header file.
self.xmppReconnect = [[XMPPReconnect alloc] init];
// Setup roster
//
// The XMPPRoster handles the xmpp protocol stuff related to the roster.
// The storage for the roster is abstracted.
// So you can use any storage mechanism you want.
// You can store it all in memory, or use core data and store it on disk, or use core data with an in-memory store,
// or setup your own using raw SQLite, or create your own storage mechanism.
// You can do it however you like! It's your application.
// But you do need to provide the roster with some storage facility.
//DDLogInfo(@"Unique Identifier: %@",self.account.uniqueIdentifier);
OTRYapDatabaseRosterStorage * rosterStorage = [[OTRYapDatabaseRosterStorage alloc] init];
self.xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:rosterStorage];
self.xmppRoster.autoFetchRoster = YES;
self.xmppRoster.autoClearAllUsersAndResources = NO;
self.xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES;
// Setup vCard support
//
// The vCard Avatar module works in conjuction with the standard vCard Temp module to download user avatars.
// The XMPPRoster will automatically integrate with XMPPvCardAvatarModule to cache roster photos in the roster.
OTRvCardYapDatabaseStorage * vCardStorage = [[OTRvCardYapDatabaseStorage alloc] init];
self.xmppvCardTempModule = [[XMPPvCardTempModule alloc] initWithvCardStorage:vCardStorage];
self.xmppvCardAvatarModule = [[XMPPvCardAvatarModule alloc] initWithvCardTempModule:self.xmppvCardTempModule];
// Setup capabilities
//
// The XMPPCapabilities module handles all the complex hashing of the caps protocol (XEP-0115).
// Basically, when other clients broadcast their presence on the network
// they include information about what capabilities their client supports (audio, video, file transfer, etc).
// But as you can imagine, this list starts to get pretty big.
// This is where the hashing stuff comes into play.
// Most people running the same version of the same client are going to have the same list of capabilities.
// So the protocol defines a standardized way to hash the list of capabilities.
// Clients then broadcast the tiny hash instead of the big list.
// The XMPPCapabilities protocol automatically handles figuring out what these hashes mean,
// and also persistently storing the hashes so lookups aren't needed in the future.
//
// Similarly to the roster, the storage of the module is abstracted.
// You are strongly encouraged to persist caps information across sessions.
//
// The XMPPCapabilitiesCoreDataStorage is an ideal solution.
// It can also be shared amongst multiple streams to further reduce hash lookups.
self.xmppCapabilitiesStorage = [[XMPPCapabilitiesCoreDataStorage alloc] initWithInMemoryStore];
self.xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:self.xmppCapabilitiesStorage];
self.xmppCapabilities.autoFetchHashedCapabilities = YES;
self.xmppCapabilities.autoFetchNonHashedCapabilities = NO;
// Activate xmpp modules
[self.xmppReconnect activate:self.xmppStream];
[self.xmppRoster activate:self.xmppStream];
[self.xmppvCardTempModule activate:self.xmppStream];
[self.xmppvCardAvatarModule activate:self.xmppStream];
[self.xmppCapabilities activate:self.xmppStream];
// Add ourself as a delegate to anything we may be interested in
[self.xmppStream addDelegate:self delegateQueue:self.workQueue];
[self.xmppRoster addDelegate:self delegateQueue:self.workQueue];
[self.xmppCapabilities addDelegate:self delegateQueue:self.workQueue];
// Optional:
//
// Replace me with the proper domain and port.
// The example below is setup for a typical google talk account.
//
// If you don't supply a hostName, then it will be automatically resolved using the JID (below).
// For example, if you supply a JID like 'user@quack.com/rsrc'
// then the xmpp framework will follow the xmpp specification, and do a SRV lookup for quack.com.
//
// If you don't specify a hostPort, then the default (5222) will be used.
// [xmppStream setHostName:@"talk.google.com"];
// [xmppStream setHostPort:5222];
}
- (void)teardownStream
{
[_xmppStream removeDelegate:self];
[_xmppRoster removeDelegate:self];
[_xmppCapabilities removeDelegate:self];
[_xmppReconnect deactivate];
[_xmppRoster deactivate];
[_xmppvCardTempModule deactivate];
[_xmppvCardAvatarModule deactivate];
[_xmppCapabilities deactivate];
[_xmppStream disconnect];
_xmppStream = nil;
_xmppReconnect = nil;
_xmppRoster = nil;
_xmppRosterStorage = nil;
_xmppvCardTempModule = nil;
_xmppvCardAvatarModule = nil;
_xmppCapabilities = nil;
_xmppCapabilitiesStorage = nil;
_certificatePinningModule = nil;
}
// It's easy to create XML elments to send and to read received XML elements.
// You have the entire NSXMLElement and NSXMLNode API's.
//
// In addition to this, the NSXMLElement+XMPP category provides some very handy methods for working with XMPP.
//
// On the iPhone, Apple chose not to include the full NSXML suite.
// No problem - we use the KissXML library as a drop in replacement.
//
// For more information on working with XML elements, see the Wiki article:
// http://code.google.com/p/xmppframework/wiki/WorkingWithElements
- (XMPPStream *)xmppStream
{
if(!_xmppStream)
{
if (self.account.accountType == OTRAccountTypeFacebook) {
_xmppStream = [[XMPPStream alloc] initWithFacebookAppId:FACEBOOK_APP_ID];
}
else{
_xmppStream = [[XMPPStream alloc] init];
}
_xmppStream.startTLSPolicy = XMPPStreamStartTLSPolicyRequired;
}
return _xmppStream;
}
- (void)goOnline
{
self.connectionStatus = OTRProtocolConnectionStatusConnected;
[[NSNotificationCenter defaultCenter]
postNotificationName:kOTRProtocolLoginSuccess object:self];
XMPPPresence *presence = [XMPPPresence presence]; // type="available" is implicit
[[self xmppStream] sendElement:presence];
}
- (void)goOffline
{
XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
[[self xmppStream] sendElement:presence];
}
- (NSString *)accountDomainWithError:(id)error;
{
return self.account.domain;
}
- (void)didRegisterNewAccount
{
self.isRegisteringNewAccount = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:OTRXMPPRegisterSucceededNotificationName object:self];
}
- (void)failedToRegisterNewAccount:(NSError *)error
{
if (error) {
[[NSNotificationCenter defaultCenter]
postNotificationName:OTRXMPPRegisterFailedNotificationName object:self userInfo:@{kOTRNotificationErrorKey:error}];
}
else {
[[NSNotificationCenter defaultCenter]
postNotificationName:OTRXMPPRegisterFailedNotificationName object:self];
}
}
- (void)refreshStreamJID:(NSString *)myJID withPassword:(NSString *)myPassword
{
int r = arc4random() % 99999;
NSString * resource = [NSString stringWithFormat:@"%@%d",kOTRXMPPResource,r];
self.JID = [XMPPJID jidWithString:myJID resource:resource];
[self.xmppStream setMyJID:self.JID];
self.password = myPassword;
}
- (void)authenticateWithStream:(XMPPStream *)stream {
NSError * error = nil;
BOOL status = YES;
if ([stream supportsXFacebookPlatformAuthentication]) {
status = [stream authenticateWithFacebookAccessToken:self.password error:&error];
}
else if ([stream supportsXOAuth2GoogleAuthentication] && self.account.accountType == OTRAccountTypeGoogleTalk) {
status = [stream authenticateWithGoogleAccessToken:self.password error:&error];
}
else {
status = [stream authenticateWithPassword:self.password error:&error];
}
}
///////////////////////////////
#pragma mark Capabilities Collected
////////////////////////////////////////////
- (NSArray *)myFeaturesForXMPPCapabilities:(XMPPCapabilities *)sender
{
return @[@"http://jabber.org/protocol/chatstates"];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Connect/disconnect
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)connectWithJID:(NSString*) myJID password:(NSString*)myPassword;
{
self.password = myPassword;
self.connectionStatus = OTRProtocolConnectionStatusConnecting;
// We aren't properly storing the Facebook JID after the OAuthToken refresher
// so have to rely on this hack for now. In theory this should be fixed elsewhere
// however that code requires a refactor first to avoid code duplication.
// Facebook Chat over XMPP will be disabled on April 30, 2015 anyway. :(
if (!myJID.length) {
if ([self.account isKindOfClass:[OTRFacebookOAuthXMPPAccount class]]) {
OTRFacebookOAuthXMPPAccount *facebookAccount = (OTRFacebookOAuthXMPPAccount*)self.account;
FBAccessTokenData *tokenData = facebookAccount.accountSpecificToken;
myJID = [NSString stringWithFormat:@"%@@%@", tokenData.userID, @"chat.facebook.com"];
[[OTRDatabaseManager sharedInstance].readWriteDatabaseConnection asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
OTRFacebookOAuthXMPPAccount *account = [transaction objectForKey:facebookAccount.uniqueId inCollection:[[facebookAccount class] collection]];
if (account) {
account = [account copy];
account.username = myJID;
[transaction setObject:account forKey:account.uniqueId inCollection:[[facebookAccount class] collection]];
}
} completionBlock:nil];
}
}
self.JID = [XMPPJID jidWithString:myJID resource:self.account.resource];
if (![self.JID.domain isEqualToString:self.xmppStream.myJID.domain]) {
[self.xmppStream disconnect];
}
[self.xmppStream setMyJID:self.JID];
//DDLogInfo(@"myJID %@",myJID);
if (![self.xmppStream isDisconnected]) {
[self authenticateWithStream:self.xmppStream];
return YES;
}
//
// If you don't want to use the Settings view to set the JID,
// uncomment the section below to hard code a JID and password.
//
// Replace me with the proper JID and password:
// myJID = @"user@gmail.com/xmppframework";
// myPassword = @"";
NSError * error = nil;
NSString * domainString = [self accountDomainWithError:error];
if (error) {
[self failedToConnect:error];
return NO;
}
if ([domainString length]) {
[self.xmppStream setHostName:domainString];
}
[self.xmppStream setHostPort:self.account.port];
error = nil;
if (![self.xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
{
[self failedToConnect:error];
DDLogError(@"Error connecting: %@", error);
return NO;
}
return YES;
}
- (void)disconnect
{
[self goOffline];
[self.xmppStream disconnect];
if([OTRSettingsManager boolForOTRSettingKey:kOTRSettingKeyDeleteOnDisconnect])
{
[self.databaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
[OTRMessage deleteAllMessagesForAccountId:self.account.uniqueId transaction:transaction];
}];
}
}
- (void)registerNewAccountWithPassword:(NSString *)newPassword
{
self.isRegisteringNewAccount = YES;
if (self.xmppStream.isConnected) {
[self.xmppStream disconnect];
}
[self connectWithJID:self.account.username password:newPassword];
}
- (void)registerNewAccountWithPassword:(NSString *)newPassword stream:(XMPPStream *)stream
{
NSError * error = nil;
if ([stream supportsInBandRegistration]) {
[stream registerWithPassword:self.password error:&error];
if(error)
{
[self failedToRegisterNewAccount:error];
}
}
else{
error = [NSError errorWithDomain:OTRXMPPErrorDomain code:OTRXMPPUnsupportedAction userInfo:nil];
[self failedToRegisterNewAccount:error];
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPStream Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void)xmppStreamDidChangeMyJID:(XMPPStream *)stream
{
if (![[stream.myJID bare] isEqualToString:self.account.username] || ![[stream.myJID resource] isEqualToString:self.account.resource])
{
self.account.username = [stream.myJID bare];
self.account.resource = [stream.myJID resource];
[self.databaseConnection asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
[self.account saveWithTransaction:transaction];
}];
}
}
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
settings[GCDAsyncSocketSSLProtocolVersionMin] = @(kTLSProtocol1);
settings[GCDAsyncSocketSSLCipherSuites] = [OTRUtilities cipherSuites];
settings[GCDAsyncSocketManuallyEvaluateTrust] = @(YES);
}
- (void)xmppStreamDidSecure:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
if (self.isRegisteringNewAccount) {
[self registerNewAccountWithPassword:self.password stream:sender];
}
else{
[self authenticateWithStream:sender];
}
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
self.connectionStatus = OTRProtocolConnectionStatusConnected;
[self goOnline];
}
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
self.connectionStatus = OTRProtocolConnectionStatusDisconnected;
[self failedToConnect:[OTRXMPPError errorForXMLElement:error]];
}
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, [iq elementID]);
return NO;
}
- (void)xmppStreamDidRegister:(XMPPStream *)sender {
[self didRegisterNewAccount];
}
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)xmlError {
self.isRegisteringNewAccount = NO;
NSError * error = [OTRXMPPError errorForXMLElement:xmlError];
[self failedToRegisterNewAccount:error];
}
-(OTRXMPPBuddy *)buddyWithMessage:(XMPPMessage *)message transaction:(YapDatabaseReadTransaction *)transaction
{
OTRXMPPBuddy *buddy = [OTRXMPPBuddy fetchBuddyWithUsername:[[message from] bare] withAccountUniqueId:self.account.uniqueId transaction:transaction];
return buddy;
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)xmppMessage
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
[self.databaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
OTRXMPPBuddy *messageBuddy = [self buddyWithMessage:xmppMessage transaction:transaction];
if ([xmppMessage isErrorMessage]) {
NSError *error = [xmppMessage errorMessage];
DDLogCWarn(@"XMPP Error: %@",error);
}
else if([xmppMessage hasChatState])
{
if([xmppMessage hasComposingChatState])
messageBuddy.chatState = kOTRChatStateComposing;
else if([xmppMessage hasPausedChatState])
messageBuddy.chatState = kOTRChatStatePaused;
else if([xmppMessage hasActiveChatState])
messageBuddy.chatState = kOTRChatStateActive;
else if([xmppMessage hasInactiveChatState])
messageBuddy.chatState = kOTRChatStateInactive;
else if([xmppMessage hasGoneChatState])
messageBuddy.chatState = kOTRChatStateGone;
[messageBuddy saveWithTransaction:transaction];
}
if ([xmppMessage hasReceiptResponse] && ![xmppMessage isErrorMessage]) {
[OTRMessage receivedDeliveryReceiptForMessageId:[xmppMessage receiptResponseID] transaction:transaction];
}
if ([xmppMessage isMessageWithBody] && ![xmppMessage isErrorMessage])
{
NSString *body = [[xmppMessage elementForName:@"body"] stringValue];
NSDate * date = [xmppMessage delayedDeliveryDate];
OTRMessage *message = [[OTRMessage alloc] init];
message.incoming = YES;
message.text = body;
message.buddyUniqueId = messageBuddy.uniqueId;
if (date) {
message.date = date;
}
message.messageId = [xmppMessage elementID];
[[OTRKit sharedInstance] decodeMessage:message.text username:messageBuddy.username accountName:self.account.username protocol:kOTRProtocolTypeXMPP tag:message];
}
if (messageBuddy) {
[transaction setObject:messageBuddy forKey:messageBuddy.uniqueId inCollection:[OTRXMPPBuddy collection]];
}
}];
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
DDLogVerbose(@"%@: %@ - %@\nType: %@\nShow: %@\nStatus: %@", THIS_FILE, THIS_METHOD, [presence from], [presence type], [presence show],[presence status]);
}
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender didFailToSendIQ:(XMPPIQ *)iq error:(NSError *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender didFailToSendMessage:(XMPPMessage *)message error:(NSError *)error
{
if ([message.elementID length]) {
[self.databaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
[OTRMessage enumerateMessagesWithMessageId:message.elementID transaction:transaction usingBlock:^(OTRMessage *message, BOOL *stop) {
message.error = error;
[message saveWithTransaction:transaction];
*stop = YES;
}];
}];
}
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStream:(XMPPStream *)sender didFailToSendPresence:(XMPPPresence *)presence error:(NSError *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
}
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
self.connectionStatus = OTRProtocolConnectionStatusDisconnected;
if (!self.isXmppConnected)
{
DDLogError(@"Unable to connect to server. Check xmppStream.hostName");
[self failedToConnect:error];
}
else {
[self.databaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
NSArray *allBuddies = [self.account allBuddiesWithTransaction:transaction];
[allBuddies enumerateObjectsUsingBlock:^(OTRXMPPBuddy *buddy, NSUInteger idx, BOOL *stop) {
buddy.status = OTRBuddyStatusOffline;
buddy.statusMessage = nil;
[transaction setObject:buddy forKey:buddy.uniqueId inCollection:[OTRXMPPBuddy collection]];
}];
}];
}
self.isXmppConnected = NO;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPRosterDelegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
-(void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
NSString *jidStrBare = [presence fromStr];
[self.databaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
OTRXMPPPresenceSubscriptionRequest *request = [OTRXMPPPresenceSubscriptionRequest fetchPresenceSubscriptionRequestWithJID:jidStrBare accontUniqueId:self.account.uniqueId transaction:transaction];
if (!request) {
request = [[OTRXMPPPresenceSubscriptionRequest alloc] init];
}
request.jid = jidStrBare;
request.accountUniqueId = self.account.uniqueId;
[request saveWithTransaction:transaction];
}];
}
- (void)xmppRoster:(XMPPRoster *)sender didReceiveRosterPush:(XMPPIQ *)iq
{
DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);
//verry unclear what this delegate call is supposed to do with jabber.ccc.de it seems to have all the subscription=both,none and jid
/*
if ([iq isSetIQ] && [[[[[[iq elementsForName:@"query"] firstObject] elementsForName:@"item"] firstObject] attributeStringValueForName:@"subscription"] isEqualToString:@"from"]) {
NSString *jidString = [[[[[iq elementsForName:@"query"] firstObject] elementsForName:@"item"] firstObject] attributeStringValueForName:@"jid"];
[self.databaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
OTRXMPPPresenceSubscriptionRequest *request = [OTRXMPPPresenceSubscriptionRequest fetchPresenceSubscriptionRequestWithJID:jidString accontUniqueId:self.account.uniqueId transaction:transaction];
if (!request) {
request = [[OTRXMPPPresenceSubscriptionRequest alloc] init];
}
request.jid = jidString;
request.accountUniqueId = self.account.uniqueId;
[transaction setObject:request forKey:request.uniqueId inCollection:[OTRXMPPPresenceSubscriptionRequest collection]];
}];
}
else if ([iq isSetIQ] && [[[[[[iq elementsForName:@"query"] firstObject] elementsForName:@"item"] firstObject] attributeStringValueForName:@"subscription"] isEqualToString:@"none"])
{
[self.databaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
NSString *jidString = [[[[[iq elementsForName:@"query"] firstObject] elementsForName:@"item"] firstObject] attributeStringValueForName:@"jid"];
OTRXMPPBuddy *buddy = [[OTRXMPPBuddy fetchBuddyWithUsername:jidString withAccountUniqueId:self.account.uniqueId transaction:transaction] copy];
buddy.pendingApproval = YES;
[buddy saveWithTransaction:transaction];
}];
}
*/
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark OTRProtocol
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (void) sendMessage:(OTRMessage*)message
{
NSString *text = message.text;
__block OTRBuddy *buddy = nil;
[[OTRDatabaseManager sharedInstance].readWriteDatabaseConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
buddy = [message buddyWithTransaction:transaction];
}];
[self invalidatePausedChatStateTimerForBuddyUniqueId:buddy.uniqueId];
if ([text length])
{
NSString * messageID = message.messageId;
XMPPMessage * xmppMessage = [XMPPMessage messageWithType:@"chat" to:[XMPPJID jidWithString:buddy.username] elementID:messageID];
[xmppMessage addBody:text];
[xmppMessage addActiveChatState];
[self.xmppStream sendElement:xmppMessage];
}
}
- (NSString*) accountName
{
return [self.JID full];
}
- (NSString*) type {
return kOTRProtocolTypeXMPP;
}
-(void)connectWithPassword:(NSString *)myPassword
{
[self connectWithJID:self.account.username password:myPassword];
}
-(void)sendChatState:(OTRChatState)chatState withBuddyID:(NSString *)buddyUniqueId
{
dispatch_async(self.workQueue, ^{
__block OTRXMPPBuddy *buddy = nil;
[self.databaseConnection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
buddy = [OTRXMPPBuddy fetchObjectWithUniqueID:buddyUniqueId transaction:transaction];
}];
if (buddy.lastSentChatState == chatState) {
return;
}
XMPPMessage * xMessage = [[XMPPMessage alloc] initWithType:@"chat" to:[XMPPJID jidWithString:buddy.username]];
BOOL shouldSend = YES;
if (chatState == kOTRChatStateActive) {
//Timers
dispatch_async(dispatch_get_main_queue(), ^{
[[self pausedChatStateTimerForBuddyObjectID:buddyUniqueId] invalidate];
[self restartInactiveChatStateTimerForBuddyObjectID:buddyUniqueId];
});
[xMessage addActiveChatState];
}
else if (chatState == kOTRChatStateComposing)
{
if(buddy.lastSentChatState !=kOTRChatStateComposing)
[xMessage addComposingChatState];
else
shouldSend = NO;
//Timers
dispatch_async(dispatch_get_main_queue(), ^{
[self restartPausedChatStateTimerForBuddyObjectID:buddy.uniqueId];
[[self inactiveChatStateTimerForBuddyObjectID:buddy.uniqueId] invalidate];
});
}
else if(chatState == kOTRChatStateInactive)
{
if(buddy.lastSentChatState != kOTRChatStateInactive)
[xMessage addInactiveChatState];
else
shouldSend = NO;
}
else if (chatState == kOTRChatStatePaused)
{
[xMessage addPausedChatState];
}
else if (chatState == kOTRChatStateGone)
{
[xMessage addGoneChatState];
}
else
{
shouldSend = NO;
}
if(shouldSend)
{
[[OTRDatabaseManager sharedInstance].readWriteDatabaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
OTRXMPPBuddy *localBuddy = [OTRXMPPBuddy fetchObjectWithUniqueID:buddy.uniqueId transaction:transaction];
localBuddy.lastSentChatState = chatState;
[localBuddy saveWithTransaction:transaction];
}];
[self.xmppStream sendElement:xMessage];
}
});
}
- (void) addBuddy:(OTRXMPPBuddy *)newBuddy
{
XMPPJID * newJID = [XMPPJID jidWithString:newBuddy.username];
[self.xmppRoster addUser:newJID withNickname:newBuddy.displayName];
}
- (void) setDisplayName:(NSString *) newDisplayName forBuddy:(OTRXMPPBuddy *)buddy
{
XMPPJID * jid = [XMPPJID jidWithString:buddy.username];
[self.xmppRoster setNickname:newDisplayName forUser:jid];
}
-(void)removeBuddies:(NSArray *)buddies
{
for (OTRXMPPBuddy *buddy in buddies){
XMPPJID * jid = [XMPPJID jidWithString:buddy.username];
[self.xmppRoster removeUser:jid];
}
[[OTRDatabaseManager sharedInstance].readWriteDatabaseConnection readWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
[transaction removeObjectsForKeys:[buddies valueForKey:NSStringFromSelector(@selector(uniqueId))] inCollection:[OTRXMPPBuddy collection]];
}];
}
-(void)blockBuddies:(NSArray *)buddies
{
for (OTRXMPPBuddy *buddy in buddies){
XMPPJID * jid = [XMPPJID jidWithString:buddy.username];
[self.xmppRoster revokePresencePermissionFromUser:jid];
}
}
//Chat State
-(OTRXMPPBudyTimers *)buddyTimersForBuddyObjectID:(NSString *)
managedBuddyObjectID
{
OTRXMPPBudyTimers * timers = (OTRXMPPBudyTimers *)[self.buddyTimers objectForKey:managedBuddyObjectID];
return timers;
}
-(NSTimer *)inactiveChatStateTimerForBuddyObjectID:(NSString *)
managedBuddyObjectID
{
return [self buddyTimersForBuddyObjectID:managedBuddyObjectID].inactiveChatStateTimer;
}
-(NSTimer *)pausedChatStateTimerForBuddyObjectID:(NSString *)
managedBuddyObjectID
{
return [self buddyTimersForBuddyObjectID:managedBuddyObjectID].pausedChatStateTimer;
}
-(void)restartPausedChatStateTimerForBuddyObjectID:(NSString *)managedBuddyObjectID
{
dispatch_async(dispatch_get_main_queue(), ^{
OTRXMPPBudyTimers * timer = (OTRXMPPBudyTimers *)[self.buddyTimers objectForKey:managedBuddyObjectID];
if(!timer)
{
timer = [[OTRXMPPBudyTimers alloc] init];
}
[timer.pausedChatStateTimer invalidate];
timer.pausedChatStateTimer = [NSTimer scheduledTimerWithTimeInterval:kOTRChatStatePausedTimeout target:self selector:@selector(sendPausedChatState:) userInfo:managedBuddyObjectID repeats:NO];
[self.buddyTimers setObject:timer forKey:managedBuddyObjectID];
});
}
-(void)restartInactiveChatStateTimerForBuddyObjectID:(NSString *)managedBuddyObjectID
{
dispatch_async(dispatch_get_main_queue(), ^{
OTRXMPPBudyTimers * timer = (OTRXMPPBudyTimers *)[self.buddyTimers objectForKey:managedBuddyObjectID];
if(!timer)
{
timer = [[OTRXMPPBudyTimers alloc] init];
}
[timer.inactiveChatStateTimer invalidate];
timer.inactiveChatStateTimer = [NSTimer scheduledTimerWithTimeInterval:kOTRChatStateInactiveTimeout target:self selector:@selector(sendInactiveChatState:) userInfo:managedBuddyObjectID repeats:NO];
[self.buddyTimers setObject:timer forKey:managedBuddyObjectID];
});
}
-(void)sendPausedChatState:(NSTimer *)timer
{
NSString * managedBuddyObjectID= (NSString *)timer.userInfo;
dispatch_async(dispatch_get_main_queue(), ^{
[timer invalidate];
});
[self sendChatState:kOTRChatStatePaused withBuddyID:managedBuddyObjectID];
}
-(void)sendInactiveChatState:(NSTimer *)timer
{
NSString *managedBuddyObjectID= (NSString *)timer.userInfo;
dispatch_async(dispatch_get_main_queue(), ^{
[timer invalidate];
});
[self sendChatState:kOTRChatStateInactive withBuddyID:managedBuddyObjectID];
}
- (void)invalidatePausedChatStateTimerForBuddyUniqueId:(NSString *)buddyUniqueId
{
[[self pausedChatStateTimerForBuddyObjectID:buddyUniqueId] invalidate];
}