2
0

ManagedFileSystem.cs 28 KB

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