Esempio n. 1
0
def rss_from_activities(activities):
  hfeed = {
    'properties': {
      'content': [{'value': 'some stuff by meee'}],
    },
  }
  return rss.from_activities(
    activities, actor=ACTOR, title='Stuff', feed_url='http://site/feed',
    home_page_url='http://site/', hfeed=hfeed)
Esempio n. 2
0
def rss_from_activities(activities):
    hfeed = {
        'properties': {
            'content': [{
                'value': 'some stuff by meee'
            }],
        },
    }
    return rss.from_activities(activities,
                               actor=ACTOR,
                               title='Stuff',
                               feed_url='http://site/feed',
                               home_page_url='http://site/',
                               hfeed=hfeed)
Esempio n. 3
0
  def test_from_activities_bad_published_datetime(self):
    self.assert_multiline_in("""
<item>
  <title>my post</title>
  <link>http://perma/link</link>
  <description>something</description>
  <guid isPermaLink="true">http://perma/link</guid>
</item>""",
      rss.from_activities([{
        'url': 'http://perma/link',
        'objectType': 'article',
        'displayName': 'my post',
        'content': 'something',
        'published': '2019',
      }], feed_url='http://this'),
      ignore_blanks=True)
Esempio n. 4
0
    def test_from_activities_bad_published_datetime(self):
        self.assert_multiline_in("""
<item>
  <title>my post</title>
  <link>http://perma/link</link>
  <description>something</description>
  <guid isPermaLink="true">http://perma/link</guid>
</item>""",
                                 rss.from_activities([{
                                     'url': 'http://perma/link',
                                     'objectType': 'article',
                                     'displayName': 'my post',
                                     'content': 'something',
                                     'published': '2019',
                                 }],
                                                     feed_url='http://this'),
                                 ignore_blanks=True)
Esempio n. 5
0
  def test_from_activities_unknown_mime_type(self):
    self.assert_multiline_in("""
<item>
<title>my post</title>
<link>http://perma/link</link>
<guid isPermaLink="true">http://perma/link</guid>
<enclosure url="http://a/podcast.foo" type=""/>
</item>""",
      rss.from_activities([{
        'url': 'http://perma/link',
        'objectType': 'article',
        'displayName': 'my post',
        'attachments': [{
          'objectType': 'video',
          'stream': {'url': 'http://a/podcast.foo'},
        }],
      }], feed_url='http://this'),
      ignore_blanks=True)
Esempio n. 6
0
    def test_from_activities_unknown_mime_type(self):
        self.assert_multiline_in("""
<item>
<title>my post</title>
<link>http://perma/link</link>
<guid isPermaLink="true">http://perma/link</guid>
<enclosure url="http://a/podcast.foo" type=""/>
</item>""",
                                 rss.from_activities([{
                                     'url':
                                     'http://perma/link',
                                     'objectType':
                                     'article',
                                     'displayName':
                                     'my post',
                                     'attachments': [{
                                         'objectType': 'video',
                                         'stream': {
                                             'url': 'http://a/podcast.foo'
                                         },
                                     }],
                                 }],
                                                     feed_url='http://this'),
                                 ignore_blanks=True)
Esempio n. 7
0
    def write_response(self,
                       response,
                       actor=None,
                       url=None,
                       title=None,
                       hfeed=None):
        """Converts ActivityStreams activities and writes them out.

    Args:
      response: response dict with values based on OpenSocial ActivityStreams
        REST API, as returned by Source.get_activities_response()
      actor: optional ActivityStreams actor dict for current user. Only used
        for Atom and JSON Feed output.
      url: the input URL
      title: string, used in feed output (Atom, JSON Feed, RSS)
      hfeed: dict, parsed mf2 h-feed, if available
    """
        format = self.request.get('format') or self.request.get(
            'output') or 'json'
        if format not in FORMATS:
            raise exc.HTTPBadRequest('Invalid format: %s, expected one of %r' %
                                     (format, FORMATS))

        if 'plaintext' in self.request.params:
            # override content type
            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(activities,
                                            actor,
                                            host_url=url
                                            or self.request.host_url + '/',
                                            request_url=self.request.url,
                                            xml_base=util.base_url(url),
                                            title=title,
                                            rels={'hub': hub} if hub else None,
                                            reader=(reader == 'true')))
                self.response.headers.add(
                    'Link', str('<%s>; rel="self"' % self.request.url))
                if hub:
                    self.response.headers.add('Link',
                                              str('<%s>; rel="hub"' % hub))
            elif format == 'rss':
                if not title:
                    title = 'Feed for %s' % url
                self.response.out.write(
                    rss.from_activities(activities,
                                        actor,
                                        title=title,
                                        feed_url=self.request.url,
                                        hfeed=hfeed,
                                        home_page_url=util.base_url(url)))
            elif format in ('as1-xml', 'xml'):
                self.response.out.write(XML_TEMPLATE % util.to_xml(response))
            elif format == 'html':
                self.response.out.write(
                    microformats2.activities_to_html(activities))
            elif format in ('mf2-json', 'json-mf2'):
                items = [microformats2.activity_to_json(a) for a in activities]
                self.response.out.write(json_dumps({'items': items}, indent=2))
            elif format == 'jsonfeed':
                try:
                    jf = jsonfeed.activities_to_jsonfeed(
                        activities,
                        actor=actor,
                        title=title,
                        feed_url=self.request.url)
                except TypeError as e:
                    raise exc.HTTPBadRequest('Unsupported input data: %s' % e)
                self.response.out.write(json_dumps(jf, indent=2))
        except ValueError as e:
            logging.warning('converting to output format failed',
                            stack_info=True)
            self.abort(400, 'Could not convert to %s: %s' % (format, str(e)))
Esempio n. 8
0
  def write_response(self, response, actor=None, url=None, title=None,
                     hfeed=None):
    """Converts ActivityStreams activities and writes them out.

    Args:
      response: response dict with values based on OpenSocial ActivityStreams
        REST API, as returned by Source.get_activities_response()
      actor: optional ActivityStreams actor dict for current user. Only used
        for Atom and JSON Feed output.
      url: the input URL
      title: string, used in feed output (Atom, JSON Feed, RSS)
      hfeed: dict, parsed mf2 h-feed, if available
    """
    format = self.request.get('format') or self.request.get('output') or 'json'
    if format not in FORMATS:
      raise exc.HTTPBadRequest('Invalid format: %s, expected one of %r' %
                               (format, FORMATS))

    activities = response['items']

    try:
      if format in ('as1', 'json', 'activitystreams'):
        # list of official MIME types:
        # https://www.iana.org/assignments/media-types/media-types.xhtml
        self.response.headers['Content-Type'] = \
          'application/json' if format == 'json' else 'application/stream+json'
        self.response.out.write(json.dumps(response, indent=2))
      elif format == 'as2':
        self.response.headers['Content-Type'] = 'application/activity+json'
        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':
        self.response.headers['Content-Type'] = 'application/atom+xml'
        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')
        self.response.out.write(atom.activities_to_atom(
          activities, actor,
          host_url=url or self.request.host_url + '/',
          request_url=self.request.url,
          xml_base=util.base_url(url),
          title=title,
          rels={'hub': hub} if hub else None,
          reader=(reader == 'true')))
        self.response.headers.add('Link', str('<%s>; rel="self"' % self.request.url))
        if hub:
          self.response.headers.add('Link', str('<%s>; rel="hub"' % hub))
      elif format == 'rss':
        self.response.headers['Content-Type'] = 'application/rss+xml'
        if not title:
          title = 'Feed for %s' % url
        self.response.out.write(rss.from_activities(
          activities, actor, title=title,
          feed_url=self.request.url, hfeed=hfeed,
          home_page_url=util.base_url(url)))
      elif format in ('as1-xml', 'xml'):
        self.response.headers['Content-Type'] = 'application/xml'
        self.response.out.write(XML_TEMPLATE % util.to_xml(response))
      elif format == 'html':
        self.response.headers['Content-Type'] = 'text/html'
        self.response.out.write(microformats2.activities_to_html(activities))
      elif format in ('mf2-json', 'json-mf2'):
        self.response.headers['Content-Type'] = 'application/json'
        items = [microformats2.activity_to_json(a) for a in activities]
        self.response.out.write(json.dumps({'items': items}, indent=2))
      elif format == 'jsonfeed':
        self.response.headers['Content-Type'] = 'application/json'
        try:
          jf = jsonfeed.activities_to_jsonfeed(activities, actor=actor, title=title,
                                               feed_url=self.request.url)
        except TypeError as e:
          raise exc.HTTPBadRequest('Unsupported input data: %s' % e)
        self.response.out.write(json.dumps(jf, indent=2))
    except ValueError as e:
      logging.warning('converting to output format failed', exc_info=True)
      self.abort(400, 'Could not convert to %s: %s' % (format, str(e)))

    if 'plaintext' in self.request.params:
      # override response content type
      self.response.headers['Content-Type'] = 'text/plain'