Skip to content

Commit

Permalink
feat: expose dedicated configuration
Browse files Browse the repository at this point in the history
feat: expose dedicated configuration
Merge pull request #37 from muka/feature/expose_config_ice
  • Loading branch information
Ivelin Ivanov committed Nov 9, 2020
2 parents 517cb7c + 5fb1f00 commit c1cf754
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 39 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,4 @@ dmypy.json
.pyre/

.peerjsrc
peerjs-config.yaml
2 changes: 0 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
94 changes: 63 additions & 31 deletions src/peerjs/ext/http-proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import logging
import sys
import json
import yaml
import aiohttp
from typing import Any
import coloredlogs
Expand All @@ -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
Expand All @@ -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")

Expand Down Expand Up @@ -87,29 +87,50 @@ 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 _loadConfig():
global config
def _loadPeerId():
global savedPeerId
conf_file = Path(CONFIG_FILE)
conf_file = Path(PEERID_FILE)
if conf_file.exists():
conf = {}
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
conf = json.load(infile)
savedPeerId = conf.get('peerId', None)


def _loadConfig():
global config
conf_file = Path(CONFIG_FILE)
exists = conf_file.exists()
if exists:
with conf_file.open() as infile:
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

return exists


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
global savedPeerId
Expand Down Expand Up @@ -272,12 +293,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',
Expand Down Expand Up @@ -324,6 +349,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 ' \
Expand All @@ -332,11 +358,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():
Expand Down Expand Up @@ -372,7 +401,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')
Expand Down
11 changes: 5 additions & 6 deletions src/peerjs/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ install_requires =
websockets>=8.1
dataclasses_json>=0.3
coloredlogs>=10.0
pyyaml>=5.3.1

[coverage:run]
source = peerjs
Expand Down

0 comments on commit c1cf754

Please sign in to comment.