Commit 81af85be by Joosep L

bug fixes/added features

parent 1a1e0835
<component name="InspectionProjectProfileManager">
<settings>
<option name="useProjectProfile" value="false" />
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.5.2+ (/usr/bin/python3.5)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/thesis-backend.iml" filepath="$PROJECT_DIR$/.idea/thesis-backend.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="thesis/settings.py" />
<option name="manageScript" value="manage.py" />
<option name="environment" value="&lt;map/&gt;" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
</component>
<component name="TestRunnerService">
<option name="PROJECT_TEST_RUNNER" value="Unittests" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
......@@ -139,7 +139,7 @@ class Answer(models.Model):
point= models.ForeignKey(Point, on_delete=models.CASCADE)
problem_type = models.ForeignKey(ProblemType, on_delete=models.CASCADE)
given_answer = models.CharField(max_length=200, blank=True, null=True)
photo = models.FileField(upload_to='photos', blank=True, null=True)
photo = models.ImageField(upload_to='photos', blank=True, null=True)
is_correct = models.BooleanField()
updated_at = models.DateTimeField(blank=True, null=True)
created_at = models.DateTimeField(default=datetime.now)
......
......@@ -63,6 +63,8 @@ class PointSerializer(serializers.ModelSerializer):
class AnswerSerializer(serializers.ModelSerializer):
problem_type = ProblemTypeSerializer(many=False)
class Meta:
model = Answer
fields = ('id', 'user_game', 'point', 'problem_type', 'is_correct')
......@@ -72,7 +74,7 @@ class AnswerSerializer(serializers.ModelSerializer):
class BoundSerializer(serializers.ModelSerializer):
class Meta:
model = Bounds
fields = ('id', 'notification_text')
fields = ('id', 'notification_text', 'mpoly')
class CheckInSerializer(serializers.ModelSerializer):
......
......@@ -8,17 +8,19 @@ router = routers.DefaultRouter()
urlpatterns = [
url(r'^', include(router.urls)),
url(r'login', views.UserViewSet.as_view()),
url(r'user/login', views.login),
url(r'user/games', views.GetUsersGames.as_view()),
url(r'user/add', views.PostUser.as_view()),
url(r'games', views.GetGame.as_view()),
url(r'game/start', views.StartGame),
url(r'game/end', views.EndGame),
url(r'game/adduser', views.PostGameToUser),
url(r'game/points', views.GetPoints.as_view()),
url(r'game/bounds', views.GetBounds.as_view()),
url(r'game/checkin', views.PostCheckIn),
url(r'game/addanswer', views.PostAnswer),
url(r'game/message', views.PostMessage),
url(r'game/stats', views.GetCheckIns),
url(r'login', views.UserViewSet.as_view()),
]
from datetime import timezone
import requests
from django.http import JsonResponse, HttpResponse
from django.utils.timezone import localtime, now
from django_filters.rest_framework import DjangoFilterBackend
......@@ -7,6 +10,30 @@ from rest_framework.response import Response
from rest_framework.views import APIView
from api.serializers import *
import base64
from django.core.files.base import ContentFile
@api_view(['POST'])
def login(request):
try:
access_token = request.GET.get('access_token')
service = request.GET.get('service')
# vaata kas fb või goole
if(service == "fb"):
r = requests.get('https://graph.facebook.com/me?access_token=' + access_token)
id = r.json()['id']
try:
user = User.objects.get(service_uid=id)
return JsonResponse(user.id, status=status.HTTP_200_OK, safe=False)
except User.DoesNotExist:
user = User(service="fb", service_uid=id, username=r.json()['name'])
user.save()
return JsonResponse(user.id, status=status.HTTP_200_OK, safe=False)
except:
return HttpResponse(status=400)
class UserViewSet(APIView):
......@@ -29,6 +56,54 @@ class PostUser(APIView):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET'])
def GetCheckIns(request):
try:
user_id = request.GET.get('user_id')
game_id = request.GET.get('game_id')
user_game = UserGame.objects.filter(user__id=user_id, game__id=game_id)
checkins = CheckIn.objects.filter(user_game=user_game[0])
json = []
for check in checkins:
serializer = CheckInSerializer(check)
json.append(serializer.data)
return JsonResponse(json, status=status.HTTP_200_OK, safe=False)
except:
return HttpResponse(status=400)
@api_view(['POST'])
def login(request):
try:
access_token = request.POST.get('access_token')
service = request.POST.get('service')
# vaata kas fb või goole
if(service == 'fb'):
r = requests.get('https://graph.facebook.com/me?access_token=' + access_token)
id = r.json()['id']
try:
user = User.objects.get(service_uid=id)
return JsonResponse(user.id, status=status.HTTP_200_OK, safe=False)
except User.DoesNotExist:
user = User(service="fb", service_uid=id, username=r.json()['name'])
user.save()
return JsonResponse(user.id, status=status.HTTP_200_OK, safe=False)
else:
r = requests.get('https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' + access_token)
email = r.json()['email']
name = r.json()['name']
try:
user = User.objects.get(service_uid=email)
return JsonResponse(user.id, status=status.HTTP_200_OK, safe=False)
except User.DoesNotExist:
user = User(service="google", service_uid=email, username=name)
user.save()
return JsonResponse(user.id, status=status.HTTP_200_OK, safe=False)
except:
return HttpResponse(status=400)
# fields = ('username', 'service', 'service_uid', 'email', 'device_id')
@api_view(['POST'])
def PostGameToUser(request):
try:
......@@ -37,14 +112,18 @@ def PostGameToUser(request):
game = Game.objects.get(game_code=game_code)
user = User.objects.get(id=user_id)
user_game = UserGame(user=user, game=game)
user_game.save()
serializer = GameSerializer(game)
try:
user_game = UserGame.objects.get(user=user, game=game)
serializer = GameSerializer(game)
json = {'user_game_id': user_game.id, 'start_time': user_game.start_time, 'game': serializer.data}
return JsonResponse(json, status=status.HTTP_200_OK, safe=False)
except UserGame.DoesNotExist:
user_game = UserGame(user=user, game=game)
user_game.save()
serializer = GameSerializer(game)
json = {'user_game_id': user_game.id, 'game': serializer.data}
return JsonResponse(json, status=status.HTTP_201_CREATED, safe=False)
json = {'user_game_id': user_game.id, 'game': serializer.data}
return JsonResponse(json, status=status.HTTP_201_CREATED, safe=False)
return HttpResponse(status=201)
except:
return HttpResponse(status=400)
......@@ -61,6 +140,18 @@ def StartGame(request):
return HttpResponse(status=400)
@api_view(['POST'])
def EndGame(request):
try:
user_game_id = request.POST.get('user_game_id')
user_game = UserGame.objects.get(id=user_game_id)
user_game.end_time = localtime(now())
user_game.save()
return Response("success", status=status.HTTP_201_CREATED)
except:
return HttpResponse(status=400)
@api_view(['GET'])
def GetCheckIns(request):
try:
......@@ -98,6 +189,13 @@ class GetPoints(generics.ListAPIView):
filter_fields = ('game',)
class GetBounds(generics.ListAPIView):
queryset = Bounds.objects.all()
serializer_class = BoundSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('game',)
@api_view(['POST'])
def PostAnswer(request):
try:
......@@ -107,6 +205,9 @@ def PostAnswer(request):
given_answer = request.POST.get('given_answer')
is_correct = request.POST.get('is_correct')
# photo = request.POST.get('photo')
# image_data = base64.b64decode(photo)
user_game = UserGame.objects.get(id=user_game_id)
point = Point.objects.get(id=point_id)
problem_type = ProblemType.objects.get(id=problem_type_id)
......@@ -123,6 +224,8 @@ def PostAnswer(request):
@api_view(['POST'])
def PostMessage(request):
try:
request.encoding = 'utf-8'
user_game_id = request.POST.get('user_game_id')
user_id = request.POST.get('user_id')
content = request.POST.get('content')
......@@ -139,6 +242,7 @@ def PostMessage(request):
@api_view(['POST'])
def PostCheckIn(request):
try:
user_game_id = request.POST.get('user_game_id')
lat = request.POST.get('lat')
lon = request.POST.get('lon')
......@@ -146,6 +250,20 @@ def PostCheckIn(request):
latest_answer_id = request.POST.get('latest_answer_id')
user_game = UserGame.objects.get(id=user_game_id)
# Check if duration is over
max_duration = user_game.game.max_duration
now = datetime.now(timezone.utc)
delta = now - user_game.start_time
difference = divmod(delta.days * 864000 + delta.seconds, 60)
game_over = 0
if difference[0] > max_duration:
game_over = 1
# Check if current_time >= end_time
if(user_game.game.end_time):
if(user_game.game.end_time < now):
game_over = 1
answer = None
point = Point.objects.get(id=current_point_id)
......@@ -153,21 +271,16 @@ def PostCheckIn(request):
json = {}
json['messages'] = []
json['bounds'] = []
# Check if any answers have been updated
if latest_answer_id is not None:
answer = Answer.objects.get(id=latest_answer_id)
if answer.point == point:
if answer.problem_type.title == 'CAM':
if answer.updated_at is not None:
answer_serializer = AnswerSerializer(answer)
json['answer'] = answer_serializer.data
json['isover'] = game_over
try:
previous_check_in = CheckIn.objects.filter(user_game=user_game).latest('created_at')
except:
previous_check_in = None
# Check if any answers have been updated
# Save new CheckIn
check_in = CheckIn(user_game=user_game, current_point=point, latest_answer=answer, lat=lat, lon=lon)
check_in.save()
......@@ -184,6 +297,17 @@ def PostCheckIn(request):
message_serializer = MessageSerializer(mes)
json['messages'].append(message_serializer.data)
if latest_answer_id is not None:
answers = Answer.objects.filter(id=latest_answer_id, updated_at__gt=previous_check_in.created_at)
if(len(answers) > 0):
answer = answers[0]
if answer.point == point:
if answer.problem_type.title == 'CAM':
if answer.updated_at is not None:
answer_serializer = AnswerSerializer(answer)
json['answer'] = answer_serializer.data
if not bounds:
return JsonResponse(json, status=status.HTTP_201_CREATED, safe=False)
else:
......@@ -193,4 +317,4 @@ def PostCheckIn(request):
return JsonResponse(json, status=status.HTTP_201_CREATED, safe=False)
except:
return HttpResponse(status=400)
return HttpResponse(status=400)
\ No newline at end of file
......@@ -24,7 +24,7 @@ SECRET_KEY = 'g-6b+0)v(%=p$^6z7-prl5z@e*-6(x=b*cflbowz=us&&$2@j#'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['128.199.63.125', '127.0.0.1']
ALLOWED_HOSTS = ['127.0.0.1']
# Application definition
......@@ -87,8 +87,7 @@ DATABASES = {
'NAME': 'andmebaasinimi',
'USER': 'kasutajanimi',
'PASSWORD': 'parool',
'HOST': '127.0.0.1',
'PORT': '5432',
'HOST': 'aadress',
}
}
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
......@@ -125,4 +124,4 @@ USE_TZ = True
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment