EnvironmentController.cs 6.8 KB

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