ManagedFileSystem.cs 30 KB

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