EnvironmentService.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Net;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.Services;
  10. using Microsoft.Extensions.Logging;
  11. namespace MediaBrowser.Api
  12. {
  13. /// <summary>
  14. /// Class GetDirectoryContents
  15. /// </summary>
  16. [Route("/Environment/DirectoryContents", "GET", Summary = "Gets the contents of a given directory in the file system")]
  17. public class GetDirectoryContents : IReturn<List<FileSystemEntryInfo>>
  18. {
  19. /// <summary>
  20. /// Gets or sets the path.
  21. /// </summary>
  22. /// <value>The path.</value>
  23. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  24. public string Path { get; set; }
  25. /// <summary>
  26. /// Gets or sets a value indicating whether [include files].
  27. /// </summary>
  28. /// <value><c>true</c> if [include files]; otherwise, <c>false</c>.</value>
  29. [ApiMember(Name = "IncludeFiles", Description = "An optional filter to include or exclude files from the results. true/false", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
  30. public bool IncludeFiles { get; set; }
  31. /// <summary>
  32. /// Gets or sets a value indicating whether [include directories].
  33. /// </summary>
  34. /// <value><c>true</c> if [include directories]; otherwise, <c>false</c>.</value>
  35. [ApiMember(Name = "IncludeDirectories", Description = "An optional filter to include or exclude folders from the results. true/false", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
  36. public bool IncludeDirectories { get; set; }
  37. }
  38. [Route("/Environment/ValidatePath", "POST", Summary = "Gets the contents of a given directory in the file system")]
  39. public class ValidatePath
  40. {
  41. /// <summary>
  42. /// Gets or sets the path.
  43. /// </summary>
  44. /// <value>The path.</value>
  45. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  46. public string Path { get; set; }
  47. public bool ValidateWriteable { get; set; }
  48. public bool? IsFile { get; set; }
  49. }
  50. [Obsolete]
  51. [Route("/Environment/NetworkShares", "GET", Summary = "Gets shares from a network device")]
  52. public class GetNetworkShares : IReturn<List<FileSystemEntryInfo>>
  53. {
  54. /// <summary>
  55. /// Gets or sets the path.
  56. /// </summary>
  57. /// <value>The path.</value>
  58. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  59. public string Path { get; set; }
  60. }
  61. /// <summary>
  62. /// Class GetDrives
  63. /// </summary>
  64. [Route("/Environment/Drives", "GET", Summary = "Gets available drives from the server's file system")]
  65. public class GetDrives : IReturn<List<FileSystemEntryInfo>>
  66. {
  67. }
  68. /// <summary>
  69. /// Class GetNetworkComputers
  70. /// </summary>
  71. [Route("/Environment/NetworkDevices", "GET", Summary = "Gets a list of devices on the network")]
  72. public class GetNetworkDevices : IReturn<List<FileSystemEntryInfo>>
  73. {
  74. }
  75. [Route("/Environment/ParentPath", "GET", Summary = "Gets the parent path of a given path")]
  76. public class GetParentPath : IReturn<string>
  77. {
  78. /// <summary>
  79. /// Gets or sets the path.
  80. /// </summary>
  81. /// <value>The path.</value>
  82. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  83. public string Path { get; set; }
  84. }
  85. public class DefaultDirectoryBrowserInfo
  86. {
  87. public string Path { get; set; }
  88. }
  89. [Route("/Environment/DefaultDirectoryBrowser", "GET", Summary = "Gets the parent path of a given path")]
  90. public class GetDefaultDirectoryBrowser : IReturn<DefaultDirectoryBrowserInfo>
  91. {
  92. }
  93. /// <summary>
  94. /// Class EnvironmentService
  95. /// </summary>
  96. [Authenticated(Roles = "Admin", AllowBeforeStartupWizard = true)]
  97. public class EnvironmentService : BaseApiService
  98. {
  99. private const char UncSeparator = '\\';
  100. private const string UncSeparatorString = "\\";
  101. /// <summary>
  102. /// The _network manager
  103. /// </summary>
  104. private readonly INetworkManager _networkManager;
  105. private readonly IFileSystem _fileSystem;
  106. /// <summary>
  107. /// Initializes a new instance of the <see cref="EnvironmentService" /> class.
  108. /// </summary>
  109. /// <param name="networkManager">The network manager.</param>
  110. public EnvironmentService(
  111. ILogger<EnvironmentService> logger,
  112. IServerConfigurationManager serverConfigurationManager,
  113. IHttpResultFactory httpResultFactory,
  114. INetworkManager networkManager,
  115. IFileSystem fileSystem)
  116. : base(logger, serverConfigurationManager, httpResultFactory)
  117. {
  118. _networkManager = networkManager;
  119. _fileSystem = fileSystem;
  120. }
  121. public void Post(ValidatePath request)
  122. {
  123. if (request.IsFile.HasValue)
  124. {
  125. if (request.IsFile.Value)
  126. {
  127. if (!File.Exists(request.Path))
  128. {
  129. throw new FileNotFoundException("File not found", request.Path);
  130. }
  131. }
  132. else
  133. {
  134. if (!Directory.Exists(request.Path))
  135. {
  136. throw new FileNotFoundException("File not found", request.Path);
  137. }
  138. }
  139. }
  140. else
  141. {
  142. if (!File.Exists(request.Path) && !Directory.Exists(request.Path))
  143. {
  144. throw new FileNotFoundException("Path not found", request.Path);
  145. }
  146. if (request.ValidateWriteable)
  147. {
  148. EnsureWriteAccess(request.Path);
  149. }
  150. }
  151. }
  152. protected void EnsureWriteAccess(string path)
  153. {
  154. var file = Path.Combine(path, Guid.NewGuid().ToString());
  155. File.WriteAllText(file, string.Empty);
  156. _fileSystem.DeleteFile(file);
  157. }
  158. public object Get(GetDefaultDirectoryBrowser request) =>
  159. ToOptimizedResult(new DefaultDirectoryBrowserInfo { Path = null });
  160. /// <summary>
  161. /// Gets the specified request.
  162. /// </summary>
  163. /// <param name="request">The request.</param>
  164. /// <returns>System.Object.</returns>
  165. public object Get(GetDirectoryContents request)
  166. {
  167. var path = request.Path;
  168. if (string.IsNullOrEmpty(path))
  169. {
  170. throw new ArgumentNullException(nameof(Path));
  171. }
  172. var networkPrefix = UncSeparatorString + UncSeparatorString;
  173. if (path.StartsWith(networkPrefix, StringComparison.OrdinalIgnoreCase)
  174. && path.LastIndexOf(UncSeparator) == 1)
  175. {
  176. return ToOptimizedResult(Array.Empty<FileSystemEntryInfo>());
  177. }
  178. return ToOptimizedResult(GetFileSystemEntries(request).ToList());
  179. }
  180. [Obsolete]
  181. public object Get(GetNetworkShares request)
  182. => ToOptimizedResult(Array.Empty<FileSystemEntryInfo>());
  183. /// <summary>
  184. /// Gets the specified request.
  185. /// </summary>
  186. /// <param name="request">The request.</param>
  187. /// <returns>System.Object.</returns>
  188. public object Get(GetDrives request)
  189. {
  190. var result = GetDrives().ToList();
  191. return ToOptimizedResult(result);
  192. }
  193. /// <summary>
  194. /// Gets the list that is returned when an empty path is supplied
  195. /// </summary>
  196. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  197. private IEnumerable<FileSystemEntryInfo> GetDrives()
  198. {
  199. return _fileSystem.GetDrives().Select(d => new FileSystemEntryInfo(d.Name, d.FullName, FileSystemEntryType.Directory));
  200. }
  201. /// <summary>
  202. /// Gets the specified request.
  203. /// </summary>
  204. /// <param name="request">The request.</param>
  205. /// <returns>System.Object.</returns>
  206. public object Get(GetNetworkDevices request)
  207. => ToOptimizedResult(Array.Empty<FileSystemEntryInfo>());
  208. /// <summary>
  209. /// Gets the file system entries.
  210. /// </summary>
  211. /// <param name="request">The request.</param>
  212. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  213. private IEnumerable<FileSystemEntryInfo> GetFileSystemEntries(GetDirectoryContents request)
  214. {
  215. var entries = _fileSystem.GetFileSystemEntries(request.Path).OrderBy(i => i.FullName).Where(i =>
  216. {
  217. var isDirectory = i.IsDirectory;
  218. if (!request.IncludeFiles && !isDirectory)
  219. {
  220. return false;
  221. }
  222. if (!request.IncludeDirectories && isDirectory)
  223. {
  224. return false;
  225. }
  226. return true;
  227. });
  228. return entries.Select(f => new FileSystemEntryInfo(f.Name, f.FullName, f.IsDirectory ? FileSystemEntryType.Directory : FileSystemEntryType.File));
  229. }
  230. public object Get(GetParentPath request)
  231. {
  232. var parent = Path.GetDirectoryName(request.Path);
  233. if (string.IsNullOrEmpty(parent))
  234. {
  235. // Check if unc share
  236. var index = request.Path.LastIndexOf(UncSeparator);
  237. if (index != -1 && request.Path.IndexOf(UncSeparator) == 0)
  238. {
  239. parent = request.Path.Substring(0, index);
  240. if (string.IsNullOrWhiteSpace(parent.TrimStart(UncSeparator)))
  241. {
  242. parent = null;
  243. }
  244. }
  245. }
  246. return parent;
  247. }
  248. }
  249. }