MediaAttachmentRepository.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Immutable;
  4. using System.Linq;
  5. using System.Threading;
  6. using Jellyfin.Database.Implementations;
  7. using Jellyfin.Database.Implementations.Entities;
  8. using MediaBrowser.Controller.Persistence;
  9. using MediaBrowser.Model.Entities;
  10. using Microsoft.EntityFrameworkCore;
  11. namespace Jellyfin.Server.Implementations.Item;
  12. /// <summary>
  13. /// Manager for handling Media Attachments.
  14. /// </summary>
  15. /// <param name="dbProvider">Efcore Factory.</param>
  16. public class MediaAttachmentRepository(IDbContextFactory<JellyfinDbContext> dbProvider) : IMediaAttachmentRepository
  17. {
  18. /// <inheritdoc />
  19. public void SaveMediaAttachments(
  20. Guid id,
  21. IReadOnlyList<MediaAttachment> attachments,
  22. CancellationToken cancellationToken)
  23. {
  24. using var context = dbProvider.CreateDbContext();
  25. using var transaction = context.Database.BeginTransaction();
  26. // Users may replace a media with a version that includes attachments to one without them.
  27. // So when saving attachments is triggered by a library scan, we always unconditionally
  28. // clear the old ones, and then add the new ones if given.
  29. context.AttachmentStreamInfos.Where(e => e.ItemId.Equals(id)).ExecuteDelete();
  30. if (attachments.Any())
  31. {
  32. context.AttachmentStreamInfos.AddRange(attachments.Select(e => Map(e, id)));
  33. }
  34. context.SaveChanges();
  35. transaction.Commit();
  36. }
  37. /// <inheritdoc />
  38. public IReadOnlyList<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery filter)
  39. {
  40. using var context = dbProvider.CreateDbContext();
  41. var query = context.AttachmentStreamInfos.AsNoTracking().Where(e => e.ItemId.Equals(filter.ItemId));
  42. if (filter.Index.HasValue)
  43. {
  44. query = query.Where(e => e.Index == filter.Index);
  45. }
  46. return query.AsEnumerable().Select(Map).ToArray();
  47. }
  48. private MediaAttachment Map(AttachmentStreamInfo attachment)
  49. {
  50. return new MediaAttachment()
  51. {
  52. Codec = attachment.Codec,
  53. CodecTag = attachment.CodecTag,
  54. Comment = attachment.Comment,
  55. FileName = attachment.Filename,
  56. Index = attachment.Index,
  57. MimeType = attachment.MimeType,
  58. };
  59. }
  60. private AttachmentStreamInfo Map(MediaAttachment attachment, Guid id)
  61. {
  62. return new AttachmentStreamInfo()
  63. {
  64. Codec = attachment.Codec,
  65. CodecTag = attachment.CodecTag,
  66. Comment = attachment.Comment,
  67. Filename = attachment.FileName,
  68. Index = attachment.Index,
  69. MimeType = attachment.MimeType,
  70. ItemId = id,
  71. Item = null!
  72. };
  73. }
  74. }