private static void RemoveTeamlabMailbox(MailBoxData mailbox, ILog log) { if (mailbox == null) { throw new ArgumentNullException("mailbox"); } if (!mailbox.IsTeamlab) { return; } try { var engineFactory = new EngineFactory( CoreContext.TenantManager.GetCurrentTenant().TenantId, SecurityContext.CurrentAccount.ID.ToString()); engineFactory.ServerMailboxEngine.RemoveMailbox(mailbox); } catch (Exception ex) { log.ErrorFormat("RemoveTeamlabMailbox(mailboxId = {0}) Failure\r\nException: {1}", mailbox.MailBoxId, ex.ToString()); } }
public static bool IsTenantQuotaEnded(this MailBoxData mailbox, long minBalance, ILog log = null) { var quotaEnded = false; log = log ?? new NullLog(); try { var quotaController = new TenantQuotaController(mailbox.TenantId); var quota = CoreContext.TenantManager.GetTenantQuota(mailbox.TenantId); var usedQuota = quotaController.QuotaCurrentGet(); quotaEnded = quota.MaxTotalSize - usedQuota < minBalance; log.DebugFormat("IsTenantQuotaEnded: {0} Tenant = {1}. Tenant quota = {2}Mb ({3}), used quota = {4}Mb ({5}) ", quotaEnded, mailbox.TenantId, MailUtil.BytesToMegabytes(quota.MaxTotalSize), quota.MaxTotalSize, MailUtil.BytesToMegabytes(usedQuota), usedQuota); } catch (Exception ex) { log.ErrorFormat("IsQuotaExhausted(Tenant={0}) Exception: {1}", mailbox.TenantId, ex.Message); } return(quotaEnded); }
public void Remove(MailBoxData mailBox) { try { if (mailBox == null) { throw new ArgumentNullException("mailBox"); } if (!IsIndexAvailable()) { return; } var selector = new Selector <MailWrapper>() .Where(m => m.MailboxId, mailBox.MailBoxId) .Where(e => e.UserId, new Guid(mailBox.UserId)) .Where(e => e.TenantId, mailBox.TenantId); FactoryIndexer <MailWrapper> .Delete(r => selector); } catch (Exception ex) { Log.ErrorFormat("IndexEngine->Remove(mailboxId = {0}) error: {1}", mailBox == null ? -1 : mailBox.MailBoxId, ex.ToString()); } }
public List <MailAttachGarbage> GetMailboxAttachs(MailBoxData mailBoxData, int limit) { List <MailAttachGarbage> list; const string m = "m"; const string a = "a"; using (var db = GetDb()) { var queryAttachemnts = new SqlQuery(MailTable.TABLE_NAME.Alias(m)) .InnerJoin(AttachmentTable.TABLE_NAME.Alias(a), Exp.EqColumns(MailTable.Columns.Id.Prefix(m), AttachmentTable.Columns.MailId.Prefix(a))) .Select(AttachmentTable.Columns.Id.Prefix(a), MailTable.Columns.Stream.Prefix(m), AttachmentTable.Columns.FileNumber.Prefix(a), AttachmentTable.Columns.StoredName.Prefix(a), AttachmentTable.Columns.Name.Prefix(a), MailTable.Columns.Id.Prefix(m)) .Where(MailTable.Columns.MailboxId.Prefix(m), mailBoxData.MailBoxId) .Where(MailTable.Columns.Tenant.Prefix(m), mailBoxData.TenantId) .Where(MailTable.Columns.User.Prefix(m), mailBoxData.UserId) .SetMaxResults(limit); list = db.ExecuteList(queryAttachemnts) .ConvertAll( r => new MailAttachGarbage(mailBoxData.UserId, Convert.ToInt32(r[0]), r[1].ToString(), Convert.ToInt32(r[2]), r[3] != null ? r[3].ToString() : r[4].ToString())) .ToList(); } return(list); }
public void CleanupMailboxData(MailBoxData mailbox, bool totalRemove) { if (!mailbox.IsRemoved) { throw new Exception("Mailbox is not removed."); } var deleteMailboxMessagesQuery = new SqlDelete(MailTable.TABLE_NAME) .Where(MailTable.Columns.MailboxId, mailbox.MailBoxId) .Where(MailTable.Columns.Tenant, mailbox.TenantId) .Where(MailTable.Columns.User, mailbox.UserId); var deleteMailboxAttachmentsQuery = new SqlDelete(AttachmentTable.TABLE_NAME) .Where(AttachmentTable.Columns.MailboxId, mailbox.MailBoxId) .Where(AttachmentTable.Columns.Tenant, mailbox.TenantId); using (var db = GetDb()) { using (var tx = db.BeginTransaction(IsolationLevel.ReadUncommitted)) { var daoFactory = new DaoFactory(db); var daoMailbox = daoFactory.CreateMailboxDao(); var mb = daoMailbox.GetMailBox( new СoncreteUserMailboxExp(mailbox.MailBoxId, mailbox.TenantId, mailbox.UserId, true)); db.ExecuteNonQuery(deleteMailboxAttachmentsQuery); db.ExecuteNonQuery(deleteMailboxMessagesQuery); daoFactory.CreateMailboxDao().RemoveMailbox(mb); if (totalRemove) { daoFactory.CreateFolderDao(mailbox.TenantId, mailbox.UserId).Delete(); var deleteContactInfoQuery = new SqlDelete(ContactInfoTable.TABLE_NAME) .Where(ContactInfoTable.Columns.User, mailbox.UserId) .Where(ContactInfoTable.Columns.Tenant, mailbox.TenantId); db.ExecuteNonQuery(deleteContactInfoQuery); var deleteContactsQuery = new SqlDelete(ContactsTable.TABLE_NAME) .Where(ContactsTable.Columns.User, mailbox.UserId) .Where(ContactsTable.Columns.Tenant, mailbox.TenantId); db.ExecuteNonQuery(deleteContactsQuery); var deleteDisplayImagesQuery = new SqlDelete(DisplayImagesTable.TABLE_NAME) .Where(DisplayImagesTable.Columns.User, mailbox.UserId) .Where(DisplayImagesTable.Columns.Tenant, mailbox.TenantId); db.ExecuteNonQuery(deleteDisplayImagesQuery); } tx.Commit(); } } }
private static string GetAutoreplyEmailInTo(MailBoxData account, MailMessage messageItem) { var autoreplyAddress = GetAddressInList(account, messageItem.ToList) ?? GetAddressInList(account, messageItem.CcList); return(autoreplyAddress); }
private static string GetAddressInList(MailBoxData account, List <MailAddress> list) { if (list.Any(address => string.Equals(address.Address, account.EMail.Address, StringComparison.InvariantCultureIgnoreCase))) { return(account.EMail.ToString()); } if (!account.IsTeamlab) { return(null); } if (account.Aliases == null) { var engine = new EngineFactory(account.TenantId, account.UserId); account.Aliases = engine.ServerEngine.GetAliases(account.MailBoxId); } var result = (from address in list from alias in account.Aliases where string.Equals(address.Address, alias.Email, StringComparison.InvariantCultureIgnoreCase) select alias.Email) .FirstOrDefault(); return(result); }
private bool HasMailboxAutoreplyHistory(MailBoxData account, string email) { if (account.MailAutoreplyHistory == null) { account.MailAutoreplyHistory = new List <string>(); } if (account.MailAutoreplyHistory.Contains(email)) { return(true); } List <string> emails; using (var daoFactory = new DaoFactory()) { var autoreplyHistoryDao = daoFactory.CreateMailboxAutoreplyHistoryDao(account.TenantId, account.UserId); emails = autoreplyHistoryDao.GetAutoreplyHistorySentEmails(account.MailBoxId, email, AutoreplyDaysInterval); } if (!emails.Any()) { return(false); } account.MailAutoreplyHistory.Add(email); return(true); }
private static bool HasGroupsInTo(MailBoxData account, MailMessage messageItem) { if (!account.IsTeamlab) { return(false); } if (account.Groups == null) { var engine = new EngineFactory(account.TenantId, account.UserId); account.Groups = engine.ServerEngine.GetGroups(account.MailBoxId); } foreach (var group in account.Groups) { if (messageItem.ToList.Any( address => string.Equals(address.Address, group.Email, StringComparison.InvariantCultureIgnoreCase))) { return(true); } if (messageItem.CcList.Any( address => string.Equals(address.Address, group.Email, StringComparison.InvariantCultureIgnoreCase))) { return(true); } } return(false); }
public void ReleaseMailbox(MailBoxData mailBoxData) { try { if (!_lockedMailBoxList.Contains(mailBoxData)) { _log.WarnFormat("QueueManager->ReleaseMailbox(Tenant = {0} MailboxId = {1}, Address = '{2}') mailbox not found", mailBoxData.TenantId, mailBoxData.MailBoxId, mailBoxData.EMail); return; } _log.InfoFormat("QueueManager->ReleaseMailbox(MailboxId = {0} Address '{1}')", mailBoxData.MailBoxId, mailBoxData.EMail); CoreContext.TenantManager.SetCurrentTenant(mailBoxData.TenantId); _engineFactory.MailboxEngine.ReleaseMaibox(mailBoxData, _tasksConfig); _lockedMailBoxList.Remove(mailBoxData); DeleteMailboxFromDumpDb(mailBoxData.MailBoxId); } catch (Exception ex) { _log.ErrorFormat("QueueManager->ReleaseMailbox(Tenant = {0} MailboxId = {1}, Address = '{2}')\r\nException: {3} \r\n", mailBoxData.TenantId, mailBoxData.MailBoxId, mailBoxData.Account, ex.ToString()); } }
public static bool IsCrmAvailable(this MailBoxData mailbox, string httpContextScheme, ILog log = null) { log = log ?? new NullLog(); try { CoreContext.TenantManager.SetCurrentTenant(mailbox.TenantId); var tenantInfo = CoreContext.TenantManager.GetCurrentTenant(); if (tenantInfo.Status == TenantStatus.RemovePending) { return(false); } SecurityContext.AuthenticateMe(new Guid(mailbox.UserId)); var apiHelper = new ApiHelper(httpContextScheme, log); return(apiHelper.IsCrmModuleAvailable()); } catch (Exception ex) { log.ErrorFormat("GetTenantStatus(Tenant={0}, User='******') Exception: {2}", mailbox.TenantId, mailbox.UserId, ex.InnerException != null ? ex.InnerException.Message : ex.Message); } return(true); }
public void RemoveMailBox(MailBoxData mailbox, bool needRecalculateFolders = true) { if (mailbox.MailBoxId <= 0) { throw new Exception("MailBox id is 0"); } long freedQuotaSize; using (var db = new DbManager(Defines.CONNECTION_STRING_NAME, Defines.RemoveMailboxTimeout)) { var daoFactory = new DaoFactory(db); using (var tx = daoFactory.DbManager.BeginTransaction()) { freedQuotaSize = RemoveMailBoxInfo(daoFactory, mailbox); tx.Commit(); } } var engine = new EngineFactory(mailbox.TenantId, mailbox.UserId, Log); engine.QuotaEngine.QuotaUsedDelete(freedQuotaSize); CacheEngine.Clear(mailbox.UserId); engine.IndexEngine.Remove(mailbox); if (!needRecalculateFolders) { return; } engine.OperationEngine.RecalculateFolders(); }
public AccountInfo CreateAccount(MailBoxData mbox, out LoginResult loginResult) { if (mbox == null) { throw new NullReferenceException("mbox"); } using (var client = new MailClient(mbox, CancellationToken.None, certificatePermit: Defines.SslCertificatesErrorPermit, log: Log)) { loginResult = client.TestLogin(); } if (!loginResult.IngoingSuccess || !loginResult.OutgoingSuccess) { return(null); } if (!MailboxEngine.SaveMailBox(mbox)) { throw new Exception(string.Format("SaveMailBox {0} failed", mbox.EMail)); } CacheEngine.Clear(User); var account = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError, MailBoxData.AuthProblemType.NoProblems, new MailSignatureData(mbox.MailBoxId, Tenant, "", false), new MailAutoreplyData(mbox.MailBoxId, Tenant, false, false, false, DateTime.MinValue, DateTime.MinValue, string.Empty, string.Empty), false, mbox.EMailInFolder, false, false); return(account); }
private static MailboxState GetMailboxState(MailBoxData mailbox, ILog log) { try { log.Debug("GetMailBoxState()"); var engine = new EngineFactory(-1); var status = engine.MailboxEngine.GetMailboxStatus(new СoncreteUserMailboxExp(mailbox.MailBoxId, mailbox.TenantId, mailbox.UserId)); if (mailbox.BeginDate != status.BeginDate) { mailbox.BeginDateChanged = true; mailbox.BeginDate = status.BeginDate; return(MailboxState.DateChanged); } if (status.IsRemoved) { return(MailboxState.Deleted); } if (!status.Enabled) { return(MailboxState.Disabled); } } catch (Exception exGetMbInfo) { log.InfoFormat("GetMailBoxState(Tenant = {0}, MailboxId = {1}, Address = '{2}') Exception: {3}", mailbox.TenantId, mailbox.MailBoxId, mailbox.EMail, exGetMbInfo.Message); } return(MailboxState.NoChanges); }
private void ClearGarbage(MailBoxData mailbox) { var taskLog = LogManager.GetLogger(string.Format("ASC.Mail Mbox_{0} Task_{1}", mailbox.MailBoxId, Task.CurrentId)); taskLog.InfoFormat("Processing MailboxId = {0}, email = '{1}', tenant = '{2}', user = '******'", mailbox.MailBoxId, mailbox.EMail.Address, mailbox.TenantId, mailbox.UserId); try { if (NeedRemove(mailbox, taskLog)) { RemoveMailboxData(mailbox, true, taskLog); } else if (mailbox.IsRemoved) { taskLog.Info("Mailbox is removed."); RemoveMailboxData(mailbox, false, taskLog); } else { RemoveGarbageMailData(mailbox, Config.GarbageOverdueDays, taskLog); } taskLog.InfoFormat("Mailbox {0} processing complete.", mailbox.MailBoxId); } catch (Exception ex) { taskLog.ErrorFormat("Mailbox {0} processed with error : {1}", mailbox.MailBoxId, ex.ToString()); } }
private void ReleaseMailbox(MailBoxData mailbox) { if (mailbox == null) { return; } if (mailbox.LastSignalrNotifySkipped) { NotifySignalrIfNeed(mailbox, _log); } _queueManager.ReleaseMailbox(mailbox); if (!Filters.ContainsKey(mailbox.UserId)) { return; } List <MailSieveFilterData> filters; if (!Filters.TryRemove(mailbox.UserId, out filters)) { _log.Error("Try forget Filters for user failed"); } }
public AccountInfo CreateAccountSimple(string email, string password, out List <LoginResult> loginResults) { MailBoxData mbox = null; var domain = email.Substring(email.IndexOf('@') + 1); var engine = new EngineFactory(Tenant, User); var mailboxSettings = engine.MailBoxSettingEngine.GetMailBoxSettings(domain); if (mailboxSettings == null) { throw new Exception("Unknown mail provider settings."); } var testMailboxes = mailboxSettings.ToMailboxList(email, password, Tenant, User); loginResults = new List <LoginResult>(); foreach (var mb in testMailboxes) { LoginResult loginResult; using (var client = new MailClient(mb, CancellationToken.None, Defines.TcpTimeout, Defines.SslCertificatesErrorPermit, log: Log)) { loginResult = client.TestLogin(); } loginResults.Add(loginResult); if (!loginResult.IngoingSuccess || !loginResult.OutgoingSuccess) { continue; } mbox = mb; break; } if (mbox == null) { return(null); } if (!MailboxEngine.SaveMailBox(mbox)) { throw new Exception(string.Format("SaveMailBox {0} failed", email)); } CacheEngine.Clear(User); var account = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError, MailBoxData.AuthProblemType.NoProblems, new MailSignatureData(mbox.MailBoxId, Tenant, "", false), new MailAutoreplyData(mbox.MailBoxId, Tenant, false, false, false, DateTime.MinValue, DateTime.MinValue, string.Empty, string.Empty), false, mbox.EMailInFolder, false, false); return(account); }
public MailRemoveMailboxOperation(Tenant tenant, IAccount user, MailBoxData mailBoxData) : base(tenant, user) { _mailBoxData = mailBoxData; Log = LogManager.GetLogger("ASC.Mail.RemoveMailboxOperation"); SetSource(_mailBoxData.MailBoxId.ToString()); }
private bool NeedRemove(MailBoxData mailbox, ILog taskLog) { var needRemove = false; lock (Locker) { Defines.TariffType type; var memTenantItem = TenantMemCache.Get(mailbox.TenantId.ToString(CultureInfo.InvariantCulture)); if (memTenantItem == null) { taskLog.InfoFormat("Tenant {0} isn't in cache", mailbox.TenantId); taskLog.DebugFormat("GetTenantStatus(OverdueDays={0})", Config.TenantOverdueDays); type = mailbox.GetTenantStatus(Config.TenantOverdueDays, Config.HttpContextScheme, Log); var cacheItem = new CacheItem(mailbox.TenantId.ToString(CultureInfo.InvariantCulture), type); var cacheItemPolicy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.UtcNow.AddDays(Config.TenantCacheDays) }; TenantMemCache.Add(cacheItem, cacheItemPolicy); } else { taskLog.InfoFormat("Tenant {0} is in cache", mailbox.TenantId); type = (Defines.TariffType)memTenantItem; } taskLog.InfoFormat("Tenant {0} has status '{1}'", mailbox.TenantId, type.ToString()); if (type == Defines.TariffType.LongDead) { needRemove = true; } else { var isUserRemoved = mailbox.IsUserRemoved(); taskLog.InfoFormat("User '{0}' status is '{1}'", mailbox.UserId, isUserRemoved ? "Terminated" : "Not terminated"); if (isUserRemoved) { needRemove = true; } } } return(needRemove); }
public MailClientMessageEventArgs(MimeKit.MimeMessage message, string messageUid, bool uread, MailFolder folder, MailBoxData mailBoxData, ILog logger) { Message = message; Unread = uread; Folder = folder; Mailbox = mailBoxData; MessageUid = messageUid; Logger = logger; }
public void AddMailbox(MailBoxData item) { lock (_processingQueue) { if (!_processingQueue.Contains(item)) { _processingQueue.Enqueue(item); } } _waitHandle.Set(); }
public void StoreAttachments(MailBoxData mailBoxData, List <MailAttachmentData> attachments, string streamId) { if (!attachments.Any() || string.IsNullOrEmpty(streamId)) { return; } try { var quotaAddSize = attachments.Sum(a => a.data != null ? a.data.LongLength : a.dataStream.Length); var storageManager = new StorageManager(mailBoxData.TenantId, mailBoxData.UserId); foreach (var attachment in attachments) { var isAttachmentNameHasBadName = string.IsNullOrEmpty(attachment.fileName) || attachment.fileName.IndexOfAny(Path.GetInvalidPathChars()) != -1 || attachment.fileName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1; if (isAttachmentNameHasBadName) { attachment.fileName = string.Format("attacment{0}{1}", attachment.fileNumber, MimeMapping.GetExtention(attachment.contentType)); } attachment.streamId = streamId; attachment.tenant = mailBoxData.TenantId; attachment.user = mailBoxData.UserId; storageManager.StoreAttachmentWithoutQuota(attachment); } var engine = new EngineFactory(mailBoxData.TenantId); engine.QuotaEngine.QuotaUsedAdd(quotaAddSize); } catch { var storedAttachmentsKeys = attachments .Where(a => !string.IsNullOrEmpty(a.storedFileUrl)) .Select(MailStoragePathCombiner.GerStoredFilePath) .ToList(); if (storedAttachmentsKeys.Any()) { var storage = MailDataStore.GetDataStore(mailBoxData.TenantId); storedAttachmentsKeys.ForEach(key => storage.Delete(string.Empty, key)); } Log.InfoFormat("[Failed] StoreAttachments(mailboxId={0}). All message attachments were deleted.", mailBoxData.MailBoxId); throw; } }
// Constructor public MailboxMessagesIterator(MailBoxData mailBoxData) { MailEngine = new EngineFactory(mailBoxData.TenantId, mailBoxData.UserId); var range = MailEngine .MessageEngine .GetRangeMessages( SimpleMessagesExp.CreateBuilder(mailBoxData.TenantId) .SetMailboxId(mailBoxData.MailBoxId) .Build()); _minMessageId = range.Item1; _maxMessageId = range.Item2; }
private void LogStat(string method, MailBoxData mailBoxData, TimeSpan duration, bool failed) { if (!_tasksConfig.CollectStatistics) { return; } _logStat.DebugWithProps(method, new KeyValuePair <string, object>("duration", duration.TotalMilliseconds), new KeyValuePair <string, object>("mailboxId", mailBoxData.MailBoxId), new KeyValuePair <string, object>("address", mailBoxData.EMail.ToString()), new KeyValuePair <string, object>("status", failed ? S_FAIL : S_OK)); }
public static MailboxData ToMailboxData(this MailBoxData mailbox) { return(new MailboxData { MailboxId = mailbox.MailBoxId, TenantId = mailbox.TenantId, UserId = mailbox.UserId, EMail = mailbox.EMail.Address, Imap = mailbox.Imap, IsTeamlab = mailbox.IsTeamlab, MessagesCount = mailbox.MessagesCount, Size = mailbox.Size }); }
public static UserInfo GetUserInfo(this MailBoxData mailbox) { try { CoreContext.TenantManager.SetCurrentTenant(mailbox.TenantId); var userInfo = CoreContext.UserManager.GetUsers(new Guid(mailbox.UserId)); return(userInfo); } catch (Exception) { return(null); } }
private static MailMessageData GetMail(MailBoxData mailbox, int mailId) { var engine = new EngineFactory(mailbox.TenantId, mailbox.UserId); return(engine.MessageEngine.GetMessage(mailId, new MailMessageData.Options { LoadBody = false, LoadImages = false, NeedProxyHttp = false, NeedSanitizer = false, OnlyUnremoved = true, LoadEmebbedAttachements = true })); }
public static bool IsUserTerminated(this MailBoxData mailbox) { try { CoreContext.TenantManager.SetCurrentTenant(mailbox.TenantId); var user = CoreContext.UserManager.GetUsers(new Guid(mailbox.UserId)); return(user.Status == EmployeeStatus.Terminated); } catch (Exception) { return(false); } }
public void SaveAutoreplyHistory(MailBoxData account, MailMessage messageItem) { using (var daoFactory = new DaoFactory()) { var autoReplyHistory = new MailboxAutoreplyHistory { MailboxId = account.MailBoxId, SendingDate = DateTime.UtcNow, SendingEmail = new MailAddress(messageItem.To).Address, Tenant = account.TenantId }; daoFactory.CreateMailboxAutoreplyHistoryDao(account.TenantId, account.UserId) .SaveAutoreplyHistory(autoReplyHistory); } }
/// <summary> /// Set mailbox removed /// </summary> /// <param name="mailBoxData"></param> /// <returns>Return freed quota value</returns> public long RemoveMailBoxInfo(MailBoxData mailBoxData) { long freedQuotaSize; using (var db = new DbManager(Defines.CONNECTION_STRING_NAME, Defines.RemoveMailboxTimeout)) { var daoFactory = new DaoFactory(db); using (var tx = daoFactory.DbManager.BeginTransaction()) { freedQuotaSize = RemoveMailBoxInfo(daoFactory, mailBoxData); tx.Commit(); } } return(freedQuotaSize); }