Files
jellyfin-jellyfin-1/MediaBrowser.Server.Implementations/Persistence/JsonUserDataRepository.cs

246 lines
7.9 KiB
C#
Raw Normal View History

2013-06-17 16:35:43 -04:00
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
2013-02-20 23:37:50 -05:00
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Persistence;
2013-02-21 15:26:35 -05:00
using MediaBrowser.Model.Logging;
2013-02-24 16:53:54 -05:00
using MediaBrowser.Model.Serialization;
2013-02-20 20:33:05 -05:00
using System;
using System.Collections.Concurrent;
2013-02-20 20:33:05 -05:00
using System.IO;
2013-06-17 16:35:43 -04:00
using System.Linq;
2013-02-20 20:33:05 -05:00
using System.Threading;
using System.Threading.Tasks;
2013-06-17 16:35:43 -04:00
namespace MediaBrowser.Server.Implementations.Persistence
2013-02-20 20:33:05 -05:00
{
2013-06-17 16:35:43 -04:00
public class JsonUserDataRepository : IUserDataRepository
2013-02-20 20:33:05 -05:00
{
2013-06-17 16:35:43 -04:00
private readonly ConcurrentDictionary<string, SemaphoreSlim> _fileLocks = new ConcurrentDictionary<string, SemaphoreSlim>();
2013-05-09 16:29:50 -04:00
2013-06-17 16:35:43 -04:00
private SemaphoreSlim GetLock(string filename)
{
return _fileLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
}
private readonly ConcurrentDictionary<string, UserItemData> _userData = new ConcurrentDictionary<string, UserItemData>();
2013-02-20 20:33:05 -05:00
/// <summary>
/// Gets the name of the repository
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
2013-06-17 16:35:43 -04:00
return "Json";
2013-02-20 20:33:05 -05:00
}
}
2013-04-07 18:09:48 -04:00
private readonly IJsonSerializer _jsonSerializer;
2013-02-24 16:53:54 -05:00
2013-06-17 16:35:43 -04:00
private readonly string _dataPath;
private readonly ILogger _logger;
2013-02-24 16:53:54 -05:00
2013-02-21 15:26:35 -05:00
/// <summary>
2013-06-17 16:35:43 -04:00
/// Initializes a new instance of the <see cref="JsonUserDataRepository" /> class.
2013-02-21 15:26:35 -05:00
/// </summary>
2013-02-24 16:53:54 -05:00
/// <param name="appPaths">The app paths.</param>
2013-04-07 18:09:48 -04:00
/// <param name="jsonSerializer">The json serializer.</param>
2013-04-02 22:59:27 -04:00
/// <param name="logManager">The log manager.</param>
2013-04-18 15:57:28 -04:00
/// <exception cref="System.ArgumentNullException">
/// jsonSerializer
/// or
/// appPaths
/// </exception>
2013-06-17 16:35:43 -04:00
public JsonUserDataRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
2013-02-21 15:26:35 -05:00
{
2013-04-07 18:09:48 -04:00
if (jsonSerializer == null)
2013-02-24 16:53:54 -05:00
{
2013-04-07 18:09:48 -04:00
throw new ArgumentNullException("jsonSerializer");
2013-02-24 16:53:54 -05:00
}
if (appPaths == null)
{
throw new ArgumentNullException("appPaths");
}
2013-06-17 16:35:43 -04:00
_logger = logManager.GetLogger(GetType().Name);
2013-04-07 18:09:48 -04:00
_jsonSerializer = jsonSerializer;
2013-06-17 16:35:43 -04:00
_dataPath = Path.Combine(appPaths.DataPath, "userdata");
2013-02-21 15:26:35 -05:00
}
2013-02-20 20:33:05 -05:00
/// <summary>
/// Opens the connection to the database
/// </summary>
/// <returns>Task.</returns>
2013-06-17 16:35:43 -04:00
public Task Initialize()
2013-02-20 20:33:05 -05:00
{
2013-06-17 16:35:43 -04:00
return Task.FromResult(true);
2013-02-20 20:33:05 -05:00
}
/// <summary>
/// Saves the user data.
2013-02-20 20:33:05 -05:00
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="key">The key.</param>
/// <param name="userData">The user data.</param>
2013-02-20 20:33:05 -05:00
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">userData
/// or
/// cancellationToken
/// or
/// userId
/// or
/// userDataId</exception>
public async Task SaveUserData(Guid userId, string key, UserItemData userData, CancellationToken cancellationToken)
2013-02-20 20:33:05 -05:00
{
if (userData == null)
2013-02-20 20:33:05 -05:00
{
throw new ArgumentNullException("userData");
2013-02-20 20:33:05 -05:00
}
if (cancellationToken == null)
{
throw new ArgumentNullException("cancellationToken");
}
if (userId == Guid.Empty)
{
throw new ArgumentNullException("userId");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException("key");
}
cancellationToken.ThrowIfCancellationRequested();
try
{
await PersistUserData(userId, key, userData, cancellationToken).ConfigureAwait(false);
// Once it succeeds, put it into the dictionary to make it available to everyone else
2013-06-17 16:35:43 -04:00
_userData.AddOrUpdate(GetInternalKey(userId, key), userData, delegate { return userData; });
}
catch (Exception ex)
{
2013-06-17 16:35:43 -04:00
_logger.ErrorException("Error saving user data", ex);
throw;
}
}
/// <summary>
/// Gets the internal key.
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="key">The key.</param>
/// <returns>System.String.</returns>
private string GetInternalKey(Guid userId, string key)
{
return userId + key;
}
/// <summary>
/// Persists the user data.
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="key">The key.</param>
/// <param name="userData">The user data.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
public async Task PersistUserData(Guid userId, string key, UserItemData userData, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
2013-06-17 16:35:43 -04:00
var path = GetUserDataPath(userId, key);
2013-06-17 16:35:43 -04:00
var parentPath = Path.GetDirectoryName(path);
if (!Directory.Exists(parentPath))
{
2013-06-17 16:35:43 -04:00
Directory.CreateDirectory(parentPath);
}
2013-05-28 13:32:50 -04:00
2013-06-17 16:35:43 -04:00
var semaphore = GetLock(path);
2013-06-17 16:35:43 -04:00
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
2013-05-28 13:32:50 -04:00
2013-06-17 16:35:43 -04:00
try
{
_jsonSerializer.SerializeToFile(userData, path);
}
finally
{
2013-06-17 16:35:43 -04:00
semaphore.Release();
}
2013-02-20 20:33:05 -05:00
}
/// <summary>
/// Gets the user data.
2013-02-20 20:33:05 -05:00
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="key">The key.</param>
/// <returns>Task{UserItemData}.</returns>
/// <exception cref="System.ArgumentNullException">
/// userId
/// or
/// key
/// </exception>
2013-06-17 16:35:43 -04:00
public UserItemData GetUserData(Guid userId, string key)
2013-02-20 20:33:05 -05:00
{
if (userId == Guid.Empty)
2013-02-20 20:33:05 -05:00
{
throw new ArgumentNullException("userId");
}
if (string.IsNullOrEmpty(key))
{
throw new ArgumentNullException("key");
2013-02-20 20:33:05 -05:00
}
2013-05-09 16:29:50 -04:00
return _userData.GetOrAdd(GetInternalKey(userId, key), keyName => RetrieveUserData(userId, key));
}
2013-02-20 20:33:05 -05:00
/// <summary>
/// Retrieves the user data.
/// </summary>
/// <param name="userId">The user id.</param>
/// <param name="key">The key.</param>
/// <returns>Task{UserItemData}.</returns>
2013-06-17 16:35:43 -04:00
private UserItemData RetrieveUserData(Guid userId, string key)
{
2013-06-17 16:35:43 -04:00
var path = GetUserDataPath(userId, key);
try
{
return _jsonSerializer.DeserializeFromFile<UserItemData>(path);
}
catch (IOException)
{
2013-06-17 16:35:43 -04:00
// File doesn't exist or is currently bring written to
return new UserItemData { UserId = userId };
}
2013-02-20 20:33:05 -05:00
}
2013-06-17 16:35:43 -04:00
private string GetUserDataPath(Guid userId, string key)
{
var userFolder = Path.Combine(_dataPath, userId.ToString());
var keyHash = key.GetMD5().ToString();
var prefix = keyHash.Substring(0, 1);
return Path.Combine(userFolder, prefix, keyHash + ".json");
}
public void Dispose()
{
// Wait up to two seconds for any existing writes to finish
var locks = _fileLocks.Values.ToList()
.Where(i => i.CurrentCount == 1)
.Select(i => i.WaitAsync(2000));
var task = Task.WhenAll(locks);
Task.WaitAll(task);
}
2013-02-20 20:33:05 -05:00
}
2013-05-09 16:29:50 -04:00
}