blob: 99f5166669bf1dd4f47815ec13b9cb09a055a1ec [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
52- (id)init {
53 if (self = [super init]) {
54 _backgroundQueue = dispatch_queue_create("RTCBackgroundQueue", NULL);
55 _sendQueue = [NSMutableArray array];
56 // Uncomment to see Request/Response logging.
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000057 // _verboseLogging = YES;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058 }
59 return self;
60}
61
62#pragma mark - Public methods
63
64- (void)connectToRoom:(NSURL *)url {
65 NSURLRequest *request = [self getRequestFromUrl:url];
66 [NSURLConnection connectionWithRequest:request delegate:self];
67}
68
69- (void)sendData:(NSData *)data {
70 @synchronized(self) {
71 [self maybeLogMessage:@"Send message"];
72 [self.sendQueue addObject:[data copy]];
73 }
74 [self requestQueueDrainInBackground];
75}
76
77#pragma mark - Internal methods
78
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000079- (NSString*)findVar:(NSString*)name
80 strippingQuotes:(BOOL)strippingQuotes {
81 NSError* error;
82 NSString* pattern =
83 [NSString stringWithFormat:@".*\n *var %@ = ([^\n]*);\n.*", name];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000084 NSRegularExpression *regexp =
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000085 [NSRegularExpression regularExpressionWithPattern:pattern
henrike@webrtc.org28e20752013-07-10 00:45:36 +000086 options:0
87 error:&error];
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000088 NSAssert(!error, @"Unexpected error compiling regex: ",
89 error.localizedDescription);
90
91 NSRange fullRange = NSMakeRange(0, [self.roomHtml length]);
92 NSArray *matches =
93 [regexp matchesInString:self.roomHtml options:0 range:fullRange];
94 if ([matches count] != 1) {
95 [self showMessage:[NSString stringWithFormat:@"%d matches for %@ in %@",
96 [matches count], name, self.roomHtml]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097 return nil;
98 }
fischman@webrtc.org1bc19542013-08-01 18:29:45 +000099 NSRange matchRange = [matches[0] rangeAtIndex:1];
100 NSString* value = [self.roomHtml substringWithRange:matchRange];
101 if (strippingQuotes) {
102 NSAssert([value length] > 2,
103 @"Can't strip quotes from short string: [%@]", value);
104 NSAssert(([value characterAtIndex:0] == '\'' &&
105 [value characterAtIndex:[value length] - 1] == '\''),
106 @"Can't strip quotes from unquoted string: [%@]", value);
107 value = [value substringWithRange:NSMakeRange(1, [value length] - 2)];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108 }
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000109 return value;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110}
111
112- (NSURLRequest *)getRequestFromUrl:(NSURL *)url {
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000113 self.roomHtml = [NSMutableString stringWithCapacity:20000];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114 NSString *path =
115 [NSString stringWithFormat:@"https:%@", [url resourceSpecifier]];
116 NSURLRequest *request =
117 [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
118 return request;
119}
120
121- (void)maybeLogMessage:(NSString *)message {
122 if (self.verboseLogging) {
123 NSLog(@"%@", message);
124 }
125}
126
127- (void)requestQueueDrainInBackground {
128 dispatch_async(self.backgroundQueue, ^(void) {
129 // TODO(hughv): This can block the UI thread. Fix.
130 @synchronized(self) {
131 if ([self.postMessageUrl length] < 1) {
132 return;
133 }
134 for (NSData *data in self.sendQueue) {
135 NSString *url = [NSString stringWithFormat:@"%@/%@",
136 self.baseURL,
137 self.postMessageUrl];
138 [self sendData:data withUrl:url];
139 }
140 [self.sendQueue removeAllObjects];
141 }
142 });
143}
144
145- (void)sendData:(NSData *)data withUrl:(NSString *)url {
146 NSMutableURLRequest *request =
147 [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
148 request.HTTPMethod = @"POST";
149 [request setHTTPBody:data];
150 NSURLResponse *response;
151 NSError *error;
152 NSData *responseData = [NSURLConnection sendSynchronousRequest:request
153 returningResponse:&response
154 error:&error];
155 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
156 int status = [httpResponse statusCode];
157 NSAssert(status == 200,
158 @"Bad response [%d] to message: %@\n\n%@",
159 status,
160 [NSString stringWithUTF8String:[data bytes]],
161 [NSString stringWithUTF8String:[responseData bytes]]);
162}
163
164- (void)showMessage:(NSString *)message {
165 NSLog(@"%@", message);
166 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Unable to join"
167 message:message
168 delegate:nil
169 cancelButtonTitle:@"OK"
170 otherButtonTitles:nil];
171 [alertView show];
172}
173
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000174- (void)updateICEServers:(NSMutableArray *)ICEServers
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000175 withTurnServer:(NSString *)turnServerUrl {
176 if ([turnServerUrl length] < 1) {
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000177 [self.ICEServerDelegate onICEServers:ICEServers];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000178 return;
179 }
180 dispatch_async(self.backgroundQueue, ^(void) {
181 NSMutableURLRequest *request = [NSMutableURLRequest
182 requestWithURL:[NSURL URLWithString:turnServerUrl]];
183 [request addValue:@"Mozilla/5.0" forHTTPHeaderField:@"user-agent"];
184 [request addValue:@"https://apprtc.appspot.com"
185 forHTTPHeaderField:@"origin"];
186 NSURLResponse *response;
187 NSError *error;
188 NSData *responseData = [NSURLConnection sendSynchronousRequest:request
189 returningResponse:&response
190 error:&error];
191 if (!error) {
192 NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
193 options:0
194 error:&error];
195 NSAssert(!error, @"Unable to parse. %@", error.localizedDescription);
196 NSString *username = json[@"username"];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000197 NSString *password = json[@"password"];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000198 NSArray* uris = json[@"uris"];
199 for (int i = 0; i < [uris count]; ++i) {
200 NSString *turnServer = [uris objectAtIndex:i];
201 RTCICEServer *ICEServer =
202 [[RTCICEServer alloc] initWithURI:[NSURL URLWithString:turnServer]
203 username:username
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000204 password:password];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000205 NSLog(@"Added ICE Server: %@", ICEServer);
206 [ICEServers addObject:ICEServer];
207 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000208 } else {
209 NSLog(@"Unable to get TURN server. Error: %@", error.description);
210 }
211
212 dispatch_async(dispatch_get_main_queue(), ^(void) {
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000213 [self.ICEServerDelegate onICEServers:ICEServers];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000214 });
215 });
216}
217
218#pragma mark - NSURLConnectionDataDelegate methods
219
220- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
221 NSString *roomHtml = [NSString stringWithUTF8String:[data bytes]];
222 [self maybeLogMessage:
223 [NSString stringWithFormat:@"Received %d chars", [roomHtml length]]];
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000224 [self.roomHtml appendString:roomHtml];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000225}
226
227- (void)connection:(NSURLConnection *)connection
228 didReceiveResponse:(NSURLResponse *)response {
229 NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
230 int statusCode = [httpResponse statusCode];
231 [self maybeLogMessage:
232 [NSString stringWithFormat:
233 @"Response received\nURL\n%@\nStatus [%d]\nHeaders\n%@",
234 [httpResponse URL],
235 statusCode,
236 [httpResponse allHeaderFields]]];
237 NSAssert(statusCode == 200, @"Invalid response of %d received.", statusCode);
238}
239
240- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
241 [self maybeLogMessage:[NSString stringWithFormat:@"finished loading %d chars",
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000242 [self.roomHtml length]]];
243 NSRegularExpression* fullRegex =
244 [NSRegularExpression regularExpressionWithPattern:@"room is full"
245 options:0
246 error:nil];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000247 if ([fullRegex
248 numberOfMatchesInString:self.roomHtml
249 options:0
250 range:NSMakeRange(0, [self.roomHtml length])]) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000251 [self showMessage:@"Room full"];
252 return;
253 }
254
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000255
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000256 NSString *fullUrl = [[[connection originalRequest] URL] absoluteString];
257 NSRange queryRange = [fullUrl rangeOfString:@"?"];
258 self.baseURL = [fullUrl substringToIndex:queryRange.location];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000259 [self maybeLogMessage:
260 [NSString stringWithFormat:@"Base URL: %@", self.baseURL]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000261
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000262 self.token = [self findVar:@"channelToken" strippingQuotes:YES];
263 if (!self.token)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000264 return;
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000265 [self maybeLogMessage:[NSString stringWithFormat:@"Token: %@", self.token]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000266
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000267 NSString* roomKey = [self findVar:@"roomKey" strippingQuotes:YES];
268 NSString* me = [self findVar:@"me" strippingQuotes:YES];
269 if (!roomKey || !me)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000270 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271 self.postMessageUrl =
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000272 [NSString stringWithFormat:@"/message?r=%@&u=%@", roomKey, me];
273 [self maybeLogMessage:[NSString stringWithFormat:@"POST message URL: %@",
274 self.postMessageUrl]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000275
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000276 NSString* pcConfig = [self findVar:@"pcConfig" strippingQuotes:NO];
277 if (!pcConfig)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000278 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000279 [self maybeLogMessage:
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000280 [NSString stringWithFormat:@"PC Config JSON: %@", pcConfig]];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000281
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000282 NSString *turnServerUrl = [self findVar:@"turnUrl" strippingQuotes:YES];
283 if (turnServerUrl) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000284 [self maybeLogMessage:
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000285 [NSString stringWithFormat:@"TURN server request URL: %@",
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000286 turnServerUrl]];
287 }
288
289 NSError *error;
290 NSData *pcData = [pcConfig dataUsingEncoding:NSUTF8StringEncoding];
291 NSDictionary *json =
292 [NSJSONSerialization JSONObjectWithData:pcData options:0 error:&error];
293 NSAssert(!error, @"Unable to parse. %@", error.localizedDescription);
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000294 NSArray *servers = [json objectForKey:@"iceServers"];
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000295 NSMutableArray *ICEServers = [NSMutableArray array];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000296 for (NSDictionary *server in servers) {
297 NSString *url = [server objectForKey:@"url"];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000298 NSString *username = json[@"username"];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000299 NSString *credential = [server objectForKey:@"credential"];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000300 if (!username) {
301 username = @"";
302 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000303 if (!credential) {
304 credential = @"";
305 }
306 [self maybeLogMessage:
307 [NSString stringWithFormat:@"url [%@] - credential [%@]",
308 url,
309 credential]];
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000310 RTCICEServer *ICEServer =
311 [[RTCICEServer alloc] initWithURI:[NSURL URLWithString:url]
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000312 username:username
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000313 password:credential];
fischman@webrtc.orgc31d4d02013-09-05 21:49:58 +0000314 NSLog(@"Added ICE Server: %@", ICEServer);
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000315 [ICEServers addObject:ICEServer];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000316 }
fischman@webrtc.org1bc19542013-08-01 18:29:45 +0000317 [self updateICEServers:ICEServers withTurnServer:turnServerUrl];
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000318
319 [self maybeLogMessage:
320 [NSString stringWithFormat:@"About to open GAE with token: %@",
321 self.token]];
322 self.gaeChannel =
323 [[GAEChannelClient alloc] initWithToken:self.token
324 delegate:self.messageHandler];
325}
326
327@end