Skip to content

Commit 1e131b8

Browse files
authored
Azure Communication Services Network Traversal - GetRelayConfiguration SDK (Azure#19583)
* Add private preview azure-communication-network-traversal python SDK * Add recordings * Fix config/build and format for PR * Update, pylint checks * Update PR * Update PR * Disable pylint warnings * Supress unused-import pylint warning, when I'm actually using it. * Update documentation * Make shared folder consistent with other packages under communication * Rename namespace name from network-traversal to networktraversal
1 parent c5aae37 commit 1e131b8

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+2680
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Release History
2+
3+
## 1.0.0b1 (2021-07-19)
4+
- Preview release of `azure-communication-networktraversal`.
5+
6+
The first preview of the Azure Communication Relay Client has the following features:
7+
8+
- get a Relay Configuration by creating a CommunicationRelayClient
9+
10+
### Added
11+
- Added CommunicationRelayClient in preview.
12+
- Added CommunicationRelayClient.get_relay_configuration in preview.
13+
14+
<!-- LINKS -->
15+
[read_me]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/communication/
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2017 Microsoft
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
include *.md
2+
include azure/__init__.py
3+
include azure/communication/__init__.py
4+
include LICENSE.txt
5+
recursive-include tests *.py
6+
recursive-include samples *.py *.md
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# Azure Communication Network Traversal Package client library for Python
2+
3+
Azure Communication Network Traversal is managing TURN credentials for Azure Communication Services.
4+
5+
It will provide TURN credentials to a user.
6+
7+
[Source code](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/communication) | [API reference documentation](https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/communication)
8+
9+
# Getting started
10+
11+
### Prerequisites
12+
13+
- Python 2.7, or 3.6 or later is required to use this package.
14+
- You must have an [Azure subscription](https://azure.microsoft.com/free/)
15+
- A deployed Communication Services resource. You can use the [Azure Portal](https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource?tabs=windows&pivots=platform-azp) or the [Azure PowerShell](https://docs.microsoft.com/powershell/module/az.communication/new-azcommunicationservice) to set it up.
16+
17+
### Install the package
18+
19+
Install the Azure Communication Identity client library for Python with [pip](https://pypi.org/project/pip/):
20+
Install the Azure Communication Relay Client library for Python with [pip](https://pypi.org/project/pip/):
21+
22+
```bash
23+
pip install azure-communication-identity
24+
pip install azure-communication-networktraversal
25+
```
26+
27+
# Key concepts
28+
29+
## Examples
30+
31+
### Initializing Relay Client
32+
33+
The following section provides code snippets covering some of the most common Azure Communication Network Traversal tasks, including:
34+
35+
- [Getting the relay configuration](#getting-the-relay-configuration)
36+
37+
```python
38+
# You can find your endpoint and access token from your resource in the Azure Portal
39+
import os
40+
from azure.communication.networktraversal import CommunicationRelayClient
41+
from azure.identity import DefaultAzureCredential
42+
from azure.communication.identity import CommunicationIdentityClient
43+
44+
connection_str = "endpoint=ENDPOINT;accessKey=KEY"
45+
endpoint = "https://<RESOURCE_NAME>.communication.azure.com"
46+
47+
# To use Azure Active Directory Authentication (DefaultAzureCredential) make sure to have
48+
# AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET as env variables.
49+
# We also need Identity client to get a User Identifier
50+
identity_client = CommunicationIdentityClient(endpoint, DefaultAzureCredential())
51+
relay_client = CommunicationRelayClient(endpoint, DefaultAzureCredential())
52+
```
53+
54+
#You can also authenticate using your connection string
55+
56+
```python
57+
identity_client = CommunicationIdentityClient.from_connection_string(self.connection_string)
58+
relay_client = CommunicationRelayClient.from_connection_string(self.connection_string)
59+
```
60+
61+
### Getting the relay configuration
62+
63+
```python
64+
# We need a user from Identity
65+
user = identity_client.create_user()
66+
relay_configuration = relay_client.get_relay_configuration(user)
67+
68+
for iceServer in config.ice_servers:
69+
assert iceServer.username is not None
70+
print('Username: ' + iceServer.username)
71+
72+
assert iceServer.credential is not None
73+
print('Credential: ' + iceServer.credential)
74+
75+
assert iceServer.urls is not None
76+
for url in iceServer.urls:
77+
print('Url:' + url)
78+
```
79+
80+
# Troubleshooting
81+
82+
The Azure Communication Relay client will raise exceptions defined in [Azure Core][azure_core].
83+
84+
# Next steps
85+
86+
## More sample code
87+
88+
## Provide Feedback
89+
90+
If you encounter any bugs or have suggestions, please file an issue in the [Issues](https://github.com/Azure/azure-sdk-for-python/issues) section of the project
91+
92+
# Contributing
93+
94+
This project welcomes contributions and suggestions. Most contributions require you to agree to a
95+
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.
96+
97+
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the
98+
PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
99+
100+
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
101+
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments.
102+
103+
<!-- LINKS -->
104+
[azure_core]: https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/core/azure-core/README.md
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# -------------------------------------------------------------------------
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License. See License.txt in the project root for
4+
# license information.
5+
# --------------------------------------------------------------------------
6+
7+
# pylint: disable=bad-option-value, unused-import
8+
from ._communication_relay_client import CommunicationRelayClient
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# coding=utf-8
2+
# ------------------------------------
3+
# Copyright (c) Microsoft Corporation.
4+
# Licensed under the MIT License.
5+
# ------------------------------------
6+
7+
from typing import TYPE_CHECKING, Any
8+
9+
from azure.core.tracing.decorator import distributed_trace
10+
from azure.communication.identity import CommunicationUserIdentifier
11+
12+
from ._generated._communication_network_traversal_client\
13+
import CommunicationNetworkTraversalClient\
14+
as CommunicationNetworkTraversalClientGen
15+
from ._shared.utils import parse_connection_str, get_authentication_policy
16+
from ._version import SDK_MONIKER
17+
from ._generated.models import CommunicationRelayConfiguration
18+
19+
if TYPE_CHECKING:
20+
from azure.core.credentials import TokenCredential
21+
22+
class CommunicationRelayClient(object):
23+
"""Azure Communication Services Relay client.
24+
25+
:param str endpoint:
26+
The endpoint url for Azure Communication Service resource.
27+
:param TokenCredential credential:
28+
The TokenCredential we use to authenticate against the service.
29+
30+
.. admonition:: Example:
31+
32+
.. literalinclude:: ../samples/network_traversal_samples.py
33+
:language: python
34+
:dedent: 8
35+
"""
36+
def __init__(
37+
self,
38+
endpoint, # type: str
39+
credential, # type: TokenCredential
40+
**kwargs # type: Any
41+
):
42+
# type: (...) -> None
43+
# pylint: disable=bad-option-value, disable=raise-missing-from
44+
try:
45+
if not endpoint.lower().startswith('http'):
46+
endpoint = "https://" + endpoint
47+
except AttributeError:
48+
raise ValueError("Account URL must be a string.")
49+
50+
if not credential:
51+
raise ValueError(
52+
"You need to provide account shared key to authenticate.")
53+
54+
self._endpoint = endpoint
55+
self._network_traversal_service_client = CommunicationNetworkTraversalClientGen(
56+
self._endpoint,
57+
authentication_policy=get_authentication_policy(endpoint, credential),
58+
sdk_moniker=SDK_MONIKER,
59+
**kwargs)
60+
61+
@classmethod
62+
def from_connection_string(
63+
cls, conn_str, # type: str
64+
**kwargs # type: Any
65+
): # type: (...) -> CommunicationRelayClient
66+
"""Create CommunicationRelayClient from a Connection String.
67+
68+
:param str conn_str: A connection string to an Azure Communication Service resource.
69+
:returns: Instance of CommunicationRelayClient.
70+
:rtype: ~azure.communication.networktraversal.CommunicationRelayClient
71+
72+
.. admonition:: Example:
73+
74+
.. literalinclude:: ../samples/network_traversal_samples_async.py
75+
:start-after: [START auth_from_connection_string]
76+
:end-before: [END auth_from_connection_string]
77+
:language: python
78+
:dedent: 8
79+
:caption: Creating the CommunicationRelayClient from a connection string.
80+
"""
81+
endpoint, access_key = parse_connection_str(conn_str)
82+
83+
return cls(endpoint, access_key, **kwargs)
84+
85+
@distributed_trace
86+
def get_relay_configuration(
87+
self,
88+
user, # type: CommunicationUserIdentifier
89+
**kwargs # type: Any
90+
):
91+
# type: (Any) -> CommunicationRelayConfiguration
92+
"""get a Communication Relay configuration
93+
:param: CommunicationUserIdentifier user: A user from which we will get an id
94+
:return: CommunicationRelayConfiguration
95+
:rtype: ~azure.communication.networktraversal.CommunicationRelayConfiguration
96+
"""
97+
return self._network_traversal_service_client.communication_network_traversal.issue_relay_configuration(
98+
user.properties['id'],
99+
**kwargs)
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# coding=utf-8
2+
# --------------------------------------------------------------------------
3+
# Copyright (c) Microsoft Corporation. All rights reserved.
4+
# Licensed under the MIT License. See License.txt in the project root for license information.
5+
# Code generated by Microsoft (R) AutoRest Code Generator.
6+
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
7+
# --------------------------------------------------------------------------
8+
9+
from ._communication_network_traversal_client import CommunicationNetworkTraversalClient
10+
__all__ = ['CommunicationNetworkTraversalClient']
11+
12+
try:
13+
from ._patch import patch_sdk # type: ignore
14+
patch_sdk()
15+
except ImportError:
16+
pass
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# coding=utf-8
2+
# --------------------------------------------------------------------------
3+
# Copyright (c) Microsoft Corporation. All rights reserved.
4+
# Licensed under the MIT License. See License.txt in the project root for license information.
5+
# Code generated by Microsoft (R) AutoRest Code Generator.
6+
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
7+
# --------------------------------------------------------------------------
8+
9+
from typing import TYPE_CHECKING
10+
11+
from azure.core import PipelineClient
12+
from msrest import Deserializer, Serializer
13+
14+
if TYPE_CHECKING:
15+
# pylint: disable=unused-import,ungrouped-imports
16+
from typing import Any
17+
18+
from azure.core.pipeline.transport import HttpRequest, HttpResponse
19+
20+
from ._configuration import CommunicationNetworkTraversalClientConfiguration
21+
from .operations import CommunicationNetworkTraversalOperations
22+
from . import models
23+
24+
25+
class CommunicationNetworkTraversalClient(object):
26+
"""Azure Communication Networking Service.
27+
28+
:ivar communication_network_traversal: CommunicationNetworkTraversalOperations operations
29+
:vartype communication_network_traversal: azure.communication.networktraversal.operations.CommunicationNetworkTraversalOperations
30+
:param endpoint: The communication resource, for example https://my-resource.communication.azure.com.
31+
:type endpoint: str
32+
"""
33+
34+
def __init__(
35+
self,
36+
endpoint, # type: str
37+
**kwargs # type: Any
38+
):
39+
# type: (...) -> None
40+
base_url = '{endpoint}'
41+
self._config = CommunicationNetworkTraversalClientConfiguration(endpoint, **kwargs)
42+
self._client = PipelineClient(base_url=base_url, config=self._config, **kwargs)
43+
44+
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
45+
self._serialize = Serializer(client_models)
46+
self._serialize.client_side_validation = False
47+
self._deserialize = Deserializer(client_models)
48+
49+
self.communication_network_traversal = CommunicationNetworkTraversalOperations(
50+
self._client, self._config, self._serialize, self._deserialize)
51+
52+
def _send_request(self, http_request, **kwargs):
53+
# type: (HttpRequest, Any) -> HttpResponse
54+
"""Runs the network request through the client's chained policies.
55+
56+
:param http_request: The network request you want to make. Required.
57+
:type http_request: ~azure.core.pipeline.transport.HttpRequest
58+
:keyword bool stream: Whether the response payload will be streamed. Defaults to True.
59+
:return: The response of your network call. Does not do error handling on your response.
60+
:rtype: ~azure.core.pipeline.transport.HttpResponse
61+
"""
62+
path_format_arguments = {
63+
'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
64+
}
65+
http_request.url = self._client.format_url(http_request.url, **path_format_arguments)
66+
stream = kwargs.pop("stream", True)
67+
pipeline_response = self._client._pipeline.run(http_request, stream=stream, **kwargs)
68+
return pipeline_response.http_response
69+
70+
def close(self):
71+
# type: () -> None
72+
self._client.close()
73+
74+
def __enter__(self):
75+
# type: () -> CommunicationNetworkTraversalClient
76+
self._client.__enter__()
77+
return self
78+
79+
def __exit__(self, *exc_details):
80+
# type: (Any) -> None
81+
self._client.__exit__(*exc_details)

0 commit comments

Comments
 (0)