StreamWriter.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using MediaBrowser.Model.Logging;
  2. using ServiceStack.Service;
  3. using ServiceStack.ServiceHost;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Threading.Tasks;
  8. namespace MediaBrowser.Server.Implementations.HttpServer
  9. {
  10. /// <summary>
  11. /// Class StreamWriter
  12. /// </summary>
  13. public class StreamWriter : IStreamWriter, IHasOptions
  14. {
  15. private ILogger Logger { get; set; }
  16. /// <summary>
  17. /// Gets or sets the source stream.
  18. /// </summary>
  19. /// <value>The source stream.</value>
  20. public Stream SourceStream { get; set; }
  21. /// <summary>
  22. /// The _options
  23. /// </summary>
  24. private readonly IDictionary<string, string> _options = new Dictionary<string, string>();
  25. /// <summary>
  26. /// Gets the options.
  27. /// </summary>
  28. /// <value>The options.</value>
  29. public IDictionary<string, string> Options
  30. {
  31. get { return _options; }
  32. }
  33. /// <summary>
  34. /// Initializes a new instance of the <see cref="StreamWriter" /> class.
  35. /// </summary>
  36. /// <param name="source">The source.</param>
  37. /// <param name="contentType">Type of the content.</param>
  38. /// <param name="logger">The logger.</param>
  39. public StreamWriter(Stream source, string contentType, ILogger logger)
  40. {
  41. if (string.IsNullOrEmpty(contentType))
  42. {
  43. throw new ArgumentNullException("contentType");
  44. }
  45. SourceStream = source;
  46. Logger = logger;
  47. Options["Content-Type"] = contentType;
  48. }
  49. /// <summary>
  50. /// Writes to.
  51. /// </summary>
  52. /// <param name="responseStream">The response stream.</param>
  53. public void WriteTo(Stream responseStream)
  54. {
  55. var task = WriteToAsync(responseStream);
  56. Task.WaitAll(task);
  57. }
  58. /// <summary>
  59. /// Writes to async.
  60. /// </summary>
  61. /// <param name="responseStream">The response stream.</param>
  62. /// <returns>Task.</returns>
  63. private async Task WriteToAsync(Stream responseStream)
  64. {
  65. try
  66. {
  67. using (var src = SourceStream)
  68. {
  69. await src.CopyToAsync(responseStream).ConfigureAwait(false);
  70. }
  71. }
  72. catch (Exception ex)
  73. {
  74. Logger.ErrorException("Error streaming media", ex);
  75. throw;
  76. }
  77. }
  78. }
  79. }