Exemplo n.º 1
0
    def __init__(self,
                 feed,
                 offset=None,
                 stop=None,
                 limit=None,
                 since=None,
                 before=None,
                 cached=False):
        """
        feed: Feed object: Feed object to return items from
        offset: int or PumpObject: beginning of slice
        stop: int or PumpObject: end of slice
        limit: int or None: Number of objects to return
        since: PumpObject: Return objects newer than this
        before: PumpObject: Return objects older than this
        cached: bool: Return objects from feed._items instead of API

        """
        self.cache = []
        self.feed = feed
        self.url = self.feed.url
        self.itemcount = 0
        self._offset = offset

        #set limit based on offset and stop
        if isinstance(stop, int):
            if isinstance(offset, int):
                self._limit = stop - offset
            else:
                self._limit = stop
        else:
            self._limit = limit

        #set since to stop if stop is a PumpObject
        if self.get_obj_id(stop):
            self._since = self.get_obj_id(stop)
        else:
            self._since = self.get_obj_id(since)

        #set before to offset if offset is a PumpObject
        if self.get_obj_id(offset):
            self._before = self.get_obj_id(offset)
            self._offset = None
        else:
            self._before = self.get_obj_id(before)

        self._cached = cached

        if self._offset and (self._since or self._before):
            raise PyPumpException(
                "can not have both offset and since/before parameters")
        elif self._since and self._before:
            raise PyPumpException(
                "can not have both since and before parameters")
Exemplo n.º 2
0
    def __init__(self,
                 feed,
                 offset=None,
                 stop=None,
                 limit=None,
                 since=None,
                 before=None,
                 cached=False):
        self.cache = []
        self.feed = feed
        self.url = self.feed.url
        self.itemcount = 0
        self._offset = offset

        # set limit based on offset and stop
        if isinstance(stop, int):
            if isinstance(offset, int):
                self._limit = stop - offset
            else:
                self._limit = stop
        else:
            self._limit = limit

        # set since to stop if stop is a PumpObject
        if self.get_obj_id(stop):
            self._since = self.get_obj_id(stop)
        else:
            self._since = self.get_obj_id(since)

        # set before to offset if offset is a PumpObject
        if self.get_obj_id(offset):
            self._before = self.get_obj_id(offset)
            self._offset = None
        else:
            self._before = self.get_obj_id(before)

        self._cached = cached

        if self._offset and (self._since or self._before):
            raise PyPumpException(
                "can not have both offset and since/before parameters")
        elif self._since and self._before:
            raise PyPumpException(
                "can not have both since and before parameters")
Exemplo n.º 3
0
    def __init__(self, name, id=None, *args, **kwargs):
        self.name = name
        self.id = self.id if id is None else id

        if self.id is None and self.name:
            user_lists = self.all()
            for user_list in user_lists:
                if user_list.name == self.name:
                    self.id = user_list.id

            if self.id is None:
                error = "Can't find list with name {0!r} (Lists found: {1})".format(
                    self.name, ", ".join(user_lists))
                PyPumpException(error)

        super(List, self).__init__(*args, **kwargs)
Exemplo n.º 4
0
    def __request(self, offset=None, count=None):
        """ Makes a request """
        param = {}

        if count:
            param["count"] = count

        if offset:
            param["offset"] = offset

        if self.actor is None:
            # oh dear, we gotta raise an error
            raise PyPumpException("No actor defined on {feed}".format(feed=self))

        data = self._pump.request(self.ENDPOINT, params=param)

        return data
Exemplo n.º 5
0
    def inbox(self):
        """ :class:`Inbox feed <pypump.models.feed.Inbox>` with all
        :class:`activities <pypump.models.activity.Activity>`
        received by the person, can only be read if logged in as the owner.

        Example:
            >>> for activity in pump.me.inbox[:2]:
            ...     print(activity.id)
            ...
            https://microca.st/api/activity/BvqXQOwXShSey1HxYuJQBQ
            https://pumpyourself.com/api/activity/iQGdnz5-T-auXnbUUdXh-A
        """
        if not self.isme:
            raise PyPumpException("You can't read other people's inboxes")
        self._inbox = self._inbox or Inbox(self.links['activity-inbox'],
                                           pypump=self._pump)
        return self._inbox
Exemplo n.º 6
0
    def __init__(self, webfinger=None, **kwargs):
        super(Person, self).__init__(**kwargs)

        if isinstance(webfinger, six.string_types):
            if "@" not in webfinger:  # TODO do better validation
                raise PyPumpException("Not a valid webfinger: %s" % webfinger)

            self.id = "acct:{0}".format(webfinger)
            self.username = webfinger.split("@")[0]

            self._add_link(
                'self', "{0}://{1}/api/user/{2}/profile".format(
                    self._pump.protocol, self.server, self.username))
            try:
                data = self._pump.request(self.links['self'])
                self.unserialize(data)
            except:
                pass
Exemplo n.º 7
0
    def request(self,
                endpoint,
                method="GET",
                data="",
                raw=False,
                params=None,
                retries=None,
                client=None,
                headers=None,
                timeout=None,
                **kwargs):
        """ Make request to endpoint with OAuth.
        Returns dictionary with response data.

        :param endpoint: endpoint path, or a fully qualified URL if raw=True.
        :param method: GET (default), POST or DELETE.
        :param data: data to send in the request body.
        :param raw: use endpoint as entered without trying to modify it.
        :param params: dictionary of parameters to send in the query string.
        :param retries: number of times to retry if a request fails.
        :param client: OAuth client data, if False do request without OAuth.
        :param headers: dictionary of HTTP headers.
        :param timeout: the timeout for a request, in seconds.

        Example:
            >>> pump.request('https://e14n.com/api/user/evan/profile', raw=True)
            {u'displayName': u'Evan Prodromou',
             u'favorites': {u'totalItems': 7227,
              u'url': u'https://e14n.com/api/user/evan/favorites'},
             u'id': u'acct:[email protected]',
             u'image': {u'height': 96,
              u'url': u'https://e14n.com/uploads/evan/2014/9/24/knyf1g_thumb.jpg',
              u'width': 96},
             u'liked': False,
             u'location': {u'displayName': u'Montreal, Quebec, Canada',
              u'objectType': u'place'},
             u'objectType': u'person',
             u'preferredUsername': u'evan',
             u'published': u'2013-02-20T15:34:52Z',
             u'summary': u'I wanna make it with you. http://payb.tc/evanp',
             u'updated': u'2014-09-24T02:38:32Z',
             u'url': u'https://e14n.com/evan'}
        """

        retries = self.retries if retries is None else retries
        timeout = self.timeout if timeout is None else timeout

        # check client has been setup
        if client is None:
            client = self.setup_oauth_client(endpoint)
        elif client is False:
            client = None

        params = {} if params is None else params

        if data and isinstance(data, dict):
            data = json.dumps(data)

        if not raw:
            url = self._build_url(endpoint)
        else:
            url = endpoint

        headers = headers or {"Content-Type": "application/json"}
        fnc = requests.get
        request = {
            "auth": client,
            "headers": headers,
            "params": params,
            "timeout": timeout,
        }
        request.update(kwargs)

        if method == "POST":
            fnc = requests.post
            request.update({"data": data})

        elif method == "PUT":
            fnc = requests.put
            request.update({"data": data})

        elif method == "GET":
            fnc = requests.get

        elif method == "DELETE":
            fnc = requests.delete,

        for attempt in range(1 + retries):
            response = self._requester(fnc=fnc,
                                       endpoint=endpoint,
                                       raw=raw,
                                       **request)

            if response.status_code == 200:
                # huray!
                return response.json()

            if response.status_code == 400:
                # can't do much
                try:
                    try:
                        data = response.json()
                        error = data["error"]
                    except ValueError:
                        error = response.content

                    if not error:
                        raise IndexError  # yesss i know.
                except IndexError:
                    error = "400 - Bad request."
                raise PyPumpException(error)

            if response.ok:
                return response

        error = "Request Failed to {url} (response: {data} | status: {status})"
        error = error.format(url=url,
                             data=response.content,
                             status=response.status_code)

        raise PyPumpException(error)
Exemplo n.º 8
0
 def id_in_list(list, id):
     if id:
         if [i for i in list if i.id == id]:
             return True
         else:
             raise PyPumpException("id %r not in feed." % self._since)
Exemplo n.º 9
0
 def inbox(self):
     if not self.isme:
         raise PyPumpException("You can't read other people's inboxes")
     self._inbox = self._inbox or Inbox(self.links['activity-inbox'],
                                        pypump=self._pump)
     return self._inbox
Exemplo n.º 10
0
    def request(self,
                endpoint,
                method="GET",
                data="",
                raw=False,
                params=None,
                attempts=10,
                client=None):
        """ This will make a request to <self.protocol>://<self.server>/<endpoint> with oauth headers
        method = GET (default), POST or PUT
        attempts = this is how many times it'll try re-attempting
        """

        if client is None:
            client = self.client

        # check client has been setup
        if client is None:
            self.setup_oauth_client()
            client = self.client

        params = {} if params is None else params

        if endpoint.startswith("/"):
            endpoint = endpoint[1:]  # remove inital / as we add it

        if data and isinstance(data, dict):
            # we actually need to make it into a json object as that's what pump.io deals with.
            data = json.dumps(data)

        data = to_unicode(data)

        if raw is False:
            url = "{protocol}://{server}/{endpoint}".format(
                protocol=self.protocol, server=self.server, endpoint=endpoint)
        else:
            url = endpoint

        for attempt in range(attempts):
            if method == "POST":
                request = {
                    "auth": client,
                    "headers": {
                        "Content-Type": "application/json"
                    },
                    "params": params,
                    "data": data,
                }
                response = self._requester(requests.post, endpoint, raw,
                                           **request)
            elif method == "GET":
                request = {
                    "params": params,
                    "auth": client,
                }

                response = self._requester(requests.get, endpoint, raw,
                                           **request)

            if response.status_code == 200:
                # huray!
                return response.json()

            ##
            # Debugging
            ##
            print response
            print response.content

            if response.status_code in [400]:
                # can't do much
                try:
                    try:
                        data = response.json()
                        error = data["error"]
                    except ValueError:
                        error = response.content

                    if not error:
                        raise IndexError  # yesss i know.
                except IndexError:
                    error = "Recieved a 400 bad request error. This is likely due to an OAuth failure"
                raise PyPumpException(error)

        # failed, oh no!
        error = "Failed to make request to {0} ({1} {2})".format(
            url, method, data)
        raise PyPumpException(error)