CommonFileSystem.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. using MediaBrowser.Model.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Model.Logging;
  4. using System;
  5. using System.IO;
  6. using System.Text;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. namespace MediaBrowser.Common.Implementations.IO
  10. {
  11. /// <summary>
  12. /// Class CommonFileSystem
  13. /// </summary>
  14. public class CommonFileSystem : IFileSystem
  15. {
  16. protected ILogger Logger;
  17. private readonly bool _supportsAsyncFileStreams;
  18. private char[] _invalidFileNameChars;
  19. public CommonFileSystem(ILogger logger, bool supportsAsyncFileStreams, bool usePresetInvalidFileNameChars)
  20. {
  21. Logger = logger;
  22. _supportsAsyncFileStreams = supportsAsyncFileStreams;
  23. SetInvalidFileNameChars(usePresetInvalidFileNameChars);
  24. }
  25. private void SetInvalidFileNameChars(bool usePresetInvalidFileNameChars)
  26. {
  27. // GetInvalidFileNameChars is less restrictive in Linux/Mac than Windows, this mimic Windows behavior for mono under Linux/Mac.
  28. if (usePresetInvalidFileNameChars)
  29. {
  30. _invalidFileNameChars = new char[41] { '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07',
  31. '\x08', '\x09', '\x0A', '\x0B', '\x0C', '\x0D', '\x0E', '\x0F', '\x10', '\x11', '\x12',
  32. '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1A', '\x1B', '\x1C', '\x1D',
  33. '\x1E', '\x1F', '\x22', '\x3C', '\x3E', '\x7C', ':', '*', '?', '\\', '/' };
  34. }
  35. else
  36. {
  37. _invalidFileNameChars = Path.GetInvalidFileNameChars();
  38. }
  39. }
  40. /// <summary>
  41. /// Determines whether the specified filename is shortcut.
  42. /// </summary>
  43. /// <param name="filename">The filename.</param>
  44. /// <returns><c>true</c> if the specified filename is shortcut; otherwise, <c>false</c>.</returns>
  45. /// <exception cref="System.ArgumentNullException">filename</exception>
  46. public virtual bool IsShortcut(string filename)
  47. {
  48. if (string.IsNullOrEmpty(filename))
  49. {
  50. throw new ArgumentNullException("filename");
  51. }
  52. var extension = Path.GetExtension(filename);
  53. return string.Equals(extension, ".mblink", StringComparison.OrdinalIgnoreCase);
  54. }
  55. /// <summary>
  56. /// Resolves the shortcut.
  57. /// </summary>
  58. /// <param name="filename">The filename.</param>
  59. /// <returns>System.String.</returns>
  60. /// <exception cref="System.ArgumentNullException">filename</exception>
  61. public virtual string ResolveShortcut(string filename)
  62. {
  63. if (string.IsNullOrEmpty(filename))
  64. {
  65. throw new ArgumentNullException("filename");
  66. }
  67. if (string.Equals(Path.GetExtension(filename), ".mblink", StringComparison.OrdinalIgnoreCase))
  68. {
  69. var path = ReadAllText(filename);
  70. return NormalizePath(path);
  71. }
  72. return null;
  73. }
  74. /// <summary>
  75. /// Creates the shortcut.
  76. /// </summary>
  77. /// <param name="shortcutPath">The shortcut path.</param>
  78. /// <param name="target">The target.</param>
  79. /// <exception cref="System.ArgumentNullException">
  80. /// shortcutPath
  81. /// or
  82. /// target
  83. /// </exception>
  84. public void CreateShortcut(string shortcutPath, string target)
  85. {
  86. if (string.IsNullOrEmpty(shortcutPath))
  87. {
  88. throw new ArgumentNullException("shortcutPath");
  89. }
  90. if (string.IsNullOrEmpty(target))
  91. {
  92. throw new ArgumentNullException("target");
  93. }
  94. _fileSystem.WriteAllText(shortcutPath, target);
  95. }
  96. /// <summary>
  97. /// Gets the file system info.
  98. /// </summary>
  99. /// <param name="path">The path.</param>
  100. /// <returns>FileSystemInfo.</returns>
  101. public FileSystemInfo GetFileSystemInfo(string path)
  102. {
  103. if (string.IsNullOrEmpty(path))
  104. {
  105. throw new ArgumentNullException("path");
  106. }
  107. // Take a guess to try and avoid two file system hits, but we'll double-check by calling Exists
  108. if (Path.HasExtension(path))
  109. {
  110. var fileInfo = new FileInfo(path);
  111. if (fileInfo.Exists)
  112. {
  113. return fileInfo;
  114. }
  115. return new DirectoryInfo(path);
  116. }
  117. else
  118. {
  119. var fileInfo = new DirectoryInfo(path);
  120. if (fileInfo.Exists)
  121. {
  122. return fileInfo;
  123. }
  124. return new FileInfo(path);
  125. }
  126. }
  127. /// <summary>
  128. /// The space char
  129. /// </summary>
  130. private const char SpaceChar = ' ';
  131. /// <summary>
  132. /// Takes a filename and removes invalid characters
  133. /// </summary>
  134. /// <param name="filename">The filename.</param>
  135. /// <returns>System.String.</returns>
  136. /// <exception cref="System.ArgumentNullException">filename</exception>
  137. public string GetValidFilename(string filename)
  138. {
  139. if (string.IsNullOrEmpty(filename))
  140. {
  141. throw new ArgumentNullException("filename");
  142. }
  143. var builder = new StringBuilder(filename);
  144. foreach (var c in _invalidFileNameChars)
  145. {
  146. builder = builder.Replace(c, SpaceChar);
  147. }
  148. return builder.ToString();
  149. }
  150. /// <summary>
  151. /// Gets the creation time UTC.
  152. /// </summary>
  153. /// <param name="info">The info.</param>
  154. /// <returns>DateTime.</returns>
  155. public DateTime GetCreationTimeUtc(FileSystemInfo info)
  156. {
  157. // This could throw an error on some file systems that have dates out of range
  158. try
  159. {
  160. return info.CreationTimeUtc;
  161. }
  162. catch (Exception ex)
  163. {
  164. Logger.ErrorException("Error determining CreationTimeUtc for {0}", ex, info.FullName);
  165. return DateTime.MinValue;
  166. }
  167. }
  168. /// <summary>
  169. /// Gets the creation time UTC.
  170. /// </summary>
  171. /// <param name="info">The info.</param>
  172. /// <returns>DateTime.</returns>
  173. public DateTime GetLastWriteTimeUtc(FileSystemInfo info)
  174. {
  175. // This could throw an error on some file systems that have dates out of range
  176. try
  177. {
  178. return info.LastWriteTimeUtc;
  179. }
  180. catch (Exception ex)
  181. {
  182. Logger.ErrorException("Error determining LastAccessTimeUtc for {0}", ex, info.FullName);
  183. return DateTime.MinValue;
  184. }
  185. }
  186. /// <summary>
  187. /// Gets the last write time UTC.
  188. /// </summary>
  189. /// <param name="path">The path.</param>
  190. /// <returns>DateTime.</returns>
  191. public DateTime GetLastWriteTimeUtc(string path)
  192. {
  193. return GetLastWriteTimeUtc(GetFileSystemInfo(path));
  194. }
  195. /// <summary>
  196. /// Gets the file stream.
  197. /// </summary>
  198. /// <param name="path">The path.</param>
  199. /// <param name="mode">The mode.</param>
  200. /// <param name="access">The access.</param>
  201. /// <param name="share">The share.</param>
  202. /// <param name="isAsync">if set to <c>true</c> [is asynchronous].</param>
  203. /// <returns>FileStream.</returns>
  204. public Stream GetFileStream(string path, FileMode mode, FileAccess access, FileShare share, bool isAsync = false)
  205. {
  206. if (_supportsAsyncFileStreams && isAsync)
  207. {
  208. return new FileStream(path, mode, access, share, StreamDefaults.DefaultFileStreamBufferSize, true);
  209. }
  210. return new FileStream(path, mode, access, share, StreamDefaults.DefaultFileStreamBufferSize);
  211. }
  212. /// <summary>
  213. /// Swaps the files.
  214. /// </summary>
  215. /// <param name="file1">The file1.</param>
  216. /// <param name="file2">The file2.</param>
  217. public void SwapFiles(string file1, string file2)
  218. {
  219. if (string.IsNullOrEmpty(file1))
  220. {
  221. throw new ArgumentNullException("file1");
  222. }
  223. if (string.IsNullOrEmpty(file2))
  224. {
  225. throw new ArgumentNullException("file2");
  226. }
  227. var temp1 = Path.GetTempFileName();
  228. var temp2 = Path.GetTempFileName();
  229. // Copying over will fail against hidden files
  230. RemoveHiddenAttribute(file1);
  231. RemoveHiddenAttribute(file2);
  232. CopyFile(file1, temp1, true);
  233. CopyFile(file2, temp2, true);
  234. CopyFile(temp1, file2, true);
  235. CopyFile(temp2, file1, true);
  236. DeleteFile(temp1);
  237. DeleteFile(temp2);
  238. }
  239. /// <summary>
  240. /// Removes the hidden attribute.
  241. /// </summary>
  242. /// <param name="path">The path.</param>
  243. private void RemoveHiddenAttribute(string path)
  244. {
  245. if (string.IsNullOrEmpty(path))
  246. {
  247. throw new ArgumentNullException("path");
  248. }
  249. var currentFile = new FileInfo(path);
  250. // This will fail if the file is hidden
  251. if (currentFile.Exists)
  252. {
  253. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  254. {
  255. currentFile.Attributes &= ~FileAttributes.Hidden;
  256. }
  257. }
  258. }
  259. public bool ContainsSubPath(string parentPath, string path)
  260. {
  261. if (string.IsNullOrEmpty(parentPath))
  262. {
  263. throw new ArgumentNullException("parentPath");
  264. }
  265. if (string.IsNullOrEmpty(path))
  266. {
  267. throw new ArgumentNullException("path");
  268. }
  269. return path.IndexOf(parentPath.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) != -1;
  270. }
  271. public bool IsRootPath(string path)
  272. {
  273. if (string.IsNullOrEmpty(path))
  274. {
  275. throw new ArgumentNullException("path");
  276. }
  277. var parent = Path.GetDirectoryName(path);
  278. if (!string.IsNullOrEmpty(parent))
  279. {
  280. return false;
  281. }
  282. return true;
  283. }
  284. public string NormalizePath(string path)
  285. {
  286. if (string.IsNullOrEmpty(path))
  287. {
  288. throw new ArgumentNullException("path");
  289. }
  290. if (path.EndsWith(":\\", StringComparison.OrdinalIgnoreCase))
  291. {
  292. return path;
  293. }
  294. return path.TrimEnd(Path.DirectorySeparatorChar);
  295. }
  296. public string SubstitutePath(string path, string from, string to)
  297. {
  298. if (string.IsNullOrWhiteSpace(path))
  299. {
  300. throw new ArgumentNullException("path");
  301. }
  302. if (string.IsNullOrWhiteSpace(from))
  303. {
  304. throw new ArgumentNullException("from");
  305. }
  306. if (string.IsNullOrWhiteSpace(to))
  307. {
  308. throw new ArgumentNullException("to");
  309. }
  310. var newPath = path.Replace(from, to, StringComparison.OrdinalIgnoreCase);
  311. if (!string.Equals(newPath, path))
  312. {
  313. if (to.IndexOf('/') != -1)
  314. {
  315. newPath = newPath.Replace('\\', '/');
  316. }
  317. else
  318. {
  319. newPath = newPath.Replace('/', '\\');
  320. }
  321. }
  322. return newPath;
  323. }
  324. public string GetFileNameWithoutExtension(FileSystemInfo info)
  325. {
  326. if (info is DirectoryInfo)
  327. {
  328. return info.Name;
  329. }
  330. return Path.GetFileNameWithoutExtension(info.FullName);
  331. }
  332. public string GetFileNameWithoutExtension(string path)
  333. {
  334. return Path.GetFileNameWithoutExtension(path);
  335. }
  336. public bool IsPathFile(string path)
  337. {
  338. if (string.IsNullOrWhiteSpace(path))
  339. {
  340. throw new ArgumentNullException("path");
  341. }
  342. // Cannot use Path.IsPathRooted because it returns false under mono when using windows-based paths, e.g. C:\\
  343. if (path.IndexOf("://", StringComparison.OrdinalIgnoreCase) != -1 &&
  344. !path.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
  345. {
  346. return false;
  347. }
  348. return true;
  349. //return Path.IsPathRooted(path);
  350. }
  351. public void DeleteFile(string path)
  352. {
  353. File.Delete(path);
  354. }
  355. public void DeleteDirectory(string path, bool recursive)
  356. {
  357. Directory.Delete(path, recursive);
  358. }
  359. public void CreateDirectory(string path)
  360. {
  361. Directory.CreateDirectory(path);
  362. }
  363. public IEnumerable<DirectoryInfo> GetDirectories(string path, bool recursive = false)
  364. {
  365. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  366. return new DirectoryInfo (path).EnumerateDirectories("*", searchOption);
  367. }
  368. public IEnumerable<FileInfo> GetFiles(string path, bool recursive = false)
  369. {
  370. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  371. return new DirectoryInfo (path).EnumerateFiles("*", searchOption);
  372. }
  373. public IEnumerable<FileSystemInfo> GetFileSystemEntries(string path, bool recursive = false)
  374. {
  375. var directoryInfo = new DirectoryInfo (path);
  376. var searchOption = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
  377. return directoryInfo.EnumerateDirectories("*", searchOption)
  378. .Concat<FileSystemInfo>(directoryInfo.EnumerateFiles("*", searchOption));
  379. }
  380. }
  381. }