Skip to content

Commit f26f88b

Browse files
committed
fix: various port fixes
1 parent ceac7ab commit f26f88b

File tree

6 files changed

+69
-72
lines changed

6 files changed

+69
-72
lines changed

cli.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ async def pnp_service_connect() -> Peer:
152152
await peer.start()
153153
log.info('pnpService: peer activated')
154154
_setPnPServiceConnectionHandlers(peer)
155-
make_discoverable(peer=peer)
155+
await make_discoverable(peer=peer)
156156
return peer
157157

158158

@@ -163,7 +163,7 @@ async def make_discoverable(peer=None):
163163
async def periodic():
164164
while True:
165165
log.info('Making peer discoverable.')
166-
join_peer_room(peer=peer)
166+
await join_peer_room(peer=peer)
167167
await asyncio.sleep(5)
168168

169169
def stop():

grep

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/Users/ivelin/ambianic.co/peerjs-python
2+
3.8.1 (v3.8.1:1b293b6006, Dec 18 2019, 14:08:53)
3+
[Clang 6.0 (clang-600.0.57)]
4+
DEBUG:__main__:Log level set to debug
5+
DEBUG:asyncio:Using selector: KqueueSelector
6+
INFO:__main__:pnpService: creating peer
7+
DEBUG:peerjs.api:API options: PeerOptions(debug=2, host='ambianic-pnp.herokuapp.com', port=80, path='/', key='peerjs', token=None, config=RTCConfiguration(iceServers=[RTCIceServer(urls=['stun:stun.l.google.com:19302'], username=None, credential=None, credentialType='password'), RTCIceServer(urls=['turn:0.peerjs.com:3478'], username='peerjs', credential='peerjsp', credentialType='password')]), secure=True, pingInterval=5)
8+
INFO:__main__:pnpService: peer created
9+
DEBUG:peerjs.api:built url: https://ambianic-pnp.herokuapp.com:?ts=0.4432262820.9929900131672725
10+
INFO:__main__:pnpService: peer activated
11+
INFO:__main__:Making peer discoverable.
12+
DEBUG:peerjs.api:API options: PeerOptions(debug=2, host='ambianic-pnp.herokuapp.com', port=80, path='/', key='peerjs', token=None, config=RTCConfiguration(iceServers=[RTCIceServer(urls=['stun:stun.l.google.com:19302'], username=None, credential=None, credentialType='password'), RTCIceServer(urls=['turn:0.peerjs.com:3478'], username='peerjs', credential='peerjsp', credentialType='password')]), secure=True, pingInterval=5)
13+
DEBUG:peerjs.api:built url: https://ambianic-pnp.herokuapp.com:?ts=0.7002259830.8773265258372509

src/peerjs/api.py

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Client side abstraction for commonly used REST APIs."""
22

33
import logging
4-
import math
4+
import random
55
import time
66
from typing import Any
77

@@ -13,21 +13,6 @@
1313
log = logging.getLogger(__name__)
1414

1515

16-
async def fetch(url=None, method=None, body=None):
17-
"""Similar to web browser JavaScript fetch."""
18-
if not method:
19-
method = HttpMethod.GET
20-
async with aiohttp.ClientSession() as session:
21-
if method == HttpMethod.GET:
22-
async with session.get(url) as response:
23-
return await response
24-
elif method == HttpMethod.POST:
25-
async with session.post(url, data=body) as response:
26-
return await response
27-
else:
28-
raise NotImplementedError(
29-
f"HTTP requst method {method} not implemented yet. "
30-
"Contributions welcome!")
3116

3217

3318
class API:
@@ -36,27 +21,40 @@ class API:
3621
def __init__(self, options: Any = None):
3722
"""Create API instance."""
3823
self._options = options
24+
log.debug('API options: %s', options)
3925

4026
def _buildUrl(self, method: str = None) -> str:
4127
protocol = "https://" if self._options.secure else "http://"
42-
url = \
43-
protocol + \
44-
self._options.host + \
45-
":" + \
46-
self._options.port + \
47-
self._options.path + \
48-
self._options.key + \
49-
"/" + \
50-
method
51-
queryString = "?ts=" + time.monotonous() + "" + math.random()
28+
url = f'{protocol}{self._options.host}:'
29+
f'{self._options.port}{self._options.path}{self._options.key}'
30+
f'/method'
31+
queryString = f'?ts={time.monotonic()}{random.random()}'
5232
url += queryString
33+
log.debug('built url: %s', url)
5334
return url
5435

36+
@staticmethod
37+
async def fetch(url=None, method=None, body=None):
38+
"""Similar to web browser JavaScript fetch."""
39+
if not method:
40+
method = HttpMethod.GET
41+
async with aiohttp.ClientSession() as session:
42+
if method == HttpMethod.GET:
43+
async with session.get(url) as response:
44+
return await response
45+
elif method == HttpMethod.POST:
46+
async with session.post(url, data=body) as response:
47+
return await response
48+
else:
49+
raise NotImplementedError(
50+
f"HTTP requst method {method} not implemented yet. "
51+
"Contributions welcome!")
52+
5553
async def retrieveId(self):
5654
"""Get a unique ID from the server and initialize with it."""
5755
url = self._buildUrl("id")
5856
try:
59-
response = await fetch(url)
57+
response = await API.fetch(url)
6058
if response.status != 200:
6159
raise ConnectionError(f'Error. Status:{response.status}')
6260
return response.text()

src/peerjs/peer.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
from dataclasses import dataclass
88
from typing import Any, List
99

10-
import attr
1110
from pyee import AsyncIOEventEmitter, BaseEventEmitter
1211

1312
from .api import API
@@ -45,13 +44,14 @@ class PeerOptions:
4544
"""Peer configuration options."""
4645

4746
debug: int = 0 # 1: Errors, 2: Warnings, 3: All logs
48-
host: str = attr.ib(default=util.CLOUD_HOST)
47+
host: str = util.CLOUD_HOST
4948
port: int = util.CLOUD_PORT
5049
path: str = "/"
5150
key: str = PEER_DEFAULT_KEY
5251
token: str = util.randomToken()
5352
config: Any = util.defaultConfig
5453
secure: bool = False
54+
pingInterval: int = 5 # ping to signaling server in seconds
5555

5656

5757
# 0: None, 1: Errors, 2: Warnings, 3: All logs
@@ -205,7 +205,6 @@ def disconnected(self, ):
205205
"""Return True if peer is disconnected from signaling server."""
206206
return self._disconnected
207207

208-
@property
209208
def _createServerConnection(self) -> Socket:
210209
socket = Socket(
211210
self._options.secure,
@@ -486,7 +485,7 @@ def emitError(self, type: PeerErrorType, err: str) -> None:
486485
error.type = type
487486
self.emit(PeerEventType.Error, error)
488487

489-
def destroy(self) -> None:
488+
async def destroy(self) -> None:
490489
"""Destroy Peer and close all active connections.
491490
492491
Close all active peer connections and the active server connection.

src/peerjs/peerroom.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
Same room defined as shared WiFi/LAN and Public IP Address.
44
"""
55

6-
from .peer import Peer
76
import logging
7+
88
from .api import API
9+
from .peer import Peer
910

1011
log = logging.getLogger(__name__)
1112

@@ -23,15 +24,17 @@ def __init__(self, peer: Peer):
2324
async def _restCall(self, http_method=None, rest_method=None):
2425
log.debug('REST Call {} {}', http_method, rest_method)
2526
url = self._api._buildUrl(method=rest_method)
27+
response = None
2628
try:
27-
response = await self._api._fetch(url=url, method=http_method)
29+
response = await API.fetch(url=url, method=http_method)
2830
if response.status != 200:
2931
raise ConnectionError()
3032
return response.json()
3133
except Exception as error:
3234
msg = f"REST Error for {http_method} {url}."
33-
f" HTTP Response Status:{response.status}"
3435
log.error(msg, error)
36+
if response is not None:
37+
log.error(f'HTTP Response Status %s', response.status)
3538
raise ConnectionError(msg, error)
3639

3740
async def _getRoomId(self):
@@ -51,7 +54,7 @@ async def _joinRoom(self):
5154
log.debug('Joined room %s, Members: %s', self._roomId, members)
5255
return members
5356

54-
async def getRoomMembers(self, roomId):
57+
async def getRoomMembers(self):
5558
"""Get the list of peers in a room."""
5659
if not self._roomId:
5760
members = await self.join()

src/peerjs/util.py

Lines changed: 19 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
"""Helper utility structures and methods."""
22
import logging
3+
import math
34
import random
5+
from dataclasses import dataclass
46

5-
from aiortc import RTCDataChannel, RTCPeerConnection
67
from aiortc.rtcconfiguration import RTCConfiguration, RTCIceServer
78

89
# import asyncio
@@ -21,6 +22,18 @@
2122
)
2223

2324

25+
@dataclass
26+
class UtilSupports:
27+
"""WebRTC parameters supported by this library."""
28+
29+
webRTC: bool = True
30+
browser: str = 'aiortc'
31+
audioVideo: bool = True
32+
data: bool = True
33+
binaryBlob: bool = False
34+
reliable: bool = True
35+
36+
2437
class Util:
2538
"""Various helper methods."""
2639

@@ -43,48 +56,19 @@ def __init__(self):
4356
self.browser = "peerjs-python" # Supports.getBrowser()
4457
self.browserVersion = "0.1" # Supports.getVersion()
4558
# Lists which features are supported
46-
self.supports = self._supported()
4759
# Binary stuff
4860
self._dataCount: int = 1
61+
self._supports = UtilSupports()
4962

5063
def validateId(self, id: str) -> bool:
5164
"""Ensure alphanumeric ids."""
5265
# Allow empty ids
5366
return not id or id.isalnum()
5467

55-
def _supported(self):
56-
supported = {
57-
'browser': 'aiortc',
58-
'webRTC': True,
59-
'audioVideo': False,
60-
'data': False,
61-
'binaryBlob': False,
62-
'reliable': False,
63-
}
64-
if not supported['webRTC']:
65-
return supported
66-
pc: RTCPeerConnection = None
67-
try:
68-
pc = RTCPeerConnection(DEFAULT_CONFIG)
69-
supported['audioVideo'] = True
70-
dc: RTCDataChannel = None
71-
try:
72-
dc = pc.createDataChannel(label="_PEERJSTEST", ordered=True)
73-
supported['data'] = True
74-
supported['reliable'] = True if dc.ordered else False
75-
# Test for Binary mode support
76-
try:
77-
dc.binaryType = "blob"
78-
supported.binaryBlob = False
79-
except Exception:
80-
pass
81-
finally:
82-
if dc:
83-
dc.close()
84-
finally:
85-
if pc:
86-
pc.close()
87-
return supported
68+
@property
69+
def supports(self):
70+
"""Return dict of supported WebRTC features."""
71+
return self._supports
8872

8973
def chunk(self, blob):
9074
"""Break up a blob into a list of smaller chunks for the wire."""

0 commit comments

Comments
 (0)