EnvironmentService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Net;
  3. using MediaBrowser.Model.IO;
  4. using MediaBrowser.Model.Net;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using MediaBrowser.Model.Services;
  10. namespace MediaBrowser.Api
  11. {
  12. /// <summary>
  13. /// Class GetDirectoryContents
  14. /// </summary>
  15. [Route("/Environment/DirectoryContents", "GET", Summary = "Gets the contents of a given directory in the file system")]
  16. public class GetDirectoryContents : IReturn<List<FileSystemEntryInfo>>
  17. {
  18. /// <summary>
  19. /// Gets or sets the path.
  20. /// </summary>
  21. /// <value>The path.</value>
  22. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  23. public string Path { get; set; }
  24. /// <summary>
  25. /// Gets or sets a value indicating whether [include files].
  26. /// </summary>
  27. /// <value><c>true</c> if [include files]; otherwise, <c>false</c>.</value>
  28. [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")]
  29. public bool IncludeFiles { get; set; }
  30. /// <summary>
  31. /// Gets or sets a value indicating whether [include directories].
  32. /// </summary>
  33. /// <value><c>true</c> if [include directories]; otherwise, <c>false</c>.</value>
  34. [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")]
  35. public bool IncludeDirectories { get; set; }
  36. /// <summary>
  37. /// Gets or sets a value indicating whether [include hidden].
  38. /// </summary>
  39. /// <value><c>true</c> if [include hidden]; otherwise, <c>false</c>.</value>
  40. [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")]
  41. public bool IncludeHidden { get; set; }
  42. public GetDirectoryContents()
  43. {
  44. IncludeHidden = true;
  45. }
  46. }
  47. [Route("/Environment/ValidatePath", "POST", Summary = "Gets the contents of a given directory in the file system")]
  48. public class ValidatePath
  49. {
  50. /// <summary>
  51. /// Gets or sets the path.
  52. /// </summary>
  53. /// <value>The path.</value>
  54. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "POST")]
  55. public string Path { get; set; }
  56. public bool ValidateWriteable { get; set; }
  57. public bool? IsFile { get; set; }
  58. }
  59. [Route("/Environment/NetworkShares", "GET", Summary = "Gets shares from a network device")]
  60. public class GetNetworkShares : IReturn<List<FileSystemEntryInfo>>
  61. {
  62. /// <summary>
  63. /// Gets or sets the path.
  64. /// </summary>
  65. /// <value>The path.</value>
  66. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  67. public string Path { get; set; }
  68. }
  69. /// <summary>
  70. /// Class GetDrives
  71. /// </summary>
  72. [Route("/Environment/Drives", "GET", Summary = "Gets available drives from the server's file system")]
  73. public class GetDrives : IReturn<List<FileSystemEntryInfo>>
  74. {
  75. }
  76. /// <summary>
  77. /// Class GetNetworkComputers
  78. /// </summary>
  79. [Route("/Environment/NetworkDevices", "GET", Summary = "Gets a list of devices on the network")]
  80. public class GetNetworkDevices : IReturn<List<FileSystemEntryInfo>>
  81. {
  82. }
  83. [Route("/Environment/ParentPath", "GET", Summary = "Gets the parent path of a given path")]
  84. public class GetParentPath : IReturn<string>
  85. {
  86. /// <summary>
  87. /// Gets or sets the path.
  88. /// </summary>
  89. /// <value>The path.</value>
  90. [ApiMember(Name = "Path", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  91. public string Path { get; set; }
  92. }
  93. public class DefaultDirectoryBrowserInfo
  94. {
  95. public string Path { get; set; }
  96. }
  97. [Route("/Environment/DefaultDirectoryBrowser", "GET", Summary = "Gets the parent path of a given path")]
  98. public class GetDefaultDirectoryBrowser : IReturn<DefaultDirectoryBrowserInfo>
  99. {
  100. }
  101. /// <summary>
  102. /// Class EnvironmentService
  103. /// </summary>
  104. [Authenticated(Roles = "Admin", AllowBeforeStartupWizard = true)]
  105. public class EnvironmentService : BaseApiService
  106. {
  107. const char UncSeparator = '\\';
  108. const string UncSeparatorString = "\\";
  109. /// <summary>
  110. /// The _network manager
  111. /// </summary>
  112. private readonly INetworkManager _networkManager;
  113. private readonly IFileSystem _fileSystem;
  114. /// <summary>
  115. /// Initializes a new instance of the <see cref="EnvironmentService" /> class.
  116. /// </summary>
  117. /// <param name="networkManager">The network manager.</param>
  118. public EnvironmentService(INetworkManager networkManager, IFileSystem fileSystem)
  119. {
  120. if (networkManager == null)
  121. {
  122. throw new ArgumentNullException("networkManager");
  123. }
  124. _networkManager = networkManager;
  125. _fileSystem = fileSystem;
  126. }
  127. public void Post(ValidatePath request)
  128. {
  129. if (request.IsFile.HasValue)
  130. {
  131. if (request.IsFile.Value)
  132. {
  133. if (!_fileSystem.FileExists(request.Path))
  134. {
  135. throw new FileNotFoundException("File not found", request.Path);
  136. }
  137. }
  138. else
  139. {
  140. if (!_fileSystem.DirectoryExists(request.Path))
  141. {
  142. throw new FileNotFoundException("File not found", request.Path);
  143. }
  144. }
  145. }
  146. else
  147. {
  148. if (!_fileSystem.FileExists(request.Path) && !_fileSystem.DirectoryExists(request.Path))
  149. {
  150. throw new FileNotFoundException("Path not found", request.Path);
  151. }
  152. if (request.ValidateWriteable)
  153. {
  154. EnsureWriteAccess(request.Path);
  155. }
  156. }
  157. }
  158. protected void EnsureWriteAccess(string path)
  159. {
  160. var file = Path.Combine(path, Guid.NewGuid().ToString());
  161. _fileSystem.WriteAllText(file, string.Empty);
  162. _fileSystem.DeleteFile(file);
  163. }
  164. public object Get(GetDefaultDirectoryBrowser request)
  165. {
  166. var result = new DefaultDirectoryBrowserInfo();
  167. try
  168. {
  169. var qnap = "/share/CACHEDEV1_DATA";
  170. if (_fileSystem.DirectoryExists(qnap))
  171. {
  172. result.Path = qnap;
  173. }
  174. }
  175. catch
  176. {
  177. }
  178. return ToOptimizedResult(result);
  179. }
  180. /// <summary>
  181. /// Gets the specified request.
  182. /// </summary>
  183. /// <param name="request">The request.</param>
  184. /// <returns>System.Object.</returns>
  185. public object Get(GetDirectoryContents request)
  186. {
  187. var path = request.Path;
  188. if (string.IsNullOrEmpty(path))
  189. {
  190. throw new ArgumentNullException("Path");
  191. }
  192. var networkPrefix = UncSeparatorString + UncSeparatorString;
  193. if (path.StartsWith(networkPrefix, StringComparison.OrdinalIgnoreCase) && path.LastIndexOf(UncSeparator) == 1)
  194. {
  195. return ToOptimizedSerializedResultUsingCache(GetNetworkShares(path).OrderBy(i => i.Path).ToList());
  196. }
  197. return ToOptimizedSerializedResultUsingCache(GetFileSystemEntries(request).OrderBy(i => i.Path).ToList());
  198. }
  199. public object Get(GetNetworkShares request)
  200. {
  201. var path = request.Path;
  202. var shares = GetNetworkShares(path).OrderBy(i => i.Path).ToList();
  203. return ToOptimizedSerializedResultUsingCache(shares);
  204. }
  205. /// <summary>
  206. /// Gets the specified request.
  207. /// </summary>
  208. /// <param name="request">The request.</param>
  209. /// <returns>System.Object.</returns>
  210. public object Get(GetDrives request)
  211. {
  212. var result = GetDrives().ToList();
  213. return ToOptimizedSerializedResultUsingCache(result);
  214. }
  215. /// <summary>
  216. /// Gets the list that is returned when an empty path is supplied
  217. /// </summary>
  218. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  219. private IEnumerable<FileSystemEntryInfo> GetDrives()
  220. {
  221. return _fileSystem.GetDrives().Select(d => new FileSystemEntryInfo
  222. {
  223. Name = d.Name,
  224. Path = d.FullName,
  225. Type = FileSystemEntryType.Directory
  226. });
  227. }
  228. /// <summary>
  229. /// Gets the specified request.
  230. /// </summary>
  231. /// <param name="request">The request.</param>
  232. /// <returns>System.Object.</returns>
  233. public object Get(GetNetworkDevices request)
  234. {
  235. var result = _networkManager.GetNetworkDevices()
  236. .OrderBy(i => i.Path)
  237. .ToList();
  238. return ToOptimizedSerializedResultUsingCache(result);
  239. }
  240. /// <summary>
  241. /// Gets the network shares.
  242. /// </summary>
  243. /// <param name="path">The path.</param>
  244. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  245. private IEnumerable<FileSystemEntryInfo> GetNetworkShares(string path)
  246. {
  247. return _networkManager.GetNetworkShares(path).Where(s => s.ShareType == NetworkShareType.Disk).Select(c => new FileSystemEntryInfo
  248. {
  249. Name = c.Name,
  250. Path = Path.Combine(path, c.Name),
  251. Type = FileSystemEntryType.NetworkShare
  252. });
  253. }
  254. /// <summary>
  255. /// Gets the file system entries.
  256. /// </summary>
  257. /// <param name="request">The request.</param>
  258. /// <returns>IEnumerable{FileSystemEntryInfo}.</returns>
  259. private IEnumerable<FileSystemEntryInfo> GetFileSystemEntries(GetDirectoryContents request)
  260. {
  261. // using EnumerateFileSystemInfos doesn't handle reparse points (symlinks)
  262. var entries = _fileSystem.GetFileSystemEntries(request.Path).Where(i =>
  263. {
  264. if (!request.IncludeHidden && i.IsHidden)
  265. {
  266. return false;
  267. }
  268. var isDirectory = i.IsDirectory;
  269. if (!request.IncludeFiles && !isDirectory)
  270. {
  271. return false;
  272. }
  273. if (!request.IncludeDirectories && isDirectory)
  274. {
  275. return false;
  276. }
  277. return true;
  278. });
  279. return entries.Select(f => new FileSystemEntryInfo
  280. {
  281. Name = f.Name,
  282. Path = f.FullName,
  283. Type = f.IsDirectory ? FileSystemEntryType.Directory : FileSystemEntryType.File
  284. }).ToList();
  285. }
  286. public object Get(GetParentPath request)
  287. {
  288. var parent = _fileSystem.GetDirectoryName(request.Path);
  289. if (string.IsNullOrEmpty(parent))
  290. {
  291. // Check if unc share
  292. var index = request.Path.LastIndexOf(UncSeparator);
  293. if (index != -1 && request.Path.IndexOf(UncSeparator) == 0)
  294. {
  295. parent = request.Path.Substring(0, index);
  296. if (string.IsNullOrWhiteSpace(parent.TrimStart(UncSeparator)))
  297. {
  298. parent = null;
  299. }
  300. }
  301. }
  302. return parent;
  303. }
  304. }
  305. }