add optional cli argument for 'man' field in ssdp

This commit is contained in:
Jack Robison 2018-10-10 11:48:31 -04:00
parent c8b2f0d5cc
commit a803bb57b3
No known key found for this signature in database
GPG key ID: DF25C68FE0239BB2
4 changed files with 24 additions and 22 deletions

View file

@ -2,7 +2,6 @@ import logging
import sys import sys
from aioupnp.upnp import UPnP from aioupnp.upnp import UPnP
log = logging.getLogger("aioupnp") log = logging.getLogger("aioupnp")
handler = logging.StreamHandler() handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)-15s-%(filename)s:%(lineno)s->%(message)s')) handler.setFormatter(logging.Formatter('%(asctime)-15s-%(filename)s:%(lineno)s->%(message)s'))
@ -47,6 +46,7 @@ def main():
'lan_address': '', 'lan_address': '',
'timeout': 1, 'timeout': 1,
'service': '', # if not provided try all of them 'service': '', # if not provided try all of them
'man': '',
'return_as_json': True 'return_as_json': True
} }
@ -80,7 +80,7 @@ def main():
UPnP.run_cli( UPnP.run_cli(
command.replace('-', '_'), options.pop('lan_address'), options.pop('gateway_address'), command.replace('-', '_'), options.pop('lan_address'), options.pop('gateway_address'),
options.pop('timeout'), options.pop('service'), options.pop('interface'), options.pop('timeout'), options.pop('service'), options.pop('man'), options.pop('interface'),
kwargs kwargs
) )

View file

@ -1,7 +1,6 @@
import logging import logging
import socket import socket
import typing from typing import Dict, List, Union, Type
from typing import Dict, List, Union, Type, Tuple
from aioupnp.util import get_dict_val_case_insensitive, BASE_PORT_REGEX, BASE_ADDRESS_REGEX from aioupnp.util import get_dict_val_case_insensitive, BASE_PORT_REGEX, BASE_ADDRESS_REGEX
from aioupnp.constants import SPEC_VERSION, UPNP_ORG_IGD, SERVICE from aioupnp.constants import SPEC_VERSION, UPNP_ORG_IGD, SERVICE
from aioupnp.commands import SCPDCommands from aioupnp.commands import SCPDCommands
@ -130,15 +129,15 @@ class Gateway:
@classmethod @classmethod
async def discover_gateway(cls, lan_address: str, gateway_address: str, timeout: int = 1, async def discover_gateway(cls, lan_address: str, gateway_address: str, timeout: int = 1,
service: str = UPNP_ORG_IGD, ssdp_socket: socket.socket = None, service: str = UPNP_ORG_IGD, man: str = '',
soap_socket: socket.socket = None): ssdp_socket: socket.socket = None, soap_socket: socket.socket = None):
datagram = await m_search(lan_address, gateway_address, timeout, service, ssdp_socket) datagram = await m_search(lan_address, gateway_address, timeout, service, man, ssdp_socket)
gateway = cls(**datagram.as_dict()) gateway = cls(**datagram.as_dict())
await gateway.discover_commands(soap_socket) await gateway.discover_commands(soap_socket)
return gateway return gateway
async def discover_commands(self, soap_socket: socket.socket = None): async def discover_commands(self, soap_socket: socket.socket = None):
response = await scpd_get("/" + self.path.decode(), self.base_ip.decode(), self.port) response = await scpd_get(self.path.decode(), self.base_ip.decode(), self.port)
self.spec_version = get_dict_val_case_insensitive(response, SPEC_VERSION) self.spec_version = get_dict_val_case_insensitive(response, SPEC_VERSION)
self.url_base = get_dict_val_case_insensitive(response, "urlbase") self.url_base = get_dict_val_case_insensitive(response, "urlbase")

View file

@ -33,10 +33,10 @@ class SSDPProtocol(MulticastProtocol):
log.debug("sending packet to %s:%i: %s", address, SSDP_PORT, packet) log.debug("sending packet to %s:%i: %s", address, SSDP_PORT, packet)
self.transport.sendto(packet.encode().encode(), (address, SSDP_PORT)) self.transport.sendto(packet.encode().encode(), (address, SSDP_PORT))
async def m_search(self, address, timeout: int = 1, service='') -> SSDPDatagram: async def m_search(self, address, timeout: int = 1, service='', man='') -> SSDPDatagram:
if (address, service) in self.discover_callbacks: if (address, service) in self.discover_callbacks:
return self.discover_callbacks[(address, service)] return self.discover_callbacks[(address, service)]
man = man or SSDP_DISCOVER
if not service: if not service:
services = [UPNP_ORG_IGD, WIFI_ALLIANCE_ORG_IGD] services = [UPNP_ORG_IGD, WIFI_ALLIANCE_ORG_IGD]
else: else:
@ -49,10 +49,10 @@ class SSDPProtocol(MulticastProtocol):
# D-Link works with both # D-Link works with both
# Cisco only works with quotes # Cisco only works with quotes
self.send_m_search_packet(service, address, '\"%s\"' % SSDP_DISCOVER) self.send_m_search_packet(service, address, '\"%s\"' % man)
# DD-WRT only works without quotes # DD-WRT only works without quotes
self.send_m_search_packet(service, address, SSDP_DISCOVER) self.send_m_search_packet(service, address, man)
f: Future = Future() f: Future = Future()
f.add_done_callback(lambda _f: outer_fut.set_result(_f.result())) f.add_done_callback(lambda _f: outer_fut.set_result(_f.result()))
@ -119,12 +119,12 @@ async def listen_ssdp(lan_address: str, gateway_address: str,
async def m_search(lan_address: str, gateway_address: str, timeout: int = 1, async def m_search(lan_address: str, gateway_address: str, timeout: int = 1,
service: str = '', ssdp_socket: socket.socket = None) -> SSDPDatagram: service: str = '', man: str = '', ssdp_socket: socket.socket = None) -> SSDPDatagram:
transport, protocol, gateway_address, lan_address = await listen_ssdp( transport, protocol, gateway_address, lan_address = await listen_ssdp(
lan_address, gateway_address, ssdp_socket lan_address, gateway_address, ssdp_socket
) )
try: try:
return await protocol.m_search(address=gateway_address, timeout=timeout, service=service) return await protocol.m_search(address=gateway_address, timeout=timeout, service=service, man=man)
except asyncio.TimeoutError: except asyncio.TimeoutError:
raise UPnPError("M-SEARCH for {}:{} timed out".format(gateway_address, SSDP_PORT)) raise UPnPError("M-SEARCH for {}:{} timed out".format(gateway_address, SSDP_PORT))
finally: finally:

View file

@ -42,21 +42,23 @@ class UPnP:
@classmethod @classmethod
async def discover(cls, lan_address: str = '', gateway_address: str = '', timeout: int = 1, async def discover(cls, lan_address: str = '', gateway_address: str = '', timeout: int = 1,
service: str = '', interface_name: str = 'default', service: str = '', man: str = '', interface_name: str = 'default',
ssdp_socket: socket.socket = None, soap_socket: socket.socket = None): ssdp_socket: socket.socket = None, soap_socket: socket.socket = None):
try: try:
lan_address, gateway_address = cls.get_lan_and_gateway(lan_address, gateway_address, interface_name) lan_address, gateway_address = cls.get_lan_and_gateway(lan_address, gateway_address, interface_name)
except Exception as err: except Exception as err:
raise UPnPError("failed to get lan and gateway addresses: %s" % str(err)) raise UPnPError("failed to get lan and gateway addresses: %s" % str(err))
gateway = await Gateway.discover_gateway(lan_address, gateway_address, timeout, service, ssdp_socket, soap_socket) gateway = await Gateway.discover_gateway(
lan_address, gateway_address, timeout, service, man, ssdp_socket, soap_socket
)
return cls(lan_address, gateway_address, gateway) return cls(lan_address, gateway_address, gateway)
@classmethod @classmethod
@cli @cli
async def m_search(cls, lan_address: str = '', gateway_address: str = '', timeout: int = 1, async def m_search(cls, lan_address: str = '', gateway_address: str = '', timeout: int = 1,
service: str = '', interface_name: str = 'default') -> Dict: service: str = '', man: str = '', interface_name: str = 'default') -> Dict:
lan_address, gateway_address = cls.get_lan_and_gateway(lan_address, gateway_address, interface_name) lan_address, gateway_address = cls.get_lan_and_gateway(lan_address, gateway_address, interface_name)
datagram = await m_search(lan_address, gateway_address, timeout, service) datagram = await m_search(lan_address, gateway_address, timeout, service, man)
return { return {
'lan_address': lan_address, 'lan_address': lan_address,
'gateway_address': gateway_address, 'gateway_address': gateway_address,
@ -214,10 +216,9 @@ class UPnP:
@classmethod @classmethod
def run_cli(cls, method, lan_address: str = '', gateway_address: str = '', timeout: int = 60, def run_cli(cls, method, lan_address: str = '', gateway_address: str = '', timeout: int = 60,
service: str = '', interface_name: str = 'default', service: str = '', man: str = '', interface_name: str = 'default',
kwargs: dict = None) -> None: kwargs: dict = None) -> None:
kwargs = kwargs or {} kwargs = kwargs or {}
try: try:
asyncio.get_running_loop() asyncio.get_running_loop()
except RuntimeError: except RuntimeError:
@ -228,10 +229,12 @@ class UPnP:
async def wrapper(): async def wrapper():
if method == 'm_search': if method == 'm_search':
fn = lambda *_a, **_kw: cls.m_search(lan_address, gateway_address, timeout, service, interface_name) fn = lambda *_a, **_kw: cls.m_search(
lan_address, gateway_address, timeout, service, man, interface_name
)
else: else:
u = await cls.discover( u = await cls.discover(
lan_address, gateway_address, timeout, service, interface_name lan_address, gateway_address, timeout, service, man, interface_name
) )
if hasattr(u, method) and hasattr(getattr(u, method), "_cli"): if hasattr(u, method) and hasattr(getattr(u, method), "_cli"):
fn = getattr(u, method) fn = getattr(u, method)