EnvironmentService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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.Net;
  10. using MediaBrowser.Model.Services;
  11. using Microsoft.Extensions.Logging;
  12. namespace MediaBrowser.Api
  13. {
  14. /// <summary>
  15. /// Class GetDirectoryContents
  16. /// </summary>
  17. [Route("/Environment/DirectoryContents", "GET", Summary = "Gets the contents of a given directory in the file system")]
  18. public class GetDirectoryContents : IReturn<List<FileSystemEntryInfo>>
  19. {
  20. /// <summary>
  21. /// Gets or sets the path.
  22. /// </summary>
  23. /// <value>The path.</value>
  24. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  25. public string Path { get; set; }
  26. /// <summary>
  27. /// Gets or sets a value indicating whether [include files].
  28. /// </summary>
  29. /// <value><c>true</c> if [include files]; otherwise, <c>false</c>.</value>
  30. [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")]
  31. public bool IncludeFiles { get; set; }
  32. /// <summary>
  33. /// Gets or sets a value indicating whether [include directories].
  34. /// </summary>
  35. /// <value><c>true</c> if [include directories]; otherwise, <c>false</c>.</value>
  36. [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")]
  37. public bool IncludeDirectories { get; set; }
  38. }
  39. [Route("/Environment/ValidatePath", "POST", Summary = "Gets the contents of a given directory in the file system")]
  40. public class ValidatePath
  41. {
  42. /// <summary>
  43. /// Gets or sets the path.
  44. /// </summary>
  45. /// <value>The path.</value>
  46. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  47. public string Path { get; set; }
  48. public bool ValidateWriteable { get; set; }
  49. public bool? IsFile { get; set; }
  50. }
  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) && path.LastIndexOf(UncSeparator) == 1)
  174. {
  175. return ToOptimizedResult(GetNetworkShares(path).OrderBy(i => i.Path).ToList());
  176. }
  177. return ToOptimizedResult(GetFileSystemEntries(request).ToList());
  178. }
  179. public object Get(GetNetworkShares request)
  180. {
  181. var path = request.Path;
  182. var shares = GetNetworkShares(path).OrderBy(i => i.Path).ToList();
  183. return ToOptimizedResult(shares);
  184. }
  185. /// <summary>
  186. /// Gets the specified request.
  187. /// </summary>
  188. /// <param name="request">The request.</param>
  189. /// <returns>System.Object.</returns>
  190. public object Get(GetDrives request)
  191. {
  192. var result = GetDrives().ToList();
  193. return ToOptimizedResult(result);
  194. }
  195. /// <summary>
  196. /// Gets the list that is returned when an empty path is supplied
  197. /// </summary>
  198. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  199. private IEnumerable<FileSystemEntryInfo> GetDrives()
  200. {
  201. return _fileSystem.GetDrives().Select(d => new FileSystemEntryInfo
  202. {
  203. Name = d.Name,
  204. Path = d.FullName,
  205. Type = FileSystemEntryType.Directory
  206. });
  207. }
  208. /// <summary>
  209. /// Gets the specified request.
  210. /// </summary>
  211. /// <param name="request">The request.</param>
  212. /// <returns>System.Object.</returns>
  213. public object Get(GetNetworkDevices request)
  214. {
  215. var result = _networkManager.GetNetworkDevices().ToList();
  216. return ToOptimizedResult(result);
  217. }
  218. /// <summary>
  219. /// Gets the network shares.
  220. /// </summary>
  221. /// <param name="path">The path.</param>
  222. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  223. private IEnumerable<FileSystemEntryInfo> GetNetworkShares(string path)
  224. {
  225. return _networkManager.GetNetworkShares(path).Where(s => s.ShareType == NetworkShareType.Disk).Select(c => new FileSystemEntryInfo
  226. {
  227. Name = c.Name,
  228. Path = Path.Combine(path, c.Name),
  229. Type = FileSystemEntryType.NetworkShare
  230. });
  231. }
  232. /// <summary>
  233. /// Gets the file system entries.
  234. /// </summary>
  235. /// <param name="request">The request.</param>
  236. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  237. private IEnumerable<FileSystemEntryInfo> GetFileSystemEntries(GetDirectoryContents request)
  238. {
  239. var entries = _fileSystem.GetFileSystemEntries(request.Path).OrderBy(i => i.FullName).Where(i =>
  240. {
  241. var isDirectory = i.IsDirectory;
  242. if (!request.IncludeFiles && !isDirectory)
  243. {
  244. return false;
  245. }
  246. if (!request.IncludeDirectories && isDirectory)
  247. {
  248. return false;
  249. }
  250. return true;
  251. });
  252. return entries.Select(f => new FileSystemEntryInfo
  253. {
  254. Name = f.Name,
  255. Path = f.FullName,
  256. Type = f.IsDirectory ? FileSystemEntryType.Directory : FileSystemEntryType.File
  257. });
  258. }
  259. public object Get(GetParentPath request)
  260. {
  261. var parent = Path.GetDirectoryName(request.Path);
  262. if (string.IsNullOrEmpty(parent))
  263. {
  264. // Check if unc share
  265. var index = request.Path.LastIndexOf(UncSeparator);
  266. if (index != -1 && request.Path.IndexOf(UncSeparator) == 0)
  267. {
  268. parent = request.Path.Substring(0, index);
  269. if (string.IsNullOrWhiteSpace(parent.TrimStart(UncSeparator)))
  270. {
  271. parent = null;
  272. }
  273. }
  274. }
  275. return parent;
  276. }
  277. }
  278. }