Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating prayer time api to aladhan.com for added functionality #21

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions aladhan_com_fetcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Fetches prayer times from 'www.aladhan.com'."""

import json
import requests
import util
from common import CalculationMethod
from datetime import datetime, timedelta
import time
from gmaps_client import GetTimezone, ReverseGeocodeCountry

_ALADHAN_API_URL = 'http://api.aladhan.com/v1/timings/'


def GetCalcMethod(lat, lng):
"""Returns the Calculation method based on given region

MWL: Europe and Far East
ISNA: North America
Egypt: Africa, Syria, Lebanon, Malaysia
Umm Al Qura: Arabian Peninsula
U. of Islamic Sciences: Pakistan, Afganistan, India, Bangladesh
Institute of Geophysics, University of Tehran: Iran
Kuwait: Kuwait
Qatar: Qatar
Majlis Ugama Islam Singapura, Singapore: Singapore
Union Organization islamic de France: France
Diyanet Isleri Baskanligi, Turkey: Turkey

Args:
lat: a double representing the latitude
lng: a double representing the longitude

Returns: calculation method"""

country = ReverseGeocodeCountry(lat, lng)

if country:
country_calc_method = util.CountryToCalculationMethod(country)
if country_calc_method > 0:
return country_calc_method

if lng >= -180 and lng < -30:
#ISNA
return CalculationMethod.ISNA
elif lng >= -30 and lng < 35 and lat >= -35 and lat <= 35:
#EGYPT
return CalculationMethod.EGYPT
elif lng >= 35 and lng < 60 and lat >= 10 and lat <= 30:
#MAKKAH
return CalculationMethod.MAKKAH
elif lng >= 60 and lng < 95 and lat >= 5 and lat <= 40:
#KAR
return CalculationMethod.KAR
else:
#MWL
return CalculationMethod.MWL


def GetDailyPrayerTimes(lat, lng, date_str):
"""Gets the daily prayer times from 'aladhan.com'.

Performs a POST request on the aladhan.com prayer times API

Args:
lat: a double representing the latitude
lng: a double representing the longitude
date_str: a string representing the requested date in YYYY-MM-DD

Returns: a dict containing of daily prayer times and an day difference integer
"""
# set up the parameters in the format expected by 'aladhan.com'
post_data = {
'latitude': lat,
'longitude': lng,
'method' : GetCalcMethod(lat, lng),
}

current_user_timestamp = util.GetCurrentUserTime(lat, lng)

timestamp = current_user_timestamp
date_time_format = "%Y-%m-%d %H:%M:%S"
day_difference = 0

if date_str and date_str != "None":
try:
agent_date = util.GetCurrentUserTime(37, -121).date()
requested_date = datetime.strptime(date_str, "%Y-%m-%d").date()
day_difference = int((requested_date - agent_date).days)

if day_difference > 0:
timestamp = current_user_timestamp + timedelta(days=day_difference)
except BaseException:
pass

try:
timestamp_UTC = str(int(time.mktime(timestamp.timetuple())))
except BaseException:
timestamp_UTC = 0

#print 'post_data = ', post_data
for request_try in range(3):
try:
request = requests.get(_ALADHAN_API_URL+timestamp_UTC, params=post_data, timeout=15)
if request.status_code == requests.codes.ok:
break
elif request_try == 2:
return (None, None)
except BaseException:
if request_try == 2:
return (None, None)
continue

response = json.loads(request.text).get("data").get("timings")
return (response, day_difference)

155 changes: 74 additions & 81 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from flask import Flask, request, render_template, redirect
from oauth2.tokengenerator import URandomTokenGenerator

from fake_db import FakeDb
from db import Database
from prayer_info import PrayerInfo
from intent_handler import IntentHandler
Expand All @@ -16,117 +15,111 @@
# pylint: disable-msg=C0103
app = Flask(__name__)
_prayer_info = PrayerInfo()
_fake_db = FakeDb()
_db = Database()
_token_generator = URandomTokenGenerator(20)
_intent_handler = IntentHandler(_prayer_info, _fake_db, _db)
_intent_handler = IntentHandler(_prayer_info, _db)


@app.route('/')
def home():
"""GET handler for home page."""
return 'Welcome to the Islam Buddy API!'
"""GET handler for home page."""
return 'Welcome to the Islam Buddy API!'


@app.route('/table', methods=['GET'])
def table():
id = request.args.get('id')
command = request.args.get('command')
response = {}
if command == 'add':
response = 'add is disabled'
"""
id = request.args.get('id')
command = request.args.get('command')
response = {}
if command == 'add':
response = 'add is disabled'
"""
_db.AddOrUpdateUser(id, {
'user_info': {'foo': id},
'city': request.args.get('city')
})
response = 'user ', id, ' was added'
"""
elif command == 'get':
response = _db.GetUser(id)
elif command == 'delete':
_db.DeleteUser(id)
response = 'user ', id, ' was deleted'
return util.JsonResponse(response)
elif command == 'get':
response = _db.GetUser(id)
elif command == 'delete':
_db.DeleteUser(id)
response = 'user ', id, ' was deleted'
return util.JsonResponse(response)


@app.route('/salah', methods=['POST', 'GET'])
def salah():
"""GET and POST handler for /salah page."""
if request.method == 'GET':
#print 'received GET request'
params = {
'lat': request.args.get('lat'),
'lng': request.args.get('lng'),
'prayer': request.args.get('prayer'),
}
#print 'params = ', params

if not params.get('lat') or not params.get('lng'):
return util.JsonError('Please provide a lat and lng.')

prayer_times = \
PrayerInfo.GetPrayerTimes(params.get('lat'), params.get('lng'))
if prayer_times == {}:
return util.JsonResponse(
"Error, the latitude and longitude entered might be wrong..")

# convert from map<PrayerTime, string> to map<string, string>
output_prayer_times = {}
for key in prayer_times:
output_prayer_times[util.GetPrayerKeyName(key)] = prayer_times[key]

return util.JsonResponse(output_prayer_times)

elif request.method == 'POST':
#print 'received POST request'

post_params = request.get_json(silent=True, force=True)
#print 'post_params = \n', json.dumps(post_params, indent=2)

post_intent_name = post_params.get('result').get('metadata').get(
'intentName')
#print 'intent_name = ', post_intent_name

if post_intent_name in IntentHandler.INTENTS_HANDLED:
server_response = _intent_handler.HandleIntent(post_params)
elif post_intent_name == 'CLEAR_LOCATION':
user_id = post_params.get('originalRequest').get('data').get('user').get(
'userId')
_fake_db.DeleteUser(user_id)
server_response = {
"speech": "OK, your location has been cleared.",
}
else:
server_response = {
"speech": "Sorry, Prayer Pal cannot process this request." \
" Please try again later.",
}

#print 'server response = ', server_response
return util.JsonResponse(server_response)
"""GET and POST handler for /salah page."""
if request.method == 'GET':
#print 'received GET request'
params = {
'lat': request.args.get('lat'),
'lng': request.args.get('lng'),
'prayer': request.args.get('prayer'),
}
#print 'params = ', params

if not params.get('lat') or not params.get('lng'):
return util.JsonError('Please provide a lat and lng.')

prayer_times = \
PrayerInfo.GetPrayerTimes(params.get('lat'), params.get('lng'), None)
if prayer_times == {}:
return util.JsonResponse(
"Error, the latitude and longitude entered might be wrong..")

# convert from map<PrayerTime, string> to map<string, string>
output_prayer_times = {}
for key in prayer_times:
output_prayer_times[util.GetPrayerKeyName(key)] = prayer_times[key]

return util.JsonResponse(output_prayer_times)

elif request.method == 'POST':
post_params = request.get_json(silent=True, force=True)

post_intent_name = post_params.get('result').get('metadata').get(
'intentName')

if post_intent_name in IntentHandler.INTENTS_HANDLED:
server_response = _intent_handler.HandleIntent(post_params)
elif post_intent_name == 'CLEAR_LOCATION':
user_id = post_params.get('originalRequest').get('data').get('user').get(
'userId')
_db.DeleteUser(user_id)
server_response = {
"speech": "OK, your location has been cleared.",
}
else:
server_response = {
"speech": "Sorry, Prayer Pal cannot process this request."
" Please try again later.",
}

return util.JsonResponse(server_response)


@app.route('/auth', methods=['GET'])
def authenticate():
"""Authentication handler."""
redirect_uri = request.args.get('redirect_uri')
state = request.args.get('state')
access_token = _token_generator.generate()
full_redirect_uri = '{}#access_token={}&token_type=bearer&state={}'.format(
redirect_uri, access_token, state)
"""Authentication handler."""
redirect_uri = request.args.get('redirect_uri')
state = request.args.get('state')
access_token = _token_generator.generate()
full_redirect_uri = '{}#access_token={}&token_type=bearer&state={}'.format(
redirect_uri, access_token, state)

#print 'FULL REDIRECT URI: ', full_redirect_uri
#print 'FULL REDIRECT URI: ', full_redirect_uri

return redirect(full_redirect_uri)
return redirect(full_redirect_uri)


@app.route('/privacy', methods=['GET'])
def render_privacy():
"""Privacy handler."""
return render_template('privacy.html')
"""Privacy handler."""
return render_template('privacy.html')


if __name__ == '__main__':
app.run()
app.run()

16 changes: 16 additions & 0 deletions common.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,19 @@ class Locality(object):
CITY = 1
MASJID = 2


class CalculationMethod(object):
UNSPECIFIED = 0
KAR = 1
ISNA = 2
MWL = 3
MAKKAH = 4
EGYPT = 5
TEHRAN = 7
GULF = 8
KUWAIT = 9
QATAR = 10
SINGAPORE = 11
FRANCE = 12
TURKEY = 13

Loading