mirror of
https://github.com/jellyfin/jellyfin.git
synced 2026-03-02 08:23:04 +00:00
Merge pull request #12798 from JPVenson/feature/EFUserData
Refactor library.db into jellyfin.db and EFCore
This commit is contained in:
@@ -40,6 +40,7 @@ using Jellyfin.MediaEncoding.Hls.Playlist;
|
||||
using Jellyfin.Networking.Manager;
|
||||
using Jellyfin.Networking.Udp;
|
||||
using Jellyfin.Server.Implementations;
|
||||
using Jellyfin.Server.Implementations.Item;
|
||||
using Jellyfin.Server.Implementations.MediaSegments;
|
||||
using MediaBrowser.Common;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
@@ -83,7 +84,6 @@ using MediaBrowser.Model.Net;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using MediaBrowser.Model.System;
|
||||
using MediaBrowser.Model.Tasks;
|
||||
using MediaBrowser.Providers.Chapters;
|
||||
using MediaBrowser.Providers.Lyric;
|
||||
using MediaBrowser.Providers.Manager;
|
||||
using MediaBrowser.Providers.Plugins.Tmdb;
|
||||
@@ -268,6 +268,11 @@ namespace Emby.Server.Implementations
|
||||
|
||||
public string ExpandVirtualPath(string path)
|
||||
{
|
||||
if (path is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var appPaths = ApplicationPaths;
|
||||
|
||||
return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
|
||||
@@ -492,10 +497,14 @@ namespace Emby.Server.Implementations
|
||||
|
||||
serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
|
||||
|
||||
serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
|
||||
serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
|
||||
|
||||
serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
|
||||
serviceCollection.AddSingleton<IItemRepository, BaseItemRepository>();
|
||||
serviceCollection.AddSingleton<IPeopleRepository, PeopleRepository>();
|
||||
serviceCollection.AddSingleton<IChapterRepository, ChapterRepository>();
|
||||
serviceCollection.AddSingleton<IMediaAttachmentRepository, MediaAttachmentRepository>();
|
||||
serviceCollection.AddSingleton<IMediaStreamRepository, MediaStreamRepository>();
|
||||
serviceCollection.AddSingleton<IItemTypeLookup, ItemTypeLookup>();
|
||||
|
||||
serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
|
||||
serviceCollection.AddSingleton<EncodingHelper>();
|
||||
@@ -540,8 +549,6 @@ namespace Emby.Server.Implementations
|
||||
|
||||
serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
|
||||
|
||||
serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
|
||||
|
||||
serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
|
||||
|
||||
serviceCollection.AddSingleton<IAuthService, AuthService>();
|
||||
@@ -579,9 +586,6 @@ namespace Emby.Server.Implementations
|
||||
}
|
||||
}
|
||||
|
||||
((SqliteItemRepository)Resolve<IItemRepository>()).Initialize();
|
||||
((SqliteUserDataRepository)Resolve<IUserDataRepository>()).Initialize();
|
||||
|
||||
var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
|
||||
await localizationManager.LoadAll().ConfigureAwait(false);
|
||||
|
||||
@@ -635,6 +639,7 @@ namespace Emby.Server.Implementations
|
||||
BaseItem.ProviderManager = Resolve<IProviderManager>();
|
||||
BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
|
||||
BaseItem.ItemRepository = Resolve<IItemRepository>();
|
||||
BaseItem.ChapterRepository = Resolve<IChapterRepository>();
|
||||
BaseItem.FileSystem = Resolve<IFileSystem>();
|
||||
BaseItem.UserDataManager = Resolve<IUserDataManager>();
|
||||
BaseItem.ChannelManager = Resolve<IChannelManager>();
|
||||
|
||||
@@ -1,269 +0,0 @@
|
||||
#nullable disable
|
||||
|
||||
#pragma warning disable CS1591
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using Jellyfin.Extensions;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Emby.Server.Implementations.Data
|
||||
{
|
||||
public abstract class BaseSqliteRepository : IDisposable
|
||||
{
|
||||
private bool _disposed = false;
|
||||
private SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
|
||||
private SqliteConnection _writeConnection;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="BaseSqliteRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">The logger.</param>
|
||||
protected BaseSqliteRepository(ILogger<BaseSqliteRepository> logger)
|
||||
{
|
||||
Logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path to the DB file.
|
||||
/// </summary>
|
||||
protected string DbFilePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the logger.
|
||||
/// </summary>
|
||||
/// <value>The logger.</value>
|
||||
protected ILogger<BaseSqliteRepository> Logger { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the cache size.
|
||||
/// </summary>
|
||||
/// <value>The cache size or null.</value>
|
||||
protected virtual int? CacheSize => null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the locking mode. <see href="https://www.sqlite.org/pragma.html#pragma_locking_mode" />.
|
||||
/// </summary>
|
||||
protected virtual string LockingMode => "NORMAL";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the journal mode. <see href="https://www.sqlite.org/pragma.html#pragma_journal_mode" />.
|
||||
/// </summary>
|
||||
/// <value>The journal mode.</value>
|
||||
protected virtual string JournalMode => "WAL";
|
||||
|
||||
/// <summary>
|
||||
/// Gets the journal size limit. <see href="https://www.sqlite.org/pragma.html#pragma_journal_size_limit" />.
|
||||
/// The default (-1) is overridden to prevent unconstrained WAL size, as reported by users.
|
||||
/// </summary>
|
||||
/// <value>The journal size limit.</value>
|
||||
protected virtual int? JournalSizeLimit => 134_217_728; // 128MiB
|
||||
|
||||
/// <summary>
|
||||
/// Gets the page size.
|
||||
/// </summary>
|
||||
/// <value>The page size or null.</value>
|
||||
protected virtual int? PageSize => null;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the temp store mode.
|
||||
/// </summary>
|
||||
/// <value>The temp store mode.</value>
|
||||
/// <see cref="TempStoreMode"/>
|
||||
protected virtual TempStoreMode TempStore => TempStoreMode.Memory;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the synchronous mode.
|
||||
/// </summary>
|
||||
/// <value>The synchronous mode or null.</value>
|
||||
/// <see cref="SynchronousMode"/>
|
||||
protected virtual SynchronousMode? Synchronous => SynchronousMode.Normal;
|
||||
|
||||
public virtual void Initialize()
|
||||
{
|
||||
// Configuration and pragmas can affect VACUUM so it needs to be last.
|
||||
using (var connection = GetConnection())
|
||||
{
|
||||
connection.Execute("VACUUM");
|
||||
}
|
||||
}
|
||||
|
||||
protected ManagedConnection GetConnection(bool readOnly = false)
|
||||
{
|
||||
if (!readOnly)
|
||||
{
|
||||
_writeLock.Wait();
|
||||
if (_writeConnection is not null)
|
||||
{
|
||||
return new ManagedConnection(_writeConnection, _writeLock);
|
||||
}
|
||||
|
||||
var writeConnection = new SqliteConnection($"Filename={DbFilePath};Pooling=False");
|
||||
writeConnection.Open();
|
||||
|
||||
if (CacheSize.HasValue)
|
||||
{
|
||||
writeConnection.Execute("PRAGMA cache_size=" + CacheSize.Value);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(LockingMode))
|
||||
{
|
||||
writeConnection.Execute("PRAGMA locking_mode=" + LockingMode);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(JournalMode))
|
||||
{
|
||||
writeConnection.Execute("PRAGMA journal_mode=" + JournalMode);
|
||||
}
|
||||
|
||||
if (JournalSizeLimit.HasValue)
|
||||
{
|
||||
writeConnection.Execute("PRAGMA journal_size_limit=" + JournalSizeLimit.Value);
|
||||
}
|
||||
|
||||
if (Synchronous.HasValue)
|
||||
{
|
||||
writeConnection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value);
|
||||
}
|
||||
|
||||
if (PageSize.HasValue)
|
||||
{
|
||||
writeConnection.Execute("PRAGMA page_size=" + PageSize.Value);
|
||||
}
|
||||
|
||||
writeConnection.Execute("PRAGMA temp_store=" + (int)TempStore);
|
||||
|
||||
return new ManagedConnection(_writeConnection = writeConnection, _writeLock);
|
||||
}
|
||||
|
||||
var connection = new SqliteConnection($"Filename={DbFilePath};Mode=ReadOnly");
|
||||
connection.Open();
|
||||
|
||||
if (CacheSize.HasValue)
|
||||
{
|
||||
connection.Execute("PRAGMA cache_size=" + CacheSize.Value);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(LockingMode))
|
||||
{
|
||||
connection.Execute("PRAGMA locking_mode=" + LockingMode);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(JournalMode))
|
||||
{
|
||||
connection.Execute("PRAGMA journal_mode=" + JournalMode);
|
||||
}
|
||||
|
||||
if (JournalSizeLimit.HasValue)
|
||||
{
|
||||
connection.Execute("PRAGMA journal_size_limit=" + JournalSizeLimit.Value);
|
||||
}
|
||||
|
||||
if (Synchronous.HasValue)
|
||||
{
|
||||
connection.Execute("PRAGMA synchronous=" + (int)Synchronous.Value);
|
||||
}
|
||||
|
||||
if (PageSize.HasValue)
|
||||
{
|
||||
connection.Execute("PRAGMA page_size=" + PageSize.Value);
|
||||
}
|
||||
|
||||
connection.Execute("PRAGMA temp_store=" + (int)TempStore);
|
||||
|
||||
return new ManagedConnection(connection, null);
|
||||
}
|
||||
|
||||
public SqliteCommand PrepareStatement(ManagedConnection connection, string sql)
|
||||
{
|
||||
var command = connection.CreateCommand();
|
||||
command.CommandText = sql;
|
||||
return command;
|
||||
}
|
||||
|
||||
protected bool TableExists(ManagedConnection connection, string name)
|
||||
{
|
||||
using var statement = PrepareStatement(connection, "select DISTINCT tbl_name from sqlite_master");
|
||||
foreach (var row in statement.ExecuteQuery())
|
||||
{
|
||||
if (string.Equals(name, row.GetString(0), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected List<string> GetColumnNames(ManagedConnection connection, string table)
|
||||
{
|
||||
var columnNames = new List<string>();
|
||||
|
||||
foreach (var row in connection.Query("PRAGMA table_info(" + table + ")"))
|
||||
{
|
||||
if (row.TryGetString(1, out var columnName))
|
||||
{
|
||||
columnNames.Add(columnName);
|
||||
}
|
||||
}
|
||||
|
||||
return columnNames;
|
||||
}
|
||||
|
||||
protected void AddColumn(ManagedConnection connection, string table, string columnName, string type, List<string> existingColumnNames)
|
||||
{
|
||||
if (existingColumnNames.Contains(columnName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
connection.Execute("alter table " + table + " add column " + columnName + " " + type + " NULL");
|
||||
}
|
||||
|
||||
protected void CheckDisposed()
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases unmanaged and - optionally - managed resources.
|
||||
/// </summary>
|
||||
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
|
||||
protected virtual void Dispose(bool dispose)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (dispose)
|
||||
{
|
||||
_writeLock.Wait();
|
||||
try
|
||||
{
|
||||
_writeConnection.Dispose();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_writeLock.Release();
|
||||
}
|
||||
|
||||
_writeLock.Dispose();
|
||||
}
|
||||
|
||||
_writeConnection = null;
|
||||
_writeLock = null;
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
#pragma warning disable CS1591
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Server.Implementations;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Emby.Server.Implementations.Data
|
||||
@@ -13,20 +16,24 @@ namespace Emby.Server.Implementations.Data
|
||||
{
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly ILogger<CleanDatabaseScheduledTask> _logger;
|
||||
private readonly IDbContextFactory<JellyfinDbContext> _dbProvider;
|
||||
|
||||
public CleanDatabaseScheduledTask(ILibraryManager libraryManager, ILogger<CleanDatabaseScheduledTask> logger)
|
||||
public CleanDatabaseScheduledTask(
|
||||
ILibraryManager libraryManager,
|
||||
ILogger<CleanDatabaseScheduledTask> logger,
|
||||
IDbContextFactory<JellyfinDbContext> dbProvider)
|
||||
{
|
||||
_libraryManager = libraryManager;
|
||||
_logger = logger;
|
||||
_dbProvider = dbProvider;
|
||||
}
|
||||
|
||||
public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
|
||||
public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
|
||||
{
|
||||
CleanDeadItems(cancellationToken, progress);
|
||||
return Task.CompletedTask;
|
||||
await CleanDeadItems(cancellationToken, progress).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private void CleanDeadItems(CancellationToken cancellationToken, IProgress<double> progress)
|
||||
private async Task CleanDeadItems(CancellationToken cancellationToken, IProgress<double> progress)
|
||||
{
|
||||
var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery
|
||||
{
|
||||
@@ -34,7 +41,7 @@ namespace Emby.Server.Implementations.Data
|
||||
});
|
||||
|
||||
var numComplete = 0;
|
||||
var numItems = itemIds.Count;
|
||||
var numItems = itemIds.Count + 1;
|
||||
|
||||
_logger.LogDebug("Cleaning {0} items with dead parent links", numItems);
|
||||
|
||||
@@ -60,6 +67,17 @@ namespace Emby.Server.Implementations.Data
|
||||
progress.Report(percent * 100);
|
||||
}
|
||||
|
||||
var context = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using (context.ConfigureAwait(false))
|
||||
{
|
||||
var transaction = await context.Database.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
|
||||
await using (transaction.ConfigureAwait(false))
|
||||
{
|
||||
await context.ItemValues.Where(e => e.BaseItemsMap!.Count == 0).ExecuteDeleteAsync(cancellationToken).ConfigureAwait(false);
|
||||
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
progress.Report(100);
|
||||
}
|
||||
}
|
||||
|
||||
64
Emby.Server.Implementations/Data/ItemTypeLookup.cs
Normal file
64
Emby.Server.Implementations/Data/ItemTypeLookup.cs
Normal file
@@ -0,0 +1,64 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Channels;
|
||||
using Emby.Server.Implementations.Playlists;
|
||||
using Jellyfin.Data.Enums;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Entities.Audio;
|
||||
using MediaBrowser.Controller.Entities.Movies;
|
||||
using MediaBrowser.Controller.Entities.TV;
|
||||
using MediaBrowser.Controller.LiveTv;
|
||||
using MediaBrowser.Controller.Persistence;
|
||||
using MediaBrowser.Controller.Playlists;
|
||||
|
||||
namespace Emby.Server.Implementations.Data;
|
||||
|
||||
/// <inheritdoc />
|
||||
public class ItemTypeLookup : IItemTypeLookup
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<string> MusicGenreTypes { get; } = [
|
||||
typeof(Audio).FullName!,
|
||||
typeof(MusicVideo).FullName!,
|
||||
typeof(MusicAlbum).FullName!,
|
||||
typeof(MusicArtist).FullName!,
|
||||
];
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyDictionary<BaseItemKind, string> BaseItemKindNames { get; } = new Dictionary<BaseItemKind, string>()
|
||||
{
|
||||
{ BaseItemKind.AggregateFolder, typeof(AggregateFolder).FullName! },
|
||||
{ BaseItemKind.Audio, typeof(Audio).FullName! },
|
||||
{ BaseItemKind.AudioBook, typeof(AudioBook).FullName! },
|
||||
{ BaseItemKind.BasePluginFolder, typeof(BasePluginFolder).FullName! },
|
||||
{ BaseItemKind.Book, typeof(Book).FullName! },
|
||||
{ BaseItemKind.BoxSet, typeof(BoxSet).FullName! },
|
||||
{ BaseItemKind.Channel, typeof(Channel).FullName! },
|
||||
{ BaseItemKind.CollectionFolder, typeof(CollectionFolder).FullName! },
|
||||
{ BaseItemKind.Episode, typeof(Episode).FullName! },
|
||||
{ BaseItemKind.Folder, typeof(Folder).FullName! },
|
||||
{ BaseItemKind.Genre, typeof(Genre).FullName! },
|
||||
{ BaseItemKind.Movie, typeof(Movie).FullName! },
|
||||
{ BaseItemKind.LiveTvChannel, typeof(LiveTvChannel).FullName! },
|
||||
{ BaseItemKind.LiveTvProgram, typeof(LiveTvProgram).FullName! },
|
||||
{ BaseItemKind.MusicAlbum, typeof(MusicAlbum).FullName! },
|
||||
{ BaseItemKind.MusicArtist, typeof(MusicArtist).FullName! },
|
||||
{ BaseItemKind.MusicGenre, typeof(MusicGenre).FullName! },
|
||||
{ BaseItemKind.MusicVideo, typeof(MusicVideo).FullName! },
|
||||
{ BaseItemKind.Person, typeof(Person).FullName! },
|
||||
{ BaseItemKind.Photo, typeof(Photo).FullName! },
|
||||
{ BaseItemKind.PhotoAlbum, typeof(PhotoAlbum).FullName! },
|
||||
{ BaseItemKind.Playlist, typeof(Playlist).FullName! },
|
||||
{ BaseItemKind.PlaylistsFolder, typeof(PlaylistsFolder).FullName! },
|
||||
{ BaseItemKind.Season, typeof(Season).FullName! },
|
||||
{ BaseItemKind.Series, typeof(Series).FullName! },
|
||||
{ BaseItemKind.Studio, typeof(Studio).FullName! },
|
||||
{ BaseItemKind.Trailer, typeof(Trailer).FullName! },
|
||||
{ BaseItemKind.TvChannel, typeof(LiveTvChannel).FullName! },
|
||||
{ BaseItemKind.TvProgram, typeof(LiveTvProgram).FullName! },
|
||||
{ BaseItemKind.UserRootFolder, typeof(UserRootFolder).FullName! },
|
||||
{ BaseItemKind.UserView, typeof(UserView).FullName! },
|
||||
{ BaseItemKind.Video, typeof(Video).FullName! },
|
||||
{ BaseItemKind.Year, typeof(Year).FullName! }
|
||||
}.ToFrozenDictionary();
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
#pragma warning disable CS1591
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using Microsoft.Data.Sqlite;
|
||||
|
||||
namespace Emby.Server.Implementations.Data;
|
||||
|
||||
public sealed class ManagedConnection : IDisposable
|
||||
{
|
||||
private readonly SemaphoreSlim? _writeLock;
|
||||
|
||||
private SqliteConnection _db;
|
||||
|
||||
private bool _disposed = false;
|
||||
|
||||
public ManagedConnection(SqliteConnection db, SemaphoreSlim? writeLock)
|
||||
{
|
||||
_db = db;
|
||||
_writeLock = writeLock;
|
||||
}
|
||||
|
||||
public SqliteTransaction BeginTransaction()
|
||||
=> _db.BeginTransaction();
|
||||
|
||||
public SqliteCommand CreateCommand()
|
||||
=> _db.CreateCommand();
|
||||
|
||||
public void Execute(string commandText)
|
||||
=> _db.Execute(commandText);
|
||||
|
||||
public SqliteCommand PrepareStatement(string sql)
|
||||
=> _db.PrepareStatement(sql);
|
||||
|
||||
public IEnumerable<SqliteDataReader> Query(string commandText)
|
||||
=> _db.Query(commandText);
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (_writeLock is null)
|
||||
{
|
||||
// Read connections are managed with an internal pool
|
||||
_db.Dispose();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Write lock is managed by BaseSqliteRepository
|
||||
// Don't dispose here
|
||||
_writeLock.Release();
|
||||
}
|
||||
|
||||
_db = null!;
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
@@ -127,8 +127,16 @@ namespace Emby.Server.Implementations.Data
|
||||
return false;
|
||||
}
|
||||
|
||||
result = reader.GetGuid(index);
|
||||
return true;
|
||||
try
|
||||
{
|
||||
result = reader.GetGuid(index);
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
result = Guid.Empty;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TryGetString(this SqliteDataReader reader, int index, out string result)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,369 +0,0 @@
|
||||
#nullable disable
|
||||
|
||||
#pragma warning disable CS1591
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using Jellyfin.Data.Entities;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Persistence;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Emby.Server.Implementations.Data
|
||||
{
|
||||
public class SqliteUserDataRepository : BaseSqliteRepository, IUserDataRepository
|
||||
{
|
||||
private readonly IUserManager _userManager;
|
||||
|
||||
public SqliteUserDataRepository(
|
||||
ILogger<SqliteUserDataRepository> logger,
|
||||
IServerConfigurationManager config,
|
||||
IUserManager userManager)
|
||||
: base(logger)
|
||||
{
|
||||
_userManager = userManager;
|
||||
|
||||
DbFilePath = Path.Combine(config.ApplicationPaths.DataPath, "library.db");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the connection to the database.
|
||||
/// </summary>
|
||||
public override void Initialize()
|
||||
{
|
||||
base.Initialize();
|
||||
|
||||
using (var connection = GetConnection())
|
||||
{
|
||||
var userDatasTableExists = TableExists(connection, "UserDatas");
|
||||
var userDataTableExists = TableExists(connection, "userdata");
|
||||
|
||||
var users = userDatasTableExists ? null : _userManager.Users;
|
||||
using var transaction = connection.BeginTransaction();
|
||||
connection.Execute(string.Join(
|
||||
';',
|
||||
"create table if not exists UserDatas (key nvarchar not null, userId INT not null, rating float null, played bit not null, playCount int not null, isFavorite bit not null, playbackPositionTicks bigint not null, lastPlayedDate datetime null, AudioStreamIndex INT, SubtitleStreamIndex INT)",
|
||||
"drop index if exists idx_userdata",
|
||||
"drop index if exists idx_userdata1",
|
||||
"drop index if exists idx_userdata2",
|
||||
"drop index if exists userdataindex1",
|
||||
"drop index if exists userdataindex",
|
||||
"drop index if exists userdataindex3",
|
||||
"drop index if exists userdataindex4",
|
||||
"create unique index if not exists UserDatasIndex1 on UserDatas (key, userId)",
|
||||
"create index if not exists UserDatasIndex2 on UserDatas (key, userId, played)",
|
||||
"create index if not exists UserDatasIndex3 on UserDatas (key, userId, playbackPositionTicks)",
|
||||
"create index if not exists UserDatasIndex4 on UserDatas (key, userId, isFavorite)",
|
||||
"create index if not exists UserDatasIndex5 on UserDatas (key, userId, lastPlayedDate)"));
|
||||
|
||||
if (!userDataTableExists)
|
||||
{
|
||||
transaction.Commit();
|
||||
return;
|
||||
}
|
||||
|
||||
var existingColumnNames = GetColumnNames(connection, "userdata");
|
||||
|
||||
AddColumn(connection, "userdata", "InternalUserId", "int", existingColumnNames);
|
||||
AddColumn(connection, "userdata", "AudioStreamIndex", "int", existingColumnNames);
|
||||
AddColumn(connection, "userdata", "SubtitleStreamIndex", "int", existingColumnNames);
|
||||
|
||||
if (userDatasTableExists)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
ImportUserIds(connection, users);
|
||||
|
||||
connection.Execute("INSERT INTO UserDatas (key, userId, rating, played, playCount, isFavorite, playbackPositionTicks, lastPlayedDate, AudioStreamIndex, SubtitleStreamIndex) SELECT key, InternalUserId, rating, played, playCount, isFavorite, playbackPositionTicks, lastPlayedDate, AudioStreamIndex, SubtitleStreamIndex from userdata where InternalUserId not null");
|
||||
|
||||
transaction.Commit();
|
||||
}
|
||||
}
|
||||
|
||||
private void ImportUserIds(ManagedConnection db, IEnumerable<User> users)
|
||||
{
|
||||
var userIdsWithUserData = GetAllUserIdsWithUserData(db);
|
||||
|
||||
using (var statement = db.PrepareStatement("update userdata set InternalUserId=@InternalUserId where UserId=@UserId"))
|
||||
{
|
||||
foreach (var user in users)
|
||||
{
|
||||
if (!userIdsWithUserData.Contains(user.Id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
statement.TryBind("@UserId", user.Id);
|
||||
statement.TryBind("@InternalUserId", user.InternalId);
|
||||
|
||||
statement.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private List<Guid> GetAllUserIdsWithUserData(ManagedConnection db)
|
||||
{
|
||||
var list = new List<Guid>();
|
||||
|
||||
using (var statement = PrepareStatement(db, "select DISTINCT UserId from UserData where UserId not null"))
|
||||
{
|
||||
foreach (var row in statement.ExecuteQuery())
|
||||
{
|
||||
try
|
||||
{
|
||||
list.Add(row.GetGuid(0));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "Error while getting user");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void SaveUserData(long userId, string key, UserItemData userData, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(userData);
|
||||
|
||||
if (userId <= 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(userId));
|
||||
}
|
||||
|
||||
ArgumentException.ThrowIfNullOrEmpty(key);
|
||||
|
||||
PersistUserData(userId, key, userData, cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void SaveAllUserData(long userId, UserItemData[] userData, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(userData);
|
||||
|
||||
if (userId <= 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(userId));
|
||||
}
|
||||
|
||||
PersistAllUserData(userId, userData, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persists the user data.
|
||||
/// </summary>
|
||||
/// <param name="internalUserId">The user id.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <param name="userData">The user data.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
public void PersistUserData(long internalUserId, string key, UserItemData userData, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
using (var connection = GetConnection())
|
||||
using (var transaction = connection.BeginTransaction())
|
||||
{
|
||||
SaveUserData(connection, internalUserId, key, userData);
|
||||
transaction.Commit();
|
||||
}
|
||||
}
|
||||
|
||||
private static void SaveUserData(ManagedConnection db, long internalUserId, string key, UserItemData userData)
|
||||
{
|
||||
using (var statement = db.PrepareStatement("replace into UserDatas (key, userId, rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex) values (@key, @userId, @rating,@played,@playCount,@isFavorite,@playbackPositionTicks,@lastPlayedDate,@AudioStreamIndex,@SubtitleStreamIndex)"))
|
||||
{
|
||||
statement.TryBind("@userId", internalUserId);
|
||||
statement.TryBind("@key", key);
|
||||
|
||||
if (userData.Rating.HasValue)
|
||||
{
|
||||
statement.TryBind("@rating", userData.Rating.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
statement.TryBindNull("@rating");
|
||||
}
|
||||
|
||||
statement.TryBind("@played", userData.Played);
|
||||
statement.TryBind("@playCount", userData.PlayCount);
|
||||
statement.TryBind("@isFavorite", userData.IsFavorite);
|
||||
statement.TryBind("@playbackPositionTicks", userData.PlaybackPositionTicks);
|
||||
|
||||
if (userData.LastPlayedDate.HasValue)
|
||||
{
|
||||
statement.TryBind("@lastPlayedDate", userData.LastPlayedDate.Value.ToDateTimeParamValue());
|
||||
}
|
||||
else
|
||||
{
|
||||
statement.TryBindNull("@lastPlayedDate");
|
||||
}
|
||||
|
||||
if (userData.AudioStreamIndex.HasValue)
|
||||
{
|
||||
statement.TryBind("@AudioStreamIndex", userData.AudioStreamIndex.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
statement.TryBindNull("@AudioStreamIndex");
|
||||
}
|
||||
|
||||
if (userData.SubtitleStreamIndex.HasValue)
|
||||
{
|
||||
statement.TryBind("@SubtitleStreamIndex", userData.SubtitleStreamIndex.Value);
|
||||
}
|
||||
else
|
||||
{
|
||||
statement.TryBindNull("@SubtitleStreamIndex");
|
||||
}
|
||||
|
||||
statement.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persist all user data for the specified user.
|
||||
/// </summary>
|
||||
private void PersistAllUserData(long internalUserId, UserItemData[] userDataList, CancellationToken cancellationToken)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
using (var connection = GetConnection())
|
||||
using (var transaction = connection.BeginTransaction())
|
||||
{
|
||||
foreach (var userItemData in userDataList)
|
||||
{
|
||||
SaveUserData(connection, internalUserId, userItemData.Key, userItemData);
|
||||
}
|
||||
|
||||
transaction.Commit();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user data.
|
||||
/// </summary>
|
||||
/// <param name="userId">The user id.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns>Task{UserItemData}.</returns>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// userId
|
||||
/// or
|
||||
/// key.
|
||||
/// </exception>
|
||||
public UserItemData GetUserData(long userId, string key)
|
||||
{
|
||||
if (userId <= 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(userId));
|
||||
}
|
||||
|
||||
ArgumentException.ThrowIfNullOrEmpty(key);
|
||||
|
||||
using (var connection = GetConnection(true))
|
||||
{
|
||||
using (var statement = connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from UserDatas where key =@Key and userId=@UserId"))
|
||||
{
|
||||
statement.TryBind("@UserId", userId);
|
||||
statement.TryBind("@Key", key);
|
||||
|
||||
foreach (var row in statement.ExecuteQuery())
|
||||
{
|
||||
return ReadRow(row);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public UserItemData GetUserData(long userId, List<string> keys)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(keys);
|
||||
|
||||
if (keys.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return GetUserData(userId, keys[0]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return all user-data associated with the given user.
|
||||
/// </summary>
|
||||
/// <param name="userId">The internal user id.</param>
|
||||
/// <returns>The list of user item data.</returns>
|
||||
public List<UserItemData> GetAllUserData(long userId)
|
||||
{
|
||||
if (userId <= 0)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(userId));
|
||||
}
|
||||
|
||||
var list = new List<UserItemData>();
|
||||
|
||||
using (var connection = GetConnection())
|
||||
{
|
||||
using (var statement = connection.PrepareStatement("select key,userid,rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate,AudioStreamIndex,SubtitleStreamIndex from UserDatas where userId=@UserId"))
|
||||
{
|
||||
statement.TryBind("@UserId", userId);
|
||||
|
||||
foreach (var row in statement.ExecuteQuery())
|
||||
{
|
||||
list.Add(ReadRow(row));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read a row from the specified reader into the provided userData object.
|
||||
/// </summary>
|
||||
/// <param name="reader">The list of result set values.</param>
|
||||
/// <returns>The user item data.</returns>
|
||||
private UserItemData ReadRow(SqliteDataReader reader)
|
||||
{
|
||||
var userData = new UserItemData
|
||||
{
|
||||
Key = reader.GetString(0)
|
||||
};
|
||||
|
||||
if (reader.TryGetDouble(2, out var rating))
|
||||
{
|
||||
userData.Rating = rating;
|
||||
}
|
||||
|
||||
userData.Played = reader.GetBoolean(3);
|
||||
userData.PlayCount = reader.GetInt32(4);
|
||||
userData.IsFavorite = reader.GetBoolean(5);
|
||||
userData.PlaybackPositionTicks = reader.GetInt64(6);
|
||||
|
||||
if (reader.TryReadDateTime(7, out var lastPlayedDate))
|
||||
{
|
||||
userData.LastPlayedDate = lastPlayedDate;
|
||||
}
|
||||
|
||||
if (reader.TryGetInt32(8, out var audioStreamIndex))
|
||||
{
|
||||
userData.AudioStreamIndex = audioStreamIndex;
|
||||
}
|
||||
|
||||
if (reader.TryGetInt32(9, out var subtitleStreamIndex))
|
||||
{
|
||||
userData.SubtitleStreamIndex = subtitleStreamIndex;
|
||||
}
|
||||
|
||||
return userData;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
namespace Emby.Server.Implementations.Data;
|
||||
|
||||
/// <summary>
|
||||
/// The disk synchronization mode, controls how aggressively SQLite will write data
|
||||
/// all the way out to physical storage.
|
||||
/// </summary>
|
||||
public enum SynchronousMode
|
||||
{
|
||||
/// <summary>
|
||||
/// SQLite continues without syncing as soon as it has handed data off to the operating system.
|
||||
/// </summary>
|
||||
Off = 0,
|
||||
|
||||
/// <summary>
|
||||
/// SQLite database engine will still sync at the most critical moments.
|
||||
/// </summary>
|
||||
Normal = 1,
|
||||
|
||||
/// <summary>
|
||||
/// SQLite database engine will use the xSync method of the VFS
|
||||
/// to ensure that all content is safely written to the disk surface prior to continuing.
|
||||
/// </summary>
|
||||
Full = 2,
|
||||
|
||||
/// <summary>
|
||||
/// EXTRA synchronous is like FULL with the addition that the directory containing a rollback journal
|
||||
/// is synced after that journal is unlinked to commit a transaction in DELETE mode.
|
||||
/// </summary>
|
||||
Extra = 3
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
namespace Emby.Server.Implementations.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Storage mode used by temporary database files.
|
||||
/// </summary>
|
||||
public enum TempStoreMode
|
||||
{
|
||||
/// <summary>
|
||||
/// The compile-time C preprocessor macro SQLITE_TEMP_STORE
|
||||
/// is used to determine where temporary tables and indices are stored.
|
||||
/// </summary>
|
||||
Default = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Temporary tables and indices are stored in a file.
|
||||
/// </summary>
|
||||
File = 1,
|
||||
|
||||
/// <summary>
|
||||
/// Temporary tables and indices are kept in as if they were pure in-memory databases memory.
|
||||
/// </summary>
|
||||
Memory = 2
|
||||
}
|
||||
@@ -10,6 +10,7 @@ using Jellyfin.Data.Enums;
|
||||
using Jellyfin.Extensions;
|
||||
using MediaBrowser.Common;
|
||||
using MediaBrowser.Controller.Channels;
|
||||
using MediaBrowser.Controller.Chapters;
|
||||
using MediaBrowser.Controller.Drawing;
|
||||
using MediaBrowser.Controller.Dto;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
@@ -51,6 +52,7 @@ namespace Emby.Server.Implementations.Dto
|
||||
private readonly Lazy<ILiveTvManager> _livetvManagerFactory;
|
||||
|
||||
private readonly ITrickplayManager _trickplayManager;
|
||||
private readonly IChapterRepository _chapterRepository;
|
||||
|
||||
public DtoService(
|
||||
ILogger<DtoService> logger,
|
||||
@@ -63,7 +65,8 @@ namespace Emby.Server.Implementations.Dto
|
||||
IApplicationHost appHost,
|
||||
IMediaSourceManager mediaSourceManager,
|
||||
Lazy<ILiveTvManager> livetvManagerFactory,
|
||||
ITrickplayManager trickplayManager)
|
||||
ITrickplayManager trickplayManager,
|
||||
IChapterRepository chapterRepository)
|
||||
{
|
||||
_logger = logger;
|
||||
_libraryManager = libraryManager;
|
||||
@@ -76,6 +79,7 @@ namespace Emby.Server.Implementations.Dto
|
||||
_mediaSourceManager = mediaSourceManager;
|
||||
_livetvManagerFactory = livetvManagerFactory;
|
||||
_trickplayManager = trickplayManager;
|
||||
_chapterRepository = chapterRepository;
|
||||
}
|
||||
|
||||
private ILiveTvManager LivetvManager => _livetvManagerFactory.Value;
|
||||
@@ -165,7 +169,7 @@ namespace Emby.Server.Implementations.Dto
|
||||
return dto;
|
||||
}
|
||||
|
||||
private static IList<BaseItem> GetTaggedItems(IItemByName byName, User? user, DtoOptions options)
|
||||
private static IReadOnlyList<BaseItem> GetTaggedItems(IItemByName byName, User? user, DtoOptions options)
|
||||
{
|
||||
return byName.GetTaggedItems(
|
||||
new InternalItemsQuery(user)
|
||||
@@ -327,7 +331,7 @@ namespace Emby.Server.Implementations.Dto
|
||||
return dto;
|
||||
}
|
||||
|
||||
private static void SetItemByNameInfo(BaseItem item, BaseItemDto dto, IList<BaseItem> taggedItems)
|
||||
private static void SetItemByNameInfo(BaseItem item, BaseItemDto dto, IReadOnlyList<BaseItem> taggedItems)
|
||||
{
|
||||
if (item is MusicArtist)
|
||||
{
|
||||
@@ -1060,7 +1064,7 @@ namespace Emby.Server.Implementations.Dto
|
||||
|
||||
if (options.ContainsField(ItemFields.Chapters))
|
||||
{
|
||||
dto.Chapters = _itemRepo.GetChapters(item);
|
||||
dto.Chapters = _chapterRepository.GetChapters(item.Id).ToList();
|
||||
}
|
||||
|
||||
if (options.ContainsField(ItemFields.Trickplay))
|
||||
|
||||
@@ -144,9 +144,15 @@ namespace Emby.Server.Implementations.EntryPoints
|
||||
.Select(i =>
|
||||
{
|
||||
var dto = _userDataManager.GetUserDataDto(i, user);
|
||||
if (dto is null)
|
||||
{
|
||||
return null!;
|
||||
}
|
||||
|
||||
dto.ItemId = i.Id;
|
||||
return dto;
|
||||
})
|
||||
.Where(e => e is not null)
|
||||
.ToArray()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -76,6 +76,7 @@ namespace Emby.Server.Implementations.Library
|
||||
private readonly IItemRepository _itemRepository;
|
||||
private readonly IImageProcessor _imageProcessor;
|
||||
private readonly NamingOptions _namingOptions;
|
||||
private readonly IPeopleRepository _peopleRepository;
|
||||
private readonly ExtraResolver _extraResolver;
|
||||
|
||||
/// <summary>
|
||||
@@ -112,6 +113,7 @@ namespace Emby.Server.Implementations.Library
|
||||
/// <param name="imageProcessor">The image processor.</param>
|
||||
/// <param name="namingOptions">The naming options.</param>
|
||||
/// <param name="directoryService">The directory service.</param>
|
||||
/// <param name="peopleRepository">The People Repository.</param>
|
||||
public LibraryManager(
|
||||
IServerApplicationHost appHost,
|
||||
ILoggerFactory loggerFactory,
|
||||
@@ -127,7 +129,8 @@ namespace Emby.Server.Implementations.Library
|
||||
IItemRepository itemRepository,
|
||||
IImageProcessor imageProcessor,
|
||||
NamingOptions namingOptions,
|
||||
IDirectoryService directoryService)
|
||||
IDirectoryService directoryService,
|
||||
IPeopleRepository peopleRepository)
|
||||
{
|
||||
_appHost = appHost;
|
||||
_logger = loggerFactory.CreateLogger<LibraryManager>();
|
||||
@@ -144,7 +147,7 @@ namespace Emby.Server.Implementations.Library
|
||||
_imageProcessor = imageProcessor;
|
||||
_cache = new ConcurrentDictionary<Guid, BaseItem>();
|
||||
_namingOptions = namingOptions;
|
||||
|
||||
_peopleRepository = peopleRepository;
|
||||
_extraResolver = new ExtraResolver(loggerFactory.CreateLogger<ExtraResolver>(), namingOptions, directoryService);
|
||||
|
||||
_configurationManager.ConfigurationUpdated += ConfigurationUpdated;
|
||||
@@ -1274,7 +1277,7 @@ namespace Emby.Server.Implementations.Library
|
||||
return ItemIsVisible(item, user) ? item : null;
|
||||
}
|
||||
|
||||
public List<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
|
||||
public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, bool allowExternalContent)
|
||||
{
|
||||
if (query.Recursive && !query.ParentId.IsEmpty())
|
||||
{
|
||||
@@ -1300,7 +1303,7 @@ namespace Emby.Server.Implementations.Library
|
||||
return itemList;
|
||||
}
|
||||
|
||||
public List<BaseItem> GetItemList(InternalItemsQuery query)
|
||||
public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query)
|
||||
{
|
||||
return GetItemList(query, true);
|
||||
}
|
||||
@@ -1324,7 +1327,7 @@ namespace Emby.Server.Implementations.Library
|
||||
return _itemRepository.GetCount(query);
|
||||
}
|
||||
|
||||
public List<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents)
|
||||
public IReadOnlyList<BaseItem> GetItemList(InternalItemsQuery query, List<BaseItem> parents)
|
||||
{
|
||||
SetTopParentIdsOrAncestors(query, parents);
|
||||
|
||||
@@ -1357,7 +1360,7 @@ namespace Emby.Server.Implementations.Library
|
||||
_itemRepository.GetItemList(query));
|
||||
}
|
||||
|
||||
public List<Guid> GetItemIds(InternalItemsQuery query)
|
||||
public IReadOnlyList<Guid> GetItemIds(InternalItemsQuery query)
|
||||
{
|
||||
if (query.User is not null)
|
||||
{
|
||||
@@ -1807,11 +1810,11 @@ namespace Emby.Server.Implementations.Library
|
||||
/// <inheritdoc />
|
||||
public void CreateItem(BaseItem item, BaseItem? parent)
|
||||
{
|
||||
CreateItems(new[] { item }, parent, CancellationToken.None);
|
||||
CreateOrUpdateItems(new[] { item }, parent, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void CreateItems(IReadOnlyList<BaseItem> items, BaseItem? parent, CancellationToken cancellationToken)
|
||||
public void CreateOrUpdateItems(IReadOnlyList<BaseItem> items, BaseItem? parent, CancellationToken cancellationToken)
|
||||
{
|
||||
_itemRepository.SaveItems(items, cancellationToken);
|
||||
|
||||
@@ -1955,13 +1958,13 @@ namespace Emby.Server.Implementations.Library
|
||||
/// <inheritdoc />
|
||||
public async Task UpdateItemsAsync(IReadOnlyList<BaseItem> items, BaseItem parent, ItemUpdateType updateReason, CancellationToken cancellationToken)
|
||||
{
|
||||
_itemRepository.SaveItems(items, cancellationToken);
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
await RunMetadataSavers(item, updateReason).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_itemRepository.SaveItems(items, cancellationToken);
|
||||
|
||||
if (ItemUpdated is not null)
|
||||
{
|
||||
foreach (var item in items)
|
||||
@@ -2736,12 +2739,12 @@ namespace Emby.Server.Implementations.Library
|
||||
return path;
|
||||
}
|
||||
|
||||
public List<PersonInfo> GetPeople(InternalPeopleQuery query)
|
||||
public IReadOnlyList<PersonInfo> GetPeople(InternalPeopleQuery query)
|
||||
{
|
||||
return _itemRepository.GetPeople(query);
|
||||
return _peopleRepository.GetPeople(query);
|
||||
}
|
||||
|
||||
public List<PersonInfo> GetPeople(BaseItem item)
|
||||
public IReadOnlyList<PersonInfo> GetPeople(BaseItem item)
|
||||
{
|
||||
if (item.SupportsPeople)
|
||||
{
|
||||
@@ -2756,12 +2759,12 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
}
|
||||
|
||||
return new List<PersonInfo>();
|
||||
return [];
|
||||
}
|
||||
|
||||
public List<Person> GetPeopleItems(InternalPeopleQuery query)
|
||||
public IReadOnlyList<Person> GetPeopleItems(InternalPeopleQuery query)
|
||||
{
|
||||
return _itemRepository.GetPeopleNames(query)
|
||||
return _peopleRepository.GetPeopleNames(query)
|
||||
.Select(i =>
|
||||
{
|
||||
try
|
||||
@@ -2779,9 +2782,9 @@ namespace Emby.Server.Implementations.Library
|
||||
.ToList()!; // null values are filtered out
|
||||
}
|
||||
|
||||
public List<string> GetPeopleNames(InternalPeopleQuery query)
|
||||
public IReadOnlyList<string> GetPeopleNames(InternalPeopleQuery query)
|
||||
{
|
||||
return _itemRepository.GetPeopleNames(query);
|
||||
return _peopleRepository.GetPeopleNames(query);
|
||||
}
|
||||
|
||||
public void UpdatePeople(BaseItem item, List<PersonInfo> people)
|
||||
@@ -2790,16 +2793,17 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task UpdatePeopleAsync(BaseItem item, List<PersonInfo> people, CancellationToken cancellationToken)
|
||||
public async Task UpdatePeopleAsync(BaseItem item, IReadOnlyList<PersonInfo> people, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!item.SupportsPeople)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_itemRepository.UpdatePeople(item.Id, people);
|
||||
if (people is not null)
|
||||
{
|
||||
people = people.Where(e => e is not null).ToArray();
|
||||
_peopleRepository.UpdatePeople(item.Id, people);
|
||||
await SavePeopleMetadataAsync(people, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -2914,14 +2918,13 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
private async Task SavePeopleMetadataAsync(IEnumerable<PersonInfo> people, CancellationToken cancellationToken)
|
||||
{
|
||||
List<BaseItem>? personsToSave = null;
|
||||
|
||||
foreach (var person in people)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var itemUpdateType = ItemUpdateType.MetadataDownload;
|
||||
var saveEntity = false;
|
||||
var createEntity = false;
|
||||
var personEntity = GetPerson(person.Name);
|
||||
|
||||
if (personEntity is null)
|
||||
@@ -2938,6 +2941,7 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
personEntity.PresentationUniqueKey = personEntity.CreatePresentationUniqueKey();
|
||||
saveEntity = true;
|
||||
createEntity = true;
|
||||
}
|
||||
|
||||
foreach (var id in person.ProviderIds)
|
||||
@@ -2965,14 +2969,14 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
if (saveEntity)
|
||||
{
|
||||
(personsToSave ??= new()).Add(personEntity);
|
||||
await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
if (createEntity)
|
||||
{
|
||||
CreateOrUpdateItems([personEntity], null, CancellationToken.None);
|
||||
}
|
||||
|
||||
if (personsToSave is not null)
|
||||
{
|
||||
CreateItems(personsToSave, null, CancellationToken.None);
|
||||
await RunMetadataSavers(personEntity, itemUpdateType).ConfigureAwait(false);
|
||||
CreateOrUpdateItems([personEntity], null, CancellationToken.None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3027,7 +3031,7 @@ namespace Emby.Server.Implementations.Library
|
||||
{
|
||||
var libraryOptions = CollectionFolder.GetLibraryOptions(virtualFolderPath);
|
||||
|
||||
libraryOptions.PathInfos = [..libraryOptions.PathInfos, pathInfo];
|
||||
libraryOptions.PathInfos = [.. libraryOptions.PathInfos, pathInfo];
|
||||
|
||||
SyncLibraryOptionsToLocations(virtualFolderPath, libraryOptions);
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
@@ -51,7 +52,8 @@ namespace Emby.Server.Implementations.Library
|
||||
private readonly ILocalizationManager _localizationManager;
|
||||
private readonly IApplicationPaths _appPaths;
|
||||
private readonly IDirectoryService _directoryService;
|
||||
|
||||
private readonly IMediaStreamRepository _mediaStreamRepository;
|
||||
private readonly IMediaAttachmentRepository _mediaAttachmentRepository;
|
||||
private readonly ConcurrentDictionary<string, ILiveStream> _openStreams = new ConcurrentDictionary<string, ILiveStream>(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly AsyncNonKeyedLocker _liveStreamLocker = new(1);
|
||||
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
|
||||
@@ -69,7 +71,9 @@ namespace Emby.Server.Implementations.Library
|
||||
IFileSystem fileSystem,
|
||||
IUserDataManager userDataManager,
|
||||
IMediaEncoder mediaEncoder,
|
||||
IDirectoryService directoryService)
|
||||
IDirectoryService directoryService,
|
||||
IMediaStreamRepository mediaStreamRepository,
|
||||
IMediaAttachmentRepository mediaAttachmentRepository)
|
||||
{
|
||||
_appHost = appHost;
|
||||
_itemRepo = itemRepo;
|
||||
@@ -82,6 +86,8 @@ namespace Emby.Server.Implementations.Library
|
||||
_localizationManager = localizationManager;
|
||||
_appPaths = applicationPaths;
|
||||
_directoryService = directoryService;
|
||||
_mediaStreamRepository = mediaStreamRepository;
|
||||
_mediaAttachmentRepository = mediaAttachmentRepository;
|
||||
}
|
||||
|
||||
public void AddParts(IEnumerable<IMediaSourceProvider> providers)
|
||||
@@ -89,9 +95,9 @@ namespace Emby.Server.Implementations.Library
|
||||
_providers = providers.ToArray();
|
||||
}
|
||||
|
||||
public List<MediaStream> GetMediaStreams(MediaStreamQuery query)
|
||||
public IReadOnlyList<MediaStream> GetMediaStreams(MediaStreamQuery query)
|
||||
{
|
||||
var list = _itemRepo.GetMediaStreams(query);
|
||||
var list = _mediaStreamRepository.GetMediaStreams(query);
|
||||
|
||||
foreach (var stream in list)
|
||||
{
|
||||
@@ -121,7 +127,7 @@ namespace Emby.Server.Implementations.Library
|
||||
return false;
|
||||
}
|
||||
|
||||
public List<MediaStream> GetMediaStreams(Guid itemId)
|
||||
public IReadOnlyList<MediaStream> GetMediaStreams(Guid itemId)
|
||||
{
|
||||
var list = GetMediaStreams(new MediaStreamQuery
|
||||
{
|
||||
@@ -131,7 +137,7 @@ namespace Emby.Server.Implementations.Library
|
||||
return GetMediaStreamsForItem(list);
|
||||
}
|
||||
|
||||
private List<MediaStream> GetMediaStreamsForItem(List<MediaStream> streams)
|
||||
private IReadOnlyList<MediaStream> GetMediaStreamsForItem(IReadOnlyList<MediaStream> streams)
|
||||
{
|
||||
foreach (var stream in streams)
|
||||
{
|
||||
@@ -145,13 +151,13 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public List<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery query)
|
||||
public IReadOnlyList<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery query)
|
||||
{
|
||||
return _itemRepo.GetMediaAttachments(query);
|
||||
return _mediaAttachmentRepository.GetMediaAttachments(query);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public List<MediaAttachment> GetMediaAttachments(Guid itemId)
|
||||
public IReadOnlyList<MediaAttachment> GetMediaAttachments(Guid itemId)
|
||||
{
|
||||
return GetMediaAttachments(new MediaAttachmentQuery
|
||||
{
|
||||
@@ -159,7 +165,7 @@ namespace Emby.Server.Implementations.Library
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<List<MediaSourceInfo>> GetPlaybackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken)
|
||||
public async Task<IReadOnlyList<MediaSourceInfo>> GetPlaybackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken)
|
||||
{
|
||||
var mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user);
|
||||
|
||||
@@ -212,7 +218,7 @@ namespace Emby.Server.Implementations.Library
|
||||
list.Add(source);
|
||||
}
|
||||
|
||||
return SortMediaSources(list);
|
||||
return SortMediaSources(list).ToArray();
|
||||
}
|
||||
|
||||
/// <inheritdoc />>
|
||||
@@ -332,7 +338,7 @@ namespace Emby.Server.Implementations.Library
|
||||
return sources.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
public List<MediaSourceInfo> GetStaticMediaSources(BaseItem item, bool enablePathSubstitution, User user = null)
|
||||
public IReadOnlyList<MediaSourceInfo> GetStaticMediaSources(BaseItem item, bool enablePathSubstitution, User user = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
|
||||
@@ -453,7 +459,7 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
}
|
||||
|
||||
private static List<MediaSourceInfo> SortMediaSources(IEnumerable<MediaSourceInfo> sources)
|
||||
private static IEnumerable<MediaSourceInfo> SortMediaSources(IEnumerable<MediaSourceInfo> sources)
|
||||
{
|
||||
return sources.OrderBy(i =>
|
||||
{
|
||||
@@ -470,8 +476,7 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
return stream?.Width ?? 0;
|
||||
})
|
||||
.Where(i => i.Type != MediaSourceType.Placeholder)
|
||||
.ToList();
|
||||
.Where(i => i.Type != MediaSourceType.Placeholder);
|
||||
}
|
||||
|
||||
public async Task<Tuple<LiveStreamResponse, IDirectStreamProvider>> OpenLiveStreamInternal(LiveStreamRequest request, CancellationToken cancellationToken)
|
||||
@@ -806,7 +811,7 @@ namespace Emby.Server.Implementations.Library
|
||||
return result.Item1;
|
||||
}
|
||||
|
||||
public async Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(ActiveRecordingInfo info, CancellationToken cancellationToken)
|
||||
public async Task<IReadOnlyList<MediaSourceInfo>> GetRecordingStreamMediaSources(ActiveRecordingInfo info, CancellationToken cancellationToken)
|
||||
{
|
||||
var stream = new MediaSourceInfo
|
||||
{
|
||||
@@ -829,10 +834,7 @@ namespace Emby.Server.Implementations.Library
|
||||
await new LiveStreamHelper(_mediaEncoder, _logger, _appPaths)
|
||||
.AddMediaInfoWithProbe(stream, false, false, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return new List<MediaSourceInfo>
|
||||
{
|
||||
stream
|
||||
};
|
||||
return [stream];
|
||||
}
|
||||
|
||||
public async Task CloseLiveStream(string id)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using Jellyfin.Data.Entities;
|
||||
using Jellyfin.Data.Enums;
|
||||
@@ -24,30 +25,23 @@ namespace Emby.Server.Implementations.Library
|
||||
_libraryManager = libraryManager;
|
||||
}
|
||||
|
||||
public List<BaseItem> GetInstantMixFromSong(Audio item, User? user, DtoOptions dtoOptions)
|
||||
{
|
||||
var list = new List<BaseItem>
|
||||
{
|
||||
item
|
||||
};
|
||||
|
||||
list.AddRange(GetInstantMixFromGenres(item.Genres, user, dtoOptions));
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public List<BaseItem> GetInstantMixFromArtist(MusicArtist artist, User? user, DtoOptions dtoOptions)
|
||||
{
|
||||
return GetInstantMixFromGenres(artist.Genres, user, dtoOptions);
|
||||
}
|
||||
|
||||
public List<BaseItem> GetInstantMixFromAlbum(MusicAlbum item, User? user, DtoOptions dtoOptions)
|
||||
public IReadOnlyList<BaseItem> GetInstantMixFromSong(Audio item, User? user, DtoOptions dtoOptions)
|
||||
{
|
||||
return GetInstantMixFromGenres(item.Genres, user, dtoOptions);
|
||||
}
|
||||
|
||||
public List<BaseItem> GetInstantMixFromFolder(Folder item, User? user, DtoOptions dtoOptions)
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<BaseItem> GetInstantMixFromArtist(MusicArtist artist, User? user, DtoOptions dtoOptions)
|
||||
{
|
||||
return GetInstantMixFromGenres(artist.Genres, user, dtoOptions);
|
||||
}
|
||||
|
||||
public IReadOnlyList<BaseItem> GetInstantMixFromAlbum(MusicAlbum item, User? user, DtoOptions dtoOptions)
|
||||
{
|
||||
return GetInstantMixFromGenres(item.Genres, user, dtoOptions);
|
||||
}
|
||||
|
||||
public IReadOnlyList<BaseItem> GetInstantMixFromFolder(Folder item, User? user, DtoOptions dtoOptions)
|
||||
{
|
||||
var genres = item
|
||||
.GetRecursiveChildren(user, new InternalItemsQuery(user)
|
||||
@@ -63,12 +57,12 @@ namespace Emby.Server.Implementations.Library
|
||||
return GetInstantMixFromGenres(genres, user, dtoOptions);
|
||||
}
|
||||
|
||||
public List<BaseItem> GetInstantMixFromPlaylist(Playlist item, User? user, DtoOptions dtoOptions)
|
||||
public IReadOnlyList<BaseItem> GetInstantMixFromPlaylist(Playlist item, User? user, DtoOptions dtoOptions)
|
||||
{
|
||||
return GetInstantMixFromGenres(item.Genres, user, dtoOptions);
|
||||
}
|
||||
|
||||
public List<BaseItem> GetInstantMixFromGenres(IEnumerable<string> genres, User? user, DtoOptions dtoOptions)
|
||||
public IReadOnlyList<BaseItem> GetInstantMixFromGenres(IEnumerable<string> genres, User? user, DtoOptions dtoOptions)
|
||||
{
|
||||
var genreIds = genres.DistinctNames().Select(i =>
|
||||
{
|
||||
@@ -85,7 +79,7 @@ namespace Emby.Server.Implementations.Library
|
||||
return GetInstantMixFromGenreIds(genreIds, user, dtoOptions);
|
||||
}
|
||||
|
||||
public List<BaseItem> GetInstantMixFromGenreIds(Guid[] genreIds, User? user, DtoOptions dtoOptions)
|
||||
public IReadOnlyList<BaseItem> GetInstantMixFromGenreIds(Guid[] genreIds, User? user, DtoOptions dtoOptions)
|
||||
{
|
||||
return _libraryManager.GetItemList(new InternalItemsQuery(user)
|
||||
{
|
||||
@@ -97,7 +91,7 @@ namespace Emby.Server.Implementations.Library
|
||||
});
|
||||
}
|
||||
|
||||
public List<BaseItem> GetInstantMixFromItem(BaseItem item, User? user, DtoOptions dtoOptions)
|
||||
public IReadOnlyList<BaseItem> GetInstantMixFromItem(BaseItem item, User? user, DtoOptions dtoOptions)
|
||||
{
|
||||
if (item is MusicGenre)
|
||||
{
|
||||
|
||||
@@ -171,7 +171,7 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
};
|
||||
|
||||
List<BaseItem> mediaItems;
|
||||
IReadOnlyList<BaseItem> mediaItems;
|
||||
|
||||
if (searchQuery.IncludeItemTypes.Length == 1 && searchQuery.IncludeItemTypes[0] == BaseItemKind.MusicArtist)
|
||||
{
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
#pragma warning disable RS0030 // Do not use banned APIs
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using Jellyfin.Data.Entities;
|
||||
using Jellyfin.Extensions;
|
||||
using Jellyfin.Server.Implementations;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Dto;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Persistence;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using AudioBook = MediaBrowser.Controller.Entities.AudioBook;
|
||||
using Book = MediaBrowser.Controller.Entities.Book;
|
||||
|
||||
@@ -26,22 +30,18 @@ namespace Emby.Server.Implementations.Library
|
||||
new ConcurrentDictionary<string, UserItemData>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private readonly IServerConfigurationManager _config;
|
||||
private readonly IUserManager _userManager;
|
||||
private readonly IUserDataRepository _repository;
|
||||
private readonly IDbContextFactory<JellyfinDbContext> _repository;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UserDataManager"/> class.
|
||||
/// </summary>
|
||||
/// <param name="config">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
|
||||
/// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
|
||||
/// <param name="repository">Instance of the <see cref="IUserDataRepository"/> interface.</param>
|
||||
/// <param name="repository">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</param>
|
||||
public UserDataManager(
|
||||
IServerConfigurationManager config,
|
||||
IUserManager userManager,
|
||||
IUserDataRepository repository)
|
||||
IDbContextFactory<JellyfinDbContext> repository)
|
||||
{
|
||||
_config = config;
|
||||
_userManager = userManager;
|
||||
_repository = repository;
|
||||
}
|
||||
|
||||
@@ -59,13 +59,27 @@ namespace Emby.Server.Implementations.Library
|
||||
|
||||
var keys = item.GetUserDataKeys();
|
||||
|
||||
var userId = user.InternalId;
|
||||
using var dbContext = _repository.CreateDbContext();
|
||||
using var transaction = dbContext.Database.BeginTransaction();
|
||||
|
||||
foreach (var key in keys)
|
||||
{
|
||||
_repository.SaveUserData(userId, key, userData, cancellationToken);
|
||||
userData.Key = key;
|
||||
var userDataEntry = Map(userData, user.Id, item.Id);
|
||||
if (dbContext.UserData.Any(f => f.ItemId == userDataEntry.ItemId && f.UserId == userDataEntry.UserId && f.CustomDataKey == userDataEntry.CustomDataKey))
|
||||
{
|
||||
dbContext.UserData.Attach(userDataEntry).State = EntityState.Modified;
|
||||
}
|
||||
else
|
||||
{
|
||||
dbContext.UserData.Add(userDataEntry);
|
||||
}
|
||||
}
|
||||
|
||||
dbContext.SaveChanges();
|
||||
transaction.Commit();
|
||||
|
||||
var userId = user.InternalId;
|
||||
var cacheKey = GetCacheKey(userId, item.Id);
|
||||
_userData.AddOrUpdate(cacheKey, userData, (_, _) => userData);
|
||||
|
||||
@@ -86,7 +100,7 @@ namespace Emby.Server.Implementations.Library
|
||||
ArgumentNullException.ThrowIfNull(item);
|
||||
ArgumentNullException.ThrowIfNull(userDataDto);
|
||||
|
||||
var userData = GetUserData(user, item);
|
||||
var userData = GetUserData(user, item) ?? throw new InvalidOperationException("UserData should not be null.");
|
||||
|
||||
if (userDataDto.PlaybackPositionTicks.HasValue)
|
||||
{
|
||||
@@ -126,33 +140,91 @@ namespace Emby.Server.Implementations.Library
|
||||
SaveUserData(user, item, userData, reason, CancellationToken.None);
|
||||
}
|
||||
|
||||
private UserItemData GetUserData(User user, Guid itemId, List<string> keys)
|
||||
private UserData Map(UserItemData dto, Guid userId, Guid itemId)
|
||||
{
|
||||
var userId = user.InternalId;
|
||||
|
||||
var cacheKey = GetCacheKey(userId, itemId);
|
||||
|
||||
return _userData.GetOrAdd(cacheKey, _ => GetUserDataInternal(userId, keys));
|
||||
return new UserData()
|
||||
{
|
||||
ItemId = itemId,
|
||||
CustomDataKey = dto.Key,
|
||||
Item = null,
|
||||
User = null,
|
||||
AudioStreamIndex = dto.AudioStreamIndex,
|
||||
IsFavorite = dto.IsFavorite,
|
||||
LastPlayedDate = dto.LastPlayedDate,
|
||||
Likes = dto.Likes,
|
||||
PlaybackPositionTicks = dto.PlaybackPositionTicks,
|
||||
PlayCount = dto.PlayCount,
|
||||
Played = dto.Played,
|
||||
Rating = dto.Rating,
|
||||
UserId = userId,
|
||||
SubtitleStreamIndex = dto.SubtitleStreamIndex,
|
||||
};
|
||||
}
|
||||
|
||||
private UserItemData GetUserDataInternal(long internalUserId, List<string> keys)
|
||||
private UserItemData Map(UserData dto)
|
||||
{
|
||||
var userData = _repository.GetUserData(internalUserId, keys);
|
||||
|
||||
if (userData is not null)
|
||||
return new UserItemData()
|
||||
{
|
||||
return userData;
|
||||
Key = dto.CustomDataKey!,
|
||||
AudioStreamIndex = dto.AudioStreamIndex,
|
||||
IsFavorite = dto.IsFavorite,
|
||||
LastPlayedDate = dto.LastPlayedDate,
|
||||
Likes = dto.Likes,
|
||||
PlaybackPositionTicks = dto.PlaybackPositionTicks,
|
||||
PlayCount = dto.PlayCount,
|
||||
Played = dto.Played,
|
||||
Rating = dto.Rating,
|
||||
SubtitleStreamIndex = dto.SubtitleStreamIndex,
|
||||
};
|
||||
}
|
||||
|
||||
private UserItemData? GetUserData(User user, Guid itemId, List<string> keys)
|
||||
{
|
||||
var cacheKey = GetCacheKey(user.InternalId, itemId);
|
||||
|
||||
if (_userData.TryGetValue(cacheKey, out var data))
|
||||
{
|
||||
return data;
|
||||
}
|
||||
|
||||
if (keys.Count > 0)
|
||||
data = GetUserDataInternal(user.Id, itemId, keys);
|
||||
|
||||
if (data is null)
|
||||
{
|
||||
return new UserItemData
|
||||
return new UserItemData()
|
||||
{
|
||||
Key = keys[0]
|
||||
Key = keys[0],
|
||||
};
|
||||
}
|
||||
|
||||
throw new UnreachableException();
|
||||
return _userData.GetOrAdd(cacheKey, data);
|
||||
}
|
||||
|
||||
private UserItemData? GetUserDataInternal(Guid userId, Guid itemId, List<string> keys)
|
||||
{
|
||||
if (keys.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var context = _repository.CreateDbContext();
|
||||
var userData = context.UserData.AsNoTracking().Where(e => e.ItemId == itemId && keys.Contains(e.CustomDataKey) && e.UserId.Equals(userId)).ToArray();
|
||||
|
||||
if (userData.Length > 0)
|
||||
{
|
||||
var directDataReference = userData.FirstOrDefault(e => e.CustomDataKey == itemId.ToString("N"));
|
||||
if (directDataReference is not null)
|
||||
{
|
||||
return Map(directDataReference);
|
||||
}
|
||||
|
||||
return Map(userData.First());
|
||||
}
|
||||
|
||||
return new UserItemData
|
||||
{
|
||||
Key = keys.Last()!
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -165,20 +237,25 @@ namespace Emby.Server.Implementations.Library
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public UserItemData GetUserData(User user, BaseItem item)
|
||||
public UserItemData? GetUserData(User user, BaseItem item)
|
||||
{
|
||||
return GetUserData(user, item.Id, item.GetUserDataKeys());
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public UserItemDataDto GetUserDataDto(BaseItem item, User user)
|
||||
public UserItemDataDto? GetUserDataDto(BaseItem item, User user)
|
||||
=> GetUserDataDto(item, null, user, new DtoOptions());
|
||||
|
||||
/// <inheritdoc />
|
||||
public UserItemDataDto GetUserDataDto(BaseItem item, BaseItemDto? itemDto, User user, DtoOptions options)
|
||||
public UserItemDataDto? GetUserDataDto(BaseItem item, BaseItemDto? itemDto, User user, DtoOptions options)
|
||||
{
|
||||
var userData = GetUserData(user, item);
|
||||
var dto = GetUserItemDataDto(userData);
|
||||
if (userData is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var dto = GetUserItemDataDto(userData, item.Id);
|
||||
|
||||
item.FillUserDataDtoValues(dto, userData, itemDto, user, options);
|
||||
return dto;
|
||||
@@ -188,9 +265,10 @@ namespace Emby.Server.Implementations.Library
|
||||
/// Converts a UserItemData to a DTOUserItemData.
|
||||
/// </summary>
|
||||
/// <param name="data">The data.</param>
|
||||
/// <param name="itemId">The reference key to an Item.</param>
|
||||
/// <returns>DtoUserItemData.</returns>
|
||||
/// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception>
|
||||
private UserItemDataDto GetUserItemDataDto(UserItemData data)
|
||||
private UserItemDataDto GetUserItemDataDto(UserItemData data, Guid itemId)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(data);
|
||||
|
||||
@@ -203,6 +281,7 @@ namespace Emby.Server.Implementations.Library
|
||||
Rating = data.Rating,
|
||||
Played = data.Played,
|
||||
LastPlayedDate = data.LastPlayedDate,
|
||||
ItemId = itemId,
|
||||
Key = data.Key
|
||||
};
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ namespace Emby.Server.Implementations.MediaEncoder
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly ILogger<EncodingManager> _logger;
|
||||
private readonly IMediaEncoder _encoder;
|
||||
private readonly IChapterManager _chapterManager;
|
||||
private readonly IChapterRepository _chapterManager;
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
|
||||
/// <summary>
|
||||
@@ -40,7 +40,7 @@ namespace Emby.Server.Implementations.MediaEncoder
|
||||
ILogger<EncodingManager> logger,
|
||||
IFileSystem fileSystem,
|
||||
IMediaEncoder encoder,
|
||||
IChapterManager chapterManager,
|
||||
IChapterRepository chapterManager,
|
||||
ILibraryManager libraryManager)
|
||||
{
|
||||
_logger = logger;
|
||||
|
||||
@@ -5,12 +5,14 @@ using System.Linq;
|
||||
using System.Text.Json.Serialization;
|
||||
using Jellyfin.Data.Entities;
|
||||
using Jellyfin.Data.Enums;
|
||||
using MediaBrowser.Common;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Playlists;
|
||||
using MediaBrowser.Model.Querying;
|
||||
|
||||
namespace Emby.Server.Implementations.Playlists
|
||||
{
|
||||
[RequiresSourceSerialisation]
|
||||
public class PlaylistsFolder : BasePluginFolder
|
||||
{
|
||||
public PlaylistsFolder()
|
||||
|
||||
@@ -7,6 +7,7 @@ using System.Threading.Tasks;
|
||||
using Jellyfin.Data.Enums;
|
||||
using Jellyfin.Extensions;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Controller.Chapters;
|
||||
using MediaBrowser.Controller.Dto;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Library;
|
||||
@@ -32,6 +33,7 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
|
||||
private readonly IEncodingManager _encodingManager;
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly ILocalizationManager _localization;
|
||||
private readonly IChapterRepository _chapterRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ChapterImagesTask" /> class.
|
||||
@@ -43,6 +45,7 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
|
||||
/// <param name="encodingManager">Instance of the <see cref="IEncodingManager"/> interface.</param>
|
||||
/// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
|
||||
/// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
|
||||
/// <param name="chapterRepository">Instance of the <see cref="IChapterRepository"/> interface.</param>
|
||||
public ChapterImagesTask(
|
||||
ILogger<ChapterImagesTask> logger,
|
||||
ILibraryManager libraryManager,
|
||||
@@ -50,7 +53,8 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
|
||||
IApplicationPaths appPaths,
|
||||
IEncodingManager encodingManager,
|
||||
IFileSystem fileSystem,
|
||||
ILocalizationManager localization)
|
||||
ILocalizationManager localization,
|
||||
IChapterRepository chapterRepository)
|
||||
{
|
||||
_logger = logger;
|
||||
_libraryManager = libraryManager;
|
||||
@@ -59,6 +63,7 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
|
||||
_encodingManager = encodingManager;
|
||||
_fileSystem = fileSystem;
|
||||
_localization = localization;
|
||||
_chapterRepository = chapterRepository;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -141,7 +146,7 @@ namespace Emby.Server.Implementations.ScheduledTasks.Tasks
|
||||
|
||||
try
|
||||
{
|
||||
var chapters = _itemRepo.GetChapters(video);
|
||||
var chapters = _chapterRepository.GetChapters(video.Id);
|
||||
|
||||
var success = await _encodingManager.RefreshChapterImages(video, directoryService, chapters, extract, true, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ namespace Emby.Server.Implementations.TV
|
||||
.ToList();
|
||||
|
||||
// Avoid implicitly captured closure
|
||||
var episodes = GetNextUpEpisodes(request, user, items, options);
|
||||
var episodes = GetNextUpEpisodes(request, user, items.Distinct().ToArray(), options);
|
||||
|
||||
return GetResult(episodes, request);
|
||||
}
|
||||
@@ -262,7 +262,7 @@ namespace Emby.Server.Implementations.TV
|
||||
{
|
||||
var userData = _userDataManager.GetUserData(user, nextEpisode);
|
||||
|
||||
if (userData.PlaybackPositionTicks > 0)
|
||||
if (userData?.PlaybackPositionTicks > 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
@@ -275,6 +275,11 @@ namespace Emby.Server.Implementations.TV
|
||||
{
|
||||
var userData = _userDataManager.GetUserData(user, lastWatchedEpisode);
|
||||
|
||||
if (userData is null)
|
||||
{
|
||||
return (DateTime.MinValue, GetEpisode);
|
||||
}
|
||||
|
||||
var lastWatchedDate = userData.LastPlayedDate ?? DateTime.MinValue.AddDays(1);
|
||||
|
||||
return (lastWatchedDate, GetEpisode);
|
||||
|
||||
Reference in New Issue
Block a user