ManagedFileSystem.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.System;
  10. using Microsoft.Extensions.Logging;
  11. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  12. namespace Emby.Server.Implementations.IO
  13. {
  14. /// <summary>
  15. /// Class ManagedFileSystem
  16. /// </summary>
  17. public class ManagedFileSystem : IFileSystem
  18. {
  19. protected ILogger Logger;
  20. private readonly List<IShortcutHandler> _shortcutHandlers = new List<IShortcutHandler>();
  21. private readonly string _tempPath;
  22. private readonly bool _isEnvironmentCaseInsensitive;
  23. public ManagedFileSystem(
  24. ILogger<ManagedFileSystem> logger,
  25. IApplicationPaths applicationPaths)
  26. {
  27. Logger = logger;
  28. _tempPath = applicationPaths.TempDirectory;
  29. _isEnvironmentCaseInsensitive = OperatingSystem.Id == OperatingSystemId.Windows;
  30. }
  31. public virtual void AddShortcutHandler(IShortcutHandler handler)
  32. {
  33. _shortcutHandlers.Add(handler);
  34. }
  35. /// <summary>
  36. /// Determines whether the specified filename is shortcut.
  37. /// </summary>
  38. /// <param name="filename">The filename.</param>
  39. /// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
  40. /// <exception cref="ArgumentNullException">filename</exception>
  41. public virtual bool IsShortcut(string filename)
  42. {
  43. if (string.IsNullOrEmpty(filename))
  44. {
  45. throw new ArgumentNullException(nameof(filename));
  46. }
  47. var extension = Path.GetExtension(filename);
  48. return _shortcutHandlers.Any(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
  49. }
  50. /// <summary>
  51. /// Resolves the shortcut.
  52. /// </summary>
  53. /// <param name="filename">The filename.</param>
  54. /// <returns>System.String.</returns>
  55. /// <exception cref="ArgumentNullException">filename</exception>
  56. public virtual string ResolveShortcut(string filename)
  57. {
  58. if (string.IsNullOrEmpty(filename))
  59. {
  60. throw new ArgumentNullException(nameof(filename));
  61. }
  62. var extension = Path.GetExtension(filename);
  63. var handler = _shortcutHandlers.FirstOrDefault(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
  64. return handler?.Resolve(filename);
  65. }
  66. public virtual string MakeAbsolutePath(string folderPath, string filePath)
  67. {
  68. if (string.IsNullOrWhiteSpace(filePath)
  69. // stream
  70. || filePath.Contains("://"))
  71. {
  72. return filePath;
  73. }
  74. if (filePath.Length > 3 && filePath[1] == ':' && filePath[2] == '/')
  75. {
  76. return filePath; // absolute local path
  77. }
  78. // unc path
  79. if (filePath.StartsWith("\\\\"))
  80. {
  81. return filePath;
  82. }
  83. var firstChar = filePath[0];
  84. if (firstChar == '/')
  85. {
  86. // For this we don't really know.
  87. return filePath;
  88. }
  89. if (firstChar == '\\') //relative path
  90. {
  91. filePath = filePath.Substring(1);
  92. }
  93. try
  94. {
  95. return Path.Combine(Path.GetFullPath(folderPath), filePath);
  96. }
  97. catch (ArgumentException)
  98. {
  99. return filePath;
  100. }
  101. catch (PathTooLongException)
  102. {
  103. return filePath;
  104. }
  105. catch (NotSupportedException)
  106. {
  107. return filePath;
  108. }
  109. }
  110. /// <summary>
  111. /// Creates the shortcut.
  112. /// </summary>
  113. /// <param name="shortcutPath">The shortcut path.</param>
  114. /// <param name="target">The target.</param>
  115. /// <exception cref="ArgumentNullException">
  116. /// shortcutPath
  117. /// or
  118. /// target
  119. /// </exception>
  120. public virtual void CreateShortcut(string shortcutPath, string target)
  121. {
  122. if (string.IsNullOrEmpty(shortcutPath))
  123. {
  124. throw new ArgumentNullException(nameof(shortcutPath));
  125. }
  126. if (string.IsNullOrEmpty(target))
  127. {
  128. throw new ArgumentNullException(nameof(target));
  129. }
  130. var extension = Path.GetExtension(shortcutPath);
  131. var handler = _shortcutHandlers.Find(i => string.Equals(extension, i.Extension, StringComparison.OrdinalIgnoreCase));
  132. if (handler != null)
  133. {
  134. handler.Create(shortcutPath, target);
  135. }
  136. else
  137. {
  138. throw new NotImplementedException();
  139. }
  140. }
  141. /// <summary>
  142. /// Returns a <see cref="FileSystemMetadata"/> object for the specified file or directory path.
  143. /// </summary>
  144. /// <param name="path">A path to a file or directory.</param>
  145. /// <returns>A <see cref="FileSystemMetadata"/> object.</returns>
  146. /// <remarks>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's
  147. /// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and all other properties will reflect the properties of the directory.</remarks>
  148. public virtual FileSystemMetadata GetFileSystemInfo(string path)
  149. {
  150. // Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists
  151. if (Path.HasExtension(path))
  152. {
  153. var fileInfo = new FileInfo(path);
  154. if (fileInfo.Exists)
  155. {
  156. return GetFileSystemMetadata(fileInfo);
  157. }
  158. return GetFileSystemMetadata(new DirectoryInfo(path));
  159. }
  160. else
  161. {
  162. var fileInfo = new DirectoryInfo(path);
  163. if (fileInfo.Exists)
  164. {
  165. return GetFileSystemMetadata(fileInfo);
  166. }
  167. return GetFileSystemMetadata(new FileInfo(path));
  168. }
  169. }
  170. /// <summary>
  171. /// Returns a <see cref="FileSystemMetadata"/> object for the specified file path.
  172. /// </summary>
  173. /// <param name="path">A path to a file.</param>
  174. /// <returns>A <see cref="FileSystemMetadata"/> object.</returns>
  175. /// <remarks><para>If the specified path points to a directory, the returned <see cref="FileSystemMetadata"/> object's
  176. /// <see cref="FileSystemMetadata.IsDirectory"/> property and the <see cref="FileSystemMetadata.Exists"/> property will both be set to false.</para>
  177. /// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
  178. public virtual FileSystemMetadata GetFileInfo(string path)
  179. {
  180. var fileInfo = new FileInfo(path);
  181. return GetFileSystemMetadata(fileInfo);
  182. }
  183. /// <summary>
  184. /// Returns a <see cref="FileSystemMetadata"/> object for the specified directory path.
  185. /// </summary>
  186. /// <param name="path">A path to a directory.</param>
  187. /// <returns>A <see cref="FileSystemMetadata"/> object.</returns>
  188. /// <remarks><para>If the specified path points to a file, the returned <see cref="FileSystemMetadata"/> object's
  189. /// <see cref="FileSystemMetadata.IsDirectory"/> property will be set to true and the <see cref="FileSystemMetadata.Exists"/> property will be set to false.</para>
  190. /// <para>For automatic handling of files <b>and</b> directories, use <see cref="GetFileSystemInfo"/>.</para></remarks>
  191. public virtual FileSystemMetadata GetDirectoryInfo(string path)
  192. {
  193. var fileInfo = new DirectoryInfo(path);
  194. return GetFileSystemMetadata(fileInfo);
  195. }
  196. private FileSystemMetadata GetFileSystemMetadata(FileSystemInfo info)
  197. {
  198. var result = new FileSystemMetadata
  199. {
  200. Exists = info.Exists,
  201. FullName = info.FullName,
  202. Extension = info.Extension,
  203. Name = info.Name
  204. };
  205. if (result.Exists)
  206. {
  207. result.IsDirectory = info is DirectoryInfo || (info.Attributes & FileAttributes.Directory) == FileAttributes.Directory;
  208. //if (!result.IsDirectory)
  209. //{
  210. // result.IsHidden = (info.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
  211. //}
  212. if (info is FileInfo fileInfo)
  213. {
  214. result.Length = fileInfo.Length;
  215. result.DirectoryName = fileInfo.DirectoryName;
  216. }
  217. result.CreationTimeUtc = GetCreationTimeUtc(info);
  218. result.LastWriteTimeUtc = GetLastWriteTimeUtc(info);
  219. }
  220. else
  221. {
  222. result.IsDirectory = info is DirectoryInfo;
  223. }
  224. return result;
  225. }
  226. private static ExtendedFileSystemInfo GetExtendedFileSystemInfo(string path)
  227. {
  228. var result = new ExtendedFileSystemInfo();
  229. var info = new FileInfo(path);
  230. if (info.Exists)
  231. {
  232. result.Exists = true;
  233. var attributes = info.Attributes;
  234. result.IsHidden = (attributes & FileAttributes.Hidden) == FileAttributes.Hidden;
  235. result.IsReadOnly = (attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
  236. }
  237. return result;
  238. }
  239. /// <summary>
  240. /// Takes a filename and removes invalid characters
  241. /// </summary>
  242. /// <param name="filename">The filename.</param>
  243. /// <returns>System.String.</returns>
  244. /// <exception cref="ArgumentNullException">filename</exception>
  245. public virtual string GetValidFilename(string filename)
  246. {
  247. var builder = new StringBuilder(filename);
  248. foreach (var c in Path.GetInvalidFileNameChars())
  249. {
  250. builder = builder.Replace(c, ' ');
  251. }
  252. return builder.ToString();
  253. }
  254. /// <summary>
  255. /// Gets the creation time UTC.
  256. /// </summary>
  257. /// <param name="info">The info.</param>
  258. /// <returns>DateTime.</returns>
  259. public DateTime GetCreationTimeUtc(FileSystemInfo info)
  260. {
  261. // This could throw an error on some file systems that have dates out of range
  262. try
  263. {
  264. return info.CreationTimeUtc;
  265. }
  266. catch (Exception ex)
  267. {
  268. Logger.LogError(ex, "Error determining CreationTimeUtc for {FullName}", info.FullName);
  269. return DateTime.MinValue;
  270. }
  271. }
  272. /// <summary>
  273. /// Gets the creation time UTC.
  274. /// </summary>
  275. /// <param name="path">The path.</param>
  276. /// <returns>DateTime.</returns>
  277. public virtual DateTime GetCreationTimeUtc(string path)
  278. {
  279. return GetCreationTimeUtc(GetFileSystemInfo(path));
  280. }
  281. public virtual DateTime GetCreationTimeUtc(FileSystemMetadata info)
  282. {
  283. return info.CreationTimeUtc;
  284. }
  285. public virtual DateTime GetLastWriteTimeUtc(FileSystemMetadata info)
  286. {
  287. return info.LastWriteTimeUtc;
  288. }
  289. /// <summary>
  290. /// Gets the creation time UTC.
  291. /// </summary>
  292. /// <param name="info">The info.</param>
  293. /// <returns>DateTime.</returns>
  294. public DateTime GetLastWriteTimeUtc(FileSystemInfo info)
  295. {
  296. // This could throw an error on some file systems that have dates out of range
  297. try
  298. {
  299. return info.LastWriteTimeUtc;
  300. }
  301. catch (Exception ex)
  302. {
  303. Logger.LogError(ex, "Error determining LastAccessTimeUtc for {FullName}", info.FullName);
  304. return DateTime.MinValue;
  305. }
  306. }
  307. /// <summary>
  308. /// Gets the last write time UTC.
  309. /// </summary>
  310. /// <param name="path">The path.</param>
  311. /// <returns>DateTime.</returns>
  312. public virtual DateTime GetLastWriteTimeUtc(string path)
  313. {
  314. return GetLastWriteTimeUtc(GetFileSystemInfo(path));
  315. }
  316. /// <summary>
  317. /// Gets the file stream.
  318. /// </summary>
  319. /// <param name="path">The path.</param>
  320. /// <param name="mode">The mode.</param>
  321. /// <param name="access">The access.</param>
  322. /// <param name="share">The share.</param>
  323. /// <param name="isAsync">if set to <c>true</c> [is asynchronous].</param>
  324. /// <returns>FileStream.</returns>
  325. public virtual Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false)
  326. {
  327. if (isAsync)
  328. {
  329. return GetFileStream(path, mode, access, share, FileOpenOptions.Asynchronous);
  330. }
  331. return GetFileStream(path, mode, access, share, FileOpenOptions.None);
  332. }
  333. public virtual Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions)
  334. => new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 4096, GetFileOptions(fileOpenOptions));
  335. private static FileOptions GetFileOptions(FileOpenOptions mode)
  336. {
  337. var val = (int)mode;
  338. return (FileOptions)val;
  339. }
  340. private static FileMode GetFileMode(FileOpenMode mode)
  341. {
  342. switch (mode)
  343. {
  344. //case FileOpenMode.Append:
  345. // return FileMode.Append;
  346. case FileOpenMode.Create:
  347. return FileMode.Create;
  348. case FileOpenMode.CreateNew:
  349. return FileMode.CreateNew;
  350. case FileOpenMode.Open:
  351. return FileMode.Open;
  352. case FileOpenMode.OpenOrCreate:
  353. return FileMode.OpenOrCreate;
  354. //case FileOpenMode.Truncate:
  355. // return FileMode.Truncate;
  356. default:
  357. throw new Exception("Unrecognized FileOpenMode");
  358. }
  359. }
  360. private static FileAccess GetFileAccess(FileAccessMode mode)
  361. {
  362. switch (mode)
  363. {
  364. //case FileAccessMode.ReadWrite:
  365. // return FileAccess.ReadWrite;
  366. case FileAccessMode.Write:
  367. return FileAccess.Write;
  368. case FileAccessMode.Read:
  369. return FileAccess.Read;
  370. default:
  371. throw new Exception("Unrecognized FileAccessMode");
  372. }
  373. }
  374. private static FileShare GetFileShare(FileShareMode mode)
  375. {
  376. switch (mode)
  377. {
  378. case FileShareMode.ReadWrite:
  379. return FileShare.ReadWrite;
  380. case FileShareMode.Write:
  381. return FileShare.Write;
  382. case FileShareMode.Read:
  383. return FileShare.Read;
  384. case FileShareMode.None:
  385. return FileShare.None;
  386. default:
  387. throw new Exception("Unrecognized FileShareMode");
  388. }
  389. }
  390. public virtual void SetHidden(string path, bool isHidden)
  391. {
  392. if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows)
  393. {
  394. return;
  395. }
  396. var info = GetExtendedFileSystemInfo(path);
  397. if (info.Exists && info.IsHidden != isHidden)
  398. {
  399. if (isHidden)
  400. {
  401. File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
  402. }
  403. else
  404. {
  405. var attributes = File.GetAttributes(path);
  406. attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
  407. File.SetAttributes(path, attributes);
  408. }
  409. }
  410. }
  411. public virtual void SetReadOnly(string path, bool isReadOnly)
  412. {
  413. if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows)
  414. {
  415. return;
  416. }
  417. var info = GetExtendedFileSystemInfo(path);
  418. if (info.Exists && info.IsReadOnly != isReadOnly)
  419. {
  420. if (isReadOnly)
  421. {
  422. File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);
  423. }
  424. else
  425. {
  426. var attributes = File.GetAttributes(path);
  427. attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
  428. File.SetAttributes(path, attributes);
  429. }
  430. }
  431. }
  432. public virtual void SetAttributes(string path, bool isHidden, bool isReadOnly)
  433. {
  434. if (OperatingSystem.Id != MediaBrowser.Model.System.OperatingSystemId.Windows)
  435. {
  436. return;
  437. }
  438. var info = GetExtendedFileSystemInfo(path);
  439. if (!info.Exists)
  440. {
  441. return;
  442. }
  443. if (info.IsReadOnly == isReadOnly && info.IsHidden == isHidden)
  444. {
  445. return;
  446. }
  447. var attributes = File.GetAttributes(path);
  448. if (isReadOnly)
  449. {
  450. attributes = attributes | FileAttributes.ReadOnly;
  451. }
  452. else
  453. {
  454. attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
  455. }
  456. if (isHidden)
  457. {
  458. attributes = attributes | FileAttributes.Hidden;
  459. }
  460. else
  461. {
  462. attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
  463. }
  464. File.SetAttributes(path, attributes);
  465. }
  466. private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
  467. {
  468. return attributes & ~attributesToRemove;
  469. }
  470. /// <summary>
  471. /// Swaps the files.
  472. /// </summary>
  473. /// <param name="file1">The file1.</param>
  474. /// <param name="file2">The file2.</param>
  475. public virtual void SwapFiles(string file1, string file2)
  476. {
  477. if (string.IsNullOrEmpty(file1))
  478. {
  479. throw new ArgumentNullException(nameof(file1));
  480. }
  481. if (string.IsNullOrEmpty(file2))
  482. {
  483. throw new ArgumentNullException(nameof(file2));
  484. }
  485. var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N"));
  486. // Copying over will fail against hidden files
  487. SetHidden(file1, false);
  488. SetHidden(file2, false);
  489. Directory.CreateDirectory(_tempPath);
  490. File.Copy(file1, temp1, true);
  491. File.Copy(file2, file1, true);
  492. File.Copy(temp1, file2, true);
  493. }
  494. public virtual bool ContainsSubPath(string parentPath, string path)
  495. {
  496. if (string.IsNullOrEmpty(parentPath))
  497. {
  498. throw new ArgumentNullException(nameof(parentPath));
  499. }
  500. if (string.IsNullOrEmpty(path))
  501. {
  502. throw new ArgumentNullException(nameof(path));
  503. }
  504. var separatorChar = Path.DirectorySeparatorChar;
  505. return path.IndexOf(parentPath.TrimEnd(separatorChar) + separatorChar, StringComparison.OrdinalIgnoreCase) != -1;
  506. }
  507. public virtual bool IsRootPath(string path)
  508. {
  509. if (string.IsNullOrEmpty(path))
  510. {
  511. throw new ArgumentNullException(nameof(path));
  512. }
  513. var parent = Path.GetDirectoryName(path);
  514. if (!string.IsNullOrEmpty(parent))
  515. {
  516. return false;
  517. }
  518. return true;
  519. }
  520. public virtual string NormalizePath(string path)
  521. {
  522. if (string.IsNullOrEmpty(path))
  523. {
  524. throw new ArgumentNullException(nameof(path));
  525. }
  526. if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
  527. {
  528. return path;
  529. }
  530. return path.TrimEnd(Path.DirectorySeparatorChar);
  531. }
  532. public virtual bool AreEqual(string path1, string path2)
  533. {
  534. if (path1 == null && path2 == null)
  535. {
  536. return true;
  537. }
  538. if (path1 == null || path2 == null)
  539. {
  540. return false;
  541. }
  542. return string.Equals(NormalizePath(path1), NormalizePath(path2), StringComparison.OrdinalIgnoreCase);
  543. }
  544. public virtual string GetFileNameWithoutExtension(FileSystemMetadata info)
  545. {
  546. if (info.IsDirectory)
  547. {
  548. return info.Name;
  549. }
  550. return Path.GetFileNameWithoutExtension(info.FullName);
  551. }
  552. public virtual bool IsPathFile(string path)
  553. {
  554. // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
  555. if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
  556. !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
  557. {
  558. return false;
  559. }
  560. return true;
  561. }
  562. public virtual void DeleteFile(string path)
  563. {
  564. SetAttributes(path, false, false);
  565. File.Delete(path);
  566. }
  567. public virtual List<FileSystemMetadata> GetDrives()
  568. {
  569. // check for ready state to avoid waiting for drives to timeout
  570. // some drives on linux have no actual size or are used for other purposes
  571. return DriveInfo.GetDrives().Where(d => d.IsReady && d.TotalSize != 0 && d.DriveType != DriveType.Ram)
  572. .Select(d => new FileSystemMetadata
  573. {
  574. Name = d.Name,
  575. FullName = d.RootDirectory.FullName,
  576. IsDirectory = true
  577. }).ToList();
  578. }
  579. public virtual IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
  580. {
  581. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  582. return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
  583. }
  584. public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false)
  585. {
  586. return GetFiles(path, null, false, recursive);
  587. }
  588. public virtual IEnumerable<FileSystemMetadata> GetFiles(string path, IReadOnlyList<string> extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  589. {
  590. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  591. // On linux and osx the search pattern is case sensitive
  592. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  593. if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Count == 1)
  594. {
  595. return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
  596. }
  597. var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
  598. if (extensions != null && extensions.Count > 0)
  599. {
  600. files = files.Where(i =>
  601. {
  602. var ext = i.Extension;
  603. if (ext == null)
  604. {
  605. return false;
  606. }
  607. return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  608. });
  609. }
  610. return ToMetadata(files);
  611. }
  612. public virtual IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
  613. {
  614. var directoryInfo = new DirectoryInfo(path);
  615. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  616. return ToMetadata(directoryInfo.EnumerateDirectories("*", searchOption))
  617. .Concat(ToMetadata(directoryInfo.EnumerateFiles("*", searchOption)));
  618. }
  619. private IEnumerable<FileSystemMetadata> ToMetadata(IEnumerable<FileSystemInfo> infos)
  620. {
  621. return infos.Select(GetFileSystemMetadata);
  622. }
  623. public virtual IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
  624. {
  625. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  626. return Directory.EnumerateDirectories(path, "*", searchOption);
  627. }
  628. public virtual IEnumerable<string> GetFilePaths(string path, bool recursive = false)
  629. {
  630. return GetFilePaths(path, null, false, recursive);
  631. }
  632. public virtual IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  633. {
  634. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  635. // On linux and osx the search pattern is case sensitive
  636. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  637. if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Length == 1)
  638. {
  639. return Directory.EnumerateFiles(path, "*" + extensions[0], searchOption);
  640. }
  641. var files = Directory.EnumerateFiles(path, "*", searchOption);
  642. if (extensions != null && extensions.Length > 0)
  643. {
  644. files = files.Where(i =>
  645. {
  646. var ext = Path.GetExtension(i);
  647. if (ext == null)
  648. {
  649. return false;
  650. }
  651. return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  652. });
  653. }
  654. return files;
  655. }
  656. public virtual IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
  657. {
  658. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  659. return Directory.EnumerateFileSystemEntries(path, "*", searchOption);
  660. }
  661. public virtual void SetExecutable(string path)
  662. {
  663. if (OperatingSystem.Id == MediaBrowser.Model.System.OperatingSystemId.Darwin)
  664. {
  665. RunProcess("chmod", "+x \"" + path + "\"", Path.GetDirectoryName(path));
  666. }
  667. }
  668. private static void RunProcess(string path, string args, string workingDirectory)
  669. {
  670. using (var process = Process.Start(new ProcessStartInfo
  671. {
  672. Arguments = args,
  673. FileName = path,
  674. CreateNoWindow = true,
  675. WorkingDirectory = workingDirectory,
  676. WindowStyle = ProcessWindowStyle.Normal
  677. }))
  678. {
  679. process.WaitForExit();
  680. }
  681. }
  682. }
  683. }