prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): <|fim_middle|> @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
"""Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {}
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): <|fim_middle|> @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
"""Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): <|fim_middle|> class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
"""Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results)
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): <|fim_middle|> class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
"""Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): <|fim_middle|> def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
"""Initialize the scanner.""" super().__init__(config) self.leasefile = None
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): <|fim_middle|> class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): <|fim_middle|> <|fim▁end|>
"""Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): <|fim_middle|> <|fim▁end|>
if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": <|fim_middle|> elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
scanner = DnsmasqUbusDeviceScanner(config[DOMAIN])
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": <|fim_middle|> else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
scanner = OdhcpdUbusDeviceScanner(config[DOMAIN])
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: <|fim_middle|> return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
scanner = UbusDeviceScanner(config[DOMAIN])
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: <|fim_middle|> if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
self._generate_mac2name()
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed <|fim_middle|> name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
return None
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: <|fim_middle|> _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
return False
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: <|fim_middle|> self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys())
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): <|fim_middle|> return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key)
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: <|fim_middle|> return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
self.last_results.append(key)
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: <|fim_middle|> result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): <|fim_middle|> else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
values = result["values"].values() self.leasefile = next(iter(values))["leasefile"]
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: <|fim_middle|> result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
return
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: <|fim_middle|> else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3]
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() <|fim_middle|> class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
return
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): <|fim_middle|> else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"]
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() <|fim_middle|> <|fim▁end|>
return
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def <|fim_middle|>(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
get_scanner
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def <|fim_middle|>(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
_refresh_on_access_denied
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def <|fim_middle|>(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
decorator
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def <|fim_middle|>(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
__init__
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def <|fim_middle|>(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
scan_devices
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def <|fim_middle|>(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
_generate_mac2name
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def <|fim_middle|>(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
get_device_name
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def <|fim_middle|>(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
_update_info
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def <|fim_middle|>(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
__init__
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def <|fim_middle|>(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def _generate_mac2name(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
_generate_mac2name
<|file_name|>device_tracker.py<|end_file_name|><|fim▁begin|>"""Support for OpenWRT (ubus) routers.""" import logging import re from openwrt.ubus import Ubus import voluptuous as vol from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, DeviceScanner, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_DHCP_SOFTWARE = "dhcp_software" DEFAULT_DHCP_SOFTWARE = "dnsmasq" DHCP_SOFTWARES = ["dnsmasq", "odhcpd", "none"] PLATFORM_SCHEMA = PARENT_PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_DHCP_SOFTWARE, default=DEFAULT_DHCP_SOFTWARE): vol.In( DHCP_SOFTWARES ), } ) def get_scanner(hass, config): """Validate the configuration and return an ubus scanner.""" dhcp_sw = config[DOMAIN][CONF_DHCP_SOFTWARE] if dhcp_sw == "dnsmasq": scanner = DnsmasqUbusDeviceScanner(config[DOMAIN]) elif dhcp_sw == "odhcpd": scanner = OdhcpdUbusDeviceScanner(config[DOMAIN]) else: scanner = UbusDeviceScanner(config[DOMAIN]) return scanner if scanner.success_init else None def _refresh_on_access_denied(func): """If remove rebooted, it lost our session so rebuild one and try again.""" def decorator(self, *args, **kwargs): """Wrap the function to refresh session_id on PermissionError.""" try: return func(self, *args, **kwargs) except PermissionError: _LOGGER.warning( "Invalid session detected." " Trying to refresh session_id and re-run RPC" ) self.ubus.connect() return func(self, *args, **kwargs) return decorator class UbusDeviceScanner(DeviceScanner): """ This class queries a wireless router running OpenWrt firmware. Adapted from Tomato scanner. """ def __init__(self, config): """Initialize the scanner.""" host = config[CONF_HOST] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.last_results = {} self.url = f"http://{host}/ubus" self.ubus = Ubus(self.url, self.username, self.password) self.hostapd = [] self.mac2name = None self.success_init = self.ubus.connect() is not None def scan_devices(self): """Scan for new devices and return a list with found device IDs.""" self._update_info() return self.last_results def _generate_mac2name(self): """Return empty MAC to name dict. Overridden if DHCP server is set.""" self.mac2name = {} @_refresh_on_access_denied def get_device_name(self, device): """Return the name of the given device or None if we don't know.""" if self.mac2name is None: self._generate_mac2name() if self.mac2name is None: # Generation of mac2name dictionary failed return None name = self.mac2name.get(device.upper(), None) return name @_refresh_on_access_denied def _update_info(self): """Ensure the information from the router is up to date. Returns boolean if scanning successful. """ if not self.success_init: return False _LOGGER.info("Checking hostapd") if not self.hostapd: hostapd = self.ubus.get_hostapd() self.hostapd.extend(hostapd.keys()) self.last_results = [] results = 0 # for each access point for hostapd in self.hostapd: if result := self.ubus.get_hostapd_clients(hostapd): results = results + 1 # Check for each device is authorized (valid wpa key) for key in result["clients"].keys(): device = result["clients"][key] if device["authorized"]: self.last_results.append(key) return bool(results) class DnsmasqUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the dnsmasq DHCP server.""" def __init__(self, config): """Initialize the scanner.""" super().__init__(config) self.leasefile = None def _generate_mac2name(self): if self.leasefile is None: if result := self.ubus.get_uci_config("dhcp", "dnsmasq"): values = result["values"].values() self.leasefile = next(iter(values))["leasefile"] else: return result = self.ubus.file_read(self.leasefile) if result: self.mac2name = {} for line in result["data"].splitlines(): hosts = line.split(" ") self.mac2name[hosts[1].upper()] = hosts[3] else: # Error, handled in the ubus.file_read() return class OdhcpdUbusDeviceScanner(UbusDeviceScanner): """Implement the Ubus device scanning for the odhcp DHCP server.""" def <|fim_middle|>(self): if result := self.ubus.get_dhcp_method("ipv4leases"): self.mac2name = {} for device in result["device"].values(): for lease in device["leases"]: mac = lease["mac"] # mac = aabbccddeeff # Convert it to expected format with colon mac = ":".join(mac[i : i + 2] for i in range(0, len(mac), 2)) self.mac2name[mac.upper()] = lease["hostname"] else: # Error, handled in the ubus.get_dhcp_method() return <|fim▁end|>
_generate_mac2name
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0]<|fim▁hole|>def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg)<|fim▁end|>
return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '')
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): <|fim_middle|> def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
"""Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found")
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): <|fim_middle|> def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found")
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): <|fim_middle|> def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
try: is_botocore() except NotConfigured as e: raise SkipTest(e)
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): <|fim_middle|> def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
""" Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): <|fim_middle|> def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): <|fim_middle|> def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
"""Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider)
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): <|fim_middle|> def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
"""Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '')
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): <|fim_middle|> def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
"""Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): <|fim_middle|> <|fim▁end|>
"""Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg)
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: <|fim_middle|> def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
raise SkipTest("AWS keys not found")
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: <|fim_middle|> def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
raise SkipTest("GCS_PROJECT_ID not found")
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): <|fim_middle|> else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path)
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: <|fim_middle|> return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path)
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def <|fim_middle|>(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
assert_aws_environ
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def <|fim_middle|>(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
assert_gcs_environ
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def <|fim_middle|>(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
skip_if_no_boto
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def <|fim_middle|>(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
get_s3_content_and_delete
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def <|fim_middle|>(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
get_gcs_content_and_delete
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def <|fim_middle|>(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
get_crawler
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def <|fim_middle|>(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
get_pythonpath
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def <|fim_middle|>(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
get_testenv
<|file_name|>test.py<|end_file_name|><|fim▁begin|>""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """Asserts the current environment is suitable for running AWS testsi. Raises SkipTest with the reason if it's not. """ skip_if_no_boto() if 'AWS_ACCESS_KEY_ID' not in os.environ: raise SkipTest("AWS keys not found") def assert_gcs_environ(): if 'GCS_PROJECT_ID' not in os.environ: raise SkipTest("GCS_PROJECT_ID not found") def skip_if_no_boto(): try: is_botocore() except NotConfigured as e: raise SkipTest(e) def get_s3_content_and_delete(bucket, path, with_key=False): """ Get content from s3 key, and delete key afterwards. """ if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and_delete(bucket, path): from google.cloud import storage client = storage.Client(project=os.environ.get('GCS_PROJECT_ID')) bucket = client.get_bucket(bucket) blob = bucket.get_blob(path) content = blob.download_as_string() bucket.delete_blob(path) return content, blob def get_crawler(spidercls=None, settings_dict=None): """Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_crawler(spidercls or Spider) def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def <|fim_middle|>(testcase, text1, text2, msg=None): """Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg) <|fim▁end|>
assert_samelines
<|file_name|>constants.py<|end_file_name|><|fim▁begin|>import math as mth import numpy as np #---------------------- # J Matthews, 21/02 # This is a file containing useful constants for python coding # # Units in CGS unless stated # #---------------------- #H=6.62606957E-27 HEV=4.13620e-15 #C=29979245800.0 #BOLTZMANN=1.3806488E-16 VERY_BIG=1e50 H=6.6262e-27 HC=1.98587e-16 HEV=4.13620e-15 # Planck's constant in eV HRYD=3.04005e-16 # NSH 1204 Planck's constant in Rydberg C =2.997925e10 G=6.670e-8 BOLTZMANN =1.38062e-16 WIEN= 5.879e10 # NSH 1208 Wien Disp Const in frequency units H_OVER_K=4.799437e-11 STEFAN_BOLTZMANN =5.6696e-5 THOMPSON=0.66524e-24 PI = 3.1415927 MELEC = 9.10956e-28 E= 4.8035e-10 # Electric charge in esu MPROT = 1.672661e-24 MSOL = 1.989e33 PC= 3.08e18 YR = 3.1556925e7 PI_E2_OVER_MC=0.02655103 # Classical cross-section PI_E2_OVER_M =7.96e8 ALPHA= 7.297351e-3 # Fine structure constant BOHR= 0.529175e-8 # Bohr radius CR= 3.288051e15 #Rydberg frequency for H != Ryd freq for infinite mass ANGSTROM = 1.e-8 #Definition of an Angstrom in units of this code, e.g. cm EV2ERGS =1.602192e-12<|fim▁hole|>RADIAN= 57.29578 RYD2ERGS =2.1798741e-11 PARSEC=3.086E18<|fim▁end|>
<|file_name|>viewsets.py<|end_file_name|><|fim▁begin|>from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def index(self, request): queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data) @action(detail=False, permission_classes=[HasModelPermission]) def export(self, request):<|fim▁hole|> @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None): serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key) class RelationViewSet(ChoicesViewSet): permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES<|fim▁end|>
serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions')
<|file_name|>viewsets.py<|end_file_name|><|fim▁begin|>from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): <|fim_middle|> class RelationViewSet(ChoicesViewSet): permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES <|fim▁end|>
permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def index(self, request): queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data) @action(detail=False, permission_classes=[HasModelPermission]) def export(self, request): serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None): serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key)
<|file_name|>viewsets.py<|end_file_name|><|fim▁begin|>from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def index(self, request): <|fim_middle|> @action(detail=False, permission_classes=[HasModelPermission]) def export(self, request): serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None): serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key) class RelationViewSet(ChoicesViewSet): permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES <|fim▁end|>
queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data)
<|file_name|>viewsets.py<|end_file_name|><|fim▁begin|>from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def index(self, request): queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data) @action(detail=False, permission_classes=[HasModelPermission]) def export(self, request): <|fim_middle|> @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None): serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key) class RelationViewSet(ChoicesViewSet): permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES <|fim▁end|>
serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions')
<|file_name|>viewsets.py<|end_file_name|><|fim▁begin|>from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def index(self, request): queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data) @action(detail=False, permission_classes=[HasModelPermission]) def export(self, request): serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None): <|fim_middle|> class RelationViewSet(ChoicesViewSet): permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES <|fim▁end|>
serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key)
<|file_name|>viewsets.py<|end_file_name|><|fim▁begin|>from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def index(self, request): queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data) @action(detail=False, permission_classes=[HasModelPermission]) def export(self, request): serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None): serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key) class RelationViewSet(ChoicesViewSet): <|fim_middle|> <|fim▁end|>
permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES
<|file_name|>viewsets.py<|end_file_name|><|fim▁begin|>from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def <|fim_middle|>(self, request): queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data) @action(detail=False, permission_classes=[HasModelPermission]) def export(self, request): serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None): serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key) class RelationViewSet(ChoicesViewSet): permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES <|fim▁end|>
index
<|file_name|>viewsets.py<|end_file_name|><|fim▁begin|>from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def index(self, request): queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data) @action(detail=False, permission_classes=[HasModelPermission]) def <|fim_middle|>(self, request): serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def detail_export(self, request, pk=None): serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key) class RelationViewSet(ChoicesViewSet): permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES <|fim▁end|>
export
<|file_name|>viewsets.py<|end_file_name|><|fim▁begin|>from django_filters.rest_framework import DjangoFilterBackend from rest_framework.decorators import action from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from rdmo.core.exports import XMLResponse from rdmo.core.permissions import HasModelPermission from rdmo.core.views import ChoicesViewSet from rdmo.core.viewsets import CopyModelMixin from .models import Condition from .renderers import ConditionRenderer from .serializers.export import ConditionExportSerializer from .serializers.v1 import ConditionIndexSerializer, ConditionSerializer class ConditionViewSet(CopyModelMixin, ModelViewSet): permission_classes = (HasModelPermission, ) queryset = Condition.objects.select_related('source', 'target_option') \ .prefetch_related('optionsets', 'questionsets', 'questions', 'tasks') serializer_class = ConditionSerializer filter_backends = (DjangoFilterBackend,) filterset_fields = ( 'uri', 'key', 'source', 'relation', 'target_text', 'target_option' ) @action(detail=False) def index(self, request): queryset = Condition.objects.select_related('source', 'target_option') serializer = ConditionIndexSerializer(queryset, many=True) return Response(serializer.data) @action(detail=False, permission_classes=[HasModelPermission]) def export(self, request): serializer = ConditionExportSerializer(self.get_queryset(), many=True) xml = ConditionRenderer().render(serializer.data) return XMLResponse(xml, name='conditions') @action(detail=True, url_path='export', permission_classes=[HasModelPermission]) def <|fim_middle|>(self, request, pk=None): serializer = ConditionExportSerializer(self.get_object()) xml = ConditionRenderer().render([serializer.data]) return XMLResponse(xml, name=self.get_object().key) class RelationViewSet(ChoicesViewSet): permission_classes = (IsAuthenticated, ) queryset = Condition.RELATION_CHOICES <|fim▁end|>
detail_export
<|file_name|>line_displaced.py<|end_file_name|><|fim▁begin|>from chiplotle.geometry.shapes.path import path from chiplotle.geometry.transforms.perpendicular_displace \ import perpendicular_displace def line_displaced(start_coord, end_coord, displacements): '''Returns a Path defined as a line spanning points `start_coord` and `end_coord`, displaced by scalars `displacements`. The number of points in the path is determined by the lenght of `displacements`. ''' p = path([start_coord, end_coord]) perpendicular_displace(p, displacements) return p <|fim▁hole|> disp = [math.sin(i**0.7 / 3.14159 * 2) * 100 for i in range(200)] line = line_displaced(Coordinate(0, 0), Coordinate(1000, 1000), disp) io.view(line)<|fim▁end|>
if __name__ == '__main__': from chiplotle import * import math
<|file_name|>line_displaced.py<|end_file_name|><|fim▁begin|>from chiplotle.geometry.shapes.path import path from chiplotle.geometry.transforms.perpendicular_displace \ import perpendicular_displace def line_displaced(start_coord, end_coord, displacements): <|fim_middle|> if __name__ == '__main__': from chiplotle import * import math disp = [math.sin(i**0.7 / 3.14159 * 2) * 100 for i in range(200)] line = line_displaced(Coordinate(0, 0), Coordinate(1000, 1000), disp) io.view(line) <|fim▁end|>
'''Returns a Path defined as a line spanning points `start_coord` and `end_coord`, displaced by scalars `displacements`. The number of points in the path is determined by the lenght of `displacements`. ''' p = path([start_coord, end_coord]) perpendicular_displace(p, displacements) return p
<|file_name|>line_displaced.py<|end_file_name|><|fim▁begin|>from chiplotle.geometry.shapes.path import path from chiplotle.geometry.transforms.perpendicular_displace \ import perpendicular_displace def line_displaced(start_coord, end_coord, displacements): '''Returns a Path defined as a line spanning points `start_coord` and `end_coord`, displaced by scalars `displacements`. The number of points in the path is determined by the lenght of `displacements`. ''' p = path([start_coord, end_coord]) perpendicular_displace(p, displacements) return p if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
from chiplotle import * import math disp = [math.sin(i**0.7 / 3.14159 * 2) * 100 for i in range(200)] line = line_displaced(Coordinate(0, 0), Coordinate(1000, 1000), disp) io.view(line)
<|file_name|>line_displaced.py<|end_file_name|><|fim▁begin|>from chiplotle.geometry.shapes.path import path from chiplotle.geometry.transforms.perpendicular_displace \ import perpendicular_displace def <|fim_middle|>(start_coord, end_coord, displacements): '''Returns a Path defined as a line spanning points `start_coord` and `end_coord`, displaced by scalars `displacements`. The number of points in the path is determined by the lenght of `displacements`. ''' p = path([start_coord, end_coord]) perpendicular_displace(p, displacements) return p if __name__ == '__main__': from chiplotle import * import math disp = [math.sin(i**0.7 / 3.14159 * 2) * 100 for i in range(200)] line = line_displaced(Coordinate(0, 0), Coordinate(1000, 1000), disp) io.view(line) <|fim▁end|>
line_displaced
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup, find_packages setup(name='gelato.models', version='0.1.2', description='Gelato models', namespace_packages=['gelato'], long_description='', author='', author_email='', license='', url='', include_package_data=True,<|fim▁hole|> install_requires=['django', 'tower'])<|fim▁end|>
packages=find_packages(exclude=['tests']),
<|file_name|>update_tokens.py<|end_file_name|><|fim▁begin|>from optparse import make_option <|fim▁hole|>from brambling.utils.payment import dwolla_update_tokens class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '--days', action='store', dest='days', default=15, help='Number of days ahead of time to update refresh tokens.'), ) def handle(self, *args, **options): try: days = int(options['days']) except ValueError: raise CommandError("Days must be an integer value.") self.stdout.write("Updating dwolla tokens...") self.stdout.flush() count, test_count = dwolla_update_tokens(days) self.stdout.write("Test tokens updated: {}".format(count)) self.stdout.write("Live tokens updated: {}".format(test_count)) self.stdout.flush()<|fim▁end|>
from django.core.management.base import BaseCommand, CommandError
<|file_name|>update_tokens.py<|end_file_name|><|fim▁begin|>from optparse import make_option from django.core.management.base import BaseCommand, CommandError from brambling.utils.payment import dwolla_update_tokens class Command(BaseCommand): <|fim_middle|> <|fim▁end|>
option_list = BaseCommand.option_list + ( make_option( '--days', action='store', dest='days', default=15, help='Number of days ahead of time to update refresh tokens.'), ) def handle(self, *args, **options): try: days = int(options['days']) except ValueError: raise CommandError("Days must be an integer value.") self.stdout.write("Updating dwolla tokens...") self.stdout.flush() count, test_count = dwolla_update_tokens(days) self.stdout.write("Test tokens updated: {}".format(count)) self.stdout.write("Live tokens updated: {}".format(test_count)) self.stdout.flush()
<|file_name|>update_tokens.py<|end_file_name|><|fim▁begin|>from optparse import make_option from django.core.management.base import BaseCommand, CommandError from brambling.utils.payment import dwolla_update_tokens class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '--days', action='store', dest='days', default=15, help='Number of days ahead of time to update refresh tokens.'), ) def handle(self, *args, **options): <|fim_middle|> <|fim▁end|>
try: days = int(options['days']) except ValueError: raise CommandError("Days must be an integer value.") self.stdout.write("Updating dwolla tokens...") self.stdout.flush() count, test_count = dwolla_update_tokens(days) self.stdout.write("Test tokens updated: {}".format(count)) self.stdout.write("Live tokens updated: {}".format(test_count)) self.stdout.flush()
<|file_name|>update_tokens.py<|end_file_name|><|fim▁begin|>from optparse import make_option from django.core.management.base import BaseCommand, CommandError from brambling.utils.payment import dwolla_update_tokens class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '--days', action='store', dest='days', default=15, help='Number of days ahead of time to update refresh tokens.'), ) def <|fim_middle|>(self, *args, **options): try: days = int(options['days']) except ValueError: raise CommandError("Days must be an integer value.") self.stdout.write("Updating dwolla tokens...") self.stdout.flush() count, test_count = dwolla_update_tokens(days) self.stdout.write("Test tokens updated: {}".format(count)) self.stdout.write("Live tokens updated: {}".format(test_count)) self.stdout.flush() <|fim▁end|>
handle
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest")<|fim▁hole|> smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db)<|fim▁end|>
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): <|fim_middle|> def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run()
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): <|fim_middle|> def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
self.group = group self.data = data self.initWindow()
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): <|fim_middle|> def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None)
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): <|fim_middle|> def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): <|fim_middle|> def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
entrySpecify.set_sensitive(radioSpecify.get_active())
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): <|fim_middle|> def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
frame, self.widthOptions = self.dimensionsFrame('Width') return frame
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): <|fim_middle|> def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
frame, self.heightOptions = self.dimensionsFrame('Height') return frame
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): <|fim_middle|> def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): <|fim_middle|> def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value)
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): <|fim_middle|> def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values)
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): <|fim_middle|> def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y)
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): <|fim_middle|> def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y)
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): <|fim_middle|> def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
return locale.atof(valor)
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): <|fim_middle|> def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush()
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): <|fim_middle|> def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
self.dlg.show()
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): <|fim_middle|> def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
self.dlg.hide()
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): <|fim_middle|> def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
return self.dlg.run()
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): <|fim_middle|> dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects")
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): <|fim_middle|> return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
return (opt,value)
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': <|fim_middle|> else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
return self.toFloat(value)
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: <|fim_middle|> def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': return min(values) else: return max(values)
<|file_name|>group_resize.py<|end_file_name|><|fim▁begin|># # -*- coding: utf-8 -*- # Dia Group Resize Plugin # Copyright (c) 2015, Alexandre Machado <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import sys, dia import os import pygtk pygtk.require("2.0") import gtk import locale class ResizeWindow(object): def __init__(self, group, data): self.group = group self.data = data self.initWindow() def initWindow(self): self.dlg = gtk.Dialog() self.dlg.set_title('Group Resize') self.dlg.set_border_width(6) self.dlg.vbox.pack_start(self.dialogContents(), fill=True, expand=True, padding=5) self.dlg.add_button(gtk.STOCK_APPLY, gtk.RESPONSE_APPLY) self.dlg.add_button(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE) self.dlg.set_has_separator(True) self.dlg.set_modal(False) self.dlg.get_widget_for_response(gtk.RESPONSE_CLOSE).connect("clicked", self.hide, None) self.dlg.get_widget_for_response(gtk.RESPONSE_APPLY).connect("clicked", self.clickAplicar, None) def dimensionsFrame(self, label): frame = gtk.Frame(label) table = gtk.Table(rows=4, columns=2) ignore = gtk.RadioButton(group=None, label="do not change") ignore.show() smallest = gtk.RadioButton(group=ignore, label="shrink to smallest") smallest.show() largest = gtk.RadioButton(group=ignore, label="enlarge to largest") largest.show() specify = gtk.RadioButton(group=ignore, label="resize to:") specify.show() value = gtk.Entry() value.show() specify.connect("toggled", self.enableValueEntry, value) self.enableValueEntry(specify, value) table.attach (ignore, 0, 1, 0, 1) table.attach (smallest, 0, 1, 1, 2) table.attach (largest, 0, 1, 2, 3) table.attach (specify, 0, 1, 3, 4) table.attach (value, 1, 2, 3, 4) frame.add(table) table.show() frame.show() options = { 'ignore': ignore, 'smallest': smallest, 'largest': largest, 'specify': specify, 'value': value } return frame, options def enableValueEntry(self, radioSpecify, entrySpecify, *args): entrySpecify.set_sensitive(radioSpecify.get_active()) def contentsFrameWidth(self): frame, self.widthOptions = self.dimensionsFrame('Width') return frame def contentsFrameHeight(self): frame, self.heightOptions = self.dimensionsFrame('Height') return frame def dialogContents(self): contents = gtk.VBox(spacing=5) contents.pack_start(self.contentsFrameWidth(), fill=True, expand=True) contents.pack_start(self.contentsFrameHeight(), fill=True, expand=True) contents.show() return contents def getSelectedGroupOption(self, options): value = options['value'].get_text() for opt in 'ignore', 'smallest', 'largest', 'specify': if options[opt].get_active(): return (opt,value) return ('ignore',value) def getValue(self, opt, value, elProperty): if opt == 'specify': return self.toFloat(value) else: values = [ x.properties[elProperty].value for x in self.group if x.properties.has_key(elProperty) ] if opt == 'smallest': <|fim_middle|> else: return max(values) def adjustWidth(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_width"): difference = value - obj.properties['elem_width'].value handleLeft = obj.handles[3] handleRight = obj.handles[4] amount = difference/2 obj.move_handle(handleLeft, (handleLeft.pos.x - amount, handleLeft.pos.y), 0, 0) obj.move_handle(handleRight, (handleRight.pos.x + amount, handleRight.pos.y), 0, 0) obj.move(pos.x, pos.y) def adjustHeight(self, value): for obj in self.group: pos = obj.properties['obj_pos'].value if obj.properties.has_key("elem_height"): difference = value - obj.properties['elem_height'].value handleTop = obj.handles[1] handleBottom = obj.handles[6] amount = difference/2 obj.move_handle(handleTop, (handleTop.pos.x, handleTop.pos.y - amount), 0, 0) obj.move_handle(handleBottom, (handleBottom.pos.x, handleBottom.pos.y + amount), 0, 0) obj.move(pos.x, pos.y) def toFloat(self, valor): return locale.atof(valor) def clickAplicar(self, *args): optWidth = self.getSelectedGroupOption(self.widthOptions) optHeight = self.getSelectedGroupOption(self.heightOptions) try: if optWidth[0] != 'ignore': width = self.getValue(optWidth[0], optWidth[1], 'elem_width') self.adjustWidth(width) if optHeight[0] != 'ignore': height = self.getValue(optHeight[0], optHeight[1], 'elem_height') self.adjustHeight(height) if dia.active_display(): diagram = dia.active_display().diagram for obj in self.group: diagram.update_connections(obj) except Exception,e: dia.message(gtk.MESSAGE_ERROR, repr(e)) if dia.active_display(): dia.active_display().add_update_all() dia.active_display().flush() def show(self): self.dlg.show() def hide(self, *args): self.dlg.hide() def run(self): return self.dlg.run() def dia_group_resize_db (data,flags): diagram = dia.active_display().diagram group = diagram.get_sorted_selected() if len(group) > 0: win = ResizeWindow(group, data) win.show() else: dia.message(gtk.MESSAGE_INFO, "Please select a group of objects") dia.register_action("ObjectGroupResize", "Group Resize", "/DisplayMenu/Objects/ObjectsExtensionStart", dia_group_resize_db) <|fim▁end|>
return min(values)