ManagedFileSystem.cs 30 KB

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