Esempio n. 1
0
def forgot_password_finish(req):
    if not req.user.is_anonymous():
        return redirect('dashboard')

    # Protection against the forces of evil
    sig = req.POST.get('__sig')
    email = req.POST.get('email')
    try:
        h = signer.unsign(sig, max_age=1800)
        if h != email:
            raise Exception()
    except Exception:
        return get_expired_page(req)

    try:
        user = User.objects.get(email=email)
    except User.DoesNotExist:
        return redirect('login')

    passwd = req.POST.get('password')
    if passwd != req.POST.get('confirm'):
        err = ugettext("You didn't type the same password twice.")
        return redirect(
            get_signed_url(
                reverse('forgot_password_finalize') +
                '?email=%s&error=%s' % (
                    urlencode(email),
                    urlencode(err))
            )
        )

    user.set_password(passwd)
    user.save()

    return redirect(reverse('login') + '?success=resetpassword')
Esempio n. 2
0
def add_blog_post(req, podcast_slug):
    site = get_site(req, podcast_slug)

    if not payment_plans.minimum(
            UserSettings.get_from_user(site.podcast.owner).plan,
            payment_plans.FEATURE_MIN_BLOG):
        raise Http404()

    try:
        publis_parsed = datetime.datetime.strptime(
            req.POST.get('publish', '').split('.')[0], '%Y-%m-%dT%H:%M:%S')
        post = SiteBlogPost(
            site=site,
            title=req.POST.get('title'),
            slug=req.POST.get('slug'),
            body=req.POST.get('body'),
            publish=publis_parsed,
            disable_comments=req.POST.get('disable_comments') == 'true')
        post.save()
    except Exception as e:
        print(e)
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '?error=sblog#site,blog')
    else:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '#site,blog')
Esempio n. 3
0
def new_collaborator(req, podcast_slug):
    pod = get_podcast(req, podcast_slug)
    if pod.owner != req.user and not req.user.is_staff:
        raise Http404

    try:
        user = User.objects.get(email__iexact=req.POST.get('email'))
    except User.DoesNotExist:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '?collaberr=collab_dne#settings,collabs')

    if req.user == user:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '?collaberr=yourself#settings,collabs')

    if Collaborator.objects.filter(collaborator=user, podcast=pod).count():
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '#settings,collabs')

    c = Collaborator(podcast=pod, collaborator=user)
    c.save()

    return redirect(
        reverse('podcast_dashboard', podcast_slug=podcast_slug) +
        '#settings,collabs')
Esempio n. 4
0
def _handle_failed_tip_sub(body):
    sub = _get_tip_subscription(body)
    if not sub: return {'warning': 'subscription unrecognized'}

    closed = body['data']['object']['closed']
    pod = sub.podcast
    if closed:
        sub.deactivated = True
        sub.save()

        send_notification_email(
            None,
            ugettext('Your subscription to %s was cancelled') % pod.name,
            ugettext('We attempted to charge your card for your '
                     'subscription to %s, but the payment failed multiple '
                     'times. If you wish to remain subscribed, please '
                     'visit the link below to enter new payment '
                     'information.\n\n%s') %
            (pod.name, BASE_URL + reverse('tip_jar', podcast_slug=pod.slug)),
            email=sub.tipper.email_address)

        return {'success': 'nastygram sent, subscription deactivated'}
    else:
        send_notification_email(
            None,
            ugettext('Your subscription to %s has problems') % pod.name,
            ugettext('We attempted to charge your card for your '
                     'subscription to %s, but the payment failed. Please '
                     'visit the tip jar and update your subscription with '
                     'new card details as soon as possible. You can do that '
                     'at the link below.\n\n%s') %
            (pod.name, BASE_URL + reverse('tip_jar', podcast_slug=pod.slug)),
            email=sub.tipper.email_address)

        return {'success': 'nastygram sent'}
Esempio n. 5
0
def new_site(req, podcast_slug):
    pod = get_podcast(req, podcast_slug)

    if not payment_plans.minimum(
            UserSettings.get_from_user(pod.owner).plan,
            payment_plans.FEATURE_MIN_SITES):
        raise Http404()

    try:
        site = Site(
            podcast=pod,
            theme=req.POST.get('theme'),
            cover_image_url=signer.unsign(req.POST.get('cover-url'))
            if req.POST.get('cover-url') else None,
            logo_url=signer.unsign(req.POST.get('logo-url'))
            if req.POST.get('logo-url') else None,
            analytics_id=req.POST.get('analytics_id'),
            itunes_url=req.POST.get('itunes_url'),
            stitcher_url=req.POST.get('stitcher_url'),
            show_itunes_banner=req.POST.get('show_itunes_banner') == 'true')
        site.save()
    except Exception as e:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '?error=true#site')
    else:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#site')
Esempio n. 6
0
def edit_site(req, podcast_slug):
    site = get_site(req, podcast_slug)
    try:
        site.theme = req.POST.get('theme')
        site.cover_image_url = signer.unsign(
            req.POST.get('cover-url')) if req.POST.get('cover-url') else None
        site.logo_url = signer.unsign(
            req.POST.get('logo-url')) if req.POST.get('logo-url') else None
        site.analytics_id = req.POST.get('analytics_id')
        site.itunes_url = req.POST.get('itunes_url')
        site.stitcher_url = req.POST.get('stitcher_url')
        site.show_itunes_banner = req.POST.get('show_itunes_banner') == 'true'
        site.custom_css = req.POST.get('custom_css')
        site.custom_cname = req.POST.get('custom_cname')

        us = UserSettings.get_from_user(site.podcast.owner)
        if payment_plans.minimum(us.plan, payment_plans.FEATURE_MIN_BLOG):
            site.disqus_url = req.POST.get('disqus_url')
        if payment_plans.minimum(us.plan,
                                 payment_plans.FEATURE_MIN_SITE_FAVICON):
            site.favicon_url = signer.unsign(req.POST.get(
                'favicon-url')) if req.POST.get('favicon-url') else None

        site.save()
    except Exception as e:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '?error=true#settings,site-options')
    else:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '#settings,site-options')
Esempio n. 7
0
def network_add_member(req, network_id):
    net = get_object_or_404(Network,
                            deactivated=False,
                            id=network_id,
                            members__in=[req.user])

    try:
        user = User.objects.get(email=req.POST.get('email'))
    except User.DoesNotExist:
        return redirect(
            reverse('network_dashboard', network_id=network_id) +
            '?error=udne#members,add-member')

    net.members.add(user)
    net.save()
    pinecast.email.send_notification_email(
        user,
        ugettext('[Pinecast] You have been added to "%s"') % net.name,
        ugettext('''
We are emailing you to let you know that you were added to the network
"%s". No action is required on your part. If you log in to Pinecast,
you will now have read and write access to all of the podcasts in the
network, and will be able to add your own podcasts to the network.
        ''') % net.name)

    return redirect(
        reverse('network_dashboard', network_id=net.id) + '#members')
Esempio n. 8
0
def set_coupon(req):
    code = req.POST.get('coupon')
    try:
        coupon = stripe.Coupon.retrieve(code)
    except stripe.error.InvalidRequestError:
        return redirect(reverse('upgrade') + '?coupon_invalid')

    if not coupon.valid:
        return redirect(reverse('upgrade') + '?coupon_invalid')

    if 'owner_id' in coupon.metadata:
        us = UserSettings.get_from_user(req.user)
        if us.plan != payment_plans.PLAN_DEMO:
            return redirect(reverse('upgrade') + '?coupon_unavailable')

        try:
            cust = us.get_stripe_customer()
        except Exception:
            pass
        else:
            if len(stripe.Invoice.list(customer=cust.id, limit=1).data):
                return redirect(reverse('upgrade') + '?coupon_unavailable')

    req.session['coupon'] = code
    return redirect(reverse('upgrade') + '?coupon_applied')
Esempio n. 9
0
def _handle_failed_tip_sub(body):
    sub = _get_tip_subscription(body)
    if not sub: return {'warning': 'subscription unrecognized'}

    closed = body['data']['object']['closed']
    pod = sub.podcast
    if closed:
        sub.deactivated = True
        sub.save()

        send_notification_email(
            None,
            ugettext('Your subscription to %s was cancelled') % pod.name,
            ugettext('We attempted to charge your card for your '
                     'subscription to %s, but the payment failed multiple '
                     'times. If you wish to remain subscribed, please '
                     'visit the link below to enter new payment '
                     'information.\n\n%s') %
                (pod.name, BASE_URL + reverse('tip_jar', podcast_slug=pod.slug)),
            email=sub.tipper.email_address)

        return {'success': 'nastygram sent, subscription deactivated'}
    else:
        send_notification_email(
            None,
            ugettext('Your subscription to %s has problems') % pod.name,
            ugettext('We attempted to charge your card for your '
                     'subscription to %s, but the payment failed. Please '
                     'visit the tip jar and update your subscription with '
                     'new card details as soon as possible. You can do that '
                     'at the link below.\n\n%s') %
                (pod.name, BASE_URL + reverse('tip_jar', podcast_slug=pod.slug)),
            email=sub.tipper.email_address)

        return {'success': 'nastygram sent'}
Esempio n. 10
0
def forgot_password_finish(req):
    if not req.user.is_anonymous():
        return redirect('dashboard')

    # Protection against the forces of evil
    sig = req.POST.get('__sig')
    email = req.POST.get('email')
    try:
        h = signer.unsign(sig, max_age=1800).decode('utf-8')
        if h != email:
            raise Exception()
    except Exception:
        return get_expired_page(req)

    try:
        user = User.objects.get(email=email)
    except User.DoesNotExist:
        return redirect('login')

    passwd = req.POST.get('password')
    if passwd != req.POST.get('confirm'):
        err = ugettext("You didn't type the same password twice.")
        return redirect(
            get_signed_url(
                reverse('forgot_password_finalize') + '?email=%s&error=%s' %
                (urlencode(email), urlencode(err))))

    user.set_password(passwd)
    user.save()

    return redirect(reverse('login') + '?success=resetpassword')
Esempio n. 11
0
def user_settings_page_changeemail(req):
    if User.objects.filter(email=req.POST.get('new_email')).count():
        return redirect(reverse('dashboard') + '?error=eae#settings')
    send_confirmation_email(
        req.user, ugettext('[Pinecast] Email change confirmation'),
        ugettext('''
Someone requested a change to your email address on Pinecast. This email is
to verify that you own the email address provided.
'''),
        reverse('user_settings_change_email_finalize') + '?user=%s&email=%s' %
        (urlencode(str(req.user.id)), urlencode(req.POST.get('new_email'))),
        req.POST.get('new_email'))
    return redirect(reverse('dashboard') + '?success=em#settings')
Esempio n. 12
0
def network_add_show(req, network_id):
    net = get_object_or_404(Network, deactivated=False, id=network_id, members__in=[req.user])
    slug = req.POST.get('slug')
    try:
        pod = Podcast.objects.get(slug=slug)
    except Podcast.DoesNotExist:
        return redirect(reverse('network_dashboard', network_id=net.id) + '?error=aslg#shows,add-show')
    else:
        if pod.owner != req.user:
            return redirect(reverse('network_dashboard', network_id=net.id) + '?error=nown#shows,add-show')
        pod.networks.add(net)
        pod.save()
    return redirect('network_dashboard', network_id=net.id)
Esempio n. 13
0
def add_link(req, podcast_slug):
    site = get_site(req, podcast_slug)

    try:
        url = req.POST.get('url')
        if not url.startswith('http://') and not url.startswith('https://'):
            raise Exception('Invalid scheme')

        SiteLink(site=site, title=req.POST.get('title'), url=url).save()
    except Exception as e:
        return redirect(reverse('podcast_dashboard', podcast_slug=podcast_slug) + '?error=slink#settings,site-options')
    else:
        return redirect(reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#settings,site-options')
Esempio n. 14
0
    def get_link(self, data):
        link = reverse('podcast_dashboard', podcast_slug=self.podcast.slug)
        if self.trigger == 'feedback':
            if data.get('episode'):
                link = reverse('podcast_episode',
                               podcast_slug=self.podcast.slug,
                               episode_id=str(
                                   data['episode'].id)) + '#feedback'
            else:
                link += '#feedback'
        elif self.trigger == 'tip':
            link += '#tips'

        return 'https://pinecast.com' + link
Esempio n. 15
0
def delete_comment(req, podcast_slug, comment_id):
    pod = get_podcast(req, podcast_slug)
    comment = get_object_or_404(Feedback, podcast=pod, id=comment_id)

    ep = comment.episode
    comment.delete()
    if ep:
        return redirect(
            reverse('podcast_episode', podcast_slug=podcast_slug, episode_id=str(ep.id)) + '#tab-feedback'
        )
    else:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#tab-feedback'
        )
Esempio n. 16
0
def delete_comment(req, podcast_slug, comment_id):
    pod = get_podcast(req, podcast_slug)
    comment = get_object_or_404(Feedback, podcast=pod, id=comment_id)

    ep = comment.episode
    comment.delete()
    if ep:
        return redirect(
            reverse('podcast_episode', podcast_slug=podcast_slug, episode_id=str(ep.id)) + '#tab-feedback'
        )
    else:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#tab-feedback'
        )
Esempio n. 17
0
def user_settings_page_changeemail(req):
    if User.objects.filter(email=req.POST.get('new_email')).count():
        return redirect(reverse('user_settings') + '?error=eae')
    send_confirmation_email(
        req.user,
        ugettext('[Pinecast] Email change confirmation'),
        ugettext('''
Someone requested a change to your email address on Pinecast. This email is
to verify that you own the email address provided.
'''),
        reverse('user_settings_change_email_finalize') + '?user=%s&email=%s' % (
            urlencode(req.user.id), urlencode(req.POST.get('new_email'))),
        req.POST.get('new_email')
    )
    return redirect(reverse('user_settings') + '?success=em')
Esempio n. 18
0
    def _exec_webhook(self, data):
        body = {
            'summary': self.get_summary(data),
            'link': self.get_link(data),
            'podcast': {
                'name': self.podcast.name,
                'slug': self.podcast.slug,
                'url': reverse('podcast_dashboard',
                               podcast_slug=self.podcast.slug),
                'feed_url': reverse('feed', podcast_slug=self.podcast.slug),
            },
            'type': self.trigger,
        }

        def get_ep_obj():
            id_ = str(data['episode'].id)
            return {
                'id':
                id_,
                'title':
                data['episode'].title,
                'url':
                reverse('podcast_episode',
                        podcast_slug=self.podcast.slug,
                        episode_id=id_),
                'listen_url':
                reverse('listen', episode_id=id_),
                'player_url':
                reverse('player', episode_id=id_),
                'publish':
                data['episode'].publish.isoformat(),
            }

        if self.trigger == 'tip':
            body.update(tipper=data['tipper'], amount=data['amount'])
        elif self.trigger == 'feedback':
            body.update(content=data['content'])
            if data.get('episode'):
                body.update(episode=get_ep_obj())
        elif self.trigger == 'first_listen':
            body.update(episode=get_ep_obj())
        elif self.trigger == 'listen_threshold':
            body.update(episode=get_ep_obj(), threshold=int(self.condition))
        elif self.trigger == 'growth_milestone':
            body.update(listens=int(data['listens']),
                        milestone=_next_ms(data['before_listens']))

        requests.post(self.destination, timeout=5, json=body)
Esempio n. 19
0
def forgot_password(req):
    if not req.user.is_anonymous():
        return redirect('dashboard')

    if not req.POST:
        return render(req, 'forgot_password.html')

    try:
        user = User.objects.get(email=req.POST.get('email'))
    except User.DoesNotExist:
        user = None

    if user and user.is_active:
        send_confirmation_email(
            user, ugettext('[Pinecast] Password reset'),
            ugettext('''
We received a request to reset the password for your Pinecast account. If you
do not want to reset your password, please ignore this email.
'''),
            reverse('forgot_password_finalize') +
            '?email=%s' % urlencode(user.email))
        return render(req, 'forgot_password_success.html')
    return render(
        req, 'forgot_password.html',
        {'error': ugettext("We don't recognize that email address.")})
Esempio n. 20
0
def _auth_subscription(req, podcast, amount):
    email = req.POST.get('email')
    token = req.POST.get('token')

    if not email:
        return {'error': ugettext('No valid email address was found.')}

    # Create the tip user if it doesn't already exist
    tipper = TipUser.tip_user_from(email_address=email)

    if tipper.id == req.session.get('pay_session'):
        try:
            _finish_sub(req, podcast, amount, email, token)
            return {'success': True, 'status': 'complete'}
        except Exception as e:
            pass

    send_email(
        email,
        ugettext('Confirm your subscription for %s') % podcast.name,
        ugettext(
            'Thanks for pledging your support for %s at $%0.2f every month! '
            'To finish the process and activate your subscription, click the '
            'link below. The link in this email will expire after one day.\n\n'
            'If you did not request this, you can ignore this email.' %
            (podcast.name, float(amount) / 100)),
        reverse('tip_jar_confirm_sub', podcast_slug=podcast.slug) +
        '?email=%s&token=%s&amount=%d' % (quote(email), quote(token), amount))

    return {'success': True, 'status': 'pending'}
Esempio n. 21
0
def delete_page(req, podcast_slug, page_slug):
    site = get_site(req, podcast_slug)
    page = get_object_or_404(SitePage, site=site, slug=page_slug)
    page.delete()

    return redirect(
        reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#site')
Esempio n. 22
0
def edit_blog_post(req, podcast_slug, post_slug):
    site = get_site(req, podcast_slug)
    post = get_object_or_404(SiteBlogPost, site=site, slug=post_slug)

    if not req.POST:
        return _pmrender(req, 'dashboard/sites/blog/page_edit.html', {
            'site': site,
            'post': post
        })
    try:
        naive_publish = datetime.datetime.strptime(
            req.POST.get('publish', '').split('.')[0],
            '%Y-%m-%dT%H:%M:%S')  # 2015-07-09T12:00
        adjusted_publish = naive_publish - UserSettings.get_from_user(
            req.user).get_tz_delta()
        post.title = req.POST.get('title')
        post.slug = req.POST.get('slug')
        post.body = req.POST.get('body')
        post.publish = adjusted_publish
        post.disable_comments = req.POST.get('disable_comments') == 'true'
        post.save()
    except Exception as e:
        data.update(error=True, default=req.POST)
        return _pmrender(req, 'dashboard/sites/blog/page_edit.html', data)
    else:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '#site,blog')
Esempio n. 23
0
def subscriptions_login(req):
    email = req.GET.get('email', req.POST.get('email'))
    if req.GET.get(CONFIRMATION_PARAM):
        validated = validate_confirmation(req)
        if validated:
            try:
                tip_user = TipUser.objects.get(email_address=email)
            except TipUser.DoesNotExist:
                # Verified because they just confirmed their email
                tip_user = TipUser(email=email, verified=True)
                tip_user.save()

            req.session['pay_session'] = tip_user.id
            return redirect('tip_jar_subs')
        # fallthrough

    if not req.POST:
        return _pmrender(req, 'payments/tip_jar/login.html')

    send_email(
        req.POST.get('email'),
        ugettext('Podcast Tip Jar - Email Verification'),
        ugettext(
            'Thanks for verifying your email! Click the link below '
            'to see your podcast subscriptions.'),
        reverse('tip_jar_login') + '?email=%s' % quote(email))

    return _pmrender(req, 'payments/tip_jar/check_email.html')
Esempio n. 24
0
def _auth_subscription(req, podcast, amount):
    email = req.POST.get('email')
    token = req.POST.get('token')

    if not email:
        return {'error': ugettext('No valid email address was found.')}

    # Create the tip user if it doesn't already exist
    tipper = TipUser.tip_user_from(email_address=email)

    if tipper.id == req.session.get('pay_session'):
        try:
            _finish_sub(req, podcast, amount, email, token)
            return {'success': True, 'status': 'complete'}
        except Exception as e:
            pass

    send_email(
        email,
        ugettext('Confirm your subscription for %s') % podcast.name,
        ugettext(
            'Thanks for pledging your support for %s at $%0.2f every month! '
            'To finish the process and activate your subscription, click the '
            'link below. The link in this email will expire after one day.\n\n'
            'If you did not request this, you can ignore this email.' %
            (podcast.name, float(amount) / 100)),
        reverse('tip_jar_confirm_sub', podcast_slug=podcast.slug) +
        '?email=%s&token=%s&amount=%d' % (quote(email), quote(token), amount))

    return {'success': True, 'status': 'pending'}
Esempio n. 25
0
def subscriptions_login(req):
    email = req.GET.get('email', req.POST.get('email'))
    if req.GET.get(CONFIRMATION_PARAM):
        validated = validate_confirmation(req)
        if validated:
            try:
                tip_user = TipUser.objects.get(email_address=email)
            except TipUser.DoesNotExist:
                # Verified because they just confirmed their email
                tip_user = TipUser(email=email, verified=True)
                tip_user.save()

            req.session['pay_session'] = tip_user.id
            return redirect('tip_jar_subs')
        # fallthrough

    if not req.POST:
        return _pmrender(req, 'payments/tip_jar/login.html')

    send_email(
        req.POST.get('email'),
        ugettext('Podcast Tip Jar - Email Verification'),
        ugettext(
            'Thanks for verifying your email! Click the link below '
            'to see your podcast subscriptions.'),
        reverse('tip_jar_login') + '?email=%s' % quote(email))

    return _pmrender(req, 'payments/tip_jar/check_email.html')
Esempio n. 26
0
def test_notification(req):
    podcast = _get_podcast(req, id=req.POST.get('podcast'))
    notification = get_object_or_404(NotificationHook, podcast=podcast, id=req.POST.get('id'))

    notification.send_test()

    return redirect(reverse('podcast_dashboard', podcast_slug=podcast.slug) + '?notification_sent=true#settings,notifications')
Esempio n. 27
0
    def get_html_description(self, is_demo=None):
        raw = self.description
        if is_demo is None:
            us = UserSettings.get_from_user(self.podcast.owner)
            is_demo = us.plan == payment_plans.PLAN_DEMO
        available_flags = self.podcast.get_available_flair_flags(flatten=True)

        if self.flair_tip_jar and FLAIR_TIP_JAR in available_flags:
            raw += "\n\nSupport %s by donating to the [tip jar](https://pinecast.com/payments/tips/%s)." % (
                self.podcast.name,
                self.podcast.slug,
            )

        if self.flair_site_link and FLAIR_SITE_LINK in available_flags:
            raw += "\n\nFind out more at [%s](http://%s.pinecast.co)." % (self.podcast.name, self.podcast.slug)

        if self.flair_feedback and FLAIR_FEEDBACK in available_flags:
            prompt = self.get_feedback_prompt()
            fb_url = "https://pinecast.com%s" % reverse(
                "ep_comment_box", podcast_slug=self.podcast.slug, episode_id=str(self.id)
            )
            raw += "\n\n%s [%s](%s)" % (prompt, fb_url, fb_url)

        if is_demo or self.flair_powered_by and FLAIR_SITE_LINK in available_flags:
            raw += "\n\nThis podcast is powered by " "[Pinecast](https://pinecast.com)."

        markdown = gfm.markdown(raw)
        return sanitize(markdown)
Esempio n. 28
0
def delete_site(req, podcast_slug):
    try:
        site = get_site(req, podcast_slug)
        site.delete()
    except Exception:
        pass
    return redirect(reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#site')
Esempio n. 29
0
def podcast_top_episodes(req, pod):
    timeframe = req.GET.get('timeframe')
    if not timeframe:
        return None

    tz = UserSettings.get_from_user(req.user).tz_offset
    top_ep_data = query.get_top_episodes(str(pod.id), timeframe, tz)
    episodes = PodcastEpisode.objects.filter(id__in=list(top_ep_data.keys()))
    mapped = {str(ep.id): ep for ep in episodes}

    # This step is necessary to filter out deleted episodes, since deleted episodes
    # are not removed from the analytics data.
    top_ep_data = {k: v for k, v in top_ep_data.items() if k in mapped}

    # Sort the top episode data descending
    return [[ugettext('Episode'), ugettext('Count')]] + [[
        {
            'href':
            reverse('podcast_episode', podcast_slug=pod.slug,
                    episode_id=ep_id),
            'title':
            mapped[ep_id].title,
        },
        count,
    ] for ep_id, count in list(
        reversed(sorted(top_ep_data.items(), key=lambda x: x[1])))[:25]]
Esempio n. 30
0
    def get_html_description(self, is_demo=None):
        raw = self.description
        if is_demo is None:
            us = UserSettings.get_from_user(self.podcast.owner)
            is_demo = us.plan == payment_plans.PLAN_DEMO
        available_flags = self.podcast.get_available_flair_flags(flatten=True)

        if (self.flair_tip_jar and FLAIR_TIP_JAR in available_flags):
            raw += '\n\nSupport %s by donating to the [tip jar](https://pinecast.com/payments/tips/%s).' % (
                self.podcast.name, self.podcast.slug)

        if (self.flair_site_link and FLAIR_SITE_LINK in available_flags):
            raw += '\n\nFind out more at [%s](http://%s.pinecast.co).' % (
                self.podcast.name, self.podcast.slug)

        if (self.flair_feedback and FLAIR_FEEDBACK in available_flags):
            prompt = self.get_feedback_prompt()
            fb_url = 'https://pinecast.com%s' % reverse(
                'ep_comment_box',
                podcast_slug=self.podcast.slug,
                episode_id=str(self.id))
            raw += '\n\n%s [%s](%s)' % (prompt, fb_url, fb_url)

        if (is_demo or self.flair_powered_by
                and FLAIR_SITE_LINK in available_flags):
            raw += ('\n\nThis podcast is powered by '
                    '[Pinecast](https://pinecast.com).')

        markdown = gfm.markdown(raw)
        return sanitize(markdown)
Esempio n. 31
0
def delete_site(req, podcast_slug):
    try:
        site = get_site(req, podcast_slug)
        site.delete()
    except Exception:
        pass
    return redirect(
        reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#site')
Esempio n. 32
0
def upgrade_set_plan(req):
    new_plan = req.POST.get('plan')
    if new_plan not in AVAILABLE_PLANS:
        return redirect('upgrade')

    new_plan_val = AVAILABLE_PLANS[new_plan]

    us = UserSettings.get_from_user(req.user)
    result = us.set_plan(new_plan_val, req.session.get('coupon'))

    if not result:
        return redirect('upgrade')
    elif result == 'card_error':
        return redirect(reverse('upgrade') + '?error=card')
    else:
        req.session['coupon'] = None
        return redirect(reverse('upgrade') + '?success')
Esempio n. 33
0
def add_link(req, podcast_slug):
    site = get_site(req, podcast_slug)

    try:
        url = req.POST.get('url')
        if not url.startswith('http://') and not url.startswith('https://'):
            raise Exception('Invalid scheme')

        SiteLink(site=site, title=req.POST.get('title'), url=url).save()
    except Exception as e:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '?error=slink#site,links')
    else:
        return redirect(
            reverse('podcast_dashboard', podcast_slug=podcast_slug) +
            '#site,links')
Esempio n. 34
0
def remove_link(req, podcast_slug):
    site = get_site(req, podcast_slug)
    try:
        link = SiteLink.objects.get(id=req.POST.get('id'), site=site)
        link.delete()
    except Exception:
        pass
    return redirect(reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#settings,site-options')
Esempio n. 35
0
def upgrade_set_plan(req):
    new_plan = req.POST.get('plan')
    if new_plan not in AVAILABLE_PLANS:
        return redirect('upgrade')

    new_plan_val = AVAILABLE_PLANS[new_plan]

    us = UserSettings.get_from_user(req.user)
    result = us.set_plan(new_plan_val, req.session.get('coupon'))

    if not result:
        return redirect('upgrade')
    elif result == 'card_error':
        return redirect(reverse('upgrade') + '?error=card')
    else:
        req.session['coupon'] = None
        return redirect(reverse('upgrade') + '?success')
Esempio n. 36
0
def new_notification(req):
    podcast = _get_podcast(req, id=req.POST.get('podcast'))
    if podcast.notifications.count() > NOTIFICATION_LIMIT:
        return redirect(reverse('podcast_dashboard', podcast_slug=podcast.slug) + '#settings,notifications')

    dest_type = req.POST.get('destination_type')
    dest = req.POST.get('destination_%s' % dest_type)
    trigger = req.POST.get('trigger')
    nh = NotificationHook(
        podcast=podcast,
        destination_type=dest_type,
        destination=dest,
        trigger=trigger,
        condition=req.POST.get('threshold') if trigger == 'listen_threshold' else None)
    nh.save()

    return redirect(reverse('podcast_dashboard', podcast_slug=podcast.slug) + '#settings,notifications')
Esempio n. 37
0
 def get_ep_obj():
     id_ = str(data['episode'].id)
     return {
         'id':
         id_,
         'title':
         data['episode'].title,
         'url':
         reverse('podcast_episode',
                 podcast_slug=self.podcast.slug,
                 episode_id=id_),
         'listen_url':
         reverse('listen', episode_id=id_),
         'player_url':
         reverse('player', episode_id=id_),
         'publish':
         data['episode'].publish.isoformat(),
     }
Esempio n. 38
0
def remove_blog_post(req, podcast_slug):
    site = get_site(req, podcast_slug)
    post = get_object_or_404(SiteBlogPost,
                             site=site,
                             slug=req.POST.get('slug'))

    post.delete()
    return redirect(
        reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#site,blog')
Esempio n. 39
0
def user_settings_page_changepassword(req):
    if req.POST.get('new_password') != req.POST.get('confirm_password'):
        return redirect(reverse('dashboard') + '?error=pwc#settings')
    if not req.user.check_password(req.POST.get('old_password')):
        return redirect(reverse('dashboard') + '?error=pwo#settings')
    if len(req.POST.get('new_password')) < 8:
        return redirect(reverse('dashboard') + '?error=pwl#settings')

    req.user.set_password(req.POST.get('new_password'))
    req.user.save()

    send_notification_email(
        req.user, ugettext('[Pinecast] Password changed'),
        ugettext('''
Your Pinecast password has been updated. If you did not request this change,
please contact Pinecast support as soon as possible at
[email protected].
'''))
    return redirect(reverse('login'))
Esempio n. 40
0
def remove_link(req, podcast_slug):
    site = get_site(req, podcast_slug)
    try:
        link = SiteLink.objects.get(id=req.POST.get('id'), site=site)
        link.delete()
    except Exception:
        pass
    return redirect(
        reverse('podcast_dashboard', podcast_slug=podcast_slug) +
        '#settings,site-options')
Esempio n. 41
0
def sitemap(req, podcast_slug):
    pod = get_object_or_404(Podcast, slug=podcast_slug)
    site = get_object_or_404(models.Site, podcast=pod)

    output = """<?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    """

    pages = pod.podcastepisode_set.all().count()
    for i in xrange(pages):
        output += """
        <url>
            <loc>{url}</loc>
            <changefreq>weekly</changefreq>
        </url>
        """.format(
            url="%s?page=%d" % (reverse("site_home", podcast_slug=pod.slug), i + 1)
        )

    output += """
    <url><loc>{url}</loc></url>
    """.format(
        url=reverse("site_blog", podcast_slug=pod.slug)
    )

    for episode in pod.podcastepisode_set.all():
        output += """
        <url><loc>{url}</loc></url>
        """.format(
            url=reverse("site_episode", podcast_slug=pod.slug, episode_id=str(episode.id))
        )

    for post in site.siteblogpost_set.all():
        output += """
        <url><loc>{url}</loc></url>
        """.format(
            url=reverse("site_post", podcast_slug=pod.slug, post_slug=post.slug)
        )

    output += "</urlset>"

    return HttpResponse(output, content_type="application/xml")
Esempio n. 42
0
def network_add_show(req, network_id):
    net = get_object_or_404(Network,
                            deactivated=False,
                            id=network_id,
                            members__in=[req.user])
    slug = req.POST.get('slug')
    try:
        pod = Podcast.objects.get(slug=slug)
    except Podcast.DoesNotExist:
        return redirect(
            reverse('network_dashboard', network_id=net.id) +
            '?error=aslg#shows,add-show')
    else:
        if pod.owner != req.user:
            return redirect(
                reverse('network_dashboard', network_id=net.id) +
                '?error=nown#shows,add-show')
        pod.networks.add(net)
        pod.save()
    return redirect('network_dashboard', network_id=net.id)
Esempio n. 43
0
def _handle_failed_subscription(body):
    customer = body['data']['object']['customer']
    try:
        us = UserSettings.objects.get(stripe_customer_id=customer)
    except UserSettings.DoesNotExist:
        rollbar.report_message('Unknown customer: %s' % customer, 'warn')
        return {'warning': 'customer unrecognized'}

    closed = body['data']['object']['closed']
    user = us.user
    if closed:
        us.set_plan(payment_plans.PLAN_DEMO)
        send_notification_email(
            user,
            ugettext('Your Pinecast subscription was cancelled.'),
            ugettext('Pinecast attempted to charge your payment card multiple '
                     'times, but was unable to collect payment. Your '
                     'account has been downgraded to a free Demo plan. Only '
                     'the ten most recent episodes from each of your podcasts '
                     'will be shown to your listeners. All recurring tip '
                     'subscriptions to your podcasts have also been '
                     'cancelled.\n\nNo content or settings have been deleted '
                     'from your account. If you wish to re-subscribe, you may '
                     'do so at any time at the URL below.\n\n%s') %
                (BASE_URL + reverse('upgrade')))

        return {'success': 'nastygram sent, account downgraded'}
    else:
        send_notification_email(
            user,
            ugettext('Payment failed for Pinecast subscription'),
            ugettext('Pinecast attempted to charge your payment card for your '
                     'current subscription, but was unable to collect payment. '
                     'If we fail to process your card three times, your '
                     'account will automatically be downgraded to a free Demo '
                     'plan.\n\n'
                     'No changes have currently been made to your account or '
                     'plan. Please update your payment information at the URL '
                     'below.\n\n%s') %
                (BASE_URL + reverse('dashboard') + '#settings,subscription'))
        return {'success': 'nastygram sent'}
Esempio n. 44
0
def user_settings_page_changepassword(req):
    if req.POST.get('new_password') != req.POST.get('confirm_password'):
        return redirect(reverse('user_settings') + '?error=pwc')
    if not req.user.check_password(req.POST.get('old_password')):
        return redirect(reverse('user_settings') + '?error=pwo')
    if len(req.POST.get('new_password')) < 8:
        return redirect(reverse('user_settings') + '?error=pwl')

    req.user.set_password(req.POST.get('new_password'))
    req.user.save()

    send_notification_email(
        req.user,
        ugettext('[Pinecast] Password changed'),
        ugettext('''
Your Pinecast password has been updated. If you did not request this change,
please contact Pinecast support as soon as possible at
[email protected].
''')
    )
    return redirect(reverse('login'))
Esempio n. 45
0
def _handle_failed_subscription(body):
    customer = body['data']['object']['customer']
    try:
        us = UserSettings.objects.get(stripe_customer_id=customer)
    except UserSettings.DoesNotExist:
        rollbar.report_message('Unknown customer: %s' % customer, 'warn')
        return {'warning': 'customer unrecognized'}

    closed = body['data']['object']['closed']
    user = us.user
    if closed:
        us.set_plan(payment_plans.PLAN_DEMO)
        send_notification_email(
            user, ugettext('Your Pinecast subscription was cancelled.'),
            ugettext('Pinecast attempted to charge your payment card multiple '
                     'times, but was unable to collect payment. Your '
                     'account has been downgraded to a free Demo plan. Only '
                     'the ten most recent episodes from each of your podcasts '
                     'will be shown to your listeners. All recurring tip '
                     'subscriptions to your podcasts have also been '
                     'cancelled.\n\nNo content or settings have been deleted '
                     'from your account. If you wish to re-subscribe, you may '
                     'do so at any time at the URL below.\n\n%s') %
            (BASE_URL + reverse('upgrade')))

        return {'success': 'nastygram sent, account downgraded'}
    else:
        send_notification_email(
            user, ugettext('Payment failed for Pinecast subscription'),
            ugettext(
                'Pinecast attempted to charge your payment card for your '
                'current subscription, but was unable to collect payment. '
                'If we fail to process your card three times, your '
                'account will automatically be downgraded to a free Demo '
                'plan.\n\n'
                'No changes have currently been made to your account or '
                'plan. Please update your payment information at the URL '
                'below.\n\n%s') %
            (BASE_URL + reverse('dashboard') + '#settings,subscription'))
        return {'success': 'nastygram sent'}
Esempio n. 46
0
def set_payment_method_redir(req):
    us = UserSettings.get_from_user(req.user)
    customer = us.get_stripe_customer()

    if req.POST.get('next_url') == 'upgrade':
        next_url = reverse('upgrade')
    else:
        next_url = reverse('dashboard') + '?success=csuc#settings'

    try:
        if customer:
            customer.source = req.POST.get('token')
            customer.save()
        else:
            us.create_stripe_customer(req.POST.get('token'))
    except stripe.error.CardError as e:
        return redirect(next_url + '?error=crej#settings')
    except Exception as e:
        rollbar.report_message(str(e), 'error')
        return redirect(next_url + '?error=cerr#settings')

    return redirect(next_url)
Esempio n. 47
0
def add_blog_post(req, podcast_slug):
    site = get_site(req, podcast_slug)

    if not payment_plans.minimum(
        UserSettings.get_from_user(site.podcast.owner).plan,
        payment_plans.FEATURE_MIN_BLOG):
        raise Http404()

    try:
        publis_parsed = datetime.datetime.strptime(req.POST.get('publish'), '%Y-%m-%dT%H:%M:00.000Z')
        post = SiteBlogPost(
            site=site,
            title=req.POST.get('title'),
            slug=req.POST.get('slug'),
            body=req.POST.get('body'),
            publish=publis_parsed,
            disable_comments=req.POST.get('disable_comments') == 'true')
        post.save()
    except Exception as e:
        return redirect(reverse('podcast_dashboard', podcast_slug=podcast_slug) + '?error=sblog#site,blog')
    else:
        return redirect(reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#site,blog')
Esempio n. 48
0
def set_coupon(req):
    code = req.POST.get('coupon')
    try:
        coupon = stripe.Coupon.retrieve(code)
    except stripe.error.InvalidRequestError:
        return redirect(reverse('upgrade') + '?coupon_invalid')

    if 'owner_id' in coupon.metadata:
        us = UserSettings.get_from_user(req.user)
        if us.plan != payment_plans.PLAN_DEMO:
            return redirect(reverse('upgrade') + '?coupon_unavailable')

        try:
            cust = us.get_stripe_customer()
        except Exception:
            pass
        else:
            if len(stripe.Invoice.list(customer=cust.id, limit=1).data):
                return redirect(reverse('upgrade') + '?coupon_unavailable')

    req.session['coupon'] = code
    return redirect(reverse('upgrade') + '?coupon_applied')
Esempio n. 49
0
def network_add_member(req, network_id):
    net = get_object_or_404(Network, deactivated=False, id=network_id, members__in=[req.user])

    try:
        user = User.objects.get(email=req.POST.get('email'))
    except User.DoesNotExist:
        return redirect(reverse('network_dashboard', network_id=network_id) + '?error=udne#members,add-member')

    net.members.add(user)
    net.save()
    pinecast.email.send_notification_email(
        user,
        ugettext('[Pinecast] You have been added to "%s"') % net.name,
        ugettext('''
We are emailing you to let you know that you were added to the network
"%s". No action is required on your part. If you log in to Pinecast,
you will now have read and write access to all of the podcasts in the
network, and will be able to add your own podcasts to the network.
        ''') % net.name
    )

    return redirect(reverse('network_dashboard', network_id=net.id) + '#members')
Esempio n. 50
0
def signup(req):
    if not req.user.is_anonymous():
        return redirect('dashboard')

    if not req.POST:
        return _pmrender(
            req,
            'signup/main.html',
            {'email': req.GET.get('email', '')}
        )

    error = None

    if not _validate_recaptcha(req):
        error = ugettext('Your humanity was not verified')
    elif not req.POST.get('email'):
        error = ugettext('Missing email address')
    elif not req.POST.get('password'):
        error = ugettext('Come on, you need a password')
    elif len(req.POST.get('password')) < 8:
        error = ugettext('Your password needs to be at least 8 characters long')
    elif User.objects.filter(email=req.POST.get('email')).count():
        error = ugettext('That email address is already associated with an account')

    if error:
        return _pmrender(req, 'signup/main.html', {
            'error': error,
            'email': req.POST.get('email'),
        })

    try:
        u = User.objects.create_user(
            str(uuid.uuid4())[:30],
            req.POST.get('email'),
            req.POST.get('password')
        )
        u.save()
    except Exception as e:
        return _pmrender(req, 'signup/main.html', {
            'error': str(e),
            'email': req.POST.get('email'),
        })

    try:
        us = UserSettings.get_from_user(u)
        us.tz_offset = req.POST.get('timezone')
        us.save()
    except Exception:
        pass  # whatever.

    return redirect(reverse('login') + '?signup_success=true')
Esempio n. 51
0
def delete_site(req, podcast_slug):
    site = get_site(req, podcast_slug)

    data = {'site': site}

    if not req.POST:
        return _pmrender(req, 'dashboard/sites/page_delete.html', data)
    elif req.POST.get('slug') != podcast_slug:
        return redirect('site_options', podcast_slug=podcast_slug)

    site.delete()
    return redirect(
        reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#tab-site'
    )
Esempio n. 52
0
def new_site(req, podcast_slug):
    pod = get_podcast(req, podcast_slug)

    if not payment_plans.minimum(
        UserSettings.get_from_user(pod.owner).plan,
        payment_plans.FEATURE_MIN_SITES):
        raise Http404()

    try:
        site = Site(
            podcast=pod,
            theme=req.POST.get('theme'),
            cover_image_url=signer.unsign(req.POST.get('cover-url')) if req.POST.get('cover-url') else None,
            logo_url=signer.unsign(req.POST.get('logo-url')) if req.POST.get('logo-url') else None,
            analytics_id=req.POST.get('analytics_id'),
            itunes_url=req.POST.get('itunes_url'),
            stitcher_url=req.POST.get('stitcher_url'),
            show_itunes_banner=req.POST.get('show_itunes_banner') == 'true')
        site.save()
    except Exception as e:
        return redirect(reverse('podcast_dashboard', podcast_slug=podcast_slug) + '?error=true#site')
    else:
        return redirect(reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#site')
Esempio n. 53
0
def edit_site(req, podcast_slug):
    site = get_site(req, podcast_slug)
    try:
        site.theme = req.POST.get('theme')
        site.cover_image_url = signer.unsign(req.POST.get('cover-url')) if req.POST.get('cover-url') else None
        site.logo_url = signer.unsign(req.POST.get('logo-url')) if req.POST.get('logo-url') else None
        site.analytics_id = req.POST.get('analytics_id')
        site.itunes_url = req.POST.get('itunes_url')
        site.stitcher_url = req.POST.get('stitcher_url')
        site.show_itunes_banner = req.POST.get('show_itunes_banner') == 'true'
        site.custom_css = req.POST.get('custom_css')
        site.custom_cname = req.POST.get('custom_cname')

        us = UserSettings.get_from_user(site.podcast.owner)
        if payment_plans.minimum(us.plan, payment_plans.FEATURE_MIN_BLOG):
            site.disqus_url = req.POST.get('disqus_url')
        if payment_plans.minimum(us.plan, payment_plans.FEATURE_MIN_SITE_FAVICON):
            site.favicon_url = signer.unsign(req.POST.get('favicon-url')) if req.POST.get('favicon-url') else None

        site.save()
    except Exception as e:
        return redirect(reverse('podcast_dashboard', podcast_slug=podcast_slug) + '?error=true#settings,site-options')
    else:
        return redirect(reverse('podcast_dashboard', podcast_slug=podcast_slug) + '#settings,site-options')
Esempio n. 54
0
def ep_comment_box(req, podcast_slug, episode_id):
    pod = get_object_or_404(Podcast, slug=podcast_slug)
    if not UserSettings.user_meets_plan(pod.owner, plans.FEATURE_MIN_COMMENT_BOX):
        raise Http404()
    ep = get_object_or_404(PodcastEpisode, podcast=pod, id=episode_id)
    if not req.POST:
        return _pmrender(req, 'feedback/comment_episode.html', {'podcast': pod, 'episode': ep})

    try:
        if not _validate_recaptcha(req):
            raise Exception('Invalid ReCAPTCHA')

        ip = analyze.get_request_ip(req)
        f = Feedback(
            podcast=pod,
            episode=ep,
            sender=req.POST.get('email'),
            message=req.POST.get('message'),
            sender_ip=ip
        )
        f.save()
        analytics_log.write('feedback', {
            'podcast': unicode(pod.id),
            'episode': unicode(ep.id),
            'profile': {
                'email': req.POST.get('email'),
                'email_host': req.POST.get('email').split('@')[1],
                'ip': ip,
                'ua': req.META.get('HTTP_USER_AGENT'),
            },
        }, req=req)
        send_notification_email(
            pod.owner,
            ugettext('[Pinecast] You got some feedback!'),
            'Go check the Feedback page of %s--an episode on %s--to see what was written.\n\n'
            'https://pinecast.com%s' %
                (ep.title,
                 pod.name,
                 reverse('podcast_episode',
                         podcast_slug=podcast_slug,
                         episode_id=str(ep.id)) +
                    '#tab-feedback')
        )
    except Exception:
        return _pmrender(req, 'feedback/comment_episode.html',
                         {'podcast': pod, 'episode': ep, 'error': True, 'default': req.POST})

    return _pmrender(req, 'feedback/thanks.html', {'podcast': pod})
Esempio n. 55
0
def network_remove_member(req, network_id, member_id):
    net = get_object_or_404(Network, deactivated=False, id=network_id, members__in=[req.user])
    user = get_object_or_404(User, id=member_id)

    if not net.members.filter(username=user.username).count():
        raise Http404()

    # We don't need to confirm if the user is the owner.
    if net.owner == user:
        return redirect('network_dashboard', network_id=net.id)

    pods = Podcast.objects.filter(owner=user, networks__in=[net])

    for pod in pods:
        pod.networks.remove(net)
        pod.save()
    net.members.remove(user)
    net.save()

    return redirect(reverse('network_dashboard', network_id=net.id) + '#members')
Esempio n. 56
0
def edit_podcast_episode(req, podcast_slug, episode_id):
    pod = get_podcast(req, podcast_slug)
    ep = get_object_or_404(PodcastEpisode, id=episode_id, podcast=pod)

    try:
        publish_parsed = datetime.datetime.strptime(req.POST.get('publish').split('.')[0], ISO_FORMAT)

        ep.title = req.POST.get('title')
        ep.subtitle = req.POST.get('subtitle')
        ep.publish = publish_parsed
        ep.description = req.POST.get('description')
        ep.duration = int(req.POST.get('duration-hours')) * 3600 + int(req.POST.get('duration-minutes')) * 60 + int(req.POST.get('duration-seconds'))

        ep.audio_url = signer.unsign(req.POST.get('audio-url'))
        ep.audio_size = int(req.POST.get('audio-url-size'))
        ep.audio_type = req.POST.get('audio-url-type')

        image_url = req.POST.get('image-url')
        if image_url:
            ep.image_url = signer.unsign(req.POST.get('image-url'))
        else:
            ep.image_url = pod.cover_image

        ep.copyright = req.POST.get('copyright')
        ep.license = req.POST.get('license')

        ep.explicit_override = req.POST.get('explicit_override')

        ep.set_flair(req.POST, no_save=True)
        ep.save()

        ep.delete_feedback_prompt()
        if req.POST.get('feedback_prompt'):
            prompt = EpisodeFeedbackPrompt(episode=ep, prompt=req.POST.get('feedback_prompt'))
            prompt.save()

    except Exception as e:
        return redirect(reverse('podcast_episode', podcast_slug=pod.slug, episode_id=str(ep.id)) + '?error=true#edit')
    return redirect('podcast_episode', podcast_slug=pod.slug, episode_id=str(ep.id))
Esempio n. 57
0
def edit_podcast(req, podcast_slug):
    pod = get_podcast(req, podcast_slug)

    ctx = {'podcast': pod,
           'PODCAST_CATEGORIES': json.dumps(list(CATEGORIES))}

    try:
        pod.name = req.POST.get('name')
        pod.subtitle = req.POST.get('subtitle')
        pod.description = req.POST.get('description')
        pod.is_explicit = req.POST.get('is_explicit', 'false') == 'true'
        pod.homepage = req.POST.get('homepage')
        pod.language = req.POST.get('language')
        pod.copyright = req.POST.get('copyright')
        pod.author_name = req.POST.get('author_name')
        pod.cover_image = signer.unsign(req.POST.get('image-url'))
        pod.set_category_list(req.POST.get('categories'))
        pod.full_clean()
        pod.save()
    except Exception as e:
        return redirect(reverse('podcast_dashboard', podcast_slug=pod.slug) + '?error=serr#settings')
    return redirect('podcast_dashboard', podcast_slug=pod.slug)
Esempio n. 58
0
def podcast_top_episodes(req, pod):
    timeframe = req.GET.get("timeframe")
    if not timeframe:
        return None

    tz = UserSettings.get_from_user(req.user).tz_offset
    top_ep_data = query.get_top_episodes(str(pod.id), timeframe, tz)
    episodes = PodcastEpisode.objects.filter(id__in=list(top_ep_data.keys()))
    mapped = {str(ep.id): ep for ep in episodes}

    # This step is necessary to filter out deleted episodes, since deleted episodes
    # are not removed from the analytics data.
    top_ep_data = {k: v for k, v in top_ep_data.items() if k in mapped}

    # Sort the top episode data descending
    return [[ugettext("Episode"), ugettext("Count")]] + [
        [
            {"href": reverse("podcast_episode", podcast_slug=pod.slug, episode_id=ep_id), "title": mapped[ep_id].title},
            count,
        ]
        for ep_id, count in list(reversed(sorted(top_ep_data.items(), key=lambda x: x[1])))[:25]
    ]