"""Logic Tier for Podcast Links."""
import re
from podcast.constants import error
from podcast.constants import stores as podcast_stores
from podcast.constants.feature_flag import FEATURE_PODCAST_IA_RESTRUCTURE
from podcast.logic import user as user_logic
from podcast.logic import user_v2 as user_v2_logic
from podcast.models import podcast as podcast_model
from podcast.models import podcast_links as podcast_links_model
from podcast.utils import feature_flag_utils
from podcast.utils.exc import OwsError
def get_stores():
"""Get all stores."""
return podcast_links_model.get_stores()
def get_podcast_links(podcast_id):
"""Get all podcast links."""
podcast = podcast_model.get_podcast_by_id(podcast_id)
if feature_flag_utils.get_feature_flag(FEATURE_PODCAST_IA_RESTRUCTURE):
user_v2_logic.current_user_owns_show_family_or_raise(podcast['show_family_id'])
else:
user_logic.current_user_owns_podcast_or_raise(podcast)
return podcast_links_model.get_podcast_links(podcast_id)
def create_podcast_links(data):
"""Create podcast links."""
user_logic.current_user_is_org_admin_or_raise()
apple_store_id = None
embed_code_store_id = None
apple_link = None
embed_code_link = None
stores = get_stores()['items']
for store in stores:
if store['name'] == podcast_stores.APPLE_PODCAST:
apple_store_id = store['id']
if store['name'] == podcast_stores.WEBSITE_EMBED_CODE:
embed_code_store_id = store['id']
for index, link in enumerate(data['links']):
if link['store_id'] == apple_store_id:
apple_link = link['link']
if link['store_id'] == embed_code_store_id:
embed_code_link = data['links'].pop(index)['link']
if apple_link:
apple_id = re.search('[^/]+(?=/$|$)', apple_link).group(0).replace('id', '').replace('?uo=4', '')
podcast_model.update_podcast(data['podcast_id'], {'apple_id': apple_id})
else:
podcast_model.update_podcast(data['podcast_id'], {'apple_id': None})
if embed_code_link:
if re.match('^https?://playlist?.megaphone?.fm\\?p=SONY[0-9]{10}$', embed_code_link):
iframe_link = ''.format(
embed_code_link)
data['links'].append({'store_id': embed_code_store_id, 'link': iframe_link})
else:
raise OwsError.bad_request(error.ERROR_MESSAGE_INVALID_EMBED_CODE)
return podcast_links_model.create_podcast_links(data)
def create_new_podcast_links(podcast_id, guid):
"""Create website embed on new podcast."""
store_id = podcast_links_model.get_website_embed_store()['id']
url = 'https://playlist.megaphone.fm?p={}'.format(guid)
link = ''.format(url)
podcast_links_model.create_podcast_link(
{'podcast_id': podcast_id, 'store_id': store_id, 'link': link})