-
Notifications
You must be signed in to change notification settings - Fork 0
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
Timezone utils #194
Merged
Merged
Timezone utils #194
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# from django.contrib import admin | ||
|
||
# Register your models here. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from django.apps import AppConfig | ||
|
||
|
||
class TimezoneUtilsConfig(AppConfig): | ||
default_auto_field = "django.db.models.BigAutoField" | ||
name = "msisdn_utils" |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# from django.db import models | ||
|
||
# Create your models here. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,163 @@ | ||
import json | ||
from datetime import datetime | ||
from unittest.mock import patch | ||
|
||
from django.contrib.auth.models import User | ||
from rest_framework.authtoken.models import Token | ||
from rest_framework.test import APIClient, APITestCase | ||
|
||
|
||
class GetMsisdnTimezonesTest(APITestCase): | ||
def setUp(self): | ||
self.api_client = APIClient() | ||
|
||
self.admin_user = User.objects.create_superuser("adminuser", "admin_password") | ||
|
||
token = Token.objects.get(user=self.admin_user) | ||
self.token = token.key | ||
|
||
self.api_client.credentials(HTTP_AUTHORIZATION="Token " + self.token) | ||
|
||
def test_auth_required_to_get_timezones(self): | ||
response = self.api_client.post( | ||
"/msisdn_utils/timezones/", | ||
data=json.dumps({"whatsapp_id": "something"}), | ||
content_type="application/json", | ||
) | ||
|
||
self.assertEqual(response.status_code, 401) | ||
|
||
def test_no_msisdn_returns_400(self): | ||
self.client.force_authenticate(user=self.admin_user) | ||
response = self.client.post( | ||
"/msisdn_utils/timezones/", | ||
data=json.dumps({}), | ||
content_type="application/json", | ||
) | ||
|
||
self.assertEqual(response.data, {"whatsapp_id": ["This field is required."]}) | ||
self.assertEqual(response.status_code, 400) | ||
|
||
def test_phonenumber_unparseable_returns_400(self): | ||
self.client.force_authenticate(user=self.admin_user) | ||
response = self.client.post( | ||
"/msisdn_utils/timezones/", | ||
data=json.dumps({"whatsapp_id": "something"}), | ||
content_type="application/json", | ||
) | ||
|
||
self.assertEqual( | ||
response.data, | ||
{ | ||
"whatsapp_id": [ | ||
"This value must be a phone number with a region prefix." | ||
] | ||
}, | ||
) | ||
self.assertEqual(response.status_code, 400) | ||
|
||
def test_not_possible_phonenumber_returns_400(self): | ||
# If the length of a number doesn't match accepted length for it's region | ||
self.client.force_authenticate(user=self.admin_user) | ||
response = self.client.post( | ||
"/msisdn_utils/timezones/", | ||
data=json.dumps({"whatsapp_id": "120012301"}), | ||
content_type="application/json", | ||
) | ||
|
||
self.assertEqual( | ||
response.data, | ||
{ | ||
"whatsapp_id": [ | ||
"This value must be a phone number with a region prefix." | ||
] | ||
}, | ||
) | ||
self.assertEqual(response.status_code, 400) | ||
|
||
def test_invalid_phonenumber_returns_400(self): | ||
# If a phone number is invalid for it's region | ||
self.client.force_authenticate(user=self.admin_user) | ||
response = self.client.post( | ||
"/msisdn_utils/timezones/", | ||
data=json.dumps({"whatsapp_id": "12001230101"}), | ||
content_type="application/json", | ||
) | ||
|
||
self.assertEqual( | ||
response.data, | ||
{ | ||
"whatsapp_id": [ | ||
"This value must be a phone number with a region prefix." | ||
] | ||
}, | ||
) | ||
self.assertEqual(response.status_code, 400) | ||
|
||
def test_phonenumber_with_plus(self): | ||
self.client.force_authenticate(user=self.admin_user) | ||
response = self.client.post( | ||
"/msisdn_utils/timezones/", | ||
data=json.dumps({"whatsapp_id": "+27345678910"}), | ||
content_type="application/json", | ||
) | ||
|
||
self.assertEqual( | ||
response.data, {"success": True, "timezones": ["Africa/Johannesburg"]} | ||
) | ||
self.assertEqual(response.status_code, 200) | ||
|
||
def test_single_timezone_number(self): | ||
self.client.force_authenticate(user=self.admin_user) | ||
response = self.client.post( | ||
"/msisdn_utils/timezones/", | ||
data=json.dumps({"whatsapp_id": "27345678910"}), | ||
content_type="application/json", | ||
) | ||
|
||
self.assertEqual( | ||
response.data, {"success": True, "timezones": ["Africa/Johannesburg"]} | ||
) | ||
self.assertEqual(response.status_code, 200) | ||
|
||
def test_multiple_timezone_number_returns_all(self): | ||
self.client.force_authenticate(user=self.admin_user) | ||
response = self.client.post( | ||
"/msisdn_utils/timezones/", | ||
data=json.dumps({"whatsapp_id": "61498765432"}), | ||
content_type="application/json", | ||
) | ||
|
||
self.assertEqual( | ||
response.data, | ||
{ | ||
"success": True, | ||
"timezones": [ | ||
"Australia/Adelaide", | ||
"Australia/Brisbane", | ||
"Australia/Eucla", | ||
"Australia/Lord_Howe", | ||
"Australia/Perth", | ||
"Australia/Sydney", | ||
"Indian/Christmas", | ||
"Indian/Cocos", | ||
], | ||
}, | ||
) | ||
self.assertEqual(response.status_code, 200) | ||
|
||
def test_return_one_flag_gives_middle_timezone(self): | ||
self.client.force_authenticate(user=self.admin_user) | ||
|
||
with patch("msisdn_utils.views.datetime") as mock_datetime: | ||
mock_datetime.utcnow.return_value = datetime(2022, 8, 8) | ||
response = self.client.post( | ||
"/msisdn_utils/timezones/?return_one=true", | ||
data=json.dumps({"whatsapp_id": "61498765432"}), | ||
content_type="application/json", | ||
) | ||
|
||
self.assertEqual( | ||
response.data, {"success": True, "timezones": ["Australia/Adelaide"]} | ||
) | ||
self.assertEqual(response.status_code, 200) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
from django.urls import path | ||
|
||
from . import views | ||
|
||
urlpatterns = [ | ||
path( | ||
"timezones/", | ||
views.GetMsisdnTimezones.as_view(), | ||
name="get-timezones", | ||
), | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
import logging | ||
from datetime import datetime | ||
from math import floor | ||
|
||
import phonenumbers | ||
import pytz | ||
from phonenumbers import timezone as ph_timezone | ||
from rest_framework import authentication, permissions | ||
from rest_framework.exceptions import ValidationError | ||
from rest_framework.response import Response | ||
from rest_framework.views import APIView | ||
|
||
LOGGER = logging.getLogger(__name__) | ||
|
||
|
||
def get_middle_tz(zones): | ||
timezones = [] | ||
for zone in zones: | ||
offset = pytz.timezone(zone).utcoffset(datetime.utcnow()) | ||
offset_seconds = (offset.days * 86400) + offset.seconds | ||
timezones.append({"name": zone, "offset": offset_seconds / 3600}) | ||
ordered_tzs = sorted(timezones, key=lambda k: k["offset"]) | ||
|
||
approx_tz = ordered_tzs[floor(len(ordered_tzs) / 2)]["name"] | ||
|
||
LOGGER.info( | ||
"Available timezones: {}. Returned timezone: {}".format(ordered_tzs, approx_tz) | ||
) | ||
return approx_tz | ||
|
||
|
||
class GetMsisdnTimezones(APIView): | ||
authentication_classes = [authentication.BasicAuthentication] | ||
permission_classes = [permissions.IsAdminUser] | ||
|
||
def post(self, request, *args, **kwargs): | ||
try: | ||
msisdn = request.data["whatsapp_id"] | ||
except KeyError: | ||
raise ValidationError({"whatsapp_id": ["This field is required."]}) | ||
|
||
msisdn = msisdn if msisdn.startswith("+") else "+" + msisdn | ||
|
||
try: | ||
msisdn = phonenumbers.parse(msisdn) | ||
except phonenumbers.phonenumberutil.NumberParseException: | ||
raise ValidationError( | ||
{ | ||
"whatsapp_id": [ | ||
"This value must be a phone number with a region prefix." | ||
] | ||
} | ||
) | ||
|
||
if not ( | ||
phonenumbers.is_possible_number(msisdn) | ||
and phonenumbers.is_valid_number(msisdn) | ||
): | ||
raise ValidationError( | ||
{ | ||
"whatsapp_id": [ | ||
"This value must be a phone number with a region prefix." | ||
] | ||
} | ||
) | ||
|
||
zones = list(ph_timezone.time_zones_for_number(msisdn)) | ||
if ( | ||
len(zones) > 1 | ||
and request.query_params.get("return_one", "false").lower() == "true" | ||
): | ||
zones = [get_middle_tz(zones)] | ||
|
||
return Response({"success": True, "timezones": zones}, status=200) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@MatthewWeppenaar did you update these or did an automated action update them?
I'm concerned about the removal of some of the libraries (especially boto3) so just want to check if something prompted you to do it or if it's automated.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Im not sure why this was removed, i didn't manually edit that line in
setup.cfg
so it must have been removed when i ran a function in the command line🤷♂️ Shall i add that line back?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ok no that's fine. Just wanted to understand the reason behind it but if it was an automated process then it was probably removed in a previous change and the setup.cfg file wasn't updated.