sphinx-gsoc2009 / sphinx / web / middleware / appserver.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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    sphinx.web.middleware.appserver
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    A middleware for Xapian search engine.

    :copyright: Copyright 2007-2009 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

try:
    import json
except ImportError:
    try:
        import simplejson as json
    except ImportError:
        raise ImportError('json module not found')

import os
import re
import time
import locale
from os import path
from difflib import Differ
from hashlib import md5

from jinja2 import Environment, FileSystemLoader, Template
from webob import Request, Response

from sphinx.errors import SphinxError
from sphinx.web.dbutils import PidDb, RepoSums
from sphinx.web.webauth import WebAuth
from sphinx.web.webconfig import WebConfig
from sphinx.web.singlebuilder import SinglefileHTMLBuilder

def index_by_key_val(data, key, val):
    """For a list of dictionaries return an index of a dictionary
    with key:val pair. If there's no such a dictionary in the list,
    return None"""
    for elem in enumerate(data):
        if elem[1].has_key(key) and elem[1].get(key) == val:
            return elem[0]
    return None

def load_comments(db_path):
    """Open a 'db_path' file, dejsonify the loaded data and return it.
    On error return empty list."""
    try:
        w = open(db_path, 'rb')
        data = json.load(w)
        w.close()
    except Exception, err:
        return []
    return data
    
def save_comments(db_path, data):
    """Open a 'db_path' file and dump the data in json format.
    Returns nothing or an exception on error."""
    try:
        w = open(db_path, 'wb')
        json.dump(data, w)
        w.close()
    except Exception, err:
        raise SphinxError(err)

def delete_comment(db, p_id, comment_no):
    """From database 'db' open file 'p_id' and find a record (which is
    a dictionary) with key-val pair { "comment_no": 'comment_no' }
    and delete it.
    """
    db_path = get_db_path(db, p_id)
    data = load_comments(db_path)
    # pop a dictionary by the value of 'comment_no' key
    cindex = index_by_key_val(data, 'comment_no', comment_no)
    data.pop(cindex)
    save_comments(db_path, data)

def get_comments_db_path(p_id):
    return 'comments/' + p_id

def get_fixes_db_path(p_id):
    return 'fixes/' + p_id

def get_db_path(db, p_id):
    if db == 'comments':
       db_path = get_comments_db_path(p_id)
    else:
       db_path = get_fixes_db_path(p_id)
    return db_path

def modify_diff(data):
    """
    Takes a list of strings, modifies it and returns a string.
    If a string starts with '?' sign, remove whole string.
    If a string starts with '+' sign, change font color to blue.
    If a string starts with '-' sign, change font color to red.
    For every string change every new-line sign to HTML new line sign ('<br>').
    """
    slen, n = len(data), 0
    while n < slen:
        # remove the lines which start with '?' sign
        if data[n][0] == '?':
            data[n] = ''
        elif data[n][0] == '+':
            data[n] = '<font color="blue">' + data[n] + '</font><br>'
        elif data[n][0] == '-':
            data[n] = '<font color="red">' + data[n] + '</font>'
        data[n] = data[n].replace('\n', '<br>')
        n += 1
    return ''.join(data)


def sort_by_thread(data, embed_level=100, embed_diff=5):
    """Sort a list 'data' by thread and return a list of tuples:
    [ (comment_no1, embed_level),
      (comment_no2, embed_level),
      ... ]

    'embed_level' - HTML width for first level of embeddedness
                    (default: 100, meaning 100% width).
    'embed_diff'  - a (HTML width) difference between levels
                    of embeddedness: embed_level - embed_diff
                    (by default, for first sub-level: 100-5=95%).
    """
    sorted_by_thread = []
    def find_children(comment_no, data):
        children = []
        for rec in enumerate(data):
            if comment_no == rec[1]['in_reply_to']:
                children.append(data[rec[0]]['comment_no'])
        return children

    def build_tree(cnr, data, level):
        children = find_children(cnr, data)
        sorted_by_thread.append((cnr, level))
        for child in children:
            build_tree(child, data, level-embed_diff)

    # build trees for all root comments
    for rec in enumerate(data):
        if rec[1]['in_reply_to'] == 'root':
            build_tree(rec[1]['comment_no'], data, embed_level)

    return sorted_by_thread


def get_sorted_by_thread(data):
    """Create a list of comments sorted by thread. For every record
    add a new field called 'width' with HTML size of given comment."""
    sorted_by_thread = sort_by_thread(data)
    comments_sorted = []
    for cno_embed_pair in sorted_by_thread:
        cno, embed_level = cno_embed_pair
        dindex = index_by_key_val(data, 'comment_no', cno)
        data[dindex]['width'] = embed_level
        comments_sorted.append(data[dindex])
    return comments_sorted


class AppServer(object):
    """This middleware is responsible for serving the docs (the docs are
    pickled files, so it has to load a file from a pickle) and for handling
    comments/fixes views (adding/scoring/sorting etc.).
    """
    def __init__(self, app, www_dir='public/', developers=None):
        self.app = app
        self.env = None
        self.www_dir = www_dir
        self.template_vals = {}
        self.webconfig = WebConfig()
        self.piddb = PidDb(self.webconfig.piddbfile)
        self.webauth = WebAuth()
        self.webauth.developers_load('developers.txt')
        self.reposums = RepoSums(self.webconfig.reposums)
        self.htmlbuilder = SinglefileHTMLBuilder(self.www_dir,
                                                 self.webconfig.repodir,
                                                 self.webconfig.piddbfile,
                                                 self.webconfig.licence)
        self.init_templates()

        # an argument for 'reverse' option of sorted function:
        # True => ascending order, False => descending order
        self.sort_order = { 'score': True, 'date': True }

        # when rating comments, we have to know in what sort order the
        # results should be returned; by default we sort by date
        self.current_sort_order = 'date'

        # we don't want to change the order if we're switching from
        # date sorting to score sorting etc.
        self.last_sort_order = None

    def __call__(self, environ, start_response):
        req = Request(environ)
        resp = Response(content_type='text/html', charset='utf8')
        resp.status = 404

        SW = req.path.startswith

        if req.path.endswith('.html'):
            resp = self.doHTMLFile(req, resp)
        elif req.path == '/add_comment':
            resp = self.doAddComment(req, resp)
        elif SW('/rate_comment'):
            resp = self.doRateComment(req, resp)
        elif SW('/sort_comments'):
            resp = self.doSortComments(req, resp)
        elif SW('/comments/'):
            resp = self.doReadComments(req, resp)
        elif SW('/fixes/'):
            resp = self.doReadFixes(req, resp)
        elif SW('/get_paragraph'):
            resp = self.doGetParagraph(req, resp)
        elif SW('/delete_comment'):
            resp = self.doDeleteComment(req, resp)
        elif SW('/isdeveloper'):
            resp = self.doIsDeveloper(req, resp)
        elif SW('/commit_fix'):
            resp = self.doCommitFix(req, resp)
        else:
            return self.app(environ, start_response)

        return resp(environ, start_response)


    def constructPath(self, req):
        if req.path == '/':
            rel_file = 'index.html'
        else:
            rel_file = req.path[1:]

        # XXX: '../../../etc/passwd' bug? ;-)
#        file_path = path.join(self.www_dir, rel_file)
#        return file_path
        return rel_file

    def doReadCF(self, req, resp, db_path_func):
        """jQuery requests for comments/fixes in two ways:
        1. It sends HEAD requests to determine if the database file exists.
        2. It sends GET requests to get the jsonified data from the file.
        After loading the file and before sending it, the records are sorted
        by the currently chosen property (score/date/thread/etc)
        and in currently chosen order (descending/ascending)."""
        if req.method == 'HEAD':
            rel_file = req.path[1:]
            if path.exists(rel_file):
                resp.status = 200
            else:
                resp.status = 404
        else:
            p_id = req.GET['id']
            db_path = db_path_func(p_id)
            if path.exists(db_path):
                data = load_comments(db_path)
                data = self.sort_cf(data)
                resp.body = json.dumps(data)
            resp.status = 200
        return resp

    def doReadComments(self, req, resp):
        return self.doReadCF(req, resp, get_comments_db_path)

    def doReadFixes(self, req, resp):
        return self.doReadCF(req, resp, get_fixes_db_path)

    def doSortComments(self, req, resp):
        """Sort the comments/fixes by chosen property (score/date/thread)
        and in chosen order (ascending/descending). 
        """
        def sort_switch(by):
            """Switch the order of sorting for property 'by' (possible values:
            'score'/'date'/'thread') from ascending to descending or vice versa.
            """
            if by == 'thread':
                return
            elif self.last_sort_order == by:
                self.last_sort_order = by
                return
            if self.sort_order[by]:
                self.sort_order[by] = False
            else:
                self.sort_order[by] = True

        p_id, db, by = req.GET['id'], req.GET['db'], req.GET['by']
        self.current_sort_order = by

        db_path = get_db_path(db, p_id)
        if path.exists(db_path):
            data = load_comments(db_path)
            data = self.sort_cf(data)
            sort_switch(self.current_sort_order)
            resp.body = json.dumps(data)
        resp.status = 200
        return resp

    def doRateComment(self, req, resp):
        """Rate comment/fix (+1/-1).

        To determine which comment to rate, following information is necessary:
        1. Which database to use: for comments or for fixes?
           'req.GET["db"]' determines it. Possible values: 'comments' or 'fixes'.
        2. Which paragraph to change?
           'req.GET["id"]' determines it.
        3. Which comment/fix under the particular paragraph should be rated?
           'req.GET["comment_no"]' keeps the index for this particular comment.
        4. Should the comment/fix be rated up or down?
           'req.GET["up_down"]' defines what to do with the counter.
           'up' means +1 and 'down' means -1.
        """
        p_id, up_down, db = req.GET['id'], req.GET['up_down'], req.GET['db']

        try:
            comment_no = int(req.GET['comment_no'])
        except TypeError:
            comment_no = 0 # should throw an error!
        
        ratedpidcno = "rated_%s_%s" % (p_id, comment_no)
        ratedval = req.cookies.get(ratedpidcno)

        db_path = get_db_path(db, p_id)
        if not ratedval and path.exists(db_path):
            data = load_comments(db_path)
            dindex = index_by_key_val(data, 'comment_no', comment_no)
            if not data[dindex].has_key('score'):
                data[dindex]['score'] = 0
            if up_down == 'up':
                data[dindex]['score'] += 1
            else:
                data[dindex]['score'] -= 1       
            save_comments(db_path, data)
            resp.set_cookie(ratedpidcno, comment_no, max_age=360*24*3600)
        resp.status = 200
        return resp

    def doDeleteComment(self, req, resp):
        """Delete comment"""
        p_id, db, cno = req.GET['id'], req.GET['db'], int(req.GET['cno'])
        if self.webauth.is_developer(req):
            delete_comment(db, p_id, cno)
        resp.status = 200
        return resp

    def doCommitFix(self, req, resp):
        """Commit fix"""
        p_id, fix_no = req.GET['id'], req.GET['fix_no']
        fixes_db_path = get_fixes_db_path(p_id)
        data = load_comments(fixes_db_path)
        fix_index = index_by_key_val(data, 'comment_no', int(fix_no))
        print '>>>', p_id, fix_no, data[fix_index]['paragraph_orig']
        return resp

    def doAddComment(self, req, resp):
        """Adds comment or diff&comment to the database"""
        # whenever a new element is added to the post form, it should
        # also be added to 'post_elems' list. It sucks a bit.
        # Second easy way would be to simply copy req.POST to a new
        # dictionary variable and populate this variable with additional
        # stuff and then save it to the database. The problem here is:
        # it becomes way too easy to pass some additional data to the
        # database.
        def build_db_record(reqdict):
            """Build a base dictionary for database record by populating it
            with the data from req.POST."""
            pid = reqdict['paragraph_id']
            post_elems = [ 'paragraph_id', 'name', 'email', 'www', 'priority',
                           'comment', 'reply_to_%s' % (pid)]
            db_rec = {}
            for elem in post_elems:
                if elem in reqdict:
                    db_rec[elem] = reqdict[elem]
            return db_rec

        p_id = req.POST['paragraph_id']
        db_rec = build_db_record(req.POST)

        # some additional keys for our DB record, which are not added
        # by a HTML form
        db_rec['score'] = 0
        db_rec['date'] = time.time()
        db_rec['width'] = 100

        if req.POST.get('submitFix'):
            p_str = 'paragraph_%s' % (p_id)
            p_orig_str = 'paragraph_orig_%s' % (p_id)
            db_rec['priority'] = req.POST.get('priority')
            db_rec['paragraph'] = req.POST.get(p_str)

            p1 = req.POST.get(p_str).splitlines(1)
            p2 = req.POST.get(p_orig_str).splitlines(1)

            d = Differ()
            pdiff = list(d.compare(p2, p1))
            db_rec['paragraph'] = modify_diff(pdiff)
            db_rec['paragraph_orig'] = pdiff
            db_path = get_fixes_db_path(p_id)
        else:
            db_path = get_comments_db_path(p_id)

        reply_to = req.POST.get('replyto_' + p_id)
        if reply_to:
           db_rec['in_reply_to'] = int(reply_to)
        else:
           db_rec['in_reply_to'] = 'root'

        # if the database file for this particular paragraph doesn't exist
        # start with empty... hmm... data structure ;)
        if path.exists(db_path):
            data = load_comments(db_path)
        else:
            data = []

        if data:
            prev_comment = data[-1]['comment_no']
        else:
            prev_comment = 0

        db_rec['comment_no'] = prev_comment + 1
        data.append(db_rec)
        save_comments(db_path, data)

        resp.status = 200
        return resp

    def doIsDeveloper(self, req, resp):
        """Check if developer's rights should be granted.
        HTTP code 200 is equal to 'true', while 404 means 'false'."""
        if self.webauth.is_developer(req):
            resp.status = 200
        else:
            resp.status = 404
        return resp

    def doGetParagraph(self, req, resp):
        node = req.GET['node']
        pid = req.GET['id']
        resp.status = 200
        resp.body = json.dumps(self.piddb.get_paragraph(node, pid, dbreload=True))
        return resp

    def doHTMLFile(self, req, resp):
        """Rendering the HTML files happens here: things like themes,
        OpenID info and so on."""
        def check_rst_sum(repo_file):
            """Count the MD5 sum for 'repo_file' and compare it with
            MD5 sum from the database. Return True if the MD5 sum has
            changed and False otherwise (return False also when the
            'repo_file' file does not exist."""
            if path.exists(repo_file):
                try:
                    w = open(repo_file)
                    rst_contents = w.read()
                    w.close()
                except Exception, err:
                    SphinxError(err)

                rst_sum = md5(rst_contents).hexdigest()

                if self.reposums.sum_changed(repo_file, rst_sum):
                    return True
            return False

        resp.content_type = 'text/html'
        resp.charset = 'utf8' 
        file_path = self.constructPath(req)

        repo_file = path.join(self.webconfig.repodir,file_path[:-5] + '.rst')
        if check_rst_sum(repo_file):
            self.htmlbuilder.render_page(file_path[:-5])

        file_path = path.join(self.www_dir, file_path)
        try:
            if file_path.endswith('.html'):
                file_contents = open(file_path).read()
                # remove the paragraph's sum before displaying the HTML file 
                file_contents = re.sub("\[psum:[\w\d]{32}\]", '', file_contents)
            else:
                file_contents = open(file_path, 'rb').read()
                resp.body = file_contents.encode('utf8')
                resp.status = 200
                return resp
        except:
            file_contents = '<html><body>doHTMLFile(): 404!</body></html>'
            return resp

#        html_code = self.htmlbuilder.render_file(file_path,
#                                                 file_contents).encode('utf8')

        html_code = unicode(file_contents,
                            locale.getpreferredencoding(), 'replace')

        self.render_openid(req.environ)
        rendered = self.env.from_string(html_code).render(self.template_vals)
        resp.body = rendered.encode('utf8')
        resp.status = 200
        return resp


    def sort_cf(self, data):
        """Sort comments or fixes.

        Do not mix this method (to be exact: do not invoke it before)
        with save_comments() on the same variable.
        The sequence of comments in the file should not be changed
        because it reflects the order of adding the comments/fixes."""
        by = self.current_sort_order
        if by == 'thread':
            data = get_sorted_by_thread(data)
        else: # sort by score or date
            data = sorted(data, key=lambda x: x[by], reverse=self.sort_order[by])
        return data

    def init_templates(self):
        self.env = Environment(loader=FileSystemLoader('html/'),
                               extensions=['jinja2.ext.i18n'])

    def render_openid(self, environ):
        openid_template = self.env.get_template('openid.html')
        openid_html = openid_template.render(
                          { 'openid_url': environ['webapp.OPENID_URL'],
                            'openid_error': environ['webapp.OPENID_ERROR'] })
        self.template_vals['openid_html'] = openid_html
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.