2
0

ActivityRepository.cs 9.3 KB

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