SystemController.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Mime;
  8. using System.Threading.Tasks;
  9. using Jellyfin.Api.Attributes;
  10. using Jellyfin.Api.Constants;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Common.Extensions;
  13. using MediaBrowser.Common.Net;
  14. using MediaBrowser.Controller;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Model.IO;
  17. using MediaBrowser.Model.Net;
  18. using MediaBrowser.Model.System;
  19. using Microsoft.AspNetCore.Authorization;
  20. using Microsoft.AspNetCore.Http;
  21. using Microsoft.AspNetCore.Mvc;
  22. using Microsoft.Extensions.Logging;
  23. namespace Jellyfin.Api.Controllers
  24. {
  25. /// <summary>
  26. /// The system controller.
  27. /// </summary>
  28. public class SystemController : BaseJellyfinApiController
  29. {
  30. private readonly IServerApplicationHost _appHost;
  31. private readonly IApplicationPaths _appPaths;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly INetworkManager _network;
  34. private readonly ILogger<SystemController> _logger;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="SystemController"/> class.
  37. /// </summary>
  38. /// <param name="serverConfigurationManager">Instance of <see cref="IServerConfigurationManager"/> interface.</param>
  39. /// <param name="appHost">Instance of <see cref="IServerApplicationHost"/> interface.</param>
  40. /// <param name="fileSystem">Instance of <see cref="IFileSystem"/> interface.</param>
  41. /// <param name="network">Instance of <see cref="INetworkManager"/> interface.</param>
  42. /// <param name="logger">Instance of <see cref="ILogger{SystemController}"/> interface.</param>
  43. public SystemController(
  44. IServerConfigurationManager serverConfigurationManager,
  45. IServerApplicationHost appHost,
  46. IFileSystem fileSystem,
  47. INetworkManager network,
  48. ILogger<SystemController> logger)
  49. {
  50. _appPaths = serverConfigurationManager.ApplicationPaths;
  51. _appHost = appHost;
  52. _fileSystem = fileSystem;
  53. _network = network;
  54. _logger = logger;
  55. }
  56. /// <summary>
  57. /// Gets information about the server.
  58. /// </summary>
  59. /// <response code="200">Information retrieved.</response>
  60. /// <returns>A <see cref="SystemInfo"/> with info about the system.</returns>
  61. [HttpGet("Info")]
  62. [Authorize(Policy = Policies.FirstTimeSetupOrIgnoreParentalControl)]
  63. [ProducesResponseType(StatusCodes.Status200OK)]
  64. public ActionResult<SystemInfo> GetSystemInfo()
  65. {
  66. return _appHost.GetSystemInfo(Request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
  67. }
  68. /// <summary>
  69. /// Gets public information about the server.
  70. /// </summary>
  71. /// <response code="200">Information retrieved.</response>
  72. /// <returns>A <see cref="PublicSystemInfo"/> with public info about the system.</returns>
  73. [HttpGet("Info/Public")]
  74. [ProducesResponseType(StatusCodes.Status200OK)]
  75. public ActionResult<PublicSystemInfo> GetPublicSystemInfo()
  76. {
  77. return _appHost.GetPublicSystemInfo(Request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
  78. }
  79. /// <summary>
  80. /// Pings the system.
  81. /// </summary>
  82. /// <param name="params">Optional: Parameters to echo back in the response.</param>
  83. /// <response code="200">Information retrieved.</response>
  84. /// <returns>The server name.</returns>
  85. [HttpGet("Ping", Name = "GetPingSystem")]
  86. [HttpPost("Ping", Name = "PostPingSystem")]
  87. [ProducesResponseType(StatusCodes.Status200OK)]
  88. public ActionResult<string> PingSystem([FromQuery]Dictionary<string, string>? @params = null)
  89. {
  90. if (@params != null && @params.Count > 0)
  91. {
  92. Response.Headers.Add("querystring", string.Join("&", @params.Select(x => x.Key + "=" + x.Value)));
  93. }
  94. return _appHost.Name;
  95. }
  96. /// <summary>
  97. /// Restarts the application.
  98. /// </summary>
  99. /// <response code="204">Server restarted.</response>
  100. /// <returns>No content. Server restarted.</returns>
  101. [HttpPost("Restart")]
  102. [Authorize(Policy = Policies.LocalAccessOrRequiresElevation)]
  103. [ProducesResponseType(StatusCodes.Status204NoContent)]
  104. public ActionResult RestartApplication()
  105. {
  106. Task.Run(async () =>
  107. {
  108. await Task.Delay(100).ConfigureAwait(false);
  109. _appHost.Restart();
  110. });
  111. return NoContent();
  112. }
  113. /// <summary>
  114. /// Shuts down the application.
  115. /// </summary>
  116. /// <response code="204">Server shut down.</response>
  117. /// <returns>No content. Server shut down.</returns>
  118. [HttpPost("Shutdown")]
  119. [Authorize(Policy = Policies.RequiresElevation)]
  120. [ProducesResponseType(StatusCodes.Status204NoContent)]
  121. public ActionResult ShutdownApplication()
  122. {
  123. Task.Run(async () =>
  124. {
  125. await Task.Delay(100).ConfigureAwait(false);
  126. await _appHost.Shutdown().ConfigureAwait(false);
  127. });
  128. return NoContent();
  129. }
  130. /// <summary>
  131. /// Gets a list of available server log files.
  132. /// </summary>
  133. /// <response code="200">Information retrieved.</response>
  134. /// <returns>An array of <see cref="LogFile"/> with the available log files.</returns>
  135. [HttpGet("Logs")]
  136. [Authorize(Policy = Policies.RequiresElevation)]
  137. [ProducesResponseType(StatusCodes.Status200OK)]
  138. public ActionResult<LogFile[]> GetServerLogs()
  139. {
  140. IEnumerable<FileSystemMetadata> files;
  141. try
  142. {
  143. files = _fileSystem.GetFiles(_appPaths.LogDirectoryPath, new[] { ".txt", ".log" }, true, false);
  144. }
  145. catch (IOException ex)
  146. {
  147. _logger.LogError(ex, "Error getting logs");
  148. files = Enumerable.Empty<FileSystemMetadata>();
  149. }
  150. var result = files.Select(i => new LogFile
  151. {
  152. DateCreated = _fileSystem.GetCreationTimeUtc(i),
  153. DateModified = _fileSystem.GetLastWriteTimeUtc(i),
  154. Name = i.Name,
  155. Size = i.Length
  156. })
  157. .OrderByDescending(i => i.DateModified)
  158. .ThenByDescending(i => i.DateCreated)
  159. .ThenBy(i => i.Name)
  160. .ToArray();
  161. return result;
  162. }
  163. /// <summary>
  164. /// Gets information about the request endpoint.
  165. /// </summary>
  166. /// <response code="200">Information retrieved.</response>
  167. /// <returns><see cref="EndPointInfo"/> with information about the endpoint.</returns>
  168. [HttpGet("Endpoint")]
  169. [Authorize(Policy = Policies.DefaultAuthorization)]
  170. [ProducesResponseType(StatusCodes.Status200OK)]
  171. public ActionResult<EndPointInfo> GetEndpointInfo()
  172. {
  173. return new EndPointInfo
  174. {
  175. IsLocal = HttpContext.IsLocal(),
  176. IsInNetwork = _network.IsInLocalNetwork(HttpContext.GetNormalizedRemoteIp())
  177. };
  178. }
  179. /// <summary>
  180. /// Gets a log file.
  181. /// </summary>
  182. /// <param name="name">The name of the log file to get.</param>
  183. /// <response code="200">Log file retrieved.</response>
  184. /// <returns>The log file.</returns>
  185. [HttpGet("Logs/Log")]
  186. [Authorize(Policy = Policies.RequiresElevation)]
  187. [ProducesResponseType(StatusCodes.Status200OK)]
  188. [ProducesFile(MediaTypeNames.Text.Plain)]
  189. public ActionResult GetLogFile([FromQuery, Required] string name)
  190. {
  191. var file = _fileSystem.GetFiles(_appPaths.LogDirectoryPath)
  192. .First(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase));
  193. // For older files, assume fully static
  194. var fileShare = file.LastWriteTimeUtc < DateTime.UtcNow.AddHours(-1) ? FileShare.Read : FileShare.ReadWrite;
  195. FileStream stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, fileShare);
  196. return File(stream, "text/plain; charset=utf-8");
  197. }
  198. /// <summary>
  199. /// Gets wake on lan information.
  200. /// </summary>
  201. /// <response code="200">Information retrieved.</response>
  202. /// <returns>An <see cref="IEnumerable{WakeOnLanInfo}"/> with the WakeOnLan infos.</returns>
  203. [HttpGet("WakeOnLanInfo")]
  204. [Authorize(Policy = Policies.DefaultAuthorization)]
  205. [ProducesResponseType(StatusCodes.Status200OK)]
  206. public ActionResult<IEnumerable<WakeOnLanInfo>> GetWakeOnLanInfo()
  207. {
  208. var result = _appHost.GetWakeOnLanInfo();
  209. return Ok(result);
  210. }
  211. }
  212. }