SharpCifsFileSystem.cs 17 KB

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