NegotiationResult.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #if !BESTHTTP_DISABLE_SIGNALR_CORE
  2. using System;
  3. using System.Collections.Generic;
  4. namespace BestHTTP.SignalRCore.Messages
  5. {
  6. public sealed class SupportedTransport
  7. {
  8. /// <summary>
  9. /// Name of the transport.
  10. /// </summary>
  11. public string Name { get; private set; }
  12. /// <summary>
  13. /// Supported transfer formats of the transport.
  14. /// </summary>
  15. public List<string> SupportedFormats { get; private set; }
  16. internal SupportedTransport(string transportName, List<string> transferFormats)
  17. {
  18. this.Name = transportName;
  19. this.SupportedFormats = transferFormats;
  20. }
  21. }
  22. /// <summary>
  23. /// Negotiation result of the /negotiation request.
  24. /// <see cref="https://github.com/dotnet/aspnetcore/blob/master/src/SignalR/docs/specs/TransportProtocols.md#post-endpoint-basenegotiate-request"/>
  25. /// </summary>
  26. public sealed class NegotiationResult
  27. {
  28. public int NegotiateVersion { get; private set; }
  29. /// <summary>
  30. /// The connectionToken which is required by the Long Polling and Server-Sent Events transports (in order to correlate sends and receives).
  31. /// </summary>
  32. public string ConnectionToken { get; private set; }
  33. /// <summary>
  34. /// The connectionId which is required by the Long Polling and Server-Sent Events transports (in order to correlate sends and receives).
  35. /// </summary>
  36. public string ConnectionId { get; private set; }
  37. /// <summary>
  38. /// The availableTransports list which describes the transports the server supports. For each transport, the name of the transport (transport) is listed, as is a list of "transfer formats" supported by the transport (transferFormats)
  39. /// </summary>
  40. public List<SupportedTransport> SupportedTransports { get; private set; }
  41. /// <summary>
  42. /// The url which is the URL the client should connect to.
  43. /// </summary>
  44. public Uri Url { get; private set; }
  45. /// <summary>
  46. /// The accessToken which is an optional bearer token for accessing the specified url.
  47. /// </summary>
  48. public string AccessToken { get; private set; }
  49. public HTTPResponse NegotiationResponse { get; internal set; }
  50. internal static NegotiationResult Parse(HTTPResponse resp, out string error, HubConnection hub)
  51. {
  52. error = null;
  53. Dictionary<string, object> response = BestHTTP.JSON.Json.Decode(resp.DataAsText) as Dictionary<string, object>;
  54. if (response == null)
  55. {
  56. error = "Json decoding failed!";
  57. return null;
  58. }
  59. try
  60. {
  61. NegotiationResult result = new NegotiationResult();
  62. result.NegotiationResponse = resp;
  63. object value;
  64. if (response.TryGetValue("negotiateVersion", out value))
  65. {
  66. int version;
  67. if (int.TryParse(value.ToString(), out version))
  68. result.NegotiateVersion = version;
  69. }
  70. if (response.TryGetValue("connectionId", out value))
  71. result.ConnectionId = value.ToString();
  72. if (response.TryGetValue("connectionToken", out value))
  73. result.ConnectionToken = value.ToString();
  74. if (response.TryGetValue("availableTransports", out value))
  75. {
  76. List<object> transports = value as List<object>;
  77. if (transports != null)
  78. {
  79. List<SupportedTransport> supportedTransports = new List<SupportedTransport>(transports.Count);
  80. foreach (Dictionary<string, object> transport in transports)
  81. {
  82. string transportName = string.Empty;
  83. List<string> transferModes = null;
  84. if (transport.TryGetValue("transport", out value))
  85. transportName = value.ToString();
  86. if (transport.TryGetValue("transferFormats", out value))
  87. {
  88. List<object> transferFormats = value as List<object>;
  89. if (transferFormats != null)
  90. {
  91. transferModes = new List<string>(transferFormats.Count);
  92. foreach (var mode in transferFormats)
  93. transferModes.Add(mode.ToString());
  94. }
  95. }
  96. supportedTransports.Add(new SupportedTransport(transportName, transferModes));
  97. }
  98. result.SupportedTransports = supportedTransports;
  99. }
  100. }
  101. if (response.TryGetValue("url", out value))
  102. {
  103. string uriStr = value.ToString();
  104. Uri redirectUri;
  105. // Here we will try to parse the received url. If TryCreate fails, we will throw an exception
  106. // as it should be able to successfully parse whole (absolute) urls (like "https://server:url/path")
  107. // and relative ones (like "/path").
  108. if (!Uri.TryCreate(uriStr, UriKind.RelativeOrAbsolute, out redirectUri))
  109. throw new Exception(string.Format("Couldn't parse url: '{0}'", uriStr));
  110. HTTPManager.Logger.Verbose("NegotiationResult", string.Format("Parsed url({0}) into uri({1}). uri.IsAbsoluteUri: {2}, IsAbsolute: {3}", uriStr, redirectUri, redirectUri.IsAbsoluteUri, IsAbsolute(uriStr)));
  111. // If received a relative url we will use the hub's current url to append the new path to it.
  112. if (!IsAbsolute(uriStr))
  113. {
  114. Uri oldUri = hub.Uri;
  115. var builder = new UriBuilder(oldUri);
  116. // ?, /
  117. var pathAndQuery = uriStr.Split(new string[] { "?", "%3F", "%3f", "/", "%2F", "%2f" }, StringSplitOptions.RemoveEmptyEntries);
  118. if (pathAndQuery.Length > 1)
  119. builder.Query = pathAndQuery[1];
  120. else
  121. builder.Query = string.Empty;
  122. builder.Path = pathAndQuery[0];
  123. redirectUri = builder.Uri;
  124. }
  125. result.Url = redirectUri;
  126. }
  127. if (response.TryGetValue("accessToken", out value))
  128. result.AccessToken = value.ToString();
  129. else if (hub.NegotiationResult != null)
  130. result.AccessToken = hub.NegotiationResult.AccessToken;
  131. return result;
  132. }
  133. catch (Exception ex)
  134. {
  135. error = "Error while parsing result: " + ex.Message + " StackTrace: " + ex.StackTrace;
  136. return null;
  137. }
  138. }
  139. private static bool IsAbsolute(string url)
  140. {
  141. // an url is absolute if contains a scheme, an authority, and a path.
  142. return url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
  143. url.StartsWith("https://", StringComparison.OrdinalIgnoreCase);
  144. }
  145. }
  146. }
  147. #endif