Exemple #1
0
    def save(self, id, email_address, display_name, login_details, delete=None, **kwargs):
        """Save changes or create a new :class:`~mediacore.model.auth.User` instance.

        :param id: User ID. If ``"new"`` a new user is created.
        :type id: ``int`` or ``"new"``
        :returns: Redirect back to :meth:`index` after successful save.

        """
        user = fetch_row(User, id)

        if delete:
            DBSession.delete(user)
            redirect(action="index", id=None)

        user.display_name = display_name
        user.email_address = email_address
        user.user_name = login_details["user_name"]

        password = login_details["password"]
        if password is not None and password != "":
            user.password = password

        if login_details["group"]:
            group = fetch_row(Group, login_details["group"])
            user.groups = [group]
        else:
            user.groups = []

        DBSession.add(user)
        DBSession.flush()
        redirect(action="index", id=None)
    def save(self, id, delete, category='topics', **kwargs):
        """Save changes or create a topic or tag.

        See :class:`~mediacore.forms.categories.EditCategoryForm` for POST vars.

        :param id: Topic or tag ID
        :param category: ``topics`` or ``tags``
        :param delete: If true the category is deleted rather than saved.
        :type delete: bool
        :rtype: JSON dict
        :returns:
            success
                bool
            category
                ``topics`` or ``tags``

        """
        model = self.select_model(category)
        item = fetch_row(model, id)

        if delete:
            DBSession.delete(item)
            item = None
        else:
            item.name = kwargs['name']
            item.slug = get_available_slug(model, kwargs['slug'], item)

            DBSession.add(item)

        if request.is_xhr:
            return dict(success=True, category=item)
        else:
            redirect(action='index', category=category)
Exemple #3
0
    def rate(self, slug, rating=1, **kwargs):
        """Rate up or down the given media.

        :param slug: The media :attr:`~mediacore.model.media.Media.slug`
        :param rating: ``1`` or ``0`` if the rating is up or down.
        :rtype: JSON dict
        :returns:
            succcess
                bool
            upRating
                Pluralized count of up raters, "# people" or "1 person"
            downRating
                Pluralized count of down raters, "# people" or "1 person"

        """
        media = fetch_row(Media, slug=slug)

        if rating > 0:
            media.rating.add_vote(1)
        else:
            media.rating.add_vote(0)
        DBSession.add(media)

        if request.is_xhr:
            return dict(
                success = True,
                upRating = helpers.text.plural(media.rating.sum, 'person', 'people'),
                downRating = None,
            )
        else:
            redirect(action='view')
Exemple #4
0
    def comment(self, slug, **values):
        """Post a comment from :class:`~mediacore.forms.media.PostCommentForm`.

        :param slug: The media :attr:`~mediacore.model.media.Media.slug`
        :returns: Redirect to :meth:`view` page for media.

        """
        if tmpl_context.form_errors:
            if request.is_xhr:
                return dict(
                    success = False,
                    errors = tmpl_context.form_errors
                )
            else:
                redirect(action='view')

        media = fetch_row(Media, slug=slug)
        c = Comment()
        c.status = 'unreviewed'
        c.author = AuthorWithIP(values['name'], None, request.environ['REMOTE_ADDR'])
        c.subject = 'Re: %s' % media.title
        c.body = helpers.clean_xhtml(values['body'])

        media.comments.append(c)
        DBSession.add(media)
        email.send_comment_notification(media, c)

        if request.is_xhr:
            return dict(success = True)
        else:
            redirect(action='view')
Exemple #5
0
    def post_login(self, came_from=url_for(controller="/admin")):
        if not request.identity:
            login_counter = request.environ["repoze.who.logins"] + 1
            redirect(came_from)

        userid = request.identity["repoze.who.userid"]
        flash(_("Welcome back, %s!") % userid)
        redirect(came_from)
Exemple #6
0
    def delete(self, id, **kwargs):
        """Delete a user.

        :param id: User ID.
        :type id: ``int``
        :returns: Redirect back to :meth:`index` after successful delete.
        """
        user = fetch_row(User, id)
        DBSession.delete(user)

        if request.is_xhr:
            return dict(success=True)
        redirect(action="index", id=None)
Exemple #7
0
    def view(self, slug, podcast_slug=None, **kwargs):
        """Display the media player, info and comments.

        :param slug: The :attr:`~mediacore.models.media.Media.slug` to lookup
        :param podcast_slug: The :attr:`~mediacore.models.podcasts.Podcast.slug`
            for podcast this media belongs to. Although not necessary for
            looking up the media, it tells us that the podcast slug was
            specified in the URL and therefore we reached this action by the
            preferred route.
        :rtype dict:
        :returns:
            media
                The :class:`~mediacore.model.media.Media` instance for display.
            comment_form
                The :class:`~mediacore.forms.comments.PostCommentForm` instance.
            comment_form_action
                ``str`` comment form action
            comment_form_values
                ``dict`` form values
            next_episode
                The next episode in the podcast series, if this media belongs to
                a podcast, another :class:`~mediacore.model.media.Media`
                instance.

        """
        media = fetch_row(Media, slug=slug)
        media.views += 1

        next_episode = None
        if media.podcast_id is not None:
            # Always view podcast media from a URL that shows the context of the podcast
            if url_for() != url_for(podcast_slug=media.podcast.slug):
               redirect(podcast_slug=media.podcast.slug)

            if media.is_published:
                next_episode = DBSession.query(Media)\
                    .filter(Media.podcast_id == media.podcast.id)\
                    .filter(Media.publish_on > media.publish_on)\
                    .filter(Media.publish_on < datetime.now())\
                    .filter(Media.status >= 'publish')\
                    .filter(Media.status.excludes('trash'))\
                    .order_by(Media.publish_on)\
                    .first()

        return dict(
            media = media,
            comment_form = post_comment_form,
            comment_form_action = url_for(action='comment'),
            comment_form_values = kwargs,
            next_episode = next_episode,
        )
Exemple #8
0
    def report(self, email='', description='', **kwargs):
        """Email a support request that's been submitted on :meth:`document`.

        Redirects back to the root URL ``/``.

        """
        url = ''
        get_vars = post_vars = {}
        for x in kwargs:
            if x.startswith('GET_'):
                get_vars[x] = kwargs[x]
            elif x.startswith('POST_'):
                post_vars[x] = kwargs[x]
        libemail.send_support_request(email, url, description, get_vars, post_vars)
        redirect('/')
Exemple #9
0
    def upload_submit(self, **kwargs):
        """
        """
        kwargs.setdefault('name')
        kwargs.setdefault('tags')

        # Save the media_obj!
        media_obj = self._save_media_obj(
            kwargs['name'], kwargs['email'],
            kwargs['title'], kwargs['description'],
            kwargs['tags'], kwargs['file']
        )
        email.send_media_notification(media_obj)

        # Redirect to success page!
        redirect(action='upload_success')
Exemple #10
0
    def feed(self, slug, **kwargs):
        """Serve the feed as RSS 2.0.

        If :attr:`~mediacore.model.podcasts.Podcast.feedburner_url` is
        specified for this podcast, we redirect there if the useragent
        does not contain 'feedburner', as described here:
        http://www.google.com/support/feedburner/bin/answer.py?hl=en&answer=78464

        :param feedburner_bypass: If true, the redirect to feedburner is disabled.
        :rtype: Dict
        :returns:
            podcast
                A :class:`~mediacore.model.podcasts.Podcast` instance.
            episodes
                A list of :class:`~mediacore.model.media.Media` instances
                that belong to the ``podcast``.

        Renders: :data:`mediacore.templates.podcasts.feed` XML

        """
        podcast = fetch_row(Podcast, slug=slug)

        if (
            podcast.feedburner_url
            and not "feedburner" in request.environ.get("HTTP_USER_AGENT").lower()
            and not kwargs.get("feedburner_bypass", False)
        ):
            redirect(podcast.feedburner_url.encode("utf-8"))

        episodes = self._filter(podcast.media).order_by(Media.publish_on.desc())[:25]

        template_vars = dict(podcast=podcast, episodes=episodes)

        for type in ("application/rss+xml", "application/xml"):
            if type in request.environ["HTTP_ACCEPT"]:
                response.content_type = type
        else:
            response.content_type = "text/html"

        # Manually render XML from genshi since tg is didnt consider it
        template_finder = config["pylons.app_globals"].dotted_filename_finder
        template_name = template_finder.get_dotted_filename(
            "mediacore.templates.podcasts.feed", template_extension=".xml"
        )

        return pylons.templating.render_genshi(template_name, extra_vars=template_vars, method="xml")
    def save_status(self, id, status, ids=None, **kwargs):
        """Approve or delete a comment or comments.

        :param id: A :attr:`~mediacore.model.comments.Comment.id` if we are
            acting on a single comment, or ``"bulk"`` if we should refer to
            ``ids``.
        :type id: ``int`` or ``"bulk"``
        :param ids: An optional string of IDs separated by commas.
        :type ids: ``unicode`` or ``None``
        :param status: ``"approve"`` or ``"trash"`` depending on what action
            the user requests.
        :rtype: JSON dict
        :returns:
            success
                bool
            ids
                A list of :attr:`~mediacore.model.comments.Comment.id`
                that have changed.

        """
        if id == 'bulk':
            ids = ids.split(',')
        else:
            ids = [id]

        approve = status == 'approve'
        comments = DBSession.query(Comment)\
            .filter(Comment.id.in_(ids))\
            .all()

        for comment in comments:
            if approve:
                comment.status.discard('unreviewed')
                comment.status.add('publish')
            else:
                comment.status.add('trash')
            DBSession.add(comment)

        if request.is_xhr:
            return dict(success=True, ids=ids)
        else:
            redirect(action='index')
    def save(self, email, legal_wording, default_wording, **kwargs):
        """Save :class:`~mediacore.forms.settings.SettingsForm`.

        Redirects back to :meth:`edit` after successful editing.

        """
        settings = self._fetch_keyed_settings()
        settings['email_media_uploaded'].value = email['media_uploaded']
        settings['email_comment_posted'].value = email['comment_posted']
        settings['email_support_requests'].value = email['support_requests']
        settings['email_send_from'].value = email['send_from']
#        settings['ftp_server'].value = ftp['server']
#        settings['ftp_username'].value = ftp['username']
#        if ftp['password'] is not None and ftp['password'] != '':
#            settings['ftp_password'].value = ftp['password']
#        settings['ftp_upload_path'].value = ftp['upload_path']
#        settings['ftp_download_url'].value = ftp['download_url']
        settings['wording_user_uploads'].value = legal_wording['user_uploads']
        settings['wording_additional_notes'].value = default_wording['additional_notes']

        DBSession.add_all(settings.values())
        DBSession.flush()
        redirect(action='edit')
Exemple #13
0
    def serve(self, id, slug, type, **kwargs):
        """Serve a :class:`~mediacore.model.media.MediaFile` binary.

        :param id: File ID
        :type id: ``int``
        :param slug: The media :attr:`~mediacore.model.media.Media.slug`
        :type slug: The file :attr:`~mediacore.model.media.MediaFile.type`
        :raises tg.exceptions.HTTPNotFound: If no file exists for the given params.
        :raises tg.exceptions.HTTPNotAcceptable: If an Accept header field
            is present, and if the mimetype of the requested file doesn't
            match, then a 406 (not acceptable) response is returned.

        """
        media = fetch_row(Media, slug=slug)

        for file in media.files:
            if file.id == id and file.type == type:
                # Redirect to an external URL
                if urlparse(file.url)[1]:
                    redirect(file.url.encode('utf-8'))

                # Ensure that the clients request allows for files of this type
                mimetype = mimeparse.best_match([file.mimetype],
                    request.environ.get('HTTP_ACCEPT', '*/*'))
                if mimetype == '':
                    raise exceptions.HTTPNotAcceptable() # 406

                file_name = '%s-%s.%s' % (media.slug, file.id, file.type)
                file_path = os.path.join(config.media_dir, file.url)
                file_handle = open(file_path, 'rb')

                response.headers['Content-Type'] = mimetype
                response.headers['Content-Disposition'] = \
                    'attachment;filename=%s' % file_name.encode('utf-8')
                return file_handle.read()
        else:
            raise exceptions.HTTPNotFound()
Exemple #14
0
    def save(self, id, slug, title, author_name, author_email,
             description, notes, details, podcast, tags, topics, delete=None, **kwargs):
        """Save changes or create a new :class:`~mediacore.model.media.Media` instance.

        Form handler the :meth:`edit` action and the
        :class:`~mediacore.forms.media.MediaForm`.

        Redirects back to :meth:`edit` after successful editing
        and :meth:`index` after successful deletion.

        """
        media = fetch_row(Media, id, incl_trash=True)

        if delete:
            media.status.add('trash')
            DBSession.add(media)
            DBSession.flush()
            redirect(action='index', id=None)

        if id == 'new':
            media.status = 'draft,unencoded,unreviewed'

        media.slug = get_available_slug(Media, slug, media)
        media.title = title
        media.author = Author(author_name, author_email)
        media.description = helpers.clean_admin_xhtml(description)
        media.notes = notes
        media.duration = helpers.duration_to_seconds(details['duration'])
        media.podcast_id = podcast
        media.set_tags(tags)
        media.set_topics(topics)

        media.update_status()
        DBSession.add(media)
        DBSession.flush()

        redirect(action='edit', id=media.id)
Exemple #15
0
        """
        media = fetch_row(Media, id, incl_trash=True)

        # Make the requested change assuming it will be allowed
        if update_button == 'Review Complete':
            media.status.discard('unreviewed')
        elif update_button == 'Publish Now':
            media.status.discard('draft')
            media.status.add('publish')
            media.publish_on = publish_on or datetime.now()
        elif publish_on:
            media.publish_on = publish_on

        try:
            # Verify the change is valid by re-determining the status
            media.update_status()
            DBSession.add(media)
            DBSession.flush()
            data = dict(success=True)
        except Exception, e:
            data = dict(success=False, message=e.message)

        if request.is_xhr:
            # Return the rendered widget for injection
            status_form_xhtml = unicode(update_status_form.display(
                action=url_for(action='update_status'), media=media))
            data['status_form'] = status_form_xhtml
            return data
        else:
            redirect(action='edit')
Exemple #16
0
    def edit_file(self, id, file_id, player_enabled, feed_enabled,
                  toggle_feed, toggle_player, delete, **kwargs):
        """Save action for the :class:`~mediacore.forms.media.EditFileForm`.

        Changes or delets a :class:`~mediacore.model.media.MediaFile`.

        :param id: Media ID
        :type id: :class:`int`
        :rtype: JSON dict
        :returns:
            success
                bool
            message
                Error message, if unsuccessful
            status_form
                Rendered XHTML for the status form, updated to reflect the
                changes made.

        """
        media = fetch_row(Media, id, incl_trash=True)
        data = {}

#        try:
        try:
            file = [file for file in media.files if file.id == file_id][0]
        except IndexError:
            raise Exception, 'File does not exist.'

        if toggle_player:
            data['field'] = 'player_enabled'
            file.enable_player = data['value'] = not player_enabled
            DBSession.add(file)
        elif toggle_feed:
            data['field'] = 'feed_enabled'
            file.enable_feed = data['value'] = not feed_enabled
            # Raises an exception if it is the only feed enabled file for
            # an already published podcast episode.
            DBSession.add(file)
        elif delete:
            data['field'] = 'delete'
            DBSession.delete(file)
            media.files.remove(file)
        else:
            raise Exception, 'No action to perform.'

        data['success'] = True
        media.update_type()
        media.update_status()
        DBSession.add(media)
#        except Exception, e:
#            data['success'] = False
#            data['message'] = e.message

        if request.is_xhr:
            # Return the rendered widget for injection
            status_form_xhtml = unicode(update_status_form.display(
                action=url_for(action='update_status'), media=media))
            data['status_form'] = status_form_xhtml
            return data
        else:
            DBSession.flush()
            redirect(action='edit')
Exemple #17
0
 def post_logout(self, came_from=url_for("/")):
     flash(_("We hope to see you soon!"))
     redirect(came_from)
 def index(self, section='topics', **kwargs):
     redirect(controller='categoryadmin', category=section)