jellyfin/MediaBrowser.Server.Implementations/Sync/SyncRepository.cs

840 lines
32 KiB
C#
Raw Normal View History

2015-03-15 01:42:09 +00:00
using System.Text;
using MediaBrowser.Controller;
2014-07-26 17:30:15 +00:00
using MediaBrowser.Controller.Sync;
2015-01-17 04:29:53 +00:00
using MediaBrowser.Model.Dto;
2014-07-26 17:30:15 +00:00
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Querying;
2015-01-17 04:29:53 +00:00
using MediaBrowser.Model.Serialization;
2014-07-26 17:30:15 +00:00
using MediaBrowser.Model.Sync;
using MediaBrowser.Server.Implementations.Persistence;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Sync
{
2014-08-10 22:13:17 +00:00
public class SyncRepository : ISyncRepository, IDisposable
2014-07-26 17:30:15 +00:00
{
private IDbConnection _connection;
private readonly ILogger _logger;
private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
private readonly IServerApplicationPaths _appPaths;
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
2015-02-03 06:57:45 +00:00
private IDbCommand _insertJobCommand;
private IDbCommand _updateJobCommand;
2014-12-11 06:20:28 +00:00
private IDbCommand _deleteJobCommand;
2015-02-03 06:57:45 +00:00
2014-12-20 06:06:27 +00:00
private IDbCommand _deleteJobItemsCommand;
2015-02-04 11:56:48 +00:00
private IDbCommand _insertJobItemCommand;
private IDbCommand _updateJobItemCommand;
2014-07-26 17:30:15 +00:00
2015-01-17 04:29:53 +00:00
private readonly IJsonSerializer _json;
public SyncRepository(ILogger logger, IServerApplicationPaths appPaths, IJsonSerializer json)
2014-07-26 17:30:15 +00:00
{
_logger = logger;
_appPaths = appPaths;
2015-01-17 04:29:53 +00:00
_json = json;
2014-07-26 17:30:15 +00:00
}
public async Task Initialize()
{
2015-01-23 06:15:15 +00:00
var dbFile = Path.Combine(_appPaths.DataPath, "sync14.db");
2014-07-26 17:30:15 +00:00
_connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false);
string[] queries = {
2015-03-15 01:42:09 +00:00
"create table if not exists SyncJobs (Id GUID PRIMARY KEY, TargetId TEXT NOT NULL, Name TEXT NOT NULL, Profile TEXT, Quality TEXT, Status TEXT NOT NULL, Progress FLOAT, UserId TEXT NOT NULL, ItemIds TEXT NOT NULL, Category TEXT, ParentId TEXT, UnwatchedOnly BIT, ItemLimit INT, SyncNewContent BIT, DateCreated DateTime, DateLastModified DateTime, ItemCount int)",
2014-07-26 17:30:15 +00:00
"create index if not exists idx_SyncJobs on SyncJobs(Id)",
2015-01-23 06:15:15 +00:00
"create table if not exists SyncJobItems (Id GUID PRIMARY KEY, ItemId TEXT, ItemName TEXT, MediaSourceId TEXT, JobId TEXT, TemporaryPath TEXT, OutputPath TEXT, Status TEXT, TargetId TEXT, DateCreated DateTime, Progress FLOAT, AdditionalFiles TEXT, MediaSource TEXT, IsMarkedForRemoval BIT, JobItemIndex INT)",
2014-07-26 17:30:15 +00:00
"create index if not exists idx_SyncJobItems on SyncJobs(Id)",
//pragmas
"pragma temp_store = memory",
"pragma shrink_memory"
};
_connection.RunQueries(queries, _logger);
2015-03-15 01:42:09 +00:00
_connection.AddColumn(_logger, "SyncJobs", "Profile", "TEXT");
2014-07-26 17:30:15 +00:00
PrepareStatements();
}
private void PrepareStatements()
{
2015-02-03 06:57:45 +00:00
// _deleteJobCommand
2014-12-11 06:20:28 +00:00
_deleteJobCommand = _connection.CreateCommand();
2014-12-20 06:06:27 +00:00
_deleteJobCommand.CommandText = "delete from SyncJobs where Id=@Id";
2014-12-11 06:20:28 +00:00
_deleteJobCommand.Parameters.Add(_deleteJobCommand, "@Id");
2015-02-03 06:57:45 +00:00
// _deleteJobItemsCommand
2014-12-20 06:06:27 +00:00
_deleteJobItemsCommand = _connection.CreateCommand();
_deleteJobItemsCommand.CommandText = "delete from SyncJobItems where JobId=@JobId";
_deleteJobItemsCommand.Parameters.Add(_deleteJobItemsCommand, "@JobId");
2014-12-30 16:36:49 +00:00
2015-02-03 06:57:45 +00:00
// _insertJobCommand
_insertJobCommand = _connection.CreateCommand();
2015-03-15 01:42:09 +00:00
_insertJobCommand.CommandText = "insert into SyncJobs (Id, TargetId, Name, Profile, Quality, Status, Progress, UserId, ItemIds, Category, ParentId, UnwatchedOnly, ItemLimit, SyncNewContent, DateCreated, DateLastModified, ItemCount) values (@Id, @TargetId, @Name, @Profile, @Quality, @Status, @Progress, @UserId, @ItemIds, @Category, @ParentId, @UnwatchedOnly, @ItemLimit, @SyncNewContent, @DateCreated, @DateLastModified, @ItemCount)";
2015-02-03 06:57:45 +00:00
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Id");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@TargetId");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Name");
2015-03-15 01:42:09 +00:00
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Profile");
2015-02-03 06:57:45 +00:00
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Quality");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Status");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Progress");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@UserId");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@ItemIds");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@Category");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@ParentId");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@UnwatchedOnly");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@ItemLimit");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@SyncNewContent");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@DateCreated");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@DateLastModified");
_insertJobCommand.Parameters.Add(_insertJobCommand, "@ItemCount");
// _updateJobCommand
_updateJobCommand = _connection.CreateCommand();
2015-03-15 01:42:09 +00:00
_updateJobCommand.CommandText = "update SyncJobs set TargetId=@TargetId,Name=@Name,Profile=@Profile,Quality=@Quality,Status=@Status,Progress=@Progress,UserId=@UserId,ItemIds=@ItemIds,Category=@Category,ParentId=@ParentId,UnwatchedOnly=@UnwatchedOnly,ItemLimit=@ItemLimit,SyncNewContent=@SyncNewContent,DateCreated=@DateCreated,DateLastModified=@DateLastModified,ItemCount=@ItemCount where Id=@ID";
2015-02-03 06:57:45 +00:00
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Id");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@TargetId");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Name");
2015-03-15 01:42:09 +00:00
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Profile");
2015-02-03 06:57:45 +00:00
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Quality");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Status");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Progress");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@UserId");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@ItemIds");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@Category");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@ParentId");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@UnwatchedOnly");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@ItemLimit");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@SyncNewContent");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@DateCreated");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@DateLastModified");
_updateJobCommand.Parameters.Add(_updateJobCommand, "@ItemCount");
2015-02-04 11:56:48 +00:00
// _insertJobItemCommand
_insertJobItemCommand = _connection.CreateCommand();
_insertJobItemCommand.CommandText = "insert into SyncJobItems (Id, ItemId, ItemName, MediaSourceId, JobId, TemporaryPath, OutputPath, Status, TargetId, DateCreated, Progress, AdditionalFiles, MediaSource, IsMarkedForRemoval, JobItemIndex) values (@Id, @ItemId, @ItemName, @MediaSourceId, @JobId, @TemporaryPath, @OutputPath, @Status, @TargetId, @DateCreated, @Progress, @AdditionalFiles, @MediaSource, @IsMarkedForRemoval, @JobItemIndex)";
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@Id");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@ItemId");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@ItemName");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@MediaSourceId");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@JobId");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@TemporaryPath");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@OutputPath");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@Status");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@TargetId");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@DateCreated");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@Progress");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@AdditionalFiles");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@MediaSource");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@IsMarkedForRemoval");
_insertJobItemCommand.Parameters.Add(_insertJobItemCommand, "@JobItemIndex");
// _updateJobItemCommand
_updateJobItemCommand = _connection.CreateCommand();
_updateJobItemCommand.CommandText = "update SyncJobItems set ItemId=@ItemId,ItemName=@ItemName,MediaSourceId=@MediaSourceId,JobId=@JobId,TemporaryPath=@TemporaryPath,OutputPath=@OutputPath,Status=@Status,TargetId=@TargetId,DateCreated=@DateCreated,Progress=@Progress,AdditionalFiles=@AdditionalFiles,MediaSource=@MediaSource,IsMarkedForRemoval=@IsMarkedForRemoval,JobItemIndex=@JobItemIndex where Id=@Id";
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@Id");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@ItemId");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@ItemName");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@MediaSourceId");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@JobId");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@TemporaryPath");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@OutputPath");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@Status");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@TargetId");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@DateCreated");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@Progress");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@AdditionalFiles");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@MediaSource");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@IsMarkedForRemoval");
_updateJobItemCommand.Parameters.Add(_updateJobItemCommand, "@JobItemIndex");
2014-07-26 17:30:15 +00:00
}
2015-03-15 01:42:09 +00:00
private const string BaseJobSelectText = "select Id, TargetId, Name, Profile, Quality, Status, Progress, UserId, ItemIds, Category, ParentId, UnwatchedOnly, ItemLimit, SyncNewContent, DateCreated, DateLastModified, ItemCount from SyncJobs";
2015-01-23 06:15:15 +00:00
private const string BaseJobItemSelectText = "select Id, ItemId, ItemName, MediaSourceId, JobId, TemporaryPath, OutputPath, Status, TargetId, DateCreated, Progress, AdditionalFiles, MediaSource, IsMarkedForRemoval, JobItemIndex from SyncJobItems";
2014-07-26 17:30:15 +00:00
public SyncJob GetJob(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
2015-02-07 03:25:23 +00:00
CheckDisposed();
2014-07-26 17:30:15 +00:00
var guid = new Guid(id);
2014-12-13 03:56:30 +00:00
if (guid == Guid.Empty)
{
throw new ArgumentNullException("id");
}
2014-12-30 16:36:49 +00:00
2014-07-26 17:30:15 +00:00
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = BaseJobSelectText + " where Id=@Id";
cmd.Parameters.Add(cmd, "@Id", DbType.Guid).Value = guid;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
{
if (reader.Read())
{
return GetJob(reader);
}
}
}
return null;
}
private SyncJob GetJob(IDataReader reader)
{
var info = new SyncJob
{
Id = reader.GetGuid(0).ToString("N"),
TargetId = reader.GetString(1),
Name = reader.GetString(2)
};
if (!reader.IsDBNull(3))
{
2015-03-15 01:42:09 +00:00
info.Profile = reader.GetString(3);
2014-07-26 17:30:15 +00:00
}
if (!reader.IsDBNull(4))
{
2015-03-15 01:42:09 +00:00
info.Quality = reader.GetString(4);
2014-07-26 17:30:15 +00:00
}
if (!reader.IsDBNull(5))
{
2015-03-15 01:42:09 +00:00
info.Status = (SyncJobStatus)Enum.Parse(typeof(SyncJobStatus), reader.GetString(5), true);
2014-07-26 17:30:15 +00:00
}
if (!reader.IsDBNull(6))
{
2015-03-15 01:42:09 +00:00
info.Progress = reader.GetDouble(6);
2014-07-26 17:30:15 +00:00
}
if (!reader.IsDBNull(7))
{
2015-03-15 01:42:09 +00:00
info.UserId = reader.GetString(7);
2014-07-26 17:30:15 +00:00
}
if (!reader.IsDBNull(8))
{
2015-03-15 01:42:09 +00:00
info.RequestedItemIds = reader.GetString(8).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
2014-07-26 17:30:15 +00:00
}
if (!reader.IsDBNull(9))
{
2015-03-15 01:42:09 +00:00
info.Category = (SyncCategory)Enum.Parse(typeof(SyncCategory), reader.GetString(9), true);
2014-07-26 17:30:15 +00:00
}
2014-12-16 05:01:57 +00:00
if (!reader.IsDBNull(10))
{
2015-03-15 01:42:09 +00:00
info.ParentId = reader.GetString(10);
2014-12-16 05:01:57 +00:00
}
if (!reader.IsDBNull(11))
{
2015-03-15 01:42:09 +00:00
info.UnwatchedOnly = reader.GetBoolean(11);
}
if (!reader.IsDBNull(12))
{
info.ItemLimit = reader.GetInt32(12);
2014-12-16 05:01:57 +00:00
}
2015-03-15 01:42:09 +00:00
info.SyncNewContent = reader.GetBoolean(13);
2014-07-26 17:30:15 +00:00
2015-03-15 01:42:09 +00:00
info.DateCreated = reader.GetDateTime(14).ToUniversalTime();
info.DateLastModified = reader.GetDateTime(15).ToUniversalTime();
info.ItemCount = reader.GetInt32(16);
2014-07-26 17:30:15 +00:00
return info;
}
public Task Create(SyncJob job)
{
2015-02-03 06:57:45 +00:00
return InsertOrUpdate(job, _insertJobCommand);
}
public Task Update(SyncJob job)
{
return InsertOrUpdate(job, _updateJobCommand);
2014-07-26 17:30:15 +00:00
}
2015-02-03 06:57:45 +00:00
private async Task InsertOrUpdate(SyncJob job, IDbCommand cmd)
2014-07-26 17:30:15 +00:00
{
if (job == null)
{
throw new ArgumentNullException("job");
}
2015-02-07 03:25:23 +00:00
CheckDisposed();
2014-07-26 17:30:15 +00:00
await _writeLock.WaitAsync().ConfigureAwait(false);
IDbTransaction transaction = null;
try
{
transaction = _connection.BeginTransaction();
var index = 0;
2015-02-03 06:57:45 +00:00
cmd.GetParameter(index++).Value = new Guid(job.Id);
cmd.GetParameter(index++).Value = job.TargetId;
cmd.GetParameter(index++).Value = job.Name;
2015-03-15 01:42:09 +00:00
cmd.GetParameter(index++).Value = job.Profile;
2015-02-03 06:57:45 +00:00
cmd.GetParameter(index++).Value = job.Quality;
cmd.GetParameter(index++).Value = job.Status.ToString();
cmd.GetParameter(index++).Value = job.Progress;
cmd.GetParameter(index++).Value = job.UserId;
cmd.GetParameter(index++).Value = string.Join(",", job.RequestedItemIds.ToArray());
cmd.GetParameter(index++).Value = job.Category;
cmd.GetParameter(index++).Value = job.ParentId;
cmd.GetParameter(index++).Value = job.UnwatchedOnly;
cmd.GetParameter(index++).Value = job.ItemLimit;
cmd.GetParameter(index++).Value = job.SyncNewContent;
cmd.GetParameter(index++).Value = job.DateCreated;
cmd.GetParameter(index++).Value = job.DateLastModified;
cmd.GetParameter(index++).Value = job.ItemCount;
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();
2014-07-26 17:30:15 +00:00
transaction.Commit();
}
catch (OperationCanceledException)
{
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
catch (Exception e)
{
_logger.ErrorException("Failed to save record:", e);
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
finally
{
if (transaction != null)
{
transaction.Dispose();
}
_writeLock.Release();
}
}
2014-12-11 06:20:28 +00:00
public async Task DeleteJob(string id)
{
if (string.IsNullOrWhiteSpace(id))
{
throw new ArgumentNullException("id");
}
2015-02-07 03:25:23 +00:00
CheckDisposed();
2014-12-11 06:20:28 +00:00
await _writeLock.WaitAsync().ConfigureAwait(false);
IDbTransaction transaction = null;
try
{
transaction = _connection.BeginTransaction();
var index = 0;
_deleteJobCommand.GetParameter(index++).Value = new Guid(id);
_deleteJobCommand.Transaction = transaction;
_deleteJobCommand.ExecuteNonQuery();
2014-12-27 22:52:41 +00:00
index = 0;
_deleteJobItemsCommand.GetParameter(index++).Value = id;
2014-12-20 06:06:27 +00:00
_deleteJobItemsCommand.Transaction = transaction;
_deleteJobItemsCommand.ExecuteNonQuery();
2014-12-30 16:36:49 +00:00
2014-12-11 06:20:28 +00:00
transaction.Commit();
}
catch (OperationCanceledException)
{
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
catch (Exception e)
{
_logger.ErrorException("Failed to save record:", e);
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
finally
{
if (transaction != null)
{
transaction.Dispose();
}
_writeLock.Release();
}
}
2014-07-26 17:30:15 +00:00
public QueryResult<SyncJob> GetJobs(SyncJobQuery query)
{
if (query == null)
{
throw new ArgumentNullException("query");
}
2015-02-07 03:25:23 +00:00
CheckDisposed();
2014-07-26 17:30:15 +00:00
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = BaseJobSelectText;
var whereClauses = new List<string>();
2015-02-04 11:56:48 +00:00
if (query.Statuses.Count > 0)
2014-12-13 03:56:30 +00:00
{
2015-02-04 11:56:48 +00:00
var statuses = string.Join(",", query.Statuses.Select(i => "'" + i.ToString() + "'").ToArray());
whereClauses.Add(string.Format("Status in ({0})", statuses));
2014-12-13 03:56:30 +00:00
}
2014-12-17 05:30:31 +00:00
if (!string.IsNullOrWhiteSpace(query.TargetId))
{
whereClauses.Add("TargetId=@TargetId");
}
2014-12-31 06:24:49 +00:00
if (!string.IsNullOrWhiteSpace(query.UserId))
{
whereClauses.Add("UserId=@UserId");
cmd.Parameters.Add(cmd, "@UserId", DbType.String).Value = query.UserId;
}
2015-02-04 11:56:48 +00:00
if (query.SyncNewContent.HasValue)
{
whereClauses.Add("SyncNewContent=@SyncNewContent");
cmd.Parameters.Add(cmd, "@SyncNewContent", DbType.Boolean).Value = query.SyncNewContent.Value;
}
2014-07-26 17:30:15 +00:00
2014-12-13 03:56:30 +00:00
var whereTextWithoutPaging = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray());
var startIndex = query.StartIndex ?? 0;
2014-07-26 17:30:15 +00:00
if (startIndex > 0)
{
2015-02-03 21:06:56 +00:00
whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM SyncJobs ORDER BY (Select Max(DateLastModified) from SyncJobs where TargetId=@TargetId) DESC, DateLastModified DESC LIMIT {0})",
2014-07-26 17:30:15 +00:00
startIndex.ToString(_usCulture)));
}
if (whereClauses.Count > 0)
{
cmd.CommandText += " where " + string.Join(" AND ", whereClauses.ToArray());
}
2015-02-03 21:06:56 +00:00
cmd.CommandText += " ORDER BY (Select Max(DateLastModified) from SyncJobs where TargetId=@TargetId) DESC, DateLastModified DESC";
cmd.Parameters.Add(cmd, "@TargetId", DbType.String).Value = query.TargetId;
2014-07-26 17:30:15 +00:00
if (query.Limit.HasValue)
{
cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(_usCulture);
}
2014-12-13 03:56:30 +00:00
cmd.CommandText += "; select count (Id) from SyncJobs" + whereTextWithoutPaging;
2014-07-26 17:30:15 +00:00
var list = new List<SyncJob>();
var count = 0;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
list.Add(GetJob(reader));
}
if (reader.NextResult() && reader.Read())
{
count = reader.GetInt32(0);
}
}
return new QueryResult<SyncJob>()
{
Items = list.ToArray(),
TotalRecordCount = count
};
}
}
public SyncJobItem GetJobItem(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new ArgumentNullException("id");
}
2015-02-07 03:25:23 +00:00
CheckDisposed();
2014-07-26 17:30:15 +00:00
var guid = new Guid(id);
using (var cmd = _connection.CreateCommand())
{
cmd.CommandText = BaseJobItemSelectText + " where Id=@Id";
cmd.Parameters.Add(cmd, "@Id", DbType.Guid).Value = guid;
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
{
if (reader.Read())
{
2014-12-13 03:56:30 +00:00
return GetJobItem(reader);
2014-07-26 17:30:15 +00:00
}
}
}
return null;
}
2015-01-24 19:03:55 +00:00
private QueryResult<T> GetJobItemReader<T>(SyncJobItemQuery query, string baseSelectText, Func<IDataReader, T> itemFactory)
2014-12-11 06:20:28 +00:00
{
2014-12-13 03:56:30 +00:00
if (query == null)
2014-12-11 06:20:28 +00:00
{
2014-12-13 03:56:30 +00:00
throw new ArgumentNullException("query");
2014-12-11 06:20:28 +00:00
}
using (var cmd = _connection.CreateCommand())
{
2015-01-24 19:03:55 +00:00
cmd.CommandText = baseSelectText;
2014-12-11 06:20:28 +00:00
2014-12-13 03:56:30 +00:00
var whereClauses = new List<string>();
if (!string.IsNullOrWhiteSpace(query.JobId))
{
whereClauses.Add("JobId=@JobId");
cmd.Parameters.Add(cmd, "@JobId", DbType.String).Value = query.JobId;
}
2015-03-07 23:39:24 +00:00
if (!string.IsNullOrWhiteSpace(query.ItemId))
{
whereClauses.Add("ItemId=@ItemId");
cmd.Parameters.Add(cmd, "@ItemId", DbType.String).Value = query.ItemId;
}
2014-12-17 05:30:31 +00:00
if (!string.IsNullOrWhiteSpace(query.TargetId))
{
whereClauses.Add("TargetId=@TargetId");
cmd.Parameters.Add(cmd, "@TargetId", DbType.String).Value = query.TargetId;
}
2014-12-28 06:21:39 +00:00
2014-12-30 19:16:01 +00:00
if (query.Statuses.Count > 0)
2014-12-17 05:30:31 +00:00
{
2014-12-30 19:16:01 +00:00
var statuses = string.Join(",", query.Statuses.Select(i => "'" + i.ToString() + "'").ToArray());
whereClauses.Add(string.Format("Status in ({0})", statuses));
2014-12-17 05:30:31 +00:00
}
2014-12-13 03:56:30 +00:00
var whereTextWithoutPaging = whereClauses.Count == 0 ?
string.Empty :
" where " + string.Join(" AND ", whereClauses.ToArray());
var startIndex = query.StartIndex ?? 0;
if (startIndex > 0)
{
2015-01-23 06:15:15 +00:00
whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM SyncJobItems ORDER BY JobItemIndex, DateCreated LIMIT {0})",
2014-12-13 03:56:30 +00:00
startIndex.ToString(_usCulture)));
}
if (whereClauses.Count > 0)
{
cmd.CommandText += " where " + string.Join(" AND ", whereClauses.ToArray());
}
2015-01-23 06:15:15 +00:00
cmd.CommandText += " ORDER BY JobItemIndex, DateCreated";
2014-12-13 03:56:30 +00:00
if (query.Limit.HasValue)
{
cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(_usCulture);
}
cmd.CommandText += "; select count (Id) from SyncJobItems" + whereTextWithoutPaging;
2015-01-24 19:03:55 +00:00
var list = new List<T>();
2014-12-13 03:56:30 +00:00
var count = 0;
2014-12-11 06:20:28 +00:00
2014-12-13 03:56:30 +00:00
using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
2014-12-11 06:20:28 +00:00
{
while (reader.Read())
{
2015-01-24 19:03:55 +00:00
list.Add(itemFactory(reader));
2014-12-13 03:56:30 +00:00
}
if (reader.NextResult() && reader.Read())
{
count = reader.GetInt32(0);
2014-12-11 06:20:28 +00:00
}
}
2014-12-13 03:56:30 +00:00
2015-01-24 19:03:55 +00:00
return new QueryResult<T>()
2014-12-13 03:56:30 +00:00
{
Items = list.ToArray(),
TotalRecordCount = count
};
2014-12-11 06:20:28 +00:00
}
}
2015-01-24 19:03:55 +00:00
public QueryResult<string> GetLibraryItemIds(SyncJobItemQuery query)
{
return GetJobItemReader(query, "select ItemId from SyncJobItems", GetItemId);
}
public QueryResult<SyncJobItem> GetJobItems(SyncJobItemQuery query)
{
return GetJobItemReader(query, BaseJobItemSelectText, GetJobItem);
}
2014-07-26 17:30:15 +00:00
public Task Create(SyncJobItem jobItem)
{
2015-02-04 11:56:48 +00:00
return InsertOrUpdate(jobItem, _insertJobItemCommand);
}
public Task Update(SyncJobItem jobItem)
{
return InsertOrUpdate(jobItem, _updateJobItemCommand);
2014-07-26 17:30:15 +00:00
}
2015-02-04 11:56:48 +00:00
private async Task InsertOrUpdate(SyncJobItem jobItem, IDbCommand cmd)
2014-07-26 17:30:15 +00:00
{
if (jobItem == null)
{
throw new ArgumentNullException("jobItem");
}
2015-02-07 03:25:23 +00:00
CheckDisposed();
2014-07-26 17:30:15 +00:00
await _writeLock.WaitAsync().ConfigureAwait(false);
IDbTransaction transaction = null;
try
{
transaction = _connection.BeginTransaction();
var index = 0;
2015-02-04 11:56:48 +00:00
cmd.GetParameter(index++).Value = new Guid(jobItem.Id);
cmd.GetParameter(index++).Value = jobItem.ItemId;
cmd.GetParameter(index++).Value = jobItem.ItemName;
cmd.GetParameter(index++).Value = jobItem.MediaSourceId;
cmd.GetParameter(index++).Value = jobItem.JobId;
cmd.GetParameter(index++).Value = jobItem.TemporaryPath;
cmd.GetParameter(index++).Value = jobItem.OutputPath;
cmd.GetParameter(index++).Value = jobItem.Status.ToString();
cmd.GetParameter(index++).Value = jobItem.TargetId;
cmd.GetParameter(index++).Value = jobItem.DateCreated;
cmd.GetParameter(index++).Value = jobItem.Progress;
cmd.GetParameter(index++).Value = _json.SerializeToString(jobItem.AdditionalFiles);
cmd.GetParameter(index++).Value = jobItem.MediaSource == null ? null : _json.SerializeToString(jobItem.MediaSource);
cmd.GetParameter(index++).Value = jobItem.IsMarkedForRemoval;
cmd.GetParameter(index++).Value = jobItem.JobItemIndex;
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();
2014-07-26 17:30:15 +00:00
transaction.Commit();
}
catch (OperationCanceledException)
{
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
catch (Exception e)
{
_logger.ErrorException("Failed to save record:", e);
if (transaction != null)
{
transaction.Rollback();
}
throw;
}
finally
{
if (transaction != null)
{
transaction.Dispose();
}
_writeLock.Release();
}
}
2014-12-13 03:56:30 +00:00
private SyncJobItem GetJobItem(IDataReader reader)
2014-07-26 17:30:15 +00:00
{
var info = new SyncJobItem
{
Id = reader.GetGuid(0).ToString("N"),
2014-12-27 22:52:41 +00:00
ItemId = reader.GetString(1)
2014-07-26 17:30:15 +00:00
};
2014-12-27 22:52:41 +00:00
if (!reader.IsDBNull(2))
{
2014-12-31 06:24:49 +00:00
info.ItemName = reader.GetString(2);
2014-12-27 22:52:41 +00:00
}
2014-12-30 16:36:49 +00:00
2014-12-31 06:24:49 +00:00
if (!reader.IsDBNull(3))
2014-07-26 17:30:15 +00:00
{
2014-12-31 06:24:49 +00:00
info.MediaSourceId = reader.GetString(3);
2014-07-26 17:30:15 +00:00
}
2014-12-31 06:24:49 +00:00
info.JobId = reader.GetString(4);
2015-01-17 04:29:53 +00:00
if (!reader.IsDBNull(5))
{
info.TemporaryPath = reader.GetString(5);
}
2015-01-06 03:25:23 +00:00
if (!reader.IsDBNull(6))
2014-07-26 17:30:15 +00:00
{
2015-01-06 03:25:23 +00:00
info.OutputPath = reader.GetString(6);
2014-07-26 17:30:15 +00:00
}
2015-01-06 03:25:23 +00:00
if (!reader.IsDBNull(7))
2014-12-31 06:24:49 +00:00
{
2015-01-06 03:25:23 +00:00
info.Status = (SyncJobItemStatus)Enum.Parse(typeof(SyncJobItemStatus), reader.GetString(7), true);
2014-12-31 06:24:49 +00:00
}
2014-08-10 22:13:17 +00:00
2015-01-06 03:25:23 +00:00
info.TargetId = reader.GetString(8);
2014-12-13 03:56:30 +00:00
2015-01-23 06:15:15 +00:00
info.DateCreated = reader.GetDateTime(9).ToUniversalTime();
2014-12-31 06:24:49 +00:00
2015-01-06 03:25:23 +00:00
if (!reader.IsDBNull(10))
2014-12-13 03:56:30 +00:00
{
2015-01-06 03:25:23 +00:00
info.Progress = reader.GetDouble(10);
2014-12-13 03:56:30 +00:00
}
2014-12-30 16:36:49 +00:00
2015-01-17 04:29:53 +00:00
if (!reader.IsDBNull(11))
{
var json = reader.GetString(11);
if (!string.IsNullOrWhiteSpace(json))
{
info.AdditionalFiles = _json.DeserializeFromString<List<ItemFileInfo>>(json);
}
}
if (!reader.IsDBNull(12))
{
var json = reader.GetString(12);
if (!string.IsNullOrWhiteSpace(json))
{
info.MediaSource = _json.DeserializeFromString<MediaSourceInfo>(json);
}
}
2015-01-21 03:54:45 +00:00
info.IsMarkedForRemoval = reader.GetBoolean(13);
2015-01-23 06:15:15 +00:00
info.JobItemIndex = reader.GetInt32(14);
2015-01-24 19:03:55 +00:00
2014-07-26 17:30:15 +00:00
return info;
}
2014-08-10 22:13:17 +00:00
2015-01-24 19:03:55 +00:00
private string GetItemId(IDataReader reader)
{
return reader.GetString(0);
}
2014-08-10 22:13:17 +00:00
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
2015-02-07 03:25:23 +00:00
private bool _disposed;
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed.");
}
}
2014-08-10 22:13:17 +00:00
private readonly object _disposeLock = new object();
/// <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 (dispose)
{
2015-02-07 03:25:23 +00:00
_disposed = true;
2014-08-10 22:13:17 +00:00
try
{
lock (_disposeLock)
{
if (_connection != null)
{
if (_connection.IsOpen())
{
_connection.Close();
}
_connection.Dispose();
_connection = null;
}
}
}
catch (Exception ex)
{
_logger.ErrorException("Error disposing database", ex);
}
}
}
2014-07-26 17:30:15 +00:00
}
}