예제 #1
0
def users(request):
    headers = SortHeaders(request, (
            ('Username', 'username'),
            ('Email', None),
            ('Role', None),
            ('Videos', 'authored_set__count')))

    users = User.objects.all().annotate(Count('authored_set'))
    users = users.order_by(headers.order_by())
    if request.GET.get('show', None) != 'all':
        filters = ~(Q(password=UNUSABLE_PASSWORD) | Q(password=''))
        if 'socialauth' in settings.INSTALLED_APPS:
            filters = filters | ~Q(authmeta=None)
        users = users.filter(filters)
    formset = forms.AuthorFormSet(queryset=users)
    add_user_form = forms.AuthorForm()
    if request.method == 'POST':
        if not request.POST.get('form-TOTAL_FORMS'):
            add_user_form = forms.AuthorForm(request.POST, request.FILES)
            if add_user_form.is_valid():
                add_user_form.save()
                return HttpResponseRedirect(request.path)
        else:
            formset = forms.AuthorFormSet(request.POST, request.FILES,
                                          queryset=User.objects.all())
            if formset.is_valid():
                formset.save()
                return HttpResponseRedirect(request.get_full_path())

    return render_to_response('localtv/admin/users.html',
                              {'formset': formset,
                               'add_user_form': add_user_form,
                               'headers': headers},
                              context_instance=RequestContext(request))
예제 #2
0
def users(request):
    headers = SortHeaders(request,
                          (('Username', 'username'), ('Email', None),
                           ('Role', None), ('Videos', 'authored_set__count')))

    users = User.objects.all().annotate(Count('authored_set'))
    users = users.order_by(headers.order_by())
    if request.GET.get('show', None) != 'all':
        filters = _filter_just_humans()
        users = users.filter(filters)

    # Display only the appropriate page. Put 50 on each page at a time.
    user_paginator = Paginator(users, 50)
    try:
        page = user_paginator.page(int(request.GET.get('page', 1)))
    except ValueError:
        return HttpResponseBadRequest('Not a page number')
    except EmptyPage:
        page = user_paginator.page(video_paginator.num_pages)

    formset = forms.AuthorFormSet(queryset=page.object_list)
    add_user_form = forms.AuthorForm()
    if request.method == 'POST':
        if not request.POST.get('form-TOTAL_FORMS'):
            add_user_form = forms.AuthorForm(request.POST, request.FILES)
            if add_user_form.is_valid():
                add_user_form.save()
                return HttpResponseRedirect(request.path)
        else:
            formset = forms.AuthorFormSet(request.POST,
                                          request.FILES,
                                          queryset=User.objects.all())
            if formset.is_valid():
                formset.save()
                return HttpResponseRedirect(request.get_full_path())

    return render_to_response('localtv/admin/users.html', {
        'formset': formset,
        'add_user_form': add_user_form,
        'page': page,
        'headers': headers
    },
                              context_instance=RequestContext(request))
예제 #3
0
def users(request):
    headers = SortHeaders(request, (
            ('Username', 'username'),
            ('Email', None),
            ('Role', None),
            ('Videos', 'authored_set__count')))

    users = User.objects.all().annotate(Count('authored_set'))
    users = users.order_by(headers.order_by())
    if request.GET.get('show', None) != 'all':
        filters = _filter_just_humans()
        users = users.filter(filters)

    # Display only the appropriate page. Put 50 on each page at a time.
    user_paginator = Paginator(users, 50)
    try:
        page = user_paginator.page(int(request.GET.get('page', 1)))
    except ValueError:
        return HttpResponseBadRequest('Not a page number')
    except EmptyPage:
        page = user_paginator.page(video_paginator.num_pages)

    formset = forms.AuthorFormSet(queryset=page.object_list)
    add_user_form = forms.AuthorForm()
    if request.method == 'POST':
        if not request.POST.get('form-TOTAL_FORMS'):
            add_user_form = forms.AuthorForm(request.POST, request.FILES)
            if add_user_form.is_valid():
                add_user_form.save()
                return HttpResponseRedirect(request.path)
        else:
            formset = forms.AuthorFormSet(request.POST, request.FILES,
                                          queryset=User.objects.all())
            if formset.is_valid():
                formset.save()
                return HttpResponseRedirect(request.get_full_path())

    return render_to_response('localtv/admin/users.html',
                              {'formset': formset,
                               'add_user_form': add_user_form,
                               'page': page,
                               'headers': headers},
                              context_instance=RequestContext(request))
예제 #4
0
def bulk_edit(request):
    if ('just_the_author_field' in request.GET and 'video_id' in request.GET):
        # generate just the particular form that the user wants
        template_data = {}
        form_prefix = request.GET['just_the_author_field']
        video = get_object_or_404(models.Video, pk=int(request.GET['video_id']))
        cache_for_form_optimization = {}
        form = forms.BulkEditVideoForm(instance=video, prefix=form_prefix,
                                       cache_for_form_optimization=cache_for_form_optimization)
        template_data['form'] = form
        template = 'localtv/admin/bulk_edit_author_widget.html'
        return render_to_response(template,
                                  template_data,
                                  context_instance=RequestContext(request))

    videos = models.Video.objects.filter(
        status=models.VIDEO_STATUS_ACTIVE,
        site=request.sitelocation().site)

    if 'filter' in request.GET:
        filter_type = request.GET['filter']
        if filter_type == 'featured':
            videos = videos.exclude(last_featured=None)
        elif filter_type == 'rejected':
            videos = models.Video.objects.filter(
                status=models.VIDEO_STATUS_REJECTED,
                site=request.sitelocation().site)
        elif filter_type == 'no-attribution':
            videos = videos.filter(authors=None)
        elif filter_type == 'no-category':
            videos = videos.filter(categories=None)
        elif filter_type == 'unapproved':
            videos = models.Video.objects.filter(
                status=models.VIDEO_STATUS_UNAPPROVED,
                site=request.sitelocation().site)

    videos = videos.select_related('feed', 'search', 'site')

    category = request.GET.get('category', '')
    try:
        category = int(category)
    except ValueError:
        category = ''

    if category != '':
        videos = videos.filter(categories__pk=category).distinct()

    author = request.GET.get('author', '')
    try:
        author = int(author)
    except ValueError:
        author = ''

    if author != '':
        videos = videos.filter(authors__pk=author).distinct()

    search_string = request.GET.get('q', '')
    if search_string != '':
        videos = videos.filter(
            Q(description__icontains=search_string) |
            Q(name__icontains=search_string) |
            Q(categories__name__icontains=search_string) |
            Q(user__username__icontains=search_string) |
            Q(user__first_name__icontains=search_string) |
            Q(user__last_name__icontains=search_string) |
            Q(video_service_user__icontains=search_string) |
            Q(feed__name__icontains=search_string)).distinct()

    headers = SortHeaders(request, (
            ('Video Title', 'name'),
            ('Source', 'source'),
            ('Categories', None),
            ('Date Published', '-when_published'),
            ('Date Imported', '-when_submitted'),
            ))

    sort = headers.order_by()
    if sort.endswith('source'):
        reverse = sort.startswith('-')
        videos = videos.extra(select={
                'name_lower':'LOWER(localtv_video.name)'})
        videos = videos.order_by(sort.replace('source', 'calculated_source_type'))
    elif sort.endswith('name'):
        videos = videos.extra(select={
                'name_lower':'LOWER(localtv_video.name)'}).order_by(
            sort.replace('name', 'name_lower'))
    else:
        videos = videos.order_by(sort)
    video_paginator = Paginator(videos, 30)
    try:
        page = video_paginator.page(int(request.GET.get('page', 1)))
    except ValueError:
        return HttpResponseBadRequest('Not a page number')
    except EmptyPage:
        page = video_paginator.page(video_paginator.num_pages)

    if request.method == 'POST':
        formset = forms.VideoFormSet(request.POST, request.FILES,
                                     queryset=page.object_list)
        if formset.is_valid():
            tier_prevented_some_action = False
            tier = request.sitelocation().get_tier()
            videos_approved_so_far = 0

            for form in list(formset.deleted_forms):
                form.cleaned_data[DELETION_FIELD_NAME] = False
                form.instance.status = models.VIDEO_STATUS_REJECTED
                form.instance.save()
            bulk_edits = formset.extra_forms[0].cleaned_data
            for key in list(bulk_edits.keys()): # get the list because we'll be
                                                # changing the dictionary
                if not bulk_edits[key]:
                    del bulk_edits[key]
            bulk_action = request.POST.get('bulk_action', '')
            if bulk_action:
                bulk_edits['action'] = bulk_action
            if bulk_edits:
                for form in formset.initial_forms:
                    if not form.cleaned_data['BULK']:
                        continue
                    for key, value in bulk_edits.items():
                        if key == 'action': # do something to the video
                            if value == 'delete':
                                form.instance.status = \
                                    models.VIDEO_STATUS_REJECTED
                            elif value == 'approve':
                                if (request.sitelocation().enforce_tiers() and
                                    tier.remaining_videos() <= videos_approved_so_far):
                                    tier_prevented_some_action = True
                                else:
                                    form.instance.status = \
                                        models.VIDEO_STATUS_ACTIVE
                                    videos_approved_so_far += 1
                            elif value == 'unapprove':
                                form.instance.status = \
                                    models.VIDEO_STATUS_UNAPPROVED
                            elif value == 'feature':
                                if form.instance.status != models.VIDEO_STATUS_ACTIVE:
                                    if (request.sitelocation().enforce_tiers() and
                                        tier.remaining_videos() <= videos_approved_so_far):
                                        tier_prevented_some_action = True
                                    else:
                                        form.instance.status = \
                                            models.VIDEO_STATUS_ACTIVE
                                if form.instance.status == models.VIDEO_STATUS_ACTIVE:
                                    form.instance.last_featured = datetime.now()
                            elif value == 'unfeature':
                                form.instance.last_featured = None
                        elif key == 'tags':
                            form.cleaned_data[key] = value
                        elif key == 'categories':
                            # categories append, not replace
                            form.cleaned_data[key] = (
                                list(form.cleaned_data[key]) +
                                list(value))
                        elif key == 'authors':
                            form.cleaned_data[key] = value
                        else:
                            setattr(form.instance, key, value)
            formset.forms = formset.initial_forms # get rid of the extra bulk
                                                  # edit form
            formset.can_delete = False
            formset.save()
            path_with_success = None
            if 'successful' in request.GET:
                path_with_success = request.get_full_path()
            else:
                path = request.get_full_path()
                if '?' in path:
                    path_with_success =  path + '&successful'
                else:
                    path_with_success = path + '?successful'

            if tier_prevented_some_action:
                path = path_with_success + '&not_all_actions_done'
            else:
                path = path_with_success

            return HttpResponseRedirect(path)
    else:
        formset = forms.VideoFormSet(queryset=page.object_list)

    return render_to_response('localtv/admin/bulk_edit.html',
                              {'formset': formset,
                               'headers': headers,
                               'search_string': search_string,
                               'page': page,
                               'categories': models.Category.objects.filter(
                site=request.sitelocation().site),
                               'users': User.objects.order_by('username')},
                              context_instance=RequestContext(request))
예제 #5
0
def manage_sources(request):
    headers = SortHeaders(request, (
            ('Source', 'name__lower'),
            ('Categories', None),
            ('User Attribution', None),
            ('Type', 'type'),
            ('Auto Approve', 'auto_approve')))

    sort = headers.order_by()
    if sort.endswith('type'):
        if sort[0] == '-':
            orm_sort = '-name__lower'
        else:
            orm_sort = 'name__lower'
    else:
        orm_sort = sort
    feeds = models.Feed.objects.filter(
        site=request.sitelocation.site,
        status=models.FEED_STATUS_ACTIVE).extra(select={
            'name__lower': 'LOWER(name)'}).order_by(orm_sort)
    searches = models.SavedSearch.objects.filter(
        site=request.sitelocation.site).extra(select={
            'name__lower': 'LOWER(query_string)'}).order_by(
            orm_sort)

    search_string = request.GET.get('q', '')

    if search_string:
        feeds = feeds.filter(Q(feed_url__icontains=search_string) |
                             Q(name__icontains=search_string) |
                             Q(webpage__icontains=search_string) |
                             Q(description__icontains=search_string))
        searches = searches.filter(query_string__icontains=search_string)

    category = request.GET.get('category')
    if category:
        category = get_object_or_404(models.Category, pk=category)
        feeds = feeds.filter(auto_categories=category)
        searches = searches.filter(auto_categories=category)

    author = request.GET.get('author')
    if author:
        author = get_object_or_404(User, pk=author)
        feeds = feeds.filter(auto_authors=author)
        searches = searches.filter(auto_authors=author)

    source_filter = request.GET.get('filter')
    if source_filter == 'search':
        queryset = searches
    elif source_filter in ('feed', 'user'):
        q = Q(feed_url__iregex=models.VIDEO_SERVICE_REGEXES[0][1])
        for service, regexp in models.VIDEO_SERVICE_REGEXES[1:]:
            q = q | Q(feed_url__iregex=regexp)
        if source_filter == 'user':
            queryset = feeds.filter(q)
        else:
            queryset = feeds.exclude(q)
    else:
        reverse = False
        if orm_sort[0] == '-':
            reverse = True
            orm_sort = orm_sort[1:]
        feeds_list = [(force_unicode(getattr(feed, orm_sort)), feed)
                      for feed in feeds]
        searches_list = [(force_unicode(getattr(search, orm_sort)), search)
                         for search in searches]
        queryset = [l[1] for l in sorted(feeds_list + searches_list,
                                         reverse=reverse)]

    if sort.endswith('type'):
        reverse = (sort[0] == '-')
        queryset = sorted(queryset,
                          reverse=reverse,
                          key=lambda source: source.source_type().lower())
    paginator = Paginator(queryset, 15)
    try:
        page = paginator.page(int(request.GET.get('page', 1)))
    except InvalidPage:
        raise Http404

    if request.method == 'POST':
        formset = forms.SourceFormset(request.POST, request.FILES,
                                      queryset=MockQueryset(page.object_list))
        if formset.is_valid():
            formset.save()
            bulk_action = request.POST.get('bulk_action', '')
            for form in formset.bulk_forms:
                if bulk_action == 'remove':
                    if request.POST.get('keep'):
                        form.instance.video_set.all().update(
                            search=None, feed=None)
                    form.instance.delete()

            for form in formset.deleted_forms:
                if request.POST.get('keep'):
                    form.instance.video_set.all().update(search=None,
                                                         feed=None)
                form.instance.delete()

            path = request.get_full_path()
            if '?' in path:
                return HttpResponseRedirect(path + '&successful')
            else:
                return HttpResponseRedirect(path + '?successful')
    else:
        formset = forms.SourceFormset(queryset=MockQueryset(page.object_list))

    return render_to_response('localtv/admin/manage_sources.html',
                              {
            'add_feed_form': forms.AddFeedForm(),
            'page': page,
            'paginator': paginator,
            'headers': headers,
            'search_string': search_string,
            'source_filter': source_filter,
            'categories': models.Category.objects.filter(
                site=request.sitelocation.site),
            'users': User.objects.order_by('username'),
            'successful': 'successful' in request.GET,
            'formset': formset},
                              context_instance=RequestContext(request))
예제 #6
0
def index(request):
    """
    Displays the list of playlists for a given user, or the current one if none
    is specified.
    """
    if not request.user.is_authenticated():
        return redirect_to_login(request.get_full_path())

    if request.user_is_admin and request.GET.get("show", None) in ("all", "waiting"):
        headers = SortHeaders(
            request,
            (
                ("Playlist", "name"),
                ("Description", None),
                ("Slug", None),
                ("Username", "user__username"),
                ("Status", None),
                ("Video Count", "items__count"),
            ),
        )
        if request.GET.get("show") == "all":
            playlists = Playlist.objects.all()
        else:
            playlists = Playlist.objects.filter(status=PLAYLIST_STATUS_WAITING_FOR_MODERATION)
    else:
        headers = SortHeaders(
            request,
            (
                ("Playlist", "name"),
                ("Description", None),
                ("Slug", None),
                ("Status", None),
                ("Video Count", "items__count"),
            ),
        )
        playlists = Playlist.objects.filter(user=request.user)

    if headers.ordering == "items__count":
        playlists = playlists.annotate(Count("items"))
    playlists = playlists.order_by(headers.order_by())

    formset = forms.PlaylistFormSet(queryset=playlists)
    form = forms.PlaylistForm()
    if request.method == "POST":
        if "form-TOTAL_FORMS" in request.POST:  # formset
            formset = forms.PlaylistFormSet(request.POST, queryset=playlists)
            if formset.is_valid():
                formset.save()
                if request.POST.get("bulk_action") == "delete":
                    for form in formset.bulk_forms:
                        form.instance.delete()
                elif request.POST.get("bulk_action") == "public":
                    if request.user_is_admin:
                        new_status = PLAYLIST_STATUS_PUBLIC
                    else:
                        new_status = PLAYLIST_STATUS_WAITING_FOR_MODERATION
                    for form in formset.bulk_forms:
                        if form.instance.status < PLAYLIST_STATUS_PUBLIC:
                            form.instance.status = new_status
                            form.instance.save()
                elif request.POST.get("bulk_action") == "private":
                    for form in formset.bulk_forms:
                        form.instance.status = PLAYLIST_STATUS_PRIVATE
                        form.instance.save()
                return HttpResponseRedirect(request.path)
        else:
            video = None
            if "video" in request.POST and "name" in request.POST:
                # Adding a new playlist from a video view.  All we get is a
                # name, so make up the slug.
                video = get_object_or_404(Video, pk=request.POST["video"])
                POST = request.POST.copy()
                POST["slug"] = slugify(request.POST["name"])
                POST["description"] = ""
                request.POST = POST
            form = forms.PlaylistForm(request.POST, instance=Playlist(user=request.user))
            if form.is_valid():
                playlist = form.save()
                if video:
                    playlist.add_video(video)
                    return HttpResponseRedirect("%s?playlist=%i" % (video.get_absolute_url(), playlist.pk))
                return HttpResponseRedirect(request.path)

    return render_to_response(
        "localtv/playlists/index.html",
        {"form": form, "headers": headers, "formset": formset},
        context_instance=RequestContext(request),
    )
예제 #7
0
def bulk_edit(request):
    if ('just_the_author_field' in request.GET and 'video_id' in request.GET):
        # generate just the particular form that the user wants
        template_data = {}
        form_prefix = request.GET['just_the_author_field']
        video = get_object_or_404(models.Video,
                                  pk=int(request.GET['video_id']))
        cache_for_form_optimization = {}
        form = forms.BulkEditVideoForm(
            instance=video,
            prefix=form_prefix,
            cache_for_form_optimization=cache_for_form_optimization)
        template_data['form'] = form
        template = 'localtv/admin/bulk_edit_author_widget.html'
        return render_to_response(template,
                                  template_data,
                                  context_instance=RequestContext(request))

    videos = models.Video.objects.filter(status=models.VIDEO_STATUS_ACTIVE,
                                         site=request.sitelocation().site)

    if 'filter' in request.GET:
        filter_type = request.GET['filter']
        if filter_type == 'featured':
            videos = videos.exclude(last_featured=None)
        elif filter_type == 'rejected':
            videos = models.Video.objects.filter(
                status=models.VIDEO_STATUS_REJECTED,
                site=request.sitelocation().site)
        elif filter_type == 'no-attribution':
            videos = videos.filter(authors=None)
        elif filter_type == 'no-category':
            videos = videos.filter(categories=None)
        elif filter_type == 'unapproved':
            videos = models.Video.objects.filter(
                status=models.VIDEO_STATUS_UNAPPROVED,
                site=request.sitelocation().site)

    videos = videos.select_related('feed', 'search', 'site')

    category = request.GET.get('category', '')
    try:
        category = int(category)
    except ValueError:
        category = ''

    if category != '':
        videos = videos.filter(categories__pk=category).distinct()

    author = request.GET.get('author', '')
    try:
        author = int(author)
    except ValueError:
        author = ''

    if author != '':
        videos = videos.filter(authors__pk=author).distinct()

    search_string = request.GET.get('q', '')
    if search_string != '':
        videos = videos.filter(
            Q(description__icontains=search_string)
            | Q(name__icontains=search_string)
            | Q(categories__name__icontains=search_string)
            | Q(user__username__icontains=search_string)
            | Q(user__first_name__icontains=search_string)
            | Q(user__last_name__icontains=search_string)
            | Q(video_service_user__icontains=search_string)
            | Q(feed__name__icontains=search_string)).distinct()

    headers = SortHeaders(request, (
        ('Video Title', 'name'),
        ('Source', 'source'),
        ('Categories', None),
        ('Date Published', '-when_published'),
        ('Date Imported', '-when_submitted'),
    ))

    sort = headers.order_by()
    if sort.endswith('source'):
        reverse = sort.startswith('-')
        videos = videos.extra(
            select={'name_lower': 'LOWER(localtv_video.name)'})
        videos = videos.order_by(
            sort.replace('source', 'calculated_source_type'))
    elif sort.endswith('name'):
        videos = videos.extra(select={
            'name_lower': 'LOWER(localtv_video.name)'
        }).order_by(sort.replace('name', 'name_lower'))
    else:
        videos = videos.order_by(sort)
    video_paginator = Paginator(videos, 30)
    try:
        page = video_paginator.page(int(request.GET.get('page', 1)))
    except ValueError:
        return HttpResponseBadRequest('Not a page number')
    except EmptyPage:
        page = video_paginator.page(video_paginator.num_pages)

    if request.method == 'POST':
        formset = forms.VideoFormSet(request.POST,
                                     request.FILES,
                                     queryset=page.object_list)
        if formset.is_valid():
            tier_prevented_some_action = False
            tier = request.sitelocation().get_tier()
            videos_approved_so_far = 0

            for form in list(formset.deleted_forms):
                form.cleaned_data[DELETION_FIELD_NAME] = False
                form.instance.status = models.VIDEO_STATUS_REJECTED
                form.instance.save()
            bulk_edits = formset.extra_forms[0].cleaned_data
            for key in list(
                    bulk_edits.keys()):  # get the list because we'll be
                # changing the dictionary
                if not bulk_edits[key]:
                    del bulk_edits[key]
            bulk_action = request.POST.get('bulk_action', '')
            if bulk_action:
                bulk_edits['action'] = bulk_action
            if bulk_edits:
                for form in formset.initial_forms:
                    if not form.cleaned_data['BULK']:
                        continue
                    for key, value in bulk_edits.items():
                        if key == 'action':  # do something to the video
                            if value == 'delete':
                                form.instance.status = \
                                    models.VIDEO_STATUS_REJECTED
                            elif value == 'approve':
                                if (request.sitelocation().enforce_tiers()
                                        and tier.remaining_videos() <=
                                        videos_approved_so_far):
                                    tier_prevented_some_action = True
                                else:
                                    form.instance.status = \
                                        models.VIDEO_STATUS_ACTIVE
                                    videos_approved_so_far += 1
                            elif value == 'unapprove':
                                form.instance.status = \
                                    models.VIDEO_STATUS_UNAPPROVED
                            elif value == 'feature':
                                if form.instance.status != models.VIDEO_STATUS_ACTIVE:
                                    if (request.sitelocation().enforce_tiers()
                                            and tier.remaining_videos() <=
                                            videos_approved_so_far):
                                        tier_prevented_some_action = True
                                    else:
                                        form.instance.status = \
                                            models.VIDEO_STATUS_ACTIVE
                                if form.instance.status == models.VIDEO_STATUS_ACTIVE:
                                    form.instance.last_featured = datetime.now(
                                    )
                            elif value == 'unfeature':
                                form.instance.last_featured = None
                        elif key == 'tags':
                            form.cleaned_data[key] = value
                        elif key == 'categories':
                            # categories append, not replace
                            form.cleaned_data[key] = (
                                list(form.cleaned_data[key]) + list(value))
                        elif key == 'authors':
                            form.cleaned_data[key] = value
                        else:
                            setattr(form.instance, key, value)
            formset.forms = formset.initial_forms  # get rid of the extra bulk
            # edit form
            formset.can_delete = False
            formset.save()
            path_with_success = None
            if 'successful' in request.GET:
                path_with_success = request.get_full_path()
            else:
                path = request.get_full_path()
                if '?' in path:
                    path_with_success = path + '&successful'
                else:
                    path_with_success = path + '?successful'

            if tier_prevented_some_action:
                path = path_with_success + '&not_all_actions_done'
            else:
                path = path_with_success

            return HttpResponseRedirect(path)
    else:
        formset = forms.VideoFormSet(queryset=page.object_list)

    return render_to_response('localtv/admin/bulk_edit.html', {
        'formset':
        formset,
        'headers':
        headers,
        'search_string':
        search_string,
        'page':
        page,
        'categories':
        models.Category.objects.filter(site=request.sitelocation().site),
        'users':
        User.objects.order_by('username')
    },
                              context_instance=RequestContext(request))
예제 #8
0
def index(request):
    """
    Displays the list of playlists for a given user, or the current one if none
    is specified.
    """
    if not request.user.is_authenticated():
        return redirect_to_login(request.get_full_path())

    if request.user_is_admin() and request.GET.get('show',
                                                   None) in ('all', 'waiting'):
        headers = SortHeaders(request,
                              (('Playlist', 'name'), ('Description', None),
                               ('Slug', None), ('Username', 'user__username'),
                               ('Status', None),
                               ('Video Count', 'items__count')))
        if request.GET.get('show') == 'all':
            playlists = Playlist.objects.all()
        else:
            playlists = Playlist.objects.filter(
                status=PLAYLIST_STATUS_WAITING_FOR_MODERATION)
    else:
        headers = SortHeaders(request,
                              (('Playlist', 'name'), ('Description', None),
                               ('Slug', None), ('Status', None),
                               ('Video Count', 'items__count')))
        playlists = Playlist.objects.filter(user=request.user)

    if headers.ordering == 'items__count':
        playlists = playlists.annotate(Count('items'))
    playlists = playlists.order_by(headers.order_by())

    formset = forms.PlaylistFormSet(queryset=playlists)
    form = forms.PlaylistForm()
    if request.method == 'POST':
        if 'form-TOTAL_FORMS' in request.POST:  # formset
            formset = forms.PlaylistFormSet(request.POST, queryset=playlists)
            if formset.is_valid():
                formset.save()
                if request.POST.get('bulk_action') == 'delete':
                    for form in formset.bulk_forms:
                        form.instance.delete()
                elif request.POST.get('bulk_action') == 'public':
                    if request.user_is_admin():
                        new_status = PLAYLIST_STATUS_PUBLIC
                    else:
                        new_status = PLAYLIST_STATUS_WAITING_FOR_MODERATION
                    for form in formset.bulk_forms:
                        if form.instance.status < PLAYLIST_STATUS_PUBLIC:
                            form.instance.status = new_status
                            form.instance.save()
                elif request.POST.get('bulk_action') == 'private':
                    for form in formset.bulk_forms:
                        form.instance.status = PLAYLIST_STATUS_PRIVATE
                        form.instance.save()
                return HttpResponseRedirect(request.path)
        else:
            video = None
            if 'video' in request.POST and 'name' in request.POST:
                # Adding a new playlist from a video view.  All we get is a
                # name, so make up the slug.
                video = get_object_or_404(Video, pk=request.POST['video'])
                POST = request.POST.copy()
                POST['slug'] = slugify(request.POST['name'])
                POST['description'] = ''
                request.POST = POST
            form = forms.PlaylistForm(request.POST,
                                      instance=Playlist(user=request.user))
            if form.is_valid():
                playlist = form.save()
                if video:
                    playlist.add_video(video)
                    return HttpResponseRedirect(
                        '%s?playlist=%i' %
                        (video.get_absolute_url(), playlist.pk))
                return HttpResponseRedirect(request.path)

    return render_to_response('localtv/playlists/index.html', {
        'form': form,
        'headers': headers,
        'formset': formset
    },
                              context_instance=RequestContext(request))
예제 #9
0
def index(request):
    """
    Displays the list of playlists for a given user, or the current one if none
    is specified.
    """
    if not request.user.is_authenticated():
        return redirect_to_login(request.get_full_path())

    if request.user_is_admin and request.GET.get(
        'show', None) in ('all', 'waiting'):
        headers = SortHeaders(request, (
                ('Playlist', 'name'),
                ('Description', None),
                ('Slug', None),
                ('Username', 'user__username'),
                ('Status', None),
                ('Video Count', 'items__count')
                ))
        if request.GET.get('show') == 'all':
            playlists = Playlist.objects.all()
        else:
            playlists = Playlist.objects.filter(
                status=PLAYLIST_STATUS_WAITING_FOR_MODERATION)
    else:
        headers = SortHeaders(request, (
                ('Playlist', 'name'),
                ('Description', None),
                ('Slug', None),
                ('Status', None),
                ('Video Count', 'items__count')
                ))
        playlists = Playlist.objects.filter(user=request.user)

    if headers.ordering == 'items__count':
        playlists = playlists.annotate(Count('items'))
    playlists = playlists.order_by(headers.order_by())


    formset = forms.PlaylistFormSet(queryset=playlists)
    form = forms.PlaylistForm()
    if request.method == 'POST':
        if 'form-TOTAL_FORMS' in request.POST: # formset
            formset = forms.PlaylistFormSet(request.POST, queryset=playlists)
            if formset.is_valid():
                formset.save()
                if request.POST.get('bulk_action') == 'delete':
                    for form in formset.bulk_forms:
                        form.instance.delete()
                elif request.POST.get('bulk_action') == 'public':
                    if request.user_is_admin:
                        new_status = PLAYLIST_STATUS_PUBLIC
                    else:
                        new_status = PLAYLIST_STATUS_WAITING_FOR_MODERATION
                    for form in formset.bulk_forms:
                        if form.instance.status < PLAYLIST_STATUS_PUBLIC:
                            form.instance.status = new_status
                            form.instance.save()
                elif request.POST.get('bulk_action') == 'private':
                    for form in formset.bulk_forms:
                        form.instance.status = PLAYLIST_STATUS_PRIVATE
                        form.instance.save()
                return HttpResponseRedirect(request.path)
        else:
            video = None
            if 'video' in request.POST and 'name' in request.POST:
                # Adding a new playlist from a video view.  All we get is a
                # name, so make up the slug.
                video = get_object_or_404(Video, pk=request.POST['video'])
                POST = request.POST.copy()
                POST['slug'] = slugify(request.POST['name'])
                POST['description'] = ''
                request.POST = POST
            form = forms.PlaylistForm(request.POST,
                                      instance=Playlist(
                    user=request.user))
            if form.is_valid():
                playlist = form.save()
                if video:
                    playlist.add_video(video)
                    return HttpResponseRedirect('%s?playlist=%i' % (
                            video.get_absolute_url(),
                            playlist.pk))
                return HttpResponseRedirect(request.path)

    return render_to_response('localtv/playlists/index.html',
                              {'form': form,
                               'headers': headers,
                               'formset': formset},
                              context_instance=RequestContext(request))
예제 #10
0
def manage_sources(request):
    headers = SortHeaders(request,
                          (('Source', 'name__lower'), ('Categories', None),
                           ('User Attribution', None), ('Type', 'type'),
                           ('Auto Approve', 'auto_approve')))

    sort = headers.order_by()
    if sort.endswith('type'):
        if sort[0] == '-':
            orm_sort = '-name__lower'
        else:
            orm_sort = 'name__lower'
    else:
        orm_sort = sort
    feeds = models.Feed.objects.filter(
        site=request.sitelocation.site,
        status=models.FEED_STATUS_ACTIVE).extra(select={
            'name__lower': 'LOWER(name)'
        }).order_by(orm_sort)
    searches = models.SavedSearch.objects.filter(
        site=request.sitelocation.site).extra(
            select={
                'name__lower': 'LOWER(query_string)'
            }).order_by(orm_sort)

    search_string = request.GET.get('q', '')

    if search_string:
        feeds = feeds.filter(
            Q(feed_url__icontains=search_string)
            | Q(name__icontains=search_string)
            | Q(webpage__icontains=search_string)
            | Q(description__icontains=search_string))
        searches = searches.filter(query_string__icontains=search_string)

    category = request.GET.get('category')
    if category:
        category = get_object_or_404(models.Category, pk=category)
        feeds = feeds.filter(auto_categories=category)
        searches = searches.filter(auto_categories=category)

    author = request.GET.get('author')
    if author:
        author = get_object_or_404(User, pk=author)
        feeds = feeds.filter(auto_authors=author)
        searches = searches.filter(auto_authors=author)

    source_filter = request.GET.get('filter')
    if source_filter == 'search':
        queryset = searches
    elif source_filter in ('feed', 'user'):
        q = Q(feed_url__iregex=models.VIDEO_SERVICE_REGEXES[0][1])
        for service, regexp in models.VIDEO_SERVICE_REGEXES[1:]:
            q = q | Q(feed_url__iregex=regexp)
        if source_filter == 'user':
            queryset = feeds.filter(q)
        else:
            queryset = feeds.exclude(q)
    else:
        reverse = False
        if orm_sort[0] == '-':
            reverse = True
            orm_sort = orm_sort[1:]
        feeds_list = [(force_unicode(getattr(feed, orm_sort)), feed)
                      for feed in feeds]
        searches_list = [(force_unicode(getattr(search, orm_sort)), search)
                         for search in searches]
        queryset = [
            l[1] for l in sorted(feeds_list + searches_list, reverse=reverse)
        ]

    if sort.endswith('type'):
        reverse = (sort[0] == '-')
        queryset = sorted(queryset,
                          reverse=reverse,
                          key=lambda source: source.source_type().lower())
    paginator = Paginator(queryset, 15)
    try:
        page = paginator.page(int(request.GET.get('page', 1)))
    except InvalidPage:
        raise Http404

    if request.method == 'POST':
        formset = forms.SourceFormset(request.POST,
                                      request.FILES,
                                      queryset=MockQueryset(page.object_list))
        if formset.is_valid():
            formset.save()
            bulk_action = request.POST.get('bulk_action', '')
            for form in formset.bulk_forms:
                if bulk_action == 'remove':
                    if request.POST.get('keep'):
                        form.instance.video_set.all().update(search=None,
                                                             feed=None)
                    form.instance.delete()

            for form in formset.deleted_forms:
                if request.POST.get('keep'):
                    form.instance.video_set.all().update(search=None,
                                                         feed=None)
                form.instance.delete()

            path = request.get_full_path()
            if '?' in path:
                return HttpResponseRedirect(path + '&successful')
            else:
                return HttpResponseRedirect(path + '?successful')
    else:
        formset = forms.SourceFormset(queryset=MockQueryset(page.object_list))

    return render_to_response('localtv/admin/manage_sources.html', {
        'add_feed_form':
        forms.AddFeedForm(),
        'page':
        page,
        'paginator':
        paginator,
        'headers':
        headers,
        'search_string':
        search_string,
        'source_filter':
        source_filter,
        'categories':
        models.Category.objects.filter(site=request.sitelocation.site),
        'users':
        User.objects.order_by('username'),
        'successful':
        'successful' in request.GET,
        'formset':
        formset
    },
                              context_instance=RequestContext(request))
예제 #11
0
def bulk_edit(request):
    videos = models.Video.objects.filter(status=models.VIDEO_STATUS_ACTIVE, site=request.sitelocation.site)
    videos = videos.select_related("feed", "search", "site")

    if "filter" in request.GET:
        filter_type = request.GET["filter"]
        if filter_type == "featured":
            videos = videos.exclude(last_featured=None)
        elif filter_type == "rejected":
            videos = models.Video.objects.filter(status=models.VIDEO_STATUS_REJECTED, site=request.sitelocation.site)
        elif filter_type == "no-attribution":
            videos = videos.filter(authors=None)
        elif filter_type == "no-category":
            videos = videos.filter(categories=None)

    category = request.GET.get("category", "")
    try:
        category = int(category)
    except ValueError:
        category = ""

    if category != "":
        videos = videos.filter(categories__pk=category).distinct()

    author = request.GET.get("author", "")
    try:
        author = int(author)
    except ValueError:
        author = ""

    if author != "":
        videos = videos.filter(authors__pk=author).distinct()

    search_string = request.GET.get("q", "")
    if search_string != "":
        videos = videos.filter(
            Q(description__icontains=search_string)
            | Q(name__icontains=search_string)
            | Q(categories__name__icontains=search_string)
            | Q(user__username__icontains=search_string)
            | Q(user__first_name__icontains=search_string)
            | Q(user__last_name__icontains=search_string)
            | Q(video_service_user__icontains=search_string)
            | Q(feed__name__icontains=search_string)
        ).distinct()

    headers = SortHeaders(
        request,
        (
            ("Video Title", "name"),
            ("Source", "source"),
            ("Categories", None),
            ("Date Published", "-when_published"),
            ("Date Imported", "-when_submitted"),
        ),
    )

    sort = headers.order_by()
    if sort.endswith("source"):
        reverse = sort.startswith("-")
        videos = videos.extra(select={"name_lower": "LOWER(localtv_video.name)"})
        videos = MockQueryset(
            sorted(
                videos.order_by(sort.replace("source", "name_lower")), reverse=reverse, key=methodcaller("source_type")
            )
        )
    elif sort.endswith("name"):
        videos = videos.extra(select={"name_lower": "LOWER(localtv_video.name)"}).order_by(
            sort.replace("name", "name_lower")
        )
    else:
        videos = videos.order_by(sort)
    video_paginator = Paginator(videos, 30)
    try:
        page = video_paginator.page(int(request.GET.get("page", 1)))
    except ValueError:
        return HttpResponseBadRequest("Not a page number")
    except EmptyPage:
        page = video_paginator.page(video_paginator.num_pages)

    if request.method == "POST":
        formset = forms.VideoFormSet(request.POST, request.FILES, queryset=page.object_list)
        if formset.is_valid():
            for form in list(formset.deleted_forms):
                form.cleaned_data[DELETION_FIELD_NAME] = False
                form.instance.status = models.VIDEO_STATUS_REJECTED
                form.instance.save()
            bulk_edits = formset.extra_forms[0].cleaned_data
            for key in list(bulk_edits.keys()):  # get the list because we'll be
                # changing the dictionary
                if not bulk_edits[key]:
                    del bulk_edits[key]
            bulk_action = request.POST.get("bulk_action", "")
            if bulk_action:
                bulk_edits["action"] = bulk_action
            if bulk_edits:
                for form in formset.initial_forms:
                    if not form.cleaned_data["BULK"]:
                        continue
                    for key, value in bulk_edits.items():
                        if key == "action":  # do something to the video
                            if value == "delete":
                                form.instance.status = models.VIDEO_STATUS_REJECTED
                            elif value == "approve":
                                form.instance.status = models.VIDEO_STATUS_ACTIVE
                            elif value == "unapprove":
                                form.instance.status = models.VIDEO_STATUS_UNAPPROVED
                            elif value == "feature":
                                form.instance.last_featured = datetime.now()
                            elif value == "unfeature":
                                form.instance.last_featured = None
                        elif key == "tags":
                            form.instance.tags = value
                        elif key == "categories":
                            # categories append, not replace
                            form.cleaned_data[key] = list(form.cleaned_data[key]) + list(value)
                        elif key == "authors":
                            form.cleaned_data[key] = value
                        else:
                            setattr(form.instance, key, value)
            formset.forms = formset.initial_forms  # get rid of the extra bulk
            # edit form
            formset.can_delete = False
            formset.save()
            if "successful" in request.GET:
                return HttpResponseRedirect(request.get_full_path())
            else:
                path = request.get_full_path()
                if "?" in path:
                    return HttpResponseRedirect(path + "&successful")
                else:
                    return HttpResponseRedirect(path + "?successful")
    else:
        formset = forms.VideoFormSet(queryset=page.object_list)

    return render_to_response(
        "localtv/admin/bulk_edit.html",
        {
            "formset": formset,
            "headers": headers,
            "search_string": search_string,
            "page": page,
            "categories": models.Category.objects.filter(site=request.sitelocation.site),
            "users": User.objects.order_by("username"),
        },
        context_instance=RequestContext(request),
    )