ManagedFileSystem.cs 29 KB

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