def test_is_new_version_checker_enabled(self, include_prerelease, enabled, interval):
        with patch('monitorrent.settings_manager.SettingsManager.new_version_check_interval',
                   new_callable=PropertyMock) as new_version_check_interval_mock:
            new_version_check_interval_mock.return_value = interval

            settings_manager = SettingsManager()
            get_is_new_version_checker_enabled_mock = Mock(return_value=enabled)
            get_new_version_check_include_prerelease_mock = Mock(return_value=include_prerelease)
            settings_manager.get_is_new_version_checker_enabled = get_is_new_version_checker_enabled_mock
            settings_manager.get_new_version_check_include_prerelease = get_new_version_check_include_prerelease_mock

            new_version_checker = NewVersionChecker(False)
            new_version_checker.execute = Mock()

            settings_new_version_checker = SettingsNewVersionChecker(settings_manager, new_version_checker)
            self.api.add_route('/api/settings/new_version_checker', settings_new_version_checker)

            body = self.simulate_request("/api/settings/new_version_checker", decode='utf-8')

            self.assertEqual(self.srmock.status, falcon.HTTP_OK)
            self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])

            result = json.loads(body)

            expected = {'include_prerelease': include_prerelease, 'enabled': enabled, 'interval': interval}
            self.assertEqual(result, expected)

            get_is_new_version_checker_enabled_mock.assert_called_once_with()
            get_new_version_check_include_prerelease_mock.assert_called_once_with()
            new_version_check_interval_mock.assert_called_once_with()
예제 #2
0
    def test_login_unauthorized(self):
        settings_manager = SettingsManager()
        settings_manager.get_password = MagicMock(return_value='monitorrent')
        settings_authentication_resource = Login(settings_manager)
        self.api.add_route(self.test_route, settings_authentication_resource)

        self.simulate_request(self.test_route, method='POST', body=json.dumps({'password': '******'}))

        self.assertEqual(self.srmock.status, falcon.HTTP_UNAUTHORIZED)
예제 #3
0
    def test_login_bad_request(self):
        settings_manager = SettingsManager()
        settings_manager.get_password = MagicMock(return_value='monitorrent')
        settings_authentication_resource = Login(settings_manager)
        self.api.add_route(self.test_route, settings_authentication_resource)

        self.simulate_request(self.test_route, method='POST', body=json.dumps({}))

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
    def test_set_is_authentication_enabled_bad_request(self, body):
        settings_manager = SettingsManager()
        settings_manager.get_password = MagicMock(return_value='monitorrent')
        settings_manager.set_is_authentication_enabled = MagicMock()
        settings_authentication_resource = SettingsAuthentication(settings_manager)
        self.api.add_route('/api/settings/authentication', settings_authentication_resource)

        self.simulate_request("/api/settings/authentication", method="PUT", body=json.dumps(body) if body else None)

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
예제 #5
0
    def test_login_bad_request(self):
        settings_manager = SettingsManager()
        settings_manager.get_password = MagicMock(return_value='monitorrent')
        settings_authentication_resource = Login(settings_manager)
        self.api.add_route(self.test_route, settings_authentication_resource)

        self.simulate_request(self.test_route,
                              method='POST',
                              body=json.dumps({}))

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
    def test_set_is_authentication_enabled_wrong_password(self, value):
        settings_manager = SettingsManager()
        settings_manager.get_password = MagicMock(return_value='monitorrent')
        settings_manager.set_is_authentication_enabled = MagicMock()
        settings_authentication_resource = SettingsAuthentication(settings_manager)
        self.api.add_route('/api/settings/authentication', settings_authentication_resource)

        request = {'password': '******', 'is_authentication_enabled': value}
        self.simulate_request("/api/settings/authentication", method="PUT", body=json.dumps(request))

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
예제 #7
0
    def test_login_unauthorized(self):
        settings_manager = SettingsManager()
        settings_manager.get_password = MagicMock(return_value='monitorrent')
        settings_authentication_resource = Login(settings_manager)
        self.api.add_route(self.test_route, settings_authentication_resource)

        self.simulate_request(self.test_route,
                              method='POST',
                              body=json.dumps({'password': '******'}))

        self.assertEqual(self.srmock.status, falcon.HTTP_UNAUTHORIZED)
    def test_delete_proxy(self, key):
        settings_manager = SettingsManager()
        set_proxy_mock = MagicMock()
        settings_manager.set_proxy = set_proxy_mock
        settings_proxy_resource = SettingsProxy(settings_manager)
        self.api.add_route(self.api_url, settings_proxy_resource)

        self.simulate_request(self.api_url, decode='utf-8', method='DELETE', query_string="key="+key)

        self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)

        set_proxy_mock.assert_called_once_with(key, None)
    def test_get_proxy_not_found(self):
        settings_manager = SettingsManager()
        get_proxy_mock = MagicMock(return_value=None)
        settings_manager.get_proxy = get_proxy_mock
        settings_proxy_resource = SettingsProxy(settings_manager)
        self.api.add_route(self.api_url, settings_proxy_resource)

        self.simulate_request(self.api_url, decode='utf-8', query_string="key=http")

        self.assertEqual(self.srmock.status, falcon.HTTP_NOT_FOUND)

        get_proxy_mock.assert_called_once_with('http')
    def test_set_is_proxy_enabled(self, value):
        settings_manager = SettingsManager()
        set_is_proxy_enabled_mock = MagicMock()
        settings_manager.set_is_proxy_enabled = set_is_proxy_enabled_mock
        settings_proxy_enabled_resource = SettingsProxyEnabled(settings_manager)
        self.api.add_route(self.api_url, settings_proxy_enabled_resource)

        request = {'enabled': value}
        self.simulate_request(self.api_url, method="PUT", body=json.dumps(request))

        self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)

        set_is_proxy_enabled_mock.assert_called_once_with(value)
    def test_set_is_developer_mode(self, value):
        settings_manager = SettingsManager()
        set_is_developer_mode_mock = MagicMock()
        settings_manager.set_is_developer_mode = set_is_developer_mode_mock
        settings_developer_resource = SettingsDeveloper(settings_manager)
        self.api.add_route('/api/settings/developer', settings_developer_resource)

        request = {'is_developer_mode': value}
        self.simulate_request("/api/settings/developer", method="PUT", body=json.dumps(request))

        self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)

        set_is_developer_mode_mock.assert_called_once_with(value)
예제 #12
0
    def test_set_is_authentication_enabled_bad_request(self, body):
        settings_manager = SettingsManager()
        settings_manager.get_password = MagicMock(return_value='monitorrent')
        settings_manager.set_is_authentication_enabled = MagicMock()
        settings_authentication_resource = SettingsAuthentication(
            settings_manager)
        self.api.add_route('/api/settings/authentication',
                           settings_authentication_resource)

        self.simulate_request("/api/settings/authentication",
                              method="PUT",
                              body=json.dumps(body) if body else None)

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
    def test_is_authentication_enabled(self, value):
        settings_manager = SettingsManager()
        settings_manager.get_is_authentication_enabled = MagicMock(return_value=value)
        settings_authentication_resource = SettingsAuthentication(settings_manager)
        self.api.add_route('/api/settings/authentication', settings_authentication_resource)

        body = self.simulate_request("/api/settings/authentication", decode='utf-8')

        self.assertEqual(self.srmock.status, falcon.HTTP_OK)
        self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])

        result = json.loads(body)

        self.assertEqual(result, {'is_authentication_enabled': value})
예제 #14
0
    def test_get_proxy_not_found(self):
        settings_manager = SettingsManager()
        get_proxy_mock = MagicMock(return_value=None)
        settings_manager.get_proxy = get_proxy_mock
        settings_proxy_resource = SettingsProxy(settings_manager)
        self.api.add_route(self.api_url, settings_proxy_resource)

        self.simulate_request(self.api_url,
                              decode='utf-8',
                              query_string="key=http")

        self.assertEqual(self.srmock.status, falcon.HTTP_NOT_FOUND)

        get_proxy_mock.assert_called_once_with('http')
    def test_put_proxy(self, key, proxy):
        settings_manager = SettingsManager()
        set_proxy_mock = MagicMock()
        settings_manager.set_proxy = set_proxy_mock
        settings_proxy_resource = SettingsProxy(settings_manager)
        self.api.add_route(self.api_url, settings_proxy_resource)

        request = {'url': proxy}
        self.simulate_request(self.api_url, decode='utf-8', method='PUT', query_string="key="+key,
                              body=json.dumps(request))

        self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)

        set_proxy_mock.assert_called_once_with(key, proxy)
예제 #16
0
    def test_delete_proxy(self, key):
        settings_manager = SettingsManager()
        set_proxy_mock = MagicMock()
        settings_manager.set_proxy = set_proxy_mock
        settings_proxy_resource = SettingsProxy(settings_manager)
        self.api.add_route(self.api_url, settings_proxy_resource)

        self.simulate_request(self.api_url,
                              decode='utf-8',
                              method='DELETE',
                              query_string="key=" + key)

        self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)

        set_proxy_mock.assert_called_once_with(key, None)
예제 #17
0
    def test_set_is_proxy_enabled(self, value):
        settings_manager = SettingsManager()
        set_is_proxy_enabled_mock = MagicMock()
        settings_manager.set_is_proxy_enabled = set_is_proxy_enabled_mock
        settings_proxy_enabled_resource = SettingsProxyEnabled(
            settings_manager)
        self.api.add_route(self.api_url, settings_proxy_enabled_resource)

        request = {'enabled': value}
        self.simulate_request(self.api_url,
                              method="PUT",
                              body=json.dumps(request))

        self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)

        set_is_proxy_enabled_mock.assert_called_once_with(value)
예제 #18
0
    def test_login_success(self, password):
        settings_manager = SettingsManager()
        settings_manager.get_password = MagicMock(return_value=password)
        settings_authentication_resource = Login(settings_manager)
        self.api.add_route(self.test_route, settings_authentication_resource)

        self.simulate_request(self.test_route, method='POST', body=json.dumps({'password': password}))

        self.assertEqual(self.srmock.status, falcon.HTTP_200)
        set_cookie = self.srmock.headers_dict['set-cookie']
        cookie = http.cookies.SimpleCookie()
        cookie.load(set_cookie)
        self.assertEqual(1, len(cookie))
        jwt_morsel = list(cookie.values())[0]
        self.assertEqual(AuthMiddleware.cookie_name, jwt_morsel.key)
        self.assertEqual(self.auth_token_verified, jwt_morsel.value)
    def test_get_proxy(self, key, proxy):
        settings_manager = SettingsManager()
        get_proxy_mock = MagicMock(return_value=proxy)
        settings_manager.get_proxy = get_proxy_mock
        settings_proxy_resource = SettingsProxy(settings_manager)
        self.api.add_route(self.api_url, settings_proxy_resource)

        body = self.simulate_request(self.api_url, decode='utf-8', query_string="key="+key)

        self.assertEqual(self.srmock.status, falcon.HTTP_OK)
        self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])

        result = json.loads(body)

        self.assertEqual(result, {'url': proxy})

        get_proxy_mock.assert_called_once_with(key)
    def test_get_is_proxy_enabled(self, value):
        settings_manager = SettingsManager()
        get_is_proxy_enabled_mock = MagicMock(return_value=value)
        settings_manager.get_is_proxy_enabled = get_is_proxy_enabled_mock
        settings_proxy_enabled_resource = SettingsProxyEnabled(settings_manager)
        self.api.add_route(self.api_url, settings_proxy_enabled_resource)

        body = self.simulate_request(self.api_url, decode='utf-8')

        self.assertEqual(self.srmock.status, falcon.HTTP_OK)
        self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])

        result = json.loads(body)

        self.assertEqual(result, {'enabled': value})

        get_is_proxy_enabled_mock.assert_called_once_with()
    def test_bad_request(self, body):
        settings_manager = SettingsManager()
        settings_developer_resource = SettingsDeveloper(settings_manager)
        self.api.add_route('/api/settings/developer', settings_developer_resource)

        self.simulate_request("/api/settings/developer", method="PUT", body=json.dumps(body) if body else None)

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
예제 #22
0
    def test_put_proxy(self, key, proxy):
        settings_manager = SettingsManager()
        set_proxy_mock = MagicMock()
        settings_manager.set_proxy = set_proxy_mock
        settings_proxy_resource = SettingsProxy(settings_manager)
        self.api.add_route(self.api_url, settings_proxy_resource)

        request = {'url': proxy}
        self.simulate_request(self.api_url,
                              decode='utf-8',
                              method='PUT',
                              query_string="key=" + key,
                              body=json.dumps(request))

        self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)

        set_proxy_mock.assert_called_once_with(key, proxy)
    def test_is_developer_mode(self, value):
        settings_manager = SettingsManager()
        get_is_developer_mode_mock = MagicMock(return_value=value)
        settings_manager.get_is_developer_mode = get_is_developer_mode_mock
        settings_developer_resource = SettingsDeveloper(settings_manager)
        self.api.add_route('/api/settings/developer', settings_developer_resource)

        body = self.simulate_request("/api/settings/developer", decode='utf-8')

        self.assertEqual(self.srmock.status, falcon.HTTP_OK)
        self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])

        result = json.loads(body)

        self.assertEqual(result, {'is_developer_mode': value})

        get_is_developer_mode_mock.assert_called_once_with()
예제 #24
0
    def test_login_success(self, password):
        settings_manager = SettingsManager()
        settings_manager.get_password = MagicMock(return_value=password)
        settings_authentication_resource = Login(settings_manager)
        self.api.add_route(self.test_route, settings_authentication_resource)

        self.simulate_request(self.test_route,
                              method='POST',
                              body=json.dumps({'password': password}))

        self.assertEqual(self.srmock.status, falcon.HTTP_200)
        set_cookie = self.srmock.headers_dict['set-cookie']
        cookie = http.cookies.SimpleCookie()
        cookie.load(set_cookie)
        self.assertEqual(1, len(cookie))
        jwt_morsel = list(cookie.values())[0]
        self.assertEqual(AuthMiddleware.cookie_name, jwt_morsel.key)
        self.assertEqual(self.auth_token_verified, jwt_morsel.value)
예제 #25
0
    def test_set_is_authentication_enabled_wrong_password(self, value):
        settings_manager = SettingsManager()
        settings_manager.get_password = MagicMock(return_value='monitorrent')
        settings_manager.set_is_authentication_enabled = MagicMock()
        settings_authentication_resource = SettingsAuthentication(
            settings_manager)
        self.api.add_route('/api/settings/authentication',
                           settings_authentication_resource)

        request = {
            'password': '******',
            'is_authentication_enabled': value
        }
        self.simulate_request("/api/settings/authentication",
                              method="PUT",
                              body=json.dumps(request))

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
    def test_bad_request(self, body):
        with patch('monitorrent.settings_manager.SettingsManager.new_version_check_interval',
                   new_callable=PropertyMock) as new_version_check_interval_mock:
            new_version_check_interval_mock.return_value = 4000

            settings_manager = SettingsManager()
            get_is_new_version_checker_enabled = Mock()
            settings_manager.get_is_new_version_checker_enabled = get_is_new_version_checker_enabled

            new_version_checker = NewVersionChecker(False)
            new_version_checker.execute = Mock()

            settings_new_version_checker = SettingsNewVersionChecker(settings_manager, new_version_checker)
            self.api.add_route('/api/settings/new_version_checker', settings_new_version_checker)

            self.simulate_request("/api/settings/new_version_checker", method="PATCH", body=json.dumps(body) if body else None)

            self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
예제 #27
0
    def test_is_authentication_enabled(self, value):
        settings_manager = SettingsManager()
        settings_manager.get_is_authentication_enabled = MagicMock(
            return_value=value)
        settings_authentication_resource = SettingsAuthentication(
            settings_manager)
        self.api.add_route('/api/settings/authentication',
                           settings_authentication_resource)

        body = self.simulate_request("/api/settings/authentication",
                                     decode='utf-8')

        self.assertEqual(self.srmock.status, falcon.HTTP_OK)
        self.assertTrue(
            'application/json' in self.srmock.headers_dict['Content-Type'])

        result = json.loads(body)

        self.assertEqual(result, {'is_authentication_enabled': value})
예제 #28
0
    def test_put_proxy_bad_request_1(self):
        settings_proxy_resource = SettingsProxy(SettingsManager())
        self.api.add_route(self.api_url, settings_proxy_resource)

        self.simulate_request(self.api_url,
                              decode='utf-8',
                              method='PUT',
                              query_string="key=http")

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
예제 #29
0
    def test_get_is_proxy_enabled(self, value):
        settings_manager = SettingsManager()
        get_is_proxy_enabled_mock = MagicMock(return_value=value)
        settings_manager.get_is_proxy_enabled = get_is_proxy_enabled_mock
        settings_proxy_enabled_resource = SettingsProxyEnabled(
            settings_manager)
        self.api.add_route(self.api_url, settings_proxy_enabled_resource)

        body = self.simulate_request(self.api_url, decode='utf-8')

        self.assertEqual(self.srmock.status, falcon.HTTP_OK)
        self.assertTrue(
            'application/json' in self.srmock.headers_dict['Content-Type'])

        result = json.loads(body)

        self.assertEqual(result, {'enabled': value})

        get_is_proxy_enabled_mock.assert_called_once_with()
    def test_is_new_version_checker_enabled(self, include_prerelease, enabled,
                                            interval):
        with patch(
                'monitorrent.settings_manager.SettingsManager.new_version_check_interval',
                new_callable=PropertyMock) as new_version_check_interval_mock:
            new_version_check_interval_mock.return_value = interval

            settings_manager = SettingsManager()
            get_is_new_version_checker_enabled_mock = Mock(
                return_value=enabled)
            get_new_version_check_include_prerelease_mock = Mock(
                return_value=include_prerelease)
            settings_manager.get_is_new_version_checker_enabled = get_is_new_version_checker_enabled_mock
            settings_manager.get_new_version_check_include_prerelease = get_new_version_check_include_prerelease_mock

            new_version_checker = NewVersionChecker(Mock(), False)
            new_version_checker.execute = Mock()

            settings_new_version_checker = SettingsNewVersionChecker(
                settings_manager, new_version_checker)
            self.api.add_route('/api/settings/new_version_checker',
                               settings_new_version_checker)

            body = self.simulate_request("/api/settings/new_version_checker",
                                         decode='utf-8')

            self.assertEqual(self.srmock.status, falcon.HTTP_OK)
            self.assertTrue(
                'application/json' in self.srmock.headers_dict['Content-Type'])

            result = json.loads(body)

            expected = {
                'include_prerelease': include_prerelease,
                'enabled': enabled,
                'interval': interval
            }
            self.assertEqual(result, expected)

            get_is_new_version_checker_enabled_mock.assert_called_once_with()
            get_new_version_check_include_prerelease_mock.assert_called_once_with(
            )
            new_version_check_interval_mock.assert_called_once_with()
예제 #31
0
    def test_bad_request(self, body):
        settings_manager = SettingsManager()
        settings_proxy_enabled_resource = SettingsProxyEnabled(
            settings_manager)
        self.api.add_route(self.api_url, settings_proxy_enabled_resource)

        self.simulate_request(self.api_url,
                              method="PUT",
                              body=json.dumps(body) if body else None)

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
예제 #32
0
    def test_get_proxy(self, key, proxy):
        settings_manager = SettingsManager()
        get_proxy_mock = MagicMock(return_value=proxy)
        settings_manager.get_proxy = get_proxy_mock
        settings_proxy_resource = SettingsProxy(settings_manager)
        self.api.add_route(self.api_url, settings_proxy_resource)

        body = self.simulate_request(self.api_url,
                                     decode='utf-8',
                                     query_string="key=" + key)

        self.assertEqual(self.srmock.status, falcon.HTTP_OK)
        self.assertTrue(
            'application/json' in self.srmock.headers_dict['Content-Type'])

        result = json.loads(body)

        self.assertEqual(result, {'url': proxy})

        get_proxy_mock.assert_called_once_with(key)
    def setUp(self):
        super(DbClientsManagerTest, self).setUp()

        self.client1 = Mock()
        self.client2 = Mock()

        self.settings_manager = SettingsManager()
        self.clients_manager = DbClientsManager(self.settings_manager, {
            self.CLIENT1_NAME: self.client1,
            self.CLIENT2_NAME: self.client2
        })
        self.clients_manager.set_default(self.CLIENT1_NAME)
    def test_patch_test(self, patch_include_prerelease, patch_enabled, patch_interval, update_include_prerelease, update_enabled, update_interval):
        with patch('monitorrent.settings_manager.SettingsManager.new_version_check_interval',
                   new_callable=PropertyMock) as new_version_check_interval_mock:

            new_version_check_interval_mock.return_value = 4000

            settings_manager = SettingsManager()
            settings_manager.get_new_version_check_include_prerelease = Mock(return_value=False)
            settings_manager.set_new_version_check_include_prerelease = Mock()
            settings_manager.get_is_new_version_checker_enabled = Mock(return_value=True)
            settings_manager.set_is_new_version_checker_enabled = Mock()
            settings_manager.new_version_check_interval = PropertyMock(return_value=3600)

            new_version_checker = NewVersionChecker(False)
            update_mock = Mock()
            new_version_checker.update = update_mock

            settings_new_version_checker = SettingsNewVersionChecker(settings_manager, new_version_checker)
            self.api.add_route('/api/settings/new_version_checker', settings_new_version_checker)

            request = dict()
            if patch_include_prerelease is not None:
                request['include_prerelease'] = patch_include_prerelease
            if patch_enabled is not None:
                request['enabled'] = patch_enabled
            if patch_interval is not None:
                request['interval'] = patch_interval
            self.simulate_request('/api/settings/new_version_checker', method="PATCH", body=json.dumps(request))

            self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)

            update_mock.assert_called_once_with(update_include_prerelease, update_enabled, update_interval)
예제 #35
0
    def test_set_is_developer_mode(self, value):
        with patch(self.remove_logs_interval_property, new_callable=PropertyMock) as remove_logs_interval_mock:
            remove_logs_interval_mock.return_value = value
            settings_manager = SettingsManager()
            settings_logs_resource = SettingsLogs(settings_manager)
            self.api.add_route('/api/settings/logs', settings_logs_resource)

            request = {'interval': value}
            self.simulate_request("/api/settings/logs", method="PUT", body=json.dumps(request))

            self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)

            remove_logs_interval_mock.assert_called_once_with(value)
    def test_bad_request(self, body):
        with patch(
                'monitorrent.settings_manager.SettingsManager.new_version_check_interval',
                new_callable=PropertyMock) as new_version_check_interval_mock:
            new_version_check_interval_mock.return_value = 4000

            settings_manager = SettingsManager()
            get_is_new_version_checker_enabled = Mock()
            settings_manager.get_is_new_version_checker_enabled = get_is_new_version_checker_enabled

            new_version_checker = NewVersionChecker(Mock(), False)
            new_version_checker.execute = Mock()

            settings_new_version_checker = SettingsNewVersionChecker(
                settings_manager, new_version_checker)
            self.api.add_route('/api/settings/new_version_checker',
                               settings_new_version_checker)

            self.simulate_request("/api/settings/new_version_checker",
                                  method="PATCH",
                                  body=json.dumps(body) if body else None)

            self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
예제 #37
0
    def test_is_developer_mode(self, value):
        with patch(self.remove_logs_interval_property, new_callable=PropertyMock) as remove_logs_interval_mock:
            remove_logs_interval_mock.return_value = value
            settings_manager = SettingsManager()
            settings_logs_resource = SettingsLogs(settings_manager)
            self.api.add_route('/api/settings/logs', settings_logs_resource)

            body = self.simulate_request("/api/settings/logs", decode='utf-8')

            self.assertEqual(self.srmock.status, falcon.HTTP_OK)
            self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])

            result = json.loads(body)

            self.assertEqual(result, {'interval': value})

            remove_logs_interval_mock.assert_called_once_with()
예제 #38
0
    def test_put_proxy_bad_request_2(self):
        settings_proxy_resource = SettingsProxy(SettingsManager())
        self.api.add_route(self.api_url, settings_proxy_resource)

        self.simulate_request(self.api_url,
                              decode='utf-8',
                              method='PUT',
                              query_string="key=http",
                              body=json.dumps({'url': None}))

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)

        self.simulate_request(self.api_url,
                              decode='utf-8',
                              method='PUT',
                              query_string="key=http",
                              body=json.dumps({'nourl':
                                               'http://1.1.1.1:8888'}))

        self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
    def test_patch_test(self, patch_include_prerelease, patch_enabled,
                        patch_interval, update_include_prerelease,
                        update_enabled, update_interval):
        with patch(
                'monitorrent.settings_manager.SettingsManager.new_version_check_interval',
                new_callable=PropertyMock) as new_version_check_interval_mock:

            new_version_check_interval_mock.return_value = 4000

            settings_manager = SettingsManager()
            settings_manager.get_new_version_check_include_prerelease = Mock(
                return_value=False)
            settings_manager.set_new_version_check_include_prerelease = Mock()
            settings_manager.get_is_new_version_checker_enabled = Mock(
                return_value=True)
            settings_manager.set_is_new_version_checker_enabled = Mock()
            settings_manager.new_version_check_interval = PropertyMock(
                return_value=3600)

            new_version_checker = NewVersionChecker(Mock(), False)
            update_mock = Mock()
            new_version_checker.update = update_mock

            settings_new_version_checker = SettingsNewVersionChecker(
                settings_manager, new_version_checker)
            self.api.add_route('/api/settings/new_version_checker',
                               settings_new_version_checker)

            request = dict()
            if patch_include_prerelease is not None:
                request['include_prerelease'] = patch_include_prerelease
            if patch_enabled is not None:
                request['enabled'] = patch_enabled
            if patch_interval is not None:
                request['interval'] = patch_interval
            self.simulate_request('/api/settings/new_version_checker',
                                  method="PATCH",
                                  body=json.dumps(request))

            self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)

            update_mock.assert_called_once_with(update_include_prerelease,
                                                update_enabled,
                                                update_interval)
 def setUp(self):
     super(SettingsManagerTest, self).setUp()
     self.settings_manager = SettingsManager() 
 def _get_settings_manager(password):
     settings_manager = SettingsManager()
     settings_manager.get_password = MagicMock(return_value=password)
     settings_manager.set_password = MagicMock()
     return settings_manager
예제 #42
0
class SettingsManagerTest(DbTestCase):
    def setUp(self):
        super(SettingsManagerTest, self).setUp()
        self.settings_manager = SettingsManager() 

    def test_get_default_password(self):
        self.assertEqual('monitorrent', self.settings_manager.get_password())

    def test_set_password(self):
        value = 'p@$$w0rd!'
        self.settings_manager.set_password(value)

        self.assertEqual(value, self.settings_manager.get_password())

    def test_get_default_is_authentication_enabled(self):
        self.assertTrue(self.settings_manager.get_is_authentication_enabled())

    def test_set_is_authentication_enabled(self):
        value = False
        self.settings_manager.set_is_authentication_enabled(value)

        self.assertEqual(value, self.settings_manager.get_is_authentication_enabled())

    def test_enable_disable_authentication(self):
        self.settings_manager.disable_authentication()

        self.assertFalse(self.settings_manager.get_is_authentication_enabled())

        self.settings_manager.enable_authentication()

        self.assertTrue(self.settings_manager.get_is_authentication_enabled())

    def test_default_client(self):
        self.assertIsNone(self.settings_manager.get_default_client())

        client = 'transmission'
        self.settings_manager.set_default_client(client)

        self.assertEqual(client, self.settings_manager.get_default_client())

    def test_get_is_developer_mode(self):
        self.assertFalse(self.settings_manager.get_is_developer_mode())

    @data(True, False)
    def test_set_is_developer_mode(self, value):
        self.settings_manager.set_is_developer_mode(value)

        self.assertEqual(value, self.settings_manager.get_is_developer_mode())

    def test_get_default_requests_timeout(self):
        self.assertEqual(10, self.settings_manager.requests_timeout)

    def test_set_requests_timeout(self):
        self.assertEqual(10, self.settings_manager.requests_timeout)

        self.settings_manager.requests_timeout = 20

        self.assertEqual(20, self.settings_manager.requests_timeout)

    def test_set_float_requests_timeout(self):
        self.assertEqual(10, self.settings_manager.requests_timeout)

        self.settings_manager.requests_timeout = 20.7

        self.assertEqual(20.7, self.settings_manager.requests_timeout)

    def test_get_default_plugin_settings(self):
        self.assertEqual(10, self.settings_manager.tracker_settings.requests_timeout)

    def test_set_plugin_settings(self):
        plugin_settings = self.settings_manager.tracker_settings
        self.assertEqual(10, plugin_settings.requests_timeout)

        plugin_settings.requests_timeout = 20
        self.settings_manager.tracker_settings = plugin_settings

        self.assertEqual(20, self.settings_manager.tracker_settings.requests_timeout)

    def test_set_float_plugin_settings(self):
        plugin_settings = self.settings_manager.tracker_settings
        self.assertEqual(10, plugin_settings.requests_timeout)

        plugin_settings.requests_timeout = 20.3
        self.settings_manager.tracker_settings = plugin_settings

        self.assertEqual(20.3, self.settings_manager.tracker_settings.requests_timeout)

    def test_get_remove_logs_interval(self):
        self.assertEqual(10, self.settings_manager.remove_logs_interval)

    def test_set_remove_logs_interval(self):
        self.assertEqual(10, self.settings_manager.remove_logs_interval)

        self.settings_manager.remove_logs_interval = 20

        self.assertEqual(20, self.settings_manager.remove_logs_interval)

    def test_get_is_proxy_enabled(self):
        self.assertFalse(self.settings_manager.get_is_proxy_enabled())

    @data(True, False)
    def test_set_is_proxy_enabled(self, value):
        self.settings_manager.set_is_proxy_enabled(value)

        self.assertEqual(self.settings_manager.get_is_proxy_enabled(), value)

    def test_get_proxy(self):
        self.assertEqual(self.settings_manager.get_proxy('http'), None)
        self.assertEqual(self.settings_manager.get_proxy('https'), None)

    def test_set_proxy(self):
        self.assertEqual(self.settings_manager.get_proxy('http'), None)
        self.assertEqual(self.settings_manager.get_proxy('https'), None)

        self.settings_manager.set_proxy('http', 'http://1.1.1.1:8888')

        self.assertEqual(self.settings_manager.get_proxy('http'), 'http://1.1.1.1:8888')
        self.assertEqual(self.settings_manager.get_proxy('https'), None)
        expected = {
            'http': 'http://1.1.1.1:8888'
        }
        self.assertEqual(self.settings_manager.get_proxies(), expected)

        self.settings_manager.set_proxy('https', 'http://2.2.2.2:8888')

        self.assertEqual(self.settings_manager.get_proxy('http'), 'http://1.1.1.1:8888')
        self.assertEqual(self.settings_manager.get_proxy('https'), 'http://2.2.2.2:8888')
        expected = {
            'http': 'http://1.1.1.1:8888',
            'https': 'http://2.2.2.2:8888'
        }
        self.assertEqual(self.settings_manager.get_proxies(), expected)

    def test_unset_proxy(self):
        self.settings_manager.set_proxy('http', 'http://1.1.1.1:8888')
        self.settings_manager.set_proxy('https', 'http://2.2.2.2:8888')
        expected = {
            'http': 'http://1.1.1.1:8888',
            'https': 'http://2.2.2.2:8888'
        }
        self.assertEqual(self.settings_manager.get_proxies(), expected)

        self.settings_manager.set_proxy('https', None)
        self.settings_manager.set_proxy('http://rutor.org', None)
        expected = {
            'http': 'http://1.1.1.1:8888'
        }
        self.assertEqual(self.settings_manager.get_proxies(), expected)

    @data(True, False)
    def test_set_is_new_version_check_enabled(self, value):
        self.settings_manager.set_is_new_version_checker_enabled(value)

        self.assertEqual(self.settings_manager.get_is_new_version_checker_enabled(), value)

    def test_get_new_version_check_include_prerelease(self):
        self.assertFalse(self.settings_manager.get_new_version_check_include_prerelease())

    @data(True, False)
    def test_set_new_version_check_include_prerelease(self, value):
        self.settings_manager.set_new_version_check_include_prerelease(value)

        self.assertEqual(self.settings_manager.get_new_version_check_include_prerelease(), value)

    def test_get_new_version_check_interval_default_value(self):
        self.assertEqual(3600, self.settings_manager.new_version_check_interval)

    def test_get_new_version_check_interval_set_value(self):
        self.assertEqual(3600, self.settings_manager.new_version_check_interval)

        self.settings_manager.new_version_check_interval = 7200

        self.assertEqual(7200, self.settings_manager.new_version_check_interval)
예제 #43
0
 def setUp(self):
     super(SettingsManagerTest, self).setUp()
     self.settings_manager = SettingsManager() 
예제 #44
0
def upgrade_0_to_1(operations_factory):
    from monitorrent.settings_manager import SettingsManager
    settings_manager = SettingsManager()
    tracker_settings = None
    with operations_factory() as operations:
        operations.add_column(AnilibriaTvTopic.__tablename__,
                              Column('format', String, nullable=True))
        operations.add_column(AnilibriaTvTopic.__tablename__,
                              Column('format_list', String, nullable=True))
        topic_values = []
        m = MetaData()
        ani_topics = Table(
            AnilibriaTvTopic.__tablename__, m,
            Column("id", Integer, ForeignKey('topics.id'), primary_key=True),
            Column("hash", String, nullable=True),
            Column("format", String, nullable=True),
            Column("format_list", String, nullable=True))
        m1 = MetaData()
        base_topics = Table(Topic.__tablename__, m1,
                            Column("id", Integer, primary_key=True),
                            Column("url", String), Column("type", String),
                            Column('status', String))
        topics = operations.db.query(base_topics).filter(
            base_topics.c.type == PLUGIN_NAME)
        for topic in topics:
            raw_topic = row2dict(topic, base_topics)
            # noinspection PyBroadException
            try:
                if tracker_settings is None:
                    tracker_settings = settings_manager.tracker_settings
                response = requests.get(
                    raw_topic['url'], **tracker_settings.get_requests_kwargs())
                soup = get_soup(response.text)
                format_list = AnilibriaTvTracker._find_format_list(soup)
                format_list.sort()
                topic_values.append({
                    'id': raw_topic['id'],
                    'format_list': ",".join(format_list),
                    'format': format_list[0],
                    'status': Status.Ok.__str__()
                })
            except:
                exc_info = sys.exc_info()
                print(u''.join(traceback.format_exception(*exc_info)))
                topic_values.append({
                    'id': raw_topic['id'],
                    'status': Status.Error.__str__()
                })

        for upd in topic_values:
            if 'format' in upd:
                operations.db.execute(
                    ani_topics.update(
                        whereclause=(ani_topics.c.id == upd['id']),
                        values={
                            'format_list': upd['format_list'],
                            'format': upd['format']
                        }))
            operations.db.execute(
                base_topics.update(whereclause=(base_topics.c.id == upd['id']),
                                   values={'status': upd['status']}))
예제 #45
0
 def _get_settings_manager(password):
     settings_manager = SettingsManager()
     settings_manager.get_password = MagicMock(return_value=password)
     settings_manager.set_password = MagicMock()
     return settings_manager
예제 #46
0
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 = scraper.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'https://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)
class SettingsManagerTest(DbTestCase):
    def setUp(self):
        super(SettingsManagerTest, self).setUp()
        self.settings_manager = SettingsManager() 

    def test_get_default_password(self):
        self.assertEqual('monitorrent', self.settings_manager.get_password())

    def test_set_password(self):
        value = 'p@$$w0rd!'
        self.settings_manager.set_password(value)

        self.assertEqual(value, self.settings_manager.get_password())

    def test_get_default_is_authentication_enabled(self):
        self.assertTrue(self.settings_manager.get_is_authentication_enabled())

    def test_set_is_authentication_enabled(self):
        value = False
        self.settings_manager.set_is_authentication_enabled(value)

        self.assertEqual(value, self.settings_manager.get_is_authentication_enabled())

    def test_enable_disable_authentication(self):
        self.settings_manager.disable_authentication()

        self.assertFalse(self.settings_manager.get_is_authentication_enabled())

        self.settings_manager.enable_authentication()

        self.assertTrue(self.settings_manager.get_is_authentication_enabled())

    def test_default_client(self):
        self.assertIsNone(self.settings_manager.get_default_client())

        client = 'transmission'
        self.settings_manager.set_default_client(client)

        self.assertEqual(client, self.settings_manager.get_default_client())

    def test_get_is_developer_mode(self):
        self.assertFalse(self.settings_manager.get_is_developer_mode())

    @data(True, False)
    def test_set_is_developer_mode(self, value):
        self.settings_manager.set_is_developer_mode(value)

        self.assertEqual(value, self.settings_manager.get_is_developer_mode())

    def test_get_default_requests_timeout(self):
        self.assertEqual(10, self.settings_manager.requests_timeout)

    def test_set_requests_timeout(self):
        self.assertEqual(10, self.settings_manager.requests_timeout)

        self.settings_manager.requests_timeout = 20

        self.assertEqual(20, self.settings_manager.requests_timeout)

    def test_set_float_requests_timeout(self):
        self.assertEqual(10, self.settings_manager.requests_timeout)

        self.settings_manager.requests_timeout = 20.7

        self.assertEqual(20.7, self.settings_manager.requests_timeout)

    def test_get_default_plugin_settings(self):
        self.assertEqual(10, self.settings_manager.tracker_settings.requests_timeout)

    def test_set_plugin_settings(self):
        plugin_settings = self.settings_manager.tracker_settings
        self.assertEqual(10, plugin_settings.requests_timeout)

        plugin_settings.requests_timeout = 20
        self.settings_manager.tracker_settings = plugin_settings

        self.assertEqual(20, self.settings_manager.tracker_settings.requests_timeout)

    def test_set_float_plugin_settings(self):
        plugin_settings = self.settings_manager.tracker_settings
        self.assertEqual(10, plugin_settings.requests_timeout)

        plugin_settings.requests_timeout = 20.3
        self.settings_manager.tracker_settings = plugin_settings

        self.assertEqual(20.3, self.settings_manager.tracker_settings.requests_timeout)

    def test_get_remove_logs_interval(self):
        self.assertEqual(10, self.settings_manager.remove_logs_interval)

    def test_set_remove_logs_interval(self):
        self.assertEqual(10, self.settings_manager.remove_logs_interval)

        self.settings_manager.remove_logs_interval = 20

        self.assertEqual(20, self.settings_manager.remove_logs_interval)
예제 #48
0
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, get_plugins('tracker'))
    clients_manager = DbClientsManager(settings_manager, get_plugins('client'))
    notifier_manager = NotifierManager(settings_manager, get_plugins('notifier'))

    log_manager = ExecuteLogManager()
    engine_runner_logger = DbLoggerWrapper(log_manager, settings_manager)
    engine_runner = DBEngineRunner(engine_runner_logger, settings_manager, tracker_manager,
                                   clients_manager, notifier_manager)

    include_prerelease = settings_manager.get_new_version_check_include_prerelease()
    new_version_checker = NewVersionChecker(notifier_manager, include_prerelease)
    if settings_manager.get_is_new_version_checker_enabled():
        # noinspection PyBroadException
        try:
            new_version_checker.execute()
        except:
            pass
        new_version_checker.start(settings_manager.new_version_check_interval)

    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, new_version_checker)
    server_start_params = (config.ip, config.port)
    server = wsgi.Server(server_start_params, app)
    print('Server started on {0}:{1}'.format(*server_start_params))

    try:
        server.start()
    except KeyboardInterrupt:
        engine_runner.stop()
        server.stop()
예제 #49
0
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, 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)

    new_version_checker = NewVersionChecker(settings_manager.get_new_version_check_include_prerelease())
    if settings_manager.get_is_new_version_checker_enabled():
        # noinspection PyBroadException
        try:
            new_version_checker.execute()
        except:
            pass
        new_version_checker.start(settings_manager.new_version_check_interval)

    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, new_version_checker)
    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()