diff --git a/.github/workflows/run_linter.yaml b/.github/workflows/run_linter.yaml new file mode 100644 index 0000000..265fdfd --- /dev/null +++ b/.github/workflows/run_linter.yaml @@ -0,0 +1,26 @@ +name: Test Python SDK + +on: + push: + branches: + - "main" + pull_request: + branches: [ main ] + + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: 3.11 + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 + - name: Lint with flake8 + run: | + flake8 */ --count --max-complexity=10 --max-line-length=120 --statistics \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1989419 --- /dev/null +++ b/.gitignore @@ -0,0 +1,131 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +.idea/ + +# Poetry +poetry.lock \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/README.md b/README.md index 6e88cd1..59ef1eb 100644 --- a/README.md +++ b/README.md @@ -2,3 +2,12 @@ This repository provides templates to help you get started with the [Sinch Python SDK](https://github.com/sinch/sinch-sdk-python). + +## Contents + + - [templates](./templates): Executable code samples with predefined placeholders. Insert your own snippets +into the designated sections to test your code using the Sinch APIs. + - client: Examples that show how to make API calls using the Sinch Client + - [Numbers API](./templates/client/src/numbers_api) + - server: Examples for handling events triggered by Sinch services. + - [Numbers API](./templates/server/src/numbers_api) \ No newline at end of file diff --git a/templates/__init__.py b/templates/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/client/.env b/templates/client/.env new file mode 100644 index 0000000..8f7d29f --- /dev/null +++ b/templates/client/.env @@ -0,0 +1,4 @@ +# Unified Credentials +SINCH_PROJECT_ID = PROJECT_ID +SINCH_KEY_ID = KEY_ID +SINCH_KEY_SECRET = KEY_SECRET diff --git a/templates/client/README.md b/templates/client/README.md new file mode 100644 index 0000000..18278ad --- /dev/null +++ b/templates/client/README.md @@ -0,0 +1,52 @@ +# Client Application Using the Sinch Python SDK + +This directory provides a Python client application built with the +[Sinch Python SDK](https://github.com/sinch/sinch-sdk-python). +It allows you to integrate Sinch APIs into your Python applications easily. + +## Prerequisites + +Before you begin, ensure you have: + - [Python](https://www.python.org/) installed (versions 3.9 to 3.12 recommended). + - [Poetry](https://python-poetry.org/) installed. + - A [Sinch account](https://dashboard.sinch.com/) with access to the APIs you want to use. + +## Configuration + +To configure the client application: + +1. **Environment Variables**: + Edit the [.env](.env) file, adding your credentials from the Sinch dashboard under the Access Keys section. + - To use [Numbers](https://developers.sinch.com/docs/numbers/), you need to fill the following variables with the values from your Sinch account: + ``` + - SINCH_PROJECT_ID=Your Sinch Project ID + - SINCH_KEY_ID=Your Sinch Access Key ID + - SINCH_KEY_SECRET=Your Sinch Key Secret associated to your Sinch Access Key + ``` +2. **API Integration**: + The application demonstrates usage via modular snippets in `client/src/numbers_api/snippet.py`, which acts as the + main integration point for testing Sinch Numbers API endpoints. You can replace the existing logic with your own, based on + the desired API functionality. + + You can explore and adapt examples from [Python SDK snippets repository.](https://github.com/sinch/sinch-sdk-python-snippets) directly into the `execute(sinch_client)` function: + - Choose a snippet + - Copy only the functional logic (skip the `SinchClient` initialization - + it's already handled in the `app.py` file). + - Paste it into the `execute(sinch_client)` function in `snippet.py`. + + +## Usage + +1. Navigate to the project's root directory in your terminal. + ``` + cd /path/to/sinch-sdk-python-quickstart + ``` +2. Install the project dependencies: + ``` + cd templates/client + poetry install + ``` +3. Make sure your `.env` file has been updated as described above. +4. Run the application: + - `poetry run python src/app.py` + Or run it directly from your IDE if preferred. diff --git a/templates/client/__init__.py b/templates/client/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/client/pyproject.toml b/templates/client/pyproject.toml new file mode 100644 index 0000000..94a5113 --- /dev/null +++ b/templates/client/pyproject.toml @@ -0,0 +1,15 @@ +[tool.poetry] +name = "sinch-sdk-python-quickstart-client" +version = "0.1.0" +description = "Sinch SDK Python Quickstart Client" +readme = "README.md" +packages = [{include = "src"}] + +[tool.poetry.dependencies] +python = "^3.9" +python-dotenv = "^1.0.0" +# sinch = "^2.0.0" # Uncomment once v2.0 is released + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" diff --git a/templates/client/src/__init__.py b/templates/client/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/client/src/app.py b/templates/client/src/app.py new file mode 100644 index 0000000..17f06f8 --- /dev/null +++ b/templates/client/src/app.py @@ -0,0 +1,22 @@ +import logging +from numbers_api.numbers_quickstart import NumbersQuickstart +from sinch_client_helper import get_sinch_client, load_config + + +def main(): + config = load_config() + sinch_client = get_sinch_client(config) + + # Set up logging at the INFO level + logging.basicConfig() + sinch_client.configuration.logger.setLevel(logging.INFO) + logger = sinch_client.configuration.logger + + try: + NumbersQuickstart(sinch_client) + except Exception as e: + logger.error(f'Error: {e}') + + +if __name__ == '__main__': + main() diff --git a/templates/client/src/numbers_api/__init__.py b/templates/client/src/numbers_api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/client/src/numbers_api/numbers_quickstart.py b/templates/client/src/numbers_api/numbers_quickstart.py new file mode 100644 index 0000000..bcd0bb7 --- /dev/null +++ b/templates/client/src/numbers_api/numbers_quickstart.py @@ -0,0 +1,7 @@ +from .snippet import execute + + +class NumbersQuickstart: + def __init__(self, sinch_client): + self.sinch_client = sinch_client + execute(self.sinch_client) diff --git a/templates/client/src/numbers_api/snippet.py b/templates/client/src/numbers_api/snippet.py new file mode 100644 index 0000000..b944402 --- /dev/null +++ b/templates/client/src/numbers_api/snippet.py @@ -0,0 +1,36 @@ +# Replace the code below with any snippet from: +# https://github.com/sinch/sinch-sdk-python-snippets +def execute(sinch_client): + logger = sinch_client.configuration.logger + logger.info("Snippet execution: Numbers service") + + +# Example usage: +# Let's say you're using the snippet from snippets/available_regions/list/snippet.py: +# +# from sinch import SinchClient +# +# sinch_client = SinchClient( +# project_id="YOUR_PROJECT_ID", +# key_id="KEY_ID", +# key_secret="KEY_SECRET" +# ) +# +# available_regions = sinch_client.numbers.regions.list( +# number_types=["MOBILE"] +# ) +# +# print("Available regions:\n") +# for region in available_regions.iterator(): +# print(region) + +# You extract the logic and place it inside the `execute` function like so: +# +# def execute(sinch_client): +# available_regions = sinch_client.numbers.regions.list( +# number_types=["MOBILE"] +# ) +# +# print("Available regions:\n") +# for region in available_regions.iterator(): +# print(region) diff --git a/templates/client/src/sinch_client_helper.py b/templates/client/src/sinch_client_helper.py new file mode 100644 index 0000000..8e5a3e6 --- /dev/null +++ b/templates/client/src/sinch_client_helper.py @@ -0,0 +1,42 @@ +from pathlib import Path +from dotenv import dotenv_values +from sinch import SinchClient + + +def load_config() -> dict[str, str]: + """ + Load configuration from the .env file in the client directory. + + Returns: + dict[str, str]: Dictionary containing configuration values + """ + current_dir = Path(__file__).resolve().parent + client_dir = current_dir.parent + env_file = client_dir / '.env' + + if not env_file.exists(): + raise FileNotFoundError(f"Could not find .env file in client directory: {env_file}") + + config_dict = dotenv_values(env_file) + + return config_dict + + +def get_sinch_client(config: dict) -> SinchClient: + """ + Create and return a configured SinchClient instance. + + Args: + config (dict): Dictionary containing configuration values + Returns: + SinchClient: Configured Sinch client instance + """ + project_id = config.get('SINCH_PROJECT_ID') + key_id = config.get('SINCH_KEY_ID') + key_secret = config.get('SINCH_KEY_SECRET') + + return SinchClient( + project_id=project_id, + key_id=key_id, + key_secret=key_secret, + ) diff --git a/templates/server/.env b/templates/server/.env new file mode 100644 index 0000000..a83d00f --- /dev/null +++ b/templates/server/.env @@ -0,0 +1,12 @@ +# Unified Credentials +SINCH_PROJECT_ID = PROJECT_ID +SINCH_KEY_ID = KEY_ID +SINCH_KEY_SECRET = KEY_SECRET + +# Server Configuration +SERVER_PORT = + +# Webhook Configuration +# The secret value used for webhook calls validation +# See https://developers.sinch.com/docs/numbers/api-reference/numbers/tag/Numbers-Callbacks/ +NUMBERS_WEBHOOKS_SECRET = WEBHOOKS_SECRET diff --git a/templates/server/README.md b/templates/server/README.md new file mode 100644 index 0000000..bb2ba87 --- /dev/null +++ b/templates/server/README.md @@ -0,0 +1,83 @@ +# Backend application built using Sinch Python SDK for Webhook Handling + +This directory contains a server application built with [Sinch Python SDK](https://github.com/sinch/sinch-sdk-python) +to process incoming webhooks. + +## Requirements + +- [Python 3.9+](https://www.python.org/) +- [Flask](https://flask.palletsprojects.com/en/stable/) +- [Sinch account](https://dashboard.sinch.com/) +- [ngrok](https://ngrok.com/docs) +- [Poetry](https://python-poetry.org/) + +## Configuration + +1. **Environment Variables**: + Edit the [.env](.env) file, adding your credentials from the Sinch dashboard under the Access Keys section. + - To use [Numbers](https://developers.sinch.com/docs/numbers/), you need to fill the following variables + with the values from your Sinch account: + ``` + - SINCH_PROJECT_ID=Your Sinch Project ID + - SINCH_KEY_ID=Your Sinch Access Key ID + - SINCH_KEY_SECRET=Your Sinch Key Secret associated to your Sinch Access Key + ``` + - Server Port: + Define the port your server will listen to on (default: 3001): + ``` + - SERVER_PORT=3001 + ``` + - Controller Settings + - Numbers controller: Set the webhook secret, which you can retrieve from the [Numbers API](https://developers.sinch.com/docs/numbers/api-reference/numbers/tag/Numbers-Callbacks/), + using the `/callbackConfiguration` endpoint: + ``` + - NUMBERS_WEBHOOK_SECRET=Your Sinch Webhook Secret + ``` + +## Usage + +### Running the server + +1. Navigate to the project's root directory in your terminal. +``` + cd /path/to/sinch-sdk-python-quickstart +``` +2. Install the project dependencies: +``` bash + cd templates/server + poetry install +``` +3. Update the `.env` file with your configuration (see above). +4. Start the server: + - `poetry run python src/server.py` +Or run it directly from your IDE if preferred. + +### Endpoints + +The server exposes the following endpoints: + +| Service | Endpoint | +|--------------|--------------------| +| Numbers | /NumbersEvent | + +## Using ngrok to expose your local server + +To test your webhook locally, you can tunnel requests to your local server using ngrok. + +*Note: The default port is `3001`, but this can be changed (see [Server port](#Configuration))* + +```bash + ngrok http 3001 +``` + +You'll see output similar to this: +``` +ngrok (Ctrl+C to quit) +... +Forwarding https://adbd-79-148-170-158.ngrok-free.app -> http://localhost:3001 +``` +Use the `https` forwarding URL in your callback configuration. For example: + - Numbers: https://adbd-79-148-170-158.ngrok-free.app/NumbersEvent + +Use this value to configure the callback URLs: + - **Numbers**: Set the `callbackUrl` parameter when renting or updating a number via the API diff --git a/templates/server/__init__.py b/templates/server/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/server/pyproject.toml b/templates/server/pyproject.toml new file mode 100644 index 0000000..661eec8 --- /dev/null +++ b/templates/server/pyproject.toml @@ -0,0 +1,16 @@ +[tool.poetry] +name = "sinch-sdk-python-quickstart-server" +version = "0.1.0" +description = "Sinch SDK Python Quickstart Server" +readme = "README.md" +packages = [{include = "src"}] + +[tool.poetry.dependencies] +python = "^3.9" +python-dotenv = "^1.0.0" +flask = "^3.0.0" +# sinch = "^2.0.0" # Uncomment once v2.0 is released + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api" \ No newline at end of file diff --git a/templates/server/src/__init__.py b/templates/server/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/templates/server/src/numbers_api/controller.py b/templates/server/src/numbers_api/controller.py new file mode 100644 index 0000000..46c1d63 --- /dev/null +++ b/templates/server/src/numbers_api/controller.py @@ -0,0 +1,30 @@ +from flask import request, Response +from templates.server.src.numbers_api.server_business_logic import handle_numbers_event + + +class NumbersController: + def __init__(self, sinch_client, webhooks_secret): + self.sinch_client = sinch_client + self.webhooks_secret = webhooks_secret + self.logger = self.sinch_client.configuration.logger + + def numbers_event(self): + headers = dict(request.headers) + body_str = request.raw_body.decode('utf-8') if request.raw_body else '' + + webhooks_service = self.sinch_client.numbers.webhooks(self.webhooks_secret) + + valid_auth = webhooks_service.validate_authentication_header( + headers=headers, + json_payload=body_str + ) + + if not valid_auth: + self.logger.error('Invalid authentication header') + return Response(status=401) + + event = webhooks_service.parse_event(body_str) + + handle_numbers_event(numbers_event=event, logger=self.logger) + + return Response(status=200) diff --git a/templates/server/src/numbers_api/server_business_logic.py b/templates/server/src/numbers_api/server_business_logic.py new file mode 100644 index 0000000..8008281 --- /dev/null +++ b/templates/server/src/numbers_api/server_business_logic.py @@ -0,0 +1,11 @@ +from sinch.domains.numbers.webhooks.v1.events.numbers_webhooks_event import NumbersWebhooksEvent + + +def handle_numbers_event(numbers_event: NumbersWebhooksEvent, logger): + """ + This method handles a Numbers event. + Args: + numbers_event (NumbersWebhooksEvent): The Numbers event data. + logger (logging.Logger, optional): Logger instance for logging. Defaults to None. + """ + logger.info(f'Handling Numbers event:\n{numbers_event.model_dump_json(indent=2)}') diff --git a/templates/server/src/server.py b/templates/server/src/server.py new file mode 100644 index 0000000..6cb56c9 --- /dev/null +++ b/templates/server/src/server.py @@ -0,0 +1,30 @@ +import logging + +from flask import Flask, request +from templates.server.src.numbers_api.controller import NumbersController +from templates.server.src.sinch_client_helper import get_sinch_client, load_config + +app = Flask(__name__) + +config = load_config() +port = int(config.get('SERVER_PORT') or 3001) +webhooks_secret = config.get('NUMBERS_WEBHOOKS_SECRET') +sinch_client = get_sinch_client(config) + +# Set up logging at the INFO level +logging.basicConfig() +sinch_client.configuration.logger.setLevel(logging.INFO) + +numbers_controller = NumbersController(sinch_client, webhooks_secret) + + +# Middleware to capture raw body +@app.before_request +def before_request(): + request.raw_body = request.get_data() + + +app.add_url_rule('/NumbersEvent', methods=['POST'], view_func=numbers_controller.numbers_event) + +if __name__ == '__main__': + app.run(port=port) diff --git a/templates/server/src/sinch_client_helper.py b/templates/server/src/sinch_client_helper.py new file mode 100644 index 0000000..2a99ac4 --- /dev/null +++ b/templates/server/src/sinch_client_helper.py @@ -0,0 +1,44 @@ +from pathlib import Path +from sinch import SinchClient +from dotenv import dotenv_values + + +def load_config() -> dict[str, str]: + """ + Load configuration from the .env file in the server directory. + + Returns: + dict[str, str]: Dictionary containing configuration values + """ + # Get the directory where this file is located + current_dir = Path(__file__).resolve().parent + # Go up one level to the server directory + server_dir = current_dir.parent + env_file = server_dir / '.env' + + if not env_file.exists(): + raise FileNotFoundError(f"Could not find .env file in server directory: {env_file}") + + config_dict = dotenv_values(env_file) + + return config_dict + + +def get_sinch_client(config: dict) -> SinchClient: + """ + Create and return a configured SinchClient instance. + + Args: + config (dict): Dictionary containing configuration values + Returns: + SinchClient: Configured Sinch client instance + """ + project_id = config.get('SINCH_PROJECT_ID') + key_id = config.get('SINCH_KEY_ID') + key_secret = config.get('SINCH_KEY_SECRET') + + return SinchClient( + project_id=project_id, + key_id=key_id, + key_secret=key_secret, + )