SharpCifsFileSystem.cs 16 KB

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