EmailStorageProcessor.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. using Quadarax.Application.TemporarySharedStorage.Client.Dtos.Request;
  2. using Quadarax.Application.TemporarySharedStorage.Client.Services;
  3. using Quadarax.Foundation.Core.Logging;
  4. using System.IO.Abstractions;
  5. using System.IO.Compression;
  6. using System.Net.Mail;
  7. using System.Text.Json;
  8. using System.Text.RegularExpressions;
  9. namespace qdr.app.studiou.orders2printpack.EmailStorage
  10. {
  11. /// <summary>
  12. /// Delegate for handling email item state change events.
  13. /// Allows subscribers to track processing progress and state transitions.
  14. /// </summary>
  15. /// <param name="sender">The processor instance that triggered the event</param>
  16. /// <param name="recipient">Email address of the recipient being processed</param>
  17. /// <param name="status">New state of the email item</param>
  18. /// <param name="progress">Progress percentage (0-100)</param>
  19. public delegate void EmailItemStateChangeHandler(object sender, string recipient, EmailStateEnum status, int progress);
  20. /// <summary>
  21. /// Main processor class responsible for handling the complete email workflow:
  22. /// 1. Scanning directories for photo files
  23. /// 2. Compressing files into ZIP archives
  24. /// 3. Uploading to Temporary Shared Storage
  25. /// 4. Sending personalized emails with download links
  26. /// 5. Managing file lifecycle and cleanup
  27. ///
  28. /// This class implements IDisposable to properly clean up resources like SMTP connections.
  29. /// </summary>
  30. public class EmailStorageProcessor : IDisposable
  31. {
  32. #region *** Private fields ***
  33. /// <summary>
  34. /// Base input directory where recipient folders containing JPG files are located
  35. /// </summary>
  36. private readonly string _inputPath;
  37. /// <summary>
  38. /// Email template used for generating personalized emails
  39. /// </summary>
  40. private readonly EmailTemplate _emailTemplate;
  41. /// <summary>
  42. /// Configuration containing API keys, SMTP settings, and other operational parameters
  43. /// </summary>
  44. private readonly EmailProcessorConfiguration _configuration;
  45. /// <summary>
  46. /// Logger instance for this processor
  47. /// </summary>
  48. private readonly ILogger _logger;
  49. /// <summary>
  50. /// Typed log instance for structured logging
  51. /// </summary>
  52. private readonly ILog _log;
  53. /// <summary>
  54. /// File system abstraction for testable file operations
  55. /// </summary>
  56. private readonly IFileSystem _fileSystem;
  57. /// <summary>
  58. /// Service for uploading files to Temporary Shared Storage
  59. /// </summary>
  60. private readonly FileUploadService _uploadService;
  61. /// <summary>
  62. /// SMTP client for sending emails to recipients
  63. /// </summary>
  64. private readonly SmtpClient _smtpClient;
  65. /// <summary>
  66. /// Cancellation token source for graceful shutdown of processing operations
  67. /// </summary>
  68. private CancellationTokenSource _cancellationTokenSource;
  69. /// <summary>
  70. /// Lock object for thread-safe metadata file operations
  71. /// </summary>
  72. private readonly object _metadataLock = new object();
  73. /// <summary>
  74. /// Flag to track if this instance has been disposed
  75. /// </summary>
  76. private bool _disposed = false;
  77. // Required directory paths for file management
  78. /// <summary>
  79. /// Directory for files currently being processed (compressed but not yet uploaded)
  80. /// </summary>
  81. private readonly string _processingDir;
  82. /// <summary>
  83. /// Directory for files ready to be sent (uploaded and email being sent)
  84. /// </summary>
  85. private readonly string _sendingDir;
  86. /// <summary>
  87. /// Directory for files that have been successfully sent
  88. /// </summary>
  89. private readonly string _sentDir;
  90. /// <summary>
  91. /// Path to the metadata.json file that tracks all processing state
  92. /// </summary>
  93. private readonly string _metadataFile;
  94. #endregion
  95. #region *** Properties ***
  96. /// <summary>
  97. /// Current metadata containing all email items and their processing state
  98. /// </summary>
  99. public Metadata Metadata { get; set; } = new Metadata();
  100. /// <summary>
  101. /// Total number of email items being tracked
  102. /// </summary>
  103. public int CountTotal => Metadata.Items.Count;
  104. /// <summary>
  105. /// Number of items currently being processed or uploaded
  106. /// </summary>
  107. public int CountProcessing => Metadata.Items.Count(x => x.State == EmailStateEnum.Processing || x.State == EmailStateEnum.Uploading);
  108. /// <summary>
  109. /// Number of items currently being sent (email transmission in progress)
  110. /// </summary>
  111. public int CountSending => Metadata.Items.Count(x => x.State == EmailStateEnum.Sending);
  112. /// <summary>
  113. /// Number of items that have been successfully sent
  114. /// </summary>
  115. public int CountSent => Metadata.Items.Count(x => x.State == EmailStateEnum.Sent);
  116. #endregion
  117. #region *** Events ***
  118. /// <summary>
  119. /// Event fired when an email item's state changes during processing.
  120. /// Useful for UI updates, progress tracking, and monitoring.
  121. /// </summary>
  122. public event EmailItemStateChangeHandler? EmailItemStateChanged;
  123. #endregion
  124. #region *** Constructor ***
  125. /// <summary>
  126. /// Initializes a new instance of the EmailStorageProcessor.
  127. /// Sets up all required services, directory structure, and loads existing metadata.
  128. /// </summary>
  129. /// <param name="fs">File system abstraction for file operations</param>
  130. /// <param name="path">Base path where recipient directories are located</param>
  131. /// <param name="emailTemplate">Template for generating personalized emails</param>
  132. /// <param name="configuration">Configuration with API keys and SMTP settings</param>
  133. /// <param name="logger">Logger for operational logging</param>
  134. /// <exception cref="ArgumentNullException">Thrown when any required parameter is null</exception>
  135. public EmailStorageProcessor(IFileSystem fs, string path, EmailTemplate emailTemplate, EmailProcessorConfiguration configuration, ILogger logger)
  136. {
  137. // Validate all required dependencies
  138. _fileSystem = fs ?? throw new ArgumentNullException(nameof(fs));
  139. _inputPath = path ?? throw new ArgumentNullException(nameof(path));
  140. _emailTemplate = emailTemplate ?? throw new ArgumentNullException(nameof(emailTemplate));
  141. _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
  142. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  143. // Initialize logging
  144. _log = _logger.GetLogger(typeof(EmailStorageProcessor));
  145. _cancellationTokenSource = new CancellationTokenSource();
  146. // Setup directory paths using IFileSystem for testability
  147. _processingDir = _fileSystem.Path.Combine(_inputPath, ".processing");
  148. _sendingDir = _fileSystem.Path.Combine(_inputPath, ".sending");
  149. _sentDir = _fileSystem.Path.Combine(_inputPath, ".sent");
  150. _metadataFile = _fileSystem.Path.Combine(_inputPath, "metadata.json");
  151. // Initialize external services
  152. _uploadService = new FileUploadService(configuration.TssUrl, configuration.TssAPIKey, logger);
  153. // Setup SMTP client with provided configuration
  154. _smtpClient = new SmtpClient(configuration.SmtpServer, configuration.SmtpServerPort)
  155. {
  156. Credentials = new System.Net.NetworkCredential(configuration.SmtpServerUser, configuration.SmtpServerPassword),
  157. EnableSsl = configuration.SmtpEnableSsl
  158. };
  159. // Initialize the processing environment
  160. InitializeDirectoryStructure();
  161. LoadOrCreateMetadata();
  162. }
  163. #endregion
  164. #region *** Public Methods ***
  165. /// <summary>
  166. /// Processes a single email item through the complete workflow:
  167. /// 1. Compress JPG files into ZIP archive
  168. /// 2. Upload to Temporary Shared Storage
  169. /// 3. Generate personalized email with download link
  170. /// 4. Send email to recipient
  171. /// 5. Move files to appropriate directory based on success/failure
  172. /// </summary>
  173. /// <param name="recipient">Email address of the recipient to process</param>
  174. public async Task ProcessItemAsync(string recipient)
  175. {
  176. try
  177. {
  178. // Find the metadata item for this recipient
  179. var item = Metadata.Items.FirstOrDefault(x => x.EmailAddress == recipient);
  180. if (item == null)
  181. {
  182. _log.Log(LogSeverityEnum.Error, $"Item with recipient '{recipient}' not found.");
  183. return;
  184. }
  185. _log.Log(LogSeverityEnum.Info, $"Starting processing for recipient: {recipient}");
  186. // Execute the complete workflow
  187. await CompressFilesAsync(item); // Step 1: Create ZIP archive
  188. await UploadCompressedFileAsync(item); // Step 2: Upload to TSS
  189. await PrepareEmailAndMoveAsync(item); // Step 3: Prepare email content
  190. await SendEmailAsync(item); // Step 4: Send email
  191. await HandleSendingResultAsync(item, true); // Step 5: Handle success
  192. _log.Log(LogSeverityEnum.Info, $"Successfully processed recipient: {recipient}");
  193. }
  194. catch (Exception ex)
  195. {
  196. // Log error and mark item as failed
  197. _log.Log(LogSeverityEnum.Error, $"Error processing recipient '{recipient}': {ex.Message}");
  198. var item = Metadata.Items.FirstOrDefault(x => x.EmailAddress == recipient);
  199. if (item != null)
  200. {
  201. item.ErrorMessage = ex.Message;
  202. await HandleSendingResultAsync(item, false);
  203. }
  204. }
  205. }
  206. /// <summary>
  207. /// Processes all email items that are in Ready state sequentially.
  208. /// Can be cancelled using the Stop() method which sets the cancellation token.
  209. /// </summary>
  210. public async Task ProcessAllAsync()
  211. {
  212. // Get all items that are ready for processing
  213. var readyItems = Metadata.Items.Where(x => x.State == EmailStateEnum.Ready).ToList();
  214. foreach (var item in readyItems)
  215. {
  216. // Check for cancellation request
  217. if (_cancellationTokenSource.Token.IsCancellationRequested)
  218. break;
  219. await ProcessItemAsync(item.EmailAddress);
  220. }
  221. }
  222. /// <summary>
  223. /// Resets an email item back to Ready state and cleans up associated files.
  224. /// This allows reprocessing of items that failed or need to be sent again.
  225. /// Items cannot be reset while actively being processed or uploaded.
  226. /// </summary>
  227. /// <param name="recipient">Email address of the recipient to reset</param>
  228. public void ResetItem(string recipient)
  229. {
  230. try
  231. {
  232. var item = Metadata.Items.FirstOrDefault(x => x.EmailAddress == recipient);
  233. if (item == null)
  234. {
  235. _log.Log(LogSeverityEnum.Warn, $"Item with recipient '{recipient}' not found for reset.");
  236. return;
  237. }
  238. // Clean up any existing processed files
  239. CleanupItemFiles(item);
  240. // Reset all processing-related fields to initial state
  241. item.State = EmailStateEnum.Ready;
  242. item.FileNameAttachment = string.Empty;
  243. item.SizeAttachment = 0;
  244. item.UploadPermalink = string.Empty;
  245. item.DownloadPassword = string.Empty;
  246. item.ProcessedDate = null;
  247. item.SentDate = null;
  248. item.ErrorMessage = null;
  249. // Notify listeners and save changes
  250. UpdateItemState(item, EmailStateEnum.Ready, 0);
  251. SaveMetadata();
  252. _log.Log(LogSeverityEnum.Info, $"Reset item for recipient: {recipient}");
  253. }
  254. catch (Exception ex)
  255. {
  256. _log.Log(LogSeverityEnum.Error, $"Error resetting item for recipient '{recipient}': {ex.Message}");
  257. }
  258. }
  259. /// <summary>
  260. /// Gracefully stops all processing operations by setting the cancellation token.
  261. /// Currently running operations will complete, but no new ones will start.
  262. /// </summary>
  263. public void Stop()
  264. {
  265. _cancellationTokenSource?.Cancel();
  266. _log.Log(LogSeverityEnum.Info, "Processing stop requested.");
  267. }
  268. #endregion
  269. #region Private Methods
  270. /// <summary>
  271. /// Creates the required directory structure for file management.
  272. /// Sets up .processing, .sending, and .sent directories if they don't exist.
  273. /// </summary>
  274. private void InitializeDirectoryStructure()
  275. {
  276. try
  277. {
  278. _fileSystem.Directory.CreateDirectory(_processingDir);
  279. _fileSystem.Directory.CreateDirectory(_sendingDir);
  280. _fileSystem.Directory.CreateDirectory(_sentDir);
  281. _log.Log(LogSeverityEnum.Info, "Directory structure initialized.");
  282. }
  283. catch (Exception ex)
  284. {
  285. _log.Log(LogSeverityEnum.Error, $"Error initializing directory structure: {ex.Message}");
  286. throw;
  287. }
  288. }
  289. /// <summary>
  290. /// Loads existing metadata from metadata.json file or creates new metadata structure.
  291. /// After loading, scans the input directory for new or changed recipient folders.
  292. /// </summary>
  293. private void LoadOrCreateMetadata()
  294. {
  295. try
  296. {
  297. lock (_metadataLock)
  298. {
  299. if (_fileSystem.File.Exists(_metadataFile))
  300. {
  301. // Load existing metadata from file
  302. var json = _fileSystem.File.ReadAllText(_metadataFile);
  303. Metadata = JsonSerializer.Deserialize<Metadata>(json) ?? new Metadata();
  304. _log.Log(LogSeverityEnum.Info, "Metadata loaded from file.");
  305. }
  306. else
  307. {
  308. // Create new metadata structure
  309. Metadata = new Metadata();
  310. _log.Log(LogSeverityEnum.Info, "New metadata created.");
  311. }
  312. // Scan directories and update metadata with current state
  313. ScanAndUpdateMetadata();
  314. }
  315. }
  316. catch (Exception ex)
  317. {
  318. _log.Log(LogSeverityEnum.Error, $"Error loading/creating metadata: {ex.Message}");
  319. Metadata = new Metadata();
  320. }
  321. }
  322. /// <summary>
  323. /// Scans the input directory for recipient folders and updates metadata accordingly.
  324. /// - Adds new items for newly discovered directories
  325. /// - Updates file counts and order information for existing items
  326. /// - Removes items for directories that no longer exist
  327. /// </summary>
  328. private void ScanAndUpdateMetadata()
  329. {
  330. try
  331. {
  332. // Get all directories that don't start with "." (hidden/system directories)
  333. var directories = _fileSystem.Directory.GetDirectories(_inputPath)
  334. .Where(d => !_fileSystem.Path.GetFileName(d).StartsWith("."))
  335. .ToList();
  336. foreach (var dir in directories)
  337. {
  338. var dirName = _fileSystem.Path.GetFileName(dir);
  339. var emailAddress = dirName; // Assume directory name is the email address
  340. var existingItem = Metadata.Items.FirstOrDefault(x => x.DirectoryName == dirName);
  341. if (existingItem == null)
  342. {
  343. // Create new metadata item for this directory
  344. var newItem = CreateMetadataItem(dir, dirName, emailAddress);
  345. Metadata.Items.Add(newItem);
  346. _log.Log(LogSeverityEnum.Info, $"Added new item for directory: {dirName}");
  347. }
  348. else
  349. {
  350. // Update existing item with current file information
  351. UpdateMetadataItem(existingItem, dir);
  352. }
  353. }
  354. // Clean up metadata for directories that no longer exist
  355. var existingDirs = directories.Select(d => _fileSystem.Path.GetFileName(d)).ToHashSet();
  356. Metadata.Items.RemoveAll(item => !existingDirs.Contains(item.DirectoryName));
  357. // Save updated metadata
  358. Metadata.Modified = DateTime.Now;
  359. SaveMetadata();
  360. }
  361. catch (Exception ex)
  362. {
  363. _log.Log(LogSeverityEnum.Error, $"Error scanning and updating metadata: {ex.Message}");
  364. }
  365. }
  366. /// <summary>
  367. /// Creates a new MetadataItem for a discovered directory.
  368. /// Scans JPG files and extracts order numbers from filenames.
  369. /// </summary>
  370. /// <param name="directoryPath">Full path to the directory</param>
  371. /// <param name="dirName">Directory name (typically email address)</param>
  372. /// <param name="emailAddress">Email address for this item</param>
  373. /// <returns>Newly created MetadataItem</returns>
  374. private MetadataItem CreateMetadataItem(string directoryPath, string dirName, string emailAddress)
  375. {
  376. var jpgFiles = _fileSystem.Directory.GetFiles(directoryPath, "*.jpg");
  377. var orders = ExtractOrderNumbers(jpgFiles);
  378. return new MetadataItem
  379. {
  380. DirectoryName = dirName,
  381. EmailAddress = emailAddress,
  382. State = EmailStateEnum.Ready,
  383. Subject = _emailTemplate.Subject,
  384. Body = _emailTemplate.Body,
  385. InternalFilesCount = jpgFiles.Length,
  386. Orders = string.Join(",", orders.OrderBy(x => x))
  387. };
  388. }
  389. /// <summary>
  390. /// Updates an existing MetadataItem with current file information.
  391. /// Refreshes file count and order numbers without changing processing state.
  392. /// </summary>
  393. /// <param name="item">Existing metadata item to update</param>
  394. /// <param name="directoryPath">Path to the directory to scan</param>
  395. private void UpdateMetadataItem(MetadataItem item, string directoryPath)
  396. {
  397. var jpgFiles = _fileSystem.Directory.GetFiles(directoryPath, "*.jpg");
  398. var orders = ExtractOrderNumbers(jpgFiles);
  399. item.InternalFilesCount = jpgFiles.Length;
  400. item.Orders = string.Join(",", orders.OrderBy(x => x));
  401. }
  402. /// <summary>
  403. /// Extracts order numbers from JPG filenames using regex pattern matching.
  404. /// Expects filenames in format: "{orderNumber}_{description}.jpg"
  405. /// Example: "1001_photo1.jpg" extracts order "1001"
  406. /// </summary>
  407. /// <param name="filePaths">Array of file paths to process</param>
  408. /// <returns>List of unique order numbers found</returns>
  409. private List<string> ExtractOrderNumbers(string[] filePaths)
  410. {
  411. var orders = new List<string>();
  412. var pattern = @"^(\d+)_.*\.jpg$"; // Match: digits_anything.jpg
  413. foreach (var filePath in filePaths)
  414. {
  415. var fileName = _fileSystem.Path.GetFileName(filePath);
  416. var match = Regex.Match(fileName, pattern);
  417. if (match.Success)
  418. {
  419. orders.Add(match.Groups[1].Value);
  420. }
  421. }
  422. return orders.Distinct().ToList();
  423. }
  424. /// <summary>
  425. /// Compresses all JPG files in the item's directory into a ZIP archive.
  426. /// Updates processing state and progress throughout the operation.
  427. /// Generated ZIP filename includes normalized recipient and timestamp.
  428. /// </summary>
  429. /// <param name="item">Metadata item to process</param>
  430. private async Task CompressFilesAsync(MetadataItem item)
  431. {
  432. UpdateItemState(item, EmailStateEnum.Processing, 10);
  433. var sourceDir = _fileSystem.Path.Combine(_inputPath, item.DirectoryName);
  434. var normalizedRecipient = NormalizeRecipientForFileName(item.EmailAddress);
  435. var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
  436. var zipFileName = $"studioufoto_{normalizedRecipient}_{timestamp}.zip";
  437. var zipPath = _fileSystem.Path.Combine(_processingDir, zipFileName);
  438. try
  439. {
  440. var jpgFiles = _fileSystem.Directory.GetFiles(sourceDir, "*.jpg");
  441. // Create ZIP archive using FileSystem abstraction for testability
  442. using (var zipFileStream = _fileSystem.File.Create(zipPath))
  443. using (var zip = new ZipArchive(zipFileStream, ZipArchiveMode.Create))
  444. {
  445. for (int i = 0; i < jpgFiles.Length; i++)
  446. {
  447. var file = jpgFiles[i];
  448. var entryName = _fileSystem.Path.GetFileName(file);
  449. var entry = zip.CreateEntry(entryName);
  450. // Copy file content to ZIP entry
  451. using (var entryStream = entry.Open())
  452. using (var fileStream = _fileSystem.File.OpenRead(file))
  453. {
  454. await fileStream.CopyToAsync(entryStream);
  455. }
  456. // Update progress (10-40% for compression phase)
  457. var progress = 10 + (int)((i + 1.0) / jpgFiles.Length * 30);
  458. UpdateItemState(item, EmailStateEnum.Processing, progress);
  459. }
  460. }
  461. // Update metadata with compression results
  462. var fileInfo = _fileSystem.FileInfo.New(zipPath);
  463. item.FileNameAttachment = zipFileName;
  464. item.SizeAttachment = (int)fileInfo.Length;
  465. item.ProcessedDate = DateTime.Now;
  466. SaveMetadata();
  467. _log.Log(LogSeverityEnum.Info, $"Compressed {jpgFiles.Length} files to: {zipFileName}");
  468. }
  469. catch (Exception ex)
  470. {
  471. _log.Log(LogSeverityEnum.Error, $"Error compressing files for {item.EmailAddress}: {ex.Message}");
  472. throw;
  473. }
  474. }
  475. /// <summary>
  476. /// Uploads the compressed ZIP file to Temporary Shared Storage service.
  477. /// Generates download password and retrieves permalink for recipient access.
  478. /// </summary>
  479. /// <param name="item">Metadata item with compressed file to upload</param>
  480. private async Task UploadCompressedFileAsync(MetadataItem item)
  481. {
  482. UpdateItemState(item, EmailStateEnum.Uploading, 50);
  483. var zipPath = _fileSystem.Path.Combine(_processingDir, item.FileNameAttachment);
  484. try
  485. {
  486. // Prepare upload request with file details and security settings
  487. var uploadRequest = new UploadFileRequest
  488. {
  489. FilePath = zipPath,
  490. Description = $"Studio photos for {item.EmailAddress}",
  491. Password = GenerateDownloadPassword(),
  492. Message = "Studio photos ready for download",
  493. Reference = $"STUDIO_{NormalizeRecipientForFileName(item.EmailAddress)}",
  494. ActiveFrom = DateTime.Now,
  495. ActiveTo = DateTime.Now.AddDays(30), // 30-day expiration
  496. ChunkSize = 1048576 // 1MB chunks for reliable upload
  497. };
  498. // Execute upload and capture result
  499. var result = await _uploadService.UploadFileAsync(uploadRequest);
  500. // Store upload results in metadata
  501. item.UploadPermalink = result.Item1;
  502. item.DownloadPassword = uploadRequest.Password;
  503. UpdateItemState(item, EmailStateEnum.Uploading, 80);
  504. SaveMetadata();
  505. _log.Log(LogSeverityEnum.Info, $"Successfully uploaded file for {item.EmailAddress}. Permalink: {result.Item1}");
  506. }
  507. catch (Exception ex)
  508. {
  509. _log.Log(LogSeverityEnum.Error, $"Error uploading file for {item.EmailAddress}: {ex.Message}");
  510. throw;
  511. }
  512. }
  513. /// <summary>
  514. /// Personalizes the email template with recipient-specific information and
  515. /// moves the ZIP file from processing to sending directory.
  516. /// Replaces template placeholders with actual values.
  517. /// </summary>
  518. /// <param name="item">Metadata item to prepare for sending</param>
  519. private async Task PrepareEmailAndMoveAsync(MetadataItem item)
  520. {
  521. try
  522. {
  523. // Personalize email body by replacing template placeholders
  524. var personalizedBody = _emailTemplate.Body
  525. .Replace("{{DOWNLOAD_LINK}}", item.UploadPermalink)
  526. .Replace("{{PASSWORD}}", item.DownloadPassword)
  527. .Replace("{{RECIPIENT}}", item.EmailAddress)
  528. .Replace("{{ORDERS}}", item.Orders);
  529. item.Body = personalizedBody;
  530. // Move ZIP file from processing to sending directory
  531. var sourceFile = _fileSystem.Path.Combine(_processingDir, item.FileNameAttachment);
  532. var targetFile = _fileSystem.Path.Combine(_sendingDir, item.FileNameAttachment);
  533. if (_fileSystem.File.Exists(sourceFile))
  534. {
  535. _fileSystem.File.Move(sourceFile, targetFile);
  536. }
  537. UpdateItemState(item, EmailStateEnum.Sending, 90);
  538. SaveMetadata();
  539. _log.Log(LogSeverityEnum.Info, $"Prepared email and moved file to sending for {item.EmailAddress}");
  540. }
  541. catch (Exception ex)
  542. {
  543. _log.Log(LogSeverityEnum.Error, $"Error preparing email for {item.EmailAddress}: {ex.Message}");
  544. throw;
  545. }
  546. }
  547. /// <summary>
  548. /// Sends the personalized email to the recipient using SMTP.
  549. /// Email contains download link, password, and order information.
  550. /// </summary>
  551. /// <param name="item">Metadata item with email details to send</param>
  552. private async Task SendEmailAsync(MetadataItem item)
  553. {
  554. try
  555. {
  556. using (var message = new MailMessage())
  557. {
  558. message.To.Add(item.EmailAddress);
  559. message.Subject = item.Subject;
  560. message.Body = item.Body;
  561. message.IsBodyHtml = true; // Support HTML formatting in email body
  562. await _smtpClient.SendMailAsync(message);
  563. }
  564. item.SentDate = DateTime.Now;
  565. _log.Log(LogSeverityEnum.Info, $"Email sent successfully to {item.EmailAddress}");
  566. }
  567. catch (Exception ex)
  568. {
  569. _log.Log(LogSeverityEnum.Error, $"Error sending email to {item.EmailAddress}: {ex.Message}");
  570. throw;
  571. }
  572. }
  573. /// <summary>
  574. /// Handles the final result of email sending operation.
  575. /// Moves files to appropriate directory and updates item state based on success/failure.
  576. /// </summary>
  577. /// <param name="item">Metadata item that was processed</param>
  578. /// <param name="success">Whether the entire process completed successfully</param>
  579. private async Task HandleSendingResultAsync(MetadataItem item, bool success)
  580. {
  581. try
  582. {
  583. var sourceFile = _fileSystem.Path.Combine(_sendingDir, item.FileNameAttachment);
  584. if (success)
  585. {
  586. // Move to sent folder for successful completions
  587. var targetFile = _fileSystem.Path.Combine(_sentDir, item.FileNameAttachment);
  588. if (_fileSystem.File.Exists(sourceFile))
  589. {
  590. _fileSystem.File.Move(sourceFile, targetFile);
  591. }
  592. UpdateItemState(item, EmailStateEnum.Sent, 100);
  593. _log.Log(LogSeverityEnum.Info, $"Successfully completed processing for {item.EmailAddress}");
  594. }
  595. else
  596. {
  597. // Keep in sending folder for failed attempts, set error state
  598. UpdateItemState(item, EmailStateEnum.Error, 0);
  599. _log.Log(LogSeverityEnum.Error, $"Failed to complete processing for {item.EmailAddress}");
  600. }
  601. SaveMetadata();
  602. }
  603. catch (Exception ex)
  604. {
  605. _log.Log(LogSeverityEnum.Error, $"Error handling sending result for {item.EmailAddress}: {ex.Message}");
  606. }
  607. }
  608. /// <summary>
  609. /// Updates an item's state and fires the state change event for subscribers.
  610. /// Provides a centralized way to track state transitions.
  611. /// </summary>
  612. /// <param name="item">Item whose state is changing</param>
  613. /// <param name="state">New state value</param>
  614. /// <param name="progress">Progress percentage (0-100)</param>
  615. private void UpdateItemState(MetadataItem item, EmailStateEnum state, int progress)
  616. {
  617. item.State = state;
  618. EmailItemStateChanged?.Invoke(this, item.EmailAddress, state, progress);
  619. }
  620. /// <summary>
  621. /// Saves the current metadata to the metadata.json file in a thread-safe manner.
  622. /// Updates the modification timestamp and formats JSON for readability.
  623. /// </summary>
  624. private void SaveMetadata()
  625. {
  626. try
  627. {
  628. lock (_metadataLock)
  629. {
  630. Metadata.Modified = DateTime.Now;
  631. var json = JsonSerializer.Serialize(Metadata, new JsonSerializerOptions
  632. {
  633. WriteIndented = true // Pretty-print for human readability
  634. });
  635. _fileSystem.File.WriteAllText(_metadataFile, json);
  636. }
  637. }
  638. catch (Exception ex)
  639. {
  640. _log.Log(LogSeverityEnum.Error, $"Error saving metadata: {ex.Message}");
  641. }
  642. }
  643. /// <summary>
  644. /// Removes all processed files associated with an email item.
  645. /// Cleans up ZIP files from processing, sending, and sent directories.
  646. /// Used during item reset operations.
  647. /// </summary>
  648. /// <param name="item">Item whose files should be cleaned up</param>
  649. private void CleanupItemFiles(MetadataItem item)
  650. {
  651. try
  652. {
  653. var filesToClean = new[]
  654. {
  655. _fileSystem.Path.Combine(_processingDir, item.FileNameAttachment),
  656. _fileSystem.Path.Combine(_sendingDir, item.FileNameAttachment),
  657. _fileSystem.Path.Combine(_sentDir, item.FileNameAttachment)
  658. };
  659. foreach (var file in filesToClean)
  660. {
  661. if (_fileSystem.File.Exists(file))
  662. {
  663. _fileSystem.File.Delete(file);
  664. _log.Log(LogSeverityEnum.Info, $"Deleted file: {file}");
  665. }
  666. }
  667. }
  668. catch (Exception ex)
  669. {
  670. _log.Log(LogSeverityEnum.Error, $"Error cleaning up files for {item.EmailAddress}: {ex.Message}");
  671. }
  672. }
  673. /// <summary>
  674. /// Normalizes an email address for use in filenames by replacing problematic characters.
  675. /// Converts @ to _at_ and . to _dot_ to create filesystem-safe names.
  676. /// </summary>
  677. /// <param name="email">Email address to normalize</param>
  678. /// <returns>Filesystem-safe version of the email address</returns>
  679. private string NormalizeRecipientForFileName(string email)
  680. {
  681. return email.Replace("@", "_at_").Replace(".", "_dot_");
  682. }
  683. /// <summary>
  684. /// Generates a cryptographically secure random password for file downloads.
  685. /// Creates a 12-character password using uppercase, lowercase, and numeric characters.
  686. /// </summary>
  687. /// <returns>Randomly generated password string</returns>
  688. private string GenerateDownloadPassword()
  689. {
  690. var random = new Random();
  691. const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  692. return new string(Enumerable.Repeat(chars, 12)
  693. .Select(s => s[random.Next(s.Length)]).ToArray());
  694. }
  695. #endregion
  696. #region IDisposable
  697. /// <summary>
  698. /// Disposes of the processor and all managed resources.
  699. /// Implements the Dispose pattern for proper resource cleanup.
  700. /// </summary>
  701. public void Dispose()
  702. {
  703. Dispose(true);
  704. GC.SuppressFinalize(this);
  705. }
  706. /// <summary>
  707. /// Protected implementation of Dispose pattern.
  708. /// Properly disposes of cancellation token and SMTP client resources.
  709. /// </summary>
  710. /// <param name="disposing">True if disposing managed resources</param>
  711. protected virtual void Dispose(bool disposing)
  712. {
  713. if (!_disposed)
  714. {
  715. if (disposing)
  716. {
  717. // Dispose managed resources
  718. _cancellationTokenSource?.Cancel();
  719. _cancellationTokenSource?.Dispose();
  720. _smtpClient?.Dispose();
  721. }
  722. _disposed = true;
  723. }
  724. }
  725. #endregion
  726. }
  727. }