コード例 #1
0
        private IMailFolder GetOrCreateLockFolder(IMailFolder parentFolderOfLockFolder, string resourceName, CancellationToken cancellationToken = default)
        {
            var         lockFolderName = parentFolderOfLockFolder.MakeSafeFolderName(resourceName);
            IMailFolder lockFolder     = null;

            try
            {
                lockFolder = parentFolderOfLockFolder.GetSubfolder(lockFolderName, cancellationToken);
            }
            catch
            {
                logger.Information("Could not get lock folder '{LockFolderName}' - maybe it does not yet exist or there was an error", lockFolderName);
            }
            if (lockFolder == null)
            {
                try
                {
                    logger.Information("Creating new lock folder with name '{LockFolderName}'", lockFolderName);
                    // note: on some mail servers (Greenmail) this will throw if the folder already exists, other servers don't throw and return any existing foldre with this name (Dovecot)
                    lockFolder = parentFolderOfLockFolder.Create(lockFolderName, true);
                }
                catch
                {
                    logger.Information("Error while creating lock folder '{LockFolderName}' - maybe it already exists or ther was an error", lockFolderName);
                }
            }

            if (lockFolder == null)
            {
                throw new TeasmCompanionException($"Could not get or create lock folder '{lockFolderName}'");
            }

            lockFolder.Open(FolderAccess.ReadOnly);
            var existingLockMessages = lockFolder.Search(SearchQuery.SubjectContains(LockMessageSubject), cancellationToken);

            if (existingLockMessages.Count == 0)
            {
                // note: this might create duplicates if run by multiple clients; we'll remove the duplicates later
                lockFolder.Append(CreateLockMimeMessage());
                Thread.Sleep(1000); // give other parallel clients the chance to produce their duplicates if any; we then always choose the first one (selected by UniqueId)
            }

            return(lockFolder);
        }