| | 1 | | using System; |
| | 2 | | using System.IO; |
| | 3 | | using System.Net.Http; |
| | 4 | | using System.Net.Mime; |
| | 5 | | using System.Threading; |
| | 6 | | using System.Threading.Tasks; |
| | 7 | | using Jellyfin.Api.Extensions; |
| | 8 | | using MediaBrowser.Controller.MediaEncoding; |
| | 9 | | using MediaBrowser.Controller.Streaming; |
| | 10 | | using Microsoft.AspNetCore.Http; |
| | 11 | | using Microsoft.AspNetCore.Mvc; |
| | 12 | | using Microsoft.Net.Http.Headers; |
| | 13 | |
|
| | 14 | | namespace Jellyfin.Api.Helpers; |
| | 15 | |
|
| | 16 | | /// <summary> |
| | 17 | | /// The stream response helpers. |
| | 18 | | /// </summary> |
| | 19 | | public static class FileStreamResponseHelpers |
| | 20 | | { |
| | 21 | | /// <summary> |
| | 22 | | /// Returns a static file from a remote source. |
| | 23 | | /// </summary> |
| | 24 | | /// <param name="state">The current <see cref="StreamState"/>.</param> |
| | 25 | | /// <param name="httpClient">The <see cref="HttpClient"/> making the remote request.</param> |
| | 26 | | /// <param name="httpContext">The current http context.</param> |
| | 27 | | /// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param> |
| | 28 | | /// <returns>A <see cref="Task{ActionResult}"/> containing the API response.</returns> |
| | 29 | | public static async Task<ActionResult> GetStaticRemoteStreamResult( |
| | 30 | | StreamState state, |
| | 31 | | HttpClient httpClient, |
| | 32 | | HttpContext httpContext, |
| | 33 | | CancellationToken cancellationToken = default) |
| | 34 | | { |
| | 35 | | using var requestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri(state.MediaPath)); |
| | 36 | |
|
| | 37 | | // Forward User-Agent if provided |
| | 38 | | if (state.RemoteHttpHeaders.TryGetValue(HeaderNames.UserAgent, out var useragent)) |
| | 39 | | { |
| | 40 | | // Clear default and add specific one if exists, otherwise HttpClient default might be used |
| | 41 | | requestMessage.Headers.UserAgent.Clear(); |
| | 42 | | requestMessage.Headers.TryAddWithoutValidation(HeaderNames.UserAgent, useragent); |
| | 43 | | } |
| | 44 | |
|
| | 45 | | // Forward Range header if present in the client request |
| | 46 | | if (httpContext.Request.Headers.TryGetValue(HeaderNames.Range, out var rangeValue)) |
| | 47 | | { |
| | 48 | | var rangeString = rangeValue.ToString(); |
| | 49 | | if (!string.IsNullOrEmpty(rangeString)) |
| | 50 | | { |
| | 51 | | requestMessage.Headers.Range = System.Net.Http.Headers.RangeHeaderValue.Parse(rangeString); |
| | 52 | | } |
| | 53 | | } |
| | 54 | |
|
| | 55 | | // Send the request to the upstream server |
| | 56 | | // Use ResponseHeadersRead to avoid downloading the whole content immediately |
| | 57 | | var response = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, cancellation |
| | 58 | |
|
| | 59 | | // Check if the upstream server supports range requests and acted upon our Range header |
| | 60 | | bool upstreamSupportsRange = response.StatusCode == System.Net.HttpStatusCode.PartialContent; |
| | 61 | | string acceptRangesValue = "none"; |
| | 62 | | if (response.Headers.TryGetValues(HeaderNames.AcceptRanges, out var acceptRangesHeaders)) |
| | 63 | | { |
| | 64 | | // Prefer upstream server's Accept-Ranges header if available |
| | 65 | | acceptRangesValue = string.Join(", ", acceptRangesHeaders); |
| | 66 | | upstreamSupportsRange |= acceptRangesValue.Contains("bytes", StringComparison.OrdinalIgnoreCase); |
| | 67 | | } |
| | 68 | | else if (upstreamSupportsRange) // If we got 206 but no Accept-Ranges header, assume bytes |
| | 69 | | { |
| | 70 | | acceptRangesValue = "bytes"; |
| | 71 | | } |
| | 72 | |
|
| | 73 | | // Set Accept-Ranges header for the client based on upstream support |
| | 74 | | httpContext.Response.Headers[HeaderNames.AcceptRanges] = acceptRangesValue; |
| | 75 | |
|
| | 76 | | // Set Content-Range header if upstream provided it (implies partial content) |
| | 77 | | if (response.Content.Headers.ContentRange is not null) |
| | 78 | | { |
| | 79 | | httpContext.Response.Headers[HeaderNames.ContentRange] = response.Content.Headers.ContentRange.ToString(); |
| | 80 | | } |
| | 81 | |
|
| | 82 | | // Set Content-Length header. For partial content, this is the length of the partial segment. |
| | 83 | | if (response.Content.Headers.ContentLength.HasValue) |
| | 84 | | { |
| | 85 | | httpContext.Response.ContentLength = response.Content.Headers.ContentLength.Value; |
| | 86 | | } |
| | 87 | |
|
| | 88 | | // Set Content-Type header |
| | 89 | | var contentType = response.Content.Headers.ContentType?.ToString() ?? MediaTypeNames.Application.Octet; // Use a |
| | 90 | |
|
| | 91 | | // Set the status code for the client response (e.g., 200 OK or 206 Partial Content) |
| | 92 | | httpContext.Response.StatusCode = (int)response.StatusCode; |
| | 93 | |
|
| | 94 | | // Return the stream from the upstream server |
| | 95 | | // IMPORTANT: Do not dispose the response stream here, FileStreamResult will handle it. |
| | 96 | | return new FileStreamResult(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false), c |
| | 97 | | } |
| | 98 | |
|
| | 99 | | /// <summary> |
| | 100 | | /// Returns a static file from the server. |
| | 101 | | /// </summary> |
| | 102 | | /// <param name="path">The path to the file.</param> |
| | 103 | | /// <param name="contentType">The content type of the file.</param> |
| | 104 | | /// <returns>An <see cref="ActionResult"/> the file.</returns> |
| | 105 | | public static ActionResult GetStaticFileResult( |
| | 106 | | string path, |
| | 107 | | string contentType) |
| | 108 | | { |
| 0 | 109 | | return new PhysicalFileResult(path, contentType) { EnableRangeProcessing = true }; |
| | 110 | | } |
| | 111 | |
|
| | 112 | | /// <summary> |
| | 113 | | /// Returns a transcoded file from the server. |
| | 114 | | /// </summary> |
| | 115 | | /// <param name="state">The current <see cref="StreamState"/>.</param> |
| | 116 | | /// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned. |
| | 117 | | /// <param name="httpContext">The current http context.</param> |
| | 118 | | /// <param name="transcodeManager">The <see cref="ITranscodeManager"/> singleton.</param> |
| | 119 | | /// <param name="ffmpegCommandLineArguments">The command line arguments to start ffmpeg.</param> |
| | 120 | | /// <param name="transcodingJobType">The <see cref="TranscodingJobType"/>.</param> |
| | 121 | | /// <param name="cancellationTokenSource">The <see cref="CancellationTokenSource"/>.</param> |
| | 122 | | /// <returns>A <see cref="Task{ActionResult}"/> containing the transcoded file.</returns> |
| | 123 | | public static async Task<ActionResult> GetTranscodedFile( |
| | 124 | | StreamState state, |
| | 125 | | bool isHeadRequest, |
| | 126 | | HttpContext httpContext, |
| | 127 | | ITranscodeManager transcodeManager, |
| | 128 | | string ffmpegCommandLineArguments, |
| | 129 | | TranscodingJobType transcodingJobType, |
| | 130 | | CancellationTokenSource cancellationTokenSource) |
| | 131 | | { |
| | 132 | | // Use the command line args with a dummy playlist path |
| | 133 | | var outputPath = state.OutputFilePath; |
| | 134 | |
|
| | 135 | | httpContext.Response.Headers[HeaderNames.AcceptRanges] = "none"; |
| | 136 | |
|
| | 137 | | var contentType = state.GetMimeType(outputPath); |
| | 138 | |
|
| | 139 | | // Headers only |
| | 140 | | if (isHeadRequest) |
| | 141 | | { |
| | 142 | | httpContext.Response.Headers[HeaderNames.ContentType] = contentType; |
| | 143 | | return new OkResult(); |
| | 144 | | } |
| | 145 | |
|
| | 146 | | using (await transcodeManager.LockAsync(outputPath, cancellationTokenSource.Token).ConfigureAwait(false)) |
| | 147 | | { |
| | 148 | | TranscodingJob? job; |
| | 149 | | if (!File.Exists(outputPath)) |
| | 150 | | { |
| | 151 | | job = await transcodeManager.StartFfMpeg( |
| | 152 | | state, |
| | 153 | | outputPath, |
| | 154 | | ffmpegCommandLineArguments, |
| | 155 | | httpContext.User.GetUserId(), |
| | 156 | | transcodingJobType, |
| | 157 | | cancellationTokenSource).ConfigureAwait(false); |
| | 158 | | } |
| | 159 | | else |
| | 160 | | { |
| | 161 | | job = transcodeManager.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive); |
| | 162 | | state.Dispose(); |
| | 163 | | } |
| | 164 | |
|
| | 165 | | var stream = new ProgressiveFileStream(outputPath, job, transcodeManager); |
| | 166 | | return new FileStreamResult(stream, contentType); |
| | 167 | | } |
| | 168 | | } |
| | 169 | | } |