Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/backend/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from .celery import app as celery_app
_all_ = ('celery_app',)
12 changes: 12 additions & 0 deletions backend/backend/celery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# backend/celery.py

import os
from celery import Celery

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')

app = Celery('backend')

app.config_from_object('django.conf:settings', namespace='CELERY')

app.autodiscover_tasks()
51 changes: 46 additions & 5 deletions backend/backend/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,14 @@
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
FRONTEND_URL = os.environ["FRONTEND_URL"]

from decouple import config
SECRET_KEY=config("DJANGO_SECRET_KEY")
FRONTEND_URL=config("FRONTEND_URL", default="http://127.0.0.1:3000")


# SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
# FRONTEND_URL = os.environ["FRONTEND_URL"]

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Expand All @@ -47,8 +53,17 @@
"authentication",
"chat",
"gpt",
#task 3
'django_filters'
]

# task 3
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}

MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
Expand Down Expand Up @@ -85,9 +100,13 @@
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'bhavani',
'USER': 'postgres',
'PASSWORD': '123456',
'HOST': 'localhost',
'PORT': '5432'
}
}

Expand Down Expand Up @@ -149,3 +168,25 @@
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = "None"

# CELERY SETTINGS
CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'

# CELERY BEAT SETTINGS
INSTALLED_APPS += ['django_celery_beat']

#task 4
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': { 'class': 'logging.StreamHandler' },
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
}

2 changes: 2 additions & 0 deletions backend/backend/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,6 @@ def root_view(request):
path("gpt/", include("gpt.urls")),
path("auth/", include("authentication.urls")),
path("", root_view),
#task 3
path('api/',include('chat.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
32 changes: 30 additions & 2 deletions backend/chat/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,35 @@

from chat.models import Conversation, Message, Role, Version


#task 3.2
from .models import FileUpload
from django import forms
from django.contrib import messages
from django.core.exceptions import ValidationError

# Custom form to show only user and file (hide hash/size in input)
class FileUploadForm(forms.ModelForm):
class Meta:
model = FileUpload
fields = ['user', 'file'] # only show user and file fields
@admin.register(FileUpload)
class FileUploadAdmin(admin.ModelAdmin):
form = FileUploadForm
list_display = ("id", "file_name", "file_size", "file_hash", "uploaded_at", "user")
readonly_fields = ("file_name", "file_size", "file_hash", "uploaded_at")

def save_model(self, request, obj, form, change):
try:
obj.save() # Triggers full_clean() with validation
self.message_user(request, "File uploaded successfully.", level=messages.SUCCESS)
except ValidationError as e:
self.message_user(
request,
f"Upload failed: {e.messages[0]}",
level=messages.WARNING
)

# task3.2 end--
class RoleAdmin(NestedModelAdmin):
list_display = ["id", "name"]

Expand Down Expand Up @@ -51,7 +79,7 @@ def queryset(self, request, queryset):
class ConversationAdmin(NestedModelAdmin):
actions = ["undelete_selected", "soft_delete_selected"]
inlines = [VersionInline]
list_display = ("title", "id", "created_at", "modified_at", "deleted_at", "version_count", "is_deleted", "user")
list_display = ("title", "id", "created_at", "modified_at", "deleted_at", "version_count", "is_deleted", "user","summary")
list_filter = (DeletedListFilter,)
ordering = ("-modified_at",)

Expand Down
3 changes: 3 additions & 0 deletions backend/chat/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@
class ChatConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "chat"

def ready(self):
import chat.signals # 👈 Load signals
20 changes: 20 additions & 0 deletions backend/chat/management/commands/cleanup_old_conversations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from django.core.management.base import BaseCommand
from django.utils import timezone
from chat.models import Conversation
from datetime import timedelta

class Command(BaseCommand):
help = 'Soft-deletes conversations older than 30 days'

def handle(self, *args, **kwargs):
days = 30
cutoff_date = timezone.now() - timedelta(days=days)

deleted_count = Conversation.objects.filter(
created_at__lt=cutoff_date,
deleted_at__isnull=True
).update(deleted_at=timezone.now())

self.stdout.write(
self.style.SUCCESS(f"{deleted_count} conversations soft-deleted.")
)
18 changes: 18 additions & 0 deletions backend/chat/migrations/0002_conversation_summary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.2.4 on 2025-07-05 09:04

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('chat', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='conversation',
name='summary',
field=models.TextField(blank=True, null=True),
),
]
28 changes: 28 additions & 0 deletions backend/chat/migrations/0003_fileupload.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 5.2.4 on 2025-07-07 16:53

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('chat', '0002_conversation_summary'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='FileUpload',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', models.FileField(upload_to='uploads/')),
('uploaded_at', models.DateTimeField(auto_now_add=True)),
('file_name', models.CharField(max_length=255)),
('file_size', models.PositiveIntegerField()),
('file_hash', models.CharField(max_length=64, unique=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 5.2.4 on 2025-07-07 17:53

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('chat', '0003_fileupload'),
]

operations = [
migrations.AlterField(
model_name='fileupload',
name='file_hash',
field=models.CharField(blank=True, max_length=64, unique=True),
),
migrations.AlterField(
model_name='fileupload',
name='file_name',
field=models.CharField(blank=True, max_length=255),
),
migrations.AlterField(
model_name='fileupload',
name='file_size',
field=models.PositiveIntegerField(blank=True, null=True),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Generated by Django 5.2.4 on 2025-07-08 11:52

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('chat', '0004_alter_fileupload_file_hash_and_more'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='FileLog',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file_name', models.CharField(max_length=255)),
('action', models.CharField(choices=[('UPLOAD', 'Upload'), ('DELETE', 'Delete'), ('ACCESS', 'Access')], max_length=10)),
('timestamp', models.DateTimeField(auto_now_add=True)),
],
),
migrations.AlterField(
model_name='fileupload',
name='file_hash',
field=models.CharField(max_length=64),
),
migrations.AlterField(
model_name='fileupload',
name='file_name',
field=models.CharField(max_length=255),
),
migrations.AlterField(
model_name='fileupload',
name='file_size',
field=models.PositiveIntegerField(default=0),
preserve_default=False,
),
migrations.AddConstraint(
model_name='fileupload',
constraint=models.UniqueConstraint(fields=('user', 'file_hash'), name='unique_user_file_hash'),
),
migrations.AddField(
model_name='filelog',
name='user',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL),
),
]
63 changes: 63 additions & 0 deletions backend/chat/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
from django.db import models

from authentication.models import CustomUser
# task-3
import hashlib
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
import hashlib
from django.contrib.auth.models import User


class Role(models.Model):
Expand All @@ -22,6 +28,7 @@ class Conversation(models.Model):
)
deleted_at = models.DateTimeField(null=True, blank=True)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
summary = models.TextField(blank=True, null=True)

def __str__(self):
return self.title
Expand All @@ -32,6 +39,48 @@ def version_count(self):
version_count.short_description = "Number of versions"


# task-3 file uploadwith duplicate check
User = get_user_model()

class FileUpload(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
file = models.FileField(upload_to='uploads/')
uploaded_at = models.DateTimeField(auto_now_add=True)
file_name = models.CharField(max_length=255)
file_size = models.PositiveIntegerField()
file_hash = models.CharField(max_length=64)

class Meta:
constraints = [
models.UniqueConstraint(fields=['user', 'file_hash'], name='unique_user_file_hash')
]

def clean(self):
# Check for duplicate files for the same user
if FileUpload.objects.filter(user=self.user, file_hash=self.file_hash).exclude(pk=self.pk).exists():
raise ValidationError("Duplicate file. Already uploaded by this user.")

def save(self, *args, **kwargs):
# Only calculate hash if not already set
if not self.file_hash:
hasher = hashlib.sha256()
for chunk in self.file.chunks():
hasher.update(chunk)
self.file_hash = hasher.hexdigest()

# Set file name and size automatically
self.file_name = self.file.name
self.file_size = self.file.size

# Run validation and save
self.full_clean() # Calls clean()
super().save(*args, **kwargs)

def _str_(self):
return f"{self.user.email} - {self.file_name}"



class Version(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
conversation = models.ForeignKey("Conversation", related_name="versions", on_delete=models.CASCADE)
Expand Down Expand Up @@ -63,3 +112,17 @@ def save(self, *args, **kwargs):

def __str__(self):
return f"{self.role}: {self.content[:20]}..."

class FileLog(models.Model):
ACTION_CHOICES= [
('UPLOAD', 'Upload'),
('DELETE', 'Delete'),
('ACCESS', 'Access'),
]
user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True)
file_name = models.CharField(max_length=255)
action = models.CharField(max_length=10, choices=ACTION_CHOICES)
timestamp = models.DateTimeField(auto_now_add=True)

def _str_(self):
return f"{self.timestamp} - {self.user} - {self.action} - {self.file_name}"
Loading