Skip to content
This repository has been archived by the owner on Nov 9, 2017. It is now read-only.

Commit

Permalink
Refactor ProfileBar and Account.all_karmas
Browse files Browse the repository at this point in the history
A couple of minor changes included:
- no longer show the "renew your reddit gold" message if you already
  have an automatically-renewing subscription
- don't show the "friends" button to logged-out users
  • Loading branch information
Deimos committed Aug 6, 2014
1 parent 473495d commit b8d9981
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 95 deletions.
2 changes: 1 addition & 1 deletion r2/r2/lib/jsontemplates.py
Expand Up @@ -1063,7 +1063,7 @@ def data(self, karmas):
'sr': label,
'link_karma': lc,
'comment_karma': cc,
} for label, title, lc, cc in karmas]
} for label, (lc, cc) in karmas.iteritems()]
return karmas

def kind(self, wrapped):
Expand Down
61 changes: 29 additions & 32 deletions r2/r2/lib/pages/pages.py
Expand Up @@ -1861,59 +1861,56 @@ class ProfileBar(Templated):
"""Draws a right box for info about the user (karma, etc)"""
def __init__(self, user):
Templated.__init__(self, user = user)
self.is_friend = None
self.my_fullname = None
self.gold_remaining = None
running_out_of_gold = False
self.gold_creddit_message = None
self.viewing_self = False
self.show_private_info = False

if c.user_is_loggedin:
if ((user._id == c.user._id or c.user_is_admin)
and getattr(user, "gold", None)):
self.gold_expiration = getattr(user, "gold_expiration", None)
if self.gold_expiration is None:
self.gold_remaining = _("an unknown amount")
self.viewing_self = user._id == c.user._id
self.show_private_info = self.viewing_self or c.user_is_admin
if user.gold and self.show_private_info:
gold_days_left = (user.gold_expiration -
datetime.datetime.now(g.tz)).days

if gold_days_left < 1:
self.gold_remaining = _("less than a day")
else:
gold_days_left = (self.gold_expiration -
datetime.datetime.now(g.tz)).days
if gold_days_left < 7:
running_out_of_gold = True

if gold_days_left < 1:
self.gold_remaining = _("less than a day")
else:
# Round remaining gold to number of days
precision = 60 * 60 * 24
self.gold_remaining = timeuntil(self.gold_expiration,
precision)
# Round remaining gold to number of days
precision = 60 * 60 * 24
self.gold_remaining = timeuntil(user.gold_expiration,
precision)

if user.has_paypal_subscription:
self.paypal_subscr_id = user.gold_subscr_id
if user.has_stripe_subscription:
self.stripe_customer_id = user.gold_subscr_id

if ((user._id == c.user._id or c.user_is_admin) and
user.gold_creddits > 0):
if user.gold_creddits > 0 and self.show_private_info:
msg = ungettext("%(creddits)s gold creddit to give",
"%(creddits)s gold creddits to give",
user.gold_creddits)
msg = msg % dict(creddits=user.gold_creddits)
self.gold_creddit_message = msg

if user._id != c.user._id:
if not self.viewing_self:
self.goldlink = "/gold?goldtype=gift&recipient=" + user.name
self.giftmsg = _("give reddit gold to %(user)s to show "
"your appreciation") % {'user': user.name}
elif running_out_of_gold:
self.goldlink = "/gold/about"
self.giftmsg = _("renew your reddit gold")
elif not c.user.gold:
elif not user.gold:
self.goldlink = "/gold/about"
self.giftmsg = _("get extra features and help support reddit "
"with a reddit gold subscription")

self.my_fullname = c.user._fullname
self.is_friend = self.user._id in c.user.friends
elif gold_days_left < 7:
will_auto_renew = (user.has_paypal_subscription or
user.has_stripe_subscription)
if not will_auto_renew:
self.goldlink = "/gold/about"
self.giftmsg = _("renew your reddit gold")

if not self.viewing_self:
self.is_friend = user._id in c.user.friends

if self.show_private_info:
self.all_karmas = user.all_karmas()


class ServerSecondsBar(Templated):
Expand Down
61 changes: 37 additions & 24 deletions r2/r2/models/account.py
Expand Up @@ -39,6 +39,7 @@
from pylons.i18n import _
import time
import hashlib
from collections import Counter, OrderedDict
from copy import copy
from datetime import datetime, timedelta
import bcrypt
Expand Down Expand Up @@ -203,32 +204,44 @@ def safe_karma(self):
return max(karma, 1) if karma > -1000 else karma

def all_karmas(self, include_old=True):
"""returns a list of tuples in the form (name, hover-text, link_karma,
comment_karma)"""
"""Get all of the user's subreddit-specific karma totals.
Returns an OrderedDict keyed on subreddit name and containing
(link_karma, comment_karma) tuples, ordered by the combined total
descending.
"""
link_suffix = '_link_karma'
comment_suffix = '_comment_karma'
karmas = []
sr_names = set()
for k in self._t.keys():
if k.endswith(link_suffix):
sr_names.add(k[:-len(link_suffix)])
elif k.endswith(comment_suffix):
sr_names.add(k[:-len(comment_suffix)])
for sr_name in sr_names:
karmas.append((sr_name, None,
self._t.get(sr_name + link_suffix, 0),
self._t.get(sr_name + comment_suffix, 0)))

karmas.sort(key = lambda x: x[2] + x[3], reverse=True)

old_link_karma = self._t.get('link_karma', 0)
old_comment_karma = self._t.get('comment_karma', 0)
if include_old and (old_link_karma or old_comment_karma):
karmas.append((_('ancient history'),
_('really obscure karma from before it was cool to track per-subreddit'),
old_link_karma, old_comment_karma))

return karmas

comment_karmas = Counter()
link_karmas = Counter()
combined_karmas = Counter()

for key, value in self._t.iteritems():
if key.endswith(link_suffix):
sr_name = key[:-len(link_suffix)]
link_karmas[sr_name] = value
elif key.endswith(comment_suffix):
sr_name = key[:-len(comment_suffix)]
comment_karmas[sr_name] = value
else:
continue

combined_karmas[sr_name] += value

all_karmas = OrderedDict()
for sr_name, total in combined_karmas.most_common():
all_karmas[sr_name] = (link_karmas[sr_name],
comment_karmas[sr_name])

if include_old:
old_link_karma = self._t.get('link_karma', 0)
old_comment_karma = self._t.get('comment_karma', 0)
if old_link_karma or old_comment_karma:
all_karmas['ancient history'] = (old_link_karma,
old_comment_karma)

return all_karmas

def update_last_visit(self, current_time):
from admintools import apply_updates
Expand Down
67 changes: 29 additions & 38 deletions r2/r2/templates/profilebar.html
Expand Up @@ -47,11 +47,11 @@ <h1>

</h1>

%if c.user != thing.user:
%if c.user_is_loggedin and not thing.viewing_self:
<div>
${toggle_button("fancy-toggle-button", _("+ friends"), _("- friends"),
"friend('%s', '%s', 'friend')" % (thing.user.name, thing.my_fullname),
"unfriend('%s', '%s', 'friend')" % (thing.user.name, thing.my_fullname),
"friend('%s', '%s', 'friend')" % (thing.user.name, c.user._fullname),
"unfriend('%s', '%s', 'friend')" % (thing.user.name, c.user._fullname),
css_class = "add", alt_css_class = "remove",
reverse = thing.is_friend, login_required=True)}
</div>
Expand All @@ -66,41 +66,36 @@ <h1>
&#32;
${_("comment karma")}

%if c.user_is_admin or c.user == thing.user:
<table id="per-sr-karma"
% if not c.user_is_admin:
class="more-karmas"
% endif
>
%if thing.show_private_info:
<table id="per-sr-karma"${" class='more-karmas'" if not c.user_is_admin else ""}>
<thead>
<tr>
<th id="sr-karma-header">subreddit</th>
<th>link</th>
<th>comment</th>
</tr>
</thead>
<%
karmas = thing.user.all_karmas()
%>
<tbody>
%for i, (label, title, lc, cc) in enumerate(karmas):
<tr
% if c.user_is_admin and i >= 5:
class="more-karmas"
% endif
>
% if title:
<th class="helpful" title="${title}"><span>${label}</span></th>
%for i, (sr_name, (link_karma, comment_karma)) in enumerate(thing.all_karmas.iteritems()):
%if c.user_is_admin and i >= 5:
<tr class="more-karmas">
%else:
<tr>
%endif

% if sr_name == "ancient history":
<th class="helpful" title="${_('really obscure karma from before it was cool to track per-subreddit')}"><span>${_(sr_name)}</span></th>
% else:
<th>${label}</th>
<th>${sr_name}</th>
% endif
<td>${lc}</td>
<td>${cc}</td>

<td>${link_karma}</td>
<td>${comment_karma}</td>
</tr>
%endfor
</tbody>
%endfor
</tbody>
</table>
% if not c.user_is_admin or len(karmas) > 5:
% if not c.user_is_admin or len(thing.all_karmas) > 5:
<div class="karma-breakdown">
<a href="javascript:void(0)"
onclick="$('.more-karmas').show();$(this).hide();return false">
Expand All @@ -110,21 +105,17 @@ <h1>
% endif
%endif

%if thing.gold_remaining or thing.gold_creddit_message:
%if thing.show_private_info and thing.user.gold:
<div class="rounded gold-accent gold-expiration-info">
%if thing.gold_remaining:
<div class="gold-remaining"
%if thing.gold_expiration:
title="${thing.gold_expiration.strftime('%Y-%m-%d')}"
%endif
>
%if hasattr(thing, "gold_remaining"):
<div class="gold-remaining" title="${thing.user.gold_expiration.strftime('%Y-%m-%d')}">
<span class="karma">
${thing.gold_remaining}
</span>
<br>
${_("of reddit gold remaining")}
</div>
%if getattr(thing, "paypal_subscr_id", None):
%if hasattr(thing, "paypal_subscr_id"):
<%
paypal_link = ("https://www.paypal.com/cgi-bin/webscr?cmd=_subscr-find&alias=%s" % g.goldthanks_email)
%>
Expand All @@ -137,23 +128,23 @@ <h1>
</div>
%endif

%if getattr(thing, "stripe_customer_id", None):
%if hasattr(thing, "stripe_customer_id"):
<div>
<a href="/gold/subscription">
${_("manage recurring subscription")}
</a>
</div>
%endif
%endif
%if thing.gold_creddit_message:
%if hasattr(thing, "gold_creddit_message"):
<div class="gold-creddits-remaining">
${plain_link(thing.gold_creddit_message, "/gold?goldtype=gift")}
</div>
%endif
</div>
%endif

%if getattr(thing, "goldlink", None):
%if hasattr(thing, "goldlink"):
<div class="giftgold">
<a href="${thing.goldlink}">
${thing.giftmsg}
Expand All @@ -162,7 +153,7 @@ <h1>
%endif

<div class="bottom">
%if thing.user != c.user:
%if not thing.viewing_self:
<img src="${static('mailgray.png')}"/>
&#32;
${plain_link(_("send message"), "/message/compose/?to=%s" % thing.user.name)}
Expand Down

0 comments on commit b8d9981

Please sign in to comment.