Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from itertools import groupby
- import json
- import operator
- from django.contrib.auth.models import User
- from django.http import HttpResponse
- from django.views.decorators.csrf import csrf_exempt
- from rest_framework.authentication import TokenAuthentication
- from rest_framework.decorators import api_view
- from rest_framework.permissions import IsAuthenticated
- from rest_framework.views import APIView
- from UnifaiCore.MessageDispatcher import MessageDispatcher
- from UnifaiCore.forms import SignupForm, MessageForm, TriggerForm
- from UnifaiCore.models import Service, Thread, Command, Trigger, Action
- from UnifaiCore.Utils import TriggerCheckUtil
- from dateutil import parser
- TriggerCheckUtil.TriggerThread()
- def extractMetaData(message, req,received):
- metadata = {}
- if "token" in req.POST:
- metadata["token"] = req.POST.get("token")
- metadata["user_id"] = req.user.id
- metadata["username"] = req.user.username
- metadata["thread_id"] = message["thread_id"]
- metadata["received"] =received
- return metadata
- @csrf_exempt
- @api_view(['POST'])
- def signup(request):
- form = SignupForm(data=request.POST)
- if not form.is_valid():
- return HttpResponse(json.dumps(form.errors), status=403)
- username = form.cleaned_data["username"]
- password = form.cleaned_data["password"]
- email = form.cleaned_data["email"]
- User.objects.create_user(username=username,
- email=email,
- password=password)
- return HttpResponse(status=200)
- class MeView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def get(self, request):
- return HttpResponse(json.dumps({"username": request.user.username, "email": request.user.email}), status=200)
- class ServiceView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def get(self, request):
- return HttpResponse(json.dumps([{"id": service.id, "name": service.name, "colour": service.colour}
- for service in Service.objects.all()]), status=200)
- class MessageView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def post(self, request):
- print("begin")
- message = {"user_id": request.user.id, "content": request.POST.get("content")}
- if not "thread_id" in request.POST:
- message["thread_id"] = Thread.objects.create().id
- else:
- message["thread_id"] = request.POST["thread_id"]
- if "type" in request.POST:
- message["type"] = request.POST["type"]
- print(request.POST)
- print(request.FILES)
- form = MessageForm(data=message)
- if not form.is_valid():
- print(json.dumps(form.errors))
- return HttpResponse(json.dumps(form.errors), status=403)
- received = Command.objects.create(
- thread_id=message["thread_id"],
- user_id=message["user_id"],
- content=message["content"],
- type = message["type"]
- )
- if "file" in request.FILES:
- received.file = request.FILES["file"]
- received.save()
- serviceResponse = MessageDispatcher().sendMessageToService(form.cleaned_data["content"],
- extractMetaData(message, request,received))
- received.processed_message = serviceResponse["processed_message"]
- received.save()
- reply = Command.objects.create(thread_id=message["thread_id"],
- user_id=message["user_id"],
- content=serviceResponse["message"],
- type=0 if "type" not in serviceResponse else serviceResponse["type"],
- data=serviceResponse["data"] if "data" in serviceResponse else "",
- service_id=serviceResponse["service_id"])
- serviceResponse["thread_id"] = message["thread_id"]
- return HttpResponse(json.dumps(reply.to_json()),
- status=200)
- class UserProfileView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def get(self, request):
- return HttpResponse(json.dumps(list(reversed([command.to_json()
- for command in Command.objects.all()
- if command.user_id is request.user.id
- and command.service_id is None]))), status=200)
- class ThreadView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def get(self, request, thread_id):
- thread = []
- for command in Command.objects.all():
- if str(command.thread_id) == thread_id:
- message = command.to_json()
- thread.append(message)
- return HttpResponse(json.dumps(thread), status=200)
- def delete(self, request, thread_id):
- Thread.objects.filter(id=thread_id).delete()
- Command.objects.filter(user_id=request.user.id , thread_id=thread_id).delete()
- return HttpResponse("", status=200)
- class ServiceProfileView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def get(self, request, service_id):
- return HttpResponse(json.dumps([command.to_json()
- for command in Command.objects.all()
- if command.service_id == service_id and request.user.id == command.user_id]),
- status=200)
- class FeedView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def get(self, request):
- messages = []
- commands = list(sorted([command for command in Command.objects.all() if request.user.id == command.user_id] , key=lambda x : x.thread_id))
- for key , group in groupby(commands , lambda x : x.thread_id):
- group = list(filter( lambda x : x.service_id is not None , group))
- list(sorted(group, key=lambda x : x.time_stamp))
- if len(group) == 0:
- continue
- last_message = group.pop()
- messages.append(last_message.to_json())
- sorted_messages = list(reversed(sorted(messages, key=lambda x : x["timestamp"])))
- return HttpResponse(json.dumps(sorted_messages), status=200)
- class SingleTriggerView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def delete(self, request, trigger_id):
- Trigger.objects.filter(id=trigger_id, user_id=request.user.id).delete()
- return HttpResponse(json.dumps("Done"), status=200)
- class TriggerView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def post(self, request):
- message = {"user_id": request.user.id, "message": request.POST.get("message"),
- "datetime": parser.parse(request.POST.get("datetime")), "repeating": request.POST["repeating"]}
- form = TriggerForm(data=message)
- if not form.is_valid():
- return HttpResponse(json.dumps(form.errors), status=403)
- trigger = Trigger.objects.create(user_id=form.cleaned_data["user_id"],
- message=form.cleaned_data["message"],
- datetime=form.cleaned_data["datetime"],
- repeating=form.cleaned_data["repeating"])
- return HttpResponse(json.dumps({"trigger_id": trigger.id}),
- status=200)
- def get(self, request):
- return HttpResponse(json.dumps([{"message": trigger.message, "trigger_id": trigger.id,
- "datetime": trigger.datetime.isoformat(),
- "repeating": trigger.repeating}
- for trigger in Trigger.objects.all()
- if trigger.user_id == request.user.id]), status=200)
- class ActionView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def get(self, request):
- return HttpResponse(json.dumps([{"message":action.message ,"name":action.name, "id":action.id}
- for action in Action.objects.all()
- if action.user_id == request.user.id]), status=200)
- def post(self, request):
- #no forms , just prayers
- Action.objects.create(message=request.POST["message"] ,name=request.POST["name"] , user_id=request.user.id)
- return HttpResponse(status=200)
- class FileView(APIView):
- authentication_classes = (TokenAuthentication,)
- permission_classes = (IsAuthenticated,)
- def get(self, request, message_id):
- command = Command.objects.filter(id=message_id)[0]
- test_file = open(command.file.path, 'rb')
- response = HttpResponse(content=test_file)
- response['Content-Length'] = command.file.size
- return response
- Service.objects.all().delete()
- Service.objects.create(name="Budget",colour='51,204,51')
- Service.objects.create(name="Skyscanner",colour='51,102,255')
- Service.objects.create(name="OneNote",colour='153,0,204')
- Service.objects.create(name="Weather",colour='255,204,0')
- Service.objects.create(name="Wikipedia" , colour="158,158,158")
- Service.objects.create(name="Web" , colour="30,144,255")
- Service.objects.create(name="Converter" , colour="204,51,0")
- Service.objects.create(name="Pastebin" , colour="51,51,153")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement