def episode(self, show, episode_dict): # Find the publication date publication_datetime_str = str(episode_dict['dato']) + " 00:00:00" publication_datetime_format = "%Y%m%d %H:%M:%S" # Start out with midnight publication_date = datetime.datetime.strptime( publication_datetime_str, publication_datetime_format) # Then go to the specified time publication_datetime_naive = \ publication_date + datetime.timedelta(seconds=episode_dict['time']) # And associate a timezone with that datetime timezone = pytz.timezone("Europe/Oslo") publication_datetime_aware = \ timezone.localize(publication_datetime_naive) # Create our episode object return Episode( show=show, media=Media(episode_dict['url'], episode_dict['filesize'], None, datetime.timedelta(seconds=episode_dict['duration'])), id="radiorevolt.no/podkast/episode/" + str(episode_dict['id']), deprecated_url=episode_dict['deprecated_url'], title=episode_dict['title'], long_summary=linkify(htmlencode(episode_dict['comment'])).replace( "\n", "<br/>\n"), publication_date=publication_datetime_aware, authors=[Person(name=episode_dict['author'])] if episode_dict['author'] else [], )
def episode(self, show, episode_dict): # Find the publication date publication_datetime_str = str(episode_dict['dato']) + " 00:00:00" publication_datetime_format = "%Y%m%d %H:%M:%S" # Start out with midnight publication_date = datetime.datetime.strptime( publication_datetime_str, publication_datetime_format ) # Then go to the specified time publication_datetime_naive = \ publication_date + datetime.timedelta(seconds=episode_dict['time']) # And associate a timezone with that datetime timezone = pytz.timezone("Europe/Oslo") publication_datetime_aware = \ timezone.localize(publication_datetime_naive) # Create our episode object return Episode( show=show, media=Media( episode_dict['url'], episode_dict['filesize'], None, datetime.timedelta(seconds=episode_dict['duration']) ), id="radiorevolt.no/podkast/episode/" + str(episode_dict['id']), deprecated_url=episode_dict['deprecated_url'], title=episode_dict['title'], long_summary=linkify(htmlencode(episode_dict['comment'])) .replace("\n", "<br/>\n"), publication_date=publication_datetime_aware, authors=[Person(name=episode_dict['author'])] if episode_dict['author'] else [], )
def main(): """Create an example podcast and print it or save it to a file.""" # There must be exactly one argument, and it is must end with rss if len(sys.argv) != 2 or not ( sys.argv[1].endswith('rss')): # Invalid usage, print help message # print_enc is just a custom function which functions like print, # except it deals with byte arrays properly. print_enc ('Usage: %s ( <file>.rss | rss )' % \ 'python -m podgen') print_enc ('') print_enc (' rss -- Generate RSS test output and print it to stdout.') print_enc (' <file>.rss -- Generate RSS test teed and write it to file.rss.') print_enc ('') exit() # Remember what type of feed the user wants arg = sys.argv[1] from podgen import Podcast, Person, Media, Category, htmlencode # Initialize the feed p = Podcast() p.name = 'Testfeed' p.authors.append(Person("Lars Kiesow", "*****@*****.**")) p.website = 'http://example.com' p.copyright = 'cc-by' p.description = 'This is a cool feed!' p.language = 'de' p.feed_url = 'http://example.com/feeds/myfeed.rss' p.category = Category('Technology', 'Podcasting') p.explicit = False p.complete = False p.new_feed_url = 'http://example.com/new-feed.rss' p.owner = Person('John Doe', '*****@*****.**') p.xslt = "http://example.com/stylesheet.xsl" e1 = p.add_episode() e1.id = 'http://lernfunk.de/_MEDIAID_123#1' e1.title = 'First Element' e1.summary = htmlencode('''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 <3.''') e1.link = 'http://example.com' e1.authors = [Person('Lars Kiesow', '*****@*****.**')] e1.publication_date = datetime.datetime(2014, 5, 17, 13, 37, 10, tzinfo=pytz.utc) e1.media = Media("http://example.com/episodes/loremipsum.mp3", 454599964, duration= datetime.timedelta(hours=1, minutes=32, seconds=19)) # Should we just print out, or write to file? if arg == 'rss': # Print print_enc(p.rss_str()) elif arg.endswith('rss'): # Write to file p.rss_file(arg, minimize=True)
def test_summariesHtml(self): self.fe.summary = "A <b>cool</b> summary" d = self.fe.rss_entry().find("description") assert d is not None assert "A <b>cool</b> summary" == d.text self.fe.summary = htmlencode("A <b>cool</b> summary") d = self.fe.rss_entry().find("description") assert d is not None assert "A <b>cool</b> summary" == d.text
def read_podcast_feed(podcast_id: int, db: Session = Depends(get_db)): db_podcast = utils.get_podcast(db, podcast_id) if db_podcast is None: raise HTTPException(status_code=404, detail="Podcast not found") p = podgen.Podcast( name=db_podcast.name, website=PUBLIC_URL, description=db_podcast.description, explicit=db_podcast.explicit, ) for db_episode in db_podcast.episodes: force_type = None try: file_extension = urlparse( db_episode.url).path.split(".")[-1].lower() if file_extension == "opus": force_type = "audio/ogg" elif file_extension == "wav": force_type = "audio/wav" except: pass p.episodes.append( podgen.Episode( summary=podgen.htmlencode(db_episode.summary), long_summary=podgen.htmlencode(db_episode.long_summary), title=db_episode.title, subtitle=db_episode.subtitle, media=podgen.Media( url=db_episode.url, size=db_episode.size, duration=db_episode.duration, type=force_type, ), )) return Response(p.rss_str(), headers={"Content-Type": "application/rss+xml"})
def pafy_download(url): if not url: url = "https://www.youtube.com/watch?v=-z4NS2zdrZc" # Here is to the Crazy Ones pafy.set_api_key("AIzaSyD5Q22HSOEJKYaNkObyb_38o_gLx24qu5Y") video = pafy.new(url) # print(f"videoid: {video.videoid}") # print(f"title: {video.title}") # print(f"description: {video.description}") # print(f"thumb: {video.thumb}") # print(f"duration: {video.duration}") # print(f"length: {video.length}") # print(f"author: {video.author}") # print(f"published: {video.published}") # print(f"rating: {video.rating}") # print(f"view count: {video.viewcount}") # print(f"likes: {video.likes}") # print(f"dislikes: {video.dislikes}") # print(f"keywords: {video.keywords}") download = VideoEpisode(title = video.title, description = video.description, subtitle = video.description, summary = htmlencode(video.description), video_id = video.videoid, author = video.author, image_url = video.thumb, published = video.published, keywords = video.keywords, media_size = globals()['filesize'], media_duration = video.length, position = 0, media_url = "https://cdn.listenbox.app/a/u4diDOUjKM4.m4a" ) print(download) create_rss(type="feed.xml", download=download)
def generate_podcast(self, feed_name: str) -> str: """ Create podcast XML based on the files found in podcastDir. Taken from https://podgen.readthedocs.io/en/latest/usage_guide/podcasts.html :param self: PodcastService class :param feed_name: name of the feed and the sub-directory for files :return: string of the podcast """ # Initialize the feed p = Podcast() # Required fields p.name = f'{feed_name} Archive' p.description = 'Stuff to listen to later' p.website = self.base_url p.complete = False # Optional p.language = 'en-US' p.feed_url = f'{p.website}/feeds/{feed_name}/rss' p.explicit = False p.authors.append(Person("Anthology")) # for filepath in glob.iglob(f'{self.search_dir}/{feed_name}/*.mp3'): for path in Path(f'{self.search_dir}/{feed_name}').glob('**/*.mp3'): filepath = str(path) episode = p.add_episode() # Attempt to load saved metadata metadata_file_name = filepath.replace('.mp3', '.json') try: with open(metadata_file_name) as metadata_file: metadata = json.load(metadata_file) except FileNotFoundError: metadata = {} except JSONDecodeError: metadata = {} self.logger.error(f'Failed to read {metadata_file_name}') # Build the episode based on either the saved metadata or the file details episode.title = metadata.get( 'title', filepath.split('/')[-1].rstrip('.mp3')) episode.summary = metadata.get('summary', htmlencode('Some Summary')) if 'link' in metadata: episode.link = metadata.get('link') if 'authors' in metadata: episode.authors = [ Person(author) for author in metadata.get('authors') ] episode.publication_date = \ isoparse(metadata.get('publication_date')) if 'publication_date' in metadata \ else datetime.fromtimestamp(os.path.getmtime(filepath), tz=pytz.utc) episode.media = Media( f'{p.website}/{filepath.lstrip(self.search_dir)}'.replace( ' ', '+'), os.path.getsize(filepath)) episode.media.populate_duration_from(filepath) if "image" in metadata: episode.image = metadata.get('image') else: for ext in ['.jpg', '.png']: image_file_name = filepath.replace('.mp3', ext) if os.path.isfile(image_file_name): episode.image = f'{p.website}/{image_file_name.lstrip(self.search_dir)}'.replace( ' ', '+') break # Save the metadata for future editing if not os.path.exists(metadata_file_name): metadata = { 'title': episode.title, 'summary': episode.summary, 'publication_date': episode.publication_date, 'authors': episode.authors } with open(metadata_file_name, 'w') as outFile: json.dump(metadata, outFile, indent=2, default=str) return p.rss_str()
def create_rss(type, download): """Create an example podcast and print it or save it to a file.""" # Create the Podcast & initialize the feed default_channel = Channel.defaultChannel() p = Podcast() p.name = default_channel.name p.description = default_channel.description p.website = default_channel.website p.explicit = default_channel.explicit p.image = default_channel.image p.copyright = default_channel.copyright p.language = default_channel.language p.feed_url = default_channel.feed_url p.category = Category(default_channel.category) # p.category = Category('Technology', 'Podcasting') # p.xslt = "https://example.com/feed/stylesheet.xsl" # URL of XSLT stylesheet p.authors = [Person(default_channel.authors, default_channel.authors_email)] p.owner = Person(default_channel.owner, default_channel.owner_email) # Other Attributes p.generator = " " # Others for iTunes # p.complete = False # p.new_feed_url = 'http://example.com/new-feed.rss' # e1 = p.add_episode() # e1.id = 'http://lernfunk.de/_MEDIAID_123#1' # e1.title = 'First Element' # e1.summary = htmlencode('''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 <3.''') # e1.link = 'http://example.com' # e1.authors = [Person('Lars Kiesow', '*****@*****.**')] # e1.publication_date = datetime.datetime(2014, 5, 17, 13, 37, 10, tzinfo=pytz.utc) # # e1.media = Media("http://example.com/episodes/loremipsum.mp3", 454599964, # # duration= # # datetime.timedelta(hours=1, minutes=32, seconds=19)) # e1.media = Media("http://example.com/episodes/loremipsum.mp3", 454599964) # Add some episodes p.episodes += [ Episode(title = download.title, subtitle = download.subtitle, # id=str(uuid.uuid4()), position =2, media = Media(download.media_url, size=download.media_size, duration=timedelta(seconds=download.media_duration)), image = download.image_url, publication_date = datetime(year=2021, month=1, day=8, hour=10, minute=0, tzinfo=pytz.utc), summary = download.summary) , Episode(title="Episode 2 - The Crazy Ones", subtitle="this is a cool episode, this is for th crazy ones", position=1, image="https://github.com/oliverbarreto/PersonalPodcast/raw/main/site-logo-1400x1400.png", media=Media("https://github.com/oliverbarreto/PersonalPodcast/raw/main/downloaded_with_pytube_Apple%20Steve%20Jobs%20Heres%20To%20The%20Crazy%20Ones.mp4", type="audio/mpeg", size=989, duration=timedelta(hours=0, minutes=1, seconds=1)), publication_date = datetime(year=2021, month=1, day=6, hour=10, minute=0, tzinfo=pytz.utc), summary=htmlencode("wow wow wow summary")) , Episode(title="Episode 3 - The Super Crazy", subtitle="crazy ones revisited", position=0, image="https://github.com/oliverbarreto/PersonalPodcast/raw/main/site-logo-1400x1400.png", media=Media("https://drive.google.com/file/d/1X5Mwa8V0Su1IDqhcQL7LdzEY0VaMC1Nn", type="audio/mpeg", size=989, duration=timedelta(hours=0, minutes=1, seconds=1)), publication_date = datetime(year=2021, month=1, day=10, hour=10, minute=0, tzinfo=pytz.utc), summary=download.summary) ] # Should we just print out, or write to file? if type == 'print': # Print print_enc(p.rss_str()) elif type== 'feed.xml': # Write to file p.rss_file(type, minimize=False) print("\n") print("feed.xml created !!!")