ManagedFileSystem.cs 28 KB

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