From 93b9a66fd4b6c4213bf982a5da04bde15243c16c Mon Sep 17 00:00:00 2001 From: Luca Capra Date: Tue, 3 Nov 2020 06:09:47 +0100 Subject: [PATCH 1/3] - expose ice servers - store config in yaml --- .gitignore | 1 + README.md | 2 - src/peerjs/ext/http-proxy.py | 88 ++++++++++++++++++++++++------------ src/peerjs/util.py | 11 ++--- src/setup.cfg | 1 + 5 files changed, 65 insertions(+), 38 deletions(-) diff --git a/.gitignore b/.gitignore index 0e687fd..7d519af 100644 --- a/.gitignore +++ b/.gitignore @@ -129,3 +129,4 @@ dmypy.json .pyre/ .peerjsrc +peerjs-config.yaml \ No newline at end of file diff --git a/README.md b/README.md index 297049a..0d27421 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,6 @@ Enables [Progressive Web Apps](https://developer.mozilla.org/en-US/docs/Web/Prog See Ambianic UI [PNP module](https://github.com/ambianic/ambianic-ui/blob/master/src/store/pnp.js) for a real-world example how PeerJS Python is used with PnP and HTTP Proxy. -- *Setting additional STUN servers* is possible using the `STUN_SERVERS` env variable, separated by semicolon (`;`). Eg. `STUN_SERVERS=stun:example1.org:19302;stun:example2.org:19302;` - ## Dependencies Uses [aiortc](https://github.com/aiortc/aiortc) as Python WebRTC provider. This requires installing a few native dependencies for audio/video media processing. diff --git a/src/peerjs/ext/http-proxy.py b/src/peerjs/ext/http-proxy.py index f28e864..65dc7a4 100644 --- a/src/peerjs/ext/http-proxy.py +++ b/src/peerjs/ext/http-proxy.py @@ -5,6 +5,7 @@ import logging import sys import json +import yaml import aiohttp from typing import Any import coloredlogs @@ -13,14 +14,15 @@ # from aiortc import RTCIceCandidate, RTCSessionDescription from peerjs.peer import Peer, PeerOptions from peerjs.peerroom import PeerRoom -from peerjs.util import util, default_stun_servers +from peerjs.util import util, default_ice_servers from peerjs.enums import ConnectionEventType, PeerEventType +from aiortc.rtcconfiguration import RTCConfiguration, RTCIceServer print(sys.version) log = logging.getLogger(__name__) -LOG_LEVEL = logging.INFO +DEFAULT_LOG_LEVEL = "INFO" peer = None savedPeerId = None @@ -30,21 +32,19 @@ AMBIANIC_PNP_PORT = 443 # 9779 AMBIANIC_PNP_SECURE = True # False -server_list_str = os.environ.get("STUN_SERVERS") -if server_list_str: - server_list = server_list_str.split(";") - for el in server_list: - if el not in default_stun_servers: - default_stun_servers.append(el) - config = { 'host': AMBIANIC_PNP_HOST, 'port': AMBIANIC_PNP_PORT, 'secure': AMBIANIC_PNP_SECURE, - 'stun_servers': default_stun_servers, + 'ice_servers': default_ice_servers, + 'log_level': DEFAULT_LOG_LEVEL, } -CONFIG_FILE = '.peerjsrc' +PEERID_FILE = '.peerjsrc' +if os.environ.get("PEERJS_PEERID_FILE"): + PEERID_FILE = os.environ.get("PEERJS_PEERID_FILE") + +CONFIG_FILE = 'peerjs-config.yaml' if os.environ.get("PEERJS_CONFIG_FILE"): CONFIG_FILE = os.environ.get("PEERJS_CONFIG_FILE") @@ -87,28 +87,45 @@ def _savePeerId(peerId=None): assert peerId global savedPeerId savedPeerId = peerId - config['peerId'] = peerId - with open(CONFIG_FILE, 'w') as outfile: - json.dump(config, outfile) + with open(PEERID_FILE, 'w') as outfile: + json.dump({ 'peerId': peerId }, outfile) + + +def _loadPeerId(): + global savedPeerId + conf_file = Path(PEERID_FILE) + if conf_file.exists(): + conf = {} + with conf_file.open() as infile: + conf = json.load(infile) + savedPeerId = conf.get('peerId', None) def _loadConfig(): global config - global savedPeerId conf_file = Path(CONFIG_FILE) if conf_file.exists(): with conf_file.open() as infile: - config = json.load(infile) - savedPeerId = config.get('peerId', None) - if "host" not in config.keys(): - config["host"] = AMBIANIC_PNP_HOST - if "port" not in config.keys(): - config["port"] = AMBIANIC_PNP_PORT - if "secure" not in config.keys(): - config["secure"] = AMBIANIC_PNP_SECURE - if "stun_servers" not in config.keys(): - config["stun_servers"] = default_stun_servers - + config = yaml.load(infile) + # Set defaults + if config is None: + config = {} + if "host" not in config.keys(): + config["host"] = AMBIANIC_PNP_HOST + if "port" not in config.keys(): + config["port"] = AMBIANIC_PNP_PORT + if "secure" not in config.keys(): + config["secure"] = AMBIANIC_PNP_SECURE + if "ice_servers" not in config.keys(): + config["ice_servers"] = default_ice_servers + +def _saveConfig(): + global config + cfg1 = config.copy() + if 'peerId' in cfg1.keys(): + del cfg1["peerId"] + with open(CONFIG_FILE, 'w') as outfile: + yaml.dump(cfg1, outfile) def _setPnPServiceConnectionHandlers(peer=None): assert peer @@ -272,12 +289,16 @@ async def pnp_service_connect() -> Peer: log.info('last saved savedPeerId %s', savedPeerId) new_token = util.randomToken() log.info('Peer session token %s', new_token) + + options = PeerOptions( host=config['host'], port=config['port'], secure=config['secure'], token=new_token, - config=config['stun_servers'] + config=RTCConfiguration( + iceServers=[RTCIceServer(**srv) for srv in config['ice_servers']] + ) ) peer = Peer(id=savedPeerId, peer_options=options) log.info('pnpService: peer created with id %s , options: %r', @@ -324,6 +345,7 @@ async def make_discoverable(peer=None): def _config_logger(): + global config root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) format_cfg = '%(asctime)s %(levelname)-4s ' \ @@ -332,11 +354,14 @@ def _config_logger(): fmt = logging.Formatter(fmt=format_cfg, datefmt=datefmt_cfg, style='%') ch = logging.StreamHandler(sys.stdout) - ch.setLevel(LOG_LEVEL) + logLevel = config["log_level"] + if not logLevel: + logLevel = DEFAULT_LOG_LEVEL + ch.setLevel(logLevel) ch.setFormatter(fmt) root_logger.handlers = [] root_logger.addHandler(ch) - coloredlogs.install(level=LOG_LEVEL, fmt=format_cfg) + coloredlogs.install(level=logLevel, fmt=format_cfg) async def _start(): @@ -372,7 +397,10 @@ async def _shutdown(): # add_signaling_arguments(parser) # args = parser.parse_args() # if args.verbose: - _loadConfig() + _loadPeerId() + exists = _loadConfig() + if not exists: + _saveConfig() _config_logger() # add formatter to ch log.debug('Log level set to debug') diff --git a/src/peerjs/util.py b/src/peerjs/util.py index 8c2135e..b1d3126 100644 --- a/src/peerjs/util.py +++ b/src/peerjs/util.py @@ -14,15 +14,14 @@ log = logging.getLogger(__name__) - -default_stun_servers = [ - "stun:stun.l.google.com:19302" +default_ice_servers = [ + { + "urls": ["stun:stun.l.google.com:19302"] + } ] DEFAULT_CONFIG = RTCConfiguration( - iceServers=[ - RTCIceServer(urls=default_stun_servers) - ] + iceServers=[RTCIceServer(**srv) for srv in default_ice_servers] ) @dataclass diff --git a/src/setup.cfg b/src/setup.cfg index f49686c..a88f3c4 100644 --- a/src/setup.cfg +++ b/src/setup.cfg @@ -29,6 +29,7 @@ install_requires = websockets>=8.1 dataclasses_json>=0.3 coloredlogs>=10.0 + pyyaml>=5.3.1 [coverage:run] source = peerjs From 49fe8f2a693f203f9d2c13def71177d49a4161e7 Mon Sep 17 00:00:00 2001 From: Luca Capra Date: Tue, 3 Nov 2020 06:11:50 +0100 Subject: [PATCH 2/3] fix lint --- src/peerjs/ext/http-proxy.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/peerjs/ext/http-proxy.py b/src/peerjs/ext/http-proxy.py index 65dc7a4..377ae1e 100644 --- a/src/peerjs/ext/http-proxy.py +++ b/src/peerjs/ext/http-proxy.py @@ -88,7 +88,7 @@ def _savePeerId(peerId=None): global savedPeerId savedPeerId = peerId with open(PEERID_FILE, 'w') as outfile: - json.dump({ 'peerId': peerId }, outfile) + json.dump({'peerId': peerId}, outfile) def _loadPeerId(): @@ -119,6 +119,7 @@ def _loadConfig(): if "ice_servers" not in config.keys(): config["ice_servers"] = default_ice_servers + def _saveConfig(): global config cfg1 = config.copy() @@ -290,7 +291,7 @@ async def pnp_service_connect() -> Peer: new_token = util.randomToken() log.info('Peer session token %s', new_token) - + options = PeerOptions( host=config['host'], port=config['port'], From 5fb1f00e609f2fe3bb7ed9172df8a07083e93744 Mon Sep 17 00:00:00 2001 From: Luca Capra Date: Tue, 3 Nov 2020 06:24:09 +0100 Subject: [PATCH 3/3] fix missing return --- src/peerjs/ext/http-proxy.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/peerjs/ext/http-proxy.py b/src/peerjs/ext/http-proxy.py index 377ae1e..c0e0006 100644 --- a/src/peerjs/ext/http-proxy.py +++ b/src/peerjs/ext/http-proxy.py @@ -104,7 +104,8 @@ def _loadPeerId(): def _loadConfig(): global config conf_file = Path(CONFIG_FILE) - if conf_file.exists(): + exists = conf_file.exists() + if exists: with conf_file.open() as infile: config = yaml.load(infile) # Set defaults @@ -119,6 +120,8 @@ def _loadConfig(): if "ice_servers" not in config.keys(): config["ice_servers"] = default_ice_servers + return exists + def _saveConfig(): global config