예제 #1
0
파일: views.py 프로젝트: drx/archfinch
 def invalid_search():
     if json:
         return render_to_response(
             "search/invalid.json", locals(), context_instance=RequestContext(request), mimetype="application/json"
         )
     else:
         return render_to_response("search/invalid.html", locals(), context_instance=RequestContext(request))
예제 #2
0
파일: views.py 프로젝트: drx/archfinch
def similar(request, page=None):
    '''
    Show users most similar to the logged in user.
    '''

    if request.user.is_authenticated():
        if page is None:
            page = 1
        else:
            page = int(page)

        n = 10
        
        similarity_max = get_max_similarity(request.user)
        similar_users = request.user.similar()
        count = similar_users.count()

        # pagination
        similar_users, paginator, current_page, page_range = paginate(similar_users, page, n)

        likes = likes_gen(similar_users, request.user)

        return render_to_response('user/similar.html', locals(), context_instance=RequestContext(request))
    else:
        return render_to_response('user/similar_anonymous.html', context_instance=RequestContext(request))
예제 #3
0
파일: views.py 프로젝트: drx/archfinch
def review_edit(request, item_id):
    if request.user.is_anonymous():
        from django.http import HttpResponseForbidden
        return HttpResponseForbidden()

    item = get_object_or_404(Item, pk=base36_to_int(item_id))

    try:
        review = request.user.review_set.get(item=item)
    except Review.DoesNotExist:
        review = None

    if request.method == 'POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            text = form.cleaned_data['text']
            if review is None:
                review = Review(item=item, user=request.user, text=text)
                review.save()
            else:
                review.text = text
                review.save()

            action, created = Action.objects.get_or_create(type=Action.types['review'], review=review, user=request.user)
            action.save()

            return HttpResponseRedirect(reverse('review', args=[request.user.username, item_id, slugify(item.name)]))
    else:
        if review is not None:
            text = review.text
        else:
            text = ''
        form = ReviewForm(initial={'text': text})

    return render_to_response('user/review_edit.html', locals(), context_instance=RequestContext(request))
예제 #4
0
파일: views.py 프로젝트: drx/archfinch
def reviews(request, username, page=None):
    if page is None:
        page = 1
    else:
        page = int(page)
    
    n = 10

    review_user = get_object_or_404(User, username=username)

    reviews = Review.objects.filter(user=review_user).extra(
        select={
            'rating': 'SELECT rating FROM main_opinion WHERE main_opinion.item_id=main_review.item_id AND main_opinion.user_id=main_review.user_id',
            'time': 'SELECT time FROM main_action WHERE main_review.id=main_action.review_id AND type=2',
        },
    ).select_related('item').order_by('-time')

    # pagination
    reviews, paginator, current_page, page_range = paginate(reviews, page, n)

    for review in reviews:
        review.rating_verbose = Opinion(rating=review.rating).get_third_person()

    single = False

    return render_to_response('user/reviews.html', locals(), context_instance=RequestContext(request))
예제 #5
0
파일: views.py 프로젝트: drx/archfinch
def edit(request, list_id):
    list_id = base36_to_int(list_id)
    list = get_object_or_404(List, pk=list_id)

    if list.owner != request.user:
        return forbidden(request)

    return render_to_response('lists/edit.html', locals(), context_instance=RequestContext(request))
예제 #6
0
파일: views.py 프로젝트: drx/archfinch
def explore_tags(request, publish=False):
    cache_key = 'popular_tags'
    cached_value = cache.get(cache_key)
    if cached_value:
        popular_tags = cached_value
    else:
        popular_tags = list(Tag.objects.related_tags([]))
        cache.set(cache_key, popular_tags, 60*60*6)

    response = render_to_response("main/explore_tags.html", locals(), context_instance=RequestContext(request))
    response.publish_static = True
    return response
예제 #7
0
파일: views.py 프로젝트: drx/archfinch
def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            new_user.backend = 'archfinch.users.auth_backends.ModelBackend'
            auth_login(request, new_user)

            return HttpResponseRedirect("/")
    else:
        form = SignupForm()
    return render_to_response("account/signup.html",
        {'form': form},
        context_instance=RequestContext(request))
예제 #8
0
파일: views.py 프로젝트: drx/archfinch
def review_show(request, username, item_id):
    item_id = base36_to_int(item_id)
    review_user = get_object_or_404(User, username=username)
    item = get_object_or_404(Item, pk=item_id)
    review = get_object_or_404(Review, user=review_user, item=item)
    try:
        opinion = review_user.opinion_set.get(item=item)
    except Opinion.DoesNotExist:
        opinion = None

    time = Action.objects.get(review=review, type=Action.types['review']).time

    reviews = [{'item': item, 'text': review.text, 'rating': opinion.rating, 'rating_verbose': opinion.get_third_person(), 'time': time}]
    single = True

    return render_to_response('user/reviews.html', locals(), context_instance=RequestContext(request))
예제 #9
0
파일: views.py 프로젝트: drx/archfinch
def item(request, item_id, publish=False):
    '''
    Item page.
    '''

    from django.contrib.sites.models import Site
    current_site = Site.objects.get_current()

    item_id = base36_to_int(item_id)
    item = get_object_or_404(Item.objects.select_related('category', 'profile'), pk=item_id)

    title = item.__unicode__()

    if item.is_comment():
        # item is a comment, so let's show its root and highlight it instead
        from django.utils.html import strip_tags
        from django.contrib.markup.templatetags.markup import markdown

        root = item.root()
        selected_path = root.path
        item, selected_comment_id = root, item.id

        title = strip_tags(markdown(title))

    else:
        selected_path = None

    add_comment_form = AddCommentForm()

    comment_tree = item.comment_tree(selected_path=selected_path, user=request.user)
    if item.category_id == 8:
        return redirect(reverse('list-view', args=[int_to_base36(item_id), slugify(item.name)]))

    if request.user.is_authenticated():
        also_liked = item.also_liked(user=request.user)
        try:
            opinion = request.user.opinion_set.get(item=item)
        except Opinion.DoesNotExist:
            opinion = None
            recommendation = item.recommendation(request.user)
    else:
        opinion = None
        also_liked = item.also_liked()

    response = render_to_response("main/item.html", locals(), context_instance=RequestContext(request))
    response.publish_static = True
    return response
예제 #10
0
파일: views.py 프로젝트: drx/archfinch
def edit(request, page_id=None, item_id=None):
    """
    Lets the user edit a wiki page.
    """

    # get the page
    if page_id is None and item_id is None:
        from django.core.exceptions import SuspiciousOperation

        raise SuspiciousOperation("Page id and item id were both empty")

    if page_id is None:
        item = get_object_or_404(Item, pk=base36_to_int(item_id))
        page = item.profile.page
        redirect_url = reverse("item", args=[item_id, slugify(item.name)])
    else:
        page = get_object_or_404(Page, pk=base36_to_int(page_id))
        redirect_url = reverse("wiki-page", args=[page_id])

    if request.method == "POST":
        form = PageForm(request.POST)
        if form.is_valid():
            if page is None:
                page = Page()
                page.save()
                item.profile.page = page
                item.profile.save()

            text = form.cleaned_data["text"]
            revision_text = RevisionText(text=text)
            revision_text.save()

            page.revisions.create(text=revision_text, user=request.user)
            request.user.add_points(5)

            return HttpResponseRedirect(redirect_url)
    else:
        if page is not None:
            try:
                text = page.current().text.render()
            except Revision.DoesNotExist:
                text = ""
        else:
            text = ""
        form = PageForm(initial={"text": text})

    return render_to_response("wiki/edit.html", locals(), context_instance=RequestContext(request))
예제 #11
0
파일: views.py 프로젝트: drx/archfinch
def view(request, list_id):
    list_id = base36_to_int(list_id)
    list = get_object_or_404(List, pk=list_id)
    if request.user.is_authenticated():
        entries = list.entries.all().extra(
            select={'your_rating': 'SELECT COALESCE((SELECT rating FROM main_opinion mo WHERE mo.user_id=%s AND mo.item_id=lists_entry.item_id))'},
            select_params=[request.user.id])
    else:
        entries = list.entries.all()

    if request.user.is_authenticated():
        try:
            opinion = request.user.opinion_set.get(item=list)
        except Opinion.DoesNotExist:
            opinion = None
    else:
        opinion = None

    return render_to_response('lists/view.html', locals(), context_instance=RequestContext(request))
예제 #12
0
파일: views.py 프로젝트: drx/archfinch
def add_comment(request, json=False):
    if json:
        return_data = {'success': False}

    if request.method == 'POST':
        data = {'category': 14}
        data.update(request.POST.items())
        form = AddCommentForm(data)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.submitter = request.user
            comment.save()

            request.user.add_points(1)
            
            if json:
                return_data['success'] = True
                return_data['redirect_url'] = comment.get_absolute_url()
            else:
                return HttpResponseRedirect(comment.get_absolute_url())

        else:
            if json:
                return_data['error_msg'] = form_error_msg(form.errors)
            else:
                return render_to_response('form_error.html', locals(), context_instance=RequestContext(request))

    else:
        if json:
            return_data['error_msg'] = 'Wrong request method'
        else:
            return HttpResponseRedirect('/')

    if json:
        json = simplejson.dumps(return_data)
        return HttpResponse(json, mimetype='application/json')
예제 #13
0
파일: views.py 프로젝트: drx/archfinch
def user(request, username):
    viewed_user = get_object_or_404(User, username=username)
    lists = viewed_user.list_set.all()
    return render_to_response('lists/user.html', locals(), context_instance=RequestContext(request))
예제 #14
0
파일: views.py 프로젝트: drx/archfinch
def overview(request, username, category_slug=None, page=None, json=None):
    viewed_user = get_object_or_404(User, username=username)

    if page is None:
        page = 1
    else:
        page = int(page)
    
    n = 100

    if category_slug is not None and category_slug:
        category = Category.objects.get(slug=category_slug)
    else:
        category = None

    hide = False
    if viewed_user.id == 1:
        # don't show drx's links
        hide = True
    categories = viewed_user.categories(hide=hide)
    your_profile = False
    if request.user==viewed_user:
        your_profile = True

    select=[
        ('review', 'SELECT EXISTS (SELECT 1 FROM main_review WHERE main_review.user_id = %s AND main_review.item_id = main_item.id)'),
        ('action_time', 'SELECT time FROM main_action WHERE main_action.opinion_id = main_opinion.id')
    ]
    select_params=[viewed_user.id]

    if request.user.is_authenticated():
        select += [('your_rating', 'SELECT rating FROM main_opinion mo2 WHERE mo2.user_id = %s AND mo2.item_id = main_item.id')]
        select_params += [request.user.id]

    show_controversial = False

    select = SortedDict(select)

    opinions = Opinion.objects.filter(user__exact=viewed_user).select_related('item__category').order_by('-action__time', '-rating','item__name').extra(
        select=select, select_params=select_params
    )
    if category is not None:
        opinions = opinions.filter(item__category=category)
    else:
        opinions = opinions.exclude(item__category__name='Lists')
    if hide:
        opinions = opinions.filter(item__category__hide=False)

    category_counts = viewed_user.categories(hide=hide)

    if request.user==viewed_user or not request.user.is_authenticated():
        similarity = 0
        similarity_max = 10

    else:
        similarity_max = get_max_similarity(request.user)

        try:
            similarity = viewed_user.similarity_set.get(
                user2=request.user.id).value
        except ObjectDoesNotExist:
            similarity = 0

    lists = viewed_user.list_set.all()

    # pagination
    opinions, paginator, current_page, page_range = paginate(opinions, page, n)

    if json:
        return render_to_response('user/overview.json', locals(), context_instance=RequestContext(request), mimetype='application/json')
    else:
        return render_to_response('user/overview.html', locals(), context_instance=RequestContext(request))
예제 #15
0
파일: views.py 프로젝트: drx/archfinch
def recommend(request, followed=False, category_slug=None, before=None, usernames=None, tag_names=None, publish=False, json=False, feed=False, feed_username=None):
    '''
    Shows a list of recommendations.
    '''
    if before is not None:
        before = base36_to_int(before)
     
    fresh = False
    tags = None
    new = False
    if tag_names:
        fresh = True
        category = None
        tag_names = tag_names.split('/')
        tags = Tag.objects.filter(name__in=tag_names)
        selected_tags = tag_names

    elif category_slug is not None and category_slug:
        if category_slug == 'fresh':
            fresh = True
            category = None
        elif category_slug == 'new':
            fresh = True
            category = None
            new = True
        else:
            category = Category.objects.get(slug=category_slug)
    elif followed:
        fresh = True
        category = None
    else:
        category = None

    if not tag_names:
        tag_names = []
    if tag_names:
        tag_names_k = ','.join(tag_names)
    else:
        tag_names_k = ''

    if not followed:
        related_cache_key = 'related_tags;%s' % (tag_names_k,)
        related_cache_key = related_cache_key.replace(' ', '_space_')
        cached_value = cache.get(related_cache_key)
        if cached_value:
            related_tags = cached_value
        else:
            related_tags = list(Tag.objects.related_tags(tags))
            cache.set(related_cache_key, related_tags, 60*60*6)

    n = 50
    if category and category.name in ('Videos', 'Pics') or fresh:
        n = 20

    if usernames is not None:
        usernames = usernames.split(',')
        users = list(map(lambda un: get_object_or_404(User, username=un), usernames))
        usernames_specified = True

    elif feed_username is not None:
        usernames = [feed_username]
        users = [get_object_or_404(User, username=feed_username)]
        usernames_specified = False

    else:
        usernames = [request.user.username]
        users = [request.user]
        usernames_specified = False


    if followed and (users[0].is_anonymous() or not users[0].tagfollow_set.exists() or (request.user.is_anonymous() and not feed_username)):
        recommendations = []
        if feed:
            return locals()
        return render_to_response('main/followed_anonymous.html', locals(), context_instance=RequestContext(request))

    user_ids = map(lambda u: u.id, users)
    usernames_k = '+'.join(sorted(set(map(str, user_ids))))
    usernames_joined = ','.join(usernames)

    try:
        opinion_count = users[0].__class__.objects.filter(pk__in=user_ids).aggregate(Count('opinion'))['opinion__count']
        if opinion_count < 10:
            generic = True
        else:
            generic = False
    except AttributeError:
        generic = True

    if followed:
        generic = False

    if fresh and request.user.is_authenticated():
        generic = False

    if generic:
        usernames_k = '#generic'

    cache_key = 'recommend;%s;%s;%s;%s;%s' % (usernames_k, category_slug, tag_names_k, before, followed)
    cache_key = cache_key.replace(' ', '_space_')
    if settings.DEBUG:
        cache_timeout = 30
    else:
        cache_timeout = 15*60

    cached_value = cache.get(cache_key)

    if category is not None and category.id in (9,10,11) or fresh:
        computed = True
        from archfinch.links.models import Link
        if generic:
            recommendations = Link.objects.recommended_generic(category=category, tags=tags, new=new)
        else:
            recommendations = Link.objects.recommended(users[0], category=category, tags=tags, followed=followed, new=new)

    else:
        if before:
            start = before
        else:
            start = 0

        computed = False
        if cached_value is not None:
            if type(cached_value) == tuple and cached_value[0] == 'task':
                task_id = cached_value[1]
                recommendations = celery.result.AsyncResult(task_id)
            else:
                recommendations = cached_value
                computed = True

        else:
            if generic:
                recommendations = tasks.recommend_generic.delay(category, start)
            else:
                recommendations = tasks.recommend.delay(category, start, users)
            task_id = recommendations.task_id
            cache.set(cache_key, ('task', task_id), cache_timeout)

        if not computed and recommendations.ready():
            recommendations = recommendations.result
            cache.set(cache_key, recommendations, cache_timeout)
            computed = True

        if not computed and (publish or json):
            recommendations = recommendations.get()
            cache.set(cache_key, recommendations, cache_timeout)
            computed = True

    if not computed:
        wait_page = 'recommend'
        return render_to_response("main/wait.html", locals(), context_instance=RequestContext(request))
    else:
        if json:
            ext = 'json'
        else:
            ext = 'html'
        if category is not None and category.id in (9,10,11) or fresh:
            # links
            if before:
                before = datetime.fromtimestamp(before)
            else:
                before = datetime.now()
            recommendations = recommendations.timeslice(before=before, n=n)
            if len(recommendations) > n:
                next_before = int(time.mktime(recommendations[n].time.timetuple()))
                recommendations = recommendations[:n]

            if feed:
                return locals()
            response = render_to_response("links/recommend.%s" % (ext,), locals(), context_instance=RequestContext(request))
        else:
            if len(recommendations) > n:
                next_before = start+n
                recommendations = recommendations[:n]

            if request.user.is_authenticated():
                user_categories = request.user.categories()
                categories = Category.objects.filter(hide=False).order_by('name').values_list('id', 'element_plural', 'slug')
            response = render_to_response("main/recommend.%s" % (ext,), locals(), context_instance=RequestContext(request))

        if json:
            json_data = simplejson.dumps(response.content)
            return HttpResponse(json_data, mimetype='application/json')
        if not tags or 'hn' in tag_names:
            response.publish_static = True
        return response
예제 #16
0
파일: views.py 프로젝트: drx/archfinch
def top_users(request):
    top_users = User.objects.order_by('-karma')[:10]

    return render_to_response('user/top_users.html', locals(), context_instance=RequestContext(request))
예제 #17
0
파일: views.py 프로젝트: drx/archfinch
def query(request, query=None, page=None, json=False, autocomplete=False):
    def invalid_search():
        if json:
            return render_to_response(
                "search/invalid.json", locals(), context_instance=RequestContext(request), mimetype="application/json"
            )
        else:
            return render_to_response("search/invalid.html", locals(), context_instance=RequestContext(request))

    if "q" in request.GET:
        query = request.GET["q"]

    if page is None:
        page = 1
    else:
        page = int(page)
    n = 10

    modifiers = {"tag": []}
    words = query.split()

    if autocomplete:
        json = True

    if len(words) > 1 and words[0] == "!":
        modifiers["bang"] = True
        words = words[1:]

    words_cleaned = []
    for word in words:
        mod, colon, arg = word.partition(":")
        if not colon:
            words_cleaned.append(word)
            continue

        if mod == "in":
            modifiers["in"] = arg

        elif mod == "tag":
            modifiers["tag"].append(arg)

        else:
            words_cleaned.append(word)

    words = words_cleaned
    title = " ".join(words)

    results = Item.search.query(title).order_by("-opinion_count", "@weight").select_related("category")
    if request.user.is_authenticated() and not json:
        results = results.extra(
            select={
                "rating": "SELECT COALESCE((SELECT rating FROM main_opinion mo WHERE mo.user_id=%s AND mo.item_id=main_item.id))"
            },
            select_params=[request.user.id],
        )

    tags = Tag.objects.filter(name__in=modifiers["tag"])
    for tag in tags:
        results = results.filter(tag=tag.id)

    results_pre_categories = results
    if "in" in modifiers:
        cat_name = modifiers["in"]
        try:
            category = Category.objects.get(
                Q(name__iexact=cat_name)
                | Q(element_singular__iexact=cat_name)
                | Q(element_plural__iexact=cat_name)
                | Q(slug__iexact=cat_name)
            )
            results = results.filter(category_id=category.id)
        except Category.DoesNotExist:
            return invalid_search()

    if "bang" in modifiers and not json:
        try:
            result = results[0]
            from django.shortcuts import redirect
            from django.utils.http import int_to_base36
            from django.core.urlresolvers import reverse
            from django.template.defaultfilters import slugify

            return redirect(result.get_absolute_url())
        except IndexError:
            from django.http import Http404

            raise Http404
        except SearchError:
            return invalid_search()

    results_categories = results_pre_categories.group_by("category_id", djangosphinx_api.SPH_GROUPBY_ATTR)
    cats = map(lambda x: x._sphinx["attrs"]["@groupby"], results_categories)
    categories = Category.objects.in_bulk(cats)

    category_counts = []
    for r in results_categories:
        cat_id = r._sphinx["attrs"]["@groupby"]
        cat_count = r._sphinx["attrs"]["@count"]
        category_counts.append({"category": categories[cat_id], "count": cat_count})

    category_counts.sort(key=lambda x: x["count"], reverse=True)

    try:
        count = results.count()
    except SearchError:
        return invalid_search()

    results, paginator, current_page, page_range = paginate(results, page, n)

    if json:
        if autocomplete:
            for result in results:
                result.highlighted_name = result.name
        return render_to_response(
            "search/results.json", locals(), context_instance=RequestContext(request), mimetype="application/json"
        )
    else:
        return render_to_response("search/results.html", locals(), context_instance=RequestContext(request))
예제 #18
0
파일: views.py 프로젝트: drx/archfinch
def forbidden(request):
    resp = render_to_response('403.html', context_instance=RequestContext(request))
    resp.status_code = 403
    return resp
예제 #19
0
파일: views.py 프로젝트: drx/archfinch
def logout(request):
    if is_lazy_user(request.user):
        return render_to_response("account/logout.html", context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('loggedout'))
예제 #20
0
파일: views.py 프로젝트: drx/archfinch
def overview(request):
    if request.user.is_authenticated():
        your_lists = request.user.list_set.all()
        recommended = Item.objects.recommended([request.user], category_id=8)  # get recommended lists
    return render_to_response('lists/overview.html', locals(), context_instance=RequestContext(request))