Advertisement
Guest User

Untitled

a guest
May 15th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.67 KB | None | 0 0
  1. from itertools import groupby
  2. import json
  3. import operator
  4.  
  5. from django.contrib.auth.models import User
  6. from django.http import HttpResponse
  7. from django.views.decorators.csrf import csrf_exempt
  8. from rest_framework.authentication import TokenAuthentication
  9. from rest_framework.decorators import api_view
  10. from rest_framework.permissions import IsAuthenticated
  11. from rest_framework.views import APIView
  12.  
  13. from UnifaiCore.MessageDispatcher import MessageDispatcher
  14. from UnifaiCore.forms import SignupForm, MessageForm, TriggerForm
  15. from UnifaiCore.models import Service, Thread, Command, Trigger, Action
  16. from UnifaiCore.Utils import TriggerCheckUtil
  17. from dateutil import parser
  18.  
  19. TriggerCheckUtil.TriggerThread()
  20.  
  21.  
  22. def extractMetaData(message, req,received):
  23. metadata = {}
  24. if "token" in req.POST:
  25. metadata["token"] = req.POST.get("token")
  26. metadata["user_id"] = req.user.id
  27. metadata["username"] = req.user.username
  28. metadata["thread_id"] = message["thread_id"]
  29. metadata["received"] =received
  30. return metadata
  31.  
  32.  
  33. @csrf_exempt
  34. @api_view(['POST'])
  35. def signup(request):
  36. form = SignupForm(data=request.POST)
  37. if not form.is_valid():
  38. return HttpResponse(json.dumps(form.errors), status=403)
  39. username = form.cleaned_data["username"]
  40. password = form.cleaned_data["password"]
  41. email = form.cleaned_data["email"]
  42. User.objects.create_user(username=username,
  43. email=email,
  44. password=password)
  45. return HttpResponse(status=200)
  46.  
  47.  
  48. class MeView(APIView):
  49. authentication_classes = (TokenAuthentication,)
  50. permission_classes = (IsAuthenticated,)
  51.  
  52. def get(self, request):
  53. return HttpResponse(json.dumps({"username": request.user.username, "email": request.user.email}), status=200)
  54.  
  55.  
  56. class ServiceView(APIView):
  57. authentication_classes = (TokenAuthentication,)
  58. permission_classes = (IsAuthenticated,)
  59.  
  60. def get(self, request):
  61. return HttpResponse(json.dumps([{"id": service.id, "name": service.name, "colour": service.colour}
  62. for service in Service.objects.all()]), status=200)
  63.  
  64.  
  65. class MessageView(APIView):
  66. authentication_classes = (TokenAuthentication,)
  67. permission_classes = (IsAuthenticated,)
  68.  
  69. def post(self, request):
  70. print("begin")
  71. message = {"user_id": request.user.id, "content": request.POST.get("content")}
  72. if not "thread_id" in request.POST:
  73. message["thread_id"] = Thread.objects.create().id
  74. else:
  75. message["thread_id"] = request.POST["thread_id"]
  76.  
  77. if "type" in request.POST:
  78. message["type"] = request.POST["type"]
  79.  
  80.  
  81. print(request.POST)
  82. print(request.FILES)
  83. form = MessageForm(data=message)
  84. if not form.is_valid():
  85. print(json.dumps(form.errors))
  86. return HttpResponse(json.dumps(form.errors), status=403)
  87.  
  88.  
  89. received = Command.objects.create(
  90. thread_id=message["thread_id"],
  91. user_id=message["user_id"],
  92. content=message["content"],
  93. type = message["type"]
  94. )
  95.  
  96. if "file" in request.FILES:
  97. received.file = request.FILES["file"]
  98. received.save()
  99.  
  100. serviceResponse = MessageDispatcher().sendMessageToService(form.cleaned_data["content"],
  101. extractMetaData(message, request,received))
  102.  
  103. received.processed_message = serviceResponse["processed_message"]
  104. received.save()
  105.  
  106. reply = Command.objects.create(thread_id=message["thread_id"],
  107. user_id=message["user_id"],
  108. content=serviceResponse["message"],
  109. type=0 if "type" not in serviceResponse else serviceResponse["type"],
  110. data=serviceResponse["data"] if "data" in serviceResponse else "",
  111. service_id=serviceResponse["service_id"])
  112. serviceResponse["thread_id"] = message["thread_id"]
  113. return HttpResponse(json.dumps(reply.to_json()),
  114. status=200)
  115.  
  116.  
  117. class UserProfileView(APIView):
  118. authentication_classes = (TokenAuthentication,)
  119. permission_classes = (IsAuthenticated,)
  120.  
  121. def get(self, request):
  122. return HttpResponse(json.dumps(list(reversed([command.to_json()
  123. for command in Command.objects.all()
  124. if command.user_id is request.user.id
  125. and command.service_id is None]))), status=200)
  126.  
  127.  
  128. class ThreadView(APIView):
  129. authentication_classes = (TokenAuthentication,)
  130. permission_classes = (IsAuthenticated,)
  131.  
  132. def get(self, request, thread_id):
  133. thread = []
  134. for command in Command.objects.all():
  135. if str(command.thread_id) == thread_id:
  136. message = command.to_json()
  137. thread.append(message)
  138. return HttpResponse(json.dumps(thread), status=200)
  139.  
  140. def delete(self, request, thread_id):
  141. Thread.objects.filter(id=thread_id).delete()
  142. Command.objects.filter(user_id=request.user.id , thread_id=thread_id).delete()
  143. return HttpResponse("", status=200)
  144.  
  145.  
  146. class ServiceProfileView(APIView):
  147. authentication_classes = (TokenAuthentication,)
  148. permission_classes = (IsAuthenticated,)
  149.  
  150. def get(self, request, service_id):
  151. return HttpResponse(json.dumps([command.to_json()
  152. for command in Command.objects.all()
  153. if command.service_id == service_id and request.user.id == command.user_id]),
  154. status=200)
  155.  
  156.  
  157. class FeedView(APIView):
  158. authentication_classes = (TokenAuthentication,)
  159. permission_classes = (IsAuthenticated,)
  160.  
  161. def get(self, request):
  162.  
  163.  
  164. messages = []
  165. commands = list(sorted([command for command in Command.objects.all() if request.user.id == command.user_id] , key=lambda x : x.thread_id))
  166.  
  167. for key , group in groupby(commands , lambda x : x.thread_id):
  168. group = list(filter( lambda x : x.service_id is not None , group))
  169. list(sorted(group, key=lambda x : x.time_stamp))
  170. if len(group) == 0:
  171. continue
  172. last_message = group.pop()
  173. messages.append(last_message.to_json())
  174. sorted_messages = list(reversed(sorted(messages, key=lambda x : x["timestamp"])))
  175.  
  176. return HttpResponse(json.dumps(sorted_messages), status=200)
  177.  
  178.  
  179. class SingleTriggerView(APIView):
  180. authentication_classes = (TokenAuthentication,)
  181. permission_classes = (IsAuthenticated,)
  182.  
  183. def delete(self, request, trigger_id):
  184. Trigger.objects.filter(id=trigger_id, user_id=request.user.id).delete()
  185. return HttpResponse(json.dumps("Done"), status=200)
  186.  
  187.  
  188. class TriggerView(APIView):
  189. authentication_classes = (TokenAuthentication,)
  190. permission_classes = (IsAuthenticated,)
  191.  
  192. def post(self, request):
  193. message = {"user_id": request.user.id, "message": request.POST.get("message"),
  194. "datetime": parser.parse(request.POST.get("datetime")), "repeating": request.POST["repeating"]}
  195. form = TriggerForm(data=message)
  196. if not form.is_valid():
  197. return HttpResponse(json.dumps(form.errors), status=403)
  198. trigger = Trigger.objects.create(user_id=form.cleaned_data["user_id"],
  199. message=form.cleaned_data["message"],
  200. datetime=form.cleaned_data["datetime"],
  201. repeating=form.cleaned_data["repeating"])
  202. return HttpResponse(json.dumps({"trigger_id": trigger.id}),
  203. status=200)
  204.  
  205. def get(self, request):
  206. return HttpResponse(json.dumps([{"message": trigger.message, "trigger_id": trigger.id,
  207. "datetime": trigger.datetime.isoformat(),
  208. "repeating": trigger.repeating}
  209. for trigger in Trigger.objects.all()
  210. if trigger.user_id == request.user.id]), status=200)
  211.  
  212. class ActionView(APIView):
  213. authentication_classes = (TokenAuthentication,)
  214. permission_classes = (IsAuthenticated,)
  215.  
  216. def get(self, request):
  217. return HttpResponse(json.dumps([{"message":action.message ,"name":action.name, "id":action.id}
  218. for action in Action.objects.all()
  219. if action.user_id == request.user.id]), status=200)
  220.  
  221. def post(self, request):
  222. #no forms , just prayers
  223. Action.objects.create(message=request.POST["message"] ,name=request.POST["name"] , user_id=request.user.id)
  224. return HttpResponse(status=200)
  225.  
  226.  
  227. class FileView(APIView):
  228. authentication_classes = (TokenAuthentication,)
  229. permission_classes = (IsAuthenticated,)
  230.  
  231. def get(self, request, message_id):
  232. command = Command.objects.filter(id=message_id)[0]
  233. test_file = open(command.file.path, 'rb')
  234. response = HttpResponse(content=test_file)
  235. response['Content-Length'] = command.file.size
  236. return response
  237.  
  238. Service.objects.all().delete()
  239. Service.objects.create(name="Budget",colour='51,204,51')
  240. Service.objects.create(name="Skyscanner",colour='51,102,255')
  241. Service.objects.create(name="OneNote",colour='153,0,204')
  242. Service.objects.create(name="Weather",colour='255,204,0')
  243. Service.objects.create(name="Wikipedia" , colour="158,158,158")
  244. Service.objects.create(name="Web" , colour="30,144,255")
  245. Service.objects.create(name="Converter" , colour="204,51,0")
  246. Service.objects.create(name="Pastebin" , colour="51,51,153")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement