/[theodore]/snips/snips/snips.py


UCC Code Repository

Contents of /snips/snips/snips.py

Parent Directory Parent Directory | Revision Log Revision Log


Revision 51 - (show annotations) (download) (as text)
Tue Jul 1 13:31:20 2008 UTC (13 years, 2 months ago) by theodore
File MIME type: text/x-python
File size: 13484 byte(s)
More adding of stuff


1 import re
2 import time
3 import ConfigParser
4
5 from os import sys
6 from string import join
7
8 """
9 Import modules from modules directory
10 """
11 sys.path.insert(0,'./modules')
12 import ezdb
13 import yaml
14 import pygments
15
16 from pygments import highlight
17 from pygments.lexers import (guess_lexer, get_all_lexers, get_lexer_by_name)
18 from pygments.formatters import HtmlFormatter
19 from mako.template import Template
20
21 del sys.path[0]
22 html_header = "Status: %s\nContent-Type: text/html\r\n\n"
23
24 def display_home():
25 mytemplate = Template(filename="templates/home.txt", module_directory='./tmp/mako')
26 main = mytemplate.render()
27 header = "Snips Homepage"
28 title = "Snips Homepage"
29 print_page(title, main)
30
31 def new_snip():
32 mytemplate = Template(filename="templates/form.txt", module_directory='./tmp/mako')
33 main = mytemplate.render(action = 'new', tags = '', languages = get_languages(), description = '', code = '', submit = 'And Save It', hidden = '')
34 print_page("Snips - Create new snip", main, "Create new snip")
35
36 def edit_snip(index):
37
38 (snip_id, code, description, language, timesaved, tags) = get_snip(index)
39
40 if tags == []:
41 tags.append('None')
42 tags = join(tags, ' ')
43
44 mytemplate = Template(filename="templates/form.txt", module_directory='./tmp/mako')
45 main = mytemplate.render(action = 'edit', tags = tags, languages = get_languages(language), description = description, code = code, submit = 'Save Changes', hidden = '<input type="hidden" name="snip_id" value="%s"></input>' % (snip_id,) )
46
47 title = "Editing snip - %s" % (snip_id)
48 header = title + ", last saved %s - <a href='?editsnip=%s'>edit</a>" % (time.ctime(timesaved), snip_id)
49
50 print_page(title, main, header)
51
52 def get_languages(language = ''):
53 lexers = []
54 list = '<option value="guess">Guess</option>'
55 for lexer in get_all_lexers():
56 name = lexer[0]
57 alias = lexer[1][0]
58 lexers.append((name,alias))
59 lexers.sort()
60 for name, alias in lexers:
61 selected = ''
62 if alias == language:
63 selected = 'selected="selected"'
64 list += '<option value="%s" %s>%s</option>' % (alias, selected, name)
65 return list
66
67 def sidebar(sidebar = True):
68 if sidebar:
69 try:
70 tagcloud = get_tagcloud()
71 except:
72 tagcloud = ''
73 else:
74 tagcloud = ''
75 mytemplate = Template(filename="templates/sidebar.txt", module_directory='./tmp/mako')
76 sidebar = mytemplate.render(tagcloud = tagcloud)
77 return sidebar
78
79 def dbh_open():
80 cursor = ezdb.Ezdb()
81 if cursor == False:
82 print_error("Database connection problem")
83 return cursor
84
85 def submit_new_snip(snip, description, language = '', tags = []):
86 cursor = dbh_open()
87 cursor.execute ("INSERT INTO snips_snip (code, description, language, timesaved) VALUES (%s, %s, %s, %s); ", (snip, description, language, time.time()))
88 cursor.execute ("SELECT LAST_INSERT_ID();")
89 snip_id = cursor.fetchone ()[0]
90 snip_id = int(snip_id)
91 for tag in tags:
92 cursor.execute ("INSERT INTO snips_tags (snip_id, tag) VALUES (%s, %s); ", (snip_id, tag))
93
94 cursor.close()
95 redirect(snip_id)
96
97 def redirect(id, page = "snip"):
98 print "Status: 303 Moved Permanently\nLocation: ./index.cgi?%s=%s\n" % (page,id)
99
100
101 def update_current_snip(snip_id, code, description, language, tags = []):
102 cursor = dbh_open()
103 cursor.execute ("UPDATE snips_snip SET code = %s, description = %s, language = %s, timesaved = %s WHERE id = %s; ", (code, description, language, time.time(), snip_id))
104 cursor.execute ("INSERT INTO snips_story (snip_id, code, description, language, timesaved) SELECT id, code, description, language, timesaved FROM snips_snip ss WHERE ss.id = %s; ", (snip_id,))
105
106 cursor.execute ("DELETE FROM snips_tags WHERE snip_id = %s; ", (snip_id,))
107 for tag in tags:
108 cursor.execute ("INSERT INTO snips_tags (snip_id, tag) VALUES (%s, %s); ", (snip_id, tag))
109
110 cursor.close()
111 redirect(snip_id)
112
113 def get_snip(index):
114 cursor = dbh_open()
115 cursor.execute ("SELECT id, code, description, language, timesaved FROM snips_snip WHERE id = %s; ", (index,))
116 try:
117 snip_id, code, description, language, timesaved = cursor.fetchone ()
118 except:
119 print_error("404 - The snip id you requested (%s) was not found." % index, "404 Not Found")
120
121 cursor.execute ("SELECT tag FROM snips_tags WHERE snip_id = %s; ", (snip_id,))
122 tupletags = cursor.fetchall ()
123 tags = []
124 for tuple in tupletags:
125 tags.append(tuple [0])
126
127 cursor.close()
128 return (snip_id, code, description, language, timesaved, tags)
129
130 def get_num_comments(snipid):
131 cursor = dbh_open()
132 cursor.execute("SELECT COUNT(*) FROM snips_comments WHERE snip_id = %s", (snipid,))
133 numcomments = int(cursor.fetchone()[0])
134 cursor.close()
135 return numcomments
136
137 def print_snip(index):
138 (snip_id, code, description, language, timesaved, tags) = get_snip(index)
139
140 main = render_snip(snip_id, code, description, language, timesaved, tags)
141 title = "Viewing snip - %s" % (index)
142 header = title + ", last saved %s - <a href='?editsnip=%s'>edit</a> | <a href='?snipstory=%s'>snipstory</a>" % (time.ctime(timesaved), snip_id, snip_id)
143
144 print_page(title, main, header)
145
146 def render_snip(snipid, code, description, language, timesaved, tags):
147 if tags == []:
148 tags.append('None')
149 tags = join(tags, ', ')
150
151 code = format_code(language, code)
152 languagename = get_longname(language)
153
154 mytemplate = Template(filename='./templates/snip.txt', module_directory='./tmp/mako')
155 main = mytemplate.render(description = description, tags = tags, snip = code, language = languagename, snipid = snipid, comments = get_num_comments(snipid))
156 return main
157
158 def get_lexer(language = "None", code = ""):
159 try:
160 mylexer = get_lexer_by_name(language)
161 except:
162 try:
163 mylexer = guess_lexer(code)
164 except:
165 mylexer= get_lexer_by_name('text')
166 return mylexer
167
168
169 def tagify(tags):
170 tags = re.split(r'\s*', tags)
171 return tags
172
173 """
174 Prints Page with required variables
175 """
176 def print_page(title, main, header = ''):
177 if header == '':
178 header = title
179 mytemplate = Template(filename='./templates/main.txt', module_directory='./tmp/mako')
180 print html_header % "200 OK"
181 print mytemplate.render(title = title, header = header, sidebar = sidebar(), main = main)
182 sys.exit(0)
183
184 def print_error(error, errorcode = "200 OK"):
185 title = "Snips - error"
186 header = ''
187 error = '<div id="error"><em>An error has occurred processing your request please review the errors below</em><p>' + error + '</p></div>'
188
189 mytemplate = Template(filename='./templates/main.txt', module_directory='./tmp/mako')
190 print html_header % errorcode
191 print mytemplate.render(title = title, header = header, sidebar = sidebar(False), main = error)
192 sys.exit(0)
193
194 def get_tagcloud():
195 tags = get_tags(20)
196 mytemplate = Template(filename="templates/cloud.txt", module_directory='./tmp/mako')
197 cloud = mytemplate.render(tags = tags, size = 'small')
198 return cloud
199
200 def get_tags(limit = 0):
201 cursor = dbh_open()
202 if limit != int(limit):
203 limit = 20
204 if limit > 0:
205 cursor.execute ("SELECT tag, COUNT(*) FROM snips_tags GROUP BY tag ORDER BY COUNT(*) DESC LIMIT %s;", limit)
206 elif limit < 0:
207 cursor.execute ("SELECT tag, COUNT(*) FROM snips_tags GROUP BY tag ORDER BY COUNT(*) DESC LIMIT %s;", limit * -1)
208 else:
209 cursor.execute ("SELECT tag, COUNT(*) FROM snips_tags GROUP BY tag ORDER BY COUNT(*) DESC;")
210 tags = cursor.fetchall ()
211 max = tags[0][1]
212 min = tags[-1][1]
213 tags = list(tags)
214 for i in range(len(tags)):
215 tag, count = tags[i]
216 tags[i] = (tag, int( (count - min + 1.0)/(max - min + 1.0) * 9))
217 tags.sort()
218
219 cursor.close()
220 return tags
221
222 def show_all_tags():
223 cloud = ''
224 tags = get_tags()
225
226 mytemplate = Template(filename="templates/cloud.txt", module_directory='./tmp/mako')
227 main = mytemplate.render(tags = tags, size = 'big')
228
229 title = "Snips - Showing all tags"
230 print_page(title, main)
231
232 def latest_snips():
233 cursor = dbh_open()
234 cursor.execute ("SELECT id, code, description, language, timesaved FROM snips_snip ORDER BY timesaved DESC LIMIT 10;")
235 snips = cursor.fetchall ()
236 cursor.close()
237
238 main = snips_to_snippets(snips)
239
240 title = "Viewing latest 20 snips"
241 print_page(title, main)
242
243 def get_longname(language = ''):
244 if language == '' or language == 'guess':
245 return "None Given"
246 for lexer in get_all_lexers():
247 if lexer[1][0] == language:
248 return lexer[0]
249 return language
250
251 def view_tag(tag):
252 cursor = dbh_open()
253 cursor.execute ("SELECT ss.id, ss.code, ss.description, ss.language, ss.timesaved FROM snips_snip ss, snips_tags st WHERE st.tag = %s AND st.snip_id = ss.id; ", (tag,))
254 snips = cursor.fetchall ()
255 cursor.close()
256
257 main = snips_to_snippets(snips)
258
259 title = "Viewing all snips tagged '%s'" % tag
260 print_page(title, main)
261
262 def snips_to_snippets(snips):
263 main = ""
264 for snip in snips:
265 (snip_id, code, description, language, timesaved) = snip
266 viewmore = False
267 code = code.splitlines()
268 if len(code) > 15:
269 code = code[:15]
270 viewmore = True
271 code = "\n".join(code)
272 languagename = get_longname(language)
273
274 code = format_code(language, code)
275
276 timesaved = diff_time(timesaved)
277
278 mytemplate = Template(filename='./templates/snippet.txt', module_directory='./tmp/mako')
279 main += mytemplate.render(description = description, snip = code, edittime = timesaved, language = languagename, snipid = snip_id, viewmore = viewmore)
280 return main
281
282 def print_snipstory(snipid):
283 cursor = dbh_open()
284 cursor.execute ("SELECT 0, code, description, language, timesaved FROM snips_snip where id = %s;", (snipid,))
285 latestsnip = cursor.fetchone ()
286 cursor.execute ("SELECT id, code, description, language, timesaved FROM snips_story where snips_story.snip_id = %s ORDER BY timesaved DESC;", (snipid,))
287 snips = cursor.fetchall ()
288 cursor.close()
289
290 snips = list(snips)
291 snips.insert(0, latestsnip)
292
293 main = ""
294 i=0
295 totalsnips = len(snips)
296 mytemplate = Template(filename='./templates/snipstory.txt', module_directory='./tmp/mako')
297 for snip in snips:
298 version = totalsnips - i
299 (id, code, description, language, timesaved) = snip
300
301 languagename = get_longname(language)
302 code = format_code(language, code)
303 timesaved = time.ctime(timesaved)
304
305 main += mytemplate.render(description = description, snip = code, edittime = timesaved, language = languagename, snipid = snipid, snipstoryid = id, total = totalsnips, count = i)
306 i += 1
307
308 title = "Snipstory of snip %s" % (snipid)
309 header = title + " - <a href='?editsnip=%s'>edit</a>" % (snipid,)
310 print_page(title, main, header)
311
312 def format_code(language, code):
313 lexer = get_lexer(language, code)
314 formatter = HtmlFormatter(linenos=True, cssclass="source")
315 code = highlight(code, lexer, formatter)
316 return code
317
318 def revert_snip(snip_id, to_id):
319 cursor = dbh_open()
320
321 cursor.execute ("INSERT INTO snips_story (snip_id, code, description, language, timesaved) SELECT id, code, description, language, timesaved FROM snips_snip ss WHERE ss.id = %s; ", (snip_id,))
322
323 cursor.execute ("UPDATE snips_snip ss, snips_story st SET ss.code = st.code, ss.description = st.description, ss.language = st.language, ss.timesaved = %s WHERE ss.id = %s AND st.id = %s; ", (time.time(), snip_id, to_id))
324
325 cursor.close()
326 redirect(snip_id)
327
328 def add_comment(index):
329 (snip_id, code, description, language, timesaved, tags) = get_snip(index)
330
331 main = render_snip(snip_id, code, description, language, timesaved, tags)
332 title = "Add comment about snip - %s" % (snip_id)
333 header = title + ", last saved %s - <a href='?editsnip=%s'>edit</a> | <a href='?snipstory=%s'>snipstory</a>" % (time.ctime(timesaved), snip_id, snip_id)
334
335 mytemplate = Template(filename="templates/newcomment.txt", module_directory='./tmp/mako')
336 main += mytemplate.render(submit = 'Add your 2 cents', snipid = index)
337
338 print_page(title, main)
339
340 def submit_comment(snipid, author, comment):
341 cursor = dbh_open()
342 cursor.execute ("INSERT INTO snips_comments (snip_id, author, comment, timesaved, flagged) VALUES (%s, %s, %s, %s, 0); ", (snipid, author, comment, time.time()))
343 cursor.close()
344 redirect(snipid,'viewcomments')
345
346 def view_comments(snipid):
347 (snip_id, code, description, language, timesaved, tags) = get_snip(index)
348 comments = get_comments(snipid)
349
350 main = render_snip(snip_id, code, description, language, timesaved, tags)
351 mytemplate = Template(filename="templates/comment.txt", module_directory='./tmp/mako')
352 count = int((time.time() - snipid) % 123)
353 main += '<a name="comments"></a><div id="container">'
354 for comment in comments:
355 commentid, author, comment, timesaved = comment
356 color = count % 4 + 1
357 main += mytemplate.render(commentid = commentid, comment = comment, author = author, timesaved = time.ctime(timesaved), color = color)
358 count += count % 7
359 main += "</div>"
360 title = "Viewing comments about snip - %s" % (snipid)
361 print_page(title, main)
362
363 def get_comments(snipid):
364 cursor = dbh_open()
365 cursor.execute ("SELECT id, author, comment, timesaved FROM snips_comments WHERE snip_id = %s AND flagged >= %s; ", (snipid,0))
366 comments = cursor.fetchall ()
367 cursor.close()
368 return list(comments)
369
370 def diff_time(pasttime, accurate = True):
371 diff = time.time() - pasttime
372 if diff < 60:
373 return "%d seconds ago" % (diff,)
374 else:
375 diff, secs = divmod(diff,60)
376 if diff < 60:
377 return "%d minutes and %d seconds ago" % (diff, secs)
378 else:
379 diff, mins = divmod(diff,60)
380 if diff < 24:
381 return "%d hours and %d minutes ago" % (diff, mins)
382 else:
383 diff, hours = divmod(diff,24)
384 if diff < 7:
385 return "%d days and %d hours ago" % (diff, hours)
386 else:
387 diff, days = divmod(diff,7)
388 if diff < 52:
389 return "%d weeks and %d days ago" % (diff, days)
390 else:
391 diff, years = divmod(diff,52)
392 return "%d years and %d weeks ago" % (diff, weeks)
393
394
395
396
397

Managed by UCC Webmasters ViewVC Help
Powered by ViewVC 1.1.26