From fdfe8a06c84d9e8fb98423ff5019332b7aa74f4b Mon Sep 17 00:00:00 2001 From: Robin Richtsfeld Date: Mon, 14 May 2018 20:46:30 +0200 Subject: [PATCH] Unify sanity checks Signed-off-by: Robin Richtsfeld --- matrix_client/checks.py | 14 ++++++++++++++ matrix_client/client.py | 2 ++ matrix_client/room.py | 7 ++----- matrix_client/user.py | 9 ++++----- 4 files changed, 22 insertions(+), 10 deletions(-) create mode 100644 matrix_client/checks.py diff --git a/matrix_client/checks.py b/matrix_client/checks.py new file mode 100644 index 00000000..510167ab --- /dev/null +++ b/matrix_client/checks.py @@ -0,0 +1,14 @@ +def check_room_id(room_id): + if not room_id.startswith("!"): + raise ValueError("RoomIDs start with !") + + if ":" not in room_id: + raise ValueError("RoomIDs must have a domain component, seperated by a :") + + +def check_user_id(user_id): + if not user_id.startswith("@"): + raise ValueError("UserIDs start with @") + + if ":" not in user_id: + raise ValueError("UserIDs must have a domain component, seperated by a :") diff --git a/matrix_client/client.py b/matrix_client/client.py index 67c3ea0e..be1abe74 100644 --- a/matrix_client/client.py +++ b/matrix_client/client.py @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. from .api import MatrixHttpApi +from .checks import check_user_id from .errors import MatrixRequestError, MatrixUnexpectedResponse from .room import Room from .user import User @@ -146,6 +147,7 @@ def __init__(self, base_url, token=None, user_id=None, # room_id: Room } if token: + check_user_id(user_id) self.user_id = user_id self._sync() diff --git a/matrix_client/room.py b/matrix_client/room.py index d4a74969..bd72f99f 100644 --- a/matrix_client/room.py +++ b/matrix_client/room.py @@ -1,6 +1,7 @@ import re from uuid import uuid4 +from .checks import check_room_id from .user import User from .errors import MatrixRequestError @@ -16,11 +17,7 @@ def __init__(self, client, room_id): NOTE: This should ideally be called from within the Client. NOTE: This does not verify the room with the Home Server. """ - if not room_id.startswith("!"): - raise ValueError("RoomIDs start with !") - - if ":" not in room_id: - raise ValueError("RoomIDs must have a domain component, seperated by a :") + check_room_id(room_id) self.room_id = room_id self.client = client diff --git a/matrix_client/user.py b/matrix_client/user.py index 839d462b..a4f51578 100644 --- a/matrix_client/user.py +++ b/matrix_client/user.py @@ -1,12 +1,11 @@ +from .checks import check_user_id + + class User(object): """ The User class can be used to call user specific functions. """ def __init__(self, api, user_id, displayname=None): - if not user_id.startswith("@"): - raise ValueError("UserIDs start with @") - - if ":" not in user_id: - raise ValueError("UserIDs must have a domain component, seperated by a :") + check_user_id(user_id) self.user_id = user_id self.displayname = displayname