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); }
public MailSignatureData SaveSignature(int mailboxId, string html, bool isActive) { if (!string.IsNullOrEmpty(html)) { var imagesReplacer = new StorageManager(Tenant, User, Log); html = imagesReplacer.ChangeEditorImagesLinks(html, mailboxId); } CacheEngine.Clear(User); var signature = new MailboxSignature { MailboxId = mailboxId, Tenant = Tenant, Html = html, IsActive = isActive }; using (var daoFactory = new DaoFactory()) { var result = daoFactory .CreateMailboxSignatureDao(Tenant, User) .SaveSignature(signature); if (result <= 0) { throw new Exception("Save failed"); } } return(ToMailMailSignature(signature)); }
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 int SetAccountEnable(MailAddress address, bool enabled, out LoginResult loginResult) { if (address == null) { throw new ArgumentNullException("address"); } var engine = new EngineFactory(Tenant); var tuple = engine.MailboxEngine.GetMailboxFullInfo(new СoncreteUserMailboxExp(address, Tenant, User)); if (tuple == null) { throw new NullReferenceException(string.Format("Account wasn't found by email: {0}", address.Address)); } if (enabled) { // Check account connection setting on activation using (var client = new MailClient(tuple.Item1, CancellationToken.None, certificatePermit: Defines.SslCertificatesErrorPermit, log: Log)) { loginResult = client.TestLogin(); } if (!loginResult.IngoingSuccess || !loginResult.OutgoingSuccess) { return(-1); } } int mailboxId; using (var daoFactory = new DaoFactory()) { var daoMailbox = daoFactory.CreateMailboxDao(); loginResult = null; mailboxId = daoMailbox.Enable(new СoncreteUserMailboxExp(tuple.Item2.Id, tuple.Item2.Tenant, tuple.Item2.User), enabled) ? tuple.Item2.Id : -1; } if (mailboxId == -1) { return(mailboxId); } CacheEngine.Clear(User); return(mailboxId); }
public AccountInfo CreateAccountOAuth(string code, byte type) { var oAuthToken = OAuth20TokenHelper.GetAccessToken <GoogleLoginProvider>(code); if (oAuthToken == null) { throw new Exception(@"Empty oauth token"); } var loginProfile = GoogleLoginProvider.Instance.GetLoginProfile(oAuthToken.AccessToken); var email = loginProfile.EMail; if (string.IsNullOrEmpty(email)) { throw new Exception(@"Empty email"); } var beginDate = DateTime.UtcNow.Subtract(new TimeSpan(MailBoxData.DefaultMailLimitedTimeDelta)); var mboxImap = MailboxEngine.GetDefaultMailboxData(email, "", (AuthorizationServiceType)type, true, false); mboxImap.OAuthToken = oAuthToken.ToJson(); mboxImap.BeginDate = beginDate; // Apply restrict for download if (!MailboxEngine.SaveMailBox(mboxImap, (AuthorizationServiceType)type)) { throw new Exception(string.Format("SaveMailBox {0} failed", email)); } CacheEngine.Clear(User); if (Defines.IsSignalRAvailable) { var engine = new EngineFactory(Tenant, User); engine.AccountEngine.SetAccountsActivity(); } var account = new AccountInfo(mboxImap.MailBoxId, mboxImap.EMailView, mboxImap.Name, mboxImap.Enabled, mboxImap.QuotaError, MailBoxData.AuthProblemType.NoProblems, new MailSignatureData(mboxImap.MailBoxId, Tenant, "", false), new MailAutoreplyData(mboxImap.MailBoxId, Tenant, false, false, false, DateTime.MinValue, DateTime.MinValue, string.Empty, string.Empty), true, mboxImap.EMailInFolder, false, false); return(account); }
public bool SetAccountEmailInFolder(int mailboxId, string emailInFolder) { if (mailboxId < 0) { throw new ArgumentNullException("mailboxId"); } bool saved; using (var daoFactory = new DaoFactory()) { var daoMailbox = daoFactory.CreateMailboxDao(); var mailbox = daoMailbox.GetMailBox( new СoncreteUserMailboxExp( mailboxId, Tenant, User) ); if (mailbox == null) { return(false); } saved = daoMailbox.SetMailboxEmailIn(mailbox, emailInFolder); } if (!saved) { return(saved); } CacheEngine.Clear(User); return(saved); }
public AccountInfo UpdateAccountOAuth(int mailboxId, string code, byte type) { if (string.IsNullOrEmpty(code)) { throw new ArgumentException(@"Empty OAuth code", "code"); } var oAuthToken = OAuth20TokenHelper.GetAccessToken <GoogleLoginProvider>(code); if (oAuthToken == null) { throw new Exception(@"Empty OAuth token"); } if (string.IsNullOrEmpty(oAuthToken.AccessToken)) { throw new Exception(@"Empty OAuth AccessToken"); } if (string.IsNullOrEmpty(oAuthToken.RefreshToken)) { throw new Exception(@"Empty OAuth RefreshToken"); } if (oAuthToken.IsExpired) { throw new Exception(@"OAuth token is expired"); } var loginProfile = GoogleLoginProvider.Instance.GetLoginProfile(oAuthToken.AccessToken); var email = loginProfile.EMail; if (string.IsNullOrEmpty(email)) { throw new Exception(@"Empty email"); } Mailbox mbox; using (var daoFactory = new DaoFactory()) { var daoMailbox = daoFactory.CreateMailboxDao(); mbox = daoMailbox.GetMailBox( new СoncreteUserMailboxExp( mailboxId, Tenant, User)); if (null == mbox) { throw new ArgumentException("Mailbox with specified email doesn't exist."); } if (mbox.IsTeamlabMailbox || string.IsNullOrEmpty(mbox.OAuthToken)) { throw new ArgumentException("Mailbox with specified email can't be updated"); } if (!mbox.Address.Equals(email, StringComparison.InvariantCultureIgnoreCase)) { throw new ArgumentException("Mailbox with specified email can't be updated"); } mbox.OAuthToken = oAuthToken.ToJson(); var result = daoMailbox.SaveMailBox(mbox); mbox.Id = result; } CacheEngine.Clear(User); if (Defines.IsSignalRAvailable) { var engine = new EngineFactory(Tenant, User); engine.AccountEngine.SetAccountsActivity(); } var accountInfo = new AccountInfo(mbox.Id, mbox.Address, mbox.Name, mbox.Enabled, mbox.QuotaError, MailBoxData.AuthProblemType.NoProblems, new MailSignatureData(mbox.Id, Tenant, "", false), new MailAutoreplyData(mbox.Id, Tenant, false, false, false, DateTime.MinValue, DateTime.MinValue, string.Empty, string.Empty), true, mbox.EmailInFolder, false, false); return(accountInfo); }
public AccountInfo UpdateAccount(MailBoxData newMailBoxData, out LoginResult loginResult) { if (newMailBoxData == null) { throw new NullReferenceException("mbox"); } Mailbox mbox; using (var daoFactory = new DaoFactory()) { var daoMailbox = daoFactory.CreateMailboxDao(); mbox = daoMailbox.GetMailBox( new СoncreteUserMailboxExp( newMailBoxData.EMail, Tenant, User)); if (null == mbox) { throw new ArgumentException("Mailbox with specified email doesn't exist."); } if (mbox.IsTeamlabMailbox) { throw new ArgumentException("Mailbox with specified email can't be updated"); } if (!string.IsNullOrEmpty(mbox.OAuthToken)) { var needSave = false; if (!mbox.Name.Equals(newMailBoxData.Name)) { mbox.Name = newMailBoxData.Name; needSave = true; } if (!mbox.BeginDate.Equals(newMailBoxData.BeginDate)) { mbox.BeginDate = newMailBoxData.BeginDate; mbox.ImapIntervals = null; needSave = true; } if (needSave) { daoMailbox.SaveMailBox(mbox); CacheEngine.Clear(User); } var accountInfo = new AccountInfo(mbox.Id, mbox.Address, mbox.Name, mbox.Enabled, mbox.QuotaError, MailBoxData.AuthProblemType.NoProblems, new MailSignatureData(mbox.Id, Tenant, "", false), new MailAutoreplyData(mbox.Id, Tenant, false, false, false, DateTime.MinValue, DateTime.MinValue, string.Empty, string.Empty), false, mbox.EmailInFolder, false, false); loginResult = new LoginResult { Imap = mbox.Imap, IngoingSuccess = true, OutgoingSuccess = true }; return(accountInfo); } } newMailBoxData.Password = string.IsNullOrEmpty(newMailBoxData.Password) ? mbox.Password : newMailBoxData.Password; newMailBoxData.SmtpPassword = string.IsNullOrEmpty(newMailBoxData.SmtpPassword) ? mbox.SmtpPassword : newMailBoxData.SmtpPassword; newMailBoxData.Imap = mbox.Imap; return(CreateAccount(newMailBoxData, out loginResult)); }
public void RemoveAlias(int mailboxId, int addressId) { if (!IsAdmin) { throw new SecurityException("Need admin privileges."); } if (mailboxId < 0) { throw new ArgumentException(@"Invalid address id.", "mailboxId"); } using (var daoFactory = new DaoFactory()) { var mailboxDao = daoFactory.CreateMailboxDao(); var mailbox = mailboxDao.GetMailBox(new ConcreteTenantServerMailboxExp(mailboxId, Tenant, false)); if (mailbox == null) { throw new ArgumentException("Mailbox not exists"); } if (!mailbox.IsTeamlabMailbox) { throw new ArgumentException("Invalid mailbox type"); } var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant); var alias = serverAddressDao.Get(addressId); if (!alias.IsAlias) { throw new ArgumentException("Address is not alias"); } var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant); var serverDomain = serverDomainDao.GetDomain(alias.DomainId); if (serverDomain == null) { throw new ArgumentException("Domain not exists"); } var aliasEmail = string.Format("{0}@{1}", alias.AddressName, serverDomain.Name); var serverDao = daoFactory.CreateServerDao(); var server = serverDao.Get(Tenant); var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString); using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted)) { serverAddressDao.Delete(addressId); engine.RemoveAlias(aliasEmail); tx.Commit(); } CacheEngine.Clear(mailbox.User); } }
public ServerDomainAddressData AddAlias(int mailboxId, string aliasName) { if (!IsAdmin) { throw new SecurityException("Need admin privileges."); } if (string.IsNullOrEmpty(aliasName)) { throw new ArgumentException(@"Invalid alias name.", "aliasName"); } if (mailboxId < 0) { throw new ArgumentException(@"Invalid mailbox id.", "mailboxId"); } if (aliasName.Length > 64) { throw new ArgumentException(@"Local part of mailbox alias exceed limitation of 64 characters.", "aliasName"); } if (!Parser.IsEmailLocalPartValid(aliasName)) { throw new ArgumentException("Incorrect mailbox alias."); } var mailboxAliasName = aliasName.ToLowerInvariant(); using (var daoFactory = new DaoFactory()) { var mailboxDao = daoFactory.CreateMailboxDao(); var mailbox = mailboxDao.GetMailBox(new ConcreteTenantMailboxExp(mailboxId, Tenant)); if (mailbox == null) { throw new ArgumentException("Mailbox not exists"); } if (!mailbox.IsTeamlabMailbox) { throw new ArgumentException("Invalid mailbox type"); } if (mailbox.Tenant == Defines.SHARED_TENANT_ID) { throw new InvalidOperationException("Adding mailbox alias is not allowed for shared domain."); } var mailAddress = new MailAddress(mailbox.Address); var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant); var serverDomain = serverDomainDao.GetDomains().FirstOrDefault(d => d.Name == mailAddress.Host); if (serverDomain == null) { throw new ArgumentException("Domain not exists"); } var mailboxAddress = mailAddress.Address; var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant); if (serverAddressDao.IsAddressAlreadyRegistered(mailboxAliasName, serverDomain.Name)) { throw new DuplicateNameException("You want to create a mailbox with already existing address."); } var utcNow = DateTime.UtcNow; var address = new ServerAddress { Id = 0, Tenant = Tenant, MailboxId = mailbox.Id, DomainId = serverDomain.Id, AddressName = mailboxAliasName, IsAlias = true, IsMailGroup = false, DateCreated = utcNow }; var aliasEmail = string.Format("{0}@{1}", mailboxAliasName, serverDomain.Name); var serverDao = daoFactory.CreateServerDao(); var server = serverDao.Get(Tenant); var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString); using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted)) { address.Id = serverAddressDao.Save(address); var serverAddress = new Alias { Name = mailbox.Name, Address = aliasEmail, GoTo = mailboxAddress, Domain = serverDomain.Name, IsActive = true, IsGroup = false, Modified = utcNow, Created = utcNow }; engine.SaveAlias(serverAddress); tx.Commit(); } CacheEngine.Clear(mailbox.User); return(new ServerDomainAddressData { Id = address.Id, DomainId = address.DomainId, Email = aliasEmail }); } }
public ServerMailboxData UpdateMailboxDisplayName(int mailboxId, string name) { using (var daoFactory = new DaoFactory()) { var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant); var serverMailboxAddresses = serverAddressDao.GetList(mailboxId); if (!serverMailboxAddresses.Any()) { throw new ArgumentException("Mailbox not found"); } var serverMailboxAddress = serverMailboxAddresses.FirstOrDefault(a => !a.IsAlias && !a.IsMailGroup); if (serverMailboxAddress == null) { throw new ArgumentException("Mailbox not found"); } var serverMailboxAliases = serverMailboxAddresses.Where(a => a.IsAlias).ToList(); var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant); var serverDomain = serverDomainDao.GetDomain(serverMailboxAddress.DomainId); var isSharedDomain = serverDomain.Tenant == Defines.SHARED_TENANT_ID; if (!IsAdmin && !isSharedDomain) { throw new SecurityException("Need admin privileges."); } var tenantQuota = CoreContext.TenantManager.GetTenantQuota(Tenant); if (isSharedDomain && (tenantQuota.Trial || tenantQuota.Free)) { throw new SecurityException("Not available in unpaid version"); } if (name.Length > 255) { throw new ArgumentException(@"Sender name exceed limitation of 64 characters.", "name"); } var mailboxDao = daoFactory.CreateMailboxDao(); var serverMailbox = mailboxDao.GetMailBox(new ConcreteTenantServerMailboxExp(mailboxId, Tenant, false)); serverMailbox.Name = name; mailboxDao.SaveMailBox(serverMailbox); CacheEngine.Clear(serverMailbox.User); var address = ToServerDomainAddressData(serverMailboxAddress, serverDomain); var aliases = serverMailboxAliases.ConvertAll(a => ToServerDomainAddressData(a, serverDomain)); var mailboxData = ToMailboxData(serverMailbox, address, aliases); return(mailboxData); } }
public ServerMailboxData CreateMailbox(string name, string localPart, int domainId, string userId) { ServerMailboxData mailboxData; using (var daoFactory = new DaoFactory()) { var serverDomainDao = daoFactory.CreateServerDomainDao(Tenant); var serverDomain = serverDomainDao.GetDomain(domainId); var isSharedDomain = serverDomain.Tenant == Defines.SHARED_TENANT_ID; if (!IsAdmin && !isSharedDomain) { throw new SecurityException("Need admin privileges."); } var tenantQuota = CoreContext.TenantManager.GetTenantQuota(Tenant); if (isSharedDomain && (tenantQuota.Trial || tenantQuota.Free)) { throw new SecurityException("Not available in unpaid version"); } if (string.IsNullOrEmpty(localPart)) { throw new ArgumentException(@"Invalid local part.", "localPart"); } if (domainId < 0) { throw new ArgumentException(@"Invalid domain id.", "domainId"); } if (name.Length > 255) { throw new ArgumentException(@"Sender name exceed limitation of 64 characters.", "name"); } Guid user; if (!Guid.TryParse(userId, out user)) { throw new ArgumentException(@"Invalid user id.", "userId"); } if (isSharedDomain && !IsAdmin && user != SecurityContext.CurrentAccount.ID) { throw new SecurityException( "Creation of a shared mailbox is allowed only for the current account if user is not admin."); } var teamlabAccount = CoreContext.Authentication.GetAccountByID(user); if (teamlabAccount == null) { throw new InvalidDataException("Unknown user."); } var userInfo = CoreContext.UserManager.GetUsers(user); if (userInfo.IsVisitor()) { throw new InvalidDataException("User is visitor."); } if (localPart.Length > 64) { throw new ArgumentException(@"Local part of mailbox exceed limitation of 64 characters.", "localPart"); } if (!Parser.IsEmailLocalPartValid(localPart)) { throw new ArgumentException("Incorrect local part of mailbox."); } var serverAddressDao = daoFactory.CreateServerAddressDao(Tenant); if (serverAddressDao.IsAddressAlreadyRegistered(localPart, serverDomain.Name)) { throw new DuplicateNameException("You want to create a mailbox with already existing address."); } if (Defines.ServerDomainMailboxPerUserLimit > 0) { var engineFactory = new EngineFactory(Tenant, userId); var accounts = engineFactory.AccountEngine.GetAccountInfoList(); var countDomainMailboxes = accounts.Count(a => a.IsTeamlabMailbox && Parser.ParseAddress(a.Email) .Domain.Equals(serverDomain.Name, StringComparison.InvariantCultureIgnoreCase)); if (countDomainMailboxes >= Defines.ServerDomainMailboxPerUserLimit) { throw new ArgumentOutOfRangeException( string.Format("Count of user's mailboxes must be less or equal {0}.", Defines.ServerDomainMailboxPerUserLimit)); } } var serverDao = daoFactory.CreateServerDao(); var server = serverDao.Get(Tenant); var mailboxLocalPart = localPart.ToLowerInvariant(); var login = string.Format("{0}@{1}", mailboxLocalPart, serverDomain.Name); var password = PasswordGenerator.GenerateNewPassword(12); var utcNow = DateTime.UtcNow; var mailboxDao = daoFactory.CreateMailboxDao(); using (var tx = daoFactory.DbManager.BeginTransaction(IsolationLevel.ReadUncommitted)) { var mailbox = new Mailbox { Id = 0, Tenant = Tenant, User = userId, Name = name, Address = login, OAuthToken = null, OAuthType = (int)AuthorizationServiceType.None, ServerId = server.ImapSettingsId, Password = password, SmtpServerId = server.SmtpSettingsId, SmtpPassword = password, SizeLast = 0, MsgCountLast = 0, BeginDate = Defines.MinBeginDate, Imap = true, Enabled = true, IsTeamlabMailbox = true, IsRemoved = false, DateCreated = utcNow }; mailbox.Id = mailboxDao.SaveMailBox(mailbox); var address = new ServerAddress { Id = 0, Tenant = Tenant, MailboxId = mailbox.Id, DomainId = serverDomain.Id, AddressName = localPart, IsAlias = false, IsMailGroup = false, DateCreated = utcNow }; address.Id = serverAddressDao.Save(address); var engine = new Server.Core.ServerEngine(server.Id, server.ConnectionString); var maildir = PostfixMaildirUtil.GenerateMaildirPath(serverDomain.Name, localPart, utcNow); var serverMailbox = new Server.Core.Entities.Mailbox { Name = name, Password = password, Login = login, LocalPart = localPart, Domain = serverDomain.Name, Active = true, Quota = 0, Maldir = maildir, Modified = utcNow, Created = utcNow, }; var serverAddress = new Alias { Name = name, Address = login, GoTo = login, Domain = serverDomain.Name, IsActive = true, IsGroup = false, Modified = utcNow, Created = utcNow }; engine.SaveMailbox(serverMailbox, serverAddress); tx.Commit(); CacheEngine.Clear(userId); mailboxData = ToMailboxData(mailbox, ToServerDomainAddressData(address, login), new List <ServerDomainAddressData>()); } } return(mailboxData); }