SharpCifsFileSystem.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using SharpCifs.Smb;
  8. using MediaBrowser.Model.IO;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.System;
  11. namespace Emby.Common.Implementations.IO
  12. {
  13. public class SharpCifsFileSystem
  14. {
  15. private readonly MediaBrowser.Model.System.OperatingSystem _operatingSystem;
  16. public SharpCifsFileSystem(MediaBrowser.Model.System.OperatingSystem operatingSystem)
  17. {
  18. _operatingSystem = operatingSystem;
  19. }
  20. public bool IsEnabledForPath(string path)
  21. {
  22. if (_operatingSystem == MediaBrowser.Model.System.OperatingSystem.Windows)
  23. {
  24. return false;
  25. }
  26. return path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase) || IsUncPath(path);
  27. }
  28. public string NormalizePath(string path)
  29. {
  30. if (path.StartsWith("smb://", StringComparison.OrdinalIgnoreCase))
  31. {
  32. return path;
  33. }
  34. if (IsUncPath(path))
  35. {
  36. return ConvertUncToSmb(path);
  37. }
  38. return path;
  39. }
  40. public string GetDirectoryName(string path)
  41. {
  42. var separator = GetDirectorySeparatorChar(path);
  43. var result = Path.GetDirectoryName(path);
  44. if (separator == '/')
  45. {
  46. result = result.Replace('\\', '/');
  47. }
  48. return result;
  49. }
  50. public char GetDirectorySeparatorChar(string path)
  51. {
  52. if (path.IndexOf('/') != -1)
  53. {
  54. return '/';
  55. }
  56. return '\\';
  57. }
  58. public FileSystemMetadata GetFileSystemInfo(string path)
  59. {
  60. var file = CreateSmbFile(path);
  61. return ToMetadata(file);
  62. }
  63. public FileSystemMetadata GetFileInfo(string path)
  64. {
  65. var file = CreateSmbFile(path);
  66. return ToMetadata(file, false);
  67. }
  68. public FileSystemMetadata GetDirectoryInfo(string path)
  69. {
  70. var file = CreateSmbFile(path);
  71. return ToMetadata(file, true);
  72. }
  73. private bool IsUncPath(string path)
  74. {
  75. return path.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase);
  76. }
  77. private string GetReturnPath(SmbFile file)
  78. {
  79. return file.GetCanonicalPath().TrimEnd('/');
  80. //return file.GetPath();
  81. }
  82. private string ConvertUncToSmb(string path)
  83. {
  84. if (IsUncPath(path))
  85. {
  86. path = path.Replace('\\', '/');
  87. path = "smb:" + path;
  88. }
  89. return path;
  90. }
  91. private string AddAuthentication(string path)
  92. {
  93. return path;
  94. }
  95. private SmbFile CreateSmbFile(string path)
  96. {
  97. path = ConvertUncToSmb(path);
  98. path = AddAuthentication(path);
  99. return new SmbFile(path);
  100. }
  101. DateTime baseDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  102. private FileSystemMetadata ToMetadata(SmbFile info, bool? isDirectory = null)
  103. {
  104. var result = new FileSystemMetadata();
  105. result.Exists = info.Exists();
  106. result.FullName = GetReturnPath(info);
  107. result.Extension = Path.GetExtension(result.FullName);
  108. result.Name = info.GetName();
  109. if (result.Exists)
  110. {
  111. result.IsDirectory = info.IsDirectory();
  112. result.IsHidden = info.IsHidden();
  113. result.IsReadOnly = !info.CanWrite();
  114. if (info.IsFile())
  115. {
  116. result.Length = info.Length();
  117. result.DirectoryName = info.GetParent();
  118. }
  119. result.CreationTimeUtc = baseDate.AddMilliseconds(info.CreateTime());
  120. result.LastWriteTimeUtc = baseDate.AddMilliseconds(info.GetLastModified());
  121. }
  122. else
  123. {
  124. if (isDirectory.HasValue)
  125. {
  126. result.IsDirectory = isDirectory.Value;
  127. }
  128. }
  129. return result;
  130. }
  131. public void SetHidden(string path, bool isHidden)
  132. {
  133. var file = CreateSmbFile(path);
  134. var isCurrentlyHidden = file.IsHidden();
  135. if (isCurrentlyHidden && !isHidden)
  136. {
  137. file.SetAttributes(file.GetAttributes() & ~SmbFile.AttrReadonly);
  138. }
  139. else if (!isCurrentlyHidden && isHidden)
  140. {
  141. file.SetAttributes(file.GetAttributes() | SmbFile.AttrReadonly);
  142. }
  143. }
  144. public void SetReadOnly(string path, bool isReadOnly)
  145. {
  146. var file = CreateSmbFile(path);
  147. var isCurrentlyReadOnly = !file.CanWrite();
  148. if (isCurrentlyReadOnly && !isReadOnly)
  149. {
  150. file.SetReadWrite();
  151. }
  152. else if (!isCurrentlyReadOnly && isReadOnly)
  153. {
  154. file.SetReadOnly();
  155. }
  156. }
  157. public void DeleteFile(string path)
  158. {
  159. var file = CreateSmbFile(path);
  160. AssertFileExists(file, path);
  161. file.Delete();
  162. }
  163. public void DeleteDirectory(string path, bool recursive)
  164. {
  165. var file = CreateSmbFile(path);
  166. AssertDirectoryExists(file, path);
  167. file.Delete();
  168. }
  169. public void CreateDirectory(string path)
  170. {
  171. }
  172. public string[] ReadAllLines(string path)
  173. {
  174. var lines = new List<string>();
  175. using (var stream = OpenRead(path))
  176. {
  177. using (var reader = new StreamReader(stream))
  178. {
  179. while (!reader.EndOfStream)
  180. {
  181. lines.Add(reader.ReadLine());
  182. }
  183. }
  184. }
  185. return lines.ToArray();
  186. }
  187. public void WriteAllLines(string path, IEnumerable<string> lines)
  188. {
  189. using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  190. {
  191. using (var writer = new StreamWriter(stream))
  192. {
  193. foreach (var line in lines)
  194. {
  195. writer.WriteLine(line);
  196. }
  197. }
  198. }
  199. }
  200. private void AssertFileExists(SmbFile file, string path)
  201. {
  202. if (!file.Exists())
  203. {
  204. throw new FileNotFoundException("File not found.", path);
  205. }
  206. }
  207. private void AssertDirectoryExists(SmbFile file, string path)
  208. {
  209. if (!file.Exists())
  210. {
  211. throw new FileNotFoundException("File not found.", path);
  212. }
  213. }
  214. public Stream OpenRead(string path)
  215. {
  216. var file = CreateSmbFile(path);
  217. AssertFileExists(file, path);
  218. return file.GetInputStream();
  219. }
  220. private Stream OpenWrite(string path)
  221. {
  222. var file = CreateSmbFile(path);
  223. AssertFileExists(file, path);
  224. return file.GetInputStream();
  225. }
  226. public void CopyFile(string source, string target, bool overwrite)
  227. {
  228. if (string.Equals(source, target, StringComparison.Ordinal))
  229. {
  230. throw new ArgumentException("Cannot CopyFile when source and target are the same");
  231. }
  232. using (var input = OpenRead(source))
  233. {
  234. using (var output = GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  235. {
  236. input.CopyTo(output);
  237. }
  238. }
  239. }
  240. public void MoveFile(string source, string target)
  241. {
  242. if (string.Equals(source, target, StringComparison.Ordinal))
  243. {
  244. throw new ArgumentException("Cannot MoveFile when source and target are the same");
  245. }
  246. using (var input = OpenRead(source))
  247. {
  248. using (var output = GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  249. {
  250. input.CopyTo(output);
  251. }
  252. }
  253. DeleteFile(source);
  254. }
  255. public void MoveDirectory(string source, string target)
  256. {
  257. throw new NotImplementedException();
  258. }
  259. public bool DirectoryExists(string path)
  260. {
  261. var dir = CreateSmbFile(path);
  262. return dir.Exists() && dir.IsDirectory();
  263. }
  264. public bool FileExists(string path)
  265. {
  266. var file = CreateSmbFile(path);
  267. return file.Exists();
  268. }
  269. public string ReadAllText(string path, Encoding encoding)
  270. {
  271. using (var stream = OpenRead(path))
  272. {
  273. using (var reader = new StreamReader(stream, encoding))
  274. {
  275. return reader.ReadToEnd();
  276. }
  277. }
  278. }
  279. public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share)
  280. {
  281. if (mode == FileOpenMode.OpenOrCreate)
  282. {
  283. var file = CreateSmbFile(path);
  284. if (!file.Exists())
  285. {
  286. file.CreateNewFile();
  287. }
  288. mode = FileOpenMode.Open;
  289. }
  290. if (mode == FileOpenMode.CreateNew)
  291. {
  292. var file = CreateSmbFile(path);
  293. if (file.Exists())
  294. {
  295. throw new IOException("File already exists");
  296. }
  297. file.CreateNewFile();
  298. mode = FileOpenMode.Open;
  299. }
  300. if (mode == FileOpenMode.Create)
  301. {
  302. var file = CreateSmbFile(path);
  303. if (file.Exists())
  304. {
  305. if (file.IsHidden())
  306. {
  307. throw new UnauthorizedAccessException(string.Format("File {0} already exists and is hidden", path));
  308. }
  309. file.Delete();
  310. file.CreateNewFile();
  311. }
  312. else
  313. {
  314. file.CreateNewFile();
  315. }
  316. mode = FileOpenMode.Open;
  317. }
  318. if (mode == FileOpenMode.Open)
  319. {
  320. if (access == FileAccessMode.Read)
  321. {
  322. return OpenRead(path);
  323. }
  324. if (access == FileAccessMode.Write)
  325. {
  326. return OpenWrite(path);
  327. }
  328. throw new NotImplementedException();
  329. }
  330. throw new NotImplementedException();
  331. }
  332. public void WriteAllBytes(string path, byte[] bytes)
  333. {
  334. using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  335. {
  336. stream.Write(bytes, 0, bytes.Length);
  337. }
  338. }
  339. public void WriteAllText(string path, string text)
  340. {
  341. using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  342. {
  343. using (var writer = new StreamWriter(stream))
  344. {
  345. writer.Write(text);
  346. }
  347. }
  348. }
  349. public void WriteAllText(string path, string text, Encoding encoding)
  350. {
  351. using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  352. {
  353. using (var writer = new StreamWriter(stream, encoding))
  354. {
  355. writer.Write(text);
  356. }
  357. }
  358. }
  359. public string ReadAllText(string path)
  360. {
  361. using (var stream = OpenRead(path))
  362. {
  363. using (var reader = new StreamReader(stream))
  364. {
  365. return reader.ReadToEnd();
  366. }
  367. }
  368. }
  369. public byte[] ReadAllBytes(string path)
  370. {
  371. using (var stream = OpenRead(path))
  372. {
  373. using (var ms = new MemoryStream())
  374. {
  375. stream.CopyTo(ms);
  376. ms.Position = 0;
  377. return ms.ToArray();
  378. }
  379. }
  380. }
  381. private SmbFile CreateSmbDirectoryForListFiles(string path)
  382. {
  383. // In order to call ListFiles, it has to end with the separator
  384. return CreateSmbFile(path.TrimEnd('/') + '/');
  385. }
  386. public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
  387. {
  388. var dir = CreateSmbDirectoryForListFiles(path);
  389. AssertDirectoryExists(dir, path);
  390. var list = ListFiles(dir, recursive);
  391. foreach (var file in list)
  392. {
  393. if (file.IsDirectory())
  394. {
  395. yield return ToMetadata(file);
  396. }
  397. }
  398. }
  399. public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  400. {
  401. var dir = CreateSmbDirectoryForListFiles(path);
  402. AssertDirectoryExists(dir, path);
  403. var list = ListFiles(dir, recursive);
  404. foreach (var file in list)
  405. {
  406. if (file.IsFile())
  407. {
  408. var filePath = GetReturnPath(file);
  409. var extension = Path.GetExtension(filePath);
  410. if (extensions == null || extensions.Length == 0 || extensions.Contains(extension ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  411. {
  412. yield return ToMetadata(file);
  413. }
  414. }
  415. }
  416. }
  417. public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
  418. {
  419. var dir = CreateSmbDirectoryForListFiles(path);
  420. AssertDirectoryExists(dir, path);
  421. var list = ListFiles(dir, recursive);
  422. foreach (var file in list)
  423. {
  424. yield return ToMetadata(file);
  425. }
  426. }
  427. public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
  428. {
  429. var dir = CreateSmbDirectoryForListFiles(path);
  430. AssertDirectoryExists(dir, path);
  431. var list = ListFiles(dir, recursive);
  432. foreach (var file in list)
  433. {
  434. yield return GetReturnPath(file);
  435. }
  436. }
  437. public IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  438. {
  439. var dir = CreateSmbDirectoryForListFiles(path);
  440. AssertDirectoryExists(dir, path);
  441. var list = ListFiles(dir, recursive);
  442. foreach (var file in list)
  443. {
  444. if (file.IsFile())
  445. {
  446. var filePath = GetReturnPath(file);
  447. var extension = Path.GetExtension(filePath);
  448. if (extensions == null || extensions.Length == 0 || extensions.Contains(extension ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  449. {
  450. yield return filePath;
  451. }
  452. }
  453. }
  454. }
  455. public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
  456. {
  457. var dir = CreateSmbDirectoryForListFiles(path);
  458. AssertDirectoryExists(dir, path);
  459. var list = ListFiles(dir, recursive);
  460. foreach (var file in list)
  461. {
  462. if (file.IsDirectory())
  463. {
  464. yield return GetReturnPath(file);
  465. }
  466. }
  467. }
  468. private IEnumerable<SmbFile> ListFiles(SmbFile dir, bool recursive)
  469. {
  470. var list = dir.ListFiles();
  471. foreach (var file in list)
  472. {
  473. yield return file;
  474. if (recursive && file.IsDirectory())
  475. {
  476. foreach (var subFile in ListFiles(file, recursive))
  477. {
  478. yield return subFile;
  479. }
  480. }
  481. }
  482. }
  483. }
  484. }