├── .gitignore ├── LICENSE ├── LayerClient ├── LayerClient.py └── __init__.py ├── README.md ├── requirements-dev.txt ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── test_api_exception.py ├── test_create_conversation.py ├── test_delete_conversation.py ├── test_get_conversation.py ├── test_prepare_rich_content.py ├── test_send_announcement.py ├── test_send_message.py └── test_utils.py └── tox.ini /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | #PyCharm 60 | .idea 61 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /LayerClient/LayerClient.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import absolute_import, unicode_literals 3 | 4 | import json 5 | import sys 6 | 7 | import dateutil.parser 8 | import requests 9 | 10 | try: 11 | from urlparse import urlparse 12 | except ImportError: 13 | from urllib.parse import urlparse 14 | 15 | MIME_TEXT_PLAIN = 'text/plain' 16 | 17 | METHOD_GET = 'GET' 18 | METHOD_POST = 'POST' 19 | METHOD_DELETE = 'DELETE' 20 | METHOD_PATCH = 'PATCH' 21 | METHOD_PUT = 'PUT' 22 | 23 | LAYER_URI_ANNOUNCEMENTS = 'announcements' 24 | LAYER_URI_CONVERSATIONS = 'conversations' 25 | LAYER_URI_MESSAGES = 'messages' 26 | LAYER_URI_CONTENT = 'content' 27 | LAYER_URI_RECEIPTS = 'receipts' 28 | 29 | LAYER_URI_USERS = 'users' 30 | LAYER_URI_USERS_IDENTITY = 'identity' 31 | LAYER_URI_USERS_BADGE = 'badge' 32 | 33 | 34 | def safe_unicode(string): 35 | if sys.version_info[0] < 3: 36 | return unicode(string) # NOQA 37 | return str(string) 38 | 39 | 40 | class LayerMessageReceipt(object): 41 | READ = "read" 42 | DELIVERY = "delivery" 43 | 44 | 45 | class LayerPlatformException(Exception): 46 | def __init__(self, message, http_code=None, code=None, error_id=None): 47 | super(LayerPlatformException, self).__init__(message) 48 | self.http_code = http_code 49 | self.code = code 50 | self.error_id = error_id 51 | 52 | 53 | class BaseLayerResponse(object): 54 | """ 55 | Base class for several of the datatypes returned by Layer - if it returns 56 | an ID and a URL, it should extend this class in order to get UUID parsing. 57 | """ 58 | 59 | def __init__(self, id, url): 60 | self.id = id 61 | self.url = url 62 | 63 | if not self.id or not self.url: 64 | raise ValueError("Response must contain at least an ID and a URL") 65 | 66 | def uuid(self): 67 | """ 68 | When we get a conversation response from the server, it doesn't include 69 | the raw UUID, only a URI of the form: 70 | layer:///conversations/f3cc7b32-3c92-11e4-baad-164230d1df67 71 | which must be parsed to retrieve the UUID for easy reference. 72 | """ 73 | uri = urlparse(self.id) 74 | path_parts = uri.path.split('/') 75 | if len(path_parts) == 3 and len(path_parts[2]) == 36: 76 | return path_parts[2] 77 | 78 | return None 79 | 80 | @staticmethod 81 | def parse_date(date): 82 | """ 83 | Convert an ISO 8601 datestamp format to a Python date object. 84 | 85 | Parameter `date`: A string datestamp in ISO 8601 format. May be None. 86 | Return: A datetime, or None if the date string was empty. 87 | """ 88 | 89 | if not date: 90 | return None 91 | 92 | return dateutil.parser.parse(date) 93 | 94 | 95 | class PlatformClient(object): 96 | """ 97 | Client to the server-side layer API 98 | """ 99 | 100 | def __init__(self, app_uuid, bearer_token): 101 | """ 102 | Create a new Layer platform client. 103 | 104 | Parameters: 105 | - `app_uuid`: The UUID for the application 106 | - `bearer_token`: A Layer authorization token, as generated by the 107 | Developer dashboard 108 | """ 109 | self.app_uuid = app_uuid 110 | self.bearer_token = bearer_token 111 | 112 | def _get_layer_headers(self, method): 113 | """ 114 | Convenience method for retrieving the default set of authenticated 115 | headers. 116 | 117 | Return: The headers required to authorize ourselves with the Layer 118 | platform API. 119 | """ 120 | 121 | content_type = 'application/json' 122 | if method == METHOD_PATCH: 123 | content_type = 'application/vnd.layer-patch+json' 124 | 125 | return { 126 | 'Accept': 'application/vnd.layer+json; version=1.0', 127 | 'Authorization': 'Bearer ' + self.bearer_token, 128 | 'Content-Type': content_type 129 | } 130 | 131 | def _get_layer_uri(self, *suffixes): 132 | """ 133 | Used for building Layer URIs for different API endpoints. 134 | 135 | Parameter`suffixes`: An array of strings, which will be joined as the 136 | end portion of the URI body. 137 | 138 | Return: A complete URI for an endpoint with optional arguments 139 | """ 140 | return 'https://api.layer.com/apps/{app_id}/{suffix}'.format( 141 | app_id=self.app_uuid, 142 | suffix='/'.join(map(safe_unicode, suffixes)), 143 | ) 144 | 145 | def _raw_request(self, method, url, data=None, extra_headers=None, 146 | params=None): 147 | """ 148 | Actually make a call to the Layer API. 149 | If the response does not come back as valid, raises a 150 | LayerPlatformException with the error data from Layer. 151 | 152 | Parameters: 153 | - `method`: The HTTP method to use 154 | - `url`: The target URL 155 | - `data`: Optional post body. Must be json encodable. 156 | 157 | Return: Raw JSON doc of the Layer API response 158 | 159 | Exception: `LayerPlatformException` if the API returns non-OK response 160 | """ 161 | headers = self._get_layer_headers(method) 162 | if extra_headers: 163 | headers.update(extra_headers) 164 | result = requests.request( 165 | method, 166 | url, 167 | headers=headers, 168 | data=(json.dumps(data) if data else None), 169 | params=params 170 | ) 171 | 172 | if result.ok: 173 | try: 174 | return result.json() 175 | except ValueError: 176 | # On patch requests it fails because there is no response 177 | return result 178 | try: 179 | error = result.json() 180 | raise LayerPlatformException( 181 | error.get('message'), 182 | http_code=result.status_code, 183 | code=error.get('code'), 184 | error_id=error.get('id'), 185 | ) 186 | except ValueError: 187 | # Catches the JSON decode error for failures that do not have 188 | # associated data 189 | raise LayerPlatformException( 190 | result.text, 191 | http_code=result.status_code, 192 | ) 193 | 194 | def get_conversation(self, conversation_uuid): 195 | """ 196 | Fetch an existing conversation by UUID 197 | 198 | Parameter `conversation_uuid`: The UUID of the conversation to fetch 199 | 200 | Return: A `Conversation` instance 201 | """ 202 | return Conversation.from_dict( 203 | self._raw_request( 204 | METHOD_GET, 205 | self._get_layer_uri( 206 | LAYER_URI_CONVERSATIONS, 207 | conversation_uuid, 208 | ), 209 | ) 210 | ) 211 | 212 | def get_conversations(self, user_id, page_size=None, from_id=None, 213 | sort_by=None): 214 | """ 215 | Fetch an existing conversation by user UUID 216 | 217 | :param user_id: User ID 218 | :param page_size: (optional) Number of results to return; 100 is 219 | default and max 220 | :param from_id: (optional) Get the Conversations logically sorted 221 | after this ID (by default, this corresponds to Conversations 222 | chronologically before this ID). Can be passed as a Layer URI 223 | layer:///conversations/uuid or simply a UUID 224 | :param sort_by: (optional) Either created_at to sort by Conversation 225 | creation time (newest first), or last_message to sort by most recently 226 | sent message (newest first) 227 | :rtype: list[Conversation] 228 | """ 229 | params = {} 230 | if page_size: 231 | params['page_size'] = page_size 232 | 233 | if from_id: 234 | params['from_id'] = from_id 235 | 236 | if sort_by: 237 | params['sort_by'] = sort_by 238 | 239 | return Conversation.from_list( 240 | self._raw_request( 241 | METHOD_GET, 242 | self._get_layer_uri( 243 | LAYER_URI_USERS, 244 | user_id, 245 | LAYER_URI_CONVERSATIONS 246 | ), 247 | params=params 248 | ) 249 | ) 250 | 251 | def get_messages(self, conversation_uuid, from_id=None, page_size=None): 252 | """ 253 | Fetch list of messages by conversation UUID 254 | 255 | :param conversation_uuid: The UUID of the conversation to fetch 256 | :param page_size: (optional) Number of messages to return; max and 257 | default of 100 258 | :param from_id: (optional) Get the Messages logically sorted after 259 | this ID (by default, this corresponds to Messages chronologically 260 | before this ID). Can be passed as a Layer URI layer:///messages/uuid 261 | or simply a UUID 262 | :rtype: list[Message] 263 | """ 264 | params = {} 265 | if page_size: 266 | params['page_size'] = page_size 267 | 268 | if from_id: 269 | params['from_id'] = from_id 270 | 271 | return Message.from_list( 272 | self._raw_request( 273 | METHOD_GET, 274 | self._get_layer_uri( 275 | LAYER_URI_CONVERSATIONS, 276 | conversation_uuid, 277 | LAYER_URI_MESSAGES 278 | ), 279 | params=params 280 | ) 281 | ) 282 | 283 | def send_message_receipt(self, user_id, message_uuid, receipt_type): 284 | """ 285 | Mark message as "read" or "delivered" 286 | :param user_id: ID of User 287 | :type user_id: unicode 288 | :param message_uuid: UUID of Message 289 | :type message_uuid: unicode 290 | :param receipt_type: Use LayerMessageReceipt (possible values are 291 | "delivery" and "read") 292 | :type receipt_type: unicode 293 | """ 294 | 295 | return self._raw_request( 296 | METHOD_POST, 297 | self._get_layer_uri( 298 | LAYER_URI_USERS, 299 | user_id, 300 | LAYER_URI_MESSAGES, 301 | message_uuid, 302 | LAYER_URI_RECEIPTS 303 | ), 304 | data={ 305 | "type": receipt_type 306 | } 307 | ) 308 | 309 | def delete_conversation(self, conversation_uuid): 310 | """ 311 | Delete a conversation. Affects all users in the conversation across all 312 | of their devices. 313 | 314 | Parameter `conversation_uuid`: The uuid of the conversation to delete 315 | """ 316 | self._raw_request( 317 | METHOD_DELETE, 318 | self._get_layer_uri( 319 | LAYER_URI_CONVERSATIONS, 320 | conversation_uuid, 321 | ), 322 | ) 323 | 324 | def create_conversation(self, participants, distinct=True, metadata=None): 325 | """ 326 | Create a new converstaion. 327 | 328 | Parameters: 329 | - `participants`: An array of participant IDs (strings) 330 | - `distinct`: Whether or not we should create a new conversation for 331 | the participants, or re-use one if one exists. Will return an 332 | existing conversation if distinct=True. 333 | - `metadata`: Unstructured data to be passed through to the client. 334 | This data must be json-serializable. 335 | 336 | Return: A new `Conversation` instance 337 | """ 338 | return Conversation.from_dict( 339 | self._raw_request( 340 | METHOD_POST, 341 | self._get_layer_uri( 342 | LAYER_URI_CONVERSATIONS, 343 | ), 344 | { 345 | 'participants': participants, 346 | 'distinct': distinct, 347 | 'metadata': metadata, 348 | } 349 | ) 350 | ) 351 | 352 | def update_conversation(self, conversation_uuid, metadata=None, 353 | custom_operations=None): 354 | ''' 355 | Updates metadata of conversation 356 | 357 | :param conversation_uuid: Conversation uuid. For backwards compatibily 358 | accepts also `Conversation` object 359 | :param metadata: Unstructured data to be passed through to the client. 360 | This data must be json-serializable. 361 | :param custom_operations: Other operations you want to do on 362 | the conversation 363 | :return: `Response` object 364 | ''' 365 | 366 | if isinstance(conversation_uuid, Conversation): 367 | conversation_uuid = conversation_uuid.uuid() 368 | 369 | operations = [] 370 | if metadata: 371 | operations.append( 372 | { 373 | "operation": "set", 374 | "property": "metadata", 375 | "value": metadata 376 | } 377 | ) 378 | if custom_operations: 379 | operations += custom_operations 380 | 381 | return self._raw_request( 382 | METHOD_PATCH, 383 | self._get_layer_uri( 384 | LAYER_URI_CONVERSATIONS, 385 | conversation_uuid 386 | ), 387 | operations 388 | ) 389 | 390 | def replace_identity(self, identity): 391 | ''' 392 | Updates metadata of user 393 | 394 | :param identity: `Sender` object 395 | :return: `Response` object 396 | ''' 397 | 398 | return self._raw_request( 399 | METHOD_PUT, 400 | self._get_layer_uri( 401 | LAYER_URI_USERS, 402 | identity.id, 403 | LAYER_URI_USERS_IDENTITY 404 | ), 405 | identity.as_dict() 406 | ) 407 | 408 | def update_user_external_badge_count(self, identity_id, count): 409 | ''' 410 | Updates external badge count of user 411 | 412 | :param identity_id: `Str` identifier of user 413 | :param count: `int` value 414 | :return: `Response` object 415 | ''' 416 | 417 | return self._raw_request( 418 | METHOD_PUT, 419 | self._get_layer_uri( 420 | LAYER_URI_USERS, 421 | identity_id, 422 | LAYER_URI_USERS_BADGE 423 | ), 424 | { 425 | 'external_unread_count': count 426 | } 427 | ) 428 | 429 | def get_identity(self, user_id): 430 | ''' 431 | Updates metadata of conversation 432 | 433 | :param identity: `Sender` object 434 | :return: `Sender` object 435 | ''' 436 | 437 | return Sender.from_dict(self._raw_request( 438 | METHOD_GET, 439 | self._get_layer_uri( 440 | LAYER_URI_USERS, 441 | user_id, 442 | LAYER_URI_USERS_IDENTITY 443 | ) 444 | )) 445 | 446 | def prepare_rich_content(self, conversation, content_type, content_size): 447 | """ 448 | Prepare the rich content by requesting the rich content upload 449 | :return: the prepared rich content ready to upload the content 450 | 451 | NB: once the rich content is prepared, you need to upload the content 452 | to the cloud storage given by the `RichContent.upload_url` property 453 | """ 454 | return RichContent.from_dict( 455 | self._raw_request( 456 | METHOD_POST, 457 | self._get_layer_uri( 458 | LAYER_URI_CONVERSATIONS, 459 | conversation.uuid(), 460 | LAYER_URI_CONTENT 461 | ), 462 | extra_headers={ 463 | 'Upload-Content-Type': content_type, 464 | 'Upload-Content-Length': content_size, 465 | # No support of the upload origin yet 466 | # 'Upload-Origin': 'http://mydomain.com' 467 | } 468 | ) 469 | ) 470 | 471 | def send_message(self, conversation, sender, message_parts, 472 | notification=None): 473 | """ 474 | Send a message to a conversation. 475 | 476 | Parameters: 477 | - `conversation`: A `LayerClient.Conversation` instance for the 478 | conversation we wish to send to 479 | - `sender`: A `LayerClient.Sender` instance 480 | - `message_parts`: An array of `LayerClient.MessagePart` objects 481 | - `notification`: Optional `PushNotification` instance. 482 | 483 | Return: A new Message instance, or None if we were passed invalid 484 | (None) arguments. 485 | """ 486 | 487 | if not conversation or not sender or not message_parts: 488 | return None 489 | 490 | request_data = { 491 | 'sender': sender.as_dict(), 492 | 'parts': [ 493 | part.as_dict() for part in message_parts 494 | ], 495 | } 496 | if notification: 497 | request_data['notification'] = notification.as_dict() 498 | 499 | return Message.from_dict( 500 | self._raw_request( 501 | METHOD_POST, 502 | self._get_layer_uri( 503 | LAYER_URI_CONVERSATIONS, 504 | conversation.uuid(), 505 | LAYER_URI_MESSAGES, 506 | ), 507 | request_data, 508 | ) 509 | ) 510 | 511 | def delete_message(self, conversation_uuid, message_uuid): 512 | """ 513 | Delete a message. Affects all users in the conversation across all 514 | of their devices. 515 | 516 | Parameter `conversation_uuid`: The uuid of the conversation that 517 | message was sent in 518 | Parameter `message_uuid`: The uuid of the message to delete 519 | """ 520 | self._raw_request( 521 | METHOD_DELETE, 522 | self._get_layer_uri( 523 | LAYER_URI_CONVERSATIONS, 524 | conversation_uuid, 525 | LAYER_URI_MESSAGES, 526 | message_uuid, 527 | ), 528 | ) 529 | 530 | def send_announcement(self, sender, recipients, message_parts, 531 | notification=None): 532 | """ 533 | Send an announcement to a list of users. 534 | 535 | Parameters: 536 | - `sender`: A `LayerClient.Sender` instance. The sender must have a 537 | name, as this endpoint cannot be used with a sender ID. 538 | - 'recipients`: A list of strings, each of which is a recipient ID. 539 | - `message_parts`: An array of `LayerClient.MessagePart` objects 540 | - `notification`: Optional `PushNotification` instance. 541 | """ 542 | request_data = { 543 | 'sender': { 544 | 'name': sender.name, 545 | }, 546 | 'parts': [ 547 | part.as_dict() for part in message_parts 548 | ], 549 | 'recipients': recipients, 550 | } 551 | if notification: 552 | request_data['notification'] = notification.as_dict() 553 | 554 | return Announcement.from_dict( 555 | self._raw_request( 556 | METHOD_POST, 557 | self._get_layer_uri(LAYER_URI_ANNOUNCEMENTS), 558 | request_data, 559 | ) 560 | ) 561 | 562 | 563 | class Announcement(BaseLayerResponse): 564 | """ 565 | Contains the data returned from the API when sending an Announcement 566 | """ 567 | 568 | def __init__(self, id, url, sent_at, recipients, sender, parts): 569 | super(Announcement, self).__init__(id, url) 570 | self.sent_at = sent_at 571 | self.recipients = recipients 572 | self.sender = sender 573 | self.parts = parts 574 | 575 | @staticmethod 576 | def from_dict(dict_data): 577 | return Announcement( 578 | dict_data.get('id'), 579 | dict_data.get('url'), 580 | Announcement.parse_date(dict_data.get('sent_at')), 581 | dict_data.get('recipients'), 582 | Sender.from_dict(dict_data.get('sender')), 583 | [ 584 | MessagePart.from_dict(part) 585 | for part in dict_data.get('parts', []) 586 | ], 587 | ) 588 | 589 | def __repr__(self): 590 | return ''.format( 591 | text=self.uuid() 592 | ) 593 | 594 | 595 | class Message(BaseLayerResponse): 596 | """ 597 | The response returned by the API when a message is sent. 598 | """ 599 | 600 | def __init__(self, id, url, sent_at=None, sender=None, 601 | conversation=None, parts=None, recipient_status=None, 602 | is_unread=True): 603 | """ 604 | :type id: unicode 605 | :type url: unicode 606 | :type sent_at: datetime 607 | :type sender: Sender 608 | :type conversation: Conversation 609 | :type parts: list[MessagePart] 610 | :type recipient_status: unicode 611 | :type is_unread: bool 612 | """ 613 | super(Message, self).__init__(id, url) 614 | self.sent_at = sent_at 615 | self.sender = sender 616 | self.conversation = conversation 617 | self.parts = parts 618 | self.recipient_status = recipient_status 619 | self.is_unread = is_unread 620 | 621 | @staticmethod 622 | def from_dict(dict_data): 623 | return Message( 624 | dict_data.get('id'), 625 | dict_data.get('url'), 626 | Message.parse_date(dict_data.get('sent_at')), 627 | Sender.from_dict(dict_data.get('sender')), 628 | Conversation.from_dict(dict_data.get('conversation')), 629 | [ 630 | MessagePart.from_dict(part) 631 | for part in dict_data.get('parts', []) 632 | ], 633 | dict_data.get('recipient_status'), 634 | dict_data.get('is_unread'), 635 | ) 636 | 637 | @classmethod 638 | def from_list(cls, list_data): 639 | return [cls.from_dict(data) for data in list_data] 640 | 641 | def __repr__(self): 642 | return ''.format( 643 | uuid=self.uuid() 644 | ) 645 | 646 | 647 | class Sender: 648 | """ 649 | Used for sending messages. 650 | Id and Name may both be set, but the send_message API will prefer 651 | one over the other. 652 | """ 653 | 654 | def __init__(self, id=None, name=None, display_name=None, avatar_url=None, 655 | first_name=None, last_name=None, 656 | phone_number=None, email_address=None, metadata=None): 657 | self.id = id 658 | self.name = name 659 | self.display_name = display_name 660 | self.avatar_url = avatar_url 661 | self.first_name = first_name 662 | self.last_name = last_name 663 | self.phone_number = phone_number 664 | self.email_address = email_address 665 | self.metadata = metadata 666 | 667 | if not id and not name: 668 | raise ValueError("A sender must have at least one of ID or Name") 669 | 670 | @staticmethod 671 | def from_dict(dict_data): 672 | if not dict_data: 673 | return None 674 | 675 | return Sender( 676 | id=dict_data.get('user_id'), 677 | name=dict_data.get('name'), 678 | display_name=dict_data.get('display_name'), 679 | avatar_url=dict_data.get('avatar_url'), 680 | first_name=dict_data.get('first_name'), 681 | last_name=dict_data.get('last_name'), 682 | phone_number=dict_data.get('phone_number'), 683 | email_address=dict_data.get('email_address'), 684 | metadata=dict_data.get('metadata'), 685 | ) 686 | 687 | def __repr__(self): 688 | return ''.format( 689 | id=self.id, 690 | name=self.name, 691 | ) 692 | 693 | def as_dict(self): 694 | # If both ID and name are set, we will default to only the ID. 695 | # The layer platform explicitly prohibits sending both. 696 | data = {} 697 | if self.display_name: 698 | data['display_name'] = self.display_name 699 | 700 | if self.avatar_url: 701 | data['avatar_url'] = self.avatar_url 702 | 703 | if self.first_name: 704 | data['first_name'] = self.first_name 705 | 706 | if self.last_name: 707 | data['last_name'] = self.last_name 708 | 709 | if self.phone_number: 710 | data['phone_number'] = self.phone_number 711 | 712 | if self.email_address: 713 | data['email_address'] = self.email_address 714 | 715 | if self.metadata: 716 | data['metadata'] = self.metadata 717 | 718 | if self.id: 719 | data['user_id'] = self.id 720 | else: 721 | data['name'] = self.name 722 | 723 | return data 724 | 725 | 726 | class RichContent: 727 | """ 728 | Used to prepare rich content 729 | 730 | Because a message part is limited to 2KiB by Layer, for bigger contents 731 | we need to first upload it to a cloud server. 732 | """ 733 | 734 | def __init__(self, content_id, content_size, upload_url, 735 | download_url=None, refresh_url=None, expiration=None): 736 | self.id = content_id 737 | self.size = content_size 738 | self.upload_url = upload_url 739 | self.download_url = download_url 740 | self.refresh_url = refresh_url 741 | self.expiration = expiration 742 | 743 | @staticmethod 744 | def from_dict(dict_data): 745 | if not dict_data: 746 | return None 747 | 748 | return RichContent( 749 | dict_data.get('id'), 750 | dict_data.get('size'), 751 | dict_data.get('upload_url'), 752 | download_url=dict_data.get('download_url'), 753 | refresh_url=dict_data.get('refresh_url'), 754 | expiration=dict_data.get('expiration'), 755 | ) 756 | 757 | 758 | class MessagePart: 759 | """ 760 | A message chunk, as used for sending messages. 761 | 762 | Message chunks are currently limited to 2KiB by Layer. If a message is 763 | larger, it must be broken into several chunks. 764 | By default, chunks are text/plain but can be any format. 765 | Messages that are non-text (e.g. images) can be sent as base64. In this 766 | case, the encoding field must be set. 767 | 768 | An instance of `MessagePart` can be of two types : 769 | - message chunk with a body 770 | >>> MessagePart("some text") 771 | - message chunk witch a rich content 772 | >>> MessagePart(None, content={"id": "TEST_CONTENT_ID", "size": 23}) 773 | """ 774 | 775 | def __init__(self, body, mime=MIME_TEXT_PLAIN, **kwargs): 776 | self.body = body 777 | self.mime_type = mime 778 | self.encoding = kwargs.get('encoding') 779 | self.content = kwargs.get('content') 780 | if self.body and self.content: 781 | raise ValueError("`body` and `content` are mutually exclusive, " 782 | "you can't define both at the same time") 783 | 784 | @staticmethod 785 | def from_dict(dict_data): 786 | return MessagePart( 787 | dict_data.get('body'), 788 | mime=dict_data.get('mime_type'), 789 | encoding=dict_data.get('encoding'), 790 | content=dict_data.get('content'), 791 | ) 792 | 793 | def __repr__(self): 794 | return ( 795 | ''.format( 796 | body=( 797 | "content of {} bytes length".format( 798 | len(self.content)) if self.content 799 | else self.body 800 | ), 801 | mime=' Content-Type: {0}'.format(self.mime_type), 802 | encoding=( 803 | ' Encoding: {0}'.format(self.encoding) if self.encoding 804 | else '' 805 | ) 806 | ) 807 | ) 808 | 809 | def as_dict(self): 810 | if self.body and self.content: 811 | raise ValueError("`body` and `content` are mutually exclusive, " 812 | "you can't define both at the same time") 813 | data = { 814 | 'mime_type': self.mime_type, 815 | } 816 | if self.body: 817 | data['body'] = self.body 818 | if self.content: 819 | data['content'] = self.content 820 | if self.encoding: 821 | data['encoding'] = self.encoding 822 | 823 | return data 824 | 825 | 826 | class PushNotification: 827 | """ 828 | Details for a push notification sent as part of a conversation message. 829 | Each push notification must have a body. 830 | Sound and recipients are optional. For Android, the sound parameter is 831 | simply sent to the client as a string. 832 | The recipients field is a map of user id to PushNotification object, 833 | allowing for one push notification to have custom settings for certain 834 | users. PushNotification instances used as part of the recipients field 835 | should not themselves have the recipient field set. 836 | """ 837 | 838 | def __init__(self, text, sound=None, recipients=None): 839 | self.text = text 840 | self.sound = sound 841 | self.recipients = recipients 842 | 843 | def __repr__(self): 844 | return ''.format( 845 | text=self.text 846 | ) 847 | 848 | def as_dict(self): 849 | data = { 850 | 'text': self.text, 851 | } 852 | if self.sound: 853 | data['sound'] = self.sound 854 | 855 | if not self.recipients: 856 | return data 857 | 858 | # If per-recipient push notification instances are present, convert 859 | # them to dictionaries as well. We don't simply recurse here to 860 | # ensure that we do not have child PushNotifications with their own 861 | # recipients fields. 862 | recipients_dict = {} 863 | try: 864 | recipients_iter = self.recipients.iteritems() 865 | pass 866 | except AttributeError: 867 | # Raised an atribute error must be using python3 868 | recipients_iter = self.recipients.items() 869 | pass 870 | for recipient, notification in recipients_iter: 871 | recipients_dict[recipient] = { 872 | 'text': notification.text, 873 | 'sound': notification.sound, 874 | } 875 | data['recipients'] = recipients_dict 876 | 877 | return data 878 | 879 | 880 | class Conversation(BaseLayerResponse): 881 | """ 882 | Represents a Layer conversation. Returned by the get_ and create_ 883 | conversation methods. 884 | """ 885 | 886 | def __init__(self, id, url, messages_url=None, created_at=None, 887 | participants=None, distinct=False, metadata=None): 888 | super(Conversation, self).__init__(id, url) 889 | self.messages_url = messages_url 890 | self.created_at = created_at 891 | self.participants = participants if participants else [] 892 | self.distinct = distinct 893 | self.metadata = metadata 894 | 895 | def as_dict(self): 896 | return { 897 | 'id': self.id, 898 | 'url': self.url, 899 | 'messages_url': self.messages_url, 900 | 'created_at': self.created_at, 901 | 'participants': self.participants, 902 | 'distinct': self.distinct, 903 | 'metadata': self.metadata, 904 | } 905 | 906 | @staticmethod 907 | def from_dict(dict_data): 908 | return Conversation( 909 | dict_data.get('id'), 910 | dict_data.get('url'), 911 | dict_data.get('messages_url'), 912 | Conversation.parse_date(dict_data.get('created_at')), 913 | dict_data.get('participants'), 914 | dict_data.get('distinct'), 915 | dict_data.get('metadata'), 916 | ) 917 | 918 | @classmethod 919 | def from_list(cls, list_data): 920 | return [cls.from_dict(data) for data in list_data] 921 | 922 | def __repr__(self): 923 | return ''.format( 924 | uuid=self.uuid() 925 | ) 926 | -------------------------------------------------------------------------------- /LayerClient/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jana-Mobile/layer-python/d1fab1f679552aa3bcf5cd444acde91664e31c98/LayerClient/__init__.py -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Layer Platform API Client 2 | 3 | ## About 4 | 5 | This library provides a simple python wrapper around the Layer [Platform 6 | API](https://developer.layer.com/docs/platform) for managing 7 | conversations, messages and announcements. 8 | 9 | The project is currently in Alpha, so please report any bugs or missing 10 | features. 11 | 12 | ## Installation 13 | 14 | Using `pip`: 15 | 16 | ` 17 | $ pip install LayerClient 18 | ` 19 | 20 | Or, download the source code and run 21 | 22 | ` 23 | $ python setup.py install 24 | ` 25 | 26 | There is a tox configuration to make testing and linting easier - the following 27 | are supported: 28 | 29 | $ tox # Runs py27-test (unit tests under python 2.7) by default 30 | $ tox -e py3-test # Runs tests under python3 31 | $ tox -e py27-coverage # Run test coverage report 32 | $ tox -e lint # Check for flake8 violations 33 | 34 | ## Usage 35 | 36 | The interface is close to that of the HTTP API itself. Here is an example of a 37 | sending a simple message: 38 | 39 | from LayerClient import LayerClient 40 | 41 | LAYER_APP_ID = 'your_app_uuid' 42 | LAYER_APP_TOKEN = 'bearer_token_from_layer_console' 43 | 44 | client = LayerClient.PlatformClient( 45 | LAYER_APP_ID, 46 | LAYER_APP_TOKEN, 47 | ) 48 | 49 | sender = LayerClient.Sender( 50 | id='alice', 51 | name='Alice', 52 | ) 53 | 54 | receiver = LayerClient.Sender( 55 | id='bob', 56 | name='Bob', 57 | ) 58 | 59 | conversation = client.create_conversation( 60 | [ 61 | sender.id, 62 | receiver.id, 63 | ], 64 | distinct=True, 65 | metadata={ 66 | 'background_color': '#3c3c3c', 67 | 'title': 'A test conversaton', 68 | } 69 | ) 70 | 71 | message_parts = [ 72 | LayerClient.MessagePart( 73 | 'Sure is nice to not talk about Crypto for a change!' 74 | ), 75 | ] 76 | 77 | notification = LayerClient.PushNotification( 78 | 'You got a message from Alice!' 79 | ) 80 | 81 | message_resp = client.send_message( 82 | conversation, 83 | sender, 84 | message_parts, 85 | notification=notification, 86 | ) 87 | 88 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | pytest==2.7.3 2 | mock==1.0.1 3 | flake8==2.1.0 4 | coverage==3.7.1 5 | pdbpp==0.8.3 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | python-dateutil 3 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | 4 | setup( 5 | name='LayerClient', 6 | version='0.1.10', 7 | packages=['LayerClient'], 8 | description='Client for the Layer Platform API', 9 | url='https://github.com/Jana-Mobile/layer-python', 10 | maintainer='Jana', 11 | maintainer_email='opensource@jana.com', 12 | license='Apache 2.0', 13 | install_requires=[ 14 | 'python-dateutil', 15 | 'requests', 16 | ], 17 | classifiers=[ 18 | 'Development Status :: 3 - Alpha', 19 | 'Intended Audience :: Developers', 20 | 'Topic :: Software Development :: Libraries :: Python Modules', 21 | 'License :: OSI Approved :: Apache Software License', 22 | 'Programming Language :: Python :: 2.6', 23 | 'Programming Language :: Python :: 2.7', 24 | 'Programming Language :: Python :: 3', 25 | ], 26 | ) 27 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Jana-Mobile/layer-python/d1fab1f679552aa3bcf5cd444acde91664e31c98/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_api_exception.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from LayerClient import LayerClient 3 | from test_utils import MockRequestResponse, TestPlatformClient 4 | 5 | 6 | class TestApiException(TestPlatformClient): 7 | 8 | def test_json_exception(self, layerclient, monkeypatch): 9 | def return_sample_response(method, url, headers, data, params): 10 | return MockRequestResponse( 11 | False, 12 | json={ 13 | 'message': 'Operation not supported', 14 | 'code': 40, 15 | 'id': 23, 16 | }, 17 | status_code=401, 18 | ) 19 | 20 | monkeypatch.setattr('requests.request', return_sample_response) 21 | 22 | with pytest.raises(LayerClient.LayerPlatformException) as e: 23 | layerclient.get_conversation('some_uuid') 24 | 25 | assert str(e.value) == 'Operation not supported' 26 | assert e.value.http_code == 401 27 | assert e.value.code == 40 28 | assert e.value.error_id == 23 29 | 30 | def test_raw_exception(self, layerclient, monkeypatch): 31 | def return_sample_response(method, url, headers, data, params): 32 | return MockRequestResponse( 33 | False, 34 | text='Internal server error', 35 | status_code=500, 36 | ) 37 | 38 | monkeypatch.setattr('requests.request', return_sample_response) 39 | 40 | with pytest.raises(LayerClient.LayerPlatformException) as e: 41 | layerclient.get_conversation('some_uuid') 42 | 43 | assert str(e.value) == 'Internal server error' 44 | assert e.value.http_code == 500 45 | -------------------------------------------------------------------------------- /tests/test_create_conversation.py: -------------------------------------------------------------------------------- 1 | import json 2 | from test_utils import MockRequestResponse, TestPlatformClient 3 | 4 | 5 | class TestCreateConverstaion(TestPlatformClient): 6 | 7 | def test_create_conversation(self, layerclient, monkeypatch): 8 | def verify_request_args(method, url, headers, data, params): 9 | assert method == 'POST' 10 | assert url == ( 11 | 'https://api.layer.com/apps/TEST_APP_UUID/conversations' 12 | ) 13 | assert headers == { 14 | 'Accept': 'application/vnd.layer+json; version=1.0', 15 | 'Authorization': 'Bearer TEST_BEARER_TOKEN', 16 | 'Content-Type': 'application/json', 17 | } 18 | json_data = json.loads(data) 19 | assert json_data == { 20 | 'participants': 'TEST_CONVERSATION_UUID', 21 | 'metadata': None, 22 | 'distinct': True, 23 | } 24 | 25 | return MockRequestResponse( 26 | True, 27 | { 28 | 'id': 'layer:///conversation/TEST_CONVERSATION_UUID', 29 | 'url': 'layer:///conversation/TEST_CONVERSATION_UUID', 30 | }, 31 | ) 32 | 33 | monkeypatch.setattr('requests.request', verify_request_args) 34 | layerclient.create_conversation('TEST_CONVERSATION_UUID') 35 | 36 | def test_create_conversation_with_options(self, layerclient, monkeypatch): 37 | def verify_request_args(method, url, headers, data, params): 38 | assert method == 'POST' 39 | assert url == ( 40 | 'https://api.layer.com/apps/TEST_APP_UUID/conversations' 41 | ) 42 | assert headers == { 43 | 'Accept': 'application/vnd.layer+json; version=1.0', 44 | 'Authorization': 'Bearer TEST_BEARER_TOKEN', 45 | 'Content-Type': 'application/json', 46 | } 47 | json_data = json.loads(data) 48 | assert json_data == { 49 | 'participants': 'TEST_CONVERSATION_UUID', 50 | 'metadata': { 51 | 'Topic': 'A coffee conversation', 52 | 'Background': '#C0FFEE', 53 | }, 54 | 'distinct': False, 55 | } 56 | 57 | return MockRequestResponse( 58 | True, 59 | { 60 | 'id': 'layer:///conversation/TEST_CONVERSATION_UUID', 61 | 'url': 'layer:///conversation/TEST_CONVERSATION_UUID', 62 | }, 63 | ) 64 | 65 | monkeypatch.setattr('requests.request', verify_request_args) 66 | layerclient.create_conversation( 67 | 'TEST_CONVERSATION_UUID', 68 | False, 69 | { 70 | 'Topic': 'A coffee conversation', 71 | 'Background': '#C0FFEE', 72 | }, 73 | ) 74 | -------------------------------------------------------------------------------- /tests/test_delete_conversation.py: -------------------------------------------------------------------------------- 1 | from test_utils import MockRequestResponse, TestPlatformClient 2 | 3 | 4 | class TestDeleteConverstaion(TestPlatformClient): 5 | 6 | def test_delete_conversation(self, layerclient, monkeypatch): 7 | def verify_request_args(method, url, headers, data, params): 8 | assert method == "DELETE" 9 | assert url == ( 10 | "https://api.layer.com/apps/TEST_APP_UUID/" 11 | "conversations/TEST_CONVERSATION_UUID" 12 | ) 13 | assert headers == { 14 | 'Accept': 'application/vnd.layer+json; version=1.0', 15 | 'Authorization': 'Bearer TEST_BEARER_TOKEN', 16 | 'Content-Type': 'application/json', 17 | } 18 | assert data is None 19 | 20 | return MockRequestResponse(True, {}) 21 | 22 | monkeypatch.setattr("requests.request", verify_request_args) 23 | layerclient.delete_conversation('TEST_CONVERSATION_UUID') 24 | -------------------------------------------------------------------------------- /tests/test_get_conversation.py: -------------------------------------------------------------------------------- 1 | from test_utils import MockRequestResponse, TestPlatformClient 2 | 3 | 4 | class TestGetConverstaion(TestPlatformClient): 5 | 6 | def test_get_conversation(self, layerclient, monkeypatch): 7 | def verify_request_args(method, url, headers, data, params): 8 | assert method == "GET" 9 | assert url == ( 10 | "https://api.layer.com/apps/TEST_APP_UUID/" 11 | "conversations/TEST_CONVERSATION_UUID" 12 | ) 13 | assert headers == { 14 | 'Accept': 'application/vnd.layer+json; version=1.0', 15 | 'Authorization': 'Bearer TEST_BEARER_TOKEN', 16 | 'Content-Type': 'application/json', 17 | } 18 | assert data is None 19 | 20 | return MockRequestResponse( 21 | True, 22 | { 23 | 'id': 'layer:///conversation/TEST_CONVERSATION_UUID', 24 | 'url': 'layer:///conversation/TEST_CONVERSATION_UUID', 25 | }, 26 | ) 27 | 28 | monkeypatch.setattr("requests.request", verify_request_args) 29 | layerclient.get_conversation('TEST_CONVERSATION_UUID') 30 | -------------------------------------------------------------------------------- /tests/test_prepare_rich_content.py: -------------------------------------------------------------------------------- 1 | from LayerClient import LayerClient 2 | from test_utils import MockRequestResponse, TestPlatformClient 3 | 4 | 5 | class TestPrepareRichContent(TestPlatformClient): 6 | 7 | def test_prepare_rich_content(self, layerclient, monkeypatch): 8 | sender = LayerClient.Sender('alice', 'Alice') 9 | recipient = LayerClient.Sender('bob', 'Bob') 10 | 11 | conversation = LayerClient.Conversation( 12 | 'layer:///conversations/f3cc7b32-3c92-11e4-baad-164230d1df67', 13 | 'some_conversation_url', 14 | participants=[sender.id, recipient.id], 15 | ) 16 | 17 | def verify_request_args(method, url, headers, data, params): 18 | assert method == 'POST' 19 | assert url == ( 20 | 'https://api.layer.com/apps/TEST_APP_UUID/' 21 | 'conversations/f3cc7b32-3c92-11e4-baad-164230d1df67/content' 22 | ) 23 | assert headers == { 24 | 'Accept': 'application/vnd.layer+json; version=1.0', 25 | 'Authorization': 'Bearer TEST_BEARER_TOKEN', 26 | 'Content-Type': 'application/json', 27 | 'Upload-Content-Type': 'image/jpeg', 28 | 'Upload-Content-Length': 23, 29 | # No support of the upload origin yet 30 | # 'Upload-Origin': 'http://mydomain.com' 31 | } 32 | assert data is None 33 | return MockRequestResponse( 34 | True, 35 | { 36 | "id": "layer:///content/TEST_RICH_CONTENT_UUID", 37 | "size": 23, 38 | "upload_url": "someuploadurl", 39 | "download_url": None, 40 | "refresh_url": None, 41 | "expiration": None 42 | }, 43 | ) 44 | 45 | monkeypatch.setattr('requests.request', verify_request_args) 46 | layerclient.prepare_rich_content( 47 | conversation, 'image/jpeg', 23 48 | ) 49 | 50 | def test_parse_response(self, layerclient, monkeypatch): 51 | def return_sample_response(method, url, headers, data, params): 52 | return MockRequestResponse( 53 | True, 54 | { 55 | "id": "layer:///content/TEST_RICH_CONTENT_UUID", 56 | "size": 23, 57 | "upload_url": "someuploadurl", 58 | "download_url": None, 59 | "refresh_url": None, 60 | "expiration": None 61 | }, 62 | ) 63 | 64 | monkeypatch.setattr('requests.request', return_sample_response) 65 | sender = LayerClient.Sender('alice', 'Alice') 66 | recipient = LayerClient.Sender('bob', 'Bob') 67 | conversation = LayerClient.Conversation( 68 | 'layer:///conversations/f3cc7b32-3c92-11e4-baad-164230d1df67', 69 | 'some_conversation_url', 70 | participants=[sender.id, recipient.id], 71 | ) 72 | rich_content = layerclient.prepare_rich_content( 73 | conversation, 'image/jpeg', 23 74 | ) 75 | assert rich_content.id == 'layer:///content/TEST_RICH_CONTENT_UUID' 76 | assert rich_content.size == 23 77 | assert rich_content.upload_url == "someuploadurl" 78 | -------------------------------------------------------------------------------- /tests/test_send_announcement.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from dateutil.tz import tzutc 3 | import json 4 | from LayerClient import LayerClient 5 | from test_utils import MockRequestResponse, TestPlatformClient 6 | 7 | 8 | class TestSendAnnouncement(TestPlatformClient): 9 | 10 | def test_send_announcement(self, layerclient, monkeypatch): 11 | sender = LayerClient.Sender('alice', 'Alice') 12 | recipients = ['bob', 'charlie'] 13 | 14 | message_parts = [ 15 | LayerClient.MessagePart( 16 | 'Top secret message', 17 | 'text/confidential', 18 | ), 19 | ] 20 | 21 | def verify_request_args(method, url, headers, data, params): 22 | assert method == 'POST' 23 | assert url == ( 24 | 'https://api.layer.com/apps/TEST_APP_UUID/announcements' 25 | ) 26 | assert headers == { 27 | 'Accept': 'application/vnd.layer+json; version=1.0', 28 | 'Authorization': 'Bearer TEST_BEARER_TOKEN', 29 | 'Content-Type': 'application/json', 30 | } 31 | json_data = json.loads(data) 32 | assert json_data == { 33 | 'recipients': recipients, 34 | 'parts': [{ 35 | 'body': 'Top secret message', 36 | 'mime_type': 'text/confidential', 37 | }], 38 | 'sender': { 39 | 'name': 'Alice', 40 | } 41 | } 42 | 43 | return MockRequestResponse( 44 | True, 45 | { 46 | 'id': 'layer:///messages/TEST_MESSAGE_UUID', 47 | 'url': 'layer:///messages/TEST_MESSAGE_UUID', 48 | }, 49 | ) 50 | 51 | monkeypatch.setattr('requests.request', verify_request_args) 52 | layerclient.send_announcement( 53 | sender, 54 | recipients, 55 | message_parts, 56 | ) 57 | 58 | def test_parse_response(self, layerclient, monkeypatch): 59 | def return_sample_response(method, url, headers, data, params): 60 | return MockRequestResponse( 61 | True, 62 | { 63 | 'id': ( 64 | 'layer:///announcements/' 65 | 'f3cc7b32-3c92-11e4-baad-164230d1df67' 66 | ), 67 | 'url': ( 68 | 'https://api.layer.com/apps/' 69 | '24f43c32-4d95-11e4-b3a2-0fd00000020d/announcements' 70 | '/f3cc7b32-3c92-11e4-baad-164230d1df67' 71 | ), 72 | 'sent_at': '2014-09-15T04:44:47+00:00', 73 | 'recipients': ['bob', 'charlie'], 74 | 'sender': { 75 | 'name': 'Alice', 76 | 'user_id': None 77 | }, 78 | 'parts': [ 79 | { 80 | 'body': 'Hello, World!', 81 | 'mime_type': 'text/plain' 82 | } 83 | ] 84 | }, 85 | ) 86 | 87 | monkeypatch.setattr('requests.request', return_sample_response) 88 | sender = LayerClient.Sender('alice', 'Alice') 89 | recipients = ['bob', 'charlie'] 90 | message_parts = [ 91 | LayerClient.MessagePart( 92 | 'Top secret message', 93 | ), 94 | ] 95 | announcement = layerclient.send_announcement( 96 | sender, 97 | recipients, 98 | message_parts, 99 | ) 100 | assert announcement.uuid() == 'f3cc7b32-3c92-11e4-baad-164230d1df67' 101 | assert announcement.sent_at == datetime.datetime( 102 | 2014, 9, 15, 4, 44, 47, tzinfo=tzutc() 103 | ) 104 | assert announcement.recipients == ['bob', 'charlie'] 105 | assert announcement.sender.as_dict() == { 106 | 'name': 'Alice', 107 | } 108 | assert announcement.parts[0].body == 'Hello, World!' 109 | assert announcement.parts[0].mime_type == 'text/plain' 110 | -------------------------------------------------------------------------------- /tests/test_send_message.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | from dateutil.tz import tzutc 3 | import json 4 | from LayerClient import LayerClient 5 | from test_utils import MockRequestResponse, TestPlatformClient 6 | 7 | 8 | class TestSendMessage(TestPlatformClient): 9 | 10 | def test_send_message(self, layerclient, monkeypatch): 11 | sender = LayerClient.Sender('alice', 'Alice') 12 | recipient = LayerClient.Sender('bob', 'Bob') 13 | 14 | conversation = LayerClient.Conversation( 15 | 'layer:///conversations/f3cc7b32-3c92-11e4-baad-164230d1df67', 16 | 'some_conversation_url', 17 | participants=[sender.id, recipient.id], 18 | ) 19 | 20 | message_parts = [ 21 | LayerClient.MessagePart( 22 | 'Top secret message', 23 | 'text/confidential', 24 | ), 25 | ] 26 | 27 | notification = LayerClient.PushNotification( 28 | 'You have a new message!', 29 | sound='foo.wav', 30 | recipients={ 31 | 'bob': LayerClient.PushNotification('Message for Bob!'), 32 | }, 33 | ) 34 | 35 | def verify_request_args(method, url, headers, data, params): 36 | assert method == 'POST' 37 | assert url == ( 38 | 'https://api.layer.com/apps/TEST_APP_UUID/conversations' 39 | '/f3cc7b32-3c92-11e4-baad-164230d1df67/messages' 40 | ) 41 | assert headers == { 42 | 'Accept': 'application/vnd.layer+json; version=1.0', 43 | 'Authorization': 'Bearer TEST_BEARER_TOKEN', 44 | 'Content-Type': 'application/json', 45 | } 46 | json_data = json.loads(data) 47 | assert json_data == { 48 | 'parts': [ 49 | { 50 | 'body': 'Top secret message', 51 | 'mime_type': 'text/confidential', 52 | }, 53 | ], 54 | 'sender': { 55 | 'user_id': 'alice', 56 | }, 57 | 'notification': { 58 | 'text': 'You have a new message!', 59 | 'sound': 'foo.wav', 60 | 'recipients': { 61 | 'bob': { 62 | 'sound': None, 63 | 'text': 'Message for Bob!', 64 | }, 65 | }, 66 | }, 67 | } 68 | 69 | return MockRequestResponse( 70 | True, 71 | { 72 | 'id': 'layer:///messages/TEST_MESSAGE_UUID', 73 | 'url': 'layer:///messages/TEST_MESSAGE_UUID', 74 | 'conversation': conversation.as_dict(), 75 | }, 76 | ) 77 | 78 | monkeypatch.setattr('requests.request', verify_request_args) 79 | layerclient.send_message( 80 | conversation, 81 | sender, 82 | message_parts, 83 | notification=notification, 84 | ) 85 | 86 | def test_parse_response(self, layerclient, monkeypatch): 87 | def return_sample_response(method, url, headers, data, params): 88 | return MockRequestResponse( 89 | True, 90 | { 91 | 'id': ( 92 | 'layer:///messages/' 93 | '940de862-3c96-11e4-baad-164230d1df67' 94 | ), 95 | 'url': ( 96 | 'https://api.layer.com/apps/' 97 | '24f43c32-4d95-11e4-b3a2-0fd00000020d/messages/' 98 | '940de862-3c96-11e4-baad-164230d1df67' 99 | ), 100 | 'conversation': { 101 | 'id': ( 102 | 'layer:///conversations/' 103 | 'f3cc7b32-3c92-11e4-baad-164230d1df67' 104 | ), 105 | 'url': ( 106 | 'https://api.layer.com/apps/' 107 | '24f43c32-4d95-11e4-b3a2-0fd00000020d' 108 | '/conversations/' 109 | 'f3cc7b32-3c92-11e4-baad-164230d1df67' 110 | ), 111 | }, 112 | 'parts': [ 113 | { 114 | 'body': 'Hello, World!', 115 | 'mime_type': 'text/plain' 116 | }, 117 | { 118 | 'body': 'YW55IGNhcm5hbCBwbGVhc3VyZQ==', 119 | 'mime_type': 'image/jpeg', 120 | 'encoding': 'base64' 121 | } 122 | ], 123 | 'sent_at': '2014-09-09T04:44:47+00:00', 124 | 'sender': { 125 | 'name': 't-bone', 126 | 'user_id': None 127 | }, 128 | 'recipient_status': { 129 | '777': 'sent', 130 | '999': 'sent', 131 | '111': 'sent' 132 | } 133 | }, 134 | ) 135 | 136 | monkeypatch.setattr('requests.request', return_sample_response) 137 | sender = LayerClient.Sender('alice', 'Alice') 138 | messagepart = LayerClient.MessagePart('Hi!') 139 | conversation = LayerClient.Conversation( 140 | 'layer:///conversations/f3cc7b32-3c92-11e4-baad-164230d1df67', 141 | 'some_conversation_url', 142 | ) 143 | response = layerclient.send_message( 144 | conversation, 145 | sender, 146 | [messagepart] 147 | ) 148 | assert response.uuid() == '940de862-3c96-11e4-baad-164230d1df67' 149 | assert response.sent_at == datetime.datetime( 150 | 2014, 9, 9, 4, 44, 47, tzinfo=tzutc() 151 | ) 152 | assert response.sender.id is None 153 | assert response.sender.name == 't-bone' 154 | 155 | assert response.conversation.uuid() == ( 156 | 'f3cc7b32-3c92-11e4-baad-164230d1df67' 157 | ) 158 | 159 | assert response.parts[0].body == 'Hello, World!' 160 | assert response.parts[1].mime_type == 'image/jpeg' 161 | assert response.parts[1].encoding == 'base64' 162 | 163 | assert response.recipient_status == { 164 | '777': 'sent', 165 | '999': 'sent', 166 | '111': 'sent' 167 | } 168 | 169 | def test_send_message_with_rich_content(self, layerclient, monkeypatch): 170 | sender = LayerClient.Sender('alice', 'Alice') 171 | recipient = LayerClient.Sender('bob', 'Bob') 172 | 173 | conversation = LayerClient.Conversation( 174 | 'layer:///conversations/f3cc7b32-3c92-11e4-baad-164230d1df67', 175 | 'some_conversation_url', 176 | participants=[sender.id, recipient.id], 177 | ) 178 | 179 | message_parts = [ 180 | LayerClient.MessagePart( 181 | None, 182 | mime='image/jpeg', 183 | content={ 184 | 'id': 'layer:///content/TEST_CONTENT_UUID', 185 | 'size': 23, 186 | } 187 | ), 188 | ] 189 | 190 | def verify_request_args(method, url, headers, data, params): 191 | assert method == 'POST' 192 | assert url == ( 193 | 'https://api.layer.com/apps/TEST_APP_UUID/conversations' 194 | '/f3cc7b32-3c92-11e4-baad-164230d1df67/messages' 195 | ) 196 | assert headers == { 197 | 'Accept': 'application/vnd.layer+json; version=1.0', 198 | 'Authorization': 'Bearer TEST_BEARER_TOKEN', 199 | 'Content-Type': 'application/json', 200 | } 201 | json_data = json.loads(data) 202 | assert json_data == { 203 | 'parts': [ 204 | { 205 | 'mime_type': 'image/jpeg', 206 | 'content': { 207 | 'id': 'layer:///content/TEST_CONTENT_UUID', 208 | 'size': 23, 209 | } 210 | }, 211 | ], 212 | 'sender': { 213 | 'user_id': 'alice', 214 | } 215 | } 216 | 217 | return MockRequestResponse( 218 | True, 219 | { 220 | 'id': 'layer:///messages/TEST_MESSAGE_UUID', 221 | 'url': 'layer:///messages/TEST_MESSAGE_UUID', 222 | 'conversation': conversation.as_dict(), 223 | }, 224 | ) 225 | 226 | monkeypatch.setattr('requests.request', verify_request_args) 227 | layerclient.send_message( 228 | conversation, 229 | sender, 230 | message_parts 231 | ) 232 | 233 | def test_parse_response_with_rich_content(self, layerclient, monkeypatch): 234 | def return_sample_response(method, url, headers, data, params): 235 | return MockRequestResponse( 236 | True, 237 | { 238 | 'id': ( 239 | 'layer:///messages/' 240 | '940de862-3c96-11e4-baad-164230d1df67' 241 | ), 242 | 'url': ( 243 | 'https://api.layer.com/apps/' 244 | '24f43c32-4d95-11e4-b3a2-0fd00000020d/messages/' 245 | '940de862-3c96-11e4-baad-164230d1df67' 246 | ), 247 | 'conversation': { 248 | 'id': ( 249 | 'layer:///conversations/' 250 | 'f3cc7b32-3c92-11e4-baad-164230d1df67' 251 | ), 252 | 'url': ( 253 | 'https://api.layer.com/apps/' 254 | '24f43c32-4d95-11e4-b3a2-0fd00000020d' 255 | '/conversations/' 256 | 'f3cc7b32-3c92-11e4-baad-164230d1df67' 257 | ), 258 | }, 259 | 'parts': [ 260 | { 261 | 'mime_type': 'image/jpeg', 262 | 'content': { 263 | 'id': 'layer:///content/TEST_CONTENT_UUID', 264 | 'size': 23, 265 | 'download_url': 'some download url', 266 | 'refresh_url': 'some refresh url', 267 | 'expiration': '2014-09-10T04:44:47+00:00' 268 | } 269 | } 270 | ], 271 | 'sent_at': '2014-09-09T04:44:47+00:00', 272 | 'sender': { 273 | 'name': 't-bone', 274 | 'user_id': None 275 | }, 276 | 'recipient_status': { 277 | '777': 'sent', 278 | '999': 'sent', 279 | '111': 'sent' 280 | } 281 | }, 282 | ) 283 | 284 | monkeypatch.setattr('requests.request', return_sample_response) 285 | sender = LayerClient.Sender('alice', 'Alice') 286 | messagepart = LayerClient.MessagePart( 287 | None, 288 | mime='image/jpeg', 289 | content={ 290 | 'id': 'layer:///content/TEST_CONTENT_UUID', 291 | 'size': 23, 292 | } 293 | ) 294 | conversation = LayerClient.Conversation( 295 | 'layer:///conversations/f3cc7b32-3c92-11e4-baad-164230d1df67', 296 | 'some_conversation_url', 297 | ) 298 | response = layerclient.send_message( 299 | conversation, 300 | sender, 301 | [messagepart] 302 | ) 303 | assert response.uuid() == '940de862-3c96-11e4-baad-164230d1df67' 304 | assert response.sent_at == datetime.datetime( 305 | 2014, 9, 9, 4, 44, 47, tzinfo=tzutc() 306 | ) 307 | assert response.sender.id is None 308 | assert response.sender.name == 't-bone' 309 | 310 | assert response.conversation.uuid() == ( 311 | 'f3cc7b32-3c92-11e4-baad-164230d1df67' 312 | ) 313 | 314 | assert response.parts[0].body is None 315 | assert response.parts[0].mime_type == 'image/jpeg' 316 | assert response.parts[0].encoding is None 317 | assert isinstance(response.parts[0].content, dict) 318 | assert ( 319 | response.parts[0].content.get('id') == 320 | 'layer:///content/TEST_CONTENT_UUID' 321 | ) 322 | assert response.parts[0].content.get('size') == 23 323 | 324 | assert response.recipient_status == { 325 | '777': 'sent', 326 | '999': 'sent', 327 | '111': 'sent' 328 | } 329 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from LayerClient import LayerClient 3 | 4 | 5 | class MockRequestResponse(object): 6 | 7 | def __init__(self, ok, json=None, text=None, status_code=200): 8 | self.ok = ok 9 | self._json = json 10 | self.text = text 11 | self.status_code = status_code 12 | 13 | def json(self): 14 | if self._json is None: 15 | raise ValueError 16 | return self._json 17 | 18 | 19 | class TestPlatformClient(object): 20 | 21 | @pytest.yield_fixture 22 | def layerclient(self): 23 | client = LayerClient.PlatformClient( 24 | 'TEST_APP_UUID', 25 | 'TEST_BEARER_TOKEN', 26 | ) 27 | yield client 28 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | deps = -rrequirements-dev.txt 3 | envlist = py27-test 4 | 5 | [testenv:py27-test] 6 | deps = {[tox]deps} 7 | commands = 8 | py.test {posargs} 9 | 10 | [testenv:py27-coverage] 11 | deps = {[tox]deps} 12 | -rrequirements.txt 13 | commands = 14 | coverage run --source=LayerClient/,tests/ -m pytest --strict {posargs} 15 | coverage report -m 16 | 17 | [testenv:lint] 18 | deps = {[tox]deps} 19 | commands = 20 | flake8 LayerClient/ 21 | flake8 tests/ 22 | 23 | [testenv:py3-test] 24 | deps = {[tox]deps} 25 | setenv = 26 | PYTHONPATH=tests/ 27 | commands = 28 | py.test {posargs} 29 | 30 | --------------------------------------------------------------------------------