You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

251 lines
8.0 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2014 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #import "ARDWebSocketChannel.h"
  11. #import <WebRTC/RTCLogging.h>
  12. #import "SRWebSocket.h"
  13. #import "ARDSignalingMessage.h"
  14. #import "ARDUtilities.h"
  15. // TODO(tkchin): move these to a configuration object.
  16. static NSString const *kARDWSSMessageErrorKey = @"error";
  17. static NSString const *kARDWSSMessagePayloadKey = @"msg";
  18. @interface ARDWebSocketChannel () <SRWebSocketDelegate>
  19. @end
  20. @implementation ARDWebSocketChannel {
  21. NSURL *_url;
  22. NSURL *_restURL;
  23. SRWebSocket *_socket;
  24. }
  25. @synthesize delegate = _delegate;
  26. @synthesize state = _state;
  27. @synthesize roomId = _roomId;
  28. @synthesize clientId = _clientId;
  29. - (instancetype)initWithURL:(NSURL *)url
  30. restURL:(NSURL *)restURL
  31. delegate:(id<ARDSignalingChannelDelegate>)delegate {
  32. if (self = [super init]) {
  33. _url = url;
  34. _restURL = restURL;
  35. _delegate = delegate;
  36. _socket = [[SRWebSocket alloc] initWithURL:url];
  37. _socket.delegate = self;
  38. RTCLog(@"Opening WebSocket.");
  39. [_socket open];
  40. }
  41. return self;
  42. }
  43. - (void)dealloc {
  44. [self disconnect];
  45. }
  46. - (void)setState:(ARDSignalingChannelState)state {
  47. if (_state == state) {
  48. return;
  49. }
  50. _state = state;
  51. [_delegate channel:self didChangeState:_state];
  52. }
  53. - (void)registerForRoomId:(NSString *)roomId
  54. clientId:(NSString *)clientId {
  55. NSParameterAssert(roomId.length);
  56. NSParameterAssert(clientId.length);
  57. _roomId = roomId;
  58. _clientId = clientId;
  59. if (_state == kARDSignalingChannelStateOpen) {
  60. [self registerWithCollider];
  61. }
  62. }
  63. - (void)sendMessage:(ARDSignalingMessage *)message {
  64. NSParameterAssert(_clientId.length);
  65. NSParameterAssert(_roomId.length);
  66. NSData *data = [message JSONData];
  67. if (_state == kARDSignalingChannelStateRegistered) {
  68. NSString *payload =
  69. [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  70. NSDictionary *message = @{
  71. @"cmd": @"send",
  72. @"msg": payload,
  73. };
  74. NSData *messageJSONObject =
  75. [NSJSONSerialization dataWithJSONObject:message
  76. options:NSJSONWritingPrettyPrinted
  77. error:nil];
  78. NSString *messageString =
  79. [[NSString alloc] initWithData:messageJSONObject
  80. encoding:NSUTF8StringEncoding];
  81. RTCLog(@"C->WSS: %@", messageString);
  82. [_socket send:messageString];
  83. } else {
  84. NSString *dataString =
  85. [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  86. RTCLog(@"C->WSS POST: %@", dataString);
  87. NSString *urlString =
  88. [NSString stringWithFormat:@"%@/%@/%@",
  89. [_restURL absoluteString], _roomId, _clientId];
  90. NSURL *url = [NSURL URLWithString:urlString];
  91. [NSURLConnection sendAsyncPostToURL:url
  92. withData:data
  93. completionHandler:nil];
  94. }
  95. }
  96. - (void)disconnect {
  97. if (_state == kARDSignalingChannelStateClosed ||
  98. _state == kARDSignalingChannelStateError) {
  99. return;
  100. }
  101. [_socket close];
  102. RTCLog(@"C->WSS DELETE rid:%@ cid:%@", _roomId, _clientId);
  103. NSString *urlString =
  104. [NSString stringWithFormat:@"%@/%@/%@",
  105. [_restURL absoluteString], _roomId, _clientId];
  106. NSURL *url = [NSURL URLWithString:urlString];
  107. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  108. request.HTTPMethod = @"DELETE";
  109. request.HTTPBody = nil;
  110. [NSURLConnection sendAsyncRequest:request completionHandler:nil];
  111. }
  112. #pragma mark - SRWebSocketDelegate
  113. - (void)webSocketDidOpen:(SRWebSocket *)webSocket {
  114. RTCLog(@"WebSocket connection opened.");
  115. self.state = kARDSignalingChannelStateOpen;
  116. if (_roomId.length && _clientId.length) {
  117. [self registerWithCollider];
  118. }
  119. }
  120. - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message {
  121. NSString *messageString = message;
  122. NSData *messageData = [messageString dataUsingEncoding:NSUTF8StringEncoding];
  123. id jsonObject = [NSJSONSerialization JSONObjectWithData:messageData
  124. options:0
  125. error:nil];
  126. if (![jsonObject isKindOfClass:[NSDictionary class]]) {
  127. RTCLogError(@"Unexpected message: %@", jsonObject);
  128. return;
  129. }
  130. NSDictionary *wssMessage = jsonObject;
  131. NSString *errorString = wssMessage[kARDWSSMessageErrorKey];
  132. if (errorString.length) {
  133. RTCLogError(@"WSS error: %@", errorString);
  134. return;
  135. }
  136. NSString *payload = wssMessage[kARDWSSMessagePayloadKey];
  137. ARDSignalingMessage *signalingMessage =
  138. [ARDSignalingMessage messageFromJSONString:payload];
  139. RTCLog(@"WSS->C: %@", payload);
  140. [_delegate channel:self didReceiveMessage:signalingMessage];
  141. }
  142. - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error {
  143. RTCLogError(@"WebSocket error: %@", error);
  144. self.state = kARDSignalingChannelStateError;
  145. }
  146. - (void)webSocket:(SRWebSocket *)webSocket
  147. didCloseWithCode:(NSInteger)code
  148. reason:(NSString *)reason
  149. wasClean:(BOOL)wasClean {
  150. RTCLog(@"WebSocket closed with code: %ld reason:%@ wasClean:%d",
  151. (long)code, reason, wasClean);
  152. NSParameterAssert(_state != kARDSignalingChannelStateError);
  153. self.state = kARDSignalingChannelStateClosed;
  154. }
  155. #pragma mark - Private
  156. - (void)registerWithCollider {
  157. if (_state == kARDSignalingChannelStateRegistered) {
  158. return;
  159. }
  160. NSParameterAssert(_roomId.length);
  161. NSParameterAssert(_clientId.length);
  162. NSDictionary *registerMessage = @{
  163. @"cmd": @"register",
  164. @"roomid" : _roomId,
  165. @"clientid" : _clientId,
  166. };
  167. NSData *message =
  168. [NSJSONSerialization dataWithJSONObject:registerMessage
  169. options:NSJSONWritingPrettyPrinted
  170. error:nil];
  171. NSString *messageString =
  172. [[NSString alloc] initWithData:message encoding:NSUTF8StringEncoding];
  173. RTCLog(@"Registering on WSS for rid:%@ cid:%@", _roomId, _clientId);
  174. // Registration can fail if server rejects it. For example, if the room is
  175. // full.
  176. [_socket send:messageString];
  177. self.state = kARDSignalingChannelStateRegistered;
  178. }
  179. @end
  180. @interface ARDLoopbackWebSocketChannel () <ARDSignalingChannelDelegate>
  181. @end
  182. @implementation ARDLoopbackWebSocketChannel
  183. - (instancetype)initWithURL:(NSURL *)url restURL:(NSURL *)restURL {
  184. return [super initWithURL:url restURL:restURL delegate:self];
  185. }
  186. #pragma mark - ARDSignalingChannelDelegate
  187. - (void)channel:(id<ARDSignalingChannel>)channel
  188. didReceiveMessage:(ARDSignalingMessage *)message {
  189. switch (message.type) {
  190. case kARDSignalingMessageTypeOffer: {
  191. // Change message to answer, send back to server.
  192. ARDSessionDescriptionMessage *sdpMessage =
  193. (ARDSessionDescriptionMessage *)message;
  194. RTCSessionDescription *description = sdpMessage.sessionDescription;
  195. NSString *dsc = description.sdp;
  196. dsc = [dsc stringByReplacingOccurrencesOfString:@"offer"
  197. withString:@"answer"];
  198. RTCSessionDescription *answerDescription =
  199. [[RTCSessionDescription alloc] initWithType:RTCSdpTypeAnswer sdp:dsc];
  200. ARDSignalingMessage *answer =
  201. [[ARDSessionDescriptionMessage alloc]
  202. initWithDescription:answerDescription];
  203. [self sendMessage:answer];
  204. break;
  205. }
  206. case kARDSignalingMessageTypeAnswer:
  207. // Should not receive answer in loopback scenario.
  208. break;
  209. case kARDSignalingMessageTypeCandidate:
  210. case kARDSignalingMessageTypeCandidateRemoval:
  211. // Send back to server.
  212. [self sendMessage:message];
  213. break;
  214. case kARDSignalingMessageTypeBye:
  215. // Nothing to do.
  216. return;
  217. }
  218. }
  219. - (void)channel:(id<ARDSignalingChannel>)channel
  220. didChangeState:(ARDSignalingChannelState)state {
  221. }
  222. @end