Pypaste / friendpaste / views.py

The default branch has multiple heads

  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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
# -*- coding: utf-8 -
# Copyright 2008 by Benoît Chesneau <benoitc@e-engura.com>
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from cStringIO import StringIO


from datetime import datetime
import os.path
import socket
import tempfile
import time
from uuid import UUID

from couchdb.client import ResourceNotFound, ResourceConflict 
from jinja2.filters import do_truncate, do_striptags, escape
from wtforms import Form, TextField, TextAreaField, SelectField, PasswordField, \
ValidationError, validators
from pygments.lexers import get_all_lexers, get_lexer_for_filename
from pygments.styles import get_all_styles
from pygments.formatters import HtmlFormatter
from werkzeug import redirect
from werkzeug.utils import url_quote
from werkzeug.exceptions import Unauthorized, NotFound

import simplejson as json

from pylint.lint import PyLinter, Run

from friendpaste import settings
from friendpaste.feeds import RssFeed, RssFeedEntry 
from friendpaste.http import FPResponse, send_json
from friendpaste.models import Paste, Fork, Review, Privacy
from friendpaste.template import render_response, highlighter, pretty_type, shighlight, \
render_template, url_for, ALL_COLORSHEME 
from friendpaste.utils import local, local_manager, datetimestr_topython,\
strptime, make_hash, datetime_tojson, send_stomp_msg, force_unicode, utf8, to_str
from friendpaste.utils.diff import get_unchanged_lines
from friendpaste.utils.html import sanitize_html
from friendpaste.utils.base62 import *
from friendpaste.ext.webpylint import PYPHTMLReporter, parse_report

def _get_lexers(request):
    lexers = list(get_all_lexers())
    top_lexers = []
    ret=[]

    preferred = request.session.get('languages', [])

    if not preferred: 
        try:
            preferred = settings.TOP_LEXERS
        except:
            preferred = []
    
    # first pass 
    if preferred:
        for l in lexers:
            if l[1][0] in preferred and l[1][0] != "text":
                top_lexers.append((l[1][0],l[0]))
        top_lexers.sort()
    
    for l in lexers:
        if l[1][0] not in preferred and l[1][0] != "text":
            ret.append((l[1][0],l[0]))

    ret.sort()
    if top_lexers: 
        ret = top_lexers + [('', '------------')] + ret
    return [('text', 'Plain text')] + ret

ALL_LEXERS=get_all_lexers()



PRIVACY_CHOICES = [
        ('open', 'Everyone can view and edit'),
        ('public', 'Require a password to edit'),
        ('private', 'Require a password to view and edit')
]



class PasteForm(Form):
    title=TextField('Title')
    snippet=TextAreaField('Paste', [validators.length(min=3, max=500000)])
    language = SelectField(u'Programming Language', choices=[])
    code = PasswordField(u'Removal/Lock code', default='')
    privacy = SelectField(u'Kind of paste', choices=PRIVACY_CHOICES, default='open')
    password = PasswordField(u'Password', default='')

    def validate_privacy(form, field):
        if field.data != "open" and not form.data['password']:
            raise ValidationError(u'Password is empty.')


def login_required(f, privacy=['private']):
    def _decorated(request, **kwargs):
        authenticated = request.session.get(
                '%s_authenticated' % request.pasteid, False)
        mimetypes = request.accept_mimetypes
        if request.privacy is not None:
            if request.privacy.privacy in privacy and not authenticated:
                if 'application/json' in mimetypes or request.is_xhr:
                    raise Unauthorized
                return redirect(url_for('login', 
                    id=request.pasteid, next=request.path))
        return f(request, **kwargs)
    return _decorated
           
def not_logged(f):
    def decorated(request, **kwargs):
        authenticated = request.session.get('%s_authenticated' % request.pasteid)
        if authenticated is not None:
            redirect_url = request.values.get('next', '/')
            return redirect(redirect_url)
        return f(request, **kwargs)
    return decorated

def create_snippet(request):
    mimetypes = request.accept_mimetypes
    error = False
    if request.method=='POST' and 'application/json' in mimetypes:
        d=json.loads(request.data)
        lang=request.values.get("lang", None)
        language=d.get('language', 'text')
        if lang == "ext":
            try:
                l = get_lexer_for_filename("test."+language)
                language = l.aliases[0]
            except:
                language = 'text'
        try:
            code = d.get('edit_code', '')
            if code:
                code = make_hash(code)

            s = Paste(
                    title=d.get('title', ""),
                    content=d.get('snippet'),
                    language=language,
                    edit_code=code 
            )
            s.store(local.db)

            p = Privacy(
                pasteid = s.id,
                privacy = form.data['privacy'],
                password = pwd
            )
            p.store(local.db)
        except:
            return send_json({'ok': False, 'reason': 'something wrong happend while saving data'})
        encoded_id =  b62encode(UUID(s.id).int)
        return send_json({
            'ok': True,
            'id': encoded_id,
            'rev': s.revid,
            'url': '%s/%s' % (settings.SITE_URI, encoded_id)
        })

    form = PasteForm(request.form, prefix='paste')
    form.language.choices = _get_lexers(request)

    if request.method=='POST' and form.validate():
        code = form.data['code']
        if code:
            code = make_hash(code)

        pwd = form.data.get('password', '')
        if pwd:
            pwd = make_hash(pwd)

        language = form.data['language'];
        if not language:
            language = "text"
        try:
            s = Paste(
                title=form.data['title'],
                content=form.data['snippet'],
                language= language,
                edit_code= code        
            )
            s.store(local.db)

            p = Privacy(
                pasteid = s.id,
                privacy = form.data['privacy'],
                password = pwd
            )
            p.store(local.db)

            encoded_id =  b62encode(UUID(s.id).int)
            request.session['%s_authenticated' % encoded_id] = True
        
            return redirect ('/%s' % encoded_id)
        except:
            error = True

    return render_response('paste/index.html', form=form, error=error)


def edit_snippet(request, id):
    revid = request.values.get('rev', None)
    pasteid = UUID(int=b62decode(id)).hex

    s = Paste.get_paste(local.db,pasteid, revid)
    if not s:
        raise NotFound

    if s.locked:
        if revid:
            redirect_url = url_for('paste/view', id=id, rev=revid)
        else:
            redirect_url = url_for('paste/view', id=id)
        return redirect(redirect_url)

    form = PasteForm(request.form, prefix='paste', **{
        'title': s.title,
        'snippet': s.content,
        'language': str(s.language)
    })
    form.language.choices = _get_lexers(request)

    error = ""

    if request.method=='POST' and form.validate():
        if 'bcancel' in form.data:
            return redirect ('/%s' % s.pasteid)
        
        old_revision = s.revid
        old_content = s.content 
        
         # add latest reviews to unchanged lines
        unchanged = get_unchanged_lines(old_content,form.data['snippet'] )

        language = form.data['language'];
        if not language:
            language = "text"

        s.title=form.data['title']
        s.content = form.data['snippet']
        s.language = language

        try:
            s.store(local.db)
        except ResourceConflict:
            error = "ResourceConflict"
        except:
            error = "Unknown"
        
        if not error:
            if revid:
                redirect_url = url_for('paste/view', id=id, rev=revid)
            else:
                redirect_url = url_for('paste/view', id=id)

            if s.revid != old_revision:
                # move reviews for unchanged lines
                Review.update_positions(local.db, s.id, s.revid, old_revision, unchanged)
                
                # warn users that paste has been updated
                message = json.dumps({
                    'revision': s.revid,
                    'type': 'update'
                })
                send_stomp_msg(' ' + message, destination='/paste/%s' % (id))
            return redirect (redirect_url)
    
    s.pasteid = id
    
    return render_response('paste/edit.html', form=form, snippet=s, error=error)
edit_snippet = login_required(edit_snippet, privacy=['private', 'public'])

@login_required
def fork_snippet(request, id):
    revid = request.values.get('rev', None)
    pasteid = UUID(int=b62decode(id)).hex
    error = False

    s = Paste.get_paste(local.db, pasteid, revid)

    if not s:
        raise NotFound

    form = PasteForm(request.form, prefix='paste', **{
        'title': s.title + ' [Forked]',
        'snippet': s.content,
        'language': str(s.language)
    })

    form.language.choices = _get_lexers(request)

    if request.method == 'POST' and form.validate():
        code = form.data['code']
        if code:
            code = make_hash(code)

        pwd = form.data.get('password', '')
        if pwd:
            pwd = make_hash(password)

        language = form.data['language'];
        if not language:
            language = "text"

        s.forked = True
        s.store(local.db)
        try:
            new_paste = Paste(
                title=form.data['title'],
                content=form.data['snippet'],
                language=language,
                edit_code= code,
                fork = True,
                fork_parent = pasteid,
                forked_atrevision = s.revid
            )
            new_paste.store(local.db)

            # save fork infos
            new_fork = Fork(
                fork_parent = pasteid,
                forked_atrevision = s.revid,
                fork_id = new_paste.id
            )
            new_fork.store(local.db)

            # save privacy
            p = Privacy(
                pasteid = new_paste.id,
                privacy = form.data['privacy'],
                password = pwd
            )
            p.store(local.db)
        
        
            encoded_id =  b62encode(UUID(new_paste.id).int)
            return redirect('/%s' % encoded_id) 
        except:
            error = True

    return render_response('paste/fork.html', form=form, snippet=s)

@login_required
def view_snippet(request, id):
    revid = request.values.get('rev', None)
    pasteid = UUID(int=b62decode(id)).hex
    s = Paste.get_paste(local.db,pasteid, revid)

    if s is None: 
        raise NotFound

    mimetypes = request.accept_mimetypes
    if 'application/json' in mimetypes and request.method=='PUT':
        d = json.loads(request.data)
        lang=request.values.get("lang", None)
        language=d.get('language', 'text')
        if lang == "ext":
            try:
                l = get_lexer_for_filename("test."+language)
                language = l.aliases[0]
            except:
                language = 'text'
        old_revid = s.revid
        try:
            s.title=d.get('title')
            s.content = d.get('snippet')
            s.language = language
            s.store(local.db)
        except:
            return send_json({'ok': False, 'reason': 'unknown'})
        if s.revid == old_revid:
            return send_json({'ok': False, 'reason': 'no changes'})

        # warn users that paste has been updated
        message = json.dumps({
            'revision': s.revid,
            'type': 'update'
        })

        send_stomp_msg(' ' + message, destination='/paste/%s' % (id))

        return send_json({
            'ok': True,
            'id': id,
            'revision': s.revid,
            'url': '%s/%s' % (settings.SITE_URI, id)
        })

        
    if 'application/json' in mimetypes:
        if s is None:
            return send_json({'ok': false})
        if request.method == 'GET':
            snippet_hash = {
                'id': id,
                'revision': s.revid,
                'title': s.title,
                'snippet': s.content,
                'language': str(s.language)
            }
            return send_json(snippet_hash)
            
    form = PasteForm(request.form, prefix='paste', **{
        'title': s.title,
        'snippet': s.content,
        'language': str(s.language)
    })
    form.language.choices = _get_lexers(request)

    s.pasteid = id

    reviews_counts = Review.get_reviews_counts(local.db, pasteid, s.revid)
    return render_response('paste/view.html', snippet=s, form=form, rev=revid, 
            reviews_counts=reviews_counts)
 
def delete_snippet(request, id):
    pasteid = UUID(int=b62decode(id)).hex
    s = Paste.load(local.db, pasteid)
    if s is None or not s.edit_code:
        raise NotFound

    error = False
    if request.method == "POST" or request.method == "DELETE":
        edit_code = request.form.get('edit_code', '')
        if edit_code and make_hash(edit_code) == s.edit_code:
            Paste.delete(local.db, pasteid)

            message = json.dumps({
                'type': 'delete'
            })
            send_stomp_msg(' ' + message, destination='/paste/%s' % (
                    id))
            if request.is_xhr:
                return send_json({ "ok": True })
            return redirect('/')
        if request.is_xhr:
            return send_json({ "ok": False })
        error = True

    s.pasteid = id

    return render_response('paste/delete.html', snippet=s, error=error)


def lock_snippet(request, id):
    pasteid = UUID(int=b62decode(id)).hex
    revid = request.values.get('rev', None)
    s = Paste.load(local.db, pasteid)

    if s is None or not s.edit_code:
        raise NotFound

    error = False
    if request.method == "POST":
        edit_code = request.form.get('edit_code', '')
        if edit_code and make_hash(edit_code) == s.edit_code:
            locked = not s.locked
            try:
                Paste.lock(local.db, pasteid, locked) 

                if request.is_xhr:
                    return send_json({ "ok": True })
                return redirect(url_for("paste/view", id=id, rev=revid))
            except:
                pass
        if request.is_xhr:
            return send_json({ "ok": False })
        error = True
    return render_response('paste/lock.html', snippet=s, error=error)

@login_required  
def view_source(request, id):
    revid = request.values.get('rev', None)
    pasteid = UUID(int=b62decode(id)).hex
    s = Paste.get_paste(local.db,pasteid, revid)

    if s is None:
        raise NotFound
               
    return render_response('paste/view_source.html', snippet=s)


def view_rss(request, id):
    pasteid = UUID(int=b62decode(id)).hex
    snippet, revisions = Paste.with_revisions(local.db, pasteid, request.values.get('rev'))
    if snippet is None:
        raise NotFound
        
    p = Privacy.for_paste(local.db, pasteid)
    if p.privacy == "private":
        if p.password != make_hash(request.values.get('password', '')):
            raise Unauthorized

    feed = RssFeed(
        title="Revisions to %s on Friendpaste" % (snippet.title and snippet.title or "snippet #%s" % id),
        description = '',
        link = "%s/%s" % (settings.SITE_URI, id)
    
    )
 
    revisions = [snippet] + revisions
    for revision in revisions:
        description = ""
        if not revision.previous:
            description = "Created"
        else:
            for change in revision.changes:
                if change['type'] != "unmod":
                    description = "%s " % pretty_type(change['type']) 
                    description += "\n".join(change['changed']['lines'])
                description = do_truncate(do_striptags(description), 60)
                description = description.replace("\n", "<br />")
                    
        feed.add_entry(RssFeedEntry(
            title="%s revision %s" % (revision.title, revision.revid),
            link= "%s/%s?rev=%s" % (settings.SITE_URI, id, revision.revid),
            description=description,
            **{ 
                'published': datetimestr_topython(revision.created),
                'updated': datetimestr_topython(revision.updated)
            }
        ))
     
    return feed.get_response()

@login_required
def view_revisions(request, id):
    pasteid = UUID(int=b62decode(id)).hex
    snippet, revisions = Paste.with_revisions(local.db, pasteid, request.values.get('rev'))
    
    if snippet is None:
        raise NotFound

    revisions = [snippet] + revisions
    revisions_ = []
    if revisions and revisions is not None:
        for rev in revisions:
            revision = rev._data
            revision['pasteid'] = rev.pasteid
            revisions_.append(revision) 

    if 'application/json' in request.accept_mimetypes:
        return send_json(revisions_)

    snippet.pasteid = id

    return render_response('paste/revisions.html', snippet=snippet, revisions=revisions_)
    
    
def highlight(request):
    highlighted = '';
    if request.is_xhr and request.method == 'POST':
        
        data = json.loads(request.data)
        highlighted = shighlight(
                        data.get('paste', ''),
                        data.get('language', 'text')
        )
        
        
    return send_json({ 'highlighted': highlighted })

@login_required
def view_rawsnippet(request, id, rev):
    pasteid = UUID(int=b62decode(id)).hex
    s = Paste.get_paste(local.db,pasteid, rev)
    paste =  Paste.get_paste(local.db, id)
    if s is None:
        raise NotFound
    
    response = FPResponse(s.content)
    response.headers['content-type'] = 'text/plain'
    return response

@login_required
def view_original(request, id, rev):
    pasteid = UUID(int=b62decode(id)).hex
    s = Paste.get_paste(local.db,pasteid, rev)
    paste =  Paste.get_paste(local.db, id)
    if s is None:
        raise NotFound
    
    from pygments import lexers
    lexer = lexers.get_lexer_by_name(s.language)
    response = FPResponse(s.content)
    response.headers['content-type'] = lexer.mimetypes[0]
    if lexer.filenames and len(lexer.filenames)>0:
        response.headers['content-disposition'] =  "filename=%s%s" % (
            id, lexer.filenames[0][1:])
    else:
        response.headers['content-disposition'] =  "filename=%s.txt" % id
    return response

@login_required
def view_changeset(request, id):
    revid = request.values.get('rev', None)
    pasteid = UUID(int=b62decode(id)).hex
    snippet = Paste.get_paste(local.db,pasteid, revid)

    unidiff, tabular, previous = snippet.get_changeset(local.db)
    mimetypes = request.accept_mimetypes
    if 'application/json' in mimetypes:
        return send_json({
            'id': id, 
            'rev': snippet.revid,
            'changeset': unidiff
        })

    format = request.values.get('format', None)
    if format is not None:
        response = FPResponse(unidiff)
        response.headers['content-type'] = 'text/plain'
        return response

    snippet.pasteid = id
    return render_response('paste/diff.html', unidiff=unidiff, difft=tabular,
            snippet=snippet, rev=snippet.revid, old_rev=previous.revid)


@login_required
def snippet_reviews(request, id, nb_line):
    revid = request.values.get('rev', None)
    pasteid = UUID(int=b62decode(id)).hex
    s = Paste.get_paste(local.db, pasteid, revid)
    
    if s is None:
        return send_json({ "ok": False })

    s.pasteid = id
    all_reviews = Review.get_line(local.db, s, nb_line)
    count = len(all_reviews)

    if all_reviews:
        for comment in all_reviews:
            value = datetimestr_topython(comment['created']) 
            comment['fcreated'] = value.strftime("%a %b %d %Y at %H:%M")

    
    return send_json({ "ok": True, "r": all_reviews })

@login_required
def snippet_reviews_set(request, id, nb_line):
    revid = request.values.get('rev', None)
    pasteid = UUID(int=b62decode(id)).hex
    s = Paste.get_paste(local.db,pasteid, revid)

    if s is None:
        return send_json({ "ok": False })

    s.pasteid = id
    all_reviews = Review.get_line(local.db, s, nb_line)
    count = len(all_reviews)

    from_line = int(request.values.get('f', 0))
    if all_reviews:
        if count >= from_line:
            all_reviews = all_reviews[:-from_line]
        else:
            all_reviews = []
    
        for comment in all_reviews:
            value = datetimestr_topython(comment['created']) 
            comment['fcreated'] = value.strftime("%a %b %d %Y at %H:%M")

    return send_json({ 
        "ok": True, 
        "r": all_reviews,
        "count":count 
    })

@login_required
def snippet_review(request, id, nb_line):
    revid = request.values.get('rev', None)
    pasteid = UUID(int=b62decode(id)).hex
    s = Paste.get_paste(local.db, pasteid, revid)

    if s is None:
        return send_json({ "ok": False })

    s.pasteid = id
    review = Review.review_for_line(local.db, s, nb_line)

    last_inserted = 0
    if request.method == "POST" and request.is_xhr:
        d = json.loads(request.data)
        last_inserted = d.get('nb_lines', last_inserted)
        new_review = {
            "nickname": d.get('nickname', 'anonymous'),
            "comment": force_unicode(sanitize_html(d.get('new_review', ''))), 
            "created": datetime_tojson(datetime.utcnow())
        }
        if review is not None:
            # hack waiting our use of simplecouchdb
            reviews = review.reviews;
            reviews.append(new_review)
            review.reviews = reviews
            review.store(local.db)    
        else:
            review = Review(
                    pasteid = pasteid,
                    revision = s.revid,
                    nb_line = nb_line,
                    reviews = [new_review]
            )
            try:
                review.store(local.db)
            except:
                return send_json({"ok": False })

        # warn all connected user of this addition
        message = json.dumps({
            'nb_line': review.nb_line,
            'reviews_count': len(review.reviews),
            'type': 'review'
        })

        send_stomp_msg(' ' + message, destination='/paste/%s/%s' % (
                    id, s.revid))

    all_reviews = []
    if review.reviews:
        if len(review.reviews) >= last_inserted:
            all_reviews = review.reviews[last_inserted:]
        else:
            all_reviews = []
    
        all_reviews.sort(lambda a,b: cmp(a['created'], b['created']))
        all_reviews.reverse()
        for comment in all_reviews:
            value = datetimestr_topython(comment['created']) 
            comment['fcreated'] = value.strftime("%a %b %d %Y at %H:%M")

    return send_json({ 
        "ok": True, 
        "r": all_reviews,
        "count": len(review.reviews)
    })

def get_all_languages(request):
    lexers = get_all_lexers()
    languages=[[l[1][0],l[0]] for l in lexers]
    languages.sort(lambda a, b: cmp(a, b))
    return send_json(languages)


def embed(request, id):
    revid = request.values.get('rev', None)
    pasteid = UUID(int=b62decode(id)).hex
    p = Paste.get_paste(local.db,pasteid, revid)
    
    if p is None:
        raise NotFound

    priv = Privacy.for_paste(local.db, p.id)
    if priv.privacy == "private":
        if priv.password != make_hash(request.values.get('password', '')):
            raise Unauthorized


    response = render_response('paste/embed.js', snippet=p, theme='default')
    response.headers['content-type'] = 'application/javascript'
    return response

def fpsettings(request):
    if request.method == "POST":
        try:
            data = json.loads(request.data)
        except ValueError:
            return send_json({'ok': False})
        
        for attrname, value in data.items():
            request.session["setting_%s" % attrname] = value
    
    _settings = {}
    for key, value in request.session.items():
        if key.startswith('setting_'):
            _settings[key[8:]] = value
    
    if not _settings:
        return send_json({"ok": False})

    return send_json( { 'ok': True, 'settings': _settings } )

def fplanguages(request):
    if request.method == "POST" and request.is_xhr:
        try:
            data = json.loads(request.data)
        except ValueError:
            return send_json({'ok': False})

        request.session['languages'] = data
        return send_json({'ok': True})
    return send_json({'ok': false})

    
@not_logged
def login(request, id):
    mimetypes = request.accept_mimetypes
    next = request.values.get('next', '/%s' % id)
    error = ""

    if request.method == "POST":
        if 'application/json' in mimetypes:
            d = json.loads(request.data)
            password = d.get('password', '')
            if not password:
                return send_json({ 'ok': False, 'reason': 'Password is empty'})
            if password == request.privacy.password:
                request.session['%s_authenticated' % id] = True
                return send_json({'ok': True})
            raise Unauthorized

        password = request.form.get('password', '')
        next = request.form.get('next', '/%s' % id)
        if password:
            if make_hash(password) == request.privacy.password:
                request.session['%s_authenticated' % id] = True
                return redirect(next)
            error = u"Password is invalid."
        else:
            error = u"Password is empty."
            
    return render_response("paste/login.html", pasteid=id, 
            next=next, error=error)

def logout(request, id):
    key = '%s_authenticated' % id
    if request.privacy.privacy in ['public', 'open']:
        next = "/%s" % id
    else:
        next = request.values.get('next', '/')
    if key in request.session:
        del request.session[key]
    return redirect(next)

# pylint for pypaste
@login_required
def view_pylint(request, id):
    revid = request.values.get('rev', None)
    pasteid = UUID(int=b62decode(id)).hex
    p = Paste.get_paste(local.db,pasteid, revid)
    
    if p is None:
        raise NotFound

    
    (fd, path) = tempfile.mkstemp()
    f = os.fdopen(fd, "w")
    f.write(to_str(p.content))
    f.close()
    output = StringIO()
    Run([path,'--disable-msg', 'C0103','--disable-msg', 'C0111'], reporter=PYPHTMLReporter(output), quiet=1)
    report=parse_report(utf8(output.getvalue()), path, id)
    output.close()
    os.unlink(path)
    p.pasteid = id
    return render_response('paste/report.html', snippet=p, report=report)


# generic views
def about(request):
    return render_response("about.html")

def services(request, page=None):
    if page is None:
        return render_response("services.html")

    return render_response("services/%s.html" % page)
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.