ManagedFileSystem.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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 Microsoft.Extensions.Logging;
  9. using MediaBrowser.Model.System;
  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(ILogger logger, IEnvironmentInfo environmentInfo, string defaultDirectory, string tempPath, bool enableSeparateFileAndDirectoryQueries)
  27. {
  28. Logger = logger;
  29. _supportsAsyncFileStreams = true;
  30. _tempPath = tempPath;
  31. _environmentInfo = environmentInfo;
  32. _defaultDirectory = defaultDirectory;
  33. // On Linux with mono, this needs to be true or symbolic links are ignored
  34. EnableSeparateFileAndDirectoryQueries = enableSeparateFileAndDirectoryQueries;
  35. SetInvalidFileNameChars(environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows);
  36. _isEnvironmentCaseInsensitive = environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows;
  37. }
  38. public string DefaultDirectory
  39. {
  40. get
  41. {
  42. var value = _defaultDirectory;
  43. if (!string.IsNullOrEmpty(value))
  44. {
  45. try
  46. {
  47. if (DirectoryExists(value))
  48. {
  49. return value;
  50. }
  51. }
  52. catch
  53. {
  54. }
  55. }
  56. return null;
  57. }
  58. }
  59. public void AddShortcutHandler(IShortcutHandler handler)
  60. {
  61. _shortcutHandlers.Add(handler);
  62. }
  63. protected void SetInvalidFileNameChars(bool enableManagedInvalidFileNameChars)
  64. {
  65. if (enableManagedInvalidFileNameChars)
  66. {
  67. _invalidFileNameChars = Path.GetInvalidFileNameChars();
  68. }
  69. else
  70. {
  71. // Be consistent across platforms because the windows server will fail to query network shares that don't follow windows conventions
  72. // https://referencesource.microsoft.com/#mscorlib/system/io/path.cs
  73. _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, ':', '*', '?', '\\', '/' };
  74. }
  75. }
  76. public char DirectorySeparatorChar => Path.DirectorySeparatorChar;
  77. public string GetFullPath(string path)
  78. {
  79. return Path.GetFullPath(path);
  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="System.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="System.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 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="System.ArgumentNullException">
  161. /// shortcutPath
  162. /// or
  163. /// target
  164. /// </exception>
  165. public 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 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 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 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. /// The space char
  285. /// </summary>
  286. private const char SpaceChar = ' ';
  287. /// <summary>
  288. /// Takes a filename and removes invalid characters
  289. /// </summary>
  290. /// <param name="filename">The filename.</param>
  291. /// <returns>System.String.</returns>
  292. /// <exception cref="System.ArgumentNullException">filename</exception>
  293. public string GetValidFilename(string filename)
  294. {
  295. var builder = new StringBuilder(filename);
  296. foreach (var c in _invalidFileNameChars)
  297. {
  298. builder = builder.Replace(c, SpaceChar);
  299. }
  300. return builder.ToString();
  301. }
  302. /// <summary>
  303. /// Gets the creation time UTC.
  304. /// </summary>
  305. /// <param name="info">The info.</param>
  306. /// <returns>DateTime.</returns>
  307. public DateTime GetCreationTimeUtc(FileSystemInfo info)
  308. {
  309. // This could throw an error on some file systems that have dates out of range
  310. try
  311. {
  312. return info.CreationTimeUtc;
  313. }
  314. catch (Exception ex)
  315. {
  316. Logger.LogError(ex, "Error determining CreationTimeUtc for {FullName}", info.FullName);
  317. return DateTime.MinValue;
  318. }
  319. }
  320. /// <summary>
  321. /// Gets the creation time UTC.
  322. /// </summary>
  323. /// <param name="path">The path.</param>
  324. /// <returns>DateTime.</returns>
  325. public DateTime GetCreationTimeUtc(string path)
  326. {
  327. return GetCreationTimeUtc(GetFileSystemInfo(path));
  328. }
  329. public DateTime GetCreationTimeUtc(FileSystemMetadata info)
  330. {
  331. return info.CreationTimeUtc;
  332. }
  333. public DateTime GetLastWriteTimeUtc(FileSystemMetadata info)
  334. {
  335. return info.LastWriteTimeUtc;
  336. }
  337. /// <summary>
  338. /// Gets the creation time UTC.
  339. /// </summary>
  340. /// <param name="info">The info.</param>
  341. /// <returns>DateTime.</returns>
  342. public DateTime GetLastWriteTimeUtc(FileSystemInfo info)
  343. {
  344. // This could throw an error on some file systems that have dates out of range
  345. try
  346. {
  347. return info.LastWriteTimeUtc;
  348. }
  349. catch (Exception ex)
  350. {
  351. Logger.LogError(ex, "Error determining LastAccessTimeUtc for {FullName}", info.FullName);
  352. return DateTime.MinValue;
  353. }
  354. }
  355. /// <summary>
  356. /// Gets the last write time UTC.
  357. /// </summary>
  358. /// <param name="path">The path.</param>
  359. /// <returns>DateTime.</returns>
  360. public DateTime GetLastWriteTimeUtc(string path)
  361. {
  362. return GetLastWriteTimeUtc(GetFileSystemInfo(path));
  363. }
  364. /// <summary>
  365. /// Gets the file stream.
  366. /// </summary>
  367. /// <param name="path">The path.</param>
  368. /// <param name="mode">The mode.</param>
  369. /// <param name="access">The access.</param>
  370. /// <param name="share">The share.</param>
  371. /// <param name="isAsync">if set to <c>true</c> [is asynchronous].</param>
  372. /// <returns>FileStream.</returns>
  373. public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, bool isAsync = false)
  374. {
  375. if (_supportsAsyncFileStreams && isAsync)
  376. {
  377. return GetFileStream(path, mode, access, share, FileOpenOptions.Asynchronous);
  378. }
  379. return GetFileStream(path, mode, access, share, FileOpenOptions.None);
  380. }
  381. public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions)
  382. {
  383. var defaultBufferSize = 4096;
  384. return new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), defaultBufferSize, GetFileOptions(fileOpenOptions));
  385. }
  386. private static FileOptions GetFileOptions(FileOpenOptions mode)
  387. {
  388. var val = (int)mode;
  389. return (FileOptions)val;
  390. }
  391. private static FileMode GetFileMode(FileOpenMode mode)
  392. {
  393. switch (mode)
  394. {
  395. //case FileOpenMode.Append:
  396. // return FileMode.Append;
  397. case FileOpenMode.Create:
  398. return FileMode.Create;
  399. case FileOpenMode.CreateNew:
  400. return FileMode.CreateNew;
  401. case FileOpenMode.Open:
  402. return FileMode.Open;
  403. case FileOpenMode.OpenOrCreate:
  404. return FileMode.OpenOrCreate;
  405. //case FileOpenMode.Truncate:
  406. // return FileMode.Truncate;
  407. default:
  408. throw new Exception("Unrecognized FileOpenMode");
  409. }
  410. }
  411. private static FileAccess GetFileAccess(FileAccessMode mode)
  412. {
  413. switch (mode)
  414. {
  415. //case FileAccessMode.ReadWrite:
  416. // return FileAccess.ReadWrite;
  417. case FileAccessMode.Write:
  418. return FileAccess.Write;
  419. case FileAccessMode.Read:
  420. return FileAccess.Read;
  421. default:
  422. throw new Exception("Unrecognized FileAccessMode");
  423. }
  424. }
  425. private static FileShare GetFileShare(FileShareMode mode)
  426. {
  427. switch (mode)
  428. {
  429. case FileShareMode.ReadWrite:
  430. return FileShare.ReadWrite;
  431. case FileShareMode.Write:
  432. return FileShare.Write;
  433. case FileShareMode.Read:
  434. return FileShare.Read;
  435. case FileShareMode.None:
  436. return FileShare.None;
  437. default:
  438. throw new Exception("Unrecognized FileShareMode");
  439. }
  440. }
  441. public void SetHidden(string path, bool isHidden)
  442. {
  443. if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
  444. {
  445. return;
  446. }
  447. var info = GetExtendedFileSystemInfo(path);
  448. if (info.Exists && info.IsHidden != isHidden)
  449. {
  450. if (isHidden)
  451. {
  452. File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
  453. }
  454. else
  455. {
  456. FileAttributes attributes = File.GetAttributes(path);
  457. attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
  458. File.SetAttributes(path, attributes);
  459. }
  460. }
  461. }
  462. public void SetReadOnly(string path, bool isReadOnly)
  463. {
  464. if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
  465. {
  466. return;
  467. }
  468. var info = GetExtendedFileSystemInfo(path);
  469. if (info.Exists && info.IsReadOnly != isReadOnly)
  470. {
  471. if (isReadOnly)
  472. {
  473. File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.ReadOnly);
  474. }
  475. else
  476. {
  477. FileAttributes attributes = File.GetAttributes(path);
  478. attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
  479. File.SetAttributes(path, attributes);
  480. }
  481. }
  482. }
  483. public void SetAttributes(string path, bool isHidden, bool isReadOnly)
  484. {
  485. if (_environmentInfo.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows)
  486. {
  487. return;
  488. }
  489. var info = GetExtendedFileSystemInfo(path);
  490. if (!info.Exists)
  491. {
  492. return;
  493. }
  494. if (info.IsReadOnly == isReadOnly && info.IsHidden == isHidden)
  495. {
  496. return;
  497. }
  498. var attributes = File.GetAttributes(path);
  499. if (isReadOnly)
  500. {
  501. attributes = attributes | FileAttributes.ReadOnly;
  502. }
  503. else
  504. {
  505. attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly);
  506. }
  507. if (isHidden)
  508. {
  509. attributes = attributes | FileAttributes.Hidden;
  510. }
  511. else
  512. {
  513. attributes = RemoveAttribute(attributes, FileAttributes.Hidden);
  514. }
  515. File.SetAttributes(path, attributes);
  516. }
  517. private static FileAttributes RemoveAttribute(FileAttributes attributes, FileAttributes attributesToRemove)
  518. {
  519. return attributes & ~attributesToRemove;
  520. }
  521. /// <summary>
  522. /// Swaps the files.
  523. /// </summary>
  524. /// <param name="file1">The file1.</param>
  525. /// <param name="file2">The file2.</param>
  526. public void SwapFiles(string file1, string file2)
  527. {
  528. if (string.IsNullOrEmpty(file1))
  529. {
  530. throw new ArgumentNullException(nameof(file1));
  531. }
  532. if (string.IsNullOrEmpty(file2))
  533. {
  534. throw new ArgumentNullException(nameof(file2));
  535. }
  536. var temp1 = Path.Combine(_tempPath, Guid.NewGuid().ToString("N"));
  537. // Copying over will fail against hidden files
  538. SetHidden(file1, false);
  539. SetHidden(file2, false);
  540. Directory.CreateDirectory(_tempPath);
  541. CopyFile(file1, temp1, true);
  542. CopyFile(file2, file1, true);
  543. CopyFile(temp1, file2, true);
  544. }
  545. private static char GetDirectorySeparatorChar(string path)
  546. {
  547. return Path.DirectorySeparatorChar;
  548. }
  549. public bool ContainsSubPath(string parentPath, string path)
  550. {
  551. if (string.IsNullOrEmpty(parentPath))
  552. {
  553. throw new ArgumentNullException(nameof(parentPath));
  554. }
  555. if (string.IsNullOrEmpty(path))
  556. {
  557. throw new ArgumentNullException(nameof(path));
  558. }
  559. var separatorChar = GetDirectorySeparatorChar(parentPath);
  560. return path.IndexOf(parentPath.TrimEnd(separatorChar) + separatorChar, StringComparison.OrdinalIgnoreCase) != -1;
  561. }
  562. public bool IsRootPath(string path)
  563. {
  564. if (string.IsNullOrEmpty(path))
  565. {
  566. throw new ArgumentNullException(nameof(path));
  567. }
  568. var parent = GetDirectoryName(path);
  569. if (!string.IsNullOrEmpty(parent))
  570. {
  571. return false;
  572. }
  573. return true;
  574. }
  575. public string GetDirectoryName(string path)
  576. {
  577. return Path.GetDirectoryName(path);
  578. }
  579. public string NormalizePath(string path)
  580. {
  581. if (string.IsNullOrEmpty(path))
  582. {
  583. throw new ArgumentNullException(nameof(path));
  584. }
  585. if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
  586. {
  587. return path;
  588. }
  589. return path.TrimEnd(GetDirectorySeparatorChar(path));
  590. }
  591. public bool AreEqual(string path1, string path2)
  592. {
  593. if (path1 == null && path2 == null)
  594. {
  595. return true;
  596. }
  597. if (path1 == null || path2 == null)
  598. {
  599. return false;
  600. }
  601. return string.Equals(NormalizePath(path1), NormalizePath(path2), StringComparison.OrdinalIgnoreCase);
  602. }
  603. public string GetFileNameWithoutExtension(FileSystemMetadata info)
  604. {
  605. if (info.IsDirectory)
  606. {
  607. return info.Name;
  608. }
  609. return Path.GetFileNameWithoutExtension(info.FullName);
  610. }
  611. public string GetFileNameWithoutExtension(string path)
  612. {
  613. return Path.GetFileNameWithoutExtension(path);
  614. }
  615. public bool IsPathFile(string path)
  616. {
  617. // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
  618. if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
  619. !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
  620. {
  621. return false;
  622. }
  623. return true;
  624. //return Path.IsPathRooted(path);
  625. }
  626. public void DeleteFile(string path)
  627. {
  628. SetAttributes(path, false, false);
  629. File.Delete(path);
  630. }
  631. public void DeleteDirectory(string path, bool recursive)
  632. {
  633. Directory.Delete(path, recursive);
  634. }
  635. public void CreateDirectory(string path)
  636. {
  637. Directory.CreateDirectory(path);
  638. }
  639. public List<FileSystemMetadata> GetDrives()
  640. {
  641. // Only include drives in the ready state or this method could end up being very slow, waiting for drives to timeout
  642. return DriveInfo.GetDrives().Where(d => d.IsReady).Select(d => new FileSystemMetadata
  643. {
  644. Name = GetName(d),
  645. FullName = d.RootDirectory.FullName,
  646. IsDirectory = true
  647. }).ToList();
  648. }
  649. private static string GetName(DriveInfo drive)
  650. {
  651. return drive.Name;
  652. }
  653. public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
  654. {
  655. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  656. return ToMetadata(new DirectoryInfo(path).EnumerateDirectories("*", searchOption));
  657. }
  658. public IEnumerable<FileSystemMetadata> GetFiles(string path, bool recursive = false)
  659. {
  660. return GetFiles(path, null, false, recursive);
  661. }
  662. public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  663. {
  664. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  665. // On linux and osx the search pattern is case sensitive
  666. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  667. if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Length == 1)
  668. {
  669. return ToMetadata(new DirectoryInfo(path).EnumerateFiles("*" + extensions[0], searchOption));
  670. }
  671. var files = new DirectoryInfo(path).EnumerateFiles("*", searchOption);
  672. if (extensions != null && extensions.Length > 0)
  673. {
  674. files = files.Where(i =>
  675. {
  676. var ext = i.Extension;
  677. if (ext == null)
  678. {
  679. return false;
  680. }
  681. return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  682. });
  683. }
  684. return ToMetadata(files);
  685. }
  686. public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
  687. {
  688. var directoryInfo = new DirectoryInfo(path);
  689. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  690. if (EnableSeparateFileAndDirectoryQueries)
  691. {
  692. return ToMetadata(directoryInfo.EnumerateDirectories("*", searchOption))
  693. .Concat(ToMetadata(directoryInfo.EnumerateFiles("*", searchOption)));
  694. }
  695. return ToMetadata(directoryInfo.EnumerateFileSystemInfos("*", searchOption));
  696. }
  697. private IEnumerable<FileSystemMetadata> ToMetadata(IEnumerable<FileSystemInfo> infos)
  698. {
  699. return infos.Select(GetFileSystemMetadata);
  700. }
  701. public string[] ReadAllLines(string path)
  702. {
  703. return File.ReadAllLines(path);
  704. }
  705. public void WriteAllLines(string path, IEnumerable<string> lines)
  706. {
  707. File.WriteAllLines(path, lines);
  708. }
  709. public Stream OpenRead(string path)
  710. {
  711. return File.OpenRead(path);
  712. }
  713. private void CopyFileUsingStreams(string source, string target, bool overwrite)
  714. {
  715. using (var sourceStream = OpenRead(source))
  716. {
  717. using (var targetStream = GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  718. {
  719. sourceStream.CopyTo(targetStream);
  720. }
  721. }
  722. }
  723. public void CopyFile(string source, string target, bool overwrite)
  724. {
  725. File.Copy(source, target, overwrite);
  726. }
  727. public void MoveFile(string source, string target)
  728. {
  729. File.Move(source, target);
  730. }
  731. public void MoveDirectory(string source, string target)
  732. {
  733. Directory.Move(source, target);
  734. }
  735. public bool DirectoryExists(string path)
  736. {
  737. return Directory.Exists(path);
  738. }
  739. public bool FileExists(string path)
  740. {
  741. return File.Exists(path);
  742. }
  743. public string ReadAllText(string path)
  744. {
  745. return File.ReadAllText(path);
  746. }
  747. public byte[] ReadAllBytes(string path)
  748. {
  749. return File.ReadAllBytes(path);
  750. }
  751. public void WriteAllText(string path, string text, Encoding encoding)
  752. {
  753. File.WriteAllText(path, text, encoding);
  754. }
  755. public void WriteAllText(string path, string text)
  756. {
  757. File.WriteAllText(path, text);
  758. }
  759. public void WriteAllBytes(string path, byte[] bytes)
  760. {
  761. File.WriteAllBytes(path, bytes);
  762. }
  763. public string ReadAllText(string path, Encoding encoding)
  764. {
  765. return File.ReadAllText(path, encoding);
  766. }
  767. public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
  768. {
  769. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  770. return Directory.EnumerateDirectories(path, "*", searchOption);
  771. }
  772. public IEnumerable<string> GetFilePaths(string path, bool recursive = false)
  773. {
  774. return GetFilePaths(path, null, false, recursive);
  775. }
  776. public IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  777. {
  778. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  779. // On linux and osx the search pattern is case sensitive
  780. // If we're OK with case-sensitivity, and we're only filtering for one extension, then use the native method
  781. if ((enableCaseSensitiveExtensions || _isEnvironmentCaseInsensitive) && extensions != null && extensions.Length == 1)
  782. {
  783. return Directory.EnumerateFiles(path, "*" + extensions[0], searchOption);
  784. }
  785. var files = Directory.EnumerateFiles(path, "*", searchOption);
  786. if (extensions != null && extensions.Length > 0)
  787. {
  788. files = files.Where(i =>
  789. {
  790. var ext = Path.GetExtension(i);
  791. if (ext == null)
  792. {
  793. return false;
  794. }
  795. return extensions.Contains(ext, StringComparer.OrdinalIgnoreCase);
  796. });
  797. }
  798. return files;
  799. }
  800. public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
  801. {
  802. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  803. return Directory.EnumerateFileSystemEntries(path, "*", searchOption);
  804. }
  805. public virtual void SetExecutable(string path)
  806. {
  807. if (_environmentInfo.OperatingSystem == MediaBrowser.Model.System.OperatingSystem.OSX)
  808. {
  809. RunProcess("chmod", "+x \"" + path + "\"", GetDirectoryName(path));
  810. }
  811. }
  812. private static void RunProcess(string path, string args, string workingDirectory)
  813. {
  814. using (var process = Process.Start(new ProcessStartInfo
  815. {
  816. Arguments = args,
  817. FileName = path,
  818. CreateNoWindow = true,
  819. WorkingDirectory = workingDirectory,
  820. WindowStyle = ProcessWindowStyle.Normal
  821. }))
  822. {
  823. process.WaitForExit();
  824. }
  825. }
  826. }
  827. }