ImageUtils.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Entities;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Progress;
  10. using MediaBrowser.Model.IO;
  11. namespace MediaBrowser.Providers.ImagesByName
  12. {
  13. public static class ImageUtils
  14. {
  15. /// <summary>
  16. /// Ensures the list.
  17. /// </summary>
  18. /// <param name="url">The URL.</param>
  19. /// <param name="file">The file.</param>
  20. /// <param name="httpClient">The HTTP client.</param>
  21. /// <param name="fileSystem">The file system.</param>
  22. /// <param name="cancellationToken">The cancellation token.</param>
  23. /// <returns>Task.</returns>
  24. public static async Task<string> EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, CancellationToken cancellationToken)
  25. {
  26. var fileInfo = fileSystem.GetFileInfo(file);
  27. if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1)
  28. {
  29. var temp = await httpClient.GetTempFile(new HttpRequestOptions
  30. {
  31. CancellationToken = cancellationToken,
  32. Progress = new SimpleProgress<double>(),
  33. Url = url
  34. }).ConfigureAwait(false);
  35. fileSystem.CreateDirectory(fileSystem.GetDirectoryName(file));
  36. try
  37. {
  38. fileSystem.CopyFile(temp, file, true);
  39. }
  40. catch
  41. {
  42. }
  43. return temp;
  44. }
  45. return file;
  46. }
  47. public static string FindMatch(IHasMetadata item, IEnumerable<string> images)
  48. {
  49. var name = GetComparableName(item.Name);
  50. return images.FirstOrDefault(i => string.Equals(name, GetComparableName(i), StringComparison.OrdinalIgnoreCase));
  51. }
  52. private static string GetComparableName(string name)
  53. {
  54. return name.Replace(" ", string.Empty)
  55. .Replace(".", string.Empty)
  56. .Replace("&", string.Empty)
  57. .Replace("!", string.Empty)
  58. .Replace(",", string.Empty)
  59. .Replace("/", string.Empty);
  60. }
  61. public static IEnumerable<string> GetAvailableImages(string file, IFileSystem fileSystem)
  62. {
  63. using (var fileStream = fileSystem.GetFileStream(file, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
  64. {
  65. using (var reader = new StreamReader(fileStream))
  66. {
  67. var lines = new List<string>();
  68. while (!reader.EndOfStream)
  69. {
  70. var text = reader.ReadLine();
  71. if (!string.IsNullOrWhiteSpace(text))
  72. {
  73. lines.Add(text);
  74. }
  75. }
  76. return lines;
  77. }
  78. }
  79. }
  80. }
  81. }