root/trunk/plugins/Comments.py

Revision 177 (checked in by llimllib, 1 year ago)

Updating comments and keywords to remove pdb calls... stupid

Line 
1 """
2 Configuration for comments module should be in a [comments] secion of your
3     cherryblossom.conf file.
4
5 options:
6 commentdir (string): Directory in which to keep/find comments
7 """
8
9 import re, os, time
10 import cherrypy as cpy
11 from urllib import basejoin as urljoin
12 from utils import config
13
14 class CommentStruct(object):
15     def __init__(self):
16         self.text = ''
17         self.url = ''
18         self.author = ''
19         self.email = ''
20         self.filename = ''
21         self.story = ''
22
23 class CommentError(Exception):
24     pass
25
26 class Comments(object):
27     def __init__(self, parent):
28         commentdir = config('commentdir', None, 'comments')
29         if not commentdir:
30             raise CommentError, "Commentdir not found in config file"
31
32         if os.path.isdir(commentdir):
33             self.commentdir = commentdir
34         else:
35             raise CommentError, "Comment Directory Not Found"
36
37         self.sanitize = re.compile('\W').sub
38
39     def delete(self, filename):
40         try:
41             os.unlink(os.path.join(self.commentdir, filename))
42         except OSError:
43             cpy.log("unable to delete file %s" % filename)
44
45     @cpy.expose
46     def add(self, story='', author='', email='', url='', comment='', **kwargs):
47         if not (comment and story):
48             return "invalid comment form"
49         s_story = self.sanitize('_', story) #s_ for sanitized
50         fname = os.path.join(self.commentdir, s_story + '.' + str(time.time()))
51         while os.path.isfile(fname):
52             fname = s_story + '.' + str(time.time())
53         f = file(fname, 'w')
54         #Assumes no \n inside name and email
55         f.write(story + '\n')
56         f.write(author.strip() + '\n')
57         f.write(email.strip() + '\n')
58         f.write(url.strip() + '\n')
59         f.write(comment)
60         f.close()
61         redirect = config('base_url') + story
62         cpy.log('redirecting to %s' % redirect)
63
64         raise cpy.HTTPRedirect(redirect)
65
66     def count_comments(self, story):
67         #TODO: this won't work for some fnames: i.e. /deep/deep.txt and
68         #     _deep_deep.txt will share comments. How to fix? Q: What is always
69         #    unique about an entry?
70         n = 0
71         for f in os.listdir(self.commentdir):
72             if f.startswith(self.sanitize('_', story)):
73                 n += 1
74         return n
75
76     def get_comments(self, story):
77         """given a story's relpath, return the comment template for that
78             story"""
79         comments = []
80         for f in os.listdir(self.commentdir):
81             fin = file(os.path.join(self.commentdir, f))
82             fstory = fin.readline().strip()
83             if fstory == story:
84                 lines = fin.readlines()
85
86                 cmt = CommentStruct()
87                 cmt.filename = f
88                 cmt.story = fstory
89                 cmt.author, cmt.email, cmt.url = [l.strip() for l in lines[:3]]
90                 cmt.text = ''.join(lines[3:])
91                 comments.append(cmt)
92         return ('comments', {'comments': comments})
93
94     def get_all_comments(self):
95         """return all comments, regardless of story"""
96         comments = []
97         for f in os.listdir(self.commentdir):
98             fin = file(os.path.join(self.commentdir, f))
99             fstory = fin.readline().strip()
100             lines = fin.readlines()
101
102             cmt = CommentStruct()
103             cmt.filename = f
104             cmt.story = fstory
105             cmt.author, cmt.email, cmt.url = [l.strip() for l in lines[:3]]
106             cmt.text = ''.join(lines[3:])
107             comments.append(cmt)
108         return comments
109
110     def cb_story(self, entry):
111         """Add the number of comments to the entry's namespace"""
112         #XXX: is it right to modify the actual entry object permanently with
113         #     this? It sticks in my craw a bit
114         entry.n_comments = self.count_comments(entry.relpath)
115         #mako doesn't allow us to modify or create variables outside of a
116         #dictionary, so give it one.
117         entry.attributes = {}
118
119     def cb_story_end(self, entries):
120         """If this is a single entry, get the comments and add the
121         "Add Comment" form"""
122         if len(entries) == 1:
123             story = entries[0].relpath
124             return [self.get_comments(story), self.comment_form(story)]
125
126     def comment_form(self, story):
127         url = urljoin(config('base_url'), '/Comments/add')
128         return ('comment_form', {'url': url, 'story':story})
129
130     def cb_admin_navbar(self):
131         return [('ls_comments', 'List Comments')]
132
133     def cb_admin_call(self, f, args, kwargs):
134         if f == "ls_comments":
135             return ('admin_ls_comments', {'comments': self.get_all_comments()})
136         if f == "delete_comments":
137             deletes = kwargs['delete_filename']
138             if len(deletes) == 0: return
139             elif type(deletes) == type(''): deletes = [deletes]
140
141             for f in deletes:
142                 self.delete(f)
143
144             raise cpy.HTTPRedirect("/Admin/ls_comments")
Note: See TracBrowser for help on using the browser.