views.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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.run()
  64. cache.delete('trips')
  65. return JsonResponse({
  66. 'created': tc.created,
  67. 'updated': tc.updated,
  68. 'skipped': tc.skipped
  69. }, status=201)
  70. def marker_view(request):
  71. data = cache.get('markers')
  72. if not data:
  73. values = list(Marker.objects.values())
  74. for marker in values:
  75. location = marker['location']
  76. if location:
  77. marker['lng'] = location.x
  78. marker['lat'] = location.y
  79. del marker['location']
  80. data = json.dumps(values, cls=DjangoJSONEncoder)
  81. cache.set('markers', data, 3600*24*30)
  82. return HttpResponse(data, content_type='application/json')
  83. def trip_view(request):
  84. data = cache.get('trips')
  85. if not data:
  86. values = list(Trip.objects.values())
  87. for trip in values:
  88. trip['path'] = json.loads(gzip.decompress(trip['path']))
  89. trip['startTime'] = trip['startTime'].timestamp()
  90. trip['endTime'] = trip['endTime'].timestamp()
  91. trip['movementTime'] = trip['movementTime'].total_seconds()
  92. trip['totalTime'] = trip['totalTime'].total_seconds()
  93. trip['center'] = {
  94. 'lng': trip['center'].x,
  95. 'lat': trip['center'].y
  96. }
  97. trip['minLng'], trip['minLat'], trip['maxLng'], trip['maxLat'] = trip['line'].extent
  98. del trip['line']
  99. data = json.dumps(values)
  100. cache.set('trips', data, 3600*24*30)
  101. return HttpResponse(data, content_type='application/json')
  102. class DeleteCensoredView(PermissionRequiredMixin, View):
  103. permission_required = ("gps-logger.markers.change",)
  104. def get(self, request):
  105. counter = censor()
  106. return JsonResponse({'censored': counter})
  107. def censor() -> int:
  108. counter = 0
  109. locations = CensoredLocation.objects.all()
  110. for location in locations:
  111. counter += location.delete_markers()
  112. if(cache.get('markers')):
  113. cache.delete('markers')
  114. return counter