def _parse_dest_path(self, path_str): if "$TV_TEMP" in path_str: tv_temp_path = Path(ConfigurationManager().path("misc")) / "tv_temp" return Path(path_str.replace("$TV_TEMP", str(tv_temp_path))) if "$TV" in path_str: return Path(path_str.replace("$TV", str(ConfigurationManager().path("tv")))) return Path(path_str)
def _connect(self): if self._ssh.connected: self.log("already connected") _user = ConfigurationManager().get(SettingKeys.WB_USERNAME, section=SettingSection.WB) _pw = ConfigurationManager().get(SettingKeys.WB_PASSWORD, section=SettingSection.WB) self._ssh.connect(self._hostname, username=_user, password=_pw)
def get_bridge() -> [Bridge, None]: key = ConfigurationManager().get("hue_api_key", default=None) hue_ip = ConfigurationManager().get("hue_ip", default=None) if not hue_ip: print("cannot load hue_ip from settings, aborting") return None if not key: print("cannot load hue_api_key from settings, aborting") return None return Bridge(hue_ip, key)
class StarryPyServerFactory(ServerFactory): """ Factory which creates `StarryPyServerProtocol` instances. """ protocol = StarryPyServerProtocol def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} self.plugin_manager = PluginManager() self.plugin_manager.activate_plugins() def stopFactory(self): """ Called when the factory is stopped. Saves the configuration. :return: None """ self.config.save() def broadcast(self, text, channel=1, world='', name=''): """ Convenience method to send a broadcasted message to all clients on the server. :param text: Message text :param channel: Channel to broadcast on. 0 is global, 1 is planet. :param world: World :param name: The name to prepend before the message, format is <name> :return: None """ for p in self.protocols.itervalues(): try: p.send_chat_message(text) except: logger.exception("Exception in broadcast.", exc_info=True) def buildProtocol(self, address): """ Builds the protocol to a given address. :rtype : Protocol """ logger.debug("Building protocol to address %s", address) p = ServerFactory.buildProtocol(self, address) return p
def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} try: self.plugin_manager = PluginManager(factory=self) except FatalPluginError: logger.critical("Shutting Down.") sys.exit() self.reaper = LoopingCall(self.reap_dead_protocols) self.reaper.start(self.config.reap_time)
def write_to_log(entry: DownloadedShowLogEntry): path = Path(ConfigurationManager().path("ripper_log")) if not path.exists() or not path.is_file(): print(f"warning: could not write to log: {str(path)}") return with open(path, "a+") as log_file: log_file.write(f"{entry.timestamp} : {entry.show_name} {str(entry.file_path)}\n")
def get_cli_args(): parser = argparse.ArgumentParser() parser.add_argument("--simulate", action="store_true") parser.add_argument("--verbose", action="store_true") parser.add_argument("--force", "-f", dest="force_download", action="store_true", help="force check/download all shows") parser.add_argument("--set-all-downloaded", "-s", dest="set_all_dl", action="store_true", help="sets all shows as downloaded today") parser.add_argument("--web", dest="use_fast_api", action="store_true") parser.add_argument("--jsonfile", dest="json_file", type=Path, default=ConfigurationManager().path("ripper_schedule")) args = parser.parse_args() return args
def __init__(self, verbose=False): BaseLog.__init__(self, verbose=verbose) self.set_log_prefix("OMDb") self._api_key = ConfigurationManager().get("omdb_api_key", default=None) self._url_args = {"apikey": self._api_key, "type": "movie"} self.log("init")
class DmenuConfig: """ Set/Get colors for dmenu""" case_insensitive: bool = True color_selected_foreground: str = "white" color_selected_background: str = "#042C44" color_bar_background: str = "black" font: str = "Monospace-{}:normal".format(ConfigurationManager().get( "dmenu_font_size", default=10)) lines: int = 40
def _setup_discovery(self): file_path = ConfigurationManager().path("cookies_txt") if not Path(file_path).exists(): file_path = Path(__file__).resolve().parent / "cookies.txt" if not Path(file_path).exists(): self.log(fcs("e[error]: could not load cookies for discoveryplus")) else: self.log(fcs("loading o[cookie.txt] for discoveryplus")) self.options["cookiefile"] = str(file_path)
def main(): CM = ConfigurationManager() configs = CM.build_configs() mode = configs["mode"] agent_name = configs["agent"] agent = getattr(agents, agent_name)(configs) try: if mode == "play": agent.run() elif mode == "learn": agent.train() else: raise AttributeError except(AttributeError): raise ConfigurationError("Error trying the mode '{}' on the agent '{}': possibly not implemented.".format(mode, agent_name))
def main(): args = get_args() handler = ServerHandler() for _key in [SettingKeys.WB_SERVER_1, SettingKeys.WB_SERVER_2]: _hostname = ConfigurationManager().get(key=_key, section=SettingSection.WB) if _hostname: handler.add(_hostname) else: print(f"could not get hostname (key {_key.value}) from settings") if not handler.valid(): print("could not connect to server(s)") return if not args.download_items or args.list_items: handler.print_file_list() elif args.download_items: _dl_dir = ConfigurationManager().path("download", convert_to_path=True, assert_path_exists=True) _keys = parse_download_arg(args.download_items) for _key in _keys: handler.download(_key, _dl_dir)
def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} self.plugin_manager = PluginManager() self.plugin_manager.activate_plugins()
def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} self.plugin_manager = PluginManager(factory=self) try: self.plugin_manager.prepare() except FatalPluginError: logger.critical('Shutting Down.') sys.exit() self.reaper = LoopingCall(self.reap_dead_protocols) self.reaper.start(self.config.reap_time) logger.debug( 'Factory created, endpoint of port %d', self.config.bind_port )
def __new__(self): print(self._instance) if not self._instance: self._instance = super(MQService, self).__new__(self) self.unitSettings = cfm.ConfigurationManager().getUnitConfig() self._webrequests_service = wrs.WebRequestsService() self._mq_settings = cfm.ConfigurationManager().getMQTTConfig() self._auth = self._mq_settings.get("authb64") self._clientId = self.unitSettings["Name"] print("Init MQService " + str(self._instance)) self._authHeader = { "Authorization": "Basic " + self._auth, "Content-Type": "application/x-www-form-urlencoded" } self._server = "http://" + self._mq_settings[ "server"] + ":8161/api/message/" return self._instance
def __init__(self): JSONDatabase.__init__(self, ConfigurationManager().path("movdb", assert_path_exists=True)) self.set_valid_keys( ["folder", "title", "year", "imdb", "scanned", "removed", "removed_date"]) self.set_key_type("folder", str) self.set_key_type("title", str) self.set_key_type("year", int) self.set_key_type("imdb", str) self.set_key_type("scanned", int) # unix timestamp self.set_key_type("removed", bool) self.set_key_type("removed_date", int)
def load_from_log(): try: path = Path(ConfigurationManager().path("ripper_log")) except TypeError as _: return [] except AttributeError as _: return [] if path is None or not path.exists(): return [] with open(path, "r") as log_file: return [DownloadedShowLogEntry.from_log_txt_line(x) for x in log_file.readlines()]
def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} self.plugin_manager = PluginManager(factory=self) self.plugin_manager.activate_plugins() self.reaper = LoopingCall(self.reap_dead_protocols) self.reaper.start(self.config.reap_time)
def run_replace_list_on_query(query_string): replace_file_path = Path( ConfigurationManager().path("scripts")) / "pre_replace.json" with open(replace_file_path) as replace_fp: _list = json.load(replace_fp) if not _list: return query_string for string, replacement in _list.items(): if "^" in string: query_string = re.sub(string, replacement, query_string) else: query_string = query_string.replace(string, replacement) return query_string
def __new__(self): print(self._instance) if not self._instance: self._instance = super(WifiManager, self).__new__(self) self.wifiSettings = cm.ConfigurationManager().getWifiConfig() self._SSID = self.wifiSettings["ssid"] self._password = self.wifiSettings["password"] self.wlan_intf = network.WLAN(network.STA_IF) self.wlan_intf.active(True) self._isConnected = False self._isConnecting = False print("init NetworkManager " + str(self._instance)) return self._instance
def __new__(self): print(self._instance) if not self._instance: self._instance = super(MQTTManager, self).__new__(self) self.mqttSettings = cm.ConfigurationManager().getMQTTConfig() self.unitSettings = cm.ConfigurationManager().getUnitConfig() self._server = self.mqttSettings["server"] self._username = self.mqttSettings["username"] self._password = self.mqttSettings["password"] self._default_topic = self.mqttSettings["defaultTopic"] self._clientId = self.unitSettings["Name"] self._port = self.mqttSettings["port"] self._socket_timeout = self.mqttSettings["timeout"] self._mq_connection = mq.MQTTClient(client_id=self._clientId, server=self._server, port=self._port, user=self._username, password=self._password) print("Init MQTTManager " + str(self._instance)) return self._instance
def export_latest_added(self): _path = ConfigurationManager().path("film", convert_to_path=True, assert_path_exists=True) if _path is None: print(cstr("could not retrieve path to \"film\"", Color.Error)) return _path = _path / "latest.txt" last_added = self.last_added(num=1000) last_added_text = [_to_text(m, last_added[m]) for m in last_added] try: with open(_path, "w") as _fp: _fp.writelines(last_added_text) print(f"wrote to {cstr(str(_path), Color.LightGreen)}") except Exception as _: print(cstr("could not save latest.txt", Color.Error))
def load_cookies_txt(self, file_path=None): self.init_session() if not file_path: file_path = ConfigurationManager().path("cookies_txt") if not Path(file_path).exists(): file_path = Path(__file__).resolve().parent / "cookies.txt" if not Path(file_path).exists(): pfcs("e[error]: could not find cookies.txt!") return # NOTE use: https://addons.mozilla.org/en-US/firefox/addon/export-cookies-txt/ try: jar = MozillaCookieJar(file_path) jar.load(ignore_discard=True, ignore_expires=True) self.SESSION.cookies.update(jar) except LoadError as error: pfcs(f"w[warning] could not load cookies.txt:\n{error}")
def __init__(self, cfg_path): logging.basicConfig(format="%{asctime}s - [%(levelname)s]: %(message)s") self._cfg_man = ConfigurationManager(cfg_path) atexit.register(self._cfg_man.save_configuration) self._is_hat = self._cfg_man.configuration.display_type == 'dothat' if self._is_hat: import dothat.backlight as backlight import dothat.lcd as lcd self._lcd = lcd self._backlight = backlight else: import dot3k.backlight as backlight import dot3k.lcd as lcd self._lcd = lcd self._backlight = backlight
def __init__(self, factory, base_class=BasePlugin): """ Initializes the plugin manager. When called, with will first attempt to get the `ConfigurationManager` singleton and extract the core plugin path. After loading the core plugins with `self.load_plugins` it will do the same for plugins that may or may not have dependencies. :param base_class: The base class to use while searching for plugins. """ self.plugins = {} self.config = ConfigurationManager() self.base_class = base_class self.factory = factory self.load_order = [] #self.plugin_dir = os.path.realpath(self.config.plugin_path) self.plugin_dir = path.child(self.config.plugin_path) sys.path.append(self.plugin_dir.path) self.load_plugins(self.plugin_dir) self.logger.info("Loaded plugins:\n%s" % "\n".join( ["%s, Active: %s" % (plugin.name, plugin.active) for plugin in self.plugins.itervalues()]))
def __init__(self, factory, base_class=BasePlugin): """ Initializes the plugin manager. When called, with will first attempt to get the `ConfigurationManager` singleton and extract the core plugin path. After loading the core plugins with `self.load_plugins` it will do the same for plugins that may or may not have dependencies. :param base_class: The base class to use while searching for plugins. """ self.packets = {} self.plugins = {} self.plugin_classes = {} self.plugins_waiting_to_load = {} self.load_order = [] self.config = ConfigurationManager() self.base_class = base_class self.factory = factory self.plugin_dir = path.child(self.config.plugin_path) sys.path.append(self.plugin_dir.path)
class SensorService: _instance = None _sensorSettings = cfm.ConfigurationManager().getSensorConfig() _print_text = disp.DisplaySingleService().print_text _clear_text = disp.DisplaySingleService().clear def __new__(self): print(self._instance) if not self._instance: self._instance = super(SensorService, self).__new__(self) print("Init SensorService " + str(self._instance)) return self._instance def collectSensorData(self): print("Collecting Data...") data_dict = [] for sensor in _sensorSettings["sensors"]: s_type = sensor["type"] if s_type is "DHT11" or "DHT22": res = dht.DHTSensors().getValues(sensor) data_dict[s[name]] = res
def change(newname): ConfigurationManager.save('prefix', '/opt/' + newname)
class StarryPyServerFactory(ServerFactory): """ Factory which creates `StarryPyServerProtocol` instances. """ protocol = StarryPyServerProtocol def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} self.plugin_manager = PluginManager(factory=self) try: self.plugin_manager.prepare() except FatalPluginError: logger.critical('Shutting Down.') sys.exit() self.reaper = LoopingCall(self.reap_dead_protocols) self.reaper.start(self.config.reap_time) logger.debug( 'Factory created, endpoint of port %d', self.config.bind_port ) def stopFactory(self): """ Called when the factory is stopped. Saves the configuration. :return: None """ self.config.save() self.plugin_manager.die() def broadcast(self, text, name=''): """ Convenience method to send a broadcasted message to all clients on the server. :param text: Message text :param name: The name to prepend before the message, format is <name> :return: None """ for p in self.protocols.itervalues(): try: p.send_chat_message(text) except: logger.exception('Exception in broadcast.') def broadcast_planet(self, text, planet, name=''): """ Convenience method to send a broadcasted message to all clients on the current planet (and ships orbiting it). :param text: Message text :param planet: The planet to send the message to :param name: The name to prepend before the message, format is <name>, not prepended when empty :return: None """ for p in self.protocols.itervalues(): if p.player.planet == planet: try: p.send_chat_message(text) except: logger.exception('Exception in broadcast.') def buildProtocol(self, address): """ Builds the protocol to a given address. :rtype : Protocol """ logger.vdebug('Building protocol to address %s', address) p = ServerFactory.buildProtocol(self, address) return p def reap_dead_protocols(self): logger.vdebug('Reaping dead connections.') count = 0 start_time = datetime.datetime.now() for protocol in self.protocols.itervalues(): total_seconds = ( protocol .client_protocol .packet_stream .last_received_timestamp - start_time ).total_seconds() if total_seconds > self.config.reap_time: logger.debug( 'Reaping protocol %s. Reason: Server protocol timeout.', protocol.id ) protocol.connectionLost() count += 1 continue if ( protocol.client_protocol is not None and total_seconds > self.config.reap_time ): protocol.connectionLost() logger.debug( 'Reaping protocol %s. Reason: Client protocol timeout.', protocol.id ) count += 1 if count == 1: logger.info('1 connection reaped.') elif count > 1: logger.info('%d connections reaped.') else: logger.vdebug('No connections reaped.')
def __init__(self): """ """ self.id = str(uuid4().hex) logger.vdebug("Creating protocol with ID %s.", self.id) self.factory.protocols[self.id] = self self.player = None self.state = None logger.debug("Trying to initialize configuration manager.") self.config = ConfigurationManager() self.parsing = False self.buffering_packet = None self.after_write_callback = None self.plugin_manager = None self.call_mapping = { packets.Packets.PROTOCOL_VERSION: self.protocol_version, # 0 packets.Packets.SERVER_DISCONNECT: self.server_disconnect, # 1 packets.Packets.CONNECT_RESPONSE: self.connect_response, # 2 packets.Packets.HANDSHAKE_CHALLENGE: self.handshake_challenge, #3 packets.Packets.CHAT_RECEIVED: self.chat_received, # 4 packets.Packets.UNIVERSE_TIME_UPDATE: self.universe_time_update, # 5 packets.Packets.CELESTIAL_RESPONSE: lambda x: True, # 6 packets.Packets.CLIENT_CONNECT: self.client_connect, # 7 packets.Packets.CLIENT_DISCONNECT_REQUEST: self.client_disconnect_request, # 8 packets.Packets.HANDSHAKE_RESPONSE: self.handshake_response, # 9 packets.Packets.PLAYER_WARP: self.player_warp, # 10 packets.Packets.FLY_SHIP: self.fly_ship, # 11 packets.Packets.CHAT_SENT: self.chat_sent, # 12 packets.Packets.CELESTIAL_REQUEST: self.celestial_request, # 13 packets.Packets.CLIENT_CONTEXT_UPDATE: self.client_context_update, # 14 packets.Packets.WORLD_START: self.world_start, # 15 packets.Packets.WORLD_STOP: self.world_stop, # 16 packets.Packets.CENTRAL_STRUCTURE_UPDATE: self.central_structure_update, # 17 packets.Packets.TILE_ARRAY_UPDATE: self.tile_array_update, # 18 packets.Packets.TILE_UPDATE: self.tile_update, # 19 packets.Packets.TILE_LIQUID_UPDATE: self.tile_liquid_update, # 20 packets.Packets.TILE_DAMAGE_UPDATE: self.tile_damage_update, # 21 packets.Packets.TILE_MODIFICATION_FAILURE: self.tile_modification_failure, #22 packets.Packets.GIVE_ITEM: self.give_item, # 23 packets.Packets.SWAP_IN_CONTAINER_RESULT: self.swap_in_container_result, # 24 packets.Packets.ENVIRONMENT_UPDATE: self.environment_update, # 25 packets.Packets.ENTITY_INTERACT_RESULT: self.entity_interact_result, # 26 packets.Packets.UPDATE_TILE_PROTECTION: lambda x: True, # 27 packets.Packets.MODIFY_TILE_LIST: self.modify_tile_list, # 28 packets.Packets.DAMAGE_TILE_GROUP: self.damage_tile_group, # 29 packets.Packets.COLLECT_LIQUID: self.collect_liquid, # 30 packets.Packets.REQUEST_DROP: self.request_drop, # 31 packets.Packets.SPAWN_ENTITY: self.spawn_entity, # 32 packets.Packets.ENTITY_INTERACT: self.entity_interact, # 33 packets.Packets.CONNECT_WIRE: self.connect_wire, # 34 packets.Packets.DISCONNECT_ALL_WIRES: self.disconnect_all_wires, # 35 packets.Packets.OPEN_CONTAINER: self.open_container, # 36 packets.Packets.CLOSE_CONTAINER: self.close_container, # 37 packets.Packets.SWAP_IN_CONTAINER: self.swap_in_container, # 38 packets.Packets.ITEM_APPLY_IN_CONTAINER: self.item_apply_in_container, # 39 packets.Packets.START_CRAFTING_IN_CONTAINER: self.start_crafting_in_container, # 40 packets.Packets.STOP_CRAFTING_IN_CONTAINER: self.stop_crafting_in_container, # 41 packets.Packets.BURN_CONTAINER: self.burn_container, # 42 packets.Packets.CLEAR_CONTAINER: self.clear_container, # 43 packets.Packets.WORLD_CLIENT_STATE_UPDATE: self.world_client_state_update, # 44 packets.Packets.ENTITY_CREATE: self.entity_create, # 45 packets.Packets.ENTITY_UPDATE: self.entity_update, # 46 packets.Packets.ENTITY_DESTROY: self.entity_destroy, # 47 packets.Packets.HIT_REQUEST: self.hit_request, # 48 packets.Packets.DAMAGE_REQUEST: lambda x: True, # 49 packets.Packets.DAMAGE_NOTIFICATION: self.damage_notification, # 50 packets.Packets.CALL_SCRIPTED_ENTITY: lambda x: True, # 51 packets.Packets.UPDATE_WORLD_PROPERTIES: self.update_world_properties, # 52 packets.Packets.HEARTBEAT: self.heartbeat, # 53 } self.client_protocol = None self.packet_stream = PacketStream(self) self.packet_stream.direction = packets.Direction.CLIENT self.plugin_manager = self.factory.plugin_manager
#!/usr/bin/python import sys from config import ConfigurationManager from mode import Modes if __name__ == '__main__': print 'Hello!' print 'This is loggy :)' print 'Loading configuration...' configManager = ConfigurationManager() configManager.load() config = configManager.get() print 'Done' print "You are following: %s" % config.filename mode = Modes.PRINT_MODE while True: try: mode = mode.execute() except KeyboardInterrupt: mode.handle_keyboard_interrupt() except Exception, ex: print 'Something has gone wrong...' print ex sys.exit(1)
#!/usr/bin/env python3.6 ''' Various tv show/episode helper/utility functions ''' import os import re from config import ConfigurationManager from cache import TvCache import util from pathlib import Path CFG = ConfigurationManager() SHOW_DIR = CFG.get('path_tv') def parse_year(string): re_year = re.compile(r'(19|20)\d{2}') year = re_year.search(string) if year: return year.group() return None def list_all_shows() -> list: '''Returns a list of all current tv show folders''' return [show for show in os.listdir(SHOW_DIR) if os.path.isdir(os.path.join(SHOW_DIR, show))] def list_all_episodes(use_cache=True):
class StarryPyServerFactory(ServerFactory): """ Factory which creates `StarryPyServerProtocol` instances. """ protocol = StarryPyServerProtocol def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} try: self.plugin_manager = PluginManager(factory=self) except FatalPluginError: logger.critical("Shutting Down.") sys.exit() self.reaper = LoopingCall(self.reap_dead_protocols) self.reaper.start(self.config.reap_time) def stopFactory(self): """ Called when the factory is stopped. Saves the configuration. :return: None """ self.config.save() self.plugin_manager.die() def broadcast(self, text, channel=1, world='', name=''): """ Convenience method to send a broadcasted message to all clients on the server. :param text: Message text :param channel: Channel to broadcast on. 0 is global, 1 is planet. :param world: World :param name: The name to prepend before the message, format is <name> :return: None """ for p in self.protocols.itervalues(): try: p.send_chat_message(text) except: logger.exception("Exception in broadcast.") def broadcast_planet(self, text, planet, name=''): """ Convenience method to send a broadcasted message to all clients on the current planet (and ships orbiting it). :param text: Message text :param planet: The planet to send the message to :param name: The name to prepend before the message, format is <name>, not prepanded when empty :return: None """ for p in self.protocols.itervalues(): if p.player.planet == planet: try: p.send_chat_message(text) except: logger.exception("Exception in broadcast.") def buildProtocol(self, address): """ Builds the protocol to a given address. :rtype : Protocol """ p = ServerFactory.buildProtocol(self, address) return p def reap_dead_protocols(self): count = 0 start_time = datetime.datetime.now() for protocol in self.protocols.itervalues(): if ( protocol.packet_stream.last_received_timestamp - start_time).total_seconds() > self.config.reap_time: protocol.connectionLost() count += 1 continue if protocol.client_protocol is not None and ( protocol.client_protocol.packet_stream.last_received_timestamp - start_time).total_seconds() > self.config.reap_time: protocol.connectionLost() count += 1 if count == 1: logger.info("1 connection reaped.") elif count > 1: logger.info("%d connections reaped.")
def print(): return ConfigurationManager.get('prefix', '/opt/ports')
class StarryPyServerFactory(ServerFactory): """ Factory which creates `StarryPyServerProtocol` instances. """ protocol = StarryPyServerProtocol def __init__(self): """ Initializes persistent objects and prepares a list of connected protocols. """ self.config = ConfigurationManager() self.protocol.factory = self self.protocols = {} try: self.plugin_manager = PluginManager(factory=self) except FatalPluginError: logger.critical("Shutting Down.") sys.exit() self.reaper = LoopingCall(self.reap_dead_protocols) self.reaper.start(self.config.reap_time) def stopFactory(self): """ Called when the factory is stopped. Saves the configuration. :return: None """ self.config.save() self.plugin_manager.die() def broadcast(self, text, channel=1, world='', name=''): """ Convenience method to send a broadcasted message to all clients on the server. :param text: Message text :param channel: Channel to broadcast on. 0 is global, 1 is planet. :param world: World :param name: The name to prepend before the message, format is <name> :return: None """ for p in self.protocols.itervalues(): try: p.send_chat_message(text) except: logger.exception("Exception in broadcast.") def broadcast_planet(self, text, planet, name=''): """ Convenience method to send a broadcasted message to all clients on the current planet (and ships orbiting it). :param text: Message text :param planet: The planet to send the message to :param name: The name to prepend before the message, format is <name>, not prepanded when empty :return: None """ for p in self.protocols.itervalues(): if p.player.planet == planet: try: p.send_chat_message(text) except: logger.exception("Exception in broadcast.") def buildProtocol(self, address): """ Builds the protocol to a given address. :rtype : Protocol """ p = ServerFactory.buildProtocol(self, address) return p def reap_dead_protocols(self): count = 0 start_time = datetime.datetime.now() for protocol in self.protocols.itervalues(): if (protocol.packet_stream.last_received_timestamp - start_time).total_seconds() > self.config.reap_time: protocol.connectionLost() count += 1 continue if protocol.client_protocol is not None and ( protocol.client_protocol.packet_stream. last_received_timestamp - start_time).total_seconds() > self.config.reap_time: protocol.connectionLost() count += 1 if count == 1: logger.info("1 connection reaped.") elif count > 1: logger.info("%d connections reaped.")
def __init__(self): """ """ self.id = str(uuid4().hex) self.factory.protocols[self.id] = self self.player = None self.state = None self.config = ConfigurationManager() self.parsing = False self.buffering_packet = None self.after_write_callback = None self.plugin_manager = None self.call_mapping = { packets.Packets.PROTOCOL_VERSION: self.protocol_version, packets.Packets.CONNECT_RESPONSE: self.connect_response, packets.Packets.SERVER_DISCONNECT: self.server_disconnect, packets.Packets.HANDSHAKE_CHALLENGE: self.handshake_challenge, packets.Packets.CHAT_RECEIVED: self.chat_received, packets.Packets.UNIVERSE_TIME_UPDATE: self.universe_time_update, packets.Packets.CLIENT_CONNECT: self.client_connect, packets.Packets.CLIENT_DISCONNECT: self.client_disconnect, packets.Packets.HANDSHAKE_RESPONSE: self.handshake_response, packets.Packets.WARP_COMMAND: self.warp_command, packets.Packets.CHAT_SENT: self.chat_sent, packets.Packets.CLIENT_CONTEXT_UPDATE: self.client_context_update, packets.Packets.WORLD_START: self.world_start, packets.Packets.WORLD_STOP: self.world_stop, packets.Packets.TILE_ARRAY_UPDATE: self.tile_array_update, packets.Packets.TILE_UPDATE: self.tile_update, packets.Packets.CELESTIALRESPONSE: lambda x: True, packets.Packets.CELESTIALREQUEST: lambda x: True, packets.Packets.TILE_LIQUID_UPDATE: self.tile_liquid_update, packets.Packets.TILE_DAMAGE_UPDATE: self.tile_damage_update, packets.Packets.TILE_MODIFICATION_FAILURE: self.tile_modification_failure, packets.Packets.GIVE_ITEM: self.item, packets.Packets.SWAP_IN_CONTAINER_RESULT: self.swap_in_container_result, packets.Packets.ENVIRONMENT_UPDATE: self.environment_update, packets.Packets.ENTITY_INTERACT_RESULT: self.entity_interact_result, packets.Packets.MODIFY_TILE_LIST: self.modify_tile_list, packets.Packets.DAMAGE_TILE: self.damage_tile, packets.Packets.DAMAGE_TILE_GROUP: self.damage_tile_group, packets.Packets.REQUEST_DROP: self.request_drop, packets.Packets.SPAWN_ENTITY: self.spawn_entity, packets.Packets.ENTITY_INTERACT: self.entity_interact, packets.Packets.CONNECT_WIRE: self.connect_wire, packets.Packets.DISCONNECT_ALL_WIRES: self.disconnect_all_wires, packets.Packets.OPEN_CONTAINER: self.open_container, packets.Packets.CLOSE_CONTAINER: self.close_container, packets.Packets.SWAP_IN_CONTAINER: self.swap_in_container, packets.Packets.ITEM_APPLY_IN_CONTAINER: self.item_apply_in_container, packets.Packets.START_CRAFTING_IN_CONTAINER: self.start_crafting_in_container, packets.Packets.STOP_CRAFTING_IN_CONTAINER: self.stop_crafting_in_container, packets.Packets.BURN_CONTAINER: self.burn_container, packets.Packets.CLEAR_CONTAINER: self.clear_container, packets.Packets.WORLD_UPDATE: self.world_update, packets.Packets.ENTITY_CREATE: self.entity_create, packets.Packets.ENTITY_UPDATE: self.entity_update, packets.Packets.ENTITY_DESTROY: self.entity_destroy, packets.Packets.DAMAGE_NOTIFICATION: self.damage_notification, packets.Packets.STATUS_EFFECT_REQUEST: self.status_effect_request, packets.Packets.UPDATE_WORLD_PROPERTIES: self.update_world_properties, packets.Packets.HEARTBEAT: self.heartbeat, } self.client_protocol = None self.packet_stream = PacketStream(self) self.packet_stream.direction = packets.Direction.CLIENT self.plugin_manager = self.factory.plugin_manager
trans = gettext.NullTranslations() trans.install() if __name__ == '__main__': init_localization() logger = logging.getLogger('starrypy') logger.setLevel(9) fh_w = logging.FileHandler("server.log") fh_w.setLevel(logging.INFO) sh = logging.StreamHandler(sys.stdout) sh.setLevel(logging.INFO) logger.addHandler(sh) logger.addHandler(fh_w) config = ConfigurationManager() console_formatter = logging.Formatter(config.logging_format_console) logfile_formatter = logging.Formatter(config.logging_format_logfile) fh_w.setFormatter(logfile_formatter) sh.setFormatter(console_formatter) if config.port_check: if not port_check(config.upstream_hostname, config.upstream_port): logger.critical( "The starbound server is not connectable at the address %s:%d." % (config.upstream_hostname, config.upstream_port)) logger.critical( "Please ensure that you are running starbound_server on the correct port and that is reflected in the StarryPy configuration." ) sys.exit()