def main(): def try_int(s, base=10, val=None): if s is None: return None try: return int(s, base) except ValueError: return val class Config(object): debug = False ip = '0.0.0.0' port = 6687 db_path = 'monitorrent.db' config = 'config.py' def __init__(self, parsed_args): if parsed_args.config is not None and not os.path.isfile(parsed_args.config): warnings.warn('File not found: {}'.format(parsed_args.config)) config_path = parsed_args.config or self.config if os.path.isfile(config_path): # noinspection PyBroadException try: parsed_config = {} with open(config_path) as config_file: six.exec_(compile(config_file.read(), config_path, 'exec'), {}, parsed_config) self.debug = parsed_config.get('debug', self.debug) self.ip = parsed_config.get('ip', self.ip) self.port = parsed_config.get('port', self.port) self.db_path = parsed_config.get('db_path', self.db_path) except: ex, val, tb = sys.exc_info() warnings.warn('Error reading: {0}: {1} ({2}'.format(parsed_args.config, ex, val)) env_debug = (os.environ.get('MONITORRENT_DEBUG', None) in ['true', 'True', '1']) self.debug = parsed_args.debug or env_debug or self.debug self.ip = parsed_args.ip or os.environ.get('MONITORRENT_IP', None) or self.ip self.port = parsed_args.port or try_int(os.environ.get('MONITORRENT_PORT', None)) or self.port self.db_path = parsed_args.db_path or os.environ.get('MONITORRENT_DB_PATH', None) or self.db_path parser = argparse.ArgumentParser(description='Monitorrent server') parser.add_argument('--debug', action='store_true', help='Run in debug mode. Secret key is always the same.') parser.add_argument('--ip', type=str, dest='ip', help='Bind interface. Default is {0}'.format(Config.ip)) parser.add_argument('--port', type=int, dest='port', help='Port for server. Default is {0}'.format(Config.port)) parser.add_argument('--db-path', type=str, dest='db_path', help='Path to SQL lite database. Default is to {0}'.format(Config.db_path)) parser.add_argument('--config', type=str, dest='config', default=os.environ.get('MONITORRENT_CONFIG', None), help='Path to config file (default {0})'.format(Config.config)) parsed_args = parser.parse_args() config = Config(parsed_args) db_connection_string = "sqlite:///" + config.db_path init_db_engine(db_connection_string, False) load_plugins() upgrade() create_db() settings_manager = SettingsManager() tracker_manager = TrackersManager(settings_manager.tracker_settings, get_plugins('tracker')) clients_manager = DbClientsManager(get_plugins('client'), settings_manager) notifier_manager = NotifierManager(get_plugins('notifier')) log_manager = ExecuteLogManager() engine_runner_logger = DbLoggerWrapper(None, log_manager, settings_manager) engine_runner = DBEngineRunner(engine_runner_logger, tracker_manager, clients_manager) debug = config.debug if debug: secret_key = 'Secret!' token = 'monitorrent' else: secret_key = os.urandom(24) token = ''.join(random.choice(string.ascii_letters) for _ in range(8)) app = create_app(secret_key, token, tracker_manager, clients_manager, notifier_manager, settings_manager, engine_runner, log_manager) d = wsgiserver.WSGIPathInfoDispatcher({'/': app}) server_start_params = (config.ip, config.port) server = wsgiserver.CherryPyWSGIServer(server_start_params, d) print('Server started on {0}:{1}'.format(*server_start_params)) try: server.start() except KeyboardInterrupt: engine_runner.stop() server.stop()
def _get_settings_manager(password): settings_manager = SettingsManager() settings_manager.get_password = MagicMock(return_value=password) settings_manager.set_password = MagicMock() return settings_manager
def setUp(self): super(SettingsManagerTest, self).setUp() self.settings_manager = SettingsManager()
def upgrade_3_to_4(engine, operations_factory): # Version 3 m3 = MetaData() lostfilm_series_3 = Table('lostfilmtv_series', m3, Column("id", Integer, ForeignKey('topics.id'), primary_key=True), Column("search_name", String, nullable=False), Column("season", Integer, nullable=True), Column("episode", Integer, nullable=True), Column("quality", String, nullable=False)) lostfilm_credentials_3 = Table("lostfilmtv_credentials", m3, Column('username', String, primary_key=True), Column('password', String, primary_key=True), Column('uid', String), Column('pass', String), Column('usess', String), Column('default_quality', String, nullable=False, server_default='SD')) # Version 4 m4 = MetaData(engine) topic_last = Table('topics', m4, *[c.copy() for c in Topic.__table__.columns]) lostfilm_series_4 = Table('lostfilmtv_series4', m4, Column("id", Integer, ForeignKey('topics.id'), primary_key=True), Column("cat", Integer, nullable=False), Column("season", Integer, nullable=True), Column("episode", Integer, nullable=True), Column("quality", String, nullable=False)) lostfilm_credentials_4 = Table("lostfilmtv_credentials4", m4, Column('username', String, primary_key=True), Column('password', String, primary_key=True), Column('session', String), Column('default_quality', String, nullable=False, server_default='SD')) cat_re = re.compile(six.text_type(r'https?://(www|old)\.lostfilm\.tv/browse\.php\?cat=_?(?P<cat>\d+)'), re.UNICODE) from monitorrent.settings_manager import SettingsManager settings_manager = SettingsManager() tracker_settings = None with operations_factory() as operations: # if previuos run fails, it can not delete this table if operations.has_table(lostfilm_series_4.name): operations.drop_table(lostfilm_series_4.name) operations.create_table(lostfilm_series_4) lostfilm_topics = operations.db.query(lostfilm_series_3) topics = operations.db.query(topic_last) topics = [row2dict(t, topic_last) for t in topics] topics = {t['id']: t for t in topics} for topic in lostfilm_topics: raw_lostfilm_topic = row2dict(topic, lostfilm_series_3) raw_topic = topics[raw_lostfilm_topic['id']] match = cat_re.match(raw_topic['url']) topic_values = {} if not match: print("can't parse old url: {0}".format(raw_topic['url'])) raw_lostfilm_topic['cat'] = 0 topic_values['status'] = Status.Error else: cat = int(match.group('cat')) raw_lostfilm_topic['cat'] = cat try: if tracker_settings is None: tracker_settings = settings_manager.tracker_settings old_url = 'https://www.lostfilm.tv/browse.php?cat={0}'.format(cat) url_response = requests.get(old_url, **tracker_settings.get_requests_kwargs()) soup = get_soup(url_response.text) meta_content = soup.find('meta').attrs['content'] redirect_url = meta_content.split(';')[1].strip()[4:] if redirect_url.startswith('/'): redirect_url = redirect_url[1:] redirect_url = u'http://www.lostfilm.tv/{0}'.format(redirect_url) url = LostFilmShow.get_seasons_url(redirect_url) if url is None: raise Exception("Can't parse url from {0} it was redirected to {1}" .format(old_url, redirect_url)) topic_values['url'] = url except: exc_info = sys.exc_info() print(u''.join(traceback.format_exception(*exc_info))) topic_values['status'] = Status.Error operations.db.execute(lostfilm_series_4.insert(), raw_lostfilm_topic) operations.db.execute(topic_last.update(whereclause=(topic_last.c.id == raw_topic['id']), values=topic_values)) # drop original table operations.drop_table(lostfilm_series_3.name) # rename new created table to old one operations.rename_table(lostfilm_series_4.name, lostfilm_series_3.name) # if previuos run fails, it can not delete this table if operations.has_table(lostfilm_credentials_4.name): operations.drop_table(lostfilm_credentials_4.name) operations.create_table(lostfilm_credentials_4) credentials = list(operations.db.query(lostfilm_credentials_3)) for credential in credentials: raw_credential = row2dict(credential, lostfilm_credentials_3) operations.db.execute(lostfilm_credentials_4.insert(), raw_credential) # drop original table operations.drop_table(lostfilm_credentials_3.name) # rename new created table to old one operations.rename_table(lostfilm_credentials_4.name, lostfilm_credentials_3.name)