Skip to content

Commit

Permalink
Merge pull request #231 from unb-mds/223/task/erros-personalizados-aj…
Browse files Browse the repository at this point in the history
…uste-em-botões

223/task/erros personalizados ajuste em botões
  • Loading branch information
TiagoBalieiro authored Feb 14, 2025
2 parents 52ab3c7 + 0d9e14b commit a4716d6
Show file tree
Hide file tree
Showing 48 changed files with 259 additions and 442 deletions.
1 change: 0 additions & 1 deletion API/AcheiUnB/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import absolute_import, unicode_literals

# Importa o Celery ao iniciar o Django
from .celery import app as celery_app

__all__ = ("celery_app",)
3 changes: 0 additions & 3 deletions API/AcheiUnB/celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@

from celery import Celery

# Define o módulo de configurações do Django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AcheiUnb.settings")

app = Celery("AcheiUnb")

# Carrega as configurações do Django
app.config_from_object("django.conf:settings", namespace="CELERY")

# Descobrir tasks automaticamente em aplicativos registrados
app.autodiscover_tasks()
39 changes: 6 additions & 33 deletions API/AcheiUnB/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,18 @@
from celery.schedules import crontab
from decouple import config

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-%7=()&6sxvzdq68n)q^8n)g6#kw8p=45v)(hp^t%@*e4ty=##u"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*"]
AUTH_USER_MODEL = "auth.User"
MEDIA_URL = "/media/" # Prefixo da URL para os arquivos
MEDIA_ROOT = os.path.join(BASE_DIR, "media") # Diretório onde os arquivos serão salvos
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

# Application definition

INSTALLED_APPS = [
"jazzmin",
Expand Down Expand Up @@ -67,10 +60,10 @@

REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"users.authentication.CookieJWTAuthentication", # Caminho do módulo e classe
"users.authentication.CookieJWTAuthentication",
),
"DEFAULT_RENDERER_CLASSES": [
"rest_framework.renderers.JSONRenderer", # Apenas JSON será usado
"rest_framework.renderers.JSONRenderer",
],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 27,
Expand Down Expand Up @@ -121,7 +114,6 @@
}
}
MICROSOFT_REDIRECT_URI = "http://localhost:8000/accounts/microsoft/login/callback/"
# Permitir apenas usuários do tenant da UnB
SOCIALACCOUNT_QUERY_EMAIL = True
SOCIALACCOUNT_PROVIDERS["microsoft"]["AUTH_PARAMS"] = {
"domain": "alunos.unb.br",
Expand All @@ -138,9 +130,6 @@
SOCIALACCOUNT_ADAPTER = "users.adapters.CustomSocialAccountAdapter"


# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases

DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
Expand All @@ -152,8 +141,6 @@
}
}

# Cloudinary


cloudinary.config(
cloud_name=config("CLOUDINARY_CLOUD_NAME"),
Expand All @@ -162,8 +149,6 @@
)


# Envio de mensagens

EMAIL_BACKEND = config("EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend")
EMAIL_HOST = config("EMAIL_HOST", default="smtp.gmail.com")
EMAIL_PORT = config("EMAIL_PORT", cast=int, default=587)
Expand All @@ -172,8 +157,6 @@
EMAIL_HOST_PASSWORD = config("EMAIL_HOST_PASSWORD", default="")
DEFAULT_FROM_EMAIL = config("DEFAULT_FROM_EMAIL", default=EMAIL_HOST_USER)

# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
Expand All @@ -191,8 +174,6 @@
]


# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/

LANGUAGE_CODE = "en-us"

Expand All @@ -206,17 +187,13 @@
CORS_ALLOW_CREDENTIALS = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = "/static/"

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "AcheiUnB/static/dist"), # Diretório dos arquivos do Vue.js
os.path.join(BASE_DIR, "AcheiUnB/static/dist"),
]

# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

Expand All @@ -227,23 +204,19 @@
LANGUAGE_CODE = "pt-br"


# Configurações do Celery
CELERY_BROKER_URL = os.getenv("CELERY_BROKER_URL", "redis://redis:6379/0")
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_TASK_SERIALIZER = "json"

# Backend para armazenar resultados (opcional)
CELERY_RESULT_BACKEND = os.getenv("CELERY_RESULT_BACKEND", "redis://redis:6379/0")

# Celery Beat Configuration
CELERY_BEAT_SCHEDULE = {
"delete_old_items_and_chats": {
"task": "users.tasks.delete_old_items_and_chats",
"schedule": crontab(hour=3, minute=0), # Executar todos os dias às 3h da manhã
"schedule": crontab(hour=3, minute=0),
},
}

# Configurações do Django celery results
INSTALLED_APPS += ["django_celery_results"]


Expand Down
10 changes: 4 additions & 6 deletions API/AcheiUnB/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,8 @@
from users.views import DeleteUserView, microsoft_callback


# View para servir o arquivo Vue.js
def vue_app(request):
return render(request, "index.html") # Caminho para o index.html dentro da pasta templates
return render(request, "index.html")


urlpatterns = [
Expand All @@ -26,18 +25,17 @@ def vue_app(request):
microsoft_callback,
name="microsoft_callback",
),
path("", vue_app, name="vue_home"), # Essa URL renderiza o arquivo index.html
path("", vue_app, name="vue_home"),
path(
"api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"
), # Obter token de acesso e refresh
),
path(
"api/token/refresh/", TokenRefreshView.as_view(), name="token_refresh"
), # Atualizar token de acesso
),
path("api/chat/", include("chat.urls")),
path("api/", include("users.urls")),
path("delete-user/<int:user_id>/", DeleteUserView.as_view(), name="delete_user"),
]

# Adiciona a configuração para servir arquivos estáticos no desenvolvimento
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
9 changes: 0 additions & 9 deletions API/AcheiUnB/wsgi.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,3 @@
"""
WSGI config for AcheiUnB project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
Expand Down
8 changes: 0 additions & 8 deletions API/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,26 +1,18 @@
# Use a imagem oficial do Python
FROM python:3.12

# Define o diretório de trabalho
WORKDIR /app

# Instale dependências do sistema
RUN apt-get update && apt-get install -y \
libpq-dev \
&& apt-get clean

# Copia o arquivo de dependências
COPY requirements.txt /app/

# Atualize o pip antes de instalar os requisitos
RUN python -m pip install --upgrade pip

# Instala as dependências do projeto
RUN pip install --no-cache-dir -r requirements.txt

# Copia o código para dentro do container
COPY . /app/

# Copia o entrypoint.sh e define como executável
COPY --chmod=755 entrypoint.sh /app/entrypoint.sh
ENTRYPOINT ["/app/entrypoint.sh"]
3 changes: 0 additions & 3 deletions API/chat/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ async def connect(self):
self.room_id = self.scope["url_route"]["kwargs"]["room_id"]
self.room_group_name = f"chat_{self.room_id}"

# Verifica se o usuário tem acesso à sala
room = await sync_to_async(ChatRoom.objects.get)(id=self.room_id)
user = self.scope["user"]
if user not in {room.participant_1, room.participant_2}:
Expand All @@ -28,13 +27,11 @@ async def receive(self, text_data):
message_content = data["message"]
sender = self.scope["user"]

# Salva a mensagem no banco
room = await sync_to_async(ChatRoom.objects.get)(id=self.room_id)
message = await sync_to_async(Message.objects.create)(
room=room, sender=sender, content=message_content
)

# Envia a mensagem para o grupo
await self.channel_layer.group_send(
self.room_group_name,
{
Expand Down
3 changes: 0 additions & 3 deletions API/manage.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AcheiUnB.settings")
try:
from django.core.management import execute_from_command_line
Expand Down
Binary file removed API/media/user_photos/42.jpg
Binary file not shown.
3 changes: 1 addition & 2 deletions API/users/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,4 @@ class UsersConfig(AppConfig):
name = "users"

def ready(self):
# Importe os sinais dentro do método ready
import users.signals # Certifique-se de que o arquivo signals.py existe e está configurado
import users.signals
1 change: 0 additions & 1 deletion API/users/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ def authenticate(self, request):
if not raw_token:
return None

# Obtém o token validado
validated_token = self.get_validated_token(raw_token)
user = self.get_user(validated_token)

Expand Down
5 changes: 0 additions & 5 deletions API/users/match.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ def get_potential_matches(target_item: Item, opposite_status: str, max_distance:
location=target_item.location,
).prefetch_related("images")

# Filtrar itens com distância de Hamming dentro do limite
matches = [
item
for item in potential_items
Expand Down Expand Up @@ -51,11 +50,9 @@ def find_and_notify_matches(target_item: Item, max_distance=2):
target_item, opposite_status="found", max_distance=max_distance
)
if matches:
# Adicionar os matches ao item perdido
target_item.matches.add(*matches)
target_item.save()

# Enviar notificação ao dono do item perdido
match_data = generate_match_data(matches)
send_match_notification.delay(
to_email=target_item.user.email,
Expand All @@ -68,11 +65,9 @@ def find_and_notify_matches(target_item: Item, max_distance=2):
target_item, opposite_status="lost", max_distance=max_distance
)
for lost_item in potential_items:
# Adicionar o item encontrado como match ao item perdido
lost_item.matches.add(target_item)
lost_item.save()

# Obter todos os matches atualizados e notificar o usuário
updated_matches = lost_item.matches.all()
match_data = generate_match_data(updated_matches)
send_match_notification.delay(
Expand Down
Loading

0 comments on commit a4716d6

Please sign in to comment.