Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@swaparup36
Copy link
Contributor

@swaparup36 swaparup36 commented Mar 21, 2025

untitled-close-btn.mp4

resolves #4024

A close button was added to every chat/thread. On clicking this it will delete that thread/chat and messages on it from the database.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features
    • Users can now delete messaging conversation threads directly from the interface using a new delete button.
    • A confirmation prompt ensures that users intend to remove a conversation before processing the deletion.
    • The conversation is immediately removed from view upon successful deletion, with error alerts provided if any issues occur.
    • New API endpoint added for deleting threads, enhancing backend capabilities.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 21, 2025

Walkthrough

The changes add a new API endpoint and corresponding front-end functionality for deleting messaging threads. A URL pattern is introduced to handle delete requests, which routes to a backend view function. This function verifies user authentication and authorization before deleting the specified thread from the database. In the user interface, a delete button is added next to conversation threads, with an event listener that triggers a confirmation dialog and sends a POST request upon confirmation. The UI then updates to remove the deleted conversation, and any active view is adjusted accordingly.

Changes

File(s) Change Summary
blt/urls.py Added URL pattern path("api/messaging/thread/<int:thread_id>/delete/", delete_thread, name="delete_thread") to enable deletion of messaging threads.
website/templates/messaging.html Introduced a delete button icon next to conversation participants. Added JavaScript to handle deletion: displays a confirmation dialog, sends a POST request to the new endpoint, updates the UI by removing the thread element, and logs actions for debugging.
website/views/user.py Implemented a new delete_thread function (protected with @login_required) that processes thread deletion requests. It checks for thread existence, validates user participation, performs deletion, and returns appropriate HTTP responses.

Assessment against linked issues

Objective Addressed Explanation
Add a close button to delete the message chat (4024)

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 69f2892 and 16e3ec9.

📒 Files selected for processing (2)
  • blt/urls.py (2 hunks)
  • website/views/user.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • blt/urls.py
🧰 Additional context used
🧬 Code Definitions (1)
website/views/user.py (1)
website/models.py (1)
  • Thread (2396-2401)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (python)
🔇 Additional comments (1)
website/views/user.py (1)

1031-1044: The delete_thread implementation is secure and well-structured.

The function properly implements thread deletion with appropriate security controls:

  • Uses @login_required to ensure authenticated access
  • Verifies the user is a participant in the thread before allowing deletion
  • Returns appropriate HTTP status codes for different error conditions
  • Leverages Django's ORM cascading deletion to remove associated messages

This implementation aligns with the PR objective of adding a close button to delete message threads and all associated messages.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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
Contributor

@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 (1)
website/templates/messaging.html (1)

243-243: Remove console.log statements.

These debugging statements should be removed before deploying to production. They're marked with "to remove" comments but were left in the code.

-                console.log("Attempting WebSocket connection..."); // to remove
+                // Connection attempt
-                    console.log("WebSocket connection established"); // to remove
+                    // Connection established
-                    console.error("WebSocket error:", error);
+                    // Handle WebSocket error silently or log to a monitoring service
-                console.error("Error creating WebSocket:", error); // to remove
+                // Handle WebSocket creation error

Also applies to: 247-247, 261-261, 267-267

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fefbf5e and 8b5df13.

📒 Files selected for processing (3)
  • blt/urls.py (2 hunks)
  • website/templates/messaging.html (4 hunks)
  • website/views/user.py (1 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
website/views/user.py (1)
website/models.py (1) (1)
  • Thread (2364-2369)
blt/urls.py (1)
website/views/user.py (1) (1)
  • delete_thread (1108-1119)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
🔇 Additional comments (4)
blt/urls.py (1)

1100-1100: New URL pattern looks good.

The API endpoint follows RESTful conventions and properly integrates with the existing URL patterns.

website/views/user.py (1)

1107-1119: Well-implemented thread deletion function.

The function includes:

  • Proper authentication via the @login_required decorator
  • Authorization check to ensure only participants can delete threads
  • Appropriate error handling with correct HTTP status codes
  • Clear JSON responses for all scenarios
website/templates/messaging.html (2)

33-33: Check participant condition for delete button.

The delete button placement might have an issue with the {% if participant != request.user %} condition. Since this is inside a loop, the condition will only evaluate correctly for the last participant. If there are multiple participants besides the current user, this condition may not work as expected.

Consider revising to ensure the delete button always appears exactly once per conversation thread, regardless of the number of participants.


415-458: Delete thread functionality implementation looks good.

The implementation:

  • Prevents event propagation to avoid triggering the conversation click
  • Confirms deletion with the user before proceeding
  • Sends a proper POST request with CSRF token
  • Handles the UI updates appropriately
  • Closes WebSocket and resets state when deleting the active thread

However, consider enhancing the error messages based on the server response:

                        } else {
-                            alert('Failed to delete conversation');
+                            alert(`Failed to delete conversation: ${data.message || 'Unknown error'}`);
                        }

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 21, 2025
@DonnieBLT
Copy link
Collaborator

@codedrabbitai can you please confirm this deletes everything related to the chat?

@DonnieBLT
Copy link
Collaborator

@coderabbitai can you please confirm this deletes everything related to the chat?

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 21, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

After examining the code, I need more information about the Thread model and how deletion is implemented. Let me dig deeper:

Let me check more specifically how the deletion is implemented in the view function and the model relationships:

Let me get more specific information about these models and the delete functionality:

I need to understand more about the message deletion by looking at the Thread-Message relationship and any custom deletion logic:

@DonnieBLT After examining the code, I can confirm that the PR implements thread deletion functionality through a dedicated endpoint. When a user clicks the close button for a chat:

  1. The frontend sends a request to the delete_thread endpoint with the thread_id
  2. The backend function verifies the user has permission to delete the thread
  3. The thread is deleted using Django's delete() method

In Django's ORM, when a model is deleted, it will automatically delete related objects if the foreign key relationship has on_delete=CASCADE configured. From the code examination, it appears messages are associated with threads through such a relationship, so deleting a thread should delete all associated messages.

However, without seeing the complete model definitions with the foreign key relationships, I can't be 100% certain that all related data is deleted. It depends on how the models are structured and whether cascade deletion is properly configured. If you want absolute confirmation, we would need to see the complete Thread and Message model definitions to verify the on_delete behavior.


🏁 Script executed:

#!/bin/bash
# Check the implementation of the delete_thread function in website/views/user.py
cat website/views/user.py | grep -A 30 "def delete_thread"

# Let's also look at the messaging models to understand the data structure
cat website/models.py | grep -A 30 "class Thread" 
cat website/models.py | grep -A 30 "class Message"

Length of output: 4016


🏁 Script executed:

#!/bin/bash
# Get more context around the delete_thread function
cat website/views/user.py | grep -n "def delete_thread" -A 30

# Look for the Thread model definition and related models
grep -r "class Thread" --include="*.py" .
grep -r "class Message" --include="*.py" .

# Let's check the model definitions more thoroughly
cat website/models.py

Length of output: 67406


🏁 Script executed:

#!/bin/bash
# First, let's look at the new delete_thread function more precisely
grep -n -A 30 "def delete_thread" website/views/user.py

# Let's examine how Thread and Message models are defined
grep -n -A 15 "class Thread" website/models.py
grep -n -A 15 "class Message" website/models.py

# Let's also check the Thread model for on_delete behavior in foreign keys
grep -B 5 -A 5 "on_delete" website/models.py | grep -A 10 Thread

# Let's look at the Message model for on_delete behavior
grep -B 5 -A 5 "on_delete" website/models.py | grep -A 10 Message

Length of output: 4960


🏁 Script executed:

#!/bin/bash
# Let's get the full model definitions for Thread and Message
cat website/models.py | grep -n -A 30 "class Thread"
cat website/models.py | grep -n -A 30 "class Message"

# Now let's see the exact implementation of delete_thread
cat website/views/user.py | grep -n -A 30 "def delete_thread"

# Check any imports at the top of user.py that might be relevant
head -30 website/views/user.py

Length of output: 5832


🏁 Script executed:

#!/bin/bash
# Let's check for any custom manager or delete method in Thread model
cat website/models.py | grep -n -A 50 "class Thread"

# Get the full delete_thread implementation 
cat website/views/user.py | grep -n -A 50 "def delete_thread"

# Check if there's a custom delete method for Thread
grep -r "def delete" --include="*.py" website/models.py | grep -A 10 "class Thread"

# Let's also look for any signals that might handle deletion
grep -r "post_delete" --include="*.py" website/
grep -r "pre_delete" --include="*.py" website/

Length of output: 5650


@DonnieBLT Yes, I can confirm that clicking the close button completely deletes everything related to the chat. Looking at the code:
  1. The Message model has this relationship to the Thread model:

    thread = models.ForeignKey(Thread, on_delete=models.CASCADE, related_name="messages", null=True, blank=True)
  2. The critical part here is on_delete=models.CASCADE, which means when a thread is deleted, all messages associated with it are automatically deleted as well (cascading deletion).

  3. The delete_thread function calls thread.delete(), which triggers Django's cascading delete:

    def delete_thread(request, thread_id):
        # ...authorization checks...
        thread.delete()
        # ...

So when you click the close button, the thread and all its messages are permanently removed from the database. Nothing related to that conversation will remain.

Copy link
Collaborator

@DonnieBLT DonnieBLT left a comment

Choose a reason for hiding this comment

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

looks good, please check the tests and remove console.logs

Copy link
Contributor

@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 (1)
website/templates/messaging.html (1)

27-33: Clarify the Conditional for Rendering the Delete Icon
The delete icon is rendered with the condition {% if participant != request.user %}. Note that the variable participant here comes from the preceding for-loop, meaning that its final value may not reliably represent the intended state for showing the delete button in multi-participant threads. Consider verifying whether this condition correctly reflects when a user should see the close (delete) button—for example, by checking a dedicated thread property (e.g., thread owner or a verified permission flag).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b5df13 and dfaf884.

📒 Files selected for processing (1)
  • website/templates/messaging.html (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
website/templates/messaging.html (1)

409-456: Review and Enhance the Delete Thread Event Listener
The new deletion logic correctly stops event propagation, retrieves the thread’s ID, and sends a confirmation prompt before issuing a POST request to delete the thread. Upon successful deletion, it removes the thread element and clears the chat window if the deleted thread was active. A couple of improvements are suggested:

  • Response Validation: Before parsing the JSON response, check response.ok to ensure the HTTP request succeeded. For example:
    -                        const response = await fetch(`/api/messaging/thread/${threadId}/delete/`, {
    -                            method: 'POST',
    -                            headers: {
    -                                'X-CSRFToken': getCookie('csrftoken'),
    -                                'Content-Type': 'application/json'
    -                            }
    -                        });
    -        
    -                        const data = await response.json();
    +                        const response = await fetch(`/api/messaging/thread/${threadId}/delete/`, {
    +                            method: 'POST',
    +                            headers: {
    +                                'X-CSRFToken': getCookie('csrftoken'),
    +                                'Content-Type': 'application/json'
    +                            }
    +                        });
    +                        if (!response.ok) {
    +                            throw new Error('Network response was not OK');
    +                        }
    +                        const data = await response.json();
  • Error Feedback: Instead of using alert() for failures, consider implementing a more user-friendly inline notification for error states (this can help avoid disruptive UI experiences).
  • Console Logging: A console error is logged in the catch block. Note that previous reviews (e.g., by DonnieBLT) requested the removal of excessive console logs, so please consider cleaning these up in production code.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 22, 2025
Copy link
Contributor Author

@swaparup36 swaparup36 left a comment

Choose a reason for hiding this comment

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

changes made

@swaparup36 swaparup36 requested a review from DonnieBLT March 24, 2025 15:35
@DonnieBLT DonnieBLT enabled auto-merge April 5, 2025 02:55
@DonnieBLT DonnieBLT added this pull request to the merge queue Apr 5, 2025
Merged via the queue into OWASP-BLT:main with commit d727769 Apr 5, 2025
11 checks passed
rahulnegi20 pushed a commit to rahulnegi20/BLT that referenced this pull request Apr 5, 2025
…T#4032)

* added a close button to delete the message chat in messages

* removed all console logs

---------

Co-authored-by: DonnieBLT <[email protected]>
github-merge-queue bot pushed a commit that referenced this pull request Apr 15, 2025
* mentor changes

* chore(deps): Bump aiohttp from 3.11.14 to 3.11.15

Bumps [aiohttp](https://github.com/aio-libs/aiohttp) from 3.11.14 to 3.11.15.
- [Release notes](https://github.com/aio-libs/aiohttp/releases)
- [Changelog](https://github.com/aio-libs/aiohttp/blob/master/CHANGES.rst)
- [Commits](aio-libs/aiohttp@v3.11.14...v3.11.15)

---
updated-dependencies:
- dependency-name: aiohttp
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): Bump openai from 1.69.0 to 1.70.0

Bumps [openai](https://github.com/openai/openai-python) from 1.69.0 to 1.70.0.
- [Release notes](https://github.com/openai/openai-python/releases)
- [Changelog](https://github.com/openai/openai-python/blob/main/CHANGELOG.md)
- [Commits](openai/openai-python@v1.69.0...v1.70.0)

---
updated-dependencies:
- dependency-name: openai
  dependency-version: 1.70.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): Bump sentry-sdk from 2.24.1 to 2.25.0

Bumps [sentry-sdk](https://github.com/getsentry/sentry-python) from 2.24.1 to 2.25.0.
- [Release notes](https://github.com/getsentry/sentry-python/releases)
- [Changelog](https://github.com/getsentry/sentry-python/blob/master/CHANGELOG.md)
- [Commits](getsentry/sentry-python@2.24.1...2.25.0)

---
updated-dependencies:
- dependency-name: sentry-sdk
  dependency-version: 2.25.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* reminder-settings logic done

* UI done for remdiner-settings

* debug statement removed

* chore(deps): Bump django from 5.1.7 to 5.1.8

Bumps [django](https://github.com/django/django) from 5.1.7 to 5.1.8.
- [Commits](django/django@5.1.7...5.1.8)

---
updated-dependencies:
- dependency-name: django
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): Bump aiohttp from 3.11.15 to 3.11.16

---
updated-dependencies:
- dependency-name: aiohttp
  dependency-version: 3.11.16
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): Bump django-storages from 1.14.5 to 1.14.6

Bumps [django-storages](https://github.com/jschneier/django-storages) from 1.14.5 to 1.14.6.
- [Changelog](https://github.com/jschneier/django-storages/blob/master/CHANGELOG.rst)
- [Commits](jschneier/django-storages@1.14.5...1.14.6)

---
updated-dependencies:
- dependency-name: django-storages
  dependency-version: 1.14.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): Bump sentry-sdk from 2.25.0 to 2.25.1

Bumps [sentry-sdk](https://github.com/getsentry/sentry-python) from 2.25.0 to 2.25.1.
- [Release notes](https://github.com/getsentry/sentry-python/releases)
- [Changelog](https://github.com/getsentry/sentry-python/blob/master/CHANGELOG.md)
- [Commits](getsentry/sentry-python@2.25.0...2.25.1)

---
updated-dependencies:
- dependency-name: sentry-sdk
  dependency-version: 2.25.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>

* Shifted Kudos view to the api (#4083)

* shifted to api

* pre commit changes

* pre-commit migration'

* made rabbit changes

* Verifying kudos sender through github login.  (#4089)

* shifted to api

* pre commit changes

* pre-commit migration'

* made rabbit changes

* verifying sender by github profile

* pre commit fix

* fixes ssrf in OWASP compliance check (#4091)

* fixes ssrf in OWASP compliance check

* isort

* try block

* Implemented change provided by coderabbitai -Voidoid (#4098)

* Implemented change provided by coderabbitai -Voidoid

* Update website/templates/hackathons/detail.html

---------

Co-authored-by: Voidoid1977 <[email protected]>
Co-authored-by: DonnieBLT <[email protected]>

* done (#4101)

* Fix: Fixed the queue page. (#4075)

* side navbar fixed

* launched_at added and conditions added for it

* transaction fixed

* paid field added

* view queue feature added

* pre-commit error

* improved UI/UX of whole page

* changes in the UI

* removed discord and slack options

* post on launch added

* pre-commit error

* pre-commit error fixed

* added h and w to all img tags

* coderabit changes

* Delete_Page UI Fixed (#4100)

* done

* done

* chat-bot fixed (#4052)

Co-authored-by: DonnieBLT <[email protected]>

* added a close button to delete the message chat in messages (#4032)

* added a close button to delete the message chat in messages

* removed all console logs

---------

Co-authored-by: DonnieBLT <[email protected]>

* Added Threat Intelligence section to the Organization dashboard (#4036)

* added Threat Intelligence

* fix

* fix

* fix

---------

Co-authored-by: DonnieBLT <[email protected]>

* done (#4048)

Co-authored-by: DonnieBLT <[email protected]>

* number updated for django migrations

* deleted old file

* extra line added

* extra line added

* code fix

* pre-commit check

* pre-commit run

* pre-commit run

* migration fix

* optimized logic to send mails

* migration

* precommit

* pre-commit run

* pre-commit

* pre-commit run

* cron changes

* migration fixes

* migration fix

* removed extra urls: code clean

* import correction

* using get_or_create now

* code refactor and bug fix

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Krrish Sehgal <[email protected]>
Co-authored-by: Abhishek Kumar <[email protected]>
Co-authored-by: Voidoid1977 <[email protected]>
Co-authored-by: Voidoid1977 <[email protected]>
Co-authored-by: DonnieBLT <[email protected]>
Co-authored-by: Lucky negi <[email protected]>
Co-authored-by: Rinkit Adhana <[email protected]>
Co-authored-by: Swaparup Mukherjee <[email protected]>
Co-authored-by: sath000007 <[email protected]>
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.

add a close button to delete the message chat in messages

2 participants