EnvironmentService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Net;
  4. using MediaBrowser.Model.IO;
  5. using MediaBrowser.Model.Net;
  6. using ServiceStack;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Linq;
  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. /// <summary>
  39. /// Gets or sets a value indicating whether [include hidden].
  40. /// </summary>
  41. /// <value><c>true</c> if [include hidden]; otherwise, <c>false</c>.</value>
  42. [ApiMember(Name = "IncludeHidden", Description = "An optional filter to include or exclude hidden files and folders. true/false", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")]
  43. public bool IncludeHidden { get; set; }
  44. }
  45. [Route("/Environment/NetworkShares", "GET", Summary = "Gets shares from a network device")]
  46. public class GetNetworkShares : IReturn<List<FileSystemEntryInfo>>
  47. {
  48. /// <summary>
  49. /// Gets or sets the path.
  50. /// </summary>
  51. /// <value>The path.</value>
  52. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  53. public string Path { get; set; }
  54. }
  55. /// <summary>
  56. /// Class GetDrives
  57. /// </summary>
  58. [Route("/Environment/Drives", "GET", Summary = "Gets available drives from the server's file system")]
  59. public class GetDrives : IReturn<List<FileSystemEntryInfo>>
  60. {
  61. }
  62. /// <summary>
  63. /// Class GetNetworkComputers
  64. /// </summary>
  65. [Route("/Environment/NetworkDevices", "GET", Summary = "Gets a list of devices on the network")]
  66. public class GetNetworkDevices : IReturn<List<FileSystemEntryInfo>>
  67. {
  68. }
  69. [Route("/Environment/ParentPath", "GET", Summary = "Gets the parent path of a given path")]
  70. public class GetParentPath : IReturn<string>
  71. {
  72. /// <summary>
  73. /// Gets or sets the path.
  74. /// </summary>
  75. /// <value>The path.</value>
  76. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  77. public string Path { get; set; }
  78. }
  79. /// <summary>
  80. /// Class EnvironmentService
  81. /// </summary>
  82. [Authenticated(Roles = "Admin", AllowBeforeStartupWizard = true)]
  83. public class EnvironmentService : BaseApiService
  84. {
  85. const char UncSeparator = '\\';
  86. /// <summary>
  87. /// The _network manager
  88. /// </summary>
  89. private readonly INetworkManager _networkManager;
  90. private IFileSystem _fileSystem;
  91. /// <summary>
  92. /// Initializes a new instance of the <see cref="EnvironmentService" /> class.
  93. /// </summary>
  94. /// <param name="networkManager">The network manager.</param>
  95. /// <exception cref="System.ArgumentNullException">networkManager</exception>
  96. public EnvironmentService(INetworkManager networkManager, IFileSystem fileSystem)
  97. {
  98. if (networkManager == null)
  99. {
  100. throw new ArgumentNullException("networkManager");
  101. }
  102. _networkManager = networkManager;
  103. _fileSystem = fileSystem;
  104. }
  105. /// <summary>
  106. /// Gets the specified request.
  107. /// </summary>
  108. /// <param name="request">The request.</param>
  109. /// <returns>System.Object.</returns>
  110. /// <exception cref="System.ArgumentNullException">Path</exception>
  111. /// <exception cref="System.ArgumentException"></exception>
  112. public object Get(GetDirectoryContents request)
  113. {
  114. var path = request.Path;
  115. if (string.IsNullOrEmpty(path))
  116. {
  117. throw new ArgumentNullException("Path");
  118. }
  119. var networkPrefix = UncSeparator.ToString(CultureInfo.InvariantCulture) + UncSeparator.ToString(CultureInfo.InvariantCulture);
  120. if (path.StartsWith(networkPrefix, StringComparison.OrdinalIgnoreCase) && path.LastIndexOf(UncSeparator) == 1)
  121. {
  122. return ToOptimizedSerializedResultUsingCache(GetNetworkShares(path).OrderBy(i => i.Path).ToList());
  123. }
  124. try
  125. {
  126. return ToOptimizedSerializedResultUsingCache(GetFileSystemEntries(request).OrderBy(i => i.Path).ToList());
  127. }
  128. catch (UnauthorizedAccessException)
  129. {
  130. // Don't throw the original UnauthorizedAccessException because it will cause a 401 response
  131. throw new ApplicationException("Access to the path " + request.Path + " is denied.");
  132. }
  133. }
  134. public object Get(GetNetworkShares request)
  135. {
  136. var path = request.Path;
  137. var shares = GetNetworkShares(path).OrderBy(i => i.Path).ToList();
  138. return ToOptimizedSerializedResultUsingCache(shares);
  139. }
  140. /// <summary>
  141. /// Gets the specified request.
  142. /// </summary>
  143. /// <param name="request">The request.</param>
  144. /// <returns>System.Object.</returns>
  145. public object Get(GetDrives request)
  146. {
  147. var result = GetDrives().ToList();
  148. return ToOptimizedSerializedResultUsingCache(result);
  149. }
  150. /// <summary>
  151. /// Gets the list that is returned when an empty path is supplied
  152. /// </summary>
  153. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  154. private IEnumerable<FileSystemEntryInfo> GetDrives()
  155. {
  156. // Only include drives in the ready state or this method could end up being very slow, waiting for drives to timeout
  157. return DriveInfo.GetDrives().Where(d => d.IsReady).Select(d => new FileSystemEntryInfo
  158. {
  159. Name = GetName(d),
  160. Path = d.RootDirectory.FullName,
  161. Type = FileSystemEntryType.Directory
  162. });
  163. }
  164. /// <summary>
  165. /// Gets the specified request.
  166. /// </summary>
  167. /// <param name="request">The request.</param>
  168. /// <returns>System.Object.</returns>
  169. public object Get(GetNetworkDevices request)
  170. {
  171. var result = _networkManager.GetNetworkDevices()
  172. .OrderBy(i => i.Path)
  173. .ToList();
  174. return ToOptimizedSerializedResultUsingCache(result);
  175. }
  176. /// <summary>
  177. /// Gets the name.
  178. /// </summary>
  179. /// <param name="drive">The drive.</param>
  180. /// <returns>System.String.</returns>
  181. private string GetName(DriveInfo drive)
  182. {
  183. return drive.Name;
  184. }
  185. /// <summary>
  186. /// Gets the network shares.
  187. /// </summary>
  188. /// <param name="path">The path.</param>
  189. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  190. private IEnumerable<FileSystemEntryInfo> GetNetworkShares(string path)
  191. {
  192. return _networkManager.GetNetworkShares(path).Where(s => s.ShareType == NetworkShareType.Disk).Select(c => new FileSystemEntryInfo
  193. {
  194. Name = c.Name,
  195. Path = Path.Combine(path, c.Name),
  196. Type = FileSystemEntryType.NetworkShare
  197. });
  198. }
  199. /// <summary>
  200. /// Gets the file system entries.
  201. /// </summary>
  202. /// <param name="request">The request.</param>
  203. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  204. private IEnumerable<FileSystemEntryInfo> GetFileSystemEntries(GetDirectoryContents request)
  205. {
  206. // using EnumerateFileSystemInfos doesn't handle reparse points (symlinks)
  207. var entries = _fileSystem.GetFileSystemEntries(request.Path).Where(i =>
  208. {
  209. if (!request.IncludeHidden && i.Attributes.HasFlag(FileAttributes.Hidden))
  210. {
  211. return false;
  212. }
  213. var isDirectory = i.Attributes.HasFlag(FileAttributes.Directory);
  214. if (!request.IncludeFiles && !isDirectory)
  215. {
  216. return false;
  217. }
  218. if (!request.IncludeDirectories && isDirectory)
  219. {
  220. return false;
  221. }
  222. return true;
  223. });
  224. return entries.Select(f => new FileSystemEntryInfo
  225. {
  226. Name = f.Name,
  227. Path = f.FullName,
  228. Type = f.Attributes.HasFlag(FileAttributes.Directory) ? FileSystemEntryType.Directory : FileSystemEntryType.File
  229. }).ToList();
  230. }
  231. public object Get(GetParentPath request)
  232. {
  233. var parent = Path.GetDirectoryName(request.Path);
  234. if (string.IsNullOrEmpty(parent))
  235. {
  236. // Check if unc share
  237. var index = request.Path.LastIndexOf(UncSeparator);
  238. if (index != -1 && request.Path.IndexOf(UncSeparator) == 0)
  239. {
  240. parent = request.Path.Substring(0, index);
  241. if (string.IsNullOrWhiteSpace(parent.TrimStart(UncSeparator)))
  242. {
  243. parent = null;
  244. }
  245. }
  246. }
  247. return parent;
  248. }
  249. }
  250. }