This repository was archived by the owner on Dec 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathfeeds.py
262 lines (200 loc) · 8.25 KB
/
feeds.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
"""Feeds for badge"""
import datetime
import hashlib
import urllib
from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.utils.feedgenerator import (SyndicationFeed, Rss201rev2Feed,
Atom1Feed, get_tag_uri)
import json
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import User
from django.conf import settings
try:
from tower import ugettext_lazy as _
except ImportError:
from django.utils.translation import ugettext_lazy as _
try:
from commons.urlresolvers import reverse
except ImportError:
from django.core.urlresolvers import reverse
from . import validate_jsonp
from .models import (Badge, Award, Nomination, Progress,
BadgeAwardNotAllowedException,
DEFAULT_BADGE_IMAGE)
MAX_FEED_ITEMS = getattr(settings, 'BADGER_MAX_FEED_ITEMS', 15)
class BaseJSONFeedGenerator(SyndicationFeed):
"""JSON feed generator"""
# TODO:liberate - Can this class be a generally-useful lib?
mime_type = 'application/json'
def _encode_complex(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
def build_item(self, item):
"""Simple base item formatter.
Omit some named keys and any keys with false-y values"""
omit_keys = ('obj', 'unique_id', )
return dict((k, v) for k, v in item.items()
if v and k not in omit_keys)
def build_feed(self):
"""Simple base feed formatter.
Omit some named keys and any keys with false-y values"""
omit_keys = ('obj', 'request', 'id', )
feed_data = dict((k, v) for k, v in self.feed.items()
if v and k not in omit_keys)
feed_data['items'] = [self.build_item(item) for item in self.items]
return feed_data
def write(self, outfile, encoding):
request = self.feed['request']
# Check for a callback param, validate it before use
callback = request.GET.get('callback', None)
if callback is not None:
if not validate_jsonp.is_valid_jsonp_callback_value(callback):
callback = None
# Build the JSON string, wrapping it in a callback param if necessary.
json_string = json.dumps(self.build_feed(),
default=self._encode_complex)
if callback:
outfile.write('%s(%s)' % (callback, json_string))
else:
outfile.write(json_string)
class BaseFeed(Feed):
"""Base feed for all of badger, allows switchable generator from URL route
and other niceties"""
# TODO:liberate - Can this class be a generally-useful lib?
json_feed_generator = BaseJSONFeedGenerator
rss_feed_generator = Rss201rev2Feed
atom_feed_generator = Atom1Feed
def __call__(self, request, *args, **kwargs):
self.request = request
return super(BaseFeed, self).__call__(request, *args, **kwargs)
def get_object(self, request, format):
self.link = request.build_absolute_uri('/')
if format == 'json':
self.feed_type = self.json_feed_generator
elif format == 'rss':
self.feed_type = self.rss_feed_generator
else:
self.feed_type = self.atom_feed_generator
return super(BaseFeed, self).get_object(request)
def feed_extra_kwargs(self, obj):
return {'request': self.request, 'obj': obj, }
def item_extra_kwargs(self, obj):
return {'obj': obj, }
def item_pubdate(self, obj):
return obj.created
def item_author_link(self, obj):
if not obj.creator or not hasattr(obj.creator, 'get_absolute_url'):
return None
else:
return self.request.build_absolute_uri(
obj.creator.get_absolute_url())
def item_author_name(self, obj):
if not obj.creator:
return None
else:
return '%s' % obj.creator
def item_description(self, obj):
if obj.image:
image_url = obj.image.url
else:
image_url = '%simg/default-badge.png' % settings.MEDIA_URL
return """
<div>
<a href="%(href)s"><img alt="%(alt)s" src="%(image_url)s" /></a>
</div>
""" % dict(
alt=unicode(obj),
href=self.request.build_absolute_uri(obj.get_absolute_url()),
image_url=self.request.build_absolute_uri(image_url)
)
class AwardActivityStreamJSONFeedGenerator(BaseJSONFeedGenerator):
pass
class AwardActivityStreamAtomFeedGenerator(Atom1Feed):
pass
class AwardsFeed(BaseFeed):
"""Base class for all feeds listing awards"""
title = _(u'Recently awarded badges')
subtitle = None
json_feed_generator = AwardActivityStreamJSONFeedGenerator
atom_feed_generator = AwardActivityStreamAtomFeedGenerator
def item_title(self, obj):
return _(u'{badgetitle} awarded to {username}').format(
badgetitle=obj.badge.title, username=obj.user.username)
def item_author_link(self, obj):
if not obj.creator:
return None
else:
return self.request.build_absolute_uri(
reverse('badger.views.awards_by_user',
args=(obj.creator.username,)))
def item_link(self, obj):
return self.request.build_absolute_uri(
reverse('badger.views.award_detail',
args=(obj.badge.slug, obj.pk, )))
class AwardsRecentFeed(AwardsFeed):
"""Feed of all recent badge awards"""
def items(self):
return (Award.objects
.order_by('-created')
.all()[:MAX_FEED_ITEMS])
class AwardsByUserFeed(AwardsFeed):
"""Feed of recent badge awards for a user"""
def get_object(self, request, format, username):
super(AwardsByUserFeed, self).get_object(request, format)
user = get_object_or_404(User, username=username)
self.title = _(u'Badges recently awarded to {username}').format(
username=user.username)
self.link = request.build_absolute_uri(
reverse('badger.views.awards_by_user', args=(user.username,)))
return user
def items(self, user):
return (Award.objects
.filter(user=user)
.order_by('-created')
.all()[:MAX_FEED_ITEMS])
class AwardsByBadgeFeed(AwardsFeed):
"""Feed of recent badge awards for a badge"""
def get_object(self, request, format, slug):
super(AwardsByBadgeFeed, self).get_object(request, format)
badge = get_object_or_404(Badge, slug=slug)
self.title = _(u'Recent awards of "{badgetitle}"').format(
badgetitle=badge.title)
self.link = request.build_absolute_uri(
reverse('badger.views.awards_by_badge', args=(badge.slug,)))
return badge
def items(self, badge):
return (Award.objects
.filter(badge=badge).order_by('-created')
.all()[:MAX_FEED_ITEMS])
class BadgesJSONFeedGenerator(BaseJSONFeedGenerator):
pass
class BadgesFeed(BaseFeed):
"""Base class for all feeds listing badges"""
title = _(u'Recently created badges')
json_feed_generator = BadgesJSONFeedGenerator
def item_title(self, obj):
return obj.title
def item_link(self, obj):
return self.request.build_absolute_uri(
reverse('badger.views.detail',
args=(obj.slug, )))
class BadgesRecentFeed(BadgesFeed):
def items(self):
return (Badge.objects
.order_by('-created')
.all()[:MAX_FEED_ITEMS])
class BadgesByUserFeed(BadgesFeed):
"""Feed of badges recently created by a user"""
def get_object(self, request, format, username):
super(BadgesByUserFeed, self).get_object(request, format)
user = get_object_or_404(User, username=username)
self.title = _(u'Badges recently created by {username}').format(
username=user.username)
self.link = request.build_absolute_uri(
reverse('badger.views.badges_by_user', args=(user.username,)))
return user
def items(self, user):
return (Badge.objects
.filter(creator=user)
.order_by('-created')
.all()[:MAX_FEED_ITEMS])