def reorder(self, id, direction, **kwargs): """Reorder a PlayerPref. :param id: Player ID. :type id: ``int`` :param direction: ``"up"`` for higher priority, ``"down"`` for lower priority :type direction: ``unicode`` :returns: Redirect back to :meth:`index` after success. """ if direction == 'up': offset = -1 elif direction == 'down': offset = 1 else: return player1 = fetch_row(PlayerPrefs, id) new_priority = player1.priority + offset try: player2 = fetch_row(PlayerPrefs, priority=new_priority) player2.priority = player1.priority player1.priority = new_priority except HTTPException, e: if e.code != 404: raise
def save(self, id, delete=None, **kwargs): """Save changes or create a category. See :class:`~mediadrop.forms.admin.settings.categories.CategoryForm` for POST vars. :param id: Category ID :param delete: If true the category is to be deleted rather than saved. :type delete: bool :rtype: JSON dict :returns: success bool """ if tmpl_context.form_errors: if request.is_xhr: return dict(success=False, errors=tmpl_context.form_errors) else: # TODO: Add error reporting for users with JS disabled? return redirect(action="edit") cat = fetch_row(Category, id) if delete: DBSession.delete(cat) data = dict(success=True, id=cat.id, parent_options=unicode(category_form.c["parent_id"].display())) else: cat.name = kwargs["name"] cat.slug = get_available_slug(Category, kwargs["slug"], cat) if kwargs["parent_id"]: parent = fetch_row(Category, kwargs["parent_id"]) if parent is not cat and cat not in parent.ancestors(): cat.parent = parent else: cat.parent = None DBSession.add(cat) DBSession.flush() data = dict( success=True, id=cat.id, name=cat.name, slug=cat.slug, parent_id=cat.parent_id, parent_options=unicode(category_form.c["parent_id"].display()), depth=cat.depth(), row=unicode( category_row_form.display( action=url_for(id=cat.id), category=cat, depth=cat.depth(), first_child=True ) ), ) if request.is_xhr: return data else: redirect(action="index", id=None)
def index(self, page=1, search=None, filter=None, podcast=None, category=None, tag=None, **kwargs): """List media with pagination and filtering. :param page: Page number, defaults to 1. :type page: int :param search: Optional search term to filter by :type search: unicode or None :param podcast_filter: Optional podcast to filter by :type podcast_filter: int or None :rtype: dict :returns: media The list of :class:`~mediadrop.model.media.Media` instances for this page. search The given search term, if any search_form The :class:`~mediadrop.forms.admin.SearchForm` instance podcast The podcast object for rendering if filtering by podcast. """ media = Media.query.options(orm.undefer("comment_count_published")) if search: media = media.admin_search(search) else: media = media.order_by_status().order_by(Media.publish_on.desc(), Media.modified_on.desc()) if not filter: pass elif filter == "unreviewed": media = media.reviewed(False) elif filter == "unencoded": media = media.reviewed().encoded(False) elif filter == "drafts": media = media.drafts() elif filter == "published": media = media.published() if category: category = fetch_row(Category, slug=category) media = media.filter(Media.categories.contains(category)) if tag: tag = fetch_row(Tag, slug=tag) media = media.filter(Media.tags.contains(tag)) if podcast: podcast = fetch_row(Podcast, slug=podcast) media = media.filter(Media.podcast == podcast) return dict( media=media, search=search, search_form=search_form, media_filter=filter, category=category, tag=tag, podcast=podcast, )
def edit(self, id, **kwargs): """Display the :class:`~mediadrop.forms.admin.groups.GroupForm` for editing or adding. :param id: Group ID :type id: ``int`` or ``"new"`` :rtype: dict :returns: user The :class:`~mediadrop.model.auth.Group` instance we're editing. user_form The :class:`~mediadrop.forms.admin.groups.GroupForm` instance. user_action ``str`` form submit url group_values ``dict`` form values """ group = fetch_row(Group, id) if tmpl_context.action == "save" or id == "new": # Use the values from error_handler or GET for new groups group_values = kwargs else: permission_ids = map(lambda permission: permission.permission_id, group.permissions) group_values = dict( display_name=group.display_name, group_name=group.group_name, permissions=permission_ids ) return dict(group=group, group_form=group_form, group_action=url_for(action="save"), group_values=group_values)
def view(self, slug, page=1, show='latest', **kwargs): """View a podcast and the media that belongs to it. :param slug: A :attr:`~mediadrop.model.podcasts.Podcast.slug` :param page: Page number, defaults to 1. :type page: int :rtype: dict :returns: podcast A :class:`~mediadrop.model.podcasts.Podcast` instance. episodes A list of :class:`~mediadrop.model.media.Media` instances that belong to the ``podcast``. podcasts A list of all the other podcasts """ podcast = fetch_row(Podcast, slug=slug) episodes = podcast.media.published() episodes, show = helpers.filter_library_controls(episodes, show) episodes = viewable_media(episodes) if request.settings['rss_display'] == 'True': response.feed_links.append((url_for(action='feed'), podcast.title)) return dict( podcast=podcast, episodes=episodes, result_count=episodes.count(), show=show, )
def rate(self, slug, up=None, down=None, **kwargs): """Say 'I like this' for the given media. :param slug: The media :attr:`~mediadrop.model.media.Media.slug` :rtype: unicode :returns: The new number of likes """ media = fetch_row(Media, slug=slug) request.perm.assert_permission(u'view', media.resource) if up: if not request.settings['appearance_show_like']: abort(status_code=403) media.increment_likes() elif down: if not request.settings['appearance_show_dislike']: abort(status_code=403) media.increment_dislikes() if request.is_xhr: return u'' else: redirect(action='view')
def view(self, slug, page=1, show='latest', **kwargs): """View a podcast and the media that belongs to it. :param slug: A :attr:`~mediadrop.model.podcasts.Podcast.slug` :param page: Page number, defaults to 1. :type page: int :rtype: dict :returns: podcast A :class:`~mediadrop.model.podcasts.Podcast` instance. episodes A list of :class:`~mediadrop.model.media.Media` instances that belong to the ``podcast``. podcasts A list of all the other podcasts """ podcast = fetch_row(Podcast, slug=slug) episodes = podcast.media.published() episodes, show = helpers.filter_library_controls(episodes, show) episodes = viewable_media(episodes) if request.settings['rss_display'] == 'True': response.feed_links.append( (url_for(action='feed'), podcast.title) ) return dict( podcast = podcast, episodes = episodes, result_count = episodes.count(), show = show, )
def edit(self, id, **kwargs): """Display the :class:`~mediadrop.forms.admin.groups.GroupForm` for editing or adding. :param id: Group ID :type id: ``int`` or ``"new"`` :rtype: dict :returns: user The :class:`~mediadrop.model.auth.Group` instance we're editing. user_form The :class:`~mediadrop.forms.admin.groups.GroupForm` instance. user_action ``str`` form submit url group_values ``dict`` form values """ group = fetch_row(Group, id) if tmpl_context.action == 'save' or id == 'new': # Use the values from error_handler or GET for new groups group_values = kwargs else: permission_ids = map(lambda permission: permission.permission_id, group.permissions) group_values = dict(display_name=group.display_name, group_name=group.group_name, permissions=permission_ids) return dict( group=group, group_form=group_form, group_action=url_for(action='save'), group_values=group_values, )
def save(self, id, display_name, group_name, permissions, delete=None, **kwargs): """Save changes or create a new :class:`~mediadrop.model.auth.Group` instance. :param id: Group ID. If ``"new"`` a new group is created. :type id: ``int`` or ``"new"`` :returns: Redirect back to :meth:`index` after successful save. """ group = fetch_row(Group, id) if delete: DBSession.delete(group) redirect(action='index', id=None) group.display_name = display_name group.group_name = group_name if permissions: query = DBSession.query(Permission).filter( Permission.permission_id.in_(permissions)) group.permissions = list(query.all()) else: group.permissions = [] DBSession.add(group) redirect(action='index', id=None)
def create_new_user(username, config): from mediadrop.model import DBSession, User, fetch_row, Group user = User.by_user_name(username) if user is None: try: print "MIDDLEWARE" print config l = ldap.initialize(config['ldap_url']) l.simple_bind_s(config['ldap_binddn'], config['ldap_pw']) filter = '(samaccountname=%s)' % username r = l.search_s(config['ldap_base'],ldap.SCOPE_SUBTREE, filter, ['displayname', 'mail']) l.unbind_s() user_attrs = {} for dn, entry in r: for attr, v in entry.iteritems(): user_attrs[attr] = v[0] except ldap.LDAPError: l.unbind_s() new_user = fetch_row(User, "new") new_user.display_name = user_attrs['displayName'] new_user.email_address = user_attrs['mail'] new_user.user_name = username query = DBSession.query(Group).filter(Group.group_name.in_(['authenticated'])) new_user.groups = list(query.all()) DBSession.add(new_user) DBSession.commit()
def save_edit(self, id, body, **kwargs): """Save an edit from :class:`~mediadrop.forms.admin.comments.EditCommentForm`. :param id: Comment ID :type id: ``int`` :rtype: JSON dict :returns: success bool body The edited comment body after validation/filtering """ comment = fetch_row(Comment, id) if comment.author_name == request.perm.user.display_name: comment.body = body comment.reviewed = False comment.publishable = False DBSession.add(comment) return dict( success=True, body=comment.body, ) else: return dict( success=False, body=comment.body, )
def update_status(self, id, status=None, publish_on=None, publish_until=None, **values): """Update the publish status for the given media. :param id: Media ID :type id: ``int`` :param update_status: The text of the submit button which indicates that the :attr:`~mediadrop.model.media.Media.status` should change. :type update_status: ``unicode`` or ``None`` :param publish_on: A date to set to :attr:`~mediadrop.model.media.Media.publish_on` :type publish_on: :class:`datetime.datetime` or ``None`` :param publish_until: A date to set to :attr:`~mediadrop.model.media.Media.publish_until` :type publish_until: :class:`datetime.datetime` or ``None`` :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) new_slug = None # Make the requested change assuming it will be allowed if status == 'unreviewed': media.reviewed = True elif status == 'draft': self._publish_media(media, publish_on) elif publish_on: media.publish_on = publish_on media.update_popularity() elif publish_until: media.publish_until = publish_until # Verify the change is valid by re-determining the status media.update_status() DBSession.flush() 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)) return dict( success=True, status_form=status_form_xhtml, slug=new_slug, ) else: redirect(action='edit')
def save(self, id, email_address, display_name, login_details, delete=None, **kwargs): """Save changes or create a new :class:`~mediadrop.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: all_deletes = dict( comments=Comment.query.filter( Comment.author_name == user.user_name), podcasts=Podcast.query.filter( Podcast.author_name == user.user_name), medias=Media.query.filter(Media.author_name == user.user_name)) for need_delete in all_deletes: for element in all_deletes[need_delete]: DBSession.delete(element) DBSession.delete(user) redirect(action='index', id=None) user.display_name = display_name user.email_address = email_address if login_details['user_name'] != 'anonymous': user.user_name = login_details['user_name'] else: raise webob.exc.HTTPUnauthorized().exception password = login_details['password'] if password is not None and password != '': user.password = password if login_details['groups']: query = DBSession.query(Group).filter( Group.group_id.in_(login_details['groups'])) user.groups = list(query.all()) else: user.groups = [] DBSession.add(user) # Check if we're changing the logged in user's own password if user.id == request.perm.user.id \ and password is not None and password != '': DBSession.commit() # repoze.who sees the Unauthorized response and clears the cookie, # forcing a fresh login with the new password raise webob.exc.HTTPUnauthorized().exception redirect(action='index', id=None)
def embed_player(self, slug, w=None, h=None, **kwargs): media = fetch_row(Media, slug=slug) request.perm.assert_permission(u'view', media.resource) return dict( media=media, width=w and int(w) or None, height=h and int(h) or None, )
def embed_player(self, slug, w=None, h=None, **kwargs): media = fetch_row(Media, slug=slug) request.perm.assert_permission(u'view', media.resource) return dict( media = media, width = w and int(w) or None, height = h and int(h) or None, )
def view(self, slug, podcast_slug=None, **kwargs): """Display the media player, info and comments. :param slug: The :attr:`~mediadrop.models.media.Media.slug` to lookup :param podcast_slug: The :attr:`~mediadrop.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:`~mediadrop.model.media.Media` instance for display. related_media A list of :class:`~mediadrop.model.media.Media` instances that rank as topically related to the given media item. comments A list of :class:`~mediadrop.model.comments.Comment` instances associated with the selected media item. 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:`~mediadrop.model.media.Media` instance. """ media = fetch_row(Media, slug=slug) request.perm.assert_permission(u'view', media.resource) 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) try: media.increment_views() DBSession.commit() except OperationalError: DBSession.rollback() if request.settings['comments_engine'] == 'facebook': response.facebook = Facebook(request.settings['facebook_appid']) related_media = viewable_media(Media.query.related(media))[:6] # TODO: finish implementation of different 'likes' buttons # e.g. the default one, plus a setting to use facebook. return dict( media=media, related_media=related_media, comments=media.comments.published().all(), comment_form_action=url_for(action='comment'), comment_form_values=kwargs, )
def index(self, page=1, show='latest', q=None, tag=None, **kwargs): """List media with pagination. The media paginator may be accessed in the template with :attr:`c.paginators.media`, see :class:`webhelpers.paginate.Page`. :param page: Page number, defaults to 1. :type page: int :param show: 'latest', 'popular' or 'featured' :type show: unicode or None :param q: A search query to filter by :type q: unicode or None :param tag: A tag slug to filter for :type tag: unicode or None :rtype: dict :returns: media The list of :class:`~mediadrop.model.media.Media` instances for this page. result_count The total number of media items for this query search_query The query the user searched for, if any """ media = Media.query.published() media, show = helpers.filter_library_controls(media, show) if q: media = media.search(q, bool=True) if tag: tag = fetch_row(Tag, slug=tag) media = media.filter(Media.tags.contains(tag)) if (request.settings['rss_display'] == 'True') and (not (q or tag)): if show == 'latest': response.feed_links.extend([ (url_for(controller='/sitemaps', action='latest'), _(u'Latest RSS')), ]) elif show == 'featured': response.feed_links.extend([ (url_for(controller='/sitemaps', action='featured'), _(u'Featured RSS')), ]) media = viewable_media(media) return dict( media=media, result_count=media.count(), search_query=q, show=show, tag=tag, )
def view(self, slug, podcast_slug=None, **kwargs): """Display the media player, info and comments. :param slug: The :attr:`~mediadrop.models.media.Media.slug` to lookup :param podcast_slug: The :attr:`~mediadrop.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:`~mediadrop.model.media.Media` instance for display. related_media A list of :class:`~mediadrop.model.media.Media` instances that rank as topically related to the given media item. comments A list of :class:`~mediadrop.model.comments.Comment` instances associated with the selected media item. 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:`~mediadrop.model.media.Media` instance. """ media = fetch_row(Media, slug=slug) request.perm.assert_permission(u'view', media.resource) 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) try: media.increment_views() DBSession.commit() except OperationalError: DBSession.rollback() if request.settings['comments_engine'] == 'facebook': response.facebook = Facebook(request.settings['facebook_appid']) related_media = viewable_media(Media.query.related(media))[:6] # TODO: finish implementation of different 'likes' buttons # e.g. the default one, plus a setting to use facebook. return dict( media = media, related_media = related_media, comments = media.comments.published().all(), comment_form_action = url_for(action='comment'), comment_form_values = kwargs, )
def fetch_engine(self, id, engine_type=None): if id != 'new': engine = fetch_row(StorageEngine, id) else: types = dict((cls.engine_type, cls) for cls in StorageEngine) engine_cls = types.get(engine_type, None) if not engine_cls: redirect(controller='/admin/storage', action='index') engine = engine_cls() return engine
def disable(self, id, **kwargs): """Disable a StorageEngine. :param id: engine ID. :type id: ``int`` :returns: Redirect back to :meth:`index` after success. """ engine = fetch_row(StorageEngine, id) engine.enabled = False redirect(action='index', id=None)
def disable(self, id, **kwargs): """Disable a PlayerPref. :param id: Player ID. :type id: ``int`` :returns: Redirect back to :meth:`index` after success. """ player = fetch_row(PlayerPrefs, id) player.enabled = False update_enabled_players() redirect(action='index', id=None)
def index(self, page=1, show='latest', q=None, tag=None, **kwargs): """List media with pagination. The media paginator may be accessed in the template with :attr:`c.paginators.media`, see :class:`webhelpers.paginate.Page`. :param page: Page number, defaults to 1. :type page: int :param show: 'latest', 'popular' or 'featured' :type show: unicode or None :param q: A search query to filter by :type q: unicode or None :param tag: A tag slug to filter for :type tag: unicode or None :rtype: dict :returns: media The list of :class:`~mediadrop.model.media.Media` instances for this page. result_count The total number of media items for this query search_query The query the user searched for, if any """ media = Media.query.published() media, show = helpers.filter_library_controls(media, show) if q: media = media.search(q, bool=True) if tag: tag = fetch_row(Tag, slug=tag) media = media.filter(Media.tags.contains(tag)) if (request.settings['rss_display'] == 'True') and (not (q or tag)): if show == 'latest': response.feed_links.extend([ (url_for(controller='/sitemaps', action='latest'), _(u'Latest RSS')), ]) elif show == 'featured': response.feed_links.extend([ (url_for(controller='/sitemaps', action='featured'), _(u'Featured RSS')), ]) media = viewable_media(media) return dict( media = media, result_count = media.count(), search_query = q, show = show, tag = tag, )
def save_thumb(self, id, thumb=None, **kwargs): """Save a thumbnail uploaded with :class:`~mediadrop.forms.admin.ThumbForm`. :param id: Media ID. If ``"new"`` a new Media stub is created. :type id: ``int`` or ``"new"`` :param file: The uploaded file :type file: :class:`cgi.FieldStorage` or ``None`` :rtype: JSON dict :returns: success bool message Error message, if unsuccessful id The :attr:`~mediadrop.model.media.Media.id` which is important if a new media has just been created. """ user = request.perm.user if id == 'new': media = Media() user = request.perm.user media.author = Author(user.display_name, user.email_address) media.title = os.path.basename(kwargs['file'].filename) media.slug = get_available_slug(Media, '_stub_' + media.title) DBSession.add(media) DBSession.flush() else: media = fetch_row(Media, id) group = request.perm.user.groups[0].group_name if media.author.name != user.display_name and group != 'admins': raise try: # Create JPEG thumbs create_thumbs_for(media, kwargs['file'].file, kwargs['file'].filename) success = True message = None except IOError, e: success = False if id == 'new': DBSession.delete(media) if e.errno == 13: message = _('Permission denied, cannot write file') elif e.message == 'cannot identify image file': message = _('Unsupported image type: %s') \ % os.path.splitext(kwargs['file'].filename)[1].lstrip('.') elif e.message == 'cannot read interlaced PNG files': message = _('Interlaced PNGs are not supported.') else: raise
def update_status(self, id, status=None, publish_on=None, publish_until=None, **values): """Update the publish status for the given media. :param id: Media ID :type id: ``int`` :param update_status: The text of the submit button which indicates that the :attr:`~mediadrop.model.media.Media.status` should change. :type update_status: ``unicode`` or ``None`` :param publish_on: A date to set to :attr:`~mediadrop.model.media.Media.publish_on` :type publish_on: :class:`datetime.datetime` or ``None`` :param publish_until: A date to set to :attr:`~mediadrop.model.media.Media.publish_until` :type publish_until: :class:`datetime.datetime` or ``None`` :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) new_slug = None # Make the requested change assuming it will be allowed if status == 'unreviewed': media.reviewed = True elif status == 'draft': self._publish_media(media, publish_on) elif publish_on: media.publish_on = publish_on media.update_popularity() elif publish_until: media.publish_until = publish_until # Verify the change is valid by re-determining the status media.update_status() DBSession.flush() 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)) return dict( success = True, status_form = status_form_xhtml, slug = new_slug, ) else: redirect(action='edit')
def _assert_succesful_media_upload(self): media = fetch_row(Media, slug=u'testing-mp3-async-upload') assert_equals('John Doe', media.author.name) assert_equals('*****@*****.**', media.author.email) assert_equals('testing mp3 async upload', media.title) assert_equals('<p>a great song</p>', media.description) assert_length(1, media.files) media_file = media.files[0] assert_equals('mp3', media_file.container) assert_equals('awesome-song.mp3', media_file.display_name) return media
def save(self, id, slug, title, author_name, author_email, description, notes, podcast, tags, categories, delete=None, **kwargs): """Save changes or create a new :class:`~mediadrop.model.media.Media` instance. Form handler the :meth:`edit` action and the :class:`~mediadrop.forms.admin.media.MediaForm`. Redirects back to :meth:`edit` after successful editing and :meth:`index` after successful deletion. """ media = fetch_row(Media, id) if delete: self._delete_media(media) redirect(action='index', id=None) if not slug: slug = slugify(title) elif slug.startswith('_stub_'): slug = slug[len('_stub_'):] if slug != media.slug: media.slug = get_available_slug(Media, slug, media) media.title = title media.author = Author(author_name, author_email) media.description = description media.notes = notes media.podcast_id = podcast media.set_tags(tags) media.set_categories(categories) media.update_status() DBSession.add(media) DBSession.flush() if id == 'new' and not has_thumbs(media): create_default_thumbs_for(media) if request.is_xhr: status_form_xhtml = unicode(update_status_form.display( action=url_for(action='update_status', id=media.id), media=media)) return dict( media_id = media.id, values = {'slug': slug}, link = url_for(action='edit', id=media.id), status_form = status_form_xhtml, ) else: redirect(action='edit', id=media.id)
def save(self, id, slug, title, subtitle, author_name, author_email, description, details, feed, delete=None, **kwargs): """Save changes or create a new :class:`~mediadrop.model.podcasts.Podcast` instance. Form handler the :meth:`edit` action and the :class:`~mediadrop.forms.admin.podcasts.PodcastForm`. Redirects back to :meth:`edit` after successful editing and :meth:`index` after successful deletion. """ podcast = fetch_row(Podcast, id) if delete: DBSession.delete(podcast) DBSession.commit() delete_thumbs(podcast) redirect(action='index', id=None) if not slug: slug = title if slug != podcast.slug: podcast.slug = get_available_slug(Podcast, slug, podcast) podcast.title = title podcast.subtitle = subtitle podcast.author = Author(author_name, author_email) podcast.description = description podcast.copyright = details['copyright'] podcast.category = details['category'] podcast.itunes_url = feed['itunes_url'] podcast.feedburner_url = feed['feedburner_url'] podcast.explicit = { 'yes': True, 'clean': False }.get(details['explicit'], None) if id == 'new': DBSession.add(podcast) DBSession.flush() create_default_thumbs_for(podcast) redirect(action='edit', id=podcast.id)
def delete(self, id, **kwargs): """Delete a group. :param id: Group ID. :type id: ``int`` :returns: Redirect back to :meth:`index` after successful delete. """ group = fetch_row(Group, id) DBSession.delete(group) if request.is_xhr: return dict(success=True) redirect(action='index', id=None)
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)
def delete(self, id, **kwargs): """Delete a StorageEngine. :param id: Storage ID. :type id: ``int`` :returns: Redirect back to :meth:`index` after successful delete. """ engine = fetch_row(StorageEngine, id) files = engine.files for f in files: engine.delete(f.unique_id) DBSession.delete(engine) redirect(action='index', id=None)
def save(self, id, **kwargs): player = fetch_row(PlayerPrefs, id) form = player.settings_form if id == 'new': DBSession.add(player) @validate(form, error_handler=self.edit) def save(id, **kwargs): # Allow the form to modify the player directly # since each can have radically different fields. save_func = getattr(form, 'save_data') save_func(player, **tmpl_context.form_values) redirect(controller='/admin/players', action='index') return save(id, **kwargs)
def edit(self, id, **kwargs): """Edit a single category. :param id: Category ID :rtype: Dict :returns: categories The list of :class:`~mediadrop.model.categories.Category` instances for this page. category_form The :class:`~mediadrop.forms.admin.settings.categories.CategoryForm` instance. """ category = fetch_row(Category, id) return dict(category=category, category_form=category_form, category_row_form=category_row_form)
def save_thumb(self, id, thumb, **kwargs): """Save a thumbnail uploaded with :class:`~mediadrop.forms.admin.ThumbForm`. :param id: Media ID. If ``"new"`` a new Media stub is created. :type id: ``int`` or ``"new"`` :param file: The uploaded file :type file: :class:`cgi.FieldStorage` or ``None`` :rtype: JSON dict :returns: success bool message Error message, if unsuccessful id The :attr:`~mediadrop.model.media.Media.id` which is important if a new media has just been created. """ if id == 'new': media = Media() user = request.perm.user media.author = Author(user.display_name, user.email_address) media.title = os.path.basename(thumb.filename) media.slug = get_available_slug(Media, '_stub_' + media.title) DBSession.add(media) DBSession.flush() else: media = fetch_row(Media, id) try: # Create JPEG thumbs create_thumbs_for(media, thumb.file, thumb.filename) success = True message = None except IOError, e: success = False if id == 'new': DBSession.delete(media) if e.errno == 13: message = _('Permission denied, cannot write file') elif e.message == 'cannot identify image file': message = _('Unsupported image type: %s') \ % os.path.splitext(thumb.filename)[1].lstrip('.') elif e.message == 'cannot read interlaced PNG files': message = _('Interlaced PNGs are not supported.') else: raise
def test_add_new_media(self): new_url = url(controller='admin/media', action='edit', id='new') save_url = url(controller='admin/media', action='save', id='new') title = 'Add New Media Test' slug = u'add-new-media-test' # this should be unique name = 'Frederick Awesomeson' email = '*****@*****.**' description = 'This media item was created to test the "admin/media/edit/new" method' htmlized_description = '<p>This media item was created to test the "admin/media/edit/new" method</p>' self._login() new_response = self.app.get(new_url, status=200) form = new_response.forms['media-form'] form['title'] = title form['author_name'] = name form['author_email'] = email form['description'] = description # form['categories'] # form['tags'] form['notes'] = '' assert form.action == save_url save_response = form.submit() # Ensure that the correct redirect was issued assert save_response.status_int == 302 media = fetch_row(Media, slug=slug) edit_url = url(controller='admin/media', action='edit', id=media.id) assert save_response.location == 'http://localhost%s' % edit_url # Ensure that the media object was correctly created assert media.title == title assert media.author.name == name assert media.author.email == email assert media.description == htmlized_description # Ensure that the edit form is correctly filled out edit_response = save_response.follow() form = edit_response.forms['media-form'] assert form['title'].value == title assert form['author_name'].value == name assert form['author_email'].value == email assert form['slug'].value == slug assert form['description'].value == htmlized_description assert form['notes'].value == ''
def edit(self, id, name=None, **kwargs): """Display the :class:`~mediadrop.model.players.PlayerPrefs` for editing or adding. :param id: PlayerPrefs ID :type id: ``int`` or ``"new"`` :rtype: dict :returns: """ playerp = fetch_row(PlayerPrefs, id) return { 'player': playerp, 'form': playerp.settings_form, 'form_action': url_for(action='save'), 'form_values': kwargs, }
def delete(self, id, **kwargs): """Delete a PlayerPref. After deleting the PlayerPref, cleans up the players table, ensuring that each Player class is represented--if the deleted PlayerPref is the last example of that Player class, creates a new disabled PlayerPref for that Player class with the default settings. :param id: Player ID. :type id: ``int`` :returns: Redirect back to :meth:`index` after successful delete. """ player = fetch_row(PlayerPrefs, id) DBSession.delete(player) DBSession.flush() cleanup_players_table() redirect(action='index', id=None)
def edit(self, id, **kwargs): """Display the :class:`~mediadrop.forms.admin.users.UserForm` for editing or adding. :param id: User ID :type id: ``int`` or ``"new"`` :rtype: dict :returns: user The :class:`~mediadrop.model.auth.User` instance we're editing. user_form The :class:`~mediadrop.forms.admin.users.UserForm` instance. user_action ``str`` form submit url user_values ``dict`` form values """ user = fetch_row(User, id) if tmpl_context.action == 'save' or id == 'new': # Use the values from error_handler or GET for new users user_values = kwargs user_values['login_details.password'] = None user_values['login_details.confirm_password'] = None else: group_ids = None if user.groups: group_ids = map(lambda group: group.group_id, user.groups) user_values = dict( display_name=user.display_name, email_address=user.email_address, login_details=dict( groups=group_ids, user_name=user.user_name, ), ) return dict( user=user, user_form=user_form, user_action=url_for(action='save'), user_values=user_values, )
def edit(self, id, **kwargs): """Edit a single tag. :param id: Tag ID :rtype: Dict :returns: tags The list of :class:`~mediadrop.model.tags.Tag` instances for this page. tag_form The :class:`~mediadrop.forms.admin.settings.tags.TagForm` instance. """ tag = fetch_row(Tag, id) return dict( tag = tag, tag_form = tag_form, )
def save_thumb(self, id, thumb, **values): """Save a thumbnail uploaded with :class:`~mediadrop.forms.admin.ThumbForm`. :param id: Media ID. If ``"new"`` a new Podcast stub is created. :type id: ``int`` or ``"new"`` :param file: The uploaded file :type file: :class:`cgi.FieldStorage` or ``None`` :rtype: JSON dict :returns: success bool message Error message, if unsuccessful id The :attr:`~mediadrop.model.podcasts.Podcast.id` which is important if a new podcast has just been created. """ if id == 'new': return dict( success=False, message= u'You must first save the podcast before you can upload a thumbnail', ) podcast = fetch_row(Podcast, id) try: # Create JPEG thumbs create_thumbs_for(podcast, thumb.file, thumb.filename) success = True message = None except IOError, e: success = False if e.errno == 13: message = _('Permission denied, cannot write file') elif e.message == 'cannot identify image file': message = _('Unsupport image type: %s') \ % os.path.splitext(thumb.filename)[1].lstrip('.') elif e.message == 'cannot read interlaced PNG files': message = _('Interlaced PNGs are not supported.') else: raise
def edit(self, id, **kwargs): """Display the :class:`~mediadrop.forms.admin.users.UserForm` for editing or adding. :param id: User ID :type id: ``int`` or ``"new"`` :rtype: dict :returns: user The :class:`~mediadrop.model.auth.User` instance we're editing. user_form The :class:`~mediadrop.forms.admin.users.UserForm` instance. user_action ``str`` form submit url user_values ``dict`` form values """ user = fetch_row(User, id) if tmpl_context.action == 'save' or id == 'new': # Use the values from error_handler or GET for new users user_values = kwargs user_values['login_details.password'] = None user_values['login_details.confirm_password'] = None else: group_ids = None if user.groups: group_ids = map(lambda group: group.group_id, user.groups) user_values = dict( display_name = user.display_name, email_address = user.email_address, login_details = dict( groups = group_ids, user_name = user.user_name, ), ) return dict( user = user, user_form = user_form, user_action = url_for(action='save'), user_values = user_values, )
def save_thumb(self, id, thumb, **values): """Save a thumbnail uploaded with :class:`~mediadrop.forms.admin.ThumbForm`. :param id: Media ID. If ``"new"`` a new Podcast stub is created. :type id: ``int`` or ``"new"`` :param file: The uploaded file :type file: :class:`cgi.FieldStorage` or ``None`` :rtype: JSON dict :returns: success bool message Error message, if unsuccessful id The :attr:`~mediadrop.model.podcasts.Podcast.id` which is important if a new podcast has just been created. """ if id == 'new': return dict( success = False, message = u'You must first save the podcast before you can upload a thumbnail', ) podcast = fetch_row(Podcast, id) try: # Create JPEG thumbs create_thumbs_for(podcast, thumb.file, thumb.filename) success = True message = None except IOError, e: success = False if e.errno == 13: message = _('Permission denied, cannot write file') elif e.message == 'cannot identify image file': message = _('Unsupport image type: %s') \ % os.path.splitext(thumb.filename)[1].lstrip('.') elif e.message == 'cannot read interlaced PNG files': message = _('Interlaced PNGs are not supported.') else: raise
def edit(self, id, **kwargs): """Edit a single category. :param id: Category ID :rtype: Dict :returns: categories The list of :class:`~mediadrop.model.categories.Category` instances for this page. category_form The :class:`~mediadrop.forms.admin.settings.categories.CategoryForm` instance. """ category = fetch_row(Category, id) return dict( category=category, category_form=category_form, category_row_form=category_row_form, )
def save_edit(self, id, body, **kwargs): """Save an edit from :class:`~mediadrop.forms.admin.comments.EditCommentForm`. :param id: Comment ID :type id: ``int`` :rtype: JSON dict :returns: success bool body The edited comment body after validation/filtering """ comment = fetch_row(Comment, id) comment.body = body DBSession.add(comment) return dict( success = True, body = comment.body, )
def save_edit(self, id, body, **kwargs): """Save an edit from :class:`~mediadrop.forms.admin.comments.EditCommentForm`. :param id: Comment ID :type id: ``int`` :rtype: JSON dict :returns: success bool body The edited comment body after validation/filtering """ comment = fetch_row(Comment, id) comment.body = body DBSession.add(comment) return dict( success=True, body=comment.body, )
def save(self, id, delete=False, **kwargs): """Save changes or create a tag. See :class:`~mediadrop.forms.admin.settings.tags.TagForm` for POST vars. :param id: Tag ID :rtype: JSON dict :returns: success bool """ if tmpl_context.form_errors: if request.is_xhr: return dict(success=False, errors=tmpl_context.form_errors) else: # TODO: Add error reporting for users with JS disabled? return redirect(action='edit') tag = fetch_row(Tag, id) if delete: DBSession.delete(tag) data = dict(success=True, id=tag.id) else: tag.name = kwargs['name'] tag.slug = get_available_slug(Tag, kwargs['slug'], tag) DBSession.add(tag) DBSession.flush() data = dict( success = True, id = tag.id, name = tag.name, slug = tag.slug, row = unicode(tag_row_form.display(tag=tag)), ) if request.is_xhr: return data else: redirect(action='index', id=None)