From 1d6224c9c66b31c9df602b4281c870a9c400767c Mon Sep 17 00:00:00 2001 From: crobibero Date: Mon, 26 Apr 2021 07:02:26 -0600 Subject: [PATCH 01/14] Add endpoint to log client events --- .../ApplicationHost.cs | 3 + .../Controllers/ClientLogController.cs | 69 +++++++++++++++++ .../Models/ClientLogDtos/ClientLogEventDto.cs | 54 +++++++++++++ Jellyfin.Server/Jellyfin.Server.csproj | 1 + Jellyfin.Server/Program.cs | 49 +++++++++--- .../ClientEvent/ClientEventLogger.cs | 38 ++++++++++ .../ClientEvent/IClientEventLogger.cs | 16 ++++ .../MediaBrowser.Controller.csproj | 2 +- .../ClientLog/ClientLogEvent.cs | 75 +++++++++++++++++++ 9 files changed, 295 insertions(+), 12 deletions(-) create mode 100644 Jellyfin.Api/Controllers/ClientLogController.cs create mode 100644 Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs create mode 100644 MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs create mode 100644 MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs create mode 100644 MediaBrowser.Model/ClientLog/ClientLogEvent.cs diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 703f8d20da..b05e0409d9 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -55,6 +55,7 @@ using MediaBrowser.Common.Updates; using MediaBrowser.Controller; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Chapters; +using MediaBrowser.Controller.ClientEvent; using MediaBrowser.Controller.Collections; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Devices; @@ -680,6 +681,8 @@ namespace Emby.Server.Implementations ServiceCollection.AddScoped(); ServiceCollection.AddScoped(); + ServiceCollection.AddScoped(); + ServiceCollection.AddSingleton(); } diff --git a/Jellyfin.Api/Controllers/ClientLogController.cs b/Jellyfin.Api/Controllers/ClientLogController.cs new file mode 100644 index 0000000000..8e38cd13c5 --- /dev/null +++ b/Jellyfin.Api/Controllers/ClientLogController.cs @@ -0,0 +1,69 @@ +using Jellyfin.Api.Models.ClientLogDtos; +using MediaBrowser.Controller.ClientEvent; +using MediaBrowser.Model.ClientLog; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace Jellyfin.Api.Controllers +{ + /// + /// Client log controller. + /// + public class ClientLogController : BaseJellyfinApiController + { + private readonly IClientEventLogger _clientEventLogger; + + /// + /// Initializes a new instance of the class. + /// + /// Instance of the interface. + public ClientLogController(IClientEventLogger clientEventLogger) + { + _clientEventLogger = clientEventLogger; + } + + /// + /// Post event from client. + /// + /// The client log dto. + /// Event logged. + /// Submission status. + [HttpPost] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult LogEvent([FromBody] ClientLogEventDto clientLogEventDto) + { + Log(clientLogEventDto); + return NoContent(); + } + + /// + /// Bulk post events from client. + /// + /// The list of client log dtos. + /// All events logged. + /// Submission status. + [HttpPost("Bulk")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult LogEvents([FromBody] ClientLogEventDto[] clientLogEventDtos) + { + foreach (var dto in clientLogEventDtos) + { + Log(dto); + } + + return NoContent(); + } + + private void Log(ClientLogEventDto dto) + { + _clientEventLogger.Log(new ClientLogEvent( + dto.Timestamp, + dto.Level, + dto.UserId, + dto.ClientName, + dto.ClientVersion, + dto.DeviceId, + dto.Message)); + } + } +} \ No newline at end of file diff --git a/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs b/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs new file mode 100644 index 0000000000..8ee1eab726 --- /dev/null +++ b/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs @@ -0,0 +1,54 @@ +using System; +using System.ComponentModel.DataAnnotations; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Api.Models.ClientLogDtos +{ + /// + /// The client log dto. + /// + public class ClientLogEventDto + { + /// + /// Gets or sets the event timestamp. + /// + [Required] + public DateTime Timestamp { get; set; } + + /// + /// Gets or sets the log level. + /// + [Required] + public LogLevel Level { get; set; } + + /// + /// Gets or sets the user id. + /// + public Guid? UserId { get; set; } + + /// + /// Gets or sets the client name. + /// + [Required] + public string ClientName { get; set; } = string.Empty; + + /// + /// Gets or sets the client version. + /// + [Required] + public string ClientVersion { get; set; } = string.Empty; + + /// + /// + /// Gets or sets the device id. + /// + [Required] + public string DeviceId { get; set; } = string.Empty; + + /// + /// Gets or sets the log message. + /// + [Required] + public string Message { get; set; } = string.Empty; + } +} \ No newline at end of file diff --git a/Jellyfin.Server/Jellyfin.Server.csproj b/Jellyfin.Server/Jellyfin.Server.csproj index 3496cabe8e..ef842ee26b 100644 --- a/Jellyfin.Server/Jellyfin.Server.csproj +++ b/Jellyfin.Server/Jellyfin.Server.csproj @@ -49,6 +49,7 @@ + diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index c10b2ddb3a..b8d3ba2397 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -14,6 +14,7 @@ using Emby.Server.Implementations; using Emby.Server.Implementations.IO; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; +using MediaBrowser.Controller.ClientEvent; using MediaBrowser.Controller.Extensions; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; @@ -24,6 +25,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Serilog; using Serilog.Extensions.Logging; +using Serilog.Filters; using SQLitePCL; using ConfigurationExtensions = MediaBrowser.Controller.Extensions.ConfigurationExtensions; using ILogger = Microsoft.Extensions.Logging.ILogger; @@ -585,22 +587,47 @@ namespace Jellyfin.Server { // Serilog.Log is used by SerilogLoggerFactory when no logger is specified Serilog.Log.Logger = new LoggerConfiguration() - .ReadFrom.Configuration(configuration) - .Enrich.FromLogContext() - .Enrich.WithThreadId() + .WriteTo.Logger(lc => + lc.ReadFrom.Configuration(configuration) + .Enrich.FromLogContext() + .Enrich.WithThreadId() + .Filter.ByExcluding(Matching.FromSource())) + .WriteTo.Logger(lc => + lc + .WriteTo.Map( + "ClientName", + (clientName, wt) + => wt.File( + Path.Combine(appPaths.LogDirectoryPath, $"log_{clientName}_.log"), + rollingInterval: RollingInterval.Day, + outputTemplate: "{Message:l}{NewLine}{Exception}", + encoding: Encoding.UTF8)) + .Filter.ByIncludingOnly(Matching.FromSource())) .CreateLogger(); } catch (Exception ex) { Serilog.Log.Logger = new LoggerConfiguration() - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}") - .WriteTo.Async(x => x.File( - Path.Combine(appPaths.LogDirectoryPath, "log_.log"), - rollingInterval: RollingInterval.Day, - outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message}{NewLine}{Exception}", - encoding: Encoding.UTF8)) - .Enrich.FromLogContext() - .Enrich.WithThreadId() + .WriteTo.Logger(lc => + lc.WriteTo.Async(x => x.File( + Path.Combine(appPaths.LogDirectoryPath, "log_.log"), + rollingInterval: RollingInterval.Day, + outputTemplate: "{Message:l}{NewLine}{Exception}", + encoding: Encoding.UTF8)) + .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss}] [{Level:u3}] [{ThreadId}] {SourceContext}: {Message:lj}{NewLine}{Exception}") + .Enrich.FromLogContext() + .Enrich.WithThreadId()) + .WriteTo.Logger(lc => + lc + .WriteTo.Map( + "ClientName", + (clientName, wt) + => wt.File( + Path.Combine(appPaths.LogDirectoryPath, $"log_{clientName}_.log"), + rollingInterval: RollingInterval.Day, + outputTemplate: "{Message:l}{NewLine}{Exception}", + encoding: Encoding.UTF8)) + .Filter.ByIncludingOnly(Matching.FromSource())) .CreateLogger(); Serilog.Log.Logger.Fatal(ex, "Failed to create/read logger configuration"); diff --git a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs new file mode 100644 index 0000000000..c00a38d1bc --- /dev/null +++ b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs @@ -0,0 +1,38 @@ +using System; +using MediaBrowser.Model.ClientLog; +using Microsoft.Extensions.Logging; + +namespace MediaBrowser.Controller.ClientEvent +{ + /// + public class ClientEventLogger : IClientEventLogger + { + private const string LogString = "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level}] [{ClientName}:{ClientVersion}]: UserId: {UserId} DeviceId: {DeviceId}{NewLine}{Message}"; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// Instance of the interface. + public ClientEventLogger(ILogger logger) + { + _logger = logger; + } + + /// + public void Log(ClientLogEvent clientLogEvent) + { + _logger.Log( + LogLevel.Critical, + LogString, + clientLogEvent.Timestamp, + clientLogEvent.Level.ToString(), + clientLogEvent.ClientName, + clientLogEvent.ClientVersion, + clientLogEvent.UserId ?? Guid.Empty, + clientLogEvent.DeviceId, + Environment.NewLine, + clientLogEvent.Message); + } + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs new file mode 100644 index 0000000000..bf799c7bf8 --- /dev/null +++ b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs @@ -0,0 +1,16 @@ +using MediaBrowser.Model.ClientLog; + +namespace MediaBrowser.Controller.ClientEvent +{ + /// + /// The client event logger. + /// + public interface IClientEventLogger + { + /// + /// Logs the event from the client. + /// + /// The client log event. + void Log(ClientLogEvent clientLogEvent); + } +} \ No newline at end of file diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 8c68b47dd7..7c95ab818c 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -16,7 +16,7 @@ - + diff --git a/MediaBrowser.Model/ClientLog/ClientLogEvent.cs b/MediaBrowser.Model/ClientLog/ClientLogEvent.cs new file mode 100644 index 0000000000..e4ee881454 --- /dev/null +++ b/MediaBrowser.Model/ClientLog/ClientLogEvent.cs @@ -0,0 +1,75 @@ +using System; +using Microsoft.Extensions.Logging; + +namespace MediaBrowser.Model.ClientLog +{ + /// + /// The client log event. + /// + public class ClientLogEvent + { + /// + /// Initializes a new instance of the class. + /// + /// The log timestamp. + /// The log level. + /// The user id. + /// The client name. + /// The client version. + /// The device id. + /// The message. + public ClientLogEvent( + DateTime timestamp, + LogLevel level, + Guid? userId, + string clientName, + string clientVersion, + string deviceId, + string message) + { + Timestamp = timestamp; + UserId = userId; + ClientName = clientName; + ClientVersion = clientVersion; + DeviceId = deviceId; + Message = message; + Level = level; + } + + /// + /// Gets the event timestamp. + /// + public DateTime Timestamp { get; } + + /// + /// Gets the log level. + /// + public LogLevel Level { get; } + + /// + /// Gets the user id. + /// + public Guid? UserId { get; } + + /// + /// Gets the client name. + /// + public string ClientName { get; } + + /// + /// Gets the client version. + /// + public string ClientVersion { get; } + + /// + /// + /// Gets the device id. + /// + public string DeviceId { get; } + + /// + /// Gets the log message. + /// + public string Message { get; } + } +} \ No newline at end of file From f8cfc55a3678186af642c74d1c7083711c96aa63 Mon Sep 17 00:00:00 2001 From: crobibero Date: Mon, 26 Apr 2021 17:02:25 -0600 Subject: [PATCH 02/14] Clean client filename generation --- Jellyfin.Server/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index b8d3ba2397..7a7e0a1cf5 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -598,7 +598,7 @@ namespace Jellyfin.Server "ClientName", (clientName, wt) => wt.File( - Path.Combine(appPaths.LogDirectoryPath, $"log_{clientName}_.log"), + Path.Combine(appPaths.LogDirectoryPath, clientName + "_.log"), rollingInterval: RollingInterval.Day, outputTemplate: "{Message:l}{NewLine}{Exception}", encoding: Encoding.UTF8)) @@ -623,7 +623,7 @@ namespace Jellyfin.Server "ClientName", (clientName, wt) => wt.File( - Path.Combine(appPaths.LogDirectoryPath, $"log_{clientName}_.log"), + Path.Combine(appPaths.LogDirectoryPath, clientName + "_.log"), rollingInterval: RollingInterval.Day, outputTemplate: "{Message:l}{NewLine}{Exception}", encoding: Encoding.UTF8)) From 3c8abeda7d5608cfe5ab099158190497edc802ef Mon Sep 17 00:00:00 2001 From: crobibero Date: Tue, 4 May 2021 07:16:35 -0600 Subject: [PATCH 03/14] Require Authorization for the ClientLogController --- Jellyfin.Api/Controllers/ClientLogController.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Jellyfin.Api/Controllers/ClientLogController.cs b/Jellyfin.Api/Controllers/ClientLogController.cs index 8e38cd13c5..b894deb84e 100644 --- a/Jellyfin.Api/Controllers/ClientLogController.cs +++ b/Jellyfin.Api/Controllers/ClientLogController.cs @@ -1,6 +1,8 @@ -using Jellyfin.Api.Models.ClientLogDtos; +using Jellyfin.Api.Constants; +using Jellyfin.Api.Models.ClientLogDtos; using MediaBrowser.Controller.ClientEvent; using MediaBrowser.Model.ClientLog; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -9,6 +11,7 @@ namespace Jellyfin.Api.Controllers /// /// Client log controller. /// + [Authorize(Policy = Policies.DefaultAuthorization)] public class ClientLogController : BaseJellyfinApiController { private readonly IClientEventLogger _clientEventLogger; From 2888567ea53c1c839b0cd69e0ec1168cf51f36a8 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Tue, 11 May 2021 08:21:04 -0600 Subject: [PATCH 04/14] Update Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs Co-authored-by: dkanada --- Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs b/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs index 8ee1eab726..04d97047a1 100644 --- a/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs +++ b/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs @@ -51,4 +51,4 @@ namespace Jellyfin.Api.Models.ClientLogDtos [Required] public string Message { get; set; } = string.Empty; } -} \ No newline at end of file +} From a6357f89abb40deaa84ed0ea52010c098e769e62 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Tue, 26 Oct 2021 18:42:17 -0600 Subject: [PATCH 05/14] Add ability to upload entire file --- .../Controllers/ClientLogController.cs | 19 ++++++++++++++-- Jellyfin.Server/Program.cs | 4 ++-- .../ClientEvent/ClientEventLogger.cs | 22 +++++++++++++++++-- .../ClientEvent/IClientEventLogger.cs | 14 ++++++++++-- 4 files changed, 51 insertions(+), 8 deletions(-) diff --git a/Jellyfin.Api/Controllers/ClientLogController.cs b/Jellyfin.Api/Controllers/ClientLogController.cs index b894deb84e..9fe3bf731c 100644 --- a/Jellyfin.Api/Controllers/ClientLogController.cs +++ b/Jellyfin.Api/Controllers/ClientLogController.cs @@ -1,4 +1,5 @@ -using Jellyfin.Api.Constants; +using System.Threading.Tasks; +using Jellyfin.Api.Constants; using Jellyfin.Api.Models.ClientLogDtos; using MediaBrowser.Controller.ClientEvent; using MediaBrowser.Model.ClientLog; @@ -57,6 +58,20 @@ namespace Jellyfin.Api.Controllers return NoContent(); } + /// + /// Upload a log file. + /// + /// The file. + /// Submission status. + [HttpPost("File")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public async Task LogFile(IFormFile file) + { + await _clientEventLogger.WriteFileAsync(file.FileName, file.OpenReadStream()) + .ConfigureAwait(false); + return NoContent(); + } + private void Log(ClientLogEventDto dto) { _clientEventLogger.Log(new ClientLogEvent( @@ -69,4 +84,4 @@ namespace Jellyfin.Api.Controllers dto.Message)); } } -} \ No newline at end of file +} diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 778e53cf66..2f8986da87 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -607,7 +607,7 @@ namespace Jellyfin.Server "ClientName", (clientName, wt) => wt.File( - Path.Combine(appPaths.LogDirectoryPath, clientName + "_.log"), + Path.Combine(appPaths.LogDirectoryPath, "log_" + clientName + "_.log"), rollingInterval: RollingInterval.Day, outputTemplate: "{Message:l}{NewLine}{Exception}", encoding: Encoding.UTF8)) @@ -632,7 +632,7 @@ namespace Jellyfin.Server "ClientName", (clientName, wt) => wt.File( - Path.Combine(appPaths.LogDirectoryPath, clientName + "_.log"), + Path.Combine(appPaths.LogDirectoryPath, "log_" + clientName + "_.log"), rollingInterval: RollingInterval.Day, outputTemplate: "{Message:l}{NewLine}{Exception}", encoding: Encoding.UTF8)) diff --git a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs index c00a38d1bc..bdc1a7eff1 100644 --- a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs @@ -1,4 +1,6 @@ using System; +using System.IO; +using System.Threading.Tasks; using MediaBrowser.Model.ClientLog; using Microsoft.Extensions.Logging; @@ -9,14 +11,19 @@ namespace MediaBrowser.Controller.ClientEvent { private const string LogString = "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}] [{Level}] [{ClientName}:{ClientVersion}]: UserId: {UserId} DeviceId: {DeviceId}{NewLine}{Message}"; private readonly ILogger _logger; + private readonly IServerApplicationPaths _applicationPaths; /// /// Initializes a new instance of the class. /// /// Instance of the interface. - public ClientEventLogger(ILogger logger) + /// Instance of the interface. + public ClientEventLogger( + ILogger logger, + IServerApplicationPaths applicationPaths) { _logger = logger; + _applicationPaths = applicationPaths; } /// @@ -34,5 +41,16 @@ namespace MediaBrowser.Controller.ClientEvent Environment.NewLine, clientLogEvent.Message); } + + /// + public async Task WriteFileAsync(string fileName, Stream fileContents) + { + // Force naming convention: upload_YYYYMMDD_$name + fileName = $"upload_{DateTime.UtcNow:yyyyMMdd}_{fileName}"; + var logFilePath = Path.Combine(_applicationPaths.LogDirectoryPath, fileName); + await using var fileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None); + await fileContents.CopyToAsync(fileStream).ConfigureAwait(false); + await fileStream.FlushAsync().ConfigureAwait(false); + } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs index bf799c7bf8..7cd71a60d6 100644 --- a/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs @@ -1,4 +1,6 @@ -using MediaBrowser.Model.ClientLog; +using System.IO; +using System.Threading.Tasks; +using MediaBrowser.Model.ClientLog; namespace MediaBrowser.Controller.ClientEvent { @@ -12,5 +14,13 @@ namespace MediaBrowser.Controller.ClientEvent /// /// The client log event. void Log(ClientLogEvent clientLogEvent); + + /// + /// Writes a file to the log directory. + /// + /// The file name. + /// The file contents. + /// A representing the asynchronous operation. + Task WriteFileAsync(string fileName, Stream fileContents); } -} \ No newline at end of file +} From c534c450330759f6595c9601e3fe8b12e6987e69 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Wed, 27 Oct 2021 19:20:14 -0600 Subject: [PATCH 06/14] Suggestions from review --- .../Controllers/ClientLogController.cs | 53 ++++++++++++++++--- .../ClientEvent/ClientEventLogger.cs | 6 +-- .../ClientEvent/IClientEventLogger.cs | 7 +-- .../ClientLog/ClientLogEvent.cs | 2 +- .../Configuration/ServerConfiguration.cs | 5 ++ 5 files changed, 59 insertions(+), 14 deletions(-) diff --git a/Jellyfin.Api/Controllers/ClientLogController.cs b/Jellyfin.Api/Controllers/ClientLogController.cs index 9fe3bf731c..aac3f6a735 100644 --- a/Jellyfin.Api/Controllers/ClientLogController.cs +++ b/Jellyfin.Api/Controllers/ClientLogController.cs @@ -1,7 +1,11 @@ -using System.Threading.Tasks; +using System.Net.Mime; +using System.Threading.Tasks; +using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; using Jellyfin.Api.Models.ClientLogDtos; using MediaBrowser.Controller.ClientEvent; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Net; using MediaBrowser.Model.ClientLog; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -15,15 +19,25 @@ namespace Jellyfin.Api.Controllers [Authorize(Policy = Policies.DefaultAuthorization)] public class ClientLogController : BaseJellyfinApiController { + private const int MaxDocumentSize = 1_000_000; private readonly IClientEventLogger _clientEventLogger; + private readonly IAuthorizationContext _authorizationContext; + private readonly IServerConfigurationManager _serverConfigurationManager; /// /// Initializes a new instance of the class. /// /// Instance of the interface. - public ClientLogController(IClientEventLogger clientEventLogger) + /// Instance of the interface. + /// Instance of the interface. + public ClientLogController( + IClientEventLogger clientEventLogger, + IAuthorizationContext authorizationContext, + IServerConfigurationManager serverConfigurationManager) { _clientEventLogger = clientEventLogger; + _authorizationContext = authorizationContext; + _serverConfigurationManager = serverConfigurationManager; } /// @@ -36,6 +50,11 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult LogEvent([FromBody] ClientLogEventDto clientLogEventDto) { + if (!_serverConfigurationManager.Configuration.AllowClientLogUpload) + { + return Forbid(); + } + Log(clientLogEventDto); return NoContent(); } @@ -50,6 +69,11 @@ namespace Jellyfin.Api.Controllers [ProducesResponseType(StatusCodes.Status204NoContent)] public ActionResult LogEvents([FromBody] ClientLogEventDto[] clientLogEventDtos) { + if (!_serverConfigurationManager.Configuration.AllowClientLogUpload) + { + return Forbid(); + } + foreach (var dto in clientLogEventDtos) { Log(dto); @@ -59,15 +83,30 @@ namespace Jellyfin.Api.Controllers } /// - /// Upload a log file. + /// Upload a document. /// - /// The file. /// Submission status. - [HttpPost("File")] + [HttpPost("Document")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public async Task LogFile(IFormFile file) + [AcceptsFile(MediaTypeNames.Text.Plain)] + [RequestSizeLimit(MaxDocumentSize)] + public async Task LogFile() { - await _clientEventLogger.WriteFileAsync(file.FileName, file.OpenReadStream()) + if (!_serverConfigurationManager.Configuration.AllowClientLogUpload) + { + return Forbid(); + } + + if (Request.ContentLength > MaxDocumentSize) + { + // Manually validate to return proper status code. + return StatusCode(StatusCodes.Status413PayloadTooLarge, $"Payload must be less than {MaxDocumentSize:N0} bytes"); + } + + var authorizationInfo = await _authorizationContext.GetAuthorizationInfo(Request) + .ConfigureAwait(false); + + await _clientEventLogger.WriteDocumentAsync(authorizationInfo, Request.Body) .ConfigureAwait(false); return NoContent(); } diff --git a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs index bdc1a7eff1..61f7adff32 100644 --- a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Threading.Tasks; +using MediaBrowser.Controller.Net; using MediaBrowser.Model.ClientLog; using Microsoft.Extensions.Logging; @@ -43,10 +44,9 @@ namespace MediaBrowser.Controller.ClientEvent } /// - public async Task WriteFileAsync(string fileName, Stream fileContents) + public async Task WriteDocumentAsync(AuthorizationInfo authorizationInfo, Stream fileContents) { - // Force naming convention: upload_YYYYMMDD_$name - fileName = $"upload_{DateTime.UtcNow:yyyyMMdd}_{fileName}"; + var fileName = $"upload_{authorizationInfo.Client}_{authorizationInfo.Version}_{DateTime.UtcNow:yyyyMMddHHmmss}.log"; var logFilePath = Path.Combine(_applicationPaths.LogDirectoryPath, fileName); await using var fileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None); await fileContents.CopyToAsync(fileStream).ConfigureAwait(false); diff --git a/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs index 7cd71a60d6..ee8e5806b7 100644 --- a/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs @@ -1,5 +1,6 @@ using System.IO; using System.Threading.Tasks; +using MediaBrowser.Controller.Net; using MediaBrowser.Model.ClientLog; namespace MediaBrowser.Controller.ClientEvent @@ -18,9 +19,9 @@ namespace MediaBrowser.Controller.ClientEvent /// /// Writes a file to the log directory. /// - /// The file name. - /// The file contents. + /// The current authorization info. + /// The file contents to write. /// A representing the asynchronous operation. - Task WriteFileAsync(string fileName, Stream fileContents); + Task WriteDocumentAsync(AuthorizationInfo authorizationInfo, Stream fileContents); } } diff --git a/MediaBrowser.Model/ClientLog/ClientLogEvent.cs b/MediaBrowser.Model/ClientLog/ClientLogEvent.cs index e4ee881454..21087b5647 100644 --- a/MediaBrowser.Model/ClientLog/ClientLogEvent.cs +++ b/MediaBrowser.Model/ClientLog/ClientLogEvent.cs @@ -72,4 +72,4 @@ namespace MediaBrowser.Model.ClientLog /// public string Message { get; } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index d1e9996665..37dc49d7a8 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -459,5 +459,10 @@ namespace MediaBrowser.Model.Configuration /// Gets or sets a value indicating whether older plugins should automatically be deleted from the plugin folder. /// public bool RemoveOldPlugins { get; set; } + + /// + /// Gets or sets a value indicating whether clients should be allowed to upload logs. + /// + public bool AllowClientLogUpload { get; set; } } } From 91204fc9f0e704a61300a7bd54f52d56f02f44b3 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Wed, 27 Oct 2021 19:40:35 -0600 Subject: [PATCH 07/14] Fix logfile name if api key is used --- MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs index 61f7adff32..04d0a3c434 100644 --- a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs @@ -46,7 +46,7 @@ namespace MediaBrowser.Controller.ClientEvent /// public async Task WriteDocumentAsync(AuthorizationInfo authorizationInfo, Stream fileContents) { - var fileName = $"upload_{authorizationInfo.Client}_{authorizationInfo.Version}_{DateTime.UtcNow:yyyyMMddHHmmss}.log"; + var fileName = $"upload_{authorizationInfo.Client}_{(authorizationInfo.IsApiKey ? "apikey" : authorizationInfo.Version)}_{DateTime.UtcNow:yyyyMMddHHmmss}.log"; var logFilePath = Path.Combine(_applicationPaths.LogDirectoryPath, fileName); await using var fileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None); await fileContents.CopyToAsync(fileStream).ConfigureAwait(false); From 0e584f68409e71204f6b9387cde8efe2adb0fbed Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Thu, 28 Oct 2021 16:11:14 -0600 Subject: [PATCH 08/14] Update documentation; use information from authorization; return generated filename --- .../Controllers/ClientLogController.cs | 43 +++++++++++++------ .../Models/ClientLogDtos/ClientLogEventDto.cs | 24 ----------- .../ClientEvent/ClientEventLogger.cs | 3 +- .../ClientEvent/IClientEventLogger.cs | 4 +- 4 files changed, 33 insertions(+), 41 deletions(-) diff --git a/Jellyfin.Api/Controllers/ClientLogController.cs b/Jellyfin.Api/Controllers/ClientLogController.cs index aac3f6a735..f50d560979 100644 --- a/Jellyfin.Api/Controllers/ClientLogController.cs +++ b/Jellyfin.Api/Controllers/ClientLogController.cs @@ -45,17 +45,22 @@ namespace Jellyfin.Api.Controllers /// /// The client log dto. /// Event logged. + /// Event logging disabled. /// Submission status. [HttpPost] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult LogEvent([FromBody] ClientLogEventDto clientLogEventDto) + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task LogEvent([FromBody] ClientLogEventDto clientLogEventDto) { if (!_serverConfigurationManager.Configuration.AllowClientLogUpload) { return Forbid(); } - Log(clientLogEventDto); + var authorizationInfo = await _authorizationContext.GetAuthorizationInfo(Request) + .ConfigureAwait(false); + + Log(clientLogEventDto, authorizationInfo); return NoContent(); } @@ -64,19 +69,24 @@ namespace Jellyfin.Api.Controllers /// /// The list of client log dtos. /// All events logged. + /// Event logging disabled. /// Submission status. [HttpPost("Bulk")] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult LogEvents([FromBody] ClientLogEventDto[] clientLogEventDtos) + [ProducesResponseType(StatusCodes.Status403Forbidden)] + public async Task LogEvents([FromBody] ClientLogEventDto[] clientLogEventDtos) { if (!_serverConfigurationManager.Configuration.AllowClientLogUpload) { return Forbid(); } + var authorizationInfo = await _authorizationContext.GetAuthorizationInfo(Request) + .ConfigureAwait(false); + foreach (var dto in clientLogEventDtos) { - Log(dto); + Log(dto, authorizationInfo); } return NoContent(); @@ -85,12 +95,17 @@ namespace Jellyfin.Api.Controllers /// /// Upload a document. /// - /// Submission status. + /// Document saved. + /// Event logging disabled. + /// Upload size too large. + /// Created file name. [HttpPost("Document")] - [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(typeof(string), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status403Forbidden)] + [ProducesResponseType(StatusCodes.Status413PayloadTooLarge)] [AcceptsFile(MediaTypeNames.Text.Plain)] [RequestSizeLimit(MaxDocumentSize)] - public async Task LogFile() + public async Task> LogFile() { if (!_serverConfigurationManager.Configuration.AllowClientLogUpload) { @@ -106,20 +121,20 @@ namespace Jellyfin.Api.Controllers var authorizationInfo = await _authorizationContext.GetAuthorizationInfo(Request) .ConfigureAwait(false); - await _clientEventLogger.WriteDocumentAsync(authorizationInfo, Request.Body) + var fileName = await _clientEventLogger.WriteDocumentAsync(authorizationInfo, Request.Body) .ConfigureAwait(false); - return NoContent(); + return Ok(fileName); } - private void Log(ClientLogEventDto dto) + private void Log(ClientLogEventDto dto, AuthorizationInfo authorizationInfo) { _clientEventLogger.Log(new ClientLogEvent( dto.Timestamp, dto.Level, - dto.UserId, - dto.ClientName, - dto.ClientVersion, - dto.DeviceId, + authorizationInfo.UserId, + authorizationInfo.Client, + authorizationInfo.Version, + authorizationInfo.DeviceId, dto.Message)); } } diff --git a/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs b/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs index 04d97047a1..9bf9be0a46 100644 --- a/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs +++ b/Jellyfin.Api/Models/ClientLogDtos/ClientLogEventDto.cs @@ -21,30 +21,6 @@ namespace Jellyfin.Api.Models.ClientLogDtos [Required] public LogLevel Level { get; set; } - /// - /// Gets or sets the user id. - /// - public Guid? UserId { get; set; } - - /// - /// Gets or sets the client name. - /// - [Required] - public string ClientName { get; set; } = string.Empty; - - /// - /// Gets or sets the client version. - /// - [Required] - public string ClientVersion { get; set; } = string.Empty; - - /// - /// - /// Gets or sets the device id. - /// - [Required] - public string DeviceId { get; set; } = string.Empty; - /// /// Gets or sets the log message. /// diff --git a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs index 04d0a3c434..870070d354 100644 --- a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs @@ -44,13 +44,14 @@ namespace MediaBrowser.Controller.ClientEvent } /// - public async Task WriteDocumentAsync(AuthorizationInfo authorizationInfo, Stream fileContents) + public async Task WriteDocumentAsync(AuthorizationInfo authorizationInfo, Stream fileContents) { var fileName = $"upload_{authorizationInfo.Client}_{(authorizationInfo.IsApiKey ? "apikey" : authorizationInfo.Version)}_{DateTime.UtcNow:yyyyMMddHHmmss}.log"; var logFilePath = Path.Combine(_applicationPaths.LogDirectoryPath, fileName); await using var fileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None); await fileContents.CopyToAsync(fileStream).ConfigureAwait(false); await fileStream.FlushAsync().ConfigureAwait(false); + return fileName; } } } diff --git a/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs index ee8e5806b7..6fc54faf2f 100644 --- a/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs @@ -21,7 +21,7 @@ namespace MediaBrowser.Controller.ClientEvent /// /// The current authorization info. /// The file contents to write. - /// A representing the asynchronous operation. - Task WriteDocumentAsync(AuthorizationInfo authorizationInfo, Stream fileContents); + /// The created file name. + Task WriteDocumentAsync(AuthorizationInfo authorizationInfo, Stream fileContents); } } From bcb1c9b652d7b74e785f1221e5df6836e6bbfffe Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Fri, 29 Oct 2021 06:33:34 -0600 Subject: [PATCH 09/14] Use response dto --- .../Controllers/ClientLogController.cs | 8 +++---- .../ClientLogDocumentResponseDto.cs | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs diff --git a/Jellyfin.Api/Controllers/ClientLogController.cs b/Jellyfin.Api/Controllers/ClientLogController.cs index f50d560979..7068c97710 100644 --- a/Jellyfin.Api/Controllers/ClientLogController.cs +++ b/Jellyfin.Api/Controllers/ClientLogController.cs @@ -98,14 +98,14 @@ namespace Jellyfin.Api.Controllers /// Document saved. /// Event logging disabled. /// Upload size too large. - /// Created file name. + /// Create response. [HttpPost("Document")] - [ProducesResponseType(typeof(string), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ClientLogDocumentResponseDto), StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status403Forbidden)] [ProducesResponseType(StatusCodes.Status413PayloadTooLarge)] [AcceptsFile(MediaTypeNames.Text.Plain)] [RequestSizeLimit(MaxDocumentSize)] - public async Task> LogFile() + public async Task> LogFile() { if (!_serverConfigurationManager.Configuration.AllowClientLogUpload) { @@ -123,7 +123,7 @@ namespace Jellyfin.Api.Controllers var fileName = await _clientEventLogger.WriteDocumentAsync(authorizationInfo, Request.Body) .ConfigureAwait(false); - return Ok(fileName); + return Ok(new ClientLogDocumentResponseDto(fileName)); } private void Log(ClientLogEventDto dto, AuthorizationInfo authorizationInfo) diff --git a/Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs b/Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs new file mode 100644 index 0000000000..c7e5ead9ed --- /dev/null +++ b/Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs @@ -0,0 +1,22 @@ +namespace Jellyfin.Api.Models.ClientLogDtos +{ + /// + /// Client log document response dto. + /// + public class ClientLogDocumentResponseDto + { + /// + /// Initializes a new instance of the class. + /// + /// The file name. + public ClientLogDocumentResponseDto(string filename) + { + Filename = filename; + } + + /// + /// Gets the resulting filename. + /// + public string Filename { get; } + } +} From 73201ed498ade1b2731b58f7e8fe1f0aba54a3e5 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Fri, 29 Oct 2021 06:33:46 -0600 Subject: [PATCH 10/14] Default log upload to enabled --- MediaBrowser.Model/Configuration/ServerConfiguration.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index 37dc49d7a8..b79d18abd8 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -463,6 +463,6 @@ namespace MediaBrowser.Model.Configuration /// /// Gets or sets a value indicating whether clients should be allowed to upload logs. /// - public bool AllowClientLogUpload { get; set; } + public bool AllowClientLogUpload { get; set; } = true; } } From f4844c08a523ea8879cb3abbc24c23b9a924dc9e Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Fri, 29 Oct 2021 11:24:27 -0600 Subject: [PATCH 11/14] Update Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs Co-authored-by: Niels van Velzen --- .../Models/ClientLogDtos/ClientLogDocumentResponseDto.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs b/Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs index c7e5ead9ed..44509a9c04 100644 --- a/Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs +++ b/Jellyfin.Api/Models/ClientLogDtos/ClientLogDocumentResponseDto.cs @@ -8,15 +8,15 @@ namespace Jellyfin.Api.Models.ClientLogDtos /// /// Initializes a new instance of the class. /// - /// The file name. - public ClientLogDocumentResponseDto(string filename) + /// The file name. + public ClientLogDocumentResponseDto(string fileName) { - Filename = filename; + FileName = fileName; } /// /// Gets the resulting filename. /// - public string Filename { get; } + public string FileName { get; } } } From 17264a6020774ac50b48bf5fe61ca9a3b1ec4d19 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Fri, 5 Nov 2021 10:40:45 -0600 Subject: [PATCH 12/14] Use client info from claims --- .../Controllers/ClientLogController.cs | 58 +++++++++++-------- .../ClientEvent/ClientEventLogger.cs | 4 +- .../ClientEvent/IClientEventLogger.cs | 8 ++- 3 files changed, 41 insertions(+), 29 deletions(-) diff --git a/Jellyfin.Api/Controllers/ClientLogController.cs b/Jellyfin.Api/Controllers/ClientLogController.cs index 7068c97710..95d07c9307 100644 --- a/Jellyfin.Api/Controllers/ClientLogController.cs +++ b/Jellyfin.Api/Controllers/ClientLogController.cs @@ -1,11 +1,12 @@ -using System.Net.Mime; +using System; +using System.Net.Mime; using System.Threading.Tasks; using Jellyfin.Api.Attributes; using Jellyfin.Api.Constants; +using Jellyfin.Api.Helpers; using Jellyfin.Api.Models.ClientLogDtos; using MediaBrowser.Controller.ClientEvent; using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.Net; using MediaBrowser.Model.ClientLog; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -21,22 +22,18 @@ namespace Jellyfin.Api.Controllers { private const int MaxDocumentSize = 1_000_000; private readonly IClientEventLogger _clientEventLogger; - private readonly IAuthorizationContext _authorizationContext; private readonly IServerConfigurationManager _serverConfigurationManager; /// /// Initializes a new instance of the class. /// /// Instance of the interface. - /// Instance of the interface. /// Instance of the interface. public ClientLogController( IClientEventLogger clientEventLogger, - IAuthorizationContext authorizationContext, IServerConfigurationManager serverConfigurationManager) { _clientEventLogger = clientEventLogger; - _authorizationContext = authorizationContext; _serverConfigurationManager = serverConfigurationManager; } @@ -50,17 +47,15 @@ namespace Jellyfin.Api.Controllers [HttpPost] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status403Forbidden)] - public async Task LogEvent([FromBody] ClientLogEventDto clientLogEventDto) + public ActionResult LogEvent([FromBody] ClientLogEventDto clientLogEventDto) { if (!_serverConfigurationManager.Configuration.AllowClientLogUpload) { return Forbid(); } - var authorizationInfo = await _authorizationContext.GetAuthorizationInfo(Request) - .ConfigureAwait(false); - - Log(clientLogEventDto, authorizationInfo); + var (clientName, clientVersion, userId, deviceId) = GetRequestInformation(); + Log(clientLogEventDto, userId, clientName, clientVersion, deviceId); return NoContent(); } @@ -74,19 +69,17 @@ namespace Jellyfin.Api.Controllers [HttpPost("Bulk")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status403Forbidden)] - public async Task LogEvents([FromBody] ClientLogEventDto[] clientLogEventDtos) + public ActionResult LogEvents([FromBody] ClientLogEventDto[] clientLogEventDtos) { if (!_serverConfigurationManager.Configuration.AllowClientLogUpload) { return Forbid(); } - var authorizationInfo = await _authorizationContext.GetAuthorizationInfo(Request) - .ConfigureAwait(false); - + var (clientName, clientVersion, userId, deviceId) = GetRequestInformation(); foreach (var dto in clientLogEventDtos) { - Log(dto, authorizationInfo); + Log(dto, userId, clientName, clientVersion, deviceId); } return NoContent(); @@ -118,24 +111,39 @@ namespace Jellyfin.Api.Controllers return StatusCode(StatusCodes.Status413PayloadTooLarge, $"Payload must be less than {MaxDocumentSize:N0} bytes"); } - var authorizationInfo = await _authorizationContext.GetAuthorizationInfo(Request) - .ConfigureAwait(false); - - var fileName = await _clientEventLogger.WriteDocumentAsync(authorizationInfo, Request.Body) + var (clientName, clientVersion, _, _) = GetRequestInformation(); + var fileName = await _clientEventLogger.WriteDocumentAsync(clientName, clientVersion, Request.Body) .ConfigureAwait(false); return Ok(new ClientLogDocumentResponseDto(fileName)); } - private void Log(ClientLogEventDto dto, AuthorizationInfo authorizationInfo) + private void Log( + ClientLogEventDto dto, + Guid userId, + string clientName, + string clientVersion, + string deviceId) { _clientEventLogger.Log(new ClientLogEvent( dto.Timestamp, dto.Level, - authorizationInfo.UserId, - authorizationInfo.Client, - authorizationInfo.Version, - authorizationInfo.DeviceId, + userId, + clientName, + clientVersion, + deviceId, dto.Message)); } + + private (string ClientName, string ClientVersion, Guid UserId, string DeviceId) GetRequestInformation() + { + var clientName = ClaimHelpers.GetClient(HttpContext.User) ?? "unknown-client"; + var clientVersion = ClaimHelpers.GetIsApiKey(HttpContext.User) + ? "apikey" + : ClaimHelpers.GetVersion(HttpContext.User) ?? "unknown-version"; + var userId = ClaimHelpers.GetUserId(HttpContext.User) ?? Guid.Empty; + var deviceId = ClaimHelpers.GetDeviceId(HttpContext.User) ?? "unknown-device-id"; + + return (clientName, clientVersion, userId, deviceId); + } } } diff --git a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs index 870070d354..2dff0f931b 100644 --- a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs @@ -44,9 +44,9 @@ namespace MediaBrowser.Controller.ClientEvent } /// - public async Task WriteDocumentAsync(AuthorizationInfo authorizationInfo, Stream fileContents) + public async Task WriteDocumentAsync(string clientName, string clientVersion, Stream fileContents) { - var fileName = $"upload_{authorizationInfo.Client}_{(authorizationInfo.IsApiKey ? "apikey" : authorizationInfo.Version)}_{DateTime.UtcNow:yyyyMMddHHmmss}.log"; + var fileName = $"upload_{clientName}_{clientVersion}_{DateTime.UtcNow:yyyyMMddHHmmss}.log"; var logFilePath = Path.Combine(_applicationPaths.LogDirectoryPath, fileName); await using var fileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None); await fileContents.CopyToAsync(fileStream).ConfigureAwait(false); diff --git a/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs index 6fc54faf2f..34968d493e 100644 --- a/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/IClientEventLogger.cs @@ -19,9 +19,13 @@ namespace MediaBrowser.Controller.ClientEvent /// /// Writes a file to the log directory. /// - /// The current authorization info. + /// The client name writing the document. + /// The client version writing the document. /// The file contents to write. /// The created file name. - Task WriteDocumentAsync(AuthorizationInfo authorizationInfo, Stream fileContents); + Task WriteDocumentAsync( + string clientName, + string clientVersion, + Stream fileContents); } } From 892b05c5e60b812d02177cef189d5ee7e858e9ab Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Sun, 7 Nov 2021 08:20:11 -0700 Subject: [PATCH 13/14] Clean up redundant code --- MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs index 2dff0f931b..31e86f6159 100644 --- a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs @@ -1,7 +1,6 @@ using System; using System.IO; using System.Threading.Tasks; -using MediaBrowser.Controller.Net; using MediaBrowser.Model.ClientLog; using Microsoft.Extensions.Logging; @@ -50,7 +49,6 @@ namespace MediaBrowser.Controller.ClientEvent var logFilePath = Path.Combine(_applicationPaths.LogDirectoryPath, fileName); await using var fileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None); await fileContents.CopyToAsync(fileStream).ConfigureAwait(false); - await fileStream.FlushAsync().ConfigureAwait(false); return fileName; } } From 666e95e27f92eabb15d6ab7ae399bdbb95eeb318 Mon Sep 17 00:00:00 2001 From: Cody Robibero Date: Sun, 7 Nov 2021 11:41:56 -0700 Subject: [PATCH 14/14] Add randomization to generated filename --- MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs index 31e86f6159..82b5b4593c 100644 --- a/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs +++ b/MediaBrowser.Controller/ClientEvent/ClientEventLogger.cs @@ -45,7 +45,7 @@ namespace MediaBrowser.Controller.ClientEvent /// public async Task WriteDocumentAsync(string clientName, string clientVersion, Stream fileContents) { - var fileName = $"upload_{clientName}_{clientVersion}_{DateTime.UtcNow:yyyyMMddHHmmss}.log"; + var fileName = $"upload_{clientName}_{clientVersion}_{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}.log"; var logFilePath = Path.Combine(_applicationPaths.LogDirectoryPath, fileName); await using var fileStream = new FileStream(logFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None); await fileContents.CopyToAsync(fileStream).ConfigureAwait(false);