SharpCifsFileSystem.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. var isCurrentlyHidden = file.IsHidden();
  139. if (isCurrentlyHidden && !isHidden)
  140. {
  141. file.SetAttributes(file.GetAttributes() & ~SmbFile.AttrReadonly);
  142. }
  143. else if (!isCurrentlyHidden && isHidden)
  144. {
  145. file.SetAttributes(file.GetAttributes() | SmbFile.AttrReadonly);
  146. }
  147. }
  148. public void SetReadOnly(string path, bool isReadOnly)
  149. {
  150. var file = CreateSmbFile(path);
  151. var isCurrentlyReadOnly = !file.CanWrite();
  152. if (isCurrentlyReadOnly && !isReadOnly)
  153. {
  154. file.SetReadWrite();
  155. }
  156. else if (!isCurrentlyReadOnly && isReadOnly)
  157. {
  158. file.SetReadOnly();
  159. }
  160. }
  161. public void DeleteFile(string path)
  162. {
  163. var file = CreateSmbFile(path);
  164. AssertFileExists(file, path);
  165. file.Delete();
  166. }
  167. public void DeleteDirectory(string path, bool recursive)
  168. {
  169. var file = CreateSmbFile(path);
  170. AssertDirectoryExists(file, path);
  171. file.Delete();
  172. }
  173. public void CreateDirectory(string path)
  174. {
  175. }
  176. public string[] ReadAllLines(string path)
  177. {
  178. var lines = new List<string>();
  179. using (var stream = OpenRead(path))
  180. {
  181. using (var reader = new StreamReader(stream))
  182. {
  183. while (!reader.EndOfStream)
  184. {
  185. lines.Add(reader.ReadLine());
  186. }
  187. }
  188. }
  189. return lines.ToArray();
  190. }
  191. public void WriteAllLines(string path, IEnumerable<string> lines)
  192. {
  193. using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  194. {
  195. using (var writer = new StreamWriter(stream))
  196. {
  197. foreach (var line in lines)
  198. {
  199. writer.WriteLine(line);
  200. }
  201. }
  202. }
  203. }
  204. private void AssertFileExists(SmbFile file, string path)
  205. {
  206. if (!file.Exists())
  207. {
  208. throw new FileNotFoundException("File not found.", path);
  209. }
  210. }
  211. private void AssertDirectoryExists(SmbFile file, string path)
  212. {
  213. if (!file.Exists())
  214. {
  215. throw new FileNotFoundException("File not found.", path);
  216. }
  217. }
  218. public Stream OpenRead(string path)
  219. {
  220. var file = CreateSmbFile(path);
  221. AssertFileExists(file, path);
  222. return file.GetInputStream();
  223. }
  224. private Stream OpenWrite(string path)
  225. {
  226. var file = CreateSmbFile(path);
  227. AssertFileExists(file, path);
  228. return file.GetInputStream();
  229. }
  230. public void CopyFile(string source, string target, bool overwrite)
  231. {
  232. if (string.Equals(source, target, StringComparison.Ordinal))
  233. {
  234. throw new ArgumentException("Cannot CopyFile when source and target are the same");
  235. }
  236. using (var input = OpenRead(source))
  237. {
  238. using (var output = GetFileStream(target, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  239. {
  240. input.CopyTo(output);
  241. }
  242. }
  243. }
  244. public void MoveFile(string source, string target)
  245. {
  246. if (string.Equals(source, target, StringComparison.Ordinal))
  247. {
  248. throw new ArgumentException("Cannot MoveFile 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. DeleteFile(source);
  258. }
  259. public void MoveDirectory(string source, string target)
  260. {
  261. throw new NotImplementedException();
  262. }
  263. public bool DirectoryExists(string path)
  264. {
  265. var dir = CreateSmbFile(path);
  266. return dir.Exists() && dir.IsDirectory();
  267. }
  268. public bool FileExists(string path)
  269. {
  270. var file = CreateSmbFile(path);
  271. return file.Exists();
  272. }
  273. public string ReadAllText(string path, Encoding encoding)
  274. {
  275. using (var stream = OpenRead(path))
  276. {
  277. using (var reader = new StreamReader(stream, encoding))
  278. {
  279. return reader.ReadToEnd();
  280. }
  281. }
  282. }
  283. public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share)
  284. {
  285. if (mode == FileOpenMode.OpenOrCreate)
  286. {
  287. var file = CreateSmbFile(path);
  288. if (!file.Exists())
  289. {
  290. file.CreateNewFile();
  291. }
  292. mode = FileOpenMode.Open;
  293. }
  294. if (mode == FileOpenMode.CreateNew)
  295. {
  296. var file = CreateSmbFile(path);
  297. if (file.Exists())
  298. {
  299. throw new IOException("File already exists");
  300. }
  301. file.CreateNewFile();
  302. mode = FileOpenMode.Open;
  303. }
  304. if (mode == FileOpenMode.Create)
  305. {
  306. var file = CreateSmbFile(path);
  307. if (file.Exists())
  308. {
  309. if (file.IsHidden())
  310. {
  311. throw new UnauthorizedAccessException(string.Format("File {0} already exists and is hidden", path));
  312. }
  313. file.Delete();
  314. file.CreateNewFile();
  315. }
  316. else
  317. {
  318. file.CreateNewFile();
  319. }
  320. mode = FileOpenMode.Open;
  321. }
  322. if (mode == FileOpenMode.Open)
  323. {
  324. if (access == FileAccessMode.Read)
  325. {
  326. return OpenRead(path);
  327. }
  328. if (access == FileAccessMode.Write)
  329. {
  330. return OpenWrite(path);
  331. }
  332. throw new NotImplementedException();
  333. }
  334. throw new NotImplementedException();
  335. }
  336. public void WriteAllBytes(string path, byte[] bytes)
  337. {
  338. using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  339. {
  340. stream.Write(bytes, 0, bytes.Length);
  341. }
  342. }
  343. public void WriteAllText(string path, string text)
  344. {
  345. using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  346. {
  347. using (var writer = new StreamWriter(stream))
  348. {
  349. writer.Write(text);
  350. }
  351. }
  352. }
  353. public void WriteAllText(string path, string text, Encoding encoding)
  354. {
  355. using (var stream = GetFileStream(path, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.None))
  356. {
  357. using (var writer = new StreamWriter(stream, encoding))
  358. {
  359. writer.Write(text);
  360. }
  361. }
  362. }
  363. public string ReadAllText(string path)
  364. {
  365. using (var stream = OpenRead(path))
  366. {
  367. using (var reader = new StreamReader(stream))
  368. {
  369. return reader.ReadToEnd();
  370. }
  371. }
  372. }
  373. public byte[] ReadAllBytes(string path)
  374. {
  375. using (var stream = OpenRead(path))
  376. {
  377. using (var ms = new MemoryStream())
  378. {
  379. stream.CopyTo(ms);
  380. ms.Position = 0;
  381. return ms.ToArray();
  382. }
  383. }
  384. }
  385. private SmbFile CreateSmbDirectoryForListFiles(string path)
  386. {
  387. // In order to call ListFiles, it has to end with the separator
  388. return CreateSmbFile(path.TrimEnd('/') + '/');
  389. }
  390. public IEnumerable<FileSystemMetadata> GetDirectories(string path, bool recursive = false)
  391. {
  392. var dir = CreateSmbDirectoryForListFiles(path);
  393. AssertDirectoryExists(dir, path);
  394. var list = ListFiles(dir, recursive);
  395. foreach (var file in list)
  396. {
  397. if (file.IsDirectory())
  398. {
  399. yield return ToMetadata(file);
  400. }
  401. }
  402. }
  403. public IEnumerable<FileSystemMetadata> GetFiles(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  404. {
  405. var dir = CreateSmbDirectoryForListFiles(path);
  406. AssertDirectoryExists(dir, path);
  407. var list = ListFiles(dir, recursive);
  408. foreach (var file in list)
  409. {
  410. if (file.IsFile())
  411. {
  412. var filePath = GetReturnPath(file);
  413. var extension = Path.GetExtension(filePath);
  414. if (extensions == null || extensions.Length == 0 || extensions.Contains(extension ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  415. {
  416. yield return ToMetadata(file);
  417. }
  418. }
  419. }
  420. }
  421. public IEnumerable<FileSystemMetadata> GetFileSystemEntries(string path, bool recursive = false)
  422. {
  423. var dir = CreateSmbDirectoryForListFiles(path);
  424. AssertDirectoryExists(dir, path);
  425. var list = ListFiles(dir, recursive);
  426. foreach (var file in list)
  427. {
  428. yield return ToMetadata(file);
  429. }
  430. }
  431. public IEnumerable<string> GetFileSystemEntryPaths(string path, bool recursive = false)
  432. {
  433. var dir = CreateSmbDirectoryForListFiles(path);
  434. AssertDirectoryExists(dir, path);
  435. var list = ListFiles(dir, recursive);
  436. foreach (var file in list)
  437. {
  438. yield return GetReturnPath(file);
  439. }
  440. }
  441. public IEnumerable<string> GetFilePaths(string path, string[] extensions, bool enableCaseSensitiveExtensions, bool recursive = false)
  442. {
  443. var dir = CreateSmbDirectoryForListFiles(path);
  444. AssertDirectoryExists(dir, path);
  445. var list = ListFiles(dir, recursive);
  446. foreach (var file in list)
  447. {
  448. if (file.IsFile())
  449. {
  450. var filePath = GetReturnPath(file);
  451. var extension = Path.GetExtension(filePath);
  452. if (extensions == null || extensions.Length == 0 || extensions.Contains(extension ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  453. {
  454. yield return filePath;
  455. }
  456. }
  457. }
  458. }
  459. public IEnumerable<string> GetDirectoryPaths(string path, bool recursive = false)
  460. {
  461. var dir = CreateSmbDirectoryForListFiles(path);
  462. AssertDirectoryExists(dir, path);
  463. var list = ListFiles(dir, recursive);
  464. foreach (var file in list)
  465. {
  466. if (file.IsDirectory())
  467. {
  468. yield return GetReturnPath(file);
  469. }
  470. }
  471. }
  472. private IEnumerable<SmbFile> ListFiles(SmbFile dir, bool recursive)
  473. {
  474. var list = dir.ListFiles();
  475. foreach (var file in list)
  476. {
  477. yield return file;
  478. if (recursive && file.IsDirectory())
  479. {
  480. foreach (var subFile in ListFiles(file, recursive))
  481. {
  482. yield return subFile;
  483. }
  484. }
  485. }
  486. }
  487. }
  488. }