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
|
//
// APIClient.m
// Juick
//
// Created by Vitaly Takmazov on 22/08/16.
// Copyright © 2016 com.juick. All rights reserved.
//
#import "APIClient.h"
#import "Message.h"
#import "Chat.h"
@interface APIClient()
@property(nonatomic, readwrite) AFHTTPSessionManager *manager;
@property(nonatomic, strong) NSOperationQueue *backgroundQueue;
@property(nonatomic, strong) NSURLSession *urlSession;
@end
@implementation APIClient
+(APIClient *) sharedClient {
static APIClient *sharedAPIClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedAPIClient = [[self alloc] init];
});
return sharedAPIClient;
}
-(id)init {
if (self = [super init]) {
NSString *baseURLString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"base_url"];
NSLog(@"Initializing with %@ base URL", baseURLString);
_manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:baseURLString]];
_manager.requestSerializer = [AFJSONRequestSerializer new];
[_manager.requestSerializer setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
self.backgroundQueue = [NSOperationQueue new];
self.dateFormatter = [[NSDateFormatter alloc] init];
self.dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
[self.dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
_urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
}
return self;
}
-(AFHTTPSessionManager *) manager {
NSString *username = [SAMKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier] account:@"com.juick.username"];
if (username) {
[_manager.requestSerializer
setAuthorizationHeaderFieldWithUsername:username
password:[SAMKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier] account:@"com.juick.password"]];
}
return _manager;
}
-(void) pullNextFromPath:(NSString *)path params:(NSDictionary *) params callback:(void(^)(NSArray<Message *> *, NSError *))callback {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self.backgroundQueue addOperationWithBlock:^{
[self.manager GET:path parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSInteger statusCode = [((NSHTTPURLResponse *) task.response) statusCode];
if (statusCode == 200) {
NSMutableArray *messages = [NSMutableArray new];
[((NSArray *)responseObject) enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[messages addObject:[Message fromJSON:obj]];
}];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(messages, nil);
}];
} else {
callback(nil, [NSError errorWithDomain:@"JuickErrorDomain" code:statusCode userInfo:nil]);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"REST Error: %@", error);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSInteger statusCode = ((NSHTTPURLResponse *)task.response).statusCode;
callback(nil, [NSError errorWithDomain:@"JuickErrorDomain" code:statusCode userInfo:nil]);
}];
}];
}];
});
}
-(void) postMessage:(NSString *)text result:(void (^)(Message *, NSError *))callback {
[self.backgroundQueue addOperationWithBlock:^{
[self.manager POST:@"post" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFormData:[text dataUsingEncoding:NSUTF8StringEncoding] name:@"body"];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"Success!");
Message *result = [Message fromJSON:responseObject];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(result, nil);
}];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", [error localizedDescription]);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(nil, error);
}];
}];
}];
}
-(void) postReplyToThread:(NSNumber *)mid inReplyTo:(NSNumber *)rid text:(NSString *)text result:(void(^)(Message *, NSError *))callback {
[self.backgroundQueue addOperationWithBlock:^{
[self.manager POST:@"comment" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFormData:[[mid stringValue] dataUsingEncoding:NSUTF8StringEncoding] name:@"mid"];
[formData appendPartWithFormData:[[NSString stringWithFormat:@"%d", [rid intValue]] dataUsingEncoding:NSUTF8StringEncoding] name:@"rid"];
[formData appendPartWithFormData:[text dataUsingEncoding:NSUTF8StringEncoding] name:@"body"];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"Success!");
Message *reply = [Message fromJSON:responseObject];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(reply, nil);
}];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", [error localizedDescription]);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(nil, error);
}];
}];
}];
}
-(void) postPMToUser:(NSString *)uname text:(NSString *)text result:(void (^)(NSError *))callback {
[self.backgroundQueue addOperationWithBlock:^{
[self.manager POST:@"pm" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
[formData appendPartWithFormData:[text dataUsingEncoding:NSUTF8StringEncoding] name:@"body"];
[formData appendPartWithFormData:[uname dataUsingEncoding:NSUTF8StringEncoding] name:@"uname"];
} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(nil);
}];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", [error localizedDescription]);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(error);
}];
}];
}];
}
-(void) fetchChats:(void (^)(NSArray *, NSError *))callback {
[self.backgroundQueue addOperationWithBlock:^{
[self.manager GET:@"groups_pms" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSMutableArray *groups = [NSMutableArray new];
NSArray *pms = [(NSDictionary *)responseObject objectForKey:@"pms"];
[pms enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[groups addObject:[Chat fromJSON:obj]];
}];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(groups, nil);
}];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", [error localizedDescription]);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(nil, error);
}];
}];
}];
}
-(void) fetchChatWithUser:(NSString *)uname callback:(void (^)(NSArray *, NSError *))callback {
NSDictionary *params = @{@"uname": uname};
[self.backgroundQueue addOperationWithBlock:^{
[self.manager GET:@"pm" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSMutableArray *messages = [NSMutableArray new];
NSArray *messagesList = (NSArray *)responseObject;
[messagesList enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[messages addObject:[Message fromJSON:obj]];
}];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(messages, nil);
}];
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Error: %@", [error localizedDescription]);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(nil, error);
}];
}];
}];
}
-(void) authenticate:(void (^)(User *user, NSError *error))callback {
[self.manager GET:@"me" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *username = [SAMKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier] account:@"com.juick.username"];
NSString *password = [SAMKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier] account:@"com.juick.password"];
[self.manager.requestSerializer setAuthorizationHeaderFieldWithUsername:username password:password];
callback([User fromJSON:responseObject], nil);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
[self.manager.requestSerializer clearAuthorizationHeader];
callback(nil, error);
}];
}
-(void) getUserByName:(NSString *) name callback:(void(^)(User *))callback {
NSDictionary *params = @{@"uname": name};
[self.manager GET:@"users" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
callback([User fromJSON:[(NSArray *)responseObject firstObject]]);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
callback(nil);
}];
}
-(void) refreshDeviceRegistration:(DeviceRegistration *)registrationData callback:(void (^)(BOOL))callback {
[self.manager PUT:@"/notifications" parameters:@[[registrationData toJSON]] success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
callback(YES);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"fail %@", [error localizedDescription]);
callback(NO);
} ];
}
-(BOOL) isAuthenticated {
NSString *password = [SAMKeychain passwordForService:[[NSBundle mainBundle] bundleIdentifier] account:@"com.juick.password"];
return password != nil;
}
- (void)fetchImageWithURL:(NSURL *)url callback:(void (^)(NSData *))callback {
NSURLSessionDataTask *dataTask = [self.urlSession dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
callback(data);
}];
}];
[self.backgroundQueue addOperationWithBlock:^{
[dataTask resume];
}];
}
+(NSString *) messagesUrl {
return @"messages";
}
+(NSString *) discussionsUrl {
return @"messages/discussions";
}
+(NSString *) threadUrl {
return @"thread";
}
+(NSString *) feedUrl {
return @"home";
}
@end
|