diff --git a/CHANGELOG.md b/CHANGELOG.md index 24ff786e..6f41b7c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ All notable changes to this project will be documented in this file. ### Bug Fixes - Removing Pager Team integration, project appears to be discontinued - Sending a test notification updates Channel.last_error (#391) +- Handle HTTP 429 responses from Matrix server when joining a Matrix room ## v1.15.0 - 2020-06-04 diff --git a/hc/front/forms.py b/hc/front/forms.py index bb35decb..3aaabc96 100644 --- a/hc/front/forms.py +++ b/hc/front/forms.py @@ -207,7 +207,14 @@ class AddMatrixForm(forms.Form): url = settings.MATRIX_HOMESERVER url += "/_matrix/client/r0/join/%s?" % quote(v) url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN}) - doc = requests.post(url, {}).json() + r = requests.post(url, {}) + if r.status_code == 429: + raise forms.ValidationError( + "Matrix server returned status code 429 (Too Many Requests), " + "please try again later." + ) + + doc = r.json() if "error" in doc: raise forms.ValidationError("Response from Matrix: %s" % doc["error"]) diff --git a/hc/front/tests/test_add_matrix.py b/hc/front/tests/test_add_matrix.py index fe729c94..d7b32e41 100644 --- a/hc/front/tests/test_add_matrix.py +++ b/hc/front/tests/test_add_matrix.py @@ -1,3 +1,4 @@ +from json import JSONDecodeError from unittest.mock import patch from django.test.utils import override_settings @@ -37,3 +38,14 @@ class AddMatrixTestCase(BaseTestCase): self.client.login(username="alice@example.org", password="password") r = self.client.get(self.url) self.assertEqual(r.status_code, 404) + + @patch("hc.front.forms.requests.post") + def test_it_handles_429(self, mock_post): + mock_post.return_value.status_code = 429 + + form = {"alias": "!foo:example.org"} + self.client.login(username="alice@example.org", password="password") + r = self.client.post(self.url, form) + + self.assertContains(r, "Matrix server returned status code 429") + self.assertFalse(Channel.objects.exists())