using System.Threading.Tasks; using System; using Bit.Core.Enums; using Bit.Core.Repositories; using Bit.Core.Models.Data; using System.Linq; using System.Collections.Generic; using Microsoft.WindowsAzure.Storage.Table; using Bit.Core.Models.Table; namespace Bit.Core.Services { public class EventService : IEventService { private readonly IEventRepository _eventRepository; private readonly IOrganizationUserRepository _organizationUserRepository; private readonly CurrentContext _currentContext; private readonly GlobalSettings _globalSettings; public EventService( IEventRepository eventRepository, IOrganizationUserRepository organizationUserRepository, CurrentContext currentContext, GlobalSettings globalSettings) { _eventRepository = eventRepository; _organizationUserRepository = organizationUserRepository; _currentContext = currentContext; _globalSettings = globalSettings; } public async Task LogUserEventAsync(Guid userId, EventType type) { var events = new List { new UserEvent(userId, type) }; IEnumerable orgEvents; if(_currentContext.UserId.HasValue) { orgEvents = _currentContext.Organizations.Select(o => new UserEvent(userId, o.Id, type)); } else { var orgs = await _organizationUserRepository.GetManyByUserAsync(userId); orgEvents = orgs.Where(o => o.Status == OrganizationUserStatusType.Confirmed) .Select(o => new UserEvent(userId, o.Id, type)); } if(orgEvents.Any()) { events.AddRange(orgEvents); await _eventRepository.CreateManyAsync(events); } else { await _eventRepository.CreateAsync(events.First()); } } public async Task LogCipherEventAsync(Cipher cipher, EventType type) { if(!cipher.OrganizationId.HasValue || (!_currentContext?.UserId.HasValue ?? true)) { return; } var e = new CipherEvent(cipher, type, _currentContext?.UserId); await _eventRepository.CreateAsync(e); } } }