Guest User

Untitled

a guest
May 26th, 2025
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.73 KB | Source Code | 0 0
  1. from django.shortcuts import render
  2.  
  3. from .tasks import send_messages
  4.  
  5. from rest_framework.status import HTTP_400_BAD_REQUEST
  6.  
  7. from django.shortcuts import render
  8.  
  9. from .models import Room, Arborist, Landlord, ArboristProfile, LandlordProfile
  10.  
  11. from arborfindr.models import User  
  12.  
  13. from rest_framework.views import APIView
  14.  
  15. from rest_framework.decorators import authentication_classes, permission_classes
  16.  
  17. from rest_framework_simplejwt.authentication import JWTAuthentication
  18.  
  19. from rest_framework.response import Response
  20.  
  21. from rest_framework.permissions import IsAuthenticated, DjangoModelPermissionsOrAnonReadOnly, AllowAny
  22.  
  23. from django.contrib.auth import login
  24.  
  25. from .serializers import RoomSerializer, RegisterChatSerializer, LoginChatSerializer, ArboristProfileSerializer, PropertyManagerSerializer
  26.  
  27. from rest_framework.authtoken.models import Token
  28.  
  29. from rest_framework import status, generics, permissions
  30.  
  31. from rest_framework_simplejwt.tokens import RefreshToken
  32.  
  33. from drf_haystack.viewsets import HaystackViewSet
  34.  
  35. from haystack.query import SearchQuerySet
  36.  
  37. from rest_framework import permissions
  38.  
  39. from rest_framework.decorators import action
  40.  
  41. from rest_framework.parsers import MultiPartParser, FormParser
  42.  
  43.  
  44. def arborchat_home(request):
  45.     return render(request, 'arborchat/index.html', {
  46.         'channels': Room.objects.values_list('room_name', flat=True)
  47.     })
  48. def index(request):
  49.     return render(request, 'arborchat/index.html', {
  50.         'rooms': Room.objects.all(),
  51. })
  52.    
  53.    
  54. def messenger_room(request):
  55.     room = Room.objects.first()
  56.     return render(request, 'messenger.html', {'room': room })
  57.    
  58.  
  59. def property_manager_room(request):
  60.     room = Room.objects.first()
  61.     return render(request, 'property_manageer.html', {'room': room }}
  62.  
  63. def business_room(request):
  64.     room = Room.objects.first()
  65.     return render (request, 'business_manager.html', {'room': room }}
  66.  
  67.  
  68. @authentication_classes([JWTAuthentication])
  69. def room_view(request, room_name):
  70.     room, created = Room.objects.get_or_create(room_name=room_name)
  71.     print('Room name is', room_name)
  72.     return render(request, 'arborchat/messenger.html', {'room_name': room_name})
  73.  
  74.  
  75.  
  76. # API endpoint for Arborist login
  77.  
  78. @authentication_classes([JWTAuthentication])
  79. class ChatLoginView(APIView):
  80.     authentication_classes = [JWTAuthentication]
  81.  
  82.     def post(self, request, *args, **kwargs):
  83.         serializer = LoginChatSerializer(data=request.data, context={'request': request})
  84.         serializer.is_valid(raise_exception=True)
  85.         user = serializer.validated_data.get('user')
  86.  
  87.         if not user:
  88.             return Response({'error': 'Invalid email/password'}, status=status.HTTP_401_UNAUTHORIZED)
  89.  
  90.         if user.role not in ('arborist', 'property_manager'):
  91.             return Response({'error': 'Unauthorized role'}, status=status.HTTP_403_FORBIDDEN)
  92.  
  93.         login(request, user)
  94.         refresh = RefreshToken.for_user(user)
  95.  
  96.         return Response({
  97.             'message': 'Successful login',
  98.             'access_token': str(refresh.access_token),
  99.             'refresh_token': str(refresh),
  100.         }, status=status.HTTP_200_OK)
  101.  
  102.  
  103. # Now reachable
  104.  
  105.  
  106.    
  107. @authentication_classes([JWTAuthentication])
  108. class ChatRegisterView(generics.CreateAPIView):  
  109.     queryset = User.objects.all()
  110.     serializer_class = RegisterChatSerializer
  111.     permission_classes = [permissions.AllowAny]
  112.  
  113.     def post(self, request, *args, **kwargs):
  114.         serializer = RegisterChatSerializer(data=request.data, context={'request': request})
  115.         serializer.is_valid(raise_exception=True)
  116.         user = (serializer.
  117.                 save())
  118.  
  119.         if user.role == 'arborist':
  120.             Arborist.objects.create(user=user)
  121.         elif user.role == 'property_manager':
  122.             Landlord.objects.create(user=user)
  123.  
  124.         return Response({'message': 'Successfully registered'}, status=status.HTTP_201_CREATED)
  125.  
  126.  
  127.  
  128.     @action(detail=False, methods=['get'])
  129.     def me(self, request):
  130.         self.kwargs['pk'] = request.user.pk
  131.         return self.retrieve(request)
  132.  
  133.     def post(self, request):
  134.         serializer = RegisterChatSerializer(data=request.data, context={'request': request})
  135.         if serializer.is_valid():
  136.             serializer.save()
  137.             return Response({
  138.                 'message': 'successfully registered',  }, status=status.HTTP_201_CREATED)
  139.         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  140.  
  141.  
  142. @authentication_classes([JWTAuthentication])
  143. class SendEmailView(APIView):
  144.  
  145.     def post(self, request, *args, **kwargs):
  146.         subject = request.data.get('subject')
  147.         message_body = request.data.get('message')
  148.         to_emails = request.data.get('to_emails', [])
  149.  
  150.         if not subject or not message_body or not to_emails:
  151.             return Response({'error': 'Missing required fields'}, status=HTTP_400_BAD_REQUEST)
  152.         send_messages.delay(subject, message_body, to_emails)
  153.  
  154.         return Response ({'message': 'Email task qeued successfully'}, status=status.HTTP_202_ACCEPTED)
  155.  
  156.  
  157. class ArboristProfileView(APIView):
  158.  
  159.     queryset = ArboristProfile.objects.all()
  160.     permission_classes = [IsAuthenticated]
  161.     authentication_classes = [JWTAuthentication]
  162.     serializer_class = ArboristProfileSerializer
  163.     parser_classes = (MultiPartParser, FormParser)
  164.    
  165.     def create(self, request, *args, **kwargs):
  166.         arborist_name = request.data["arborist_name"]
  167.         arborist_location = request.data["arborist_location"]
  168.         services_arborist = request.data["services_arborist"]
  169.         description = request.data["description"]
  170.         arborist_logo = request.data["arborist_logo"]
  171.  
  172.         ArboristProfile.objects.create(arborist_name = arborist_name, arborist_location = arborist_location, services_arborist = services_arborist,
  173.                                        description = description, arborist_logo)
  174.  
  175.         return Response("Profile created", status=status.HTTP_200_OK)
  176.        
  177.        
  178. class PropertyManagerProfileView(APIView):
  179.  
  180.     queryset = LandlordProfile.objects.all()
  181.     permission_classes = [IsAuthenticated]
  182.     authentication_classes = [JWTAuthentication]
  183.     serializer_class = PropertyManagerSerializer
  184.     parser_classes = (MultiPartParser, FormParser)
  185.  
  186.      def create(self, request, *args, **kwargs):
  187.    
  188.         first_name = request.data["first_name"]
  189.         last_name = request.data["last_name"]
  190.         property_name = request.data["property_name"]
  191.         property_location = request.data["property_location"]
  192.         profile_pic = request.data["profile_pic"]
  193.  
  194.         LandlordProfile.objects.create(first_name = first_name, last_name = last_name, property_name = property_name,
  195.                                        property_location = property_location, profile_pic = profile_pic)
  196.  
  197.          return Response("Profile created", status=status.HTTP_200_OK)
  198.    
  199.    
  200. class SearchBarView(APIView):
  201.    
  202.     model = Arborist
  203.     permission_classes = [IsAuthenticated]
  204.     serializer_classes = ArboristProfileSerializer
  205.     success_url = '/'
  206.     context_object_name = 'all_search_results'
  207.    
  208.    
  209.     def get(self):
  210.        
  211.        query = self.request.GET.get('search')
  212.        results = SearchQuerySet().filter(content=query)
  213.    
  214.    # serialize results based on models
  215.    
  216.        serialized_results = []
  217.        for result in results:
  218.            if result.model == 'arborist':
  219.                serializer = ArboristProfileSerializer(result.object)
  220.            elif result.model == 'company':
  221.                serializer = PropertyManagerSerializer(result.object)
  222.            else:
  223.                continue
  224.            serialized_results.append(serializer.data)
  225.        return Response(serialized_results)
  226.  
Advertisement
Add Comment
Please, Sign In to add comment