views.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import json
  2. import gzip
  3. from datetime import datetime
  4. from django.shortcuts import render
  5. from django.http import JsonResponse, HttpResponse
  6. from django.core.serializers.json import DjangoJSONEncoder
  7. from django.views import View
  8. from django.core.cache import cache
  9. from django.contrib.auth.decorators import permission_required
  10. from django.contrib.auth.mixins import PermissionRequiredMixin
  11. from django.contrib.gis.geos import Point
  12. from .models import *
  13. from .workers.points2trips import TripConverter
  14. def index(request):
  15. return render(request, 'gps_logger/index.html')
  16. @permission_required("gps-logger.markers.change")
  17. def upload(request):
  18. return render(request, 'gps_logger/upload.html')
  19. class MarkerCreateView(PermissionRequiredMixin, View):
  20. permission_required = ("gps-logger.markers.change")
  21. def post(self, request):
  22. insert_count = censor_count = replace_count = 0
  23. data = json.loads(request.body)
  24. for file in data:
  25. if len(data[file]) == 0:
  26. continue
  27. objects = [Marker(
  28. timestamp=datetime.strptime(x['timestamp'].replace("Z","-0000"), r"%Y-%m-%dT%H:%M:%S.%f%z"),
  29. location = Point(x['lng'], x['lat']),
  30. alt = x['alt'],
  31. hdop = x.get('hdop', None),
  32. speed = x.get('speed', None)
  33. ) for x in data[file]]
  34. start_date = objects[0].timestamp
  35. end_date = objects[-1].timestamp
  36. oldMarkers = Marker.objects.filter(timestamp__range=(start_date, end_date)).all()
  37. identical = len(oldMarkers) == len(objects)
  38. if identical:
  39. for i, marker in enumerate(oldMarkers):
  40. if marker.timestamp != objects[i].timestamp:
  41. identical = False
  42. break
  43. if identical:
  44. for i, marker in enumerate(oldMarkers):
  45. objects[i].id = marker.id
  46. Marker.objects.bulk_update(objects, ['location', 'alt', 'hdop', 'speed'])
  47. replace_count += len(oldMarkers)
  48. else:
  49. insert_count += len(objects) - len(oldMarkers)
  50. oldMarkers.delete()
  51. Marker.objects.bulk_create(objects)
  52. censor_count = censor()
  53. return JsonResponse({
  54. 'censored': censor_count,
  55. 'replaced': replace_count,
  56. 'inserted': insert_count - censor_count
  57. }, status=201)
  58. class CreateTripsView(PermissionRequiredMixin, View):
  59. permission_required = ("gps-logger.trips.change")
  60. def get(self, request):
  61. data = list(Marker.objects.all())
  62. tc = TripConverter(data)
  63. tc.save()
  64. cache.delete('trips')
  65. return JsonResponse({
  66. 'inserted': len(tc.trips)
  67. }, status=201)
  68. def marker_view(request):
  69. data = cache.get('markers')
  70. if not data:
  71. values = list(Marker.objects.values())
  72. for marker in values:
  73. location = marker['location']
  74. if location:
  75. marker['lng'] = location.x
  76. marker['lat'] = location.y
  77. del marker['location']
  78. data = json.dumps(values, cls=DjangoJSONEncoder)
  79. cache.set('markers', data, 3600*24*30)
  80. return HttpResponse(data, content_type='application/json')
  81. def trip_view(request):
  82. data = cache.get('trips')
  83. if not data:
  84. values = list(Trip.objects.values())
  85. for trip in values:
  86. trip['path'] = json.loads(gzip.decompress(trip['path']))
  87. trip['startTime'] = trip['startTime'].timestamp()
  88. trip['endTime'] = trip['endTime'].timestamp()
  89. trip['movementTime'] = trip['movementTime'].total_seconds()
  90. trip['totalTime'] = trip['totalTime'].total_seconds()
  91. trip['center'] = {
  92. 'lng': trip['center'].x,
  93. 'lat': trip['center'].y
  94. }
  95. trip['minLng'], trip['minLat'], trip['maxLng'], trip['maxLat'] = trip['line'].extent
  96. del trip['line']
  97. data = json.dumps(values)
  98. cache.set('trips', data, 3600*24*30)
  99. return HttpResponse(data, content_type='application/json')
  100. class DeleteCensoredView(PermissionRequiredMixin, View):
  101. permission_required = ("gps-logger.markers.change",)
  102. def get(self, request):
  103. counter = censor()
  104. return JsonResponse({'censored': counter})
  105. def censor() -> int:
  106. counter = 0
  107. locations = CensoredLocation.objects.all()
  108. for location in locations:
  109. counter += location.delete_markers()
  110. if(cache.get('markers')):
  111. cache.delete('markers')
  112. return counter