webhooks.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import logging
  2. import pendulum
  3. from django.views.decorators.csrf import csrf_exempt
  4. from rest_framework import status
  5. from rest_framework.decorators import api_view, permission_classes
  6. from rest_framework.permissions import IsAuthenticated
  7. from rest_framework.response import Response
  8. from scrobbles.scrobblers import (
  9. todoist_scrobble_task,
  10. todoist_scrobble_task_finish,
  11. )
  12. logger = logging.getLogger(__name__)
  13. @csrf_exempt
  14. @permission_classes([IsAuthenticated])
  15. @api_view(["POST"])
  16. def todoist_webhook(request):
  17. post_data = request.data
  18. logger.info(
  19. "[todoist_webhook] called",
  20. extra={"post_data": post_data},
  21. )
  22. todoist_type, todoist_event = post_data.get("event_name").split(":")
  23. event_data = post_data.get("event_data", {})
  24. todoist_task = {
  25. "todoist_id": event_data.get("id"),
  26. "todoist_label_list": event_data.get("labels"),
  27. "todoist_type": todoist_type,
  28. "todoist_event": todoist_event,
  29. "todoist_project_id": event_data.get("project_id"),
  30. "description": event_data.get("content"),
  31. "details": event_data.get("description"),
  32. "timestamp_utc": pendulum.parse(event_data.get("updated_at")),
  33. }
  34. if todoist_task["todoist_type"] != "item" or todoist_task[
  35. "todoist_event"
  36. ] not in [
  37. "updated",
  38. "completed",
  39. ]:
  40. logger.info(
  41. "[todoist_webhook] ignoring wrong todoist type or event",
  42. extra={
  43. "todoist_type": todoist_task["todoist_type"],
  44. "todoist_event": todoist_task["todoist_event"],
  45. },
  46. )
  47. return Response({}, status=status.HTTP_304_NOT_MODIFIED)
  48. scrobble = None
  49. if "completed" in todoist_task["todoist_event"]:
  50. scrobble = todoist_scrobble_task_finish(todoist_task, request.user.id)
  51. elif "inprogress" in todoist_task["todoist_label_list"]:
  52. scrobble = todoist_scrobble_task(todoist_task, request.user.id)
  53. if not scrobble:
  54. return Response({}, status=status.HTTP_400_BAD_REQUEST)
  55. logger.info(
  56. "[todoist_webhook] finished",
  57. extra={"scrobble_id": scrobble.id},
  58. )
  59. return Response({"scrobble_id": scrobble.id}, status=status.HTTP_200_OK)