ManagedFileSystem.cs 29 KB

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