Beispiel #1
0
def rss(_):
    """Returns the XML content of my RSS feed for the music part of the website.

    NOTE: We are doing no caching here at all right now, because this function is very fast and the website has
    no traffic. If this situation changes, then I should cache it so that I don't build this object from scratch every
    time."""
    generator = FeedGenerator()

    # Add basic metadata.
    generator.title("Paul's Music Feed")
    generator.author(name=MY_NAME, email=MY_EMAIL)
    generator.contributor(name=MY_NAME, email=MY_EMAIL)
    # RSS requires that we point to our own feed here. Not sure why.
    generator.link(href=(URL_ROOT + "rss"), rel="self")
    favicon_path = URL_ROOT + "static/favicon.png"
    generator.icon(favicon_path)
    generator.logo(favicon_path)
    generator.subtitle(
        "A feed for anyone who wants to know what albums I'm liking.")
    generator.language("en")

    albums = get_recent_music(quantity=30)
    for album in albums:
        entry = generator.add_entry()
        entry.title(album.name)
        path_to_album = URL_ROOT + "music/music/{}".format(album.id)
        entry.guid(path_to_album, permalink=True)
        entry.description(album.description())
        entry.updated(album.reviewed_at)
        entry.published(album.reviewed_at)
        entry.author(name=MY_NAME, email=MY_EMAIL)
        entry.link(href=path_to_album, rel="alternate")
        entry.category(term="score__{}".format(album.rating))

    return HttpResponse(generator.rss_str())
Beispiel #2
0
def feed(column_id):
    api = Api(column_id)

    with request.urlopen(api.info) as stream:
        result = stream.read().decode('utf-8')

    if not result:
        return '', 404

    info = json.loads(result)

    with request.urlopen(api.posts) as stream:
        result = stream.read().decode('utf-8')
        entries = json.loads(result)

    fg = FeedGenerator()
    fg.id(str(entries[0]['slug']))
    fg.title(info['name'])
    fg.language('zh_CN')
    fg.icon(info['avatar']['template'].replace('{id}', info['avatar']['id']).replace('{size}', 's'))
    fg.logo(info['avatar']['template'].replace('{id}', info['avatar']['id']).replace('{size}', 'l'))
    fg.description(info['intro'])
    fg.author(dict(name=info['creator']['name']))
    fg.link(href=api.base_url + info['url'], rel='alternate')
    for entry in entries:
        fe = fg.add_entry()
        fe.id(entry['url'])
        fe.title(entry['title'])
        fe.published(entry['publishedTime'])
        fe.updated(entry['publishedTime'])
        fe.author(dict(name=entry['author']['name']))
        fe.link(href=api.base_url + entry['url'], rel='alternate')
        fe.content(entry['content'])

    return fg.atom_str(pretty=True)
Beispiel #3
0
    def get(self):
        fg = FeedGenerator()
        fg.id("http://test.ts")
        fg.title("My Test Feed")
        fg.icon("https://avatars1.githubusercontent.com/u/715660?v=3&s=32")
        fg.author({'name': "The Author", 'email': "*****@*****.**"})

        fg.link(href="http://example.org/index.atom?page=2", rel="next")

        fg.link(href="http://test.ts", rel="alternate")
        fg.logo("https://avatars1.githubusercontent.com/u/715660?v=3&s=32")
        fg.description("Este é o monstro do lago 1")
        fg.subtitle("This is an example feed!")
        fg.language("en-us")
        # Handle this:
        #< sy:updatePeriod > hourly < / sy:updatePeriod >
        #< sy:updateFrequency > 1 < / sy:updateFrequency >

        fg.lastBuildDate(datetime.now(pytz.timezone("America/Sao_Paulo")))

        fi = fg.add_item()
        fi.id("http://test.ts/id/1", )
        #fi.link(link="http://test.ts/id/1")
        fi.title("Monstro do Lago 1")
        fi.description("Este é o monstro do lago 1")
        fi.comments("http://test.ts/id/1/comments")
        fi.pubdate(datetime.now(pytz.timezone("America/Sao_Paulo")))

        fi = fg.add_item()
        fi.id("http://test.ts/id/2")
        fi.title("Monstro do Lago 2")
        fi.description("Este é o monstro do lago 2")
        fi.pubdate(datetime.now(pytz.timezone("America/Sao_Paulo")))

        #test = fg.atom_str(pretty=True)

        rss_str = fg.rss_str(pretty=True)
        self.set_header("Content-Type", 'application/xml; charset="utf-8"')
        #self.set_header("Content-Disposition",
        # "attachment; filename='test.xml'")
        self.write(rss_str)


        #if regexp.search(word) is not None:
        #    print
        #    'matched'
        if self.is_browser_mobile():
            print("buu")
        else:
            print(self.request.headers["User-Agent"])
Beispiel #4
0
class Feed:
    def __init__(self, baseURL, audioDir):
        self.baseURL = baseURL
        self.dir = audioDir
        self.fg = FeedGenerator()
        self.fg.load_extension('podcast')
        self.fg.id(baseURL)
        self.fg.title('Yesterdays Baseball')
        self.fg.author(name='MLB')
        self.fg.link(href=baseURL, rel='alternate')
        self.fg.logo(
            'http://en.wikipedia.org/wiki/Major_League_Baseball_logo#/media/File:Major_League_Baseball.svg'
        )
        self.fg.icon(
            'http://en.wikipedia.org/wiki/Major_League_Baseball_logo#/media/File:Major_League_Baseball.svg'
        )
        self.fg.subtitle(
            "Awright, 'arry? See that ludicrous display last night?")
        self.fg.link(href=baseURL + 'podcast.xml', rel='self')
        self.fg.language('en')
        self.fg.podcast.itunes_explicit('no')
        self.fg.podcast.itunes_complete('no')
        self.fg.podcast.itunes_new_feed_url(baseURL + 'podcast.xml')
        self.fg.podcast.itunes_summary(
            "Awright, 'arry? See that ludicrous display last night?")
        self.addAllEntries()

    def __repr__(self):
        return self.fg.rss_str(pretty=True)

    def addAllEntries(self):
        for root, dirs, files in os.walk(self.dir):
            for f in files:
                if os.path.splitext(f)[1] in MIME_TYPES.keys():
                    self.addEntry(root, f)

    def addEntry(self, root, f):
        path = os.path.join(root, f)
        fileName, fileExtension = os.path.splitext(f)
        print "Adding...", path
        fe = self.fg.add_entry()
        fe.id(self.baseURL + f)
        mediafile = ID3(path)

        fe.title(mediafile['TIT2'].text[0] + " " + fileName)
        fe.summary(mediafile['TPE1'].text[0])
        fe.content(mediafile['TPE1'].text[0])

        fe.enclosure(self.baseURL + f, 0, MIME_TYPES[fileExtension])
Beispiel #5
0
    def get(self):
        fg = FeedGenerator()
        fg.id("http://test.ts")
        fg.title("My Test Feed")
        fg.icon("https://avatars1.githubusercontent.com/u/715660?v=3&s=32")
        fg.author({'name': "The Author", 'email': "*****@*****.**"})

        fg.link(href="http://example.org/index.atom?page=2", rel="next")

        fg.link(href="http://test.ts", rel="alternate")
        fg.logo("https://avatars1.githubusercontent.com/u/715660?v=3&s=32")
        fg.description("Este é o monstro do lago 1")
        fg.subtitle("This is an example feed!")
        fg.language("en-us")
        # Handle this:
        #< sy:updatePeriod > hourly < / sy:updatePeriod >
        #< sy:updateFrequency > 1 < / sy:updateFrequency >

        fg.lastBuildDate(datetime.now(pytz.timezone("America/Sao_Paulo")))

        fi = fg.add_item()
        fi.id("http://test.ts/id/1", )
        #fi.link(link="http://test.ts/id/1")
        fi.title("Monstro do Lago 1")
        fi.description("Este é o monstro do lago 1")
        fi.comments("http://test.ts/id/1/comments")
        fi.pubdate(datetime.now(pytz.timezone("America/Sao_Paulo")))

        fi = fg.add_item()
        fi.id("http://test.ts/id/2")
        fi.title("Monstro do Lago 2")
        fi.description("Este é o monstro do lago 2")
        fi.pubdate(datetime.now(pytz.timezone("America/Sao_Paulo")))

        #test = fg.atom_str(pretty=True)

        rss_str = fg.rss_str(pretty=True)
        self.set_header("Content-Type", 'application/xml; charset="utf-8"')
        #self.set_header("Content-Disposition",
        # "attachment; filename='test.xml'")
        self.write(rss_str)

        #if regexp.search(word) is not None:
        #    print
        #    'matched'
        if self.is_browser_mobile():
            print("buu")
        else:
            print(self.request.headers["User-Agent"])
Beispiel #6
0
class Feed:
  def __init__(self, baseURL, audioDir):
    self.baseURL = baseURL
    self.dir = audioDir
    self.fg = FeedGenerator()
    self.fg.load_extension('podcast')
    self.fg.id(baseURL)
    self.fg.title('Yesterdays Baseball')
    self.fg.author( name='MLB' )
    self.fg.link( href=baseURL, rel='alternate' )
    self.fg.logo('http://en.wikipedia.org/wiki/Major_League_Baseball_logo#/media/File:Major_League_Baseball.svg')
    self.fg.icon('http://en.wikipedia.org/wiki/Major_League_Baseball_logo#/media/File:Major_League_Baseball.svg')
    self.fg.subtitle("Awright, 'arry? See that ludicrous display last night?")
    self.fg.link( href=baseURL+'podcast.xml', rel='self' )
    self.fg.language('en')
    self.fg.podcast.itunes_explicit('no')
    self.fg.podcast.itunes_complete('no')
    self.fg.podcast.itunes_new_feed_url(baseURL+'podcast.xml')
    self.fg.podcast.itunes_summary("Awright, 'arry? See that ludicrous display last night?")
    self.addAllEntries()

  def __repr__(self):
    return self.fg.rss_str(pretty=True)

  def addAllEntries(self):
    for root, dirs, files in os.walk(self.dir):
      for f in files:
        if os.path.splitext(f)[1] in MIME_TYPES.keys(): 
          self.addEntry(root,f)

  def addEntry(self,root,f):
    path = os.path.join(root,f)
    fileName, fileExtension = os.path.splitext(f)
    print "Adding...",path
    fe = self.fg.add_entry()
    fe.id(self.baseURL+f)
    mediafile = ID3(path)

    fe.title(mediafile['TIT2'].text[0] + " " + fileName)
    fe.summary(mediafile['TPE1'].text[0])
    fe.content(mediafile['TPE1'].text[0])

    fe.enclosure(self.baseURL+f, 0, MIME_TYPES[fileExtension])
Beispiel #7
0
def feed(column_id):
    api = Api(column_id)

    with request.urlopen(api.info) as stream:
        result = stream.read().decode('utf-8')

    if not result:
        return '', 404

    info = json.loads(result)

    with request.urlopen(api.posts) as stream:
        result = stream.read().decode('utf-8')
        entries = json.loads(result)

    fg = FeedGenerator()
    fg.id(str(entries[0]['slug']))
    fg.title(info['name'])
    fg.language('zh_CN')
    fg.icon(info['avatar']['template'].replace('{id}',
                                               info['avatar']['id']).replace(
                                                   '{size}', 's'))
    fg.logo(info['avatar']['template'].replace('{id}',
                                               info['avatar']['id']).replace(
                                                   '{size}', 'l'))
    fg.description(info['intro'])
    fg.author(dict(name=info['creator']['name']))
    fg.link(href=api.base_url + info['url'], rel='alternate')
    for entry in entries:
        fe = fg.add_entry()
        fe.id(entry['url'])
        fe.title(entry['title'])
        fe.published(entry['publishedTime'])
        fe.updated(entry['publishedTime'])
        fe.author(dict(name=entry['author']['name']))
        fe.link(href=api.base_url + entry['url'], rel='alternate')
        fe.content(entry['content'])

    return fg.atom_str(pretty=True)
Beispiel #8
0
async def recent_episodes():
    logo_link = url_for('static', filename='favicon.png', _external=True)

    feed = FeedGenerator()
    feed.title('Arrowverse.info - Recent Episodes')
    feed.id(request.url_root)
    feed.link(href=request.url)
    feed.logo(logo_link)
    feed.icon(logo_link)
    feed.language('en')

    hide_shows_list = request.args.getlist('hide_show')

    newest_first_episode_list = get_full_series_episode_list(
        excluded_series=hide_shows_list)[::-1]

    for episode in newest_first_episode_list[:15]:
        title = '{series} - {episode_id} - {episode_name}'.format(**episode)
        content = '{series} {episode_id} {episode_name} will air on {air_date}'.format(
            **episode)
        show_dict = app.config['SHOW_DICT_WITH_NAMES'][episode['series']]
        data_source = f"{show_dict['root']}{show_dict['url']}"

        feed_entry = FeedEntry()
        feed_entry.id(data_source)
        feed_entry.link({'href': data_source})
        feed_entry.title(title)
        feed_entry.content(content, type='text')
        feed_entry.author(uri=show_dict['root'])

        feed.add_entry(feed_entry)

    response = await make_response(feed.atom_str(pretty=True))
    response.headers['Content-Type'] = 'application/atom+xml'

    return response
Beispiel #9
0
def newsfeed():
    def makedate(strdate):
        dt = datetime.datetime.strptime(strdate, '%Y-%m-%d %H:%M')
        return datetime.datetime(
            year=dt.year,
            month=dt.month,
            day=dt.day,
            hour=dt.hour,
            minute=dt.minute,
            tzinfo=datetime.timezone.utc,
        )

    news = load_news()
    feed = FeedGenerator()
    feed.icon(make_external('static/favicon.ico'))
    feed.id(request.url)
    feed.language('en-US')
    feed.link(href=make_external('news'))
    feed.link(href=request.url, rel='self')
    feed.title('The State of Taisei')
    feed.updated(makedate(news[0][0]))

    for article in news:
        date = makedate(article[0])
        url = make_external("/news/" + article[3])

        entry = feed.add_entry()
        entry.author(name='Taisei team')
        entry.content(article[2], type='html')
        entry.id(url)
        entry.link(href=make_external("/news/" + article[3]))
        entry.published(date)
        entry.title(article[1])
        entry.updated(date)

    return Response(feed.atom_str(), mimetype='text/xml')
Beispiel #10
0
def hello():
    base = 'http://www.interpressnews.ge/ge/'
    headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; JHR Build/98234) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.95 Mobile Safari/537.36'}
    r = requests.get(base, headers=headers)
    r.encoding = 'utf-8'
    soup = BeautifulSoup(r.text, 'lxml')

    a_list = []

    items = soup.find(id='mobile_topnews').find_all(class_='topnews_content')
    for item in items:
        a = my_item(item, base)
        a_list.append(a)

    fg = FeedGenerator()
    fg.id('http://lernfunk.de/media/654321')
    fg.title('Some Testfeed')
    fg.author( {'name':'John Doe','email':'*****@*****.**'} )
    fg.link( href='http://goo.gl/OzZCmm', rel='alternate' )
    fg.icon('https://goo.gl/vsNdil')
    fg.subtitle('This is a cool feed!')
    fg.link( href='http://larskiesow.de/test.atom', rel='self' )
    fg.language('ge')

    for a in a_list:
        fe = fg.add_entry()
        fe.id(str(hash(a.get('title', ''))))
        fe.title(a.get('title', 'EMPTY'))
        fe.content('COMING SOON', type='text')
        fe.summary('COMING SOON')
        fe.link(href=a.get('link', ''), type='text/html')
        fe.author( {'name':'John Doe','email':'*****@*****.**'} )
        fe.updated(datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%dT%H:%M:%SZ'))

    atomfeed = fg.atom_str(pretty=True)
    return atomfeed
Beispiel #11
0
            '  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
			domesticam, aliam forensem, ut in fronte ostentatio sit, intus veritas
			occultetur? Cum id fugiunt, re eadem defendunt, quae Peripatetici,
			verba.''')
Beispiel #12
0
                    out.write(chunk)
            download.release_conn()
            print("done!")
            good_count += 1

fg = FeedGenerator()
fg.load_extension('podcast')
fg.title("Live From Here (Unofficial Full Episode Feed)")
fg.link(href="https://raw.githubusercontent.com/slacy/lfhrss/master/lfh.rss",
        rel='self')
fg.description("Live From Here (Unofficial Full Episode Feed)")
fg.image('https://raw.githubusercontent.com/slacy/lfhrss/master/lfh.png',
         width=400,
         height=400)
fg.logo('https://raw.githubusercontent.com/slacy/lfhrss/master/lfh_450.png')
fg.icon('https://raw.githubusercontent.com/slacy/lfhrss/master/lfh.png')
fg.podcast.itunes_image(
    'https://raw.githubusercontent.com/slacy/lfhrss/master/lfh.png')
fg.podcast.itunes_explicit("no")

for year in years:
    for month in months:
        for day in days:
            vars = {'year': year, 'month': month, 'day': day}
            url = "https://download.stream.publicradio.org/livefromhere/{year:04d}/{month:02d}/{day:02d}/lfh_{year:04d}{month:02d}{day:02d}.mp3".format(
                **vars)
            cachefile = "cache/{year:04d}_{month:02d}_{day:02d}".format(**vars)
            if not os.path.exists(cachefile):
                continue
            s = os.path.getsize(cachefile)
            if s < 1000:
Beispiel #13
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
Beispiel #14
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
Beispiel #15
0
class Feed:
    def __init__(self,
                 url: str,
                 name: str,
                 email: str,
                 title: str = None,
                 generator: str = None,
                 generator_version: str = None,
                 logo: str = None,
                 icon: str = None,
                 description: str = None,
                 language: str = None) -> None:
        self.name = name
        self.email = email

        self.fg = FeedGenerator()
        self.fg.id(url + "feed.atom")
        self.fg.link(href=url + "feed.xml", rel="self")
        self.fg.link(href=url, rel="alternate")
        self.fg.author(name=name, email=email)
        self.fg.contributor(name=name, email=email)
        self.fg.managingEditor(email)
        self.fg.webMaster(email)

        self.fg.title(title)
        self.fg.generator(generator=generator, version=generator_version)
        self.fg.logo(logo)
        self.fg.icon(icon)
        self.fg.description(description)
        self.fg.language(language)

    def add(self, article: Article) -> None:
        feed_entry = self.fg.add_entry()
        feed_entry.id(article.url)
        feed_entry.title(article.title)
        feed_entry.link(href=article.url)
        feed_entry.guid(guid=article.url, permalink=True)
        feed_entry.author(name=self.name, email=self.email)
        feed_entry.summary(article.description or article.snippet)
        feed_entry.content(content=article.content, type="CDATA")
        feed_entry.published(article.date)
        if article.date:
            feed_entry.published(article.date)
            feed_entry.updated(article.date)
        else:
            epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
            feed_entry.published(epoch)
            feed_entry.updated(epoch)

    def add_from_blog(self, url: str) -> None:
        blog = Blog(url)
        if not self.fg.title():
            self.fg.title(blog.title)
        for article in blog.articles:
            self.add(article)

    def atom(self) -> bytes:
        return self.fg.atom_str(pretty=True)

    def rss(self) -> bytes:
        return self.fg.rss_str(pretty=True)

    def atom_file(self, filename: str = "feed.atom") -> None:
        self.fg.atom_file(filename, pretty=True)

    def rss_file(self, filename: str = "feed.xml") -> None:
        self.fg.rss_file(filename, pretty=True)
Beispiel #16
0
        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
			domesticam, aliam forensem, ut in fronte ostentatio sit, intus veritas
			occultetur? Cum id fugiunt, re eadem defendunt, quae Peripatetici,
			verba."""
Beispiel #17
0
    print("Cannot load the list of PR content: HTTP %s received!" %  response.status_code)
    sys.exit(1)
pull_requests = response.json()

# Process the obtained list and generate the feed in memory
print("[+] Process the obtained list and generate the feed in memory (%s) items)..." % len(pull_requests))
feed_generator = FeedGenerator()
current_date = datetime.utcnow().strftime("%a, %d %B %Y %H:%M:%S GMT")  # Sun, 19 May 2002 15:21:36 GMT
feed_generator.id("https://cheatsheetseries.owasp.org/")
feed_generator.title("OWASP Cheat Sheet Series update")
feed_generator.description("List of the last updates on the content")
feed_generator.author({"name": "Core team", "email": "*****@*****.**"})
feed_generator.link({"href": "https://cheatsheetseries.owasp.org", "rel": "self"})
feed_generator.link({"href": "https://github.com/OWASP/CheatSheetSeries", "rel": "alternate"})
feed_generator.language("en")
feed_generator.icon("https://cheatsheetseries.owasp.org/gitbook/images/favicon.ico")
feed_generator.pubDate(current_date)
feed_generator.lastBuildDate(current_date)
for pull_request in pull_requests:
    # Take only merged PR
    if pull_request["merged_at"] is None:
        continue
    # Convert merge date from 2019-08-25T06:36:35Z To Sun, 19 May 2002 15:21:36 GMT
    merge_date_src = pull_request["merged_at"]
    merge_date_dst = datetime.strptime(merge_date_src, "%Y-%m-%dT%H:%M:%SZ").strftime("%a, %d %B %Y %H:%M:%S GMT")
    feed_entry = feed_generator.add_entry()
    feed_entry.id(pull_request["html_url"])
    feed_entry.title(pull_request["title"])
    feed_entry.link({"href": pull_request["html_url"], "rel": "self"})
    feed_entry.link({"href": pull_request["html_url"], "rel": "alternate"})
    feed_entry.pubDate(merge_date_dst)
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)
Beispiel #19
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)
Beispiel #20
0
		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
			occultetur? Cum id fugiunt, re eadem defendunt, quae Peripatetici,
			verba.''')
	fe.summary('Lorem ipsum dolor sit amet, consectetur adipiscing elit...')
Beispiel #21
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