Пример #1
0
    def _get_auth(self):
        parsed_url = urlparse(self.authentication_url)
        post_data = {
            'name': self.username,
            'password': self.password,
            'next': parsed_url.path + '?' + parsed_url.query
        }

        try:
            response = self.session.post(self.url, data=post_data,
                                         allow_redirects=False)
            response.raise_for_status()

            response = self.session.get(response.headers['location'],
                                        allow_redirects=False)
            response.raise_for_status()

            resulting_uri = '{redirect_uri}#access_token=(.*)'.format(
                redirect_uri=re.escape(self.redirect_uri))

            self.auth = re.search(resulting_uri, response.headers['location']).group(1)

        except Exception as error:
            helpers.handle_requests_exception(error)
            self.auth = None

        return self.auth
Пример #2
0
    def testAuthentication(self):
        """
        Tests the parameters the user has provided in the ui to see if they are correct
        """
        try:
            self.response = self.session.get(self.url,
                                             timeout=120,
                                             verify=False)
        except Exception:
            pass

        try:
            self._get_auth()
            if not self.response:
                raise HTTPError(404, 'Not Found')

            self.response.raise_for_status()
            if self.auth:
                return True, 'Success: Connected and Authenticated'
            else:
                return False, 'Failed to authenticate with {0}'.format(
                    self.name)
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False, '{0}'.format(error)
Пример #3
0
    def _get_auth(self):
        next_params = {
            'client_id': self.client_id,
            'response_type': 'token',
            'redirect_uri': self.redirect_uri
        }

        post_data = {
            'name': self.username,
            'password': self.password,
            'next': '/v2/oauth2/authenticate?' + urlencode(next_params)
        }

        try:
            response = self.session.post(self.url,
                                         data=post_data,
                                         allow_redirects=False)
            response.raise_for_status()

            response = self.session.get(response.headers['location'],
                                        allow_redirects=False)
            response.raise_for_status()

            resulting_uri = '{redirect_uri}#access_token=(.*)'.format(
                redirect_uri=re.escape(self.redirect_uri))

            self.auth = re.search(resulting_uri,
                                  response.headers['location']).group(1)

        except Exception as error:
            helpers.handle_requests_exception(error)
            self.auth = None

        return self.auth
Пример #4
0
    def _get_auth(self):
        self.url = 'https://api.put.io/login'
        self.session.headers['Accept'] = 'application/json'
        next_params = {
            'client_id': self.client_id,
            'response_type': 'token',
            'redirect_uri': self.redirect_uri
        }

        post_data = {
            'name': self.username,
            'password': self.password,
            'next': '/v2/oauth2/authenticate?' + urlencode(next_params)
        }

        try:
            response = self.session.post(self.url, data=post_data,
                                         allow_redirects=False)
            response.raise_for_status()

            response = self.session.get(response.headers['location'],
                                        allow_redirects=False)
            response.raise_for_status()

            resulting_uri = '{redirect_uri}#access_token=(.*)'.format(
                redirect_uri=re.escape(self.redirect_uri))

            self.auth = re.search(resulting_uri, response.headers['location']).group(1)

        except Exception as error:
            helpers.handle_requests_exception(error)
            self.auth = None

        return self.auth
Пример #5
0
    def _get_auth(self):
        client = PutioClient(self.password)
        try:
            client.Account.info()
        except ClientError as error:
            helpers.handle_requests_exception(error)
            self.auth = None
        else:
            self.auth = client

        return self.auth
Пример #6
0
    def _get_auth(self):
        client = PutioClient(self.password)
        try:
            client.Account.info()
        except ClientError as error:
            helpers.handle_requests_exception(error)
            self.auth = None
        else:
            self.auth = client

        return self.auth
Пример #7
0
    def _add_uri(self, result):
        try:
            payload={
                "name":result.name,
                "links":[result.url]
            }
            payloadJSON = {k: json.dumps(v) for k, v in payload.items()}
            self.response = self.session.request(
                "POST", self.host+"api/addPackage", data=payloadJSON, timeout=120, cookies=self.cookies)
            return True

        except Exception as error:
            helpers.handle_requests_exception(error)
            return False
Пример #8
0
    def _add_uri(self, result):
        try:
            payload = {"name": result.name, "links": [result.url]}
            payloadJSON = {k: json.dumps(v) for k, v in payload.items()}
            self.response = self.session.request("POST",
                                                 self.host + "api/addPackage",
                                                 data=payloadJSON,
                                                 timeout=120,
                                                 cookies=self.cookies)
            return True

        except Exception as error:
            helpers.handle_requests_exception(error)
            return False
Пример #9
0
    def _add_torrent_file(self, result):
        post_data = {
            'name': 'putio_torrent',
            'parent': 0,
            'oauth_token': self.auth
        }

        try:
            self.response = self.session.post('https://api.put.io/v2/files/upload',
                                              data=post_data, files=('putio_torrent', result.content))
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        return self.response.json()['status'] == "OK"
Пример #10
0
    def _add_torrent_file(self, result):
        post_data = {
            'name': 'putio_torrent',
            'parent': 0,
            'oauth_token': self.auth
        }

        try:
            self.response = self.session.post(
                'https://api.put.io/v2/files/upload',
                data=post_data,
                files=('putio_torrent', result.content))
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        return self.response.json()['status'] == "OK"
Пример #11
0
    def _add_torrent_uri(self, result):

        post_data = {
            'url': result.url,
            'save_parent_id': 0,
            'extract': True,
            'oauth_token': self.auth
        }

        try:
            self.response = self.session.post('https://api.put.io/v2/transfers/add',
                                              data=post_data)
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        j = self.response.json()
        return j.get("transfer", {}).get('save_parent_id', None) == 0
Пример #12
0
    def _add_torrent_uri(self, result):

        post_data = {
            'url': result.url,
            'save_parent_id': 0,
            'extract': True,
            'oauth_token': self.auth
        }

        try:
            self.response = self.session.post(
                'https://api.put.io/v2/transfers/add', data=post_data)
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        j = self.response.json()
        return j.get("transfer", {}).get('save_parent_id', None) == 0
Пример #13
0
    def _get_auth(self):
        try:
            post_data={'username':self.username,'password':self.password}

            self.response = self.session.request(
                "POST", self.host+"api/login", data=post_data, timeout=120)

            if self.response.text == "false":
                raise Exception('Login fail')

            self.cookies = self.response.cookies
            self.auth = self.response.text

        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        return self.auth
Пример #14
0
    def testAuthentication(self):
        """
        Tests the parameters the user has provided in the ui to see if they are correct
        """
        try:
            self.response = self.session.get(self.url, timeout=120, verify=False)
            self.response.raise_for_status()
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False, '{0}'.format(error)

        try:
            self._get_auth()
            self.response.raise_for_status()
            return True, 'Success: Connected and Authenticated'
        except Exception:
            helpers.handle_requests_exception(error)
            return False, '{0}'.format(error)
Пример #15
0
    def _get_auth(self):
        try:
            post_data = {'username': self.username, 'password': self.password}

            self.response = self.session.request("POST",
                                                 self.host + "api/login",
                                                 data=post_data,
                                                 timeout=120)

            if self.response.text == "false":
                raise Exception('Login fail')

            self.cookies = self.response.cookies
            self.auth = self.response.text

        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        return self.auth
Пример #16
0
    def testAuthentication(self):
        """
        Tests the parameters the user has provided in the ui to see if they are correct
        """
        try:
            self.response = self.session.get(self.url, timeout=120, verify=False)
        except Exception:
            pass

        try:
            self._get_auth()
            if not self.response:
                raise HTTPError(404, 'Not Found')

            self.response.raise_for_status()
            if self.auth:
                return True, 'Success: Connected and Authenticated'
            else:
                return False, 'Failed to authenticate with {0}'.format(self.name)
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False, '{0}'.format(error)
Пример #17
0
    def _request(self, method='get', params=None, data=None, files=None, cookies=None):  # pylint: disable=too-many-arguments, too-many-return-statements
        """
        Makes the actual request for the client, for everything except auth
        """

        if time.time() > self.last_time + 1800 or not self.auth:
            self.last_time = time.time()
            self._get_auth()

        log_string = '{0}: Requested a {1} connection to url {2}'.format(
            self.name, method.upper(), self.url)

        if params:
            log_string += '?{0}'.format(urlencode(params))

        if data:
            log_string += ' and data: {0}{1}'.format(
                str(data)[0:99], '...' if len(str(data)) > 100 else '')

        logger.log(log_string, logger.DEBUG)

        if not self.auth:
            logger.log('{0}: Authentication Failed'.format(self.name), logger.WARNING)
            return False

        try:
            self.response = self.session.request(
                method.upper(), self.url, params=params, data=data,
                files=files, cookies=cookies, timeout=120, verify=False)

            self.response.raise_for_status()
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        logger.log('{0}: Response to the {1} request is {2}'.format
                   (self.name, method.upper(), self.response.text), logger.DEBUG)

        return True
Пример #18
0
    def _request(self, method='get', params=None, data=None, files=None, cookies=None):  # pylint: disable=too-many-arguments, too-many-return-statements
        """
        Makes the actual request for the client, for everything except auth
        """

        if time.time() > self.last_time + 1800 or not self.auth:
            self.last_time = time.time()
            self._get_auth()

        log_string = '{0}: Requested a {1} connection to url {2}'.format(
            self.name, method.upper(), self.url)

        if params:
            log_string += '?{0}'.format(urlencode(params))

        if data:
            log_string += ' and data: {0}{1}'.format(
                str(data)[0:99], '...' if len(str(data)) > 100 else '')

        logger.log(log_string, logger.DEBUG)

        if not self.auth:
            logger.log('{0}: Authentication Failed'.format(self.name), logger.WARNING)
            return False

        try:
            self.response = self.session.request(
                method.upper(), self.url, params=params, data=data,
                files=files, cookies=cookies, timeout=120, verify=False)

            self.response.raise_for_status()
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        logger.log('{0}: Response to the {1} request is {2}'.format
                   (self.name, method.upper(), self.response.text), logger.DEBUG)

        return True
    def _get_auth(self):
        if self.session.cookies and self.auth:
            return self.auth

        params = {
            'api': 'SYNO.API.Auth',
            'version': 2,
            'method': 'login',
            'account': self.username,
            'passwd': self.password,
            'session': 'DownloadStation',
            'format': 'cookie',
        }

        try:
            self.response = self.session.get(self.urls['login'], params=params, verify=False)
            self.response.raise_for_status()
        except RequestException as error:
            handle_requests_exception(error)
            self.session.cookies.clear()
            self.auth = False
            return self.auth
        else:
            return self._check_response()
    def _check_destination(self):  # pylint: disable=too-many-return-statements, too-many-branches
        """
        Validate and set torrent destination
        """

        torrent_path = sickbeard.TORRENT_PATH

        if not (self.auth or self._get_auth()):
            return False

        if self.checked_destination and self.destination == torrent_path:
            return True

        params = {
            'api': 'SYNO.DSM.Info',
            'version': 2,
            'method': 'getinfo',
            'session': 'DownloadStation',
        }

        try:
            self.response = self.session.get(self.urls['dsminfo'], params=params, verify=False, timeout=120)
            self.response.raise_for_status()
        except RequestException as error:
            handle_requests_exception(error)
            self.session.cookies.clear()
            self.auth = False
            return False

        destination = ''
        if self._check_response():
            jdata = self.response.json()
            version_string = jdata.get('data', {}).get('version_string')
            if not version_string:
                logger.log('Could not get the version string from DSM: {response}'.format
                           (response=jdata))
                return False

            if version_string.startswith('DSM 6'):
                #  This is DSM6, lets make sure the location is relative
                if torrent_path and os.path.isabs(torrent_path):
                    torrent_path = re.sub(r'^/volume\d/', '', torrent_path).lstrip('/')
                else:
                    #  Since they didn't specify the location in the settings,
                    #  lets make sure the default is relative,
                    #  or forcefully set the location setting
                    params.update({
                        'method': 'getconfig',
                        'version': 2,
                    })

                    try:
                        self.response = self.session.get(self.urls['info'], params=params, verify=False, timeout=120)
                        self.response.raise_for_status()
                    except RequestException as error:
                        handle_requests_exception(error)
                        self.session.cookies.clear()
                        self.auth = False
                        return False

                    if self._check_response():
                        jdata = self.response.json()
                        destination = jdata.get('data', {}).get('default_destination')
                        if destination and os.path.isabs(destination):
                            torrent_path = re.sub(r'^/volume\d/', '', destination).lstrip('/')
                        else:
                            logger.log('Default destination could not be determined '
                                       'for DSM6: {response}'.format(response=jdata))
                            return False

        if destination or torrent_path:
            logger.log('Destination is now {path}'.format
                       (path=torrent_path or destination))

        self.checked_destination = True
        self.destination = torrent_path
        return True
Пример #21
0
    def _request(self, method='get', params=None, data=None, files=None, cookies=None):  # pylint: disable=too-many-arguments, too-many-return-statements
        """
        Makes the actual request for the client, for everything except auth
        """

        if time.time() > self.last_time + 1800 or not self.auth:
            self.last_time = time.time()
            self._get_auth()

        log_string = '{0}: Requested a {1} connection to url {2}'.format(
            self.name, method.upper(), self.url)

        if params:
            log_string += '?{0}'.format(urlencode(params))

        if data:
            log_string += ' and data: {0}{1}'.format(
                str(data)[0:99], '...' if len(str(data)) > 100 else '')

        logger.log(log_string, logger.DEBUG)

        if not self.auth:
            logger.log('{0}: Authentication Failed'.format(self.name), logger.WARNING)
            return False

        # Dict, loop through and change all key,value pairs to bytes
        if isinstance(params, dict):
            for key, value in six.iteritems(params):
                if isinstance(key, six.text_type):
                    del params[key]
                    key = key.encode('utf-8')

                if isinstance(value, six.text_type):
                    value = value.encode('utf-8')
                params[key] = value

        if isinstance(data, dict):
            for key, value in six.iteritems(data):
                if isinstance(key, six.text_type):
                    del data[key]
                    key = key.encode('utf-8')

                if isinstance(value, six.text_type):
                    value = value.encode('utf-8')
                data[key] = value

        # List, loop through and change all indexes to bytes
        if isinstance(params, list):
            for index, value in enumerate(params):
                if isinstance(value, six.text_type):
                    params[index] = value.encode('utf-8')

        if isinstance(data, list):
            for index, value in enumerate(data):
                if isinstance(value, six.text_type):
                    data[index] = value.encode('utf-8')

        # Unicode, encode to bytes
        if isinstance(params, six.text_type):
            params = params.encode('utf-8')

        if isinstance(data, six.text_type):
            data = data.encode('utf-8')

        try:
            self.response = self.session.request(
                method.upper(), self.url, params=params, data=data,
                files=files, cookies=cookies, timeout=120, verify=False)

            self.response.raise_for_status()
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        logger.log('{0}: Response to the {1} request is {2}'.format
                   (self.name, method.upper(), self.response.text), logger.DEBUG)

        return True
Пример #22
0
    def _request(self,
                 method='get',
                 params=None,
                 data=None,
                 files=None,
                 cookies=None):  # pylint: disable=too-many-arguments, too-many-return-statements
        """
        Makes the actual request for the client, for everything except auth
        """

        if time.time() > self.last_time + 1800 or not self.auth:
            self.last_time = time.time()
            self._get_auth()

        log_string = '{0}: Requested a {1} connection to url {2}'.format(
            self.name, method.upper(), self.url)

        if params:
            log_string += '?{0}'.format(urlencode(params))

        if data:
            log_string += ' and data: {0}{1}'.format(
                str(data)[0:99], '...' if len(str(data)) > 100 else '')

        logger.log(log_string, logger.DEBUG)

        if not self.auth:
            logger.log('{0}: Authentication Failed'.format(self.name),
                       logger.WARNING)
            return False

        # Dict, loop through and change all key,value pairs to bytes
        if isinstance(params, dict):
            for key, value in six.iteritems(params):
                if isinstance(key, six.text_type):
                    del params[key]
                    key = key.encode('utf-8')

                if isinstance(value, six.text_type):
                    value = value.encode('utf-8')
                params[key] = value

        if isinstance(data, dict):
            for key, value in six.iteritems(data):
                if isinstance(key, six.text_type):
                    del data[key]
                    key = key.encode('utf-8')

                if isinstance(value, six.text_type):
                    value = value.encode('utf-8')
                data[key] = value

        # List, loop through and change all indexes to bytes
        if isinstance(params, list):
            for index, value in enumerate(params):
                if isinstance(value, six.text_type):
                    params[index] = value.encode('utf-8')

        if isinstance(data, list):
            for index, value in enumerate(data):
                if isinstance(value, six.text_type):
                    data[index] = value.encode('utf-8')

        # Unicode, encode to bytes
        if isinstance(params, six.text_type):
            params = params.encode('utf-8')

        if isinstance(data, six.text_type):
            data = data.encode('utf-8')

        try:
            self.response = self.session.request(method.upper(),
                                                 self.url,
                                                 params=params,
                                                 data=data,
                                                 files=files,
                                                 cookies=cookies,
                                                 timeout=120,
                                                 verify=False)

            self.response.raise_for_status()
        except Exception as error:
            helpers.handle_requests_exception(error)
            return False

        logger.log(
            '{0}: Response to the {1} request is {2}'.format(
                self.name, method.upper(), self.response.text), logger.DEBUG)

        return True