2
0

ImageUtils.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. using CommonIO;
  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="semaphore">The semaphore.</param>
  23. /// <param name="cancellationToken">The cancellation token.</param>
  24. /// <returns>Task.</returns>
  25. public static async Task EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, SemaphoreSlim semaphore, CancellationToken cancellationToken)
  26. {
  27. var fileInfo = fileSystem.GetFileInfo(file);
  28. if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1)
  29. {
  30. await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  31. try
  32. {
  33. var temp = await httpClient.GetTempFile(new HttpRequestOptions
  34. {
  35. CancellationToken = cancellationToken,
  36. Progress = new Progress<double>(),
  37. Url = url
  38. }).ConfigureAwait(false);
  39. fileSystem.CreateDirectory(Path.GetDirectoryName(file));
  40. fileSystem.CopyFile(temp, file, true);
  41. }
  42. finally
  43. {
  44. semaphore.Release();
  45. }
  46. }
  47. }
  48. public static string FindMatch(IHasImages item, IEnumerable<string> images)
  49. {
  50. var name = GetComparableName(item.Name);
  51. return images.FirstOrDefault(i => string.Equals(name, GetComparableName(i), StringComparison.OrdinalIgnoreCase));
  52. }
  53. private static string GetComparableName(string name)
  54. {
  55. return name.Replace(" ", string.Empty)
  56. .Replace(".", string.Empty)
  57. .Replace("&", string.Empty)
  58. .Replace("!", string.Empty)
  59. .Replace(",", string.Empty)
  60. .Replace("/", string.Empty);
  61. }
  62. public static IEnumerable<string> GetAvailableImages(string file)
  63. {
  64. using (var reader = new StreamReader(file))
  65. {
  66. var lines = new List<string>();
  67. while (!reader.EndOfStream)
  68. {
  69. var text = reader.ReadLine();
  70. if (!string.IsNullOrWhiteSpace(text))
  71. {
  72. lines.Add(text);
  73. }
  74. }
  75. return lines;
  76. }
  77. }
  78. }
  79. }