2
0

ImageUtils.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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.Model.IO;
  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="cancellationToken">The cancellation token.</param>
  22. /// <returns>Task.</returns>
  23. public static async Task<string> EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, CancellationToken cancellationToken)
  24. {
  25. var fileInfo = fileSystem.GetFileInfo(file);
  26. if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1)
  27. {
  28. var temp = await httpClient.GetTempFile(new HttpRequestOptions
  29. {
  30. CancellationToken = cancellationToken,
  31. Progress = new Progress<double>(),
  32. Url = url
  33. }).ConfigureAwait(false);
  34. fileSystem.CreateDirectory(fileSystem.GetDirectoryName(file));
  35. try
  36. {
  37. fileSystem.CopyFile(temp, file, true);
  38. }
  39. catch
  40. {
  41. }
  42. return temp;
  43. }
  44. return file;
  45. }
  46. public static string FindMatch(IHasImages item, IEnumerable<string> images)
  47. {
  48. var name = GetComparableName(item.Name);
  49. return images.FirstOrDefault(i => string.Equals(name, GetComparableName(i), StringComparison.OrdinalIgnoreCase));
  50. }
  51. private static string GetComparableName(string name)
  52. {
  53. return name.Replace(" ", string.Empty)
  54. .Replace(".", string.Empty)
  55. .Replace("&", string.Empty)
  56. .Replace("!", string.Empty)
  57. .Replace(",", string.Empty)
  58. .Replace("/", string.Empty);
  59. }
  60. public static IEnumerable<string> GetAvailableImages(string file, IFileSystem fileSystem)
  61. {
  62. using (var fileStream = fileSystem.GetFileStream(file, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.Read))
  63. {
  64. using (var reader = new StreamReader(fileStream))
  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. }
  80. }