WebSocketSharpResponse.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Emby.Server.Implementations;
  11. using MediaBrowser.Model.IO;
  12. using MediaBrowser.Model.Services;
  13. using Microsoft.Extensions.Logging;
  14. using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
  15. using IRequest = MediaBrowser.Model.Services.IRequest;
  16. namespace Jellyfin.Server.SocketSharp
  17. {
  18. public class WebSocketSharpResponse : IHttpResponse
  19. {
  20. private readonly ILogger _logger;
  21. private readonly HttpListenerResponse _response;
  22. public WebSocketSharpResponse(ILogger logger, HttpListenerResponse response, IRequest request)
  23. {
  24. _logger = logger;
  25. this._response = response;
  26. Items = new Dictionary<string, object>();
  27. Request = request;
  28. }
  29. public IRequest Request { get; private set; }
  30. public Dictionary<string, object> Items { get; private set; }
  31. public object OriginalResponse => _response;
  32. public int StatusCode
  33. {
  34. get => this._response.StatusCode;
  35. set => this._response.StatusCode = value;
  36. }
  37. public string StatusDescription
  38. {
  39. get => this._response.StatusDescription;
  40. set => this._response.StatusDescription = value;
  41. }
  42. public string ContentType
  43. {
  44. get => _response.ContentType;
  45. set => _response.ContentType = value;
  46. }
  47. public QueryParamCollection Headers => new QueryParamCollection(_response.Headers);
  48. private static string AsHeaderValue(Cookie cookie)
  49. {
  50. DateTime defaultExpires = DateTime.MinValue;
  51. var path = cookie.Expires == defaultExpires
  52. ? "/"
  53. : cookie.Path ?? "/";
  54. var sb = new StringBuilder();
  55. sb.Append($"{cookie.Name}={cookie.Value};path={path}");
  56. if (cookie.Expires != defaultExpires)
  57. {
  58. sb.Append($";expires={cookie.Expires:R}");
  59. }
  60. if (!string.IsNullOrEmpty(cookie.Domain))
  61. {
  62. sb.Append($";domain={cookie.Domain}");
  63. }
  64. if (cookie.Secure)
  65. {
  66. sb.Append(";Secure");
  67. }
  68. if (cookie.HttpOnly)
  69. {
  70. sb.Append(";HttpOnly");
  71. }
  72. return sb.ToString();
  73. }
  74. public void AddHeader(string name, string value)
  75. {
  76. if (string.Equals(name, "Content-Type", StringComparison.OrdinalIgnoreCase))
  77. {
  78. ContentType = value;
  79. return;
  80. }
  81. _response.AddHeader(name, value);
  82. }
  83. public string GetHeader(string name)
  84. {
  85. return _response.Headers[name];
  86. }
  87. public void Redirect(string url)
  88. {
  89. _response.Redirect(url);
  90. }
  91. public Stream OutputStream => _response.OutputStream;
  92. public void Close()
  93. {
  94. if (!this.IsClosed)
  95. {
  96. this.IsClosed = true;
  97. try
  98. {
  99. var response = this._response;
  100. var outputStream = response.OutputStream;
  101. // This is needed with compression
  102. outputStream.Flush();
  103. outputStream.Dispose();
  104. response.Close();
  105. }
  106. catch (SocketException)
  107. {
  108. }
  109. catch (Exception ex)
  110. {
  111. _logger.LogError(ex, "Error in HttpListenerResponseWrapper");
  112. }
  113. }
  114. }
  115. public bool IsClosed
  116. {
  117. get;
  118. private set;
  119. }
  120. public void SetContentLength(long contentLength)
  121. {
  122. // you can happily set the Content-Length header in Asp.Net
  123. // but HttpListener will complain if you do - you have to set ContentLength64 on the response.
  124. // workaround: HttpListener throws "The parameter is incorrect" exceptions when we try to set the Content-Length header
  125. //_response.ContentLength64 = contentLength;
  126. }
  127. public void SetCookie(Cookie cookie)
  128. {
  129. var cookieStr = AsHeaderValue(cookie);
  130. _response.Headers.Add("Set-Cookie", cookieStr);
  131. }
  132. public bool SendChunked
  133. {
  134. get => _response.SendChunked;
  135. set => _response.SendChunked = value;
  136. }
  137. public bool KeepAlive { get; set; }
  138. public void ClearCookies()
  139. {
  140. }
  141. const int StreamCopyToBufferSize = 81920;
  142. public async Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, IFileSystem fileSystem, IStreamHelper streamHelper, CancellationToken cancellationToken)
  143. {
  144. // TODO
  145. // return _response.TransmitFile(path, offset, count, fileShareMode, cancellationToken);
  146. var allowAsync = !RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
  147. //if (count <= 0)
  148. //{
  149. // allowAsync = true;
  150. //}
  151. var fileOpenOptions = FileOpenOptions.SequentialScan;
  152. if (allowAsync)
  153. {
  154. fileOpenOptions |= FileOpenOptions.Asynchronous;
  155. }
  156. // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
  157. using (var fs = fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShareMode, fileOpenOptions))
  158. {
  159. if (offset > 0)
  160. {
  161. fs.Position = offset;
  162. }
  163. if (count > 0)
  164. {
  165. await streamHelper.CopyToAsync(fs, OutputStream, count, cancellationToken).ConfigureAwait(false);
  166. }
  167. else
  168. {
  169. await fs.CopyToAsync(OutputStream, StreamCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  170. }
  171. }
  172. }
  173. }
  174. }