summaryrefslogtreecommitdiff
path: root/planet/generator.py
blob: 5fb4d3e099d53d7b0f43fe0a4fb5fb1209289052 (plain)
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
#!/usr/bin/env python
"""PostgreSQL Planet Aggregator

This file contains the functions to generate output RSS and
HTML data from what's currently in the database.

Copyright (C) 2008 PostgreSQL Global Development Group
"""

import psycopg2
import PyRSS2Gen
import datetime
import sys
import tidy
import urllib
from HTMLParser import HTMLParser
from planethtml import PlanetHtml

class Generator:
	def __init__(self,db):
		self.db = db
		self.tidyopts = dict(   drop_proprietary_attributes=1,
					alt_text='',
					hide_comments=1,
					output_xhtml=1,
					show_body_only=1,
					clean=1,
					)


	def Generate(self):
		rss = PyRSS2Gen.RSS2(
			title = 'Planet PostgreSQL',
			link = 'http://planet.postgresql.org',
			description = 'Planet PostgreSQL',
			generator = 'Planet PostgreSQL',
			lastBuildDate = datetime.datetime.utcnow())
		html = PlanetHtml()

		c = self.db.cursor()
		c.execute("SET TIMEZONE=GMT")
		c.execute("SELECT guid,link,dat,title,txt,name,blogurl,guidisperma FROM planet.posts INNER JOIN planet.feeds ON planet.feeds.id=planet.posts.feed ORDER BY dat DESC LIMIT 30")
		for post in c.fetchall():
			desc = self.TruncateAndCleanDescription(post[4], post[3])
			rss.items.append(PyRSS2Gen.RSSItem(
				title=post[5] + ': ' + post[3],
				link=post[1],
				guid=PyRSS2Gen.Guid(post[0],post[7]),
				pubDate=post[2],
				description=desc))
			html.AddItem(post[0], post[1], post[2], post[3], post[5], post[6], desc)

		c.execute("SELECT name,blogurl,feedurl FROM planet.feeds ORDER BY name")
		for feed in c.fetchall():
			html.AddFeed(feed[0], feed[1], feed[2])

		rss.write_xml(open("www/rss20.xml","w"), encoding='utf-8')
		html.WriteFile("www/index.html")

	def TruncateAndCleanDescription(self, txt, title):
		# First apply Tidy
		txt = str(tidy.parseString(txt, **self.tidyopts))

		# Then truncate as necessary
		ht = HtmlTruncator(1024, title)
		ht.feed(txt)
		out = ht.GetText()

		# Remove initial <br /> tags
		while out.startswith('<br'):
			out = out[out.find('>')+1:]

		return out

class HtmlTruncator(HTMLParser):
	def __init__(self, maxlen, title = None):
		HTMLParser.__init__(self)
		self.len = 0
		self.maxlen = maxlen
		self.fulltxt = ''
		self.trunctxt = ''
		self.tagstack = []
		self.skiprest = False
		self.title = title
	
	def feed(self, txt):
		txt = txt.lstrip()
		self.fulltxt += txt
		HTMLParser.feed(self, txt)

	def handle_startendtag(self, tag, attrs):
		if self.skiprest: return
		self.trunctxt += self.get_starttag_text()
	
	def quoteurl(self, str):
		p = str.split(":",2)
		return p[0] + ":" + urllib.quote(p[1])

	def cleanhref(self, attrs):
		if attrs[0] == 'href':
			return 'href', self.quoteurl(attrs[1])
		return attrs

	def handle_starttag(self, tag, attrs):
		if self.skiprest: return
		self.trunctxt += "<" + tag
		self.trunctxt += (' '.join([(' %s="%s"' % (k,v)) for k,v in map(self.cleanhref, attrs)]))
		self.trunctxt += ">"
		self.tagstack.append(tag)

	def handle_endtag(self, tag):
		if self.skiprest: return
		self.trunctxt += "</" + tag + ">"
		self.tagstack.pop()

	def handle_entityref(self, ref):
		self.len += 1
		if self.skiprest: return
		self.trunctxt += "&" + ref + ";"

	def handle_data(self, data):
		self.len += len(data)
		if self.skiprest: return
		self.trunctxt += data
		if self.len > self.maxlen:
			# Passed max length, so truncate text as close to the limit as possible
			self.trunctxt = self.trunctxt[0:len(self.trunctxt)-(self.len-self.maxlen)]

			# Now append any tags that weren't properly closed
			self.tagstack.reverse()
			for tag in self.tagstack:
				self.trunctxt += "</" + tag + ">"
			self.skiprest = True

			# Finally, append the continuation chars
			self.trunctxt += "[...]"

	def GetText(self):
		if self.len > self.maxlen:
			return self.trunctxt
		else:
			return self.fulltxt

if __name__=="__main__":
	Generator(psycopg2.connect('dbname=planetpg host=/tmp')).Generate()