EnvironmentService.cs 11 KB

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