Exemple #1
0
    def _request_credentials(self, authorization_key):
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}

        body = {
            'code': authorization_key,
            'client_id': self.CLIENT_ID,
            'client_secret': self.CLIENT_NOT_SO_SECRET,
            'grant_type': 'authorization_code'
        }
        body = urllib.parse.urlencode(body)

        request = urllib.request.Request(self.TOKEN_URL,
                                         data=body,
                                         headers=headers)

        try:
            response = utils.urlopen(request)

        except urllib.error.HTTPError as e:
            error = json.load(e)
            raise Exception(
                error.get('error_description') or error.get('error') or str(e))

        data = json.load(response)

        return {'access_token': data['access_token']}
Exemple #2
0
def main(parser, args):
    from motioneye import meyectl
    from motioneye import utils

    options = parse_options(parser, args)

    meyectl.configure_logging('webhook', options.log_to_file)
    meyectl.configure_tornado()

    logging.debug('hello!')
    logging.debug('method = %s' % options.method)
    logging.debug('url = %s' % options.url)

    headers = {}
    parts = urllib.parse.urlparse(options.url)
    url = options.url
    data = None

    if options.method == 'POST':
        headers['Content-Type'] = 'text/plain'
        data = ''

    elif options.method == 'POSTf':  # form url-encoded
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
        data = parts.query
        url = options.url.split('?')[0]

    elif options.method == 'POSTj':  # json
        headers['Content-Type'] = 'application/json'
        data = urllib.parse.parse_qs(parts.query)
        data = {k: v[0] for (k, v) in list(data.items())}
        data = json.dumps(data)
        url = options.url.split('?')[0]

    else:  # GET
        pass

    request = urllib.request.Request(url, data, headers=headers)
    try:
        utils.urlopen(request, timeout=settings.REMOTE_REQUEST_TIMEOUT)
        logging.debug('webhook successfully called')

    except Exception as e:
        logging.error('failed to call webhook: %s' % e)

    logging.debug('bye!')
Exemple #3
0
    def _request(self, url, body=None, headers=None, retry_auth=True):
        if not self._credentials:
            if not self._authorization_key:
                msg = 'missing authorization key'
                self.error(msg)
                raise Exception(msg)

            self.debug('requesting credentials')
            try:
                self._credentials = self._request_credentials(
                    self._authorization_key)
                self.save()

            except Exception as e:
                self.error('failed to obtain credentials: %s' % e)
                raise

        headers = headers or {}
        headers[
            'Authorization'] = 'Bearer %s' % self._credentials['access_token']

        self.debug('requesting %s' % url)
        request = urllib.request.Request(url, data=body, headers=headers)
        try:
            response = utils.urlopen(request)

        except urllib.error.HTTPError as e:
            if e.code == 401 and retry_auth:  # unauthorized, access token may have expired
                try:
                    self.debug(
                        'credentials have probably expired, refreshing them')
                    self._credentials = self._request_credentials(
                        self._authorization_key)
                    self.save()

                    # retry the request with refreshed credentials
                    return self._request(url, body, headers, retry_auth=False)

                except Exception:
                    self.error('refreshing credentials failed')
                    raise

            elif str(e).count('not_found'):
                msg = 'folder "%s" not found' % self._location
                self.error(msg)
                raise Exception(msg)

            else:
                self.error('request failed: %s' % e)
                raise

        except Exception as e:
            self.error('request failed: %s' % e)
            raise

        return response.read()
Exemple #4
0
    def _request(self,
                 url,
                 body=None,
                 headers=None,
                 retry_auth=True,
                 method=None):
        if not self._credentials:
            if not self._authorization_key:
                msg = 'missing authorization key'
                self.error(msg)
                raise Exception(msg)

            self.debug('requesting credentials')
            try:
                self._credentials = self._request_credentials(
                    self._authorization_key)
                self.save()

            except Exception as e:
                self.error('failed to obtain credentials: %s' % e)
                raise

        headers = headers or {}
        headers[
            'Authorization'] = 'Bearer %s' % self._credentials['access_token']

        self.debug('requesting %s' % url)
        request = urllib.request.Request(url, data=body, headers=headers)
        if method:
            request.get_method = lambda: method
        try:
            response = utils.urlopen(request)

        except urllib.error.HTTPError as e:
            if e.code == 401 and retry_auth:  # unauthorized, access token may have expired
                try:
                    self.debug(
                        'credentials have probably expired, refreshing them')
                    self._credentials = self._refresh_credentials(
                        self._credentials['refresh_token'])
                    self.save()

                    # retry the request with refreshed credentials
                    return self._request(url, body, headers, retry_auth=False)

                except Exception:
                    self.error('refreshing credentials failed')
                    raise

            else:
                try:
                    e = json.load(e)
                    msg = e['error']['message']

                except Exception:
                    msg = str(e)

                self.error('request failed: %s' % msg)
                raise Exception(msg)

        except Exception as e:
            self.error('request failed: %s' % e)
            raise

        return response.read()