2
0

EnvironmentService.cs 10 KB

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