eaefc572ab5ba099d9bedc11666a637cf933a451
1 """Base class for a front page source, as well as a handful of specific
5 from collections
import namedtuple
8 from subprocess
import PIPE
13 from pylons
import cache
15 from spline
.lib
import helpers
17 def max_age_to_datetime(max_age
):
18 """``max_age`` is specified in config as a number of seconds old. This
19 function takes that number and returns a corresponding datetime object.
24 dt
= datetime
.datetime
.now()
25 dt
-= datetime
.timedelta(seconds
=int(max_age
))
31 """Represents a source to be polled for updates. Sources are populated
32 directly from the configuration file.
37 A name to identify this specific source.
40 Name of a Fugue icon to show next to the name.
43 A URL where the full history of this source can be found.
46 The maximum number of items from this source to show at a time.
50 Items older than this age (in seconds) will be excluded. Optional.
52 Additionally, subclasses **must** define a ``template`` property -- a path
53 to a Mako template that knows how to render an update from this source.
54 The template will be passed one parameter: the update object, ``update``.
57 def __init__(self
, title
, icon
, link
, limit
=None, max_age
=None):
61 self
.limit
= int(limit
)
62 self
.max_age
= max_age_to_datetime(max_age
)
64 def do_cron(self
, *args
, **kwargs
):
67 def poll(self
, global_limit
, global_max_age
):
68 """Public wrapper that takes care of reconciling global and source item
71 Subclasses should implement ``_poll``, below.
74 limit
= min(self
.limit
, global_limit
)
76 # Latest max age wins. Note that either could be None, but that's
77 # fine, because None is less than everything else
78 max_age
= max(self
.max_age
, global_max_age
)
80 return self
._poll(limit
, max_age
)
82 def _poll(self
, limit
, max_age
):
83 """Implementation of polling for updates. Must return an iterable.
84 Each element should be an object with ``source`` and ``time``
85 properties. A namedtuple works well.
87 raise NotImplementedError
89 class CachedSource(Source
):
90 """Supports caching a source's updates in memcache.
92 On the surface, this functions just like any other ``Source``. Calling
93 ``poll`` still returns a list of updates. However, ``poll`` does not call
94 your ``_poll``; instead, your implementation is called by the spline cron,
95 and the results are cached. ``poll`` then returns the contents of the
98 You must define a ``_cache_key`` method that returns a key uniquely
99 identifying this object. Your key will be combined with the class name, so
100 it only needs to be unique for that source, not globally.
102 You may also override ``poll_frequency``, the number of minutes between
103 pollings. By default, this is a rather conservative 60.
105 Note that it may take up to a minute after server startup for updates
106 from a cached source to appear.
112 return repr(type(self
)) + ':' + self
._cache_key()
114 def _cache_key(self
):
115 raise NotImplementedError
117 def do_cron(self
, tic
, *args
, **kwargs
):
118 if tic % self
.poll_frequency
!= 0:
122 updates
= self
._poll(self
.limit
, self
.max_age
)
123 cache
.get_cache('spline-frontpage')[self
.cache_key()] = updates
127 def poll(self
, global_limit
, global_max_age
):
128 """Fetches cached updates."""
130 return cache
.get_cache('spline-frontpage')[self
.cache_key()]
132 # Haven't cached anything yet, apparently
136 FrontPageRSS
= namedtuple('FrontPageRSS', ['source', 'time', 'entry', 'content'])
137 class FeedSource(CachedSource
):
138 """Represents an RSS or Atom feed.
146 template
= '/front_page/rss.mako'
148 SUMMARY_LENGTH
= 1000
152 def __init__(self
, feed_url
, **kwargs
):
153 kwargs
.setdefault('title', None)
154 super(FeedSource
, self
).__init__(**kwargs
)
156 self
.feed_url
= feed_url
158 def _cache_key(self
):
161 def _poll(self
, limit
, max_age
):
162 feed
= feedparser
.parse(self
.feed_url
)
165 self
.title
= feed
.feed
.title
168 for entry
in feed
.entries
[:limit
]:
169 # Grab a date -- Atom has published, RSS usually just has updated.
170 # Both come out as time tuples, which datetime.datetime() can read
172 timestamp_tuple
= entry
.published_parsed
173 except AttributeError:
174 timestamp_tuple
= entry
.updated_parsed
175 timestamp
= datetime
.datetime(*timestamp_tuple
[:6])
177 if max_age
and timestamp
< max_age
:
178 # Entries should be oldest-first, so we can bail after the first
182 # Try to find something to show! Default to the summary, if there is
183 # one, or try to generate one otherwise
185 if 'summary' in entry
:
186 # If there be a summary, cheerfully trust that it's actually a
188 content
= entry
.summary
189 elif 'content' in entry
:
190 # Full content is way too much, especially for my giant blog posts.
191 # Cut this down to some arbitrary number of characters, then feed
192 # it to lxml.html to fix tag nesting
193 broken_html
= entry
.content
[0].value
[:self
.SUMMARY_LENGTH
]
194 fragment
= lxml
.html
.fromstring(broken_html
)
196 # Insert an ellipsis at the end of the last node with text
197 last_text_node
= None
198 last_tail_node
= None
199 # Need to find the last node with a tail, OR the last node with
201 for node
in fragment
.iter():
203 last_tail_node
= node
204 last_text_node
= None
206 last_text_node
= node
207 last_tail_node
= None
209 if last_text_node
is not None:
210 last_text_node
.text
+= '...'
211 if last_tail_node
is not None:
212 last_tail_node
.tail
+= '...'
215 content
= lxml
.html
.tostring(fragment
)
217 content
= helpers
.literal(content
)
219 update
= FrontPageRSS(
225 updates
.append(update
)
230 FrontPageGit
= namedtuple('FrontPageGit', ['source', 'time', 'log', 'tag'])
231 FrontPageGitCommit
= namedtuple('FrontPageGitCommit',
232 ['hash', 'author', 'time', 'subject', 'repo'])
234 class GitSource(CachedSource
):
235 """Represents a git repository.
237 The main repository is checked for annotated tags, and an update is
238 considered to be the list of commits between them. If any other
239 repositories are listed and have the same tags, their commits will be
245 Space-separated list of repositories. These must be repository PATHS,
246 not arbitrary git URLs. Only the first one will be checked for the
250 A list of names for the repositories, in parallel with ``repo_paths``.
251 Used for constructing gitweb URLs and identifying the repositories.
254 Base URL to a gitweb installation, so commit ids can be linked to the
258 Optional. A shell glob pattern used to filter the tags.
261 template
= '/front_page/git.mako'
263 def __init__(self
, repo_paths
, repo_names
, gitweb
, tag_pattern
=None, **kwargs
):
264 kwargs
.setdefault('title', None)
265 super(GitSource
, self
).__init__(**kwargs
)
267 # Repo stuff can be space-delimited lists
268 self
.repo_paths
= repo_paths
.split()
269 self
.repo_names
= repo_names
.split()
272 self
.tag_pattern
= tag_pattern
274 def _cache_key(self
):
275 return self
.repo_paths
[0]
277 def _poll(self
, limit
, max_age
):
278 # Fetch the main repo's git tags
279 git_dir
= '--git-dir=' + self
.repo_paths
[0]
286 args
.append(self
.tag_pattern
)
288 git_output
, _
= subprocess
.Popen(args
, stdout
=PIPE
).communicate()
289 tags
= git_output
.strip().split('\n')
291 # Tags come out in alphabetical order, which means earliest first. Reverse
292 # it to make the slicing easier
294 # Only history from tag to tag is actually interesting, so get the most
295 # recent $limit tags but skip the earliest
296 interesting_tags
= tags
[:-1][:limit
]
299 for tag
, since_tag
in zip(interesting_tags
, tags
[1:]):
300 # Get the date when this tag was actually created.
301 # 'raw' format gives unixtime followed by timezone offset
306 '--format=%(taggerdate:raw)',
309 tag_timestamp
, _
= subprocess
.Popen(args
, stdout
=PIPE
).communicate()
310 tag_unixtime
, tag_timezone
= tag_timestamp
.split(None, 1)
311 tagged_timestamp
= datetime
.datetime
.fromtimestamp(int(tag_unixtime
))
313 if max_age
and tagged_timestamp
< max_age
:
318 for repo_path
, repo_name
in zip(self
.repo_paths
, self
.repo_names
):
319 # Grab an easily-parsed history: fields delimited by nulls.
320 # Hash, author's name, commit timestamp, subject.
323 '--git-dir=' + repo_path
,
325 '--pretty=%h%x00%an%x00%at%x00%s',
326 "{0}..{1}".format(since_tag
, tag
),
328 proc
= subprocess
.Popen(git_log_args
, stdout
=PIPE
)
329 for line
in proc
.stdout
:
330 hash, author
, time
, subject
= line
.strip().split('\x00')
335 time
= datetime
.datetime
.fromtimestamp(int(time
)),
341 update
= FrontPageGit(
343 time
= tagged_timestamp
,
347 updates
.append(update
)