blob: 170720172400ae0a5f2f79d15d85f2d9ccdba32a [file] [log] [blame]
tkchin@webrtc.org87776a82014-12-09 19:32:35 +00001/*
2 * libjingle
3 * Copyright 2014, 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 "ARDWebSocketChannel.h"
29
30#import "ARDUtilities.h"
31#import "SRWebSocket.h"
32
33// TODO(tkchin): move these to a configuration object.
34static NSString const *kARDWSSMessageErrorKey = @"error";
35static NSString const *kARDWSSMessagePayloadKey = @"msg";
36
37@interface ARDWebSocketChannel () <SRWebSocketDelegate>
38@end
39
40@implementation ARDWebSocketChannel {
41 NSURL *_url;
42 NSURL *_restURL;
43 SRWebSocket *_socket;
44}
45
46@synthesize delegate = _delegate;
47@synthesize state = _state;
48@synthesize roomId = _roomId;
49@synthesize clientId = _clientId;
50
51- (instancetype)initWithURL:(NSURL *)url
52 restURL:(NSURL *)restURL
53 delegate:(id<ARDWebSocketChannelDelegate>)delegate {
54 if (self = [super init]) {
55 _url = url;
56 _restURL = restURL;
57 _delegate = delegate;
58 _socket = [[SRWebSocket alloc] initWithURL:url];
59 _socket.delegate = self;
60 NSLog(@"Opening WebSocket.");
61 [_socket open];
62 }
63 return self;
64}
65
66- (void)dealloc {
67 [self disconnect];
68}
69
70- (void)setState:(ARDWebSocketChannelState)state {
71 if (_state == state) {
72 return;
73 }
74 _state = state;
75 [_delegate channel:self didChangeState:_state];
76}
77
78- (void)registerForRoomId:(NSString *)roomId
79 clientId:(NSString *)clientId {
80 NSParameterAssert(roomId.length);
81 NSParameterAssert(clientId.length);
82 _roomId = roomId;
83 _clientId = clientId;
84 if (_state == kARDWebSocketChannelStateOpen) {
85 [self registerWithCollider];
86 }
87}
88
89- (void)sendData:(NSData *)data {
90 NSParameterAssert(_clientId.length);
91 NSParameterAssert(_roomId.length);
92 if (_state == kARDWebSocketChannelStateRegistered) {
93 NSString *payload =
94 [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
95 NSDictionary *message = @{
96 @"cmd": @"send",
97 @"msg": payload,
98 };
99 NSData *messageJSONObject =
100 [NSJSONSerialization dataWithJSONObject:message
101 options:NSJSONWritingPrettyPrinted
102 error:nil];
103 NSString *messageString =
104 [[NSString alloc] initWithData:messageJSONObject
105 encoding:NSUTF8StringEncoding];
106 NSLog(@"C->WSS: %@", messageString);
107 [_socket send:messageString];
108 } else {
109 NSString *dataString =
110 [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
111 NSLog(@"C->WSS POST: %@", dataString);
112 NSString *urlString =
113 [NSString stringWithFormat:@"%@/%@/%@",
114 [_restURL absoluteString], _roomId, _clientId];
115 NSURL *url = [NSURL URLWithString:urlString];
116 [NSURLConnection sendAsyncPostToURL:url
117 withData:data
118 completionHandler:nil];
119 }
120}
121
122- (void)disconnect {
123 if (_state == kARDWebSocketChannelStateClosed ||
124 _state == kARDWebSocketChannelStateError) {
125 return;
126 }
127 [_socket close];
128 NSLog(@"C->WSS DELETE rid:%@ cid:%@", _roomId, _clientId);
129 NSString *urlString =
130 [NSString stringWithFormat:@"%@/%@/%@",
131 [_restURL absoluteString], _roomId, _clientId];
132 NSURL *url = [NSURL URLWithString:urlString];
133 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
134 request.HTTPMethod = @"DELETE";
135 request.HTTPBody = nil;
136 [NSURLConnection sendAsyncRequest:request completionHandler:nil];
137}
138
139#pragma mark - SRWebSocketDelegate
140
141- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
142 NSLog(@"WebSocket connection opened.");
143 self.state = kARDWebSocketChannelStateOpen;
144 if (_roomId.length && _clientId.length) {
145 [self registerWithCollider];
146 }
147}
148
149- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
150 NSString *messageString = message;
151 NSData *messageData = [messageString dataUsingEncoding:NSUTF8StringEncoding];
152 id jsonObject = [NSJSONSerialization JSONObjectWithData:messageData
153 options:0
154 error:nil];
155 if (![jsonObject isKindOfClass:[NSDictionary class]]) {
156 NSLog(@"Unexpected message: %@", jsonObject);
157 return;
158 }
159 NSDictionary *wssMessage = jsonObject;
160 NSString *errorString = wssMessage[kARDWSSMessageErrorKey];
161 if (errorString.length) {
162 NSLog(@"WSS error: %@", errorString);
163 return;
164 }
165 NSString *payload = wssMessage[kARDWSSMessagePayloadKey];
166 ARDSignalingMessage *signalingMessage =
167 [ARDSignalingMessage messageFromJSONString:payload];
168 NSLog(@"WSS->C: %@", payload);
169 [_delegate channel:self didReceiveMessage:signalingMessage];
170}
171
172- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
173 NSLog(@"WebSocket error: %@", error);
174 self.state = kARDWebSocketChannelStateError;
175}
176
177- (void)webSocket:(SRWebSocket *)webSocket
178 didCloseWithCode:(NSInteger)code
179 reason:(NSString *)reason
180 wasClean:(BOOL)wasClean {
181 NSLog(@"WebSocket closed with code: %ld reason:%@ wasClean:%d",
182 (long)code, reason, wasClean);
183 NSParameterAssert(_state != kARDWebSocketChannelStateError);
184 self.state = kARDWebSocketChannelStateClosed;
185}
186
187#pragma mark - Private
188
189- (void)registerWithCollider {
190 if (_state == kARDWebSocketChannelStateRegistered) {
191 return;
192 }
193 NSParameterAssert(_roomId.length);
194 NSParameterAssert(_clientId.length);
195 NSDictionary *registerMessage = @{
196 @"cmd": @"register",
197 @"roomid" : _roomId,
198 @"clientid" : _clientId,
199 };
200 NSData *message =
201 [NSJSONSerialization dataWithJSONObject:registerMessage
202 options:NSJSONWritingPrettyPrinted
203 error:nil];
204 NSString *messageString =
205 [[NSString alloc] initWithData:message encoding:NSUTF8StringEncoding];
206 NSLog(@"Registering on WSS for rid:%@ cid:%@", _roomId, _clientId);
207 // Registration can fail if server rejects it. For example, if the room is
208 // full.
209 [_socket send:messageString];
210 self.state = kARDWebSocketChannelStateRegistered;
211}
212
213@end