How to use the granary.as2.from_as1 function in granary

To help you get started, we’ve selected a few granary examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github snarfed / bridgy-fed / activitypub.py View on Github external
tld = domain.split('.')[-1]
        if tld in common.TLD_BLOCKLIST:
            self.error('', status=404)

        mf2 = util.fetch_mf2('http://%s/' % domain, gateway=True,
                             headers=common.HEADERS)
        # logging.info('Parsed mf2 for %s: %s', resp.url, json_dumps(mf2, indent=2))

        hcard = mf2util.representative_hcard(mf2, mf2['url'])
        logging.info('Representative h-card: %s', json_dumps(hcard, indent=2))
        if not hcard:
            self.error("""\
Couldn't find a representative h-card (http://microformats.org/wiki/representative-hcard-parsing) on %s""" % mf2['url'])

        key = MagicKey.get_or_create(domain)
        obj = self.postprocess_as2(as2.from_as1(microformats2.json_to_object(hcard)),
                                   key=key)
        obj.update({
            'inbox': '%s/%s/inbox' % (self.request.host_url, domain),
            'outbox': '%s/%s/outbox' % (self.request.host_url, domain),
            'following': '%s/%s/following' % (self.request.host_url, domain),
            'followers': '%s/%s/followers' % (self.request.host_url, domain),
        })
        logging.info('Returning: %s', json_dumps(obj, indent=2))

        self.response.headers.update({
            'Content-Type': common.CONTENT_TYPE_AS2,
            'Access-Control-Allow-Origin': '*',
        })
        self.response.write(json_dumps(obj, indent=2))
github snarfed / bridgy-fed / redirect.py View on Github external
def convert_to_as2(self, url):
        """Fetch a URL as HTML, convert it to AS2, and return it.

        Currently mainly for Pixelfed.
        https://github.com/snarfed/bridgy-fed/issues/39
        """
        mf2 = util.fetch_mf2(url)
        entry = mf2util.find_first_entry(mf2, ['h-entry'])
        logging.info('Parsed mf2 for %s: %s', mf2['url'], json_dumps(entry, indent=2))

        obj = self.postprocess_as2(as2.from_as1(microformats2.json_to_object(entry)))
        logging.info('Returning: %s', json_dumps(obj, indent=2))

        self.response.headers.update({
            'Content-Type': common.CONTENT_TYPE_AS2,
            'Access-Control-Allow-Origin': '*',
        })
        self.response.write(json_dumps(obj, indent=2))
github snarfed / bridgy-fed / webmention.py View on Github external
def try_activitypub(self):
        """Returns True if we attempted ActivityPub delivery, False otherwise."""
        targets = self._activitypub_targets()
        if not targets:
            return False

        key = MagicKey.get_or_create(self.source_domain)
        error = None
        last_success = None

        # TODO: collect by inbox, add 'to' fields, de-dupe inboxes and recipients

        for resp, inbox in targets:
            target_obj = json_loads(resp.target_as2) if resp.target_as2 else None
            source_activity = self.postprocess_as2(
                as2.from_as1(self.source_obj), target=target_obj, key=key)

            if resp.status == 'complete':
                source_activity['type'] = 'Update'

            try:
                last = activitypub.send(source_activity, inbox, self.source_domain)
                resp.status = 'complete'
                last_success = last
            except BaseException as e:
                error = e
                resp.status = 'error'

            resp.put()

        # Pass the AP response status code and body through as our response
        if last_success:
github snarfed / granary / api.py View on Github external
self.response.headers['Content-Type'] = 'text/plain'
    else:
      content_type = FORMATS.get(format)
      if content_type:
        self.response.headers['Content-Type'] = content_type

    if self.request.method == 'HEAD':
      return

    activities = response['items']
    try:
      if format in ('as1', 'json', 'activitystreams'):
        self.response.out.write(json_dumps(response, indent=2))
      elif format == 'as2':
        response.update({
          'items': [as2.from_as1(a) for a in activities],
          'totalItems': response.pop('totalResults', None),
          'updated': response.pop('updatedSince', None),
          'filtered': None,
          'sorted': None,
        })
        self.response.out.write(json_dumps(util.trim_nulls(response), indent=2))
      elif format == 'atom':
        hub = self.request.get('hub')
        reader = self.request.get('reader', 'true').lower()
        if reader not in ('true', 'false'):
          self.abort(400, 'reader param must be either true or false')
        if not actor and hfeed:
          actor = microformats2.json_to_object({
            'properties': hfeed.get('properties', {}),
          })
        self.response.out.write(atom.activities_to_atom(