| | | 1 | | #pragma warning disable RS0030 // Do not use banned APIs |
| | | 2 | | |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Globalization; |
| | | 6 | | using System.Linq; |
| | | 7 | | using System.Threading; |
| | | 8 | | using BitFaster.Caching.Lru; |
| | | 9 | | using Jellyfin.Database.Implementations; |
| | | 10 | | using Jellyfin.Database.Implementations.Entities; |
| | | 11 | | using MediaBrowser.Controller.Configuration; |
| | | 12 | | using MediaBrowser.Controller.Dto; |
| | | 13 | | using MediaBrowser.Controller.Entities; |
| | | 14 | | using MediaBrowser.Controller.Library; |
| | | 15 | | using MediaBrowser.Model.Dto; |
| | | 16 | | using MediaBrowser.Model.Entities; |
| | | 17 | | using Microsoft.EntityFrameworkCore; |
| | | 18 | | using AudioBook = MediaBrowser.Controller.Entities.AudioBook; |
| | | 19 | | using Book = MediaBrowser.Controller.Entities.Book; |
| | | 20 | | |
| | | 21 | | namespace Emby.Server.Implementations.Library |
| | | 22 | | { |
| | | 23 | | /// <summary> |
| | | 24 | | /// Class UserDataManager. |
| | | 25 | | /// </summary> |
| | | 26 | | public class UserDataManager : IUserDataManager |
| | | 27 | | { |
| | | 28 | | private readonly IServerConfigurationManager _config; |
| | | 29 | | private readonly IDbContextFactory<JellyfinDbContext> _repository; |
| | | 30 | | private readonly FastConcurrentLru<string, UserItemData> _cache; |
| | | 31 | | |
| | | 32 | | /// <summary> |
| | | 33 | | /// Initializes a new instance of the <see cref="UserDataManager"/> class. |
| | | 34 | | /// </summary> |
| | | 35 | | /// <param name="config">Instance of the <see cref="IServerConfigurationManager"/> interface.</param> |
| | | 36 | | /// <param name="repository">Instance of the <see cref="IDbContextFactory{JellyfinDbContext}"/> interface.</para |
| | | 37 | | public UserDataManager( |
| | | 38 | | IServerConfigurationManager config, |
| | | 39 | | IDbContextFactory<JellyfinDbContext> repository) |
| | | 40 | | { |
| | 21 | 41 | | _config = config; |
| | 21 | 42 | | _repository = repository; |
| | 21 | 43 | | _cache = new FastConcurrentLru<string, UserItemData>(Environment.ProcessorCount, _config.Configuration.Cache |
| | 21 | 44 | | } |
| | | 45 | | |
| | | 46 | | /// <inheritdoc /> |
| | | 47 | | public event EventHandler<UserDataSaveEventArgs>? UserDataSaved; |
| | | 48 | | |
| | | 49 | | /// <inheritdoc /> |
| | | 50 | | public void SaveUserData(User user, BaseItem item, UserItemData userData, UserDataSaveReason reason, Cancellatio |
| | | 51 | | { |
| | 0 | 52 | | ArgumentNullException.ThrowIfNull(userData); |
| | | 53 | | |
| | 0 | 54 | | ArgumentNullException.ThrowIfNull(item); |
| | | 55 | | |
| | 0 | 56 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 57 | | |
| | 0 | 58 | | var keys = item.GetUserDataKeys(); |
| | | 59 | | |
| | 0 | 60 | | using var dbContext = _repository.CreateDbContext(); |
| | 0 | 61 | | using var transaction = dbContext.Database.BeginTransaction(); |
| | | 62 | | |
| | 0 | 63 | | foreach (var key in keys) |
| | | 64 | | { |
| | 0 | 65 | | userData.Key = key; |
| | 0 | 66 | | var userDataEntry = Map(userData, user.Id, item.Id); |
| | 0 | 67 | | if (dbContext.UserData.Any(f => f.ItemId == userDataEntry.ItemId && f.UserId == userDataEntry.UserId && |
| | | 68 | | { |
| | 0 | 69 | | dbContext.UserData.Attach(userDataEntry).State = EntityState.Modified; |
| | | 70 | | } |
| | | 71 | | else |
| | | 72 | | { |
| | 0 | 73 | | dbContext.UserData.Add(userDataEntry); |
| | | 74 | | } |
| | | 75 | | } |
| | | 76 | | |
| | 0 | 77 | | dbContext.SaveChanges(); |
| | 0 | 78 | | transaction.Commit(); |
| | | 79 | | |
| | 0 | 80 | | var userId = user.InternalId; |
| | 0 | 81 | | var cacheKey = GetCacheKey(userId, item.Id); |
| | 0 | 82 | | _cache.AddOrUpdate(cacheKey, userData); |
| | 0 | 83 | | item.UserData = dbContext.UserData.Where(e => e.ItemId == item.Id).AsNoTracking().ToArray(); // rehydrate th |
| | | 84 | | |
| | 0 | 85 | | UserDataSaved?.Invoke(this, new UserDataSaveEventArgs |
| | 0 | 86 | | { |
| | 0 | 87 | | Keys = keys, |
| | 0 | 88 | | UserData = userData, |
| | 0 | 89 | | SaveReason = reason, |
| | 0 | 90 | | UserId = user.Id, |
| | 0 | 91 | | Item = item |
| | 0 | 92 | | }); |
| | 0 | 93 | | } |
| | | 94 | | |
| | | 95 | | /// <inheritdoc /> |
| | | 96 | | public void SaveUserData(User user, BaseItem item, UpdateUserItemDataDto userDataDto, UserDataSaveReason reason) |
| | | 97 | | { |
| | 0 | 98 | | ArgumentNullException.ThrowIfNull(user); |
| | 0 | 99 | | ArgumentNullException.ThrowIfNull(item); |
| | 0 | 100 | | ArgumentNullException.ThrowIfNull(userDataDto); |
| | | 101 | | |
| | 0 | 102 | | var userData = GetUserData(user, item) ?? throw new InvalidOperationException("UserData should not be null." |
| | | 103 | | |
| | 0 | 104 | | if (userDataDto.PlaybackPositionTicks.HasValue) |
| | | 105 | | { |
| | 0 | 106 | | userData.PlaybackPositionTicks = userDataDto.PlaybackPositionTicks.Value; |
| | | 107 | | } |
| | | 108 | | |
| | 0 | 109 | | if (userDataDto.PlayCount.HasValue) |
| | | 110 | | { |
| | 0 | 111 | | userData.PlayCount = userDataDto.PlayCount.Value; |
| | | 112 | | } |
| | | 113 | | |
| | 0 | 114 | | if (userDataDto.IsFavorite.HasValue) |
| | | 115 | | { |
| | 0 | 116 | | userData.IsFavorite = userDataDto.IsFavorite.Value; |
| | | 117 | | } |
| | | 118 | | |
| | 0 | 119 | | if (userDataDto.Likes.HasValue) |
| | | 120 | | { |
| | 0 | 121 | | userData.Likes = userDataDto.Likes.Value; |
| | | 122 | | } |
| | | 123 | | |
| | 0 | 124 | | if (userDataDto.Played.HasValue) |
| | | 125 | | { |
| | 0 | 126 | | userData.Played = userDataDto.Played.Value; |
| | | 127 | | } |
| | | 128 | | |
| | 0 | 129 | | if (userDataDto.LastPlayedDate.HasValue) |
| | | 130 | | { |
| | 0 | 131 | | userData.LastPlayedDate = userDataDto.LastPlayedDate.Value; |
| | | 132 | | } |
| | | 133 | | |
| | 0 | 134 | | if (userDataDto.Rating.HasValue) |
| | | 135 | | { |
| | 0 | 136 | | userData.Rating = userDataDto.Rating.Value; |
| | | 137 | | } |
| | | 138 | | |
| | 0 | 139 | | SaveUserData(user, item, userData, reason, CancellationToken.None); |
| | 0 | 140 | | } |
| | | 141 | | |
| | | 142 | | private UserData Map(UserItemData dto, Guid userId, Guid itemId) |
| | | 143 | | { |
| | 0 | 144 | | return new UserData() |
| | 0 | 145 | | { |
| | 0 | 146 | | ItemId = itemId, |
| | 0 | 147 | | CustomDataKey = dto.Key, |
| | 0 | 148 | | Item = null, |
| | 0 | 149 | | User = null, |
| | 0 | 150 | | AudioStreamIndex = dto.AudioStreamIndex, |
| | 0 | 151 | | IsFavorite = dto.IsFavorite, |
| | 0 | 152 | | LastPlayedDate = dto.LastPlayedDate, |
| | 0 | 153 | | Likes = dto.Likes, |
| | 0 | 154 | | PlaybackPositionTicks = dto.PlaybackPositionTicks, |
| | 0 | 155 | | PlayCount = dto.PlayCount, |
| | 0 | 156 | | Played = dto.Played, |
| | 0 | 157 | | Rating = dto.Rating, |
| | 0 | 158 | | UserId = userId, |
| | 0 | 159 | | SubtitleStreamIndex = dto.SubtitleStreamIndex, |
| | 0 | 160 | | }; |
| | | 161 | | } |
| | | 162 | | |
| | | 163 | | private static UserItemData Map(UserData dto) |
| | | 164 | | { |
| | 0 | 165 | | return new UserItemData() |
| | 0 | 166 | | { |
| | 0 | 167 | | Key = dto.CustomDataKey!, |
| | 0 | 168 | | AudioStreamIndex = dto.AudioStreamIndex, |
| | 0 | 169 | | IsFavorite = dto.IsFavorite, |
| | 0 | 170 | | LastPlayedDate = dto.LastPlayedDate, |
| | 0 | 171 | | Likes = dto.Likes, |
| | 0 | 172 | | PlaybackPositionTicks = dto.PlaybackPositionTicks, |
| | 0 | 173 | | PlayCount = dto.PlayCount, |
| | 0 | 174 | | Played = dto.Played, |
| | 0 | 175 | | Rating = dto.Rating, |
| | 0 | 176 | | SubtitleStreamIndex = dto.SubtitleStreamIndex, |
| | 0 | 177 | | }; |
| | | 178 | | } |
| | | 179 | | |
| | | 180 | | /// <inheritdoc /> |
| | | 181 | | public Dictionary<Guid, UserItemData> GetUserDataBatch(IReadOnlyList<BaseItem> items, User user) |
| | | 182 | | { |
| | 4 | 183 | | var result = new Dictionary<Guid, UserItemData>(items.Count); |
| | 4 | 184 | | var itemsNeedingQuery = new List<(BaseItem Item, List<string> Keys)>(); |
| | | 185 | | |
| | 14 | 186 | | foreach (var item in items) |
| | | 187 | | { |
| | 3 | 188 | | var cacheKey = GetCacheKey(user.InternalId, item.Id); |
| | 3 | 189 | | if (_cache.TryGet(cacheKey, out var cachedData)) |
| | | 190 | | { |
| | 2 | 191 | | result[item.Id] = cachedData; |
| | | 192 | | } |
| | | 193 | | else |
| | | 194 | | { |
| | 1 | 195 | | var userData = item.UserData?.Where(e => e.UserId.Equals(user.Id)).Select(Map).FirstOrDefault(); |
| | 1 | 196 | | if (userData is not null) |
| | | 197 | | { |
| | 0 | 198 | | result[item.Id] = userData; |
| | 0 | 199 | | _cache.AddOrUpdate(cacheKey, userData); |
| | | 200 | | } |
| | | 201 | | else |
| | | 202 | | { |
| | 1 | 203 | | var keys = item.GetUserDataKeys(); |
| | 1 | 204 | | itemsNeedingQuery.Add((item, keys)); |
| | | 205 | | } |
| | | 206 | | } |
| | | 207 | | } |
| | | 208 | | |
| | 4 | 209 | | if (itemsNeedingQuery.Count == 0) |
| | | 210 | | { |
| | 3 | 211 | | return result; |
| | | 212 | | } |
| | | 213 | | |
| | | 214 | | // Build a single query for all missing items |
| | 1 | 215 | | var allItemIds = itemsNeedingQuery.Select(x => x.Item.Id).ToList(); |
| | 1 | 216 | | var allKeys = itemsNeedingQuery.SelectMany(x => x.Keys).Distinct().ToList(); |
| | 1 | 217 | | if (allKeys.Count > 0) |
| | | 218 | | { |
| | 1 | 219 | | using var context = _repository.CreateDbContext(); |
| | 1 | 220 | | var userDataArray = context.UserData |
| | 1 | 221 | | .AsNoTracking() |
| | 1 | 222 | | .Where(e => e.UserId.Equals(user.Id)) |
| | 1 | 223 | | .WhereOneOrMany(allItemIds, e => e.ItemId) |
| | 1 | 224 | | .WhereOneOrMany(allKeys, e => e.CustomDataKey) |
| | 1 | 225 | | .ToArray(); |
| | | 226 | | |
| | 1 | 227 | | var userDataByItem = userDataArray.GroupBy(e => e.ItemId).ToDictionary(g => g.Key, g => g.ToArray()); |
| | 4 | 228 | | foreach (var (item, keys) in itemsNeedingQuery) |
| | | 229 | | { |
| | | 230 | | UserItemData userData; |
| | 1 | 231 | | if (userDataByItem.TryGetValue(item.Id, out var itemUserData) && itemUserData.Length > 0) |
| | | 232 | | { |
| | 0 | 233 | | var directDataReference = itemUserData.FirstOrDefault(e => e.CustomDataKey == item.Id.ToString(" |
| | 0 | 234 | | userData = directDataReference is not null ? Map(directDataReference) : Map(itemUserData.First() |
| | | 235 | | } |
| | | 236 | | else |
| | | 237 | | { |
| | 1 | 238 | | userData = new UserItemData { Key = keys.Count > 0 ? keys[0] : string.Empty }; |
| | | 239 | | } |
| | | 240 | | |
| | 1 | 241 | | result[item.Id] = userData; |
| | 1 | 242 | | var cacheKey = GetCacheKey(user.InternalId, item.Id); |
| | 1 | 243 | | _cache.AddOrUpdate(cacheKey, userData); |
| | | 244 | | } |
| | | 245 | | } |
| | | 246 | | |
| | 1 | 247 | | return result; |
| | | 248 | | } |
| | | 249 | | |
| | | 250 | | /// <summary> |
| | | 251 | | /// Gets the internal key. |
| | | 252 | | /// </summary> |
| | | 253 | | /// <returns>System.String.</returns> |
| | | 254 | | private static string GetCacheKey(long internalUserId, Guid itemId) |
| | | 255 | | { |
| | 4 | 256 | | return internalUserId.ToString(CultureInfo.InvariantCulture) + "-" + itemId.ToString("N", CultureInfo.Invari |
| | | 257 | | } |
| | | 258 | | |
| | | 259 | | /// <inheritdoc /> |
| | | 260 | | public UserItemData? GetUserData(User user, BaseItem item) |
| | | 261 | | { |
| | 6 | 262 | | return item.UserData?.Where(e => e.UserId.Equals(user.Id)).Select(Map).FirstOrDefault() ?? new UserItemData( |
| | 6 | 263 | | { |
| | 6 | 264 | | Key = item.GetUserDataKeys()[0], |
| | 6 | 265 | | }; |
| | | 266 | | } |
| | | 267 | | |
| | | 268 | | /// <inheritdoc /> |
| | | 269 | | public UserItemDataDto? GetUserDataDto(BaseItem item, User user) |
| | 0 | 270 | | => GetUserDataDto(item, null, user, new DtoOptions()); |
| | | 271 | | |
| | | 272 | | /// <inheritdoc /> |
| | | 273 | | public UserItemDataDto? GetUserDataDto(BaseItem item, BaseItemDto? itemDto, User user, DtoOptions options) |
| | | 274 | | { |
| | 6 | 275 | | var userData = GetUserData(user, item); |
| | 6 | 276 | | if (userData is null) |
| | | 277 | | { |
| | 0 | 278 | | return null; |
| | | 279 | | } |
| | | 280 | | |
| | 6 | 281 | | var dto = GetUserItemDataDto(userData, item.Id); |
| | | 282 | | |
| | 6 | 283 | | item.FillUserDataDtoValues(dto, userData, itemDto, user, options); |
| | 6 | 284 | | return dto; |
| | | 285 | | } |
| | | 286 | | |
| | | 287 | | /// <summary> |
| | | 288 | | /// Converts a UserItemData to a DTOUserItemData. |
| | | 289 | | /// </summary> |
| | | 290 | | /// <param name="data">The data.</param> |
| | | 291 | | /// <param name="itemId">The reference key to an Item.</param> |
| | | 292 | | /// <returns>DtoUserItemData.</returns> |
| | | 293 | | /// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception> |
| | | 294 | | private UserItemDataDto GetUserItemDataDto(UserItemData data, Guid itemId) |
| | | 295 | | { |
| | 6 | 296 | | ArgumentNullException.ThrowIfNull(data); |
| | | 297 | | |
| | 6 | 298 | | return new UserItemDataDto |
| | 6 | 299 | | { |
| | 6 | 300 | | IsFavorite = data.IsFavorite, |
| | 6 | 301 | | Likes = data.Likes, |
| | 6 | 302 | | PlaybackPositionTicks = data.PlaybackPositionTicks, |
| | 6 | 303 | | PlayCount = data.PlayCount, |
| | 6 | 304 | | Rating = data.Rating, |
| | 6 | 305 | | Played = data.Played, |
| | 6 | 306 | | LastPlayedDate = data.LastPlayedDate, |
| | 6 | 307 | | ItemId = itemId, |
| | 6 | 308 | | Key = data.Key |
| | 6 | 309 | | }; |
| | | 310 | | } |
| | | 311 | | |
| | | 312 | | /// <inheritdoc /> |
| | | 313 | | public bool UpdatePlayState(BaseItem item, UserItemData data, long? reportedPositionTicks) |
| | | 314 | | { |
| | 0 | 315 | | var playedToCompletion = false; |
| | | 316 | | |
| | 0 | 317 | | var runtimeTicks = item.GetRunTimeTicksForPlayState(); |
| | | 318 | | |
| | 0 | 319 | | var positionTicks = reportedPositionTicks ?? runtimeTicks; |
| | 0 | 320 | | var hasRuntime = runtimeTicks > 0; |
| | | 321 | | |
| | | 322 | | // If a position has been reported, and if we know the duration |
| | 0 | 323 | | if (positionTicks > 0 && hasRuntime && item is not AudioBook && item is not Book) |
| | | 324 | | { |
| | 0 | 325 | | var pctIn = decimal.Divide(positionTicks, runtimeTicks) * 100; |
| | | 326 | | |
| | 0 | 327 | | if (pctIn < _config.Configuration.MinResumePct) |
| | | 328 | | { |
| | | 329 | | // ignore progress during the beginning |
| | 0 | 330 | | positionTicks = 0; |
| | | 331 | | } |
| | 0 | 332 | | else if (pctIn > _config.Configuration.MaxResumePct || positionTicks >= (runtimeTicks - TimeSpan.TicksPe |
| | | 333 | | { |
| | | 334 | | // mark as completed close to the end |
| | 0 | 335 | | positionTicks = 0; |
| | 0 | 336 | | data.Played = playedToCompletion = true; |
| | | 337 | | } |
| | | 338 | | else |
| | | 339 | | { |
| | | 340 | | // Enforce MinResumeDuration |
| | 0 | 341 | | var durationSeconds = TimeSpan.FromTicks(runtimeTicks).TotalSeconds; |
| | 0 | 342 | | if (durationSeconds < _config.Configuration.MinResumeDurationSeconds) |
| | | 343 | | { |
| | 0 | 344 | | positionTicks = 0; |
| | 0 | 345 | | data.Played = playedToCompletion = true; |
| | | 346 | | } |
| | | 347 | | } |
| | | 348 | | } |
| | 0 | 349 | | else if (positionTicks > 0 && hasRuntime && item is AudioBook) |
| | | 350 | | { |
| | 0 | 351 | | var playbackPositionInMinutes = TimeSpan.FromTicks(positionTicks).TotalMinutes; |
| | 0 | 352 | | var remainingTimeInMinutes = TimeSpan.FromTicks(runtimeTicks - positionTicks).TotalMinutes; |
| | | 353 | | |
| | 0 | 354 | | if (playbackPositionInMinutes < _config.Configuration.MinAudiobookResume) |
| | | 355 | | { |
| | | 356 | | // ignore progress during the beginning |
| | 0 | 357 | | positionTicks = 0; |
| | | 358 | | } |
| | 0 | 359 | | else if (remainingTimeInMinutes < _config.Configuration.MaxAudiobookResume || positionTicks >= runtimeTi |
| | | 360 | | { |
| | | 361 | | // mark as completed close to the end |
| | 0 | 362 | | positionTicks = 0; |
| | 0 | 363 | | data.Played = playedToCompletion = true; |
| | | 364 | | } |
| | | 365 | | } |
| | 0 | 366 | | else if (!hasRuntime) |
| | | 367 | | { |
| | | 368 | | // If we don't know the runtime we'll just have to assume it was fully played |
| | 0 | 369 | | data.Played = playedToCompletion = true; |
| | 0 | 370 | | positionTicks = 0; |
| | | 371 | | } |
| | | 372 | | |
| | 0 | 373 | | if (!item.SupportsPlayedStatus) |
| | | 374 | | { |
| | 0 | 375 | | positionTicks = 0; |
| | 0 | 376 | | data.Played = false; |
| | | 377 | | } |
| | | 378 | | |
| | 0 | 379 | | if (!item.SupportsPositionTicksResume) |
| | | 380 | | { |
| | 0 | 381 | | positionTicks = 0; |
| | | 382 | | } |
| | | 383 | | |
| | 0 | 384 | | data.PlaybackPositionTicks = positionTicks; |
| | | 385 | | |
| | 0 | 386 | | return playedToCompletion; |
| | | 387 | | } |
| | | 388 | | } |
| | | 389 | | } |