Skip to content

Commit

Permalink
text fun working
Browse files Browse the repository at this point in the history
  • Loading branch information
krrish-sehgal committed Jan 26, 2025
1 parent 57403a9 commit 05e94d5
Show file tree
Hide file tree
Showing 12 changed files with 194 additions and 195 deletions.
6 changes: 4 additions & 2 deletions blt/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,19 @@
from django.core.asgi import get_asgi_application
from django.urls import path

from website.consumers import ChatConsumer, SimilarityConsumer

tracemalloc.start()

from website import consumers # You will define a consumer for handling WebSockets

application = ProtocolTypeRouter(
{
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
[
path("ws/similarity/", consumers.SimilarityConsumer.as_asgi()), # WebSocket URL
path("ws/similarity/", SimilarityConsumer.as_asgi()), # WebSocket URL
path("ws/discussion-rooms/chat/<int:room_id>/", ChatConsumer.as_asgi()),
]
)
),
Expand Down
4 changes: 2 additions & 2 deletions blt/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -567,8 +567,8 @@
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [os.environ.get("REDISCLOUD_URL")],
# "hosts": [("127.0.0.1", 6379)],
# "hosts": [os.environ.get("REDISCLOUD_URL")],
"hosts": [("127.0.0.1", 6379)],
},
},
}
12 changes: 6 additions & 6 deletions blt/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@
PreviousHunts,
ReportedIpListView,
ReportIpView,
RoomCreateView,
RoomsListView,
ScoreboardView,
TimeLogListAPIView,
TimeLogListView,
Expand All @@ -147,11 +149,13 @@
approve_activity,
checkIN,
checkIN_detail,
delete_room,
delete_time_entry,
dislike_activity,
feed,
get_scoreboard,
hunt_results,
join_room,
like_activity,
organization_dashboard,
organization_dashboard_domain_detail,
Expand All @@ -168,10 +172,6 @@
user_sizzle_report,
view_hunt,
weekly_report,
RoomsListView,
RoomCreateView,
RoomDetailView,
join_room,
)
from website.views.project import (
ProjectBadgeView,
Expand Down Expand Up @@ -865,10 +865,10 @@
path("project/<slug:slug>/", ProjectsDetailView.as_view(), name="projects_detail"),
path("slack/events", slack_events, name="slack_events"),
path("owasp/", TemplateView.as_view(template_name="owasp.html"), name="owasp"),

path("discussion-rooms/", RoomsListView.as_view(), name="rooms_list"),
path("discussion-rooms/create/", RoomCreateView.as_view(), name="room_create"),

path("discussion-rooms/join-room/<int:room_id>/", join_room, name="join_room"),
path("discussion-rooms/delete-room/<int:room_id>/", delete_room, name="delete_room"),
]

if settings.DEBUG:
Expand Down
60 changes: 35 additions & 25 deletions website/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,7 @@ async def receive(self, text_data):
branch2 = data.get("branch2") # Branch name for the second repository

if not repo1 or not repo2 or not type1 or not type2:
await self.send(
json.dumps({"error": "Both repositories and their types are required."})
)
await self.send(json.dumps({"error": "Both repositories and their types are required."}))
return

if type1 not in ["github", "zip"] or type2 not in ["github", "zip"]:
Expand Down Expand Up @@ -152,9 +150,7 @@ async def download_and_extract_zip(self, zip_url, temp_dir, repo_name):
async with aiohttp.ClientSession() as session:
async with session.get(zip_url) as response:
if response.status != 200:
raise Exception(
f"Failed to download ZIP file. Status code: {response.status}"
)
raise Exception(f"Failed to download ZIP file. Status code: {response.status}")

# Extract the ZIP file
zip_file_path = Path(temp_dir) / f"{repo_name}.zip"
Expand Down Expand Up @@ -229,9 +225,7 @@ def process_similarity_analysis(self, repo1_path, repo2_path):
if i % 5 == 0:
# Ping the frontend every 5 iterations
try:
asyncio.run(
self.send(json.dumps({"ping": "ping"}))
) # Send ping from the worker thread
asyncio.run(self.send(json.dumps({"ping": "ping"}))) # Send ping from the worker thread
except Exception as e:
return None # Stop the analysis if the connection is lost
i += 1
Expand All @@ -247,23 +241,14 @@ def process_similarity_analysis(self, repo1_path, repo2_path):
for func1 in functions1:
for func2 in functions2:
name_similarity = (
difflib.SequenceMatcher(
None, func1["signature"]["name"], func2["signature"]["name"]
).ratio()
* 100
difflib.SequenceMatcher(None, func1["signature"]["name"], func2["signature"]["name"]).ratio() * 100
)

# Signature similarity using difflib
signature1 = (
f"{func1['signature']['name']}({', '.join(func1['signature']['args'])})"
)
signature2 = (
f"{func2['signature']['name']}({', '.join(func2['signature']['args'])})"
)
signature1 = f"{func1['signature']['name']}({', '.join(func1['signature']['args'])})"
signature2 = f"{func2['signature']['name']}({', '.join(func2['signature']['args'])})"

signature_similarity = (
difflib.SequenceMatcher(None, signature1, signature2).ratio() * 100
)
signature_similarity = difflib.SequenceMatcher(None, signature1, signature2).ratio() * 100

# Content similarity using OpenAI embeddings
fulltext1 = func1["full_text"]
Expand Down Expand Up @@ -302,9 +287,7 @@ def process_similarity_analysis(self, repo1_path, repo2_path):
models2 = extract_django_models(repo2_path)
for model1 in models1:
for model2 in models2:
model_similarity = (
difflib.SequenceMatcher(None, model1["name"], model2["name"]).ratio() * 100
)
model_similarity = difflib.SequenceMatcher(None, model1["name"], model2["name"]).ratio() * 100

model_fields_similarity = compare_model_fields(model1, model2)
matching_details["models"].append(
Expand All @@ -323,3 +306,30 @@ def process_similarity_analysis(self, repo1_path, repo2_path):

return matching_details


class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_id = self.scope["url_route"]["kwargs"]["room_id"]
self.room_group_name = f"chat_{self.room_id}"

await self.channel_layer.group_add(self.room_group_name, self.channel_name)

await self.accept()

async def disconnect(self, close_code):
await self.channel_layer.group_discard(self.room_group_name, self.channel_name)

async def receive(self, text_data):
data = json.loads(text_data)
message = data.get("message", "")
username = data.get("username", "Anonymous")

await self.channel_layer.group_send(
self.room_group_name, {"type": "chat_message", "message": message, "username": username}
)

async def chat_message(self, event):
message = event["message"]
username = event["username"]

await self.send(text_data=json.dumps({"message": message, "username": username}))
3 changes: 2 additions & 1 deletion website/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
from django import forms
from mdeditor.fields import MDTextFormField

from .models import Bid, IpReport, Monitor, UserProfile
from website.models import Room

from .models import Bid, IpReport, Monitor, UserProfile


class UserProfileForm(forms.ModelForm):
email = forms.EmailField(required=True)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.1.4 on 2025-01-25 09:26
# Generated by Django 5.1.4 on 2025-01-26 10:57

import django.db.models.deletion
from django.conf import settings
Expand All @@ -8,7 +8,7 @@
class Migration(migrations.Migration):

dependencies = [
("website", "0182_project_status"),
("website", "0184_merge_0183_merge_20250124_0618_0183_slackbotactivity"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

Expand Down Expand Up @@ -60,36 +60,4 @@ class Migration(migrations.Migration):
),
],
),
migrations.CreateModel(
name="RoomMessage",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("message", models.TextField()),
("timestamp", models.DateTimeField(auto_now_add=True)),
(
"room",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="messages",
to="website.room",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="messages",
to=settings.AUTH_USER_MODEL,
),
),
],
),
]
1 change: 0 additions & 1 deletion website/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1373,4 +1373,3 @@ class Room(models.Model):

def __str__(self):
return self.name

85 changes: 85 additions & 0 deletions website/templates/room.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
{% extends "base.html" %}
{% block title %}{{ room.name }}{% endblock title %}
{% block content %}
{% include "includes/sidenav.html" %}
<div class="max-w-4xl mx-auto py-8">
<h1 class="text-3xl font-bold text-gray-900">{{ room.name }}</h1>
<div id="log-history" class="mt-4 p-4 bg-gray-100 rounded-lg h-96 overflow-y-auto">
<!-- Messages will be appended here -->
</div>
<input id="message-field" type="text" placeholder="Type a message..."
class="border rounded-lg px-4 py-2 w-full" />
<button id="send-button"
class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-lg mt-2">
Send
</button>
</div>
<script>
const roomId = {{ room.id }};
const username = "{{ request.user.username|escapejs }}"; // Add user's name
let socket;

const protocol = window.location.protocol === "https:" ? "wss://" : "ws://";
const wsUrl = `${protocol}${window.location.host}/ws/discussion-rooms/chat/${roomId}/`;

const sendButton = document.getElementById("send-button");
const messageInput = document.getElementById('message-field');
const chatLog = document.getElementById('log-history');

// Connect to WebSocket server
function connectWebSocket() {
return new Promise((resolve, reject) => {
socket = new WebSocket(wsUrl);

socket.onopen = () => {
resolve(); // Resolve the promise when the connection is established
};

socket.onmessage = (event) => {
const data = JSON.parse(event.data);
handleSocketMessage(data);
};

socket.onerror = (error) => {
reject(error); // Reject the promise if there's an error
};

socket.onclose = () => {
console.error('Chat socket closed unexpectedly');
};
});
}

// Handle WebSocket messages
function handleSocketMessage(data) {
const newMessage = document.createElement('div');
newMessage.innerHTML = `<strong>${data.username}:</strong> ${data.message}`;
newMessage.classList.add('py-1', 'px-2', 'bg-white', 'rounded-lg', 'mb-2', 'shadow-sm');
chatLog.appendChild(newMessage);
chatLog.scrollTop = chatLog.scrollHeight; // Auto-scroll to the bottom
}

// Send message through WebSocket
function sendMessage() {
const message = messageInput.value;
if (message.trim() !== "") {
const data = {
'type': 'message',
'message': message,
'username': username
};
socket.send(JSON.stringify(data));
// handleSocketMessage(data); // Display the message for the sender
messageInput.value = '';
}
}

// Event listener for send button
sendButton.addEventListener('click', sendMessage);

// Connect to WebSocket when the page loads
connectWebSocket().catch(error => {
console.error('WebSocket connection failed:', error);
});
</script>
{% endblock content %}
Loading

0 comments on commit 05e94d5

Please sign in to comment.