blob: d6c86d8422fa03f8ba6a089616ddc8577bae30a1 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2013, Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#import "APPRTCAppClient.h"
29
30#import <dispatch/dispatch.h>
31
32#import "GAEChannelClient.h"
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000033#import "RTCICEServer.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000034
35@interface APPRTCAppClient ()
36
fischman@webrtc.orgd0f4c212013-08-20 22:16:55 +000037@property(nonatomic, strong) dispatch_queue_t backgroundQueue;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000038@property(nonatomic, copy) NSString *baseURL;
39@property(nonatomic, strong) GAEChannelClient *gaeChannel;
40@property(nonatomic, copy) NSString *postMessageUrl;
41@property(nonatomic, copy) NSString *pcConfig;
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000042@property(nonatomic, strong) NSMutableString *roomHtml;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000043@property(atomic, strong) NSMutableArray *sendQueue;
44@property(nonatomic, copy) NSString *token;
45
46@property(nonatomic, assign) BOOL verboseLogging;
47
48@end
49
50@implementation APPRTCAppClient
51
fischman@webrtc.org9ca93a82013-10-29 00:14:15 +000052@synthesize ICEServerDelegate = _ICEServerDelegate;
53@synthesize messageHandler = _messageHandler;
54
55@synthesize backgroundQueue = _backgroundQueue;
56@synthesize baseURL = _baseURL;
57@synthesize gaeChannel = _gaeChannel;
58@synthesize postMessageUrl = _postMessageUrl;
59@synthesize pcConfig = _pcConfig;
60@synthesize roomHtml = _roomHtml;
61@synthesize sendQueue = _sendQueue;
62@synthesize token = _token;
63@synthesize verboseLogging = _verboseLogging;
64
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065- (id)init {
66 if (self = [super init]) {
67 _backgroundQueue = dispatch_queue_create("RTCBackgroundQueue", NULL);
68 _sendQueue = [NSMutableArray array];
69 // Uncomment to see Request/Response logging.
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000070 // _verboseLogging = YES;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071 }
72 return self;
73}
74
75#pragma mark - Public methods
76
77- (void)connectToRoom:(NSURL *)url {
78 NSURLRequest *request = [self getRequestFromUrl:url];
79 [NSURLConnection connectionWithRequest:request delegate:self];
80}
81
82- (void)sendData:(NSData *)data {
83 @synchronized(self) {
84 [self maybeLogMessage:@"Send message"];
85 [self.sendQueue addObject:[data copy]];
86 }
87 [self requestQueueDrainInBackground];
88}
89
90#pragma mark - Internal methods
91
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000092- (NSString*)findVar:(NSString*)name
93 strippingQuotes:(BOOL)strippingQuotes {
94 NSError* error;
95 NSString* pattern =
96 [NSString stringWithFormat:@".*\n *var %@ = ([^\n]*);\n.*", name];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097 NSRegularExpression *regexp =
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000098 [NSRegularExpression regularExpressionWithPattern:pattern
henrike@webrtc.org28e20752013-07-10 00:45:36 +000099 options:0
100 error:&error];
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000101 NSAssert(!error, @"Unexpected error compiling regex: ",
102 error.localizedDescription);
103
104 NSRange fullRange = NSMakeRange(0, [self.roomHtml length]);
105 NSArray *matches =
106 [regexp matchesInString:self.roomHtml options:0 range:fullRange];
107 if ([matches count] != 1) {
108 [self showMessage:[NSString stringWithFormat:@"%d matches for %@ in %@",
109 [matches count], name, self.roomHtml]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 return nil;
111 }
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000112 NSRange matchRange = [matches[0] rangeAtIndex:1];
113 NSString* value = [self.roomHtml substringWithRange:matchRange];
114 if (strippingQuotes) {
115 NSAssert([value length] > 2,
116 @"Can't strip quotes from short string: [%@]", value);
117 NSAssert(([value characterAtIndex:0] == '\'' &&
118 [value characterAtIndex:[value length] - 1] == '\''),
119 @"Can't strip quotes from unquoted string: [%@]", value);
120 value = [value substringWithRange:NSMakeRange(1, [value length] - 2)];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000121 }
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000122 return value;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000123}
124
125- (NSURLRequest *)getRequestFromUrl:(NSURL *)url {
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000126 self.roomHtml = [NSMutableString stringWithCapacity:20000];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000127 NSString *path =
128 [NSString stringWithFormat:@"https:%@", [url resourceSpecifier]];
129 NSURLRequest *request =
130 [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
131 return request;
132}
133
134- (void)maybeLogMessage:(NSString *)message {
135 if (self.verboseLogging) {
136 NSLog(@"%@", message);
137 }
138}
139
140- (void)requestQueueDrainInBackground {
141 dispatch_async(self.backgroundQueue, ^(void) {
142 // TODO(hughv): This can block the UI thread. Fix.
143 @synchronized(self) {
144 if ([self.postMessageUrl length] < 1) {
145 return;
146 }
147 for (NSData *data in self.sendQueue) {
148 NSString *url = [NSString stringWithFormat:@"%@/%@",
149 self.baseURL,
150 self.postMessageUrl];
151 [self sendData:data withUrl:url];
152 }
153 [self.sendQueue removeAllObjects];
154 }
155 });
156}
157
158- (void)sendData:(NSData *)data withUrl:(NSString *)url {
159 NSMutableURLRequest *request =
160 [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
161 request.HTTPMethod = @"POST";
162 [request setHTTPBody:data];
163 NSURLResponse *response;
164 NSError *error;
165 NSData *responseData = [NSURLConnection sendSynchronousRequest:request
166 returningResponse:&response
167 error:&error];
168 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
169 int status = [httpResponse statusCode];
170 NSAssert(status == 200,
171 @"Bad response [%d] to message: %@\n\n%@",
172 status,
173 [NSString stringWithUTF8String:[data bytes]],
174 [NSString stringWithUTF8String:[responseData bytes]]);
175}
176
177- (void)showMessage:(NSString *)message {
178 NSLog(@"%@", message);
179 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Unable to join"
180 message:message
181 delegate:nil
182 cancelButtonTitle:@"OK"
183 otherButtonTitles:nil];
184 [alertView show];
185}
186
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000187- (void)updateICEServers:(NSMutableArray *)ICEServers
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000188 withTurnServer:(NSString *)turnServerUrl {
189 if ([turnServerUrl length] < 1) {
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000190 [self.ICEServerDelegate onICEServers:ICEServers];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000191 return;
192 }
193 dispatch_async(self.backgroundQueue, ^(void) {
194 NSMutableURLRequest *request = [NSMutableURLRequest
195 requestWithURL:[NSURL URLWithString:turnServerUrl]];
196 [request addValue:@"Mozilla/5.0" forHTTPHeaderField:@"user-agent"];
197 [request addValue:@"https://apprtc.appspot.com"
198 forHTTPHeaderField:@"origin"];
199 NSURLResponse *response;
200 NSError *error;
201 NSData *responseData = [NSURLConnection sendSynchronousRequest:request
202 returningResponse:&response
203 error:&error];
204 if (!error) {
205 NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
206 options:0
207 error:&error];
208 NSAssert(!error, @"Unable to parse. %@", error.localizedDescription);
209 NSString *username = json[@"username"];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000210 NSString *password = json[@"password"];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000211 NSArray* uris = json[@"uris"];
212 for (int i = 0; i < [uris count]; ++i) {
213 NSString *turnServer = [uris objectAtIndex:i];
214 RTCICEServer *ICEServer =
215 [[RTCICEServer alloc] initWithURI:[NSURL URLWithString:turnServer]
216 username:username
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000217 password:password];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000218 NSLog(@"Added ICE Server: %@", ICEServer);
219 [ICEServers addObject:ICEServer];
220 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000221 } else {
222 NSLog(@"Unable to get TURN server. Error: %@", error.description);
223 }
224
225 dispatch_async(dispatch_get_main_queue(), ^(void) {
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000226 [self.ICEServerDelegate onICEServers:ICEServers];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000227 });
228 });
229}
230
231#pragma mark - NSURLConnectionDataDelegate methods
232
233- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
234 NSString *roomHtml = [NSString stringWithUTF8String:[data bytes]];
235 [self maybeLogMessage:
236 [NSString stringWithFormat:@"Received %d chars", [roomHtml length]]];
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000237 [self.roomHtml appendString:roomHtml];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000238}
239
240- (void)connection:(NSURLConnection *)connection
241 didReceiveResponse:(NSURLResponse *)response {
242 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
243 int statusCode = [httpResponse statusCode];
244 [self maybeLogMessage:
245 [NSString stringWithFormat:
246 @"Response received\nURL\n%@\nStatus [%d]\nHeaders\n%@",
247 [httpResponse URL],
248 statusCode,
249 [httpResponse allHeaderFields]]];
250 NSAssert(statusCode == 200, @"Invalid response of %d received.", statusCode);
251}
252
253- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
254 [self maybeLogMessage:[NSString stringWithFormat:@"finished loading %d chars",
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000255 [self.roomHtml length]]];
256 NSRegularExpression* fullRegex =
257 [NSRegularExpression regularExpressionWithPattern:@"room is full"
258 options:0
259 error:nil];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000260 if ([fullRegex
261 numberOfMatchesInString:self.roomHtml
262 options:0
263 range:NSMakeRange(0, [self.roomHtml length])]) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000264 [self showMessage:@"Room full"];
265 return;
266 }
267
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000268
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000269 NSString *fullUrl = [[[connection originalRequest] URL] absoluteString];
270 NSRange queryRange = [fullUrl rangeOfString:@"?"];
271 self.baseURL = [fullUrl substringToIndex:queryRange.location];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000272 [self maybeLogMessage:
273 [NSString stringWithFormat:@"Base URL: %@", self.baseURL]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000274
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000275 self.token = [self findVar:@"channelToken" strippingQuotes:YES];
276 if (!self.token)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000277 return;
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000278 [self maybeLogMessage:[NSString stringWithFormat:@"Token: %@", self.token]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000279
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000280 NSString* roomKey = [self findVar:@"roomKey" strippingQuotes:YES];
281 NSString* me = [self findVar:@"me" strippingQuotes:YES];
282 if (!roomKey || !me)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000283 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000284 self.postMessageUrl =
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000285 [NSString stringWithFormat:@"/message?r=%@&u=%@", roomKey, me];
286 [self maybeLogMessage:[NSString stringWithFormat:@"POST message URL: %@",
287 self.postMessageUrl]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000288
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000289 NSString* pcConfig = [self findVar:@"pcConfig" strippingQuotes:NO];
290 if (!pcConfig)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000291 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000292 [self maybeLogMessage:
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000293 [NSString stringWithFormat:@"PC Config JSON: %@", pcConfig]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000294
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000295 NSString *turnServerUrl = [self findVar:@"turnUrl" strippingQuotes:YES];
296 if (turnServerUrl) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000297 [self maybeLogMessage:
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000298 [NSString stringWithFormat:@"TURN server request URL: %@",
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000299 turnServerUrl]];
300 }
301
302 NSError *error;
303 NSData *pcData = [pcConfig dataUsingEncoding:NSUTF8StringEncoding];
304 NSDictionary *json =
305 [NSJSONSerialization JSONObjectWithData:pcData options:0 error:&error];
306 NSAssert(!error, @"Unable to parse. %@", error.localizedDescription);
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000307 NSArray *servers = [json objectForKey:@"iceServers"];
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000308 NSMutableArray *ICEServers = [NSMutableArray array];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000309 for (NSDictionary *server in servers) {
310 NSString *url = [server objectForKey:@"url"];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000311 NSString *username = json[@"username"];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000312 NSString *credential = [server objectForKey:@"credential"];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000313 if (!username) {
314 username = @"";
315 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000316 if (!credential) {
317 credential = @"";
318 }
319 [self maybeLogMessage:
320 [NSString stringWithFormat:@"url [%@] - credential [%@]",
321 url,
322 credential]];
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000323 RTCICEServer *ICEServer =
324 [[RTCICEServer alloc] initWithURI:[NSURL URLWithString:url]
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000325 username:username
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000326 password:credential];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000327 NSLog(@"Added ICE Server: %@", ICEServer);
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000328 [ICEServers addObject:ICEServer];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000329 }
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000330 [self updateICEServers:ICEServers withTurnServer:turnServerUrl];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000331
332 [self maybeLogMessage:
333 [NSString stringWithFormat:@"About to open GAE with token: %@",
334 self.token]];
335 self.gaeChannel =
336 [[GAEChannelClient alloc] initWithToken:self.token
337 delegate:self.messageHandler];
338}
339
340@end