ManagedFileSystem.cs 28 KB

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