ImageUtils.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Entities;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace MediaBrowser.Providers.ImagesByName
  11. {
  12. public static class ImageUtils
  13. {
  14. /// <summary>
  15. /// Ensures the list.
  16. /// </summary>
  17. /// <param name="url">The URL.</param>
  18. /// <param name="file">The file.</param>
  19. /// <param name="httpClient">The HTTP client.</param>
  20. /// <param name="fileSystem">The file system.</param>
  21. /// <param name="semaphore">The semaphore.</param>
  22. /// <param name="cancellationToken">The cancellation token.</param>
  23. /// <returns>Task.</returns>
  24. public static async Task EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, SemaphoreSlim semaphore, CancellationToken cancellationToken)
  25. {
  26. var fileInfo = new FileInfo(file);
  27. if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1)
  28. {
  29. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  30. try
  31. {
  32. var temp = await httpClient.GetTempFile(new HttpRequestOptions
  33. {
  34. CancellationToken = cancellationToken,
  35. Progress = new Progress<double>(),
  36. Url = url
  37. }).ConfigureAwait(false);
  38. Directory.CreateDirectory(Path.GetDirectoryName(file));
  39. File.Copy(temp, file, true);
  40. }
  41. finally
  42. {
  43. semaphore.Release();
  44. }
  45. }
  46. }
  47. public static string FindMatch(IHasImages 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)
  62. {
  63. using (var reader = new StreamReader(file))
  64. {
  65. var lines = new List<string>();
  66. while (!reader.EndOfStream)
  67. {
  68. var text = reader.ReadLine();
  69. if (!string.IsNullOrWhiteSpace(text))
  70. {
  71. lines.Add(text);
  72. }
  73. }
  74. return lines;
  75. }
  76. }
  77. }
  78. }