SharpCifsFileSystem.cs 18 KB

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