-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathRNLayerKit.m
More file actions
417 lines (379 loc) · 18.2 KB
/
Copy pathRNLayerKit.m
File metadata and controls
417 lines (379 loc) · 18.2 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
#import "RNLayerKit.h"
@implementation RNLayerKit{
NSString *_appID;
LYRClient *_layerClient;
JSONHelper *_jsonHelper;
NSData *_deviceToken;
}
@synthesize bridge = _bridge;
- (id)init
{
if ((self = [super init])) {
RCTLogInfo(@"LayerBridge init");
_jsonHelper = [JSONHelper new];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(receivedNotification:)
name:@"RNLayerKitNotification"
object:nil];
}
return self;
}
//- (dispatch_queue_t)methodQueue
//{
// return dispatch_queue_create("com.schoolstatus.LayerCLientQueue", DISPATCH_QUEUE_SERIAL);
//}
RCT_EXPORT_MODULE()
RCT_EXPORT_METHOD(connect:(NSString*)appIDstr callback:(RCTResponseSenderBlock)callback)
{
if (!_layerClient) {
NSLog(@"No Layer Client");
NSURL *appID = [NSURL URLWithString:appIDstr];
_layerClient = [LYRClient clientWithAppID:appID];
[_layerClient setDelegate:self];
[_layerClient connectWithCompletion:^(BOOL success, NSError *error) {
if (!success) {
RCTLogInfo(@"Failed to connect to Layer: %@", error);
callback(@[[_jsonHelper convertErrorToDictionary:error], @NO]);
} else {
RCTLogInfo(@"Connected to Layer!");
if(_deviceToken)
[self updateRemoteNotificationDeviceToken:_deviceToken];
callback(@[[NSNull null], @YES]);
}
}];
}
}
RCT_EXPORT_METHOD(disconnect)
{
[_layerClient disconnect];
}
RCT_EXPORT_METHOD(sendMessageToUserIDs:(NSString*)messageText userIDs:(NSArray*)userIDs callback:(RCTResponseSenderBlock)callback)
{
// Declares a MIME type string
static NSString *const MIMETypeTextPlain = @"text/plain";
// Creates and returns a new conversation object with a single participant represented by
// your backend's user identifier for the participant
NSError *convErr = nil;
LYRConversation *conversation = [self fetchLayerConversationWithParticipants:userIDs andErr:convErr];
if(!conversation){
RCTLogError(@"Error creating conversastion");
}
if(convErr){
id retErr = RCTMakeAndLogError(@"Error creating conversastion",convErr,NULL);
callback(@[retErr,[NSNull null]]);
}
// Creates a message part with a text/plain MIMEType
NSError *error = nil;
NSData *messageData = [messageText dataUsingEncoding:NSUTF8StringEncoding];
LYRMessagePart *messagePart = [LYRMessagePart messagePartWithMIMEType:MIMETypeTextPlain data:messageData];
// Creates and returns a new message object with the given conversation and array of message parts
LYRMessage *message = [_layerClient newMessageWithParts:@[ messagePart ] options:@{LYRMessageOptionsPushNotificationAlertKey: messageText,LYRMessageOptionsPushNotificationSoundNameKey: @"layerbell.caf"} error:&error];
// Sends the specified message
BOOL success = [conversation sendMessage:message error:&error];
if(success){
RCTLogInfo(@"Layer Message sent to %@", userIDs);
//callback(@[[NSNull null],conversation]);
callback(@[[NSNull null],@YES]);
}
else {
id retErr = RCTMakeAndLogError(@"Error sending Layer message",error,NULL);
callback(@[retErr,[NSNull null]]);
}
}
RCT_EXPORT_METHOD(getConversations:(int)limit offset:(int)offset callback:(RCTResponseSenderBlock)callback)
{
LayerQuery *query = [LayerQuery new];
NSError *queryError;
id allConvos = [query fetchConvosForClient:_layerClient limit:limit offset:offset error:queryError];
if(queryError){
id retErr = RCTMakeAndLogError(@"Error getting Layer conversations",queryError,NULL);
callback(@[retErr,[NSNull null]]);
}
else{
JSONHelper *helper = [JSONHelper new];
NSArray *retData = [helper convertConvosToArray:allConvos];
callback(@[[NSNull null],retData]);
}
}
RCT_EXPORT_METHOD(getMessages:(NSString*)convoID limit:(int)limit offset:(int)offset callback:(RCTResponseSenderBlock)callback)
{
LayerQuery *query = [LayerQuery new];
NSError *queryError;
NSOrderedSet *convoMessages = [query fetchMessagesForConvoId:convoID client:_layerClient limit:limit offset:offset error:queryError];
if(queryError){
id retErr = RCTMakeAndLogError(@"Error getting Layer messages",queryError,NULL);
callback(@[retErr,[NSNull null]]);
}
else{
JSONHelper *helper = [JSONHelper new];
NSArray *retData = [helper convertMessagesToArray:convoMessages];
callback(@[[NSNull null],retData]);
}
}
RCT_EXPORT_METHOD(markAllAsRead:(NSString*)convoID callback:(RCTResponseSenderBlock)callback)
{
LayerQuery *query = [LayerQuery new];
NSError *err;
LYRConversation *thisConvo = [query fetchConvoWithId:convoID client:_layerClient error:err];
if(err){
[self sendErrorEvent:err];
}
else {
NSError *error;
BOOL success = [thisConvo markAllMessagesAsRead:&error];
if(success){
//RCTLogInfo(@"Layer Messages marked as read");
callback(@[[NSNull null],@YES]);
}
else {
id retErr = RCTMakeAndLogError(@"Error marking messages as read ",error,NULL);
callback(@[retErr,[NSNull null]]);
}
}
}
RCT_EXPORT_METHOD(sendTypingBegin:(NSString*)convoID)
{
LayerQuery *query = [LayerQuery new];
NSError *err;
LYRConversation *thisConvo = [query fetchConvoWithId:convoID client:_layerClient error:err];
if(err){
[self sendErrorEvent:err];
}
else {
[thisConvo sendTypingIndicator:LYRTypingDidBegin];
}
}
RCT_EXPORT_METHOD(sendTypingEnd:(NSString*)convoID)
{
LayerQuery *query = [LayerQuery new];
NSError *err;
LYRConversation *thisConvo = [query fetchConvoWithId:convoID client:_layerClient error:err];
if(err){
[self sendErrorEvent:err];
}
else {
[thisConvo sendTypingIndicator:LYRTypingDidBegin];
}
}
RCT_EXPORT_METHOD(registerForTypingEvents)
{
// Registers and object for typing indicator notifications.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didReceiveTypingIndicator:)
name:LYRConversationDidReceiveTypingIndicatorNotification
object:nil];
}
RCT_EXPORT_METHOD(unregisterForTypingEvents)
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:LYRConversationDidReceiveTypingIndicatorNotification object:nil];
}
#pragma mark - Authentication
RCT_EXPORT_METHOD(authenticateLayerWithUserID:(NSString *)userID callback:(RCTResponseSenderBlock)callback)
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:LYRConversationDidReceiveTypingIndicatorNotification object:nil];
LayerAuthenticate *lAuth = [LayerAuthenticate new];
[lAuth authenticateLayerWithUserID:userID layerClient:_layerClient completion:^(NSError *error) {
if (!error) {
//GOOD LOGIN!!!
callback(@[[NSNull null],@(YES)]);
}
else{
id retErr = RCTMakeAndLogError(@"Error logging in",error,NULL);
callback(@[retErr,[NSNull null]]);
}
}];
}
#pragma mark - Register for Push Notif
- (void) receivedNotification:(NSNotification *) notification
{
// [notification name] should always be @"TestNotification"
// unless you use this method for observation of other notifications
// as well.
if ([[notification name] isEqualToString:@"RNLayerKitNotification"])
{
NSLog (@"Successfully received the test notification!");
NSDictionary *userInfo = notification.userInfo;
NSData *myToken = [userInfo objectForKey:@"deviceToken"];
[self updateRemoteNotificationDeviceToken:myToken];
}
}
-(void)updateRemoteNotificationDeviceToken:(NSData*)deviceToken
{
// if we haven't initialize our client, then save the token for later
if(!_layerClient){
_deviceToken=deviceToken;
}
else{
NSError *error;
BOOL success = [_layerClient updateRemoteNotificationDeviceToken:deviceToken error:&error];
if (success) {
NSLog(@"Application did register for remote notifications");
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient",@"type": @"didRegisterForRemoteNotificationsWithDeviceToken"}];
} else {
NSLog(@"Error updating Layer device token for push:%@", error);
//[self sendErrorEvent:error];
}
}
}
#pragma mark - Error Handle
-(void)sendErrorEvent:(NSError*)error{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"error",@"error":@{@"code":@(error.code),@"domain":error.domain,@"description":[error localizedDescription]}}];
}
#pragma mark - Layer Client Delegate
- (void)layerClient:(LYRClient *)client didAuthenticateAsUserID:(NSString *)userID
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient",@"type": @"didAuthenticateAsUserID", @"data":@{@"userID":userID}}];
}
- (void)layerClient:(LYRClient *)client didFailOperationWithError:(NSError *)error
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"didFailOperationWithError",@"error":@{@"code":@(error.code),@"domain":error.domain,@"description":[error localizedDescription]}}];
}
- (void)layerClient:(LYRClient *)client didFailSynchronizationWithError:(NSError *)error
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"didFailSynchronizationWithError",@"error":@{@"code":@(error.code),@"domain":error.domain,@"description":[error localizedDescription]}}];
}
- (void)layerClient:(LYRClient *)client didFinishContentTransfer:(LYRContentTransferType)contentTransferType ofObject:(id)object
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"didFinishContentTransfer"}];
}
- (void)layerClient:(LYRClient *)client didFinishSynchronizationWithChanges:(NSArray *)changes
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"didFinishSynchronizationWithChanges"}];
}
- (void)layerClient:(LYRClient *)client didLoseConnectionWithError:(NSError *)error
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"didLoseConnectionWithError", @"error":@{@"code":@(error.code),@"domain":error.domain,@"description":[error localizedDescription]}}];
}
- (void)layerClient:(LYRClient *)client didReceiveAuthenticationChallengeWithNonce:(NSString *)nonce
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"didReceiveAuthenticationChallengeWithNonce"}];
}
- (void)layerClient:(LYRClient *)client objectsDidChange:(NSArray *)changes;
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient",
@"type": @"objectsDidChange",
@"data":[_jsonHelper convertChangesToArray:changes]}];
}
- (void)layerClient:(LYRClient *)client willAttemptToConnect:(NSUInteger)attemptNumber afterDelay:(NSTimeInterval)delayInterval maximumNumberOfAttempts:(NSUInteger)attemptLimit
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type":@"willAttemptToConnect", @"data":@{@"attemptNumber":@(attemptNumber), @"delayInterval":@(delayInterval), @"attemptLimit":@(attemptLimit)}}];
}
- (void)layerClient:(LYRClient *)client willBeginContentTransfer:(LYRContentTransferType)contentTransferType ofObject:(id)object withProgress:(LYRProgress *)progress
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"willBeginContentTransfer"}];
}
- (void)layerClientDidConnect:(LYRClient *)client{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"layerClientDidConnect"}];
}
- (void)layerClientDidDeauthenticate:(LYRClient *)client
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"layerClientDidDeauthenticate"}];
}
- (void)layerClientDidDisconnect:(LYRClient *)client
{
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient", @"type": @"layerClientDidDisconnect"}];
}
#pragma mark - Typing Indicator
- (void)didReceiveTypingIndicator:(NSNotification *)notification
{
NSString *participantID = notification.userInfo[LYRTypingIndicatorParticipantUserInfoKey];
NSString *convoID = [[notification.object valueForKey:@"identifier"] absoluteString];
LYRTypingIndicator typingIndicator = [notification.userInfo[LYRTypingIndicatorValueUserInfoKey] unsignedIntegerValue];
if (typingIndicator == LYRTypingDidBegin) {
NSLog(@"Typing Started");
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient",
@"type": @"typingIndicator",
@"data":@{@"participantID":participantID,
@"event":@"LYRTypingDidBegin",
@"conversationID":convoID}}];
}
else if(typingIndicator==LYRTypingDidPause){
NSLog(@"Typing paused");
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient",
@"type": @"typingIndicator",
@"data":@{@"participantID":participantID,
@"event":@"LYRTypingDidPause",
@"conversationID":convoID}}];
}
else {
NSLog(@"Typing Stopped");
[self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
body:@{@"source":@"LayerClient",
@"type": @"typingIndicator",
@"data":@{@"participantID":participantID,
@"event":@"LYRTypingDidEnd",
@"conversationID":convoID}}];
}
}
//#pragma mark - Layer Query Delegate
//- (void)queryController:(LYRQueryController *)controller didChangeObject:(id)object atIndexPath:(NSIndexPath *)indexPath forChangeType:(LYRQueryControllerChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
//{
// [self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
// body:@{@"source":@"LayerQuery", @"type": @"queryControllerDidChangeObject"}];
//
//}
//- (void)queryControllerDidChangeContent:(LYRQueryController *)queryController
//{
// [self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
// body:@{@"source":@"LayerQuery", @"type": @"queryControllerDidChangeContent"}];
//
//}
//- (void)queryControllerWillChangeContent:(LYRQueryController *)queryController
//{
// [self.bridge.eventDispatcher sendAppEventWithName:@"LayerEvent"
// body:@{@"source":@"LayerQuery", @"type": @"queryControllerWillChangeContent"}];
//
//}
#pragma mark - Fetching Layer Content
- (LYRConversation*)fetchLayerConversationWithParticipants:(NSArray*)participants andErr:(NSError*)convErr
{
// Fetches all conversations between the authenticated user and the supplied participant
// For more information about Querying, check out https://developer.layer.com/docs/integration/ios#querying
LYRQuery *query = [LYRQuery queryWithQueryableClass:[LYRConversation class]];
query.predicate = [LYRPredicate predicateWithProperty:@"participants" predicateOperator:LYRPredicateOperatorIsEqualTo value:participants];
query.sortDescriptors = @[ [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO] ];
NSOrderedSet *conversations = [_layerClient executeQuery:query error:&convErr];
if (conversations.count <= 0) {
NSError *conv_error = nil;
return [_layerClient newConversationWithParticipants:[NSSet setWithArray: participants ] options:nil error:&conv_error];
}
else {
return [conversations lastObject];
}
}
-(id) fetchAllLayerConversasions
{
// Fetches all LYRConversation objects
LYRQuery *query = [LYRQuery queryWithQueryableClass:[LYRConversation class]];
NSError *error = nil;
NSOrderedSet *conversations = [_layerClient executeQuery:query error:&error];
if (conversations) {
RCTLogInfo(@"%tu conversations", conversations.count);
} else {
RCTLogError(@"Query failed with error %@", error);
}
if (!error) {
return conversations;
}
else {
return error;
}
}
@end