Ejemplo n.º 1
0
def get_user_bill_reactions(request, bill):
    import json
    from website.models import Reaction

    # get aggregate counts
    reaction_subject = "bill:" + bill.congressproject_id
    emoji_counts = { }
    for r in Reaction.objects.filter(subject=reaction_subject).values("reaction").annotate(count=Count('id')):
        v = json.loads(r["reaction"])
        if isinstance(v, dict):
            for emoji in v.get("emojis", []):
                emoji_counts[emoji] = emoji_counts.get(emoji, 0) + r["count"]

    # get user's reactions
    r = Reaction.get_for_user(request).filter(subject=reaction_subject).first()
    my_emojis = set()
    if r and isinstance(r.reaction, dict):
        my_emojis = set(r.reaction.get("emojis", []))

    # get all possible emojis
    ret = [ ]
    for emoji in Reaction.EMOJI_CHOICES:
        ret.append({
            "name": emoji,
            "count": emoji_counts.get(emoji, 0),
            "me": emoji in my_emojis,
        })

    # stable sort by count so that zeroes are in our preferred order
    ret = sorted(ret, key = lambda x : -x["count"])

    return ret
Ejemplo n.º 2
0
def get_user_bill_reactions(request, bill):
    import json
    from website.models import Reaction

    # get aggregate counts
    reaction_subject = "bill:" + bill.congressproject_id
    emoji_counts = { }
    for r in Reaction.objects.filter(subject=reaction_subject).values("reaction").annotate(count=Count('id')):
        v = json.loads(r["reaction"])
        if isinstance(v, dict):
            for emoji in v.get("emojis", []):
                emoji_counts[emoji] = emoji_counts.get(emoji, 0) + r["count"]

    # get user's reactions
    r = Reaction.get_for_user(request).filter(subject=reaction_subject).first()
    my_emojis = set()
    if r and isinstance(r.reaction, dict):
        my_emojis = set(r.reaction.get("emojis", []))

    # get all possible emojis
    ret = [ ]
    for emoji in Reaction.EMOJI_CHOICES:
        ret.append({
            "name": emoji,
            "count": emoji_counts.get(emoji, 0),
            "me": emoji in my_emojis,
        })

    # stable sort by count so that zeroes are in our preferred order
    ret = sorted(ret, key = lambda x : -x["count"])

    return ret
Ejemplo n.º 3
0
def add_remove_reaction(request):
    from website.models import Reaction
    res = {"status": "error"}
    if request.method == "POST" \
        and request.POST.get("subject") \
        and request.POST.get("mode") in ("-1", "1") \
        and request.POST.get("emoji") in Reaction.EMOJI_CHOICES:

        print(request.META)

        r, isnew = Reaction.objects.get_or_create(
            subject=request.POST["subject"],
            user=request.user if request.user.is_authenticated() else None,
            anon_session_key=Reaction.get_session_key(request)
            if not request.user.is_authenticated() else None,
        )

        if isnew:
            r.extra = {
                "ip": request.META['REMOTE_ADDR'],
            }

        if not isinstance(r.reaction, dict):
            r.reaction = {}
        emojis = set(r.reaction.get("emojis", []))
        if request.POST["mode"] == "1":
            emojis.add(request.POST["emoji"])
        elif request.POST["mode"] == "-1":
            emojis.remove(request.POST["emoji"])
        r.reaction["emojis"] = sorted(emojis)
        if len(r.reaction["emojis"]) == 0:
            del r.reaction["emojis"]
        if not r.reaction:
            # no data, delete record
            r.delete()
        else:
            # save
            r.save()

    return HttpResponse(json.dumps(res), content_type="application/json")
Ejemplo n.º 4
0
def add_remove_reaction(request):
    from website.models import Reaction
    res = { "status": "error" }
    if request.method == "POST" \
        and request.POST.get("subject") \
        and request.POST.get("mode") in ("-1", "1") \
        and request.POST.get("emoji") in Reaction.EMOJI_CHOICES:

        print(request.META)

        r, isnew = Reaction.objects.get_or_create(
            subject=request.POST["subject"],
            user=request.user if request.user.is_authenticated() else None,
            anon_session_key=Reaction.get_session_key(request) if not request.user.is_authenticated() else None,
        )

        if isnew:
            r.extra = {
                "ip": request.META['REMOTE_ADDR'],
            }

        if not isinstance(r.reaction, dict):
            r.reaction = { }
        emojis = set(r.reaction.get("emojis", []))
        if request.POST["mode"] == "1":
            emojis.add(request.POST["emoji"])
        elif request.POST["mode"] == "-1":
            emojis.remove(request.POST["emoji"])
        r.reaction["emojis"] = sorted(emojis)
        if len(r.reaction["emojis"]) == 0:
            del r.reaction["emojis"]
        if not r.reaction:
            # no data, delete record
            r.delete()
        else:
            # save
            r.save()

    return HttpResponse(json.dumps(res), content_type="application/json")
Ejemplo n.º 5
0
def bill_details_user_view(request, congress, type_slug, number):
    bill = load_bill_from_url(congress, type_slug, number)

    ret = { }
    if request.user.is_staff:
        admin_panel = """
            {% load humanize %}
            <div class="clear"> </div>
            <div style="margin-top: 1.5em; padding: .5em; background-color: #EEE; ">
                <b>ADMIN</b> - <a href="{% url "bill_go_to_summary_admin" %}?bill={{bill.id}}">Edit Summary</a>
                 | <a href="/admin/bill/bill/{{bill.id}}">Edit</a>
                <br/>Tracked by {{feed.tracked_in_lists.count|intcomma}} users
                ({{feed.tracked_in_lists_with_email.count|intcomma}} w/ email).
                <br/>{{num_issuepos}} poll responses, {{num_calls}} phone calls to Congress.
            </div>
            """

        from poll_and_call.models import RelatedBill as IssueByBill
        try:
            from poll_and_call.models import *
            ix = RelatedBill.objects.get(bill=bill).issue
            num_issuepos = UserPosition.objects.filter(position__issue=ix).count()
            num_calls = len([c for c in CallLog.objects.filter(position__position__issue=ix) if c.is_complete()])
        except IssueByBill.DoesNotExist:
            num_issuepos = 0
            num_calls = 0

        from django.template import Template, Context, RequestContext, loader
        ret["admin_panel"] = Template(admin_panel).render(RequestContext(request, {
            'bill': bill,
            "feed": bill.get_feed(),
            "num_issuepos": num_issuepos,
            "num_calls": num_calls,
            }))

    from person.views import render_subscribe_inline
    ret.update(render_subscribe_inline(request, bill.get_feed()))

    # poll_and_call
    if request.user.is_authenticated():
        from poll_and_call.models import RelatedBill as IssueByBill, UserPosition
        try:
            issue = IssueByBill.objects.get(bill=bill).issue
            try:
                up = UserPosition.objects.get(user=request.user, position__issue=issue)
                targets = up.get_current_targets()
                ret["poll_and_call_position"] =  {
                    "id": up.position.id,
                    "text": up.position.text,
                    "can_change": up.can_change_position(),
                    "can_call": [(t.id, t.person.name) for t in targets] if isinstance(targets, list) else [],
                    "call_url": issue.get_absolute_url() + "/make_call",
                }
            except UserPosition.DoesNotExist:
                pass
        except IssueByBill.DoesNotExist:
            pass

    # emoji reactions
    import json
    from website.models import Reaction
    # get aggregate counts
    reaction_subject = "bill:" + bill.congressproject_id
    emoji_counts = { }
    for r in Reaction.objects.filter(subject=reaction_subject).values("reaction").annotate(count=Count('id')):
        v = json.loads(r["reaction"])
        if isinstance(v, dict):
            for emoji in v.get("emojis", []):
                emoji_counts[emoji] = emoji_counts.get(emoji, 0) + r["count"]
    # get user's reactions
    r = Reaction.get_for_user(request).filter(subject=reaction_subject).first()
    my_emojis = set()
    if r and isinstance(r.reaction, dict):
        my_emojis = set(r.reaction.get("emojis", []))
    ret["reactions"] = [ ]
    for emoji in Reaction.EMOJI_CHOICES:
        ret["reactions"].append({
            "name": emoji,
            "count": emoji_counts.get(emoji, 0),
            "me": emoji in my_emojis,
        })
    # stable sort by count so that zeroes are in our preferred order
    ret["reactions"] = sorted(ret["reactions"], key = lambda x : -x["count"])

    return ret
Ejemplo n.º 6
0
def bill_details_user_view(request, congress, type_slug, number):
    bill = load_bill_from_url(congress, type_slug, number)

    ret = { }
    if request.user.is_staff:
        admin_panel = """
            {% load humanize %}
            <div class="clear"> </div>
            <div style="margin-top: 1.5em; padding: .5em; background-color: #EEE; ">
                <b>ADMIN</b> - <a href="{% url "bill_go_to_summary_admin" %}?bill={{bill.id}}">Edit Summary</a>
                 | <a href="/admin/bill/bill/{{bill.id}}">Edit</a>
                <br/>Tracked by {{feed.tracked_in_lists.count|intcomma}} users
                ({{feed.tracked_in_lists_with_email.count|intcomma}} w/ email).
                <br/>{{num_issuepos}} poll responses, {{num_calls}} phone calls to Congress.
            </div>
            """

        from poll_and_call.models import RelatedBill as IssueByBill
        try:
            from poll_and_call.models import *
            ix = RelatedBill.objects.get(bill=bill).issue
            num_issuepos = UserPosition.objects.filter(position__issue=ix).count()
            num_calls = len([c for c in CallLog.objects.filter(position__position__issue=ix) if c.is_complete()])
        except IssueByBill.DoesNotExist:
            num_issuepos = 0
            num_calls = 0

        from django.template import Template, Context, RequestContext, loader
        ret["admin_panel"] = Template(admin_panel).render(RequestContext(request, {
            'bill': bill,
            "feed": bill.get_feed(),
            "num_issuepos": num_issuepos,
            "num_calls": num_calls,
            }))

    from person.views import render_subscribe_inline
    ret.update(render_subscribe_inline(request, bill.get_feed()))

    # poll_and_call
    if request.user.is_authenticated():
        from poll_and_call.models import RelatedBill as IssueByBill, UserPosition
        try:
            issue = IssueByBill.objects.get(bill=bill).issue
            try:
                up = UserPosition.objects.get(user=request.user, position__issue=issue)
                targets = up.get_current_targets()
                ret["poll_and_call_position"] =  {
                    "id": up.position.id,
                    "text": up.position.text,
                    "can_change": up.can_change_position(),
                    "can_call": [(t.id, t.person.name) for t in targets] if isinstance(targets, list) else [],
                    "call_url": issue.get_absolute_url() + "/make_call",
                }
            except UserPosition.DoesNotExist:
                pass
        except IssueByBill.DoesNotExist:
            pass

    # emoji reactions
    import json
    from website.models import Reaction
    # get aggregate counts
    reaction_subject = "bill:" + bill.congressproject_id
    emoji_counts = { }
    for r in Reaction.objects.filter(subject=reaction_subject).values("reaction").annotate(count=Count('id')):
        v = json.loads(r["reaction"])
        if isinstance(v, dict):
            for emoji in v.get("emojis", []):
                emoji_counts[emoji] = emoji_counts.get(emoji, 0) + r["count"]
    # get user's reactions
    r = Reaction.get_for_user(request).filter(subject=reaction_subject).first()
    my_emojis = set()
    if r and isinstance(r.reaction, dict):
        my_emojis = set(r.reaction.get("emojis", []))
    ret["reactions"] = [ ]
    for emoji in Reaction.EMOJI_CHOICES:
        ret["reactions"].append({
            "name": emoji,
            "count": emoji_counts.get(emoji, 0),
            "me": emoji in my_emojis,
        })
    # stable sort by count so that zeroes are in our preferred order
    ret["reactions"] = sorted(ret["reactions"], key = lambda x : -x["count"])

    return ret