From 8fc46e56954e28e5eb979a1cf81a60133499aae7 Mon Sep 17 00:00:00 2001 From: sousaUA Date: Sat, 3 Feb 2024 22:03:00 +0000 Subject: [PATCH 1/3] Update .gitignore --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index dd8a3b4..fb50ccd 100755 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ __pycache__/ *.py[cod] *$py.class +.DS_Store + # C extensions *.so From 19b0d2816c052097860d52cd0ce2d6356fe6b929 Mon Sep 17 00:00:00 2001 From: sousaUA Date: Sat, 3 Feb 2024 22:03:12 +0000 Subject: [PATCH 2/3] GMaps call from the API --- src/SaoMiguelBus/settings.py | 8 ++++++ src/SaoMiguelBus/urls.py | 1 + src/app/views.py | 46 ++++++++++++++++++++++++++++++++++- src/db.sqlite3 | Bin 507904 -> 507904 bytes src/requirements.txt | 4 ++- 5 files changed, 57 insertions(+), 2 deletions(-) diff --git a/src/SaoMiguelBus/settings.py b/src/SaoMiguelBus/settings.py index 76dfd55..5e65208 100755 --- a/src/SaoMiguelBus/settings.py +++ b/src/SaoMiguelBus/settings.py @@ -12,6 +12,14 @@ import os +import environ + +env = environ.Env() +# Reading .env file +environ.Env.read_env() + +GOOGLE_MAPS_API_KEY = env('GOOGLE_MAPS_API_KEY') + # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, "static") diff --git a/src/SaoMiguelBus/urls.py b/src/SaoMiguelBus/urls.py index 6069271..2cfe7b2 100755 --- a/src/SaoMiguelBus/urls.py +++ b/src/SaoMiguelBus/urls.py @@ -37,5 +37,6 @@ path('api/v1/info/active', views.get_active_infos_v1), path('api/v1/stats/group', views.get_group_stats_v1), path('api/v1/infos', views.get_infos_v1), + path('api/v1/gmaps', views.get_gmaps_v1), path('statistics', views.stats), ] diff --git a/src/app/views.py b/src/app/views.py index 4ee2757..57fbfd8 100755 --- a/src/app/views.py +++ b/src/app/views.py @@ -2,6 +2,7 @@ from difflib import SequenceMatcher from django.shortcuts import render from django.utils import timezone +from SaoMiguelBus import settings from numpy import full from rest_framework.decorators import api_view from rest_framework.response import Response @@ -10,7 +11,9 @@ from django.views.decorators.http import require_GET, require_POST from datetime import datetime, date, timedelta from statistics import median -import json +import requests +from django.http import JsonResponse + #Get All Stops @api_view(['GET']) @@ -73,6 +76,47 @@ def get_trip_v1(request): except Exception as e: print(e) return Response(status=404) + +@api_view(['GET']) +@require_GET +def get_gmaps_v1(request): + # If can use maps is true + # variable = Variables.objects.all().first().__dict__ + # if not variable['maps']: + # return JsonResponse({'error': 'Google Maps API is disabled'}, status=400) + + origin = request.GET.get('origin') + destination = request.GET.get('destination') + datetime_str = request.GET.get('datetime') # Expected in ISO format + language_code = request.GET.get('languageCode', 'en') # Default language set to English + arrival_departure = request.GET.get('arrival_departure', 'departure') + + if not (origin and destination and datetime_str): + return JsonResponse({'error': 'Missing required parameters'}, status=400) + + # Convert datetime from ISO format to datetime object + try: + datetime_obj = datetime.fromisoformat(datetime_str) + except ValueError: + return JsonResponse({'error': 'Invalid datetime format'}, status=400) + + # Build the Google Maps API URL + maps_url = f"https://maps.googleapis.com/maps/api/directions/json?origin={origin}&destination={destination}&mode=transit&key={settings.GOOGLE_MAPS_API_KEY}&language={language_code}&alternatives=true" + + if arrival_departure == 'arrival': + maps_url += f"&arrival_time={int(datetime_obj.timestamp())}" + else: + maps_url += f"&departure_time={int(datetime_obj.timestamp())}" + try: + response = requests.get(maps_url) + if response.status_code == 200: + data = response.json() + # Process the data and return as needed + return JsonResponse(data) # Simplified for demonstration + else: + return JsonResponse({'warning': 'NA'}, status=response.status_code) + except Exception as e: + return JsonResponse({'warning': 'NA'}, status=500) @api_view(['GET']) @require_GET diff --git a/src/db.sqlite3 b/src/db.sqlite3 index db744d0fe42e79d8f6e575e1288af8b440a8d4fa..6961570973fa8f366f311e9475c4c61f5aec9145 100755 GIT binary patch del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lj)!F%KT)8QCjxW zPj;<9lXfgkS4CfnJg|>eJry^1jXq5XQFYs9OY}0Iep7X~pVMwCM4{Mh<)5~!y2@+% zTN6y*fXy~()5RCr9jMW@E=|H9!FRmH6WqmB4D!Qc5Icm^)LJPXwhQnq(_^lzdEOZZ z%=n3DED$yO&6EAHWN%+08Bg>r)FU2_;MOCe@y*fK8qE*ukE-H=81QnWXJUY5h5g=& S%}T7>$!jBCw=&J9&iw^dIi3vw diff --git a/src/requirements.txt b/src/requirements.txt index 8e0f5c1..1eb8b0b 100755 --- a/src/requirements.txt +++ b/src/requirements.txt @@ -6,4 +6,6 @@ numpy==1.23.3 jsonfield==3.1.0 SQLAlchemy==1.4.41 gunicorn==20.1.0 -psycopg2-binary==2.8.6 \ No newline at end of file +django-environ==0.11.2 +requests==2.31.0 +#psycopg2-binary==2.8.6 \ No newline at end of file From ba5dd1890f376d4a5c37b3a02ff2e4f5fe6b5dc5 Mon Sep 17 00:00:00 2001 From: sousaUA Date: Sun, 4 Feb 2024 09:39:15 +0000 Subject: [PATCH 3/3] Add AuthKeys --- src/SaoMiguelBus/settings.py | 3 ++- src/app/views.py | 42 ++++++++++++++++++++++-------------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/src/SaoMiguelBus/settings.py b/src/SaoMiguelBus/settings.py index 5e65208..abd21eb 100755 --- a/src/SaoMiguelBus/settings.py +++ b/src/SaoMiguelBus/settings.py @@ -19,6 +19,7 @@ environ.Env.read_env() GOOGLE_MAPS_API_KEY = env('GOOGLE_MAPS_API_KEY') +AUTH_KEY = env('AUTH_KEY') # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) @@ -31,7 +32,7 @@ SECRET_KEY = 'hjq2808rur(19m(zf$3ahcxi=!r74qdvkard7a4yc32j3^jwss' # SECURITY WARNING: don't run with debug turned on in production! -DEBUG = False +DEBUG = True ALLOWED_HOSTS = ['saomiguelbus-api.herokuapp.com', '127.0.0.1'] diff --git a/src/app/views.py b/src/app/views.py index 57fbfd8..fbebdd2 100755 --- a/src/app/views.py +++ b/src/app/views.py @@ -13,7 +13,7 @@ from statistics import median import requests from django.http import JsonResponse - +import pytz #Get All Stops @api_view(['GET']) @@ -84,29 +84,39 @@ def get_gmaps_v1(request): # variable = Variables.objects.all().first().__dict__ # if not variable['maps']: # return JsonResponse({'error': 'Google Maps API is disabled'}, status=400) - + print("here") origin = request.GET.get('origin') destination = request.GET.get('destination') - datetime_str = request.GET.get('datetime') # Expected in ISO format language_code = request.GET.get('languageCode', 'en') # Default language set to English arrival_departure = request.GET.get('arrival_departure', 'departure') - - if not (origin and destination and datetime_str): + time = request.GET.get('time', "NA") + platform = request.GET.get('platform', 'NA') + version = request.GET.get('version', 'NA') + debug = request.GET.get('debug', False) + sessionToken = request.GET.get('sessionToken', 'NA') + key = request.GET.get('key', 'NA') + if key != settings.AUTH_KEY or int(version.split('.')[0]) < 5: + return JsonResponse({'error': 'Unauthorized'}, status=401) + if not debug: + debug = True + + if time == "NA": + # Define the Azores timezone + azores_timezone = pytz.timezone('Atlantic/Azores') + # Get the current UTC time, aware of the timezone + current_utc_time = datetime.now(pytz.utc) + # Convert the current UTC time to Azores time + azores_time = current_utc_time.astimezone(azores_timezone) + # Convert Azores time to Unix timestamp in seconds + time = int(azores_time.timestamp()) + + if not (origin and destination): return JsonResponse({'error': 'Missing required parameters'}, status=400) - # Convert datetime from ISO format to datetime object - try: - datetime_obj = datetime.fromisoformat(datetime_str) - except ValueError: - return JsonResponse({'error': 'Invalid datetime format'}, status=400) - # Build the Google Maps API URL maps_url = f"https://maps.googleapis.com/maps/api/directions/json?origin={origin}&destination={destination}&mode=transit&key={settings.GOOGLE_MAPS_API_KEY}&language={language_code}&alternatives=true" - - if arrival_departure == 'arrival': - maps_url += f"&arrival_time={int(datetime_obj.timestamp())}" - else: - maps_url += f"&departure_time={int(datetime_obj.timestamp())}" + maps_url += f"&arrival_time={time}" if arrival_departure == 'arrival' else f"&departure_time={time}" + try: response = requests.get(maps_url) if response.status_code == 200: