EnvironmentController.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.IO;
  5. using System.Linq;
  6. using Jellyfin.Api.Constants;
  7. using Jellyfin.Api.Models.EnvironmentDtos;
  8. using MediaBrowser.Common.Api;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Model.IO;
  11. using Microsoft.AspNetCore.Authorization;
  12. using Microsoft.AspNetCore.Http;
  13. using Microsoft.AspNetCore.Mvc;
  14. using Microsoft.Extensions.Logging;
  15. namespace Jellyfin.Api.Controllers;
  16. /// <summary>
  17. /// Environment Controller.
  18. /// </summary>
  19. [Authorize(Policy = Policies.FirstTimeSetupOrElevated)]
  20. public class EnvironmentController : BaseJellyfinApiController
  21. {
  22. private const char UncSeparator = '\\';
  23. private const string UncStartPrefix = @"\\";
  24. private readonly IFileSystem _fileSystem;
  25. private readonly ILogger<EnvironmentController> _logger;
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="EnvironmentController"/> class.
  28. /// </summary>
  29. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  30. /// <param name="logger">Instance of the <see cref="ILogger{EnvironmentController}"/> interface.</param>
  31. public EnvironmentController(IFileSystem fileSystem, ILogger<EnvironmentController> logger)
  32. {
  33. _fileSystem = fileSystem;
  34. _logger = logger;
  35. }
  36. /// <summary>
  37. /// Gets the contents of a given directory in the file system.
  38. /// </summary>
  39. /// <param name="path">The path.</param>
  40. /// <param name="includeFiles">An optional filter to include or exclude files from the results. true/false.</param>
  41. /// <param name="includeDirectories">An optional filter to include or exclude folders from the results. true/false.</param>
  42. /// <response code="200">Directory contents returned.</response>
  43. /// <returns>Directory contents.</returns>
  44. [HttpGet("DirectoryContents")]
  45. [ProducesResponseType(StatusCodes.Status200OK)]
  46. public IEnumerable<FileSystemEntryInfo> GetDirectoryContents(
  47. [FromQuery, Required] string path,
  48. [FromQuery] bool includeFiles = false,
  49. [FromQuery] bool includeDirectories = false)
  50. {
  51. if (path.StartsWith(UncStartPrefix, StringComparison.OrdinalIgnoreCase)
  52. && path.LastIndexOf(UncSeparator) == 1)
  53. {
  54. return Array.Empty<FileSystemEntryInfo>();
  55. }
  56. var entries =
  57. _fileSystem.GetFileSystemEntries(path)
  58. .Where(i => (i.IsDirectory && includeDirectories) || (!i.IsDirectory && includeFiles))
  59. .OrderBy(i => i.FullName);
  60. return entries.Select(f => new FileSystemEntryInfo(f.Name, f.FullName, f.IsDirectory ? FileSystemEntryType.Directory : FileSystemEntryType.File));
  61. }
  62. /// <summary>
  63. /// Validates path.
  64. /// </summary>
  65. /// <param name="validatePathDto">Validate request object.</param>
  66. /// <response code="204">Path validated.</response>
  67. /// <response code="404">Path not found.</response>
  68. /// <returns>Validation status.</returns>
  69. [HttpPost("ValidatePath")]
  70. [ProducesResponseType(StatusCodes.Status204NoContent)]
  71. [ProducesResponseType(StatusCodes.Status404NotFound)]
  72. public ActionResult ValidatePath([FromBody, Required] ValidatePathDto validatePathDto)
  73. {
  74. if (validatePathDto.IsFile.HasValue)
  75. {
  76. if (validatePathDto.IsFile.Value)
  77. {
  78. if (!System.IO.File.Exists(validatePathDto.Path))
  79. {
  80. return NotFound();
  81. }
  82. }
  83. else
  84. {
  85. if (!Directory.Exists(validatePathDto.Path))
  86. {
  87. return NotFound();
  88. }
  89. }
  90. }
  91. else
  92. {
  93. if (!System.IO.File.Exists(validatePathDto.Path) && !Directory.Exists(validatePathDto.Path))
  94. {
  95. return NotFound();
  96. }
  97. if (validatePathDto.ValidateWritable)
  98. {
  99. if (validatePathDto.Path is null)
  100. {
  101. throw new ResourceNotFoundException(nameof(validatePathDto.Path));
  102. }
  103. var file = Path.Combine(validatePathDto.Path, Guid.NewGuid().ToString());
  104. try
  105. {
  106. System.IO.File.WriteAllText(file, string.Empty);
  107. }
  108. finally
  109. {
  110. if (System.IO.File.Exists(file))
  111. {
  112. System.IO.File.Delete(file);
  113. }
  114. }
  115. }
  116. }
  117. return NoContent();
  118. }
  119. /// <summary>
  120. /// Gets network paths.
  121. /// </summary>
  122. /// <response code="200">Empty array returned.</response>
  123. /// <returns>List of entries.</returns>
  124. [Obsolete("This endpoint is obsolete.")]
  125. [HttpGet("NetworkShares")]
  126. [ProducesResponseType(StatusCodes.Status200OK)]
  127. public ActionResult<IEnumerable<FileSystemEntryInfo>> GetNetworkShares()
  128. {
  129. _logger.LogWarning("Obsolete endpoint accessed: /Environment/NetworkShares");
  130. return Array.Empty<FileSystemEntryInfo>();
  131. }
  132. /// <summary>
  133. /// Gets available drives from the server's file system.
  134. /// </summary>
  135. /// <response code="200">List of entries returned.</response>
  136. /// <returns>List of entries.</returns>
  137. [HttpGet("Drives")]
  138. [ProducesResponseType(StatusCodes.Status200OK)]
  139. public IEnumerable<FileSystemEntryInfo> GetDrives()
  140. {
  141. return _fileSystem.GetDrives().Select(d => new FileSystemEntryInfo(d.Name, d.FullName, FileSystemEntryType.Directory));
  142. }
  143. /// <summary>
  144. /// Gets the parent path of a given path.
  145. /// </summary>
  146. /// <param name="path">The path.</param>
  147. /// <returns>Parent path.</returns>
  148. [HttpGet("ParentPath")]
  149. [ProducesResponseType(StatusCodes.Status200OK)]
  150. public ActionResult<string?> GetParentPath([FromQuery, Required] string path)
  151. {
  152. string? parent = Path.GetDirectoryName(path);
  153. if (string.IsNullOrEmpty(parent))
  154. {
  155. // Check if unc share
  156. var index = path.LastIndexOf(UncSeparator);
  157. if (index != -1 && path[0] == UncSeparator)
  158. {
  159. parent = path.Substring(0, index);
  160. if (string.IsNullOrWhiteSpace(parent.TrimStart(UncSeparator)))
  161. {
  162. parent = null;
  163. }
  164. }
  165. }
  166. return parent;
  167. }
  168. /// <summary>
  169. /// Get Default directory browser.
  170. /// </summary>
  171. /// <response code="200">Default directory browser returned.</response>
  172. /// <returns>Default directory browser.</returns>
  173. [HttpGet("DefaultDirectoryBrowser")]
  174. [ProducesResponseType(StatusCodes.Status200OK)]
  175. public ActionResult<DefaultDirectoryBrowserInfoDto> GetDefaultDirectoryBrowser()
  176. {
  177. return new DefaultDirectoryBrowserInfoDto();
  178. }
  179. }