EnvironmentService.cs 10 KB

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