Esempio n. 1
0
def gen_feed(title,
             author,
             feed_url,
             url,
             subtitle,
             logo,
             categories=None,
             album=False,
             licenses=False):
    fg = FeedGenerator()
    fg.load_extension("podcast")

    fg.id(feed_url)
    fg.title(title)
    fg.author(author)
    fg.link(href=url)
    fg.link(href=feed_url, rel="self")
    fg.logo(logo)
    fg.subtitle(subtitle)
    fg.language("en")
    fg.generator(generator="reel2bits",
                 uri=f"https://{current_app.config['AP_DOMAIN']}",
                 version=g.cfg["REEL2BITS_VERSION"])

    if album and categories:
        fg.podcast.itunes_category(categories[0])
        fg.category([{"term": c, "label": c} for c in categories])

    if licenses:
        fg.rights("See individual tracks: " + ", ".join(licenses))

    return fg
Esempio n. 2
0
def main():
    now = datetime.now()
    today_day_of_week = now.weekday()
    most_recent_sunday = now - timedelta(
        days=today_day_of_week + 1)  # sunday is day 6

    fg = FeedGenerator()
    fg.load_extension('podcast')
    fg.id(URL)
    fg.title('Wicked Bites Radio')
    fg.category(term='Food')
    fg.language('en')
    fg.logo(
        'http://www.nedine.com/wp-content/themes/wickedbites/images/logo.png')
    fg.link(href='http://www.nedine.com', rel='alternate')
    fg.link(href=URL, rel='self')
    fg.description('The Pat Whitley Restaurant Show')
    fg.podcast.itunes_category('Food')
    fg.podcast.itunes_summary('Pat Whitley Restaurant Show')
    fg.podcast.itunes_explicit('no')
    fg.podcast.itunes_new_feed_url(URL)
    fg.podcast.itunes_category('Arts', 'Food')
    fg.podcast.itunes_owner('Eric Biagiotti', '*****@*****.**')

    for i in range(10):
        datestamp = (most_recent_sunday - timedelta(weeks=i))
        url = 'http://www.nedine.com/Radio/Shows/%s.mp3' % datestamp.strftime(
            '%m%d%y')

        r = requests.head(url)
        if r.status_code == 200:
            entry = fg.add_entry(order='append')
            entry.id(url)
            entry.title(datestamp.strftime('%m/%d/%Y'))
            entry.pubDate(datestamp.strftime('%Y-%m-%d 00:00:00 UTC'))
            entry.description(
                datestamp.strftime('Wicked Bites Radio show for %A, %B %e %Y'))
            entry.podcast.itunes_summary(
                datestamp.strftime('Wicked Bites Radio show for %A, %B %e %Y'))
            entry.enclosure(url, r.headers.get('Content-Length', 0),
                            'audio/mpeg')

    fg.rss_file('wickedbites.rss')

    s3_connection = boto.connect_s3()
    bucket = s3_connection.get_bucket('ebiagiotti')
    key = boto.s3.key.Key(bucket, 'wickedbites.rss')
    key.set_contents_from_filename('wickedbites.rss', policy='public-read')
Esempio n. 3
0
def main():
    now = datetime.now()
    today_day_of_week = now.weekday()
    most_recent_sunday = now - timedelta(days=today_day_of_week+1)  # sunday is day 6

    fg = FeedGenerator()
    fg.load_extension('podcast')
    fg.id(URL)
    fg.title('Wicked Bites Radio')
    fg.category(term='Food')
    fg.language('en')
    fg.logo('http://www.nedine.com/wp-content/themes/wickedbites/images/logo.png')
    fg.link(href='http://www.nedine.com', rel='alternate')
    fg.link(href=URL, rel='self')
    fg.description('''The Pat Whitley Restaurant Show – The Country’s longest Running and most successful Restaurant Show, Sundays 10am-Noon on WRKO, Pat Whitley is the 'brand' on America's First Restaurant Show. Heard every show: "Praise or Zing from Pizza to Gourmet – where you are the food critic"''')
    fg.podcast.itunes_category('Food')
    fg.podcast.itunes_summary('Pat Whitley Restaurant Show')
    fg.podcast.itunes_explicit('no')
    fg.podcast.itunes_new_feed_url(URL)
    fg.podcast.itunes_category('Arts', 'Food')
    fg.podcast.itunes_owner('Matt Perry', '*****@*****.**')

    for i in range(10):
        datestamp = (most_recent_sunday - timedelta(weeks=i))
        url = 'http://www.nedine.com/Radio/Shows/%s.mp3' % datestamp.strftime('%m%d%y')

        r = requests.head(url)
        if r.status_code == HTTPStatus.OK:
            entry = fg.add_entry(order='append')
            entry.id(url)
            entry.title(datestamp.strftime('%m/%d/%Y'))
            entry.pubdate(datestamp.strftime('%Y-%m-%d 12:00:00 EST'))
            entry.description(datestamp.strftime('Wicked Bites Radio show for %A, %B %e %Y'))
            entry.podcast.itunes_summary(datestamp.strftime('Wicked Bites Radio show for %A, %B %e %Y'))
            entry.enclosure(url, r.headers.get('Content-Length', 0), 'audio/mpeg')

    fg.rss_file('wickedbites.rss')
Esempio n. 4
0
		print_enc ('  atom        -- Generate ATOM test output and print it to stdout.')
		print_enc ('  rss         -- Generate RSS test output and print it to stdout.')
		print_enc ('  <file>.atom -- Generate ATOM test feed and write it to file.atom.')
		print_enc ('  <file>.rss  -- Generate RSS test teed and write it to file.rss.')
		print_enc ('  podcast     -- Generator Podcast test output and print it to stdout.')
		print_enc ('')
		exit()

	arg = sys.argv[1]

	fg = FeedGenerator()
	fg.id('http://lernfunk.de/_MEDIAID_123')
	fg.title('Testfeed')
	fg.author( {'name':'Lars Kiesow','email':'*****@*****.**'} )
	fg.link( href='http://example.com', rel='alternate' )
	fg.category(term='test')
	fg.contributor( name='Lars Kiesow', email='*****@*****.**' )
	fg.contributor( name='John Doe', email='*****@*****.**' )
	fg.icon('http://ex.com/icon.jpg')
	fg.logo('http://ex.com/logo.jpg')
	fg.rights('cc-by')
	fg.subtitle('This is a cool feed!')
	fg.link( href='http://larskiesow.de/test.atom', rel='self' )
	fg.language('de')
	fe = fg.add_entry()
	fe.id('http://lernfunk.de/_MEDIAID_123#1')
	fe.title('First Element')
	fe.content('''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Tamen
			aberramus a proposito, et, ne longius, prorsus, inquam, Piso, si ista
			mala sunt, placet. Aut etiam, ut vestitum, sic sententiam habeas aliam
			domesticam, aliam forensem, ut in fronte ostentatio sit, intus veritas
def main():
    if len(sys.argv) != 2 or not (
            sys.argv[1].endswith('rss') or sys.argv[1].endswith('atom')
            or sys.argv[1] == 'torrent' or sys.argv[1] == 'podcast'):
        print(USAGE)
        exit()

    arg = sys.argv[1]

    fg = FeedGenerator()
    fg.id('http://lernfunk.de/_MEDIAID_123')
    fg.title('Testfeed')
    fg.author({'name': 'Lars Kiesow', 'email': '*****@*****.**'})
    fg.link(href='http://example.com', rel='alternate')
    fg.category(term='test')
    fg.contributor(name='Lars Kiesow', email='*****@*****.**')
    fg.contributor(name='John Doe', email='*****@*****.**')
    fg.icon('http://ex.com/icon.jpg')
    fg.logo('http://ex.com/logo.jpg')
    fg.rights('cc-by')
    fg.subtitle('This is a cool feed!')
    fg.link(href='http://larskiesow.de/test.atom', rel='self')
    fg.language('de')
    fe = fg.add_entry()
    fe.id('http://lernfunk.de/_MEDIAID_123#1')
    fe.title('First Element')
    fe.content(
        '''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Tamen
            aberramus a proposito, et, ne longius, prorsus, inquam, Piso, si
            ista mala sunt, placet. Aut etiam, ut vestitum, sic sententiam
            habeas aliam domesticam, aliam forensem, ut in fronte ostentatio
            sit, intus veritas occultetur? Cum id fugiunt, re eadem defendunt,
            quae Peripatetici, verba.''')
    fe.summary(u'Lorem ipsum dolor sit amet, consectetur adipiscing elit…')
    fe.link(href='http://example.com', rel='alternate')
    fe.author(name='Lars Kiesow', email='*****@*****.**')

    if arg == 'atom':
        print_enc(fg.atom_str(pretty=True))
    elif arg == 'rss':
        print_enc(fg.rss_str(pretty=True))
    elif arg == 'podcast':
        # Load the podcast extension. It will automatically be loaded for all
        # entries in the feed, too. Thus also for our “fe”.
        fg.load_extension('podcast')
        fg.podcast.itunes_author('Lars Kiesow')
        fg.podcast.itunes_category('Technology', 'Podcasting')
        fg.podcast.itunes_explicit('no')
        fg.podcast.itunes_complete('no')
        fg.podcast.itunes_new_feed_url('http://example.com/new-feed.rss')
        fg.podcast.itunes_owner('John Doe', '*****@*****.**')
        fg.podcast.itunes_summary('Lorem ipsum dolor sit amet, consectetur ' +
                                  'adipiscing elit. Verba tu fingas et ea ' +
                                  'dicas, quae non sentias?')
        fe.podcast.itunes_author('Lars Kiesow')
        print_enc(fg.rss_str(pretty=True))

    elif arg == 'torrent':
        fg.load_extension('torrent')
        fe.link(href='http://example.com/torrent/debian-8-netint.iso.torrent',
                rel='alternate',
                type='application/x-bittorrent, length=1000')
        fe.torrent.filename('debian-8.4.0-i386-netint.iso.torrent')
        fe.torrent.infohash('7661229811ef32014879ceedcdf4a48f256c88ba')
        fe.torrent.contentlength('331350016')
        fe.torrent.seeds('789')
        fe.torrent.peers('456')
        fe.torrent.verified('123')
        print_enc(fg.rss_str(pretty=True))

    elif arg.startswith('dc.'):
        fg.load_extension('dc')
        fg.dc.dc_contributor('Lars Kiesow')
        if arg.endswith('.atom'):
            print_enc(fg.atom_str(pretty=True))
        else:
            print_enc(fg.rss_str(pretty=True))

    elif arg.startswith('syndication'):
        fg.load_extension('syndication')
        fg.syndication.update_period('daily')
        fg.syndication.update_frequency(2)
        fg.syndication.update_base('2000-01-01T12:00+00:00')
        if arg.endswith('.rss'):
            print_enc(fg.rss_str(pretty=True))
        else:
            print_enc(fg.atom_str(pretty=True))

    elif arg.endswith('atom'):
        fg.atom_file(arg)

    elif arg.endswith('rss'):
        fg.rss_file(arg)
Esempio n. 6
0
        print_enc("  podcast          -- Generate Podcast test output and print it to stdout.")
        print_enc("  dc.atom          -- Generate DC extension test output (atom format) and print it to stdout.")
        print_enc("  dc.rss           -- Generate DC extension test output (rss format) and print it to stdout.")
        print_enc("  syndication.atom -- Generate DC extension test output (atom format) and print it to stdout.")
        print_enc("  syndication.rss  -- Generate DC extension test output (rss format) and print it to stdout.")
        print_enc("")
        exit()

    arg = sys.argv[1]

    fg = FeedGenerator()
    fg.id("http://lernfunk.de/_MEDIAID_123")
    fg.title("Testfeed")
    fg.author({"name": "Lars Kiesow", "email": "*****@*****.**"})
    fg.link(href="http://example.com", rel="alternate")
    fg.category(term="test")
    fg.contributor(name="Lars Kiesow", email="*****@*****.**")
    fg.contributor(name="John Doe", email="*****@*****.**")
    fg.icon("http://ex.com/icon.jpg")
    fg.logo("http://ex.com/logo.jpg")
    fg.rights("cc-by")
    fg.subtitle("This is a cool feed!")
    fg.link(href="http://larskiesow.de/test.atom", rel="self")
    fg.language("de")
    fe = fg.add_entry()
    fe.id("http://lernfunk.de/_MEDIAID_123#1")
    fe.title("First Element")
    fe.content(
        """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Tamen
			aberramus a proposito, et, ne longius, prorsus, inquam, Piso, si ista
			mala sunt, placet. Aut etiam, ut vestitum, sic sententiam habeas aliam
Esempio n. 7
0
            '  dc.atom     -- Generate DC extension test output (atom format) and print it to stdout.'
        )
        print_enc(
            '  dc.rss      -- Generate DC extension test output (rss format) and print it to stdout.'
        )
        print_enc('')
        exit()

    arg = sys.argv[1]

    fg = FeedGenerator()
    fg.id('http://lernfunk.de/_MEDIAID_123')
    fg.title('Testfeed')
    fg.author({'name': 'Lars Kiesow', 'email': '*****@*****.**'})
    fg.link(href='http://example.com', rel='alternate')
    fg.category(term='test')
    fg.contributor(name='Lars Kiesow', email='*****@*****.**')
    fg.contributor(name='John Doe', email='*****@*****.**')
    fg.icon('http://ex.com/icon.jpg')
    fg.logo('http://ex.com/logo.jpg')
    fg.rights('cc-by')
    fg.subtitle('This is a cool feed!')
    fg.link(href='http://larskiesow.de/test.atom', rel='self')
    fg.language('de')
    fe = fg.add_entry()
    fe.id('http://lernfunk.de/_MEDIAID_123#1')
    fe.title('First Element')
    fe.content(
        '''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Tamen
			aberramus a proposito, et, ne longius, prorsus, inquam, Piso, si ista
			mala sunt, placet. Aut etiam, ut vestitum, sic sententiam habeas aliam
Esempio n. 8
0
    def write_rss(self, audio=False):
        """Write podcast feeds to files."""

        print("playlist self.info", flush=True)
        pp.pprint(self.info)

        prefix = "audio-" if audio else ""

        feed_url = self.controller.base_url + self.folder + '/' + prefix + 'podcast.xml'

        feedgen = FeedGenerator()
        feedgen.load_extension('podcast')

        feedgen.generator('Adafruit-Podcast')
        feedgen.id(feed_url)
        feedgen.title(self.info['title'])
        feedgen.subtitle(self.info['itunesSubtitle'])
        feedgen.author({'name': self.info['author']})
        for category in self.info['categories']:
            feedgen.category(term=category)
        feedgen.webMaster(self.info['webMaster'])
        feedgen.managingEditor(self.info['managingEditor'])
        feedgen.link(href=feed_url, rel='self')

        # Link to a chosen URL as an alternate, if set.
        if 'htmlUrl' in self.info:
            feedgen.link(href=self.info['htmlUrl'], rel='alternate')
        else:
            # Otherwise link to the original YouTube playlist as an alternate:
            if isinstance(self.url, list):
                for url in self.url:
                    feedgen.link(href=url, rel='alternate')
            else:
                feedgen.link(href=self.url, rel='alternate')

        feedgen.language('en')

        # feedgen.logo('http://ex.com/logo.jpg')

        # pylint: disable=no-member
        feedgen.podcast.itunes_category(self.info['itunesCategory']['text'])
        feedgen.podcast.itunes_subtitle(self.info['itunesSubtitle'])
        feedgen.podcast.itunes_summary(self.info['description'])
        feedgen.podcast.itunes_owner(email=self.info['itunesOwner']['email'],
                                     name=self.info['itunesOwner']['name'])
        feedgen.podcast.itunes_author(self.info['itunesOwner']['name'])
        feedgen.podcast.itunes_image(self.controller.base_url + self.folder +
                                     '/image.jpg')
        feedgen.podcast.itunes_explicit('clean')

        for vid in self.videos:
            print("vid:\n", flush=True)
            pp.pprint(vid)
            print("\n", flush=True)

            vid_filename = vid['_filename'].split('.')[0] + (".mp3" if audio
                                                             else ".mp4")

            vid_url = self.video_url(vid_filename)

            # Size of enclosed file in bytes:
            vid_size = os.path.getsize(vid_filename)

            # Date of upload (from the youtube-dl JSON data)
            eastern = pytz.timezone('US/Eastern')
            vid_date = eastern.localize(
                datetime.datetime.strptime(vid['upload_date'], '%Y%m%d'))

            entry = feedgen.add_entry()
            entry.id(vid_url)
            entry.title(vid['fulltitle'])
            entry.published(vid_date)
            for category in vid['categories']:
                entry.category(term=category)
            entry.description(vid['description'])
            entry.enclosure(vid_url, str(vid_size),
                            ('audio/mp3' if audio else 'video/mp4'))
            entry.podcast.itunes_image(self.controller.base_url + self.folder +
                                       '/image.jpg')

            entry.podcast.itunes_author(self.info['author'])
            entry.podcast.itunes_summary(vid['description'])
            entry.podcast.itunes_duration(vid['duration'])

        feedgen.rss_str(pretty=True)

        # Ensure output folder for this podcast exists:
        os.makedirs(os.path.join(self.controller.output_dir, self.folder),
                    exist_ok=True)

        # Generate RSS file in output folder:
        feedgen.rss_file(
            os.path.join(self.controller.output_dir, self.folder,
                         prefix + 'podcast.xml'))
Esempio n. 9
0
    def setUp(self):

        fg = FeedGenerator()

        self.nsAtom = "http://www.w3.org/2005/Atom"
        self.nsRss = "http://purl.org/rss/1.0/modules/content/"

        self.feedId = 'http://lernfunk.de/media/654321'
        self.title = 'Some Testfeed'

        self.authorName = 'John Doe'
        self.authorMail = '*****@*****.**'
        self.author = {'name': self.authorName, 'email': self.authorMail}

        self.linkHref = 'http://example.com'
        self.linkRel = 'alternate'

        self.logo = 'http://ex.com/logo.jpg'
        self.subtitle = 'This is a cool feed!'

        self.link2Href = 'http://larskiesow.de/test.atom'
        self.link2Rel = 'self'

        self.language = 'en'

        self.categoryTerm = 'This category term'
        self.categoryScheme = 'This category scheme'
        self.categoryLabel = 'This category label'

        self.cloudDomain = 'example.com'
        self.cloudPort = '4711'
        self.cloudPath = '/ws/example'
        self.cloudRegisterProcedure = 'registerProcedure'
        self.cloudProtocol = 'SOAP 1.1'

        self.icon = "http://example.com/icon.png"
        self.contributor = {
            'name': "Contributor Name",
            'uri': "Contributor Uri",
            'email': 'Contributor email'
        }
        self.copyright = "The copyright notice"
        self.docs = 'http://www.rssboard.org/rss-specification'
        self.managingEditor = '*****@*****.**'
        self.rating = '(PICS-1.1 "http://www.classify.org/safesurf/" ' + \
            '1 r (SS~~000 1))'
        self.skipDays = 'Tuesday'
        self.skipHours = 23

        self.textInputTitle = "Text input title"
        self.textInputDescription = "Text input description"
        self.textInputName = "Text input name"
        self.textInputLink = "Text input link"

        self.ttl = 900

        self.webMaster = '*****@*****.**'

        fg.id(self.feedId)
        fg.title(self.title)
        fg.author(self.author)
        fg.link(href=self.linkHref, rel=self.linkRel)
        fg.logo(self.logo)
        fg.subtitle(self.subtitle)
        fg.link(href=self.link2Href, rel=self.link2Rel)
        fg.language(self.language)
        fg.cloud(domain=self.cloudDomain,
                 port=self.cloudPort,
                 path=self.cloudPath,
                 registerProcedure=self.cloudRegisterProcedure,
                 protocol=self.cloudProtocol)
        fg.icon(self.icon)
        fg.category(term=self.categoryTerm,
                    scheme=self.categoryScheme,
                    label=self.categoryLabel)
        fg.contributor(self.contributor)
        fg.copyright(self.copyright)
        fg.docs(docs=self.docs)
        fg.managingEditor(self.managingEditor)
        fg.rating(self.rating)
        fg.skipDays(self.skipDays)
        fg.skipHours(self.skipHours)
        fg.textInput(title=self.textInputTitle,
                     description=self.textInputDescription,
                     name=self.textInputName,
                     link=self.textInputLink)
        fg.ttl(self.ttl)
        fg.webMaster(self.webMaster)
        fg.updated('2017-02-05 13:26:58+01:00')
        fg.pubDate('2017-02-05 13:26:58+01:00')
        fg.generator('python-feedgen', 'x', uri='http://github.com/lkie...')
        fg.image(url=self.logo,
                 title=self.title,
                 link=self.link2Href,
                 width='123',
                 height='123',
                 description='Example Inage')

        self.fg = fg
Esempio n. 10
0
def main():
    if len(sys.argv) != 2 or not (
            sys.argv[1].endswith('rss') or
            sys.argv[1].endswith('atom') or
            sys.argv[1] == 'torrent' or
            sys.argv[1] == 'podcast'):
        print(USAGE)
        exit()

    arg = sys.argv[1]

    fg = FeedGenerator()
    fg.id('http://lernfunk.de/_MEDIAID_123')
    fg.title('Testfeed')
    fg.author({'name': 'Lars Kiesow', 'email': '*****@*****.**'})
    fg.link(href='http://example.com', rel='alternate')
    fg.category(term='test')
    fg.contributor(name='Lars Kiesow', email='*****@*****.**')
    fg.contributor(name='John Doe', email='*****@*****.**')
    fg.icon('http://ex.com/icon.jpg')
    fg.logo('http://ex.com/logo.jpg')
    fg.rights('cc-by')
    fg.subtitle('This is a cool feed!')
    fg.link(href='http://larskiesow.de/test.atom', rel='self')
    fg.language('de')
    fe = fg.add_entry()
    fe.id('http://lernfunk.de/_MEDIAID_123#1')
    fe.title('First Element')
    fe.content('''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Tamen
            aberramus a proposito, et, ne longius, prorsus, inquam, Piso, si
            ista mala sunt, placet. Aut etiam, ut vestitum, sic sententiam
            habeas aliam domesticam, aliam forensem, ut in fronte ostentatio
            sit, intus veritas occultetur? Cum id fugiunt, re eadem defendunt,
            quae Peripatetici, verba.''')
    fe.summary(u'Lorem ipsum dolor sit amet, consectetur adipiscing elit…')
    fe.link(href='http://example.com', rel='alternate')
    fe.author(name='Lars Kiesow', email='*****@*****.**')

    if arg == 'atom':
        print_enc(fg.atom_str(pretty=True))
    elif arg == 'rss':
        print_enc(fg.rss_str(pretty=True))
    elif arg == 'podcast':
        # Load the podcast extension. It will automatically be loaded for all
        # entries in the feed, too. Thus also for our “fe”.
        fg.load_extension('podcast')
        fg.podcast.itunes_author('Lars Kiesow')
        fg.podcast.itunes_category('Technology', 'Podcasting')
        fg.podcast.itunes_explicit('no')
        fg.podcast.itunes_complete('no')
        fg.podcast.itunes_new_feed_url('http://example.com/new-feed.rss')
        fg.podcast.itunes_owner('John Doe', '*****@*****.**')
        fg.podcast.itunes_summary('Lorem ipsum dolor sit amet, consectetur ' +
                                  'adipiscing elit. Verba tu fingas et ea ' +
                                  'dicas, quae non sentias?')
        fe.podcast.itunes_author('Lars Kiesow')
        print_enc(fg.rss_str(pretty=True))

    elif arg == 'torrent':
        fg.load_extension('torrent')
        fe.link(href='http://example.com/torrent/debian-8-netint.iso.torrent',
                rel='alternate',
                type='application/x-bittorrent, length=1000')
        fe.torrent.filename('debian-8.4.0-i386-netint.iso.torrent')
        fe.torrent.infohash('7661229811ef32014879ceedcdf4a48f256c88ba')
        fe.torrent.contentlength('331350016')
        fe.torrent.seeds('789')
        fe.torrent.peers('456')
        fe.torrent.verified('123')
        print_enc(fg.rss_str(pretty=True))

    elif arg.startswith('dc.'):
        fg.load_extension('dc')
        fg.dc.dc_contributor('Lars Kiesow')
        if arg.endswith('.atom'):
            print_enc(fg.atom_str(pretty=True))
        else:
            print_enc(fg.rss_str(pretty=True))

    elif arg.startswith('syndication'):
        fg.load_extension('syndication')
        fg.syndication.update_period('daily')
        fg.syndication.update_frequency(2)
        fg.syndication.update_base('2000-01-01T12:00+00:00')
        if arg.endswith('.rss'):
            print_enc(fg.rss_str(pretty=True))
        else:
            print_enc(fg.atom_str(pretty=True))

    elif arg.endswith('atom'):
        fg.atom_file(arg)

    elif arg.endswith('rss'):
        fg.rss_file(arg)
Esempio n. 11
0
    def setUp(self):

        fg = FeedGenerator()

        self.nsAtom = "http://www.w3.org/2005/Atom"
        self.nsRss = "http://purl.org/rss/1.0/modules/content/"

        self.feedId = 'http://lernfunk.de/media/654321'
        self.title = 'Some Testfeed'

        self.authorName = 'John Doe'
        self.authorMail = '*****@*****.**'
        self.author = {'name': self.authorName, 'email': self.authorMail}

        self.linkHref = 'http://example.com'
        self.linkRel = 'alternate'

        self.logo = 'http://ex.com/logo.jpg'
        self.subtitle = 'This is a cool feed!'

        self.link2Href = 'http://larskiesow.de/test.atom'
        self.link2Rel = 'self'

        self.language = 'en'

        self.categoryTerm = 'This category term'
        self.categoryScheme = 'This category scheme'
        self.categoryLabel = 'This category label'

        self.cloudDomain = 'example.com'
        self.cloudPort = '4711'
        self.cloudPath = '/ws/example'
        self.cloudRegisterProcedure = 'registerProcedure'
        self.cloudProtocol = 'SOAP 1.1'

        self.icon = "http://example.com/icon.png"
        self.contributor = {'name': "Contributor Name",
                            'uri': "Contributor Uri",
                            'email': 'Contributor email'}
        self.copyright = "The copyright notice"
        self.docs = 'http://www.rssboard.org/rss-specification'
        self.managingEditor = '*****@*****.**'
        self.rating = '(PICS-1.1 "http://www.classify.org/safesurf/" ' + \
            '1 r (SS~~000 1))'
        self.skipDays = 'Tuesday'
        self.skipHours = 23

        self.textInputTitle = "Text input title"
        self.textInputDescription = "Text input description"
        self.textInputName = "Text input name"
        self.textInputLink = "Text input link"

        self.ttl = 900

        self.webMaster = '*****@*****.**'

        fg.id(self.feedId)
        fg.title(self.title)
        fg.author(self.author)
        fg.link(href=self.linkHref, rel=self.linkRel)
        fg.logo(self.logo)
        fg.subtitle(self.subtitle)
        fg.link(href=self.link2Href, rel=self.link2Rel)
        fg.language(self.language)
        fg.cloud(domain=self.cloudDomain, port=self.cloudPort,
                 path=self.cloudPath,
                 registerProcedure=self.cloudRegisterProcedure,
                 protocol=self.cloudProtocol)
        fg.icon(self.icon)
        fg.category(term=self.categoryTerm, scheme=self.categoryScheme,
                    label=self.categoryLabel)
        fg.contributor(self.contributor)
        fg.copyright(self.copyright)
        fg.docs(docs=self.docs)
        fg.managingEditor(self.managingEditor)
        fg.rating(self.rating)
        fg.skipDays(self.skipDays)
        fg.skipHours(self.skipHours)
        fg.textInput(title=self.textInputTitle,
                     description=self.textInputDescription,
                     name=self.textInputName, link=self.textInputLink)
        fg.ttl(self.ttl)
        fg.webMaster(self.webMaster)
        fg.updated('2017-02-05 13:26:58+01:00')
        fg.pubDate('2017-02-05 13:26:58+01:00')
        fg.generator('python-feedgen', 'x', uri='http://github.com/lkie...')
        fg.image(url=self.logo,
                 title=self.title,
                 link=self.link2Href,
                 width='123',
                 height='123',
                 description='Example Inage')

        self.fg = fg
Esempio n. 12
0
def _build_feed(id, lang, url, return_type=None):
	fg = None
	fg = FeedGenerator()
	fg.id(url)
	fg.link( href=url, rel='self' )
	req  = urllib2.Request('%s://%s:%i%sview/series/%s?with_name=true' % (
		app.config['LERNFUNK_CORE_PROTOCOL'],
		app.config['LERNFUNK_CORE_HOST'],
		app.config['LERNFUNK_CORE_PORT'],
		app.config['LERNFUNK_CORE_PATH'],
		id))
	req.add_header('Accept', 'application/json')
	u = urllib2.urlopen(req)
	try:
		series = json.loads(u.read())
	finally:
		u.close()
	s = series['result']['lf:series'][0]
	fg.title(s['dc:title'])
	fg.language(s['dc:language'])
	for cat in s['dc:subject']:
		fg.category( term=cat.lower(), label=cat )
	fg.description(s['dc:description'] or s['dc:title'])
	for name in s.get('lf:creator') or ['']:
		fg.author( name=name )

	# Get media
	req  = urllib2.Request('%s://%s:%i%sview/series/%s/media/%s%s' % (
		app.config['LERNFUNK_CORE_PROTOCOL'],
		app.config['LERNFUNK_CORE_HOST'],
		app.config['LERNFUNK_CORE_PORT'],
		app.config['LERNFUNK_CORE_PATH'],
		id,
		lang or '',
		'?with_file=1&with_name=1'))
	req.add_header('Accept', 'application/json')
	u = urllib2.urlopen(req)
	try:
		media = json.loads(u.read())
	finally:
		u.close()

	# Add media to feed
	for media in media['result']['lf:media']:
		fe = fg.add_entry()
		fe.id('%s/%s/%s' % (url, media['dc:identifier'], media['lf:version']))
		fe.title(media['dc:title'])
		for name in media.get('lf:creator') or ['']:
			fe.author( name=name )
			fg.contributor( name=name )
		for name in media.get('lf:contributor') or []:
			fe.contributor( name=name )
			fg.contributor( name=name )
		fe.content(media['dc:description'])
		is_av = lambda x: x.startswith('video') or x.startswith('audio')
		for file in media['lf:file']:
			fe.link( 
					href=file['lf:uri'], 
					rel=( 'enclosure' if is_av(file['dc:format']) else 'alternate' ),
					type=file['dc:format'] )
		fe.published(media['dc:date'] + ' +0')

	rssfeed  = fg.rss_str(pretty=False)
	atomfeed = fg.atom_str(pretty=False)

	# Podcast specific values
	fg.load_extension('podcast')

	podcast = fg.rss_str(pretty=False)

	r_server = get_redis()
	r_server.set('%slast_update_%s_%s' % (REDIS_NS, id, lang), int(time.time()))
	r_server.set('%srss_%s_%s'     % (REDIS_NS, id, lang), rssfeed)
	r_server.set('%satom_%s_%s'    % (REDIS_NS, id, lang), atomfeed)
	r_server.set('%spodcast_%s_%s' % (REDIS_NS, id, lang), podcast)

	if return_type == 'rss':
		return rssfeed
	if return_type == 'atom':
		return atomfeed
	if return_type == 'podcast':
		return podcast
Esempio n. 13
0
def generateRSS(type="", username=""):
    if type not in ["rss", "atom"]:
        raise ValueError(
            'Wrong Type of RSS Feed given to the generator, only "rss" and "atom" accepted.'
        )

    try:
        user = FeedUser.objects.get(username=username)
    except ObjectDoesNotExist:
        raise ValueError("The requested user ['" + username +
                         "'] doesn't exist.")

    try:
        max_rss_posts = int(
            Option.objects.get(parameter="max_rss_posts").value)
    except ObjectDoesNotExist:
        raise ValueError("The Option 'max_rss_posts' doesn't exist.")

    ########## ======================================== FEED GENERATION =========================================== ##########

    fg = FeedGenerator()
    fg.id('https://www.feedcrunch.io/@' + username + '/')
    fg.title('Feedcrunch.IO - @' + user.username + " - " + user.rss_feed_title)
    fg.subtitle(user.description)

    fg.link(href="https://www.feedcrunch.io/", rel='alternate')
    if type == "rss":
        fg.link(href='https://www.feedcrunch.io/@' + username + '/rss/',
                rel='self',
                type="application/rss+xml")
    else:
        fg.link(href='https://www.feedcrunch.io/@' + username + '/atom/',
                rel='self',
                type="application/atom+xml")

    fg.logo('https://www.feedcrunch.io/static/images/favicon.png')
    fg.icon('https://www.feedcrunch.io/static/images/favicon.png')

    for interest in user.interests.all():
        fg.category(term=interest.name)

    fg.language("en-us")
    fg.rights('cc-by')
    fg.author({'name': user.get_full_name(), 'email': user.email})

    last_post_date = Post.objects.filter(
        user=user.username).order_by("-when")[:1][0].when
    fg.lastBuildDate(last_post_date)

    # ======== Adding Posts to the Feed ======== #

    listPosts = Post.objects.filter(
        user=username, activeLink=True).order_by('-id')[:max_rss_posts]

    for post in listPosts:
        fe = fg.add_entry()
        #fe.id(post.link)
        fe.id('https://www.feedcrunch.io/@' + username + '/redirect/' +
              str(post.id))
        fe.title(post.title)
        fe.summary(post.title)
        """
        fe.content('''Lorem ipsum dolor sit amet, consectetur adipiscing elit. Tamen
            aberramus a proposito, et, ne longius, prorsus, inquam, Piso, si ista
            mala sunt, placet. Aut etiam, ut vestitum, sic sententiam habeas aliam
            domesticam, aliam forensem, ut in fronte ostentatio sit, intus veritas
            occultetur? Cum id fugiunt, re eadem defendunt, quae Peripatetici,
            verba.''', type="CDATA")
        """

        fe.link(href='https://www.feedcrunch.io/@' + username + '/redirect/' +
                str(post.id),
                rel='alternate')
        fe.author({'name': user.get_full_name(), 'email': user.email})
        fe.updated(post.when)

        #fe.category([{'term' : 'category', 'scheme': 'http://www.somedomain.com/category', 'label' : 'Category'}])
        for tag in post.tags.all():
            fe.category([{'term': tag.name}])

    return fg