Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added skipping for mail without attachments and already processed mail #13

Merged
merged 1 commit into from
Feb 14, 2025

Conversation

christianlouis
Copy link
Owner

@christianlouis christianlouis commented Feb 14, 2025

Summary by CodeRabbit

  • New Features

    • Emails are now tracked persistently across restarts, ensuring reliable storage of processed messages.
    • The email retrieval window has been extended to cover the past seven days, with enhanced attachment processing.
  • Improvements

    • Streamlined email polling and processing for greater consistency.
    • Enhanced error handling and automatic cleanup of outdated email records for improved system performance.

Copy link

coderabbitai bot commented Feb 14, 2025

Walkthrough

The changes update the email processing logic in imap_tasks.py by replacing an in-memory dictionary with a persistent JSON file (processed_mails.json) to track processed email IDs. New functions have been added to load, save, and clean up the stored data. The polling mechanisms have been simplified so that each mailbox is processed directly without checking intervals. Additionally, the email fetching process now retrieves emails from the last seven days and ensures emails without a Message-ID are skipped, while attachment processing now returns a boolean indicator. Comments have also been revised for clarity.

Changes

File Change Summary
app/tasks/imap_tasks.py Removed LAST_POLL_TIMES and added persistent caching using processed_mails.json. Introduced new functions: load_processed_emails, save_processed_emails, and cleanup_old_entries to manage the cache. Modified pull_all_inboxes and check_and_pull_mailbox to remove polling logic, updated pull_inbox to fetch emails from the last 7 days and skip emails lacking Message-ID, and revised fetch_attachments_and_enqueue to return a boolean.

Sequence Diagram(s)

sequenceDiagram
    participant Worker as Email Worker
    participant Cache as Processed Emails (JSON)
    participant Mailbox as Email Server

    Worker->>Cache: load_processed_emails()
    loop For Each Mailbox
        Worker->>Worker: check_and_pull_mailbox()
        Worker->>Mailbox: Fetch emails (last 7 days)
        Mailbox-->>Worker: Return emails
        alt Email has valid Message-ID
            Worker->>Worker: Process email
            Worker->>Worker: fetch_attachments_and_enqueue(email)
            Note right of Worker: Returns boolean indicating attachment found
            Worker->>Cache: save_processed_emails()
        else Email missing Message-ID
            Note over Worker: Skip processing
        end
    end
    Worker->>Cache: cleanup_old_entries()
Loading

Poem

I'm a hopping rabbit in a code-filled glade,
Nibbling on JSON carrots that never fade,
No more lost emails in a memory maze,
Now attachments jump in with a cheerful blaze,
I hop through sequences, light and free,
Celebrating changes with a joyful "Whee!" 🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (11)
app/tasks/imap_tasks.py (11)

16-17: Validate File-Storage Design
Storing processed emails in a local JSON file is a quick solution. However, be mindful of file write permissions and concurrency if multiple processes might write to this file simultaneously. Also consider environment setups where local storage may not be persistent.


20-29: Improve Error Handling
The function already handles JSON decoding errors, but file I/O exceptions (e.g., IOError) are not currently caught. Consider a broader exception handling strategy to ensure the process isn't stalled by file access issues.


32-35: Handle Save Failures
Similar to load_processed_emails, this function doesn’t handle exceptions for file access or json.dump. For robustness, wrapping in try-except could help prevent data loss or partial writes.


56-56: Consider Looping over Mailboxes
Listing mailbox #1 explicitly is fine, but if more mailboxes are added, consider iterating over them dynamically in a shared configuration list/dict to simplify future maintenance.


67-67: Reuse Mailbox Logic
Similar to mailbox #1, a loop or dictionary-based approach can reduce duplicated code.


96-104: Simplification & Potential Frequency
Removing polling intervals simplifies the logic but can increase polling frequency if called regularly. Ensure that repeated pulls don’t overwhelm the IMAP server or cause performance issues over time.


121-121: Potential Repeated Loads
Calling load_processed_emails() each time an inbox is pulled may be okay for small volumes. If the JSON grows large or there are many mailboxes, consider loading once, processing all, and then saving at the end for efficiency.


154-156: Skipping Messages Without Message-ID
Skipping these emails might be correct for all typical cases, but if some valid messages lack Message-ID, they will remain unprocessed. If that is not desired, consider generating a fallback ID (e.g., a hash of content).


163-165: Attachment-Only Processing
Currently you only call fetch_attachments_and_enqueue. If the email content is important (without attachments), consider whether you want to mark it processed as well.


205-205: Filtering on PDF Attachments
Processing only PDFs works if that’s the sole relevant format. If other file types become relevant, a quick extension or MIME type check can be added.


210-210: Temporary Directory Placement
Saving the attachment to the workdir first is a common approach. Ensure this directory is secured and cleared if attachments might contain sensitive data.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite

📥 Commits

Reviewing files that changed from the base of the PR and between 230c59f and 99684f9.

📒 Files selected for processing (1)
  • app/tasks/imap_tasks.py (5 hunks)
🔇 Additional comments (20)
app/tasks/imap_tasks.py (20)

4-4: No Issues with JSON Import
Importing json from the standard library is straightforward and appropriate for local caching.


38-45: Validate strptime Edge Cases
If a date string in the JSON is invalid or malformed, datetime.strptime may raise an exception. Consider wrapping parsing in a try-except or skipping improperly formatted entries to avoid breaking the cleanup process.


51-52: Clear Docstring
The revised docstring accurately reflects the new logic of checking all mailboxes. Nice clarification.


54-54: Startup Log
Logging at info level here is fine for verifying that the task has begun.


90-90: Helpful Docstring
"Check and pull new emails from a given mailbox" clarifies the function's purpose well.


95-95: Good Logging
Logging the mailbox being checked aids in troubleshooting and monitoring.


117-118: Updated Docstring
Indicating that only the last 7 days are fetched and that emails are not marked as read is straightforward and helpful for future maintainers.


132-134: Might Exclude Older Unread Emails
By restricting fetching to the last 7 days, older but unread or unprocessed emails remain unqueried. This could be intentional, but confirm that skipping older mail is acceptable.


142-142: Useful Summary
Logging the count of emails found helps gauge mailbox activity over the 7-day window.


152-152: Reliance on Message-ID
Grabbing Message-ID to uniquely track emails is sensible. Always confirm reliability of Message-ID for the mail servers in use.


158-162: Efficient Duplication Check
Using the in-memory processed_emails dict to skip duplicates prevents reprocessing. Appropriately avoids repeated work.


166-170: Conditional Logging & Saving
Storing the email in processed_emails only if there’s an attachment is logical if that’s your main concern. Just reaffirm that non-attachment emails won't repeatedly appear in subsequent pulls.


171-174: Conditional Deletion
Deleting the original emails after processing attachments is a standard approach. Make sure end-users are aware that the source record is no longer in their mailbox once attachments have been extracted.


189-192: Returns a Boolean
Returning a boolean is a clean way to indicate whether attachments were found. This improves clarity when deciding whether to track an email as processed.


194-194: Attachment Flag Initialization
has_attachment = False is straightforward. No issues.


201-201: Skipping Container Parts
Skipping multipart container messages is correct to avoid confusion; only actual file parts should be processed.


203-203: No Filename
Skipping parts with no filename is typical. If there's a chance of inlined attachments lacking a filename, confirm you don't need those.


208-208: Setting has_attachment
Marking has_attachment = True upon finding a PDF is correct.


217-217: Asynchronous Upload
Using upload_to_s3.delay(file_path) keeps the process from blocking. Good approach for concurrency.


220-220: Clear Return Value
Returning has_attachment elegantly signals whether or not to update the processed-emails cache.

@christianlouis christianlouis merged commit 9fc27d6 into main Feb 14, 2025
4 checks passed
@christianlouis christianlouis deleted the only-mark-mail-unread-with-attachments branch February 14, 2025 15:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant