jellyfin-server/MediaBrowser.Server.Implementations/Activity/ActivityRepository.cs

279 lines
9.4 KiB
C#
Raw Normal View History

2014-08-10 22:13:17 +00:00
using MediaBrowser.Controller;
using MediaBrowser.Controller.Activity;
using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Querying;
using MediaBrowser.Server.Implementations.Persistence;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Activity
{
2016-02-10 18:13:24 +00:00
public class ActivityRepository : BaseSqliteRepository, IActivityRepository
2014-08-10 22:13:17 +00:00
{
private IDbConnection _connection;
private readonly IServerApplicationPaths _appPaths;
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private IDbCommand _saveActivityCommand;
2016-02-10 18:13:24 +00:00
public ActivityRepository(ILogManager logManager, IServerApplicationPaths appPaths)
: base(logManager)
2014-08-10 22:13:17 +00:00
{
_appPaths = appPaths;
}
public async Task Initialize()
{
var dbFile = Path.Combine(_appPaths.DataPath, "activitylog.db");
2016-02-10 18:13:24 +00:00
_connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false);
2014-08-10 22:13:17 +00:00
string[] queries = {
"create table if not exists ActivityLogEntries (Id GUID PRIMARY KEY, Name TEXT, Overview TEXT, ShortOverview TEXT, Type TEXT, ItemId TEXT, UserId TEXT, DateCreated DATETIME, LogSeverity TEXT)",
"create index if not exists idx_ActivityLogEntries on ActivityLogEntries(Id)",
//pragmas
"pragma temp_store = memory",
"pragma shrink_memory"
};
2016-02-10 18:13:24 +00:00
_connection.RunQueries(queries, Logger);
2014-08-10 22:13:17 +00:00
PrepareStatements();
}
private void PrepareStatements()
{
_saveActivityCommand = _connection.CreateCommand();
_saveActivityCommand.CommandText = "replace into ActivityLogEntries (Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Id, @Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)";
_saveActivityCommand.Parameters.Add(_saveActivityCommand, "@Id");
_saveActivityCommand.Parameters.Add(_saveActivityCommand, "@Name");
_saveActivityCommand.Parameters.Add(_saveActivityCommand, "@Overview");
_saveActivityCommand.Parameters.Add(_saveActivityCommand, "@ShortOverview");
_saveActivityCommand.Parameters.Add(_saveActivityCommand, "@Type");
_saveActivityCommand.Parameters.Add(_saveActivityCommand, "@ItemId");
_saveActivityCommand.Parameters.Add(_saveActivityCommand, "@UserId");
_saveActivityCommand.Parameters.Add(_saveActivityCommand, "@DateCreated");
_saveActivityCommand.Parameters.Add(_saveActivityCommand, "@LogSeverity");
}
private const string BaseActivitySelectText = "select Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity from ActivityLogEntries";
public Task Create(ActivityLogEntry entry)
{
return Update(entry);
}
public async Task Update(ActivityLogEntry entry)
{
if (entry == null)
{
throw new ArgumentNullException("entry");
}
2016-02-10 18:13:24 +00:00
await WriteLock.WaitAsync().ConfigureAwait(false);
2014-08-10 22:13:17 +00:00
IDbTransaction transaction = null;
try
{
transaction = _connection.BeginTransaction();
var index = 0;
_saveActivityCommand.GetParameter(index++).Value = new Guid(entry.Id);
_saveActivityCommand.GetParameter(index++).Value = entry.Name;
_saveActivityCommand.GetParameter(index++).Value = entry.Overview;
_saveActivityCommand.GetParameter(index++).Value = entry.ShortOverview;
_saveActivityCommand.GetParameter(index++).Value = entry.Type;
_saveActivityCommand.GetParameter(index++).Value = entry.ItemId;
_saveActivityCommand.GetParameter(index++).Value = entry.UserId;
_saveActivityCommand.GetParameter(index++).Value = entry.Date;
_saveActivityCommand.GetParameter(index++).Value = entry.Severity.ToString();
_saveActivityCommand.Transaction = transaction;
_saveActivityCommand.ExecuteNonQuery();
transaction.Commit();
}
catch (OperationCanceledException)
{
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
catch (Exception e)
{
2016-02-10 18:13:24 +00:00
Logger.ErrorException("Failed to save record:", e);
2014-08-10 22:13:17 +00:00
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
finally
{
if (transaction != null)
{
transaction.Dispose();
}
2016-02-10 18:13:24 +00:00
WriteLock.Release();
2014-08-10 22:13:17 +00:00
}
}
2014-08-14 13:24:30 +00:00
public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, int? startIndex, int? limit)
2014-08-10 22:13:17 +00:00
{
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = BaseActivitySelectText;
var whereClauses = new List<string>();
2014-08-14 13:24:30 +00:00
if (minDate.HasValue)
2014-08-10 22:13:17 +00:00
{
2014-08-14 13:24:30 +00:00
whereClauses.Add("DateCreated>=@DateCreated");
cmd.Parameters.Add(cmd, "@DateCreated", DbType.Date).Value = minDate.Value;
2014-08-10 22:13:17 +00:00
}
2014-08-14 13:24:30 +00:00
var whereTextWithoutPaging = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray());
if (startIndex.HasValue && startIndex.Value > 0)
2014-08-10 22:13:17 +00:00
{
2014-08-14 13:24:30 +00:00
var pagingWhereText = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray());
whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLogEntries {0} ORDER BY DateCreated DESC LIMIT {1})",
pagingWhereText,
startIndex.Value.ToString(_usCulture)));
2014-08-10 22:13:17 +00:00
}
2014-08-14 13:24:30 +00:00
var whereText = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray());
cmd.CommandText += whereText;
2014-08-10 22:13:17 +00:00
cmd.CommandText += " ORDER BY DateCreated DESC";
if (limit.HasValue)
{
cmd.CommandText += " LIMIT " + limit.Value.ToString(_usCulture);
}
2014-08-14 13:24:30 +00:00
cmd.CommandText += "; select count (Id) from ActivityLogEntries" + whereTextWithoutPaging;
2014-08-10 22:13:17 +00:00
var list = new List<ActivityLogEntry>();
var count = 0;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
list.Add(GetEntry(reader));
}
if (reader.NextResult() && reader.Read())
{
count = reader.GetInt32(0);
}
}
return new QueryResult<ActivityLogEntry>()
{
Items = list.ToArray(),
TotalRecordCount = count
};
}
}
private ActivityLogEntry GetEntry(IDataReader reader)
{
var index = 0;
var info = new ActivityLogEntry
{
Id = reader.GetGuid(index).ToString("N")
};
index++;
if (!reader.IsDBNull(index))
{
info.Name = reader.GetString(index);
}
index++;
if (!reader.IsDBNull(index))
{
info.Overview = reader.GetString(index);
}
index++;
if (!reader.IsDBNull(index))
{
info.ShortOverview = reader.GetString(index);
}
index++;
if (!reader.IsDBNull(index))
{
info.Type = reader.GetString(index);
}
index++;
if (!reader.IsDBNull(index))
{
info.ItemId = reader.GetString(index);
}
index++;
if (!reader.IsDBNull(index))
{
info.UserId = reader.GetString(index);
}
index++;
info.Date = reader.GetDateTime(index).ToUniversalTime();
index++;
if (!reader.IsDBNull(index))
{
info.Severity = (LogSeverity)Enum.Parse(typeof(LogSeverity), reader.GetString(index), true);
}
return info;
}
2016-02-10 18:13:24 +00:00
protected override void CloseConnection()
2014-08-10 22:13:17 +00:00
{
2016-02-10 18:13:24 +00:00
if (_connection != null)
2014-08-10 22:13:17 +00:00
{
2016-02-10 18:13:24 +00:00
if (_connection.IsOpen())
2014-08-10 22:13:17 +00:00
{
2016-02-10 18:13:24 +00:00
_connection.Close();
2014-08-10 22:13:17 +00:00
}
2016-02-10 18:13:24 +00:00
_connection.Dispose();
_connection = null;
2014-08-10 22:13:17 +00:00
}
}
}
}