ActivityRepository.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Activity;
  3. using MediaBrowser.Model.Activity;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Querying;
  6. using MediaBrowser.Server.Implementations.Persistence;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Data;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Server.Implementations.Activity
  15. {
  16. public class ActivityRepository : BaseSqliteRepository, IActivityRepository
  17. {
  18. private IDbConnection _connection;
  19. private readonly IServerApplicationPaths _appPaths;
  20. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  21. private IDbCommand _saveActivityCommand;
  22. public ActivityRepository(ILogManager logManager, IServerApplicationPaths appPaths)
  23. : base(logManager)
  24. {
  25. _appPaths = appPaths;
  26. }
  27. public async Task Initialize()
  28. {
  29. var dbFile = Path.Combine(_appPaths.DataPath, "activitylog.db");
  30. _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false);
  31. string[] queries = {
  32. "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)",
  33. "create index if not exists idx_ActivityLogEntries on ActivityLogEntries(Id)",
  34. //pragmas
  35. "pragma temp_store = memory",
  36. "pragma shrink_memory"
  37. };
  38. _connection.RunQueries(queries, Logger);
  39. PrepareStatements();
  40. }
  41. private void PrepareStatements()
  42. {
  43. _saveActivityCommand = _connection.CreateCommand();
  44. _saveActivityCommand.CommandText = "replace into ActivityLogEntries (Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity) values (@Id, @Name, @Overview, @ShortOverview, @Type, @ItemId, @UserId, @DateCreated, @LogSeverity)";
  45. _saveActivityCommand.Parameters.Add(_saveActivityCommand, "@Id");
  46. _saveActivityCommand.Parameters.Add(_saveActivityCommand, "@Name");
  47. _saveActivityCommand.Parameters.Add(_saveActivityCommand, "@Overview");
  48. _saveActivityCommand.Parameters.Add(_saveActivityCommand, "@ShortOverview");
  49. _saveActivityCommand.Parameters.Add(_saveActivityCommand, "@Type");
  50. _saveActivityCommand.Parameters.Add(_saveActivityCommand, "@ItemId");
  51. _saveActivityCommand.Parameters.Add(_saveActivityCommand, "@UserId");
  52. _saveActivityCommand.Parameters.Add(_saveActivityCommand, "@DateCreated");
  53. _saveActivityCommand.Parameters.Add(_saveActivityCommand, "@LogSeverity");
  54. }
  55. private const string BaseActivitySelectText = "select Id, Name, Overview, ShortOverview, Type, ItemId, UserId, DateCreated, LogSeverity from ActivityLogEntries";
  56. public Task Create(ActivityLogEntry entry)
  57. {
  58. return Update(entry);
  59. }
  60. public async Task Update(ActivityLogEntry entry)
  61. {
  62. if (entry == null)
  63. {
  64. throw new ArgumentNullException("entry");
  65. }
  66. await WriteLock.WaitAsync().ConfigureAwait(false);
  67. IDbTransaction transaction = null;
  68. try
  69. {
  70. transaction = _connection.BeginTransaction();
  71. var index = 0;
  72. _saveActivityCommand.GetParameter(index++).Value = new Guid(entry.Id);
  73. _saveActivityCommand.GetParameter(index++).Value = entry.Name;
  74. _saveActivityCommand.GetParameter(index++).Value = entry.Overview;
  75. _saveActivityCommand.GetParameter(index++).Value = entry.ShortOverview;
  76. _saveActivityCommand.GetParameter(index++).Value = entry.Type;
  77. _saveActivityCommand.GetParameter(index++).Value = entry.ItemId;
  78. _saveActivityCommand.GetParameter(index++).Value = entry.UserId;
  79. _saveActivityCommand.GetParameter(index++).Value = entry.Date;
  80. _saveActivityCommand.GetParameter(index++).Value = entry.Severity.ToString();
  81. _saveActivityCommand.Transaction = transaction;
  82. _saveActivityCommand.ExecuteNonQuery();
  83. transaction.Commit();
  84. }
  85. catch (OperationCanceledException)
  86. {
  87. if (transaction != null)
  88. {
  89. transaction.Rollback();
  90. }
  91. throw;
  92. }
  93. catch (Exception e)
  94. {
  95. Logger.ErrorException("Failed to save record:", e);
  96. if (transaction != null)
  97. {
  98. transaction.Rollback();
  99. }
  100. throw;
  101. }
  102. finally
  103. {
  104. if (transaction != null)
  105. {
  106. transaction.Dispose();
  107. }
  108. WriteLock.Release();
  109. }
  110. }
  111. public QueryResult<ActivityLogEntry> GetActivityLogEntries(DateTime? minDate, int? startIndex, int? limit)
  112. {
  113. using (var cmd = _connection.CreateCommand())
  114. {
  115. cmd.CommandText = BaseActivitySelectText;
  116. var whereClauses = new List<string>();
  117. if (minDate.HasValue)
  118. {
  119. whereClauses.Add("DateCreated>=@DateCreated");
  120. cmd.Parameters.Add(cmd, "@DateCreated", DbType.Date).Value = minDate.Value;
  121. }
  122. var whereTextWithoutPaging = whereClauses.Count == 0 ?
  123. string.Empty :
  124. " where " + string.Join(" AND ", whereClauses.ToArray());
  125. if (startIndex.HasValue && startIndex.Value > 0)
  126. {
  127. var pagingWhereText = whereClauses.Count == 0 ?
  128. string.Empty :
  129. " where " + string.Join(" AND ", whereClauses.ToArray());
  130. whereClauses.Add(string.Format("Id NOT IN (SELECT Id FROM ActivityLogEntries {0} ORDER BY DateCreated DESC LIMIT {1})",
  131. pagingWhereText,
  132. startIndex.Value.ToString(_usCulture)));
  133. }
  134. var whereText = whereClauses.Count == 0 ?
  135. string.Empty :
  136. " where " + string.Join(" AND ", whereClauses.ToArray());
  137. cmd.CommandText += whereText;
  138. cmd.CommandText += " ORDER BY DateCreated DESC";
  139. if (limit.HasValue)
  140. {
  141. cmd.CommandText += " LIMIT " + limit.Value.ToString(_usCulture);
  142. }
  143. cmd.CommandText += "; select count (Id) from ActivityLogEntries" + whereTextWithoutPaging;
  144. var list = new List<ActivityLogEntry>();
  145. var count = 0;
  146. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
  147. {
  148. while (reader.Read())
  149. {
  150. list.Add(GetEntry(reader));
  151. }
  152. if (reader.NextResult() && reader.Read())
  153. {
  154. count = reader.GetInt32(0);
  155. }
  156. }
  157. return new QueryResult<ActivityLogEntry>()
  158. {
  159. Items = list.ToArray(),
  160. TotalRecordCount = count
  161. };
  162. }
  163. }
  164. private ActivityLogEntry GetEntry(IDataReader reader)
  165. {
  166. var index = 0;
  167. var info = new ActivityLogEntry
  168. {
  169. Id = reader.GetGuid(index).ToString("N")
  170. };
  171. index++;
  172. if (!reader.IsDBNull(index))
  173. {
  174. info.Name = reader.GetString(index);
  175. }
  176. index++;
  177. if (!reader.IsDBNull(index))
  178. {
  179. info.Overview = reader.GetString(index);
  180. }
  181. index++;
  182. if (!reader.IsDBNull(index))
  183. {
  184. info.ShortOverview = reader.GetString(index);
  185. }
  186. index++;
  187. if (!reader.IsDBNull(index))
  188. {
  189. info.Type = reader.GetString(index);
  190. }
  191. index++;
  192. if (!reader.IsDBNull(index))
  193. {
  194. info.ItemId = reader.GetString(index);
  195. }
  196. index++;
  197. if (!reader.IsDBNull(index))
  198. {
  199. info.UserId = reader.GetString(index);
  200. }
  201. index++;
  202. info.Date = reader.GetDateTime(index).ToUniversalTime();
  203. index++;
  204. if (!reader.IsDBNull(index))
  205. {
  206. info.Severity = (LogSeverity)Enum.Parse(typeof(LogSeverity), reader.GetString(index), true);
  207. }
  208. return info;
  209. }
  210. protected override void CloseConnection()
  211. {
  212. if (_connection != null)
  213. {
  214. if (_connection.IsOpen())
  215. {
  216. _connection.Close();
  217. }
  218. _connection.Dispose();
  219. _connection = null;
  220. }
  221. }
  222. }
  223. }