aboutsummaryrefslogtreecommitdiffstats
path: root/bn_django/git_wiki/views.py
blob: dcd1646bcedf78d6a7bab9172303b5e6e4ddac2a (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
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
from django import forms, http, template
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponse, Http404, HttpResponseServerError

import os, commands

from models import *
from settings import *
from django.contrib.comments.models import Comment,FreeComment

# Create your views here.

def frontpage(request):
    t = fromslug('')
    t.update()
    #TODO: doesn't display free comments unless there's a comment
    lc = Comment.objects.filter(content_type__name="item").order_by('-submit_date')[:6]
    lfc = FreeComment.objects.filter(content_type__name="item").order_by('-submit_date')[:6]
    return render_to_response('git_wiki/frontpage.html', \
            dict(shortlog=shortlog(), tree=t,
                 latest_comments=lc, latest_freecomments=lfc,
                 newitems=newest_items()))

def tree(request, reqslug, tree=None):
    if not tree:
        t = fromslug(reqslug)
        if not t:
            raise Http404
        if t.type == 'blob':
            return item(request, reqslug, blob=t)
    else: 
        t = tree

    t.update()
    (heads,tags) = reposcan()
    return render_to_response('git_wiki/tree.html',
            dict(shortlog=shortlog(tree=t), tree=t,
                heads=heads,tags=tags))

def item(request, reqslug, blob=None):
    if not blob:
        i = fromslug(reqslug)
        if not i:
            raise Http404
        if i.type == 'tree':
            return tree(request, reqslug)
    else: 
        i = blob
    i.update()

    try:
        from docutils.core import publish_parts,Publisher
        import latex_directive
        latex_directive.dorawtexstuff = False
        latex_directive.register()
    except ImportError:
        if settings.DEBUG:
            raise HttpResponseServerError(request)
    else:
        docutils_settings = getattr(settings, "GITWIKI_REST_SETTINGS", {})
        parts = publish_parts(source=i.contents, writer_name="html4css1", settings_overrides=docutils_settings)
        return render_to_response('git_wiki/item.html',
                        dict(item=i,doc=parts,user=request.user))

def latexitem(request, reqslug, blob=None):
    if not blob:
        i = fromslug(reqslug)
        if not i:
            raise Http404
        if i.type == 'tree':
            return tree(request, reqslug)
    else: 
        i = blob
    i.update()

    try:
        from docutils.core import publish_parts,Publisher
        import latex_directive
        latex_directive.dorawtexstuff = True
        latex_directive.register()
    except ImportError:
        if settings.DEBUG:
            raise HttpResponseServerError(request)
    else:
        docutils_settings = getattr(settings, "GITWIKI_REST_SETTINGS", 
            {'format':'latex'})
        parts = publish_parts(source=i.contents, writer_name="latex", settings_overrides=docutils_settings)
        hr = HttpResponse(mimetype="text/plain")
        hr['Content-Disposition'] = 'filename=%s.tex' % reqslug
        hr.write(parts['whole'].replace('{\$}','$'))
        #hr.write(parts['whole'])
        return hr

def pdfitem(request, reqslug, blob=None):
    if not blob:
        i = fromslug(reqslug)
        if not i:
            raise Http404
        if i.type == 'tree':
            return tree(request, reqslug)
    else: 
        i = blob
    i.update()

    try:
        from docutils.core import publish_parts,Publisher
        import latex_directive
        latex_directive.dorawtexstuff = True
        latex_directive.register()
        import tempfile,re,os,shutil
    except ImportError:
        if settings.DEBUG:
            raise HttpResponseServerError(request)
    else:
        docutils_settings = getattr(settings, "GITWIKI_REST_SETTINGS", 
            {'format':'latex'})
        parts = publish_parts(source=i.contents, writer_name="latex", settings_overrides=docutils_settings)
        tmpdir = tempfile.mkdtemp()
        pre = i.slug().split('/')
        for fig in re.findall('\\includegraphics.*\{(.+)\}', parts['whole']):
            try:
                if len(pre) > 1:
                    fig_blob = fromslug("%s/%s" % ('/'.join(pre[:-1])),fig)
                else:
                    fig_blob = fromslug(fig)
                fig_blob.update()
                # if might have to create subdirectories for figures
                fig_pre = fig.split('/')
                if len(fig_pre) > 1:
                    os.mkdir("%s/%s" % (tmpdir,'/'.join(fig_pre[:-1])))
                fig_file = file(str("%s/%s" % (tmpdir,fig)),'wb')
                fig_file.write(fig_blob.contents)
                fig_file.close()
            except:
                parts['whole'].replace(fig,'')
        hr = HttpResponse(mimetype="application/pdf")
        #hr = HttpResponse()
        hr['Content-Disposition'] = 'filename=%s.pdf' % reqslug
        write_tex,pdf = os.popen2('rubber-pipe -qqq -d --into %s' % tmpdir)
        write_tex.write(parts['whole'].replace('{\$}','$'))
        write_tex.flush()
        write_tex.close()
        #hr.write(parts['whole'])
        #pdf.flush()
        for l in pdf.readlines():
            hr.write(l)
        try:
            pdff = open("%s/rubtmp0.pdf" % tmpdir,'r')
            for l in pdff.readlines():
                hr.write(l)
            pdff.close()
        except: 
            pass
        pdf.close()
        shutil.rmtree(tmpdir)
        return hr

def rawitem(request, reqslug, blob=None):
    if reqslug.endswith('/'):
        reqslug=reqslug[:-1]
    if not blob:
        i = fromslug(reqslug)
        if not i:
            raise Http404
        if i.type == 'tree':
            return tree(request, reqslug)
    else: 
        i = blob
    i.update()
    slug = i.slug()
    r = HttpResponse(mimetype="text/plain")
    r['Content-Disposition'] = 'filename=%s.txt' % reqslug
    r.write(i.contents)
    return r

def figure(request, reqslug, blob=None, download=False):
    if reqslug.endswith('/'):
        reqslug=reqslug[:-1]
    if not blob:
        i = fromslug(reqslug)
        if not i:
            l = reqslug.split('/')
            if l[-2] == 'fig':
                l = l[:-3] + l[-2:]
            else:
                l = l[:-2] + l[-1:]
            i = fromslug('/'.join(l))
            if not i:
                raise Http404
        if i.type == 'tree':
            return tree(request, reqslug)
    else: 
        i = blob
    mime = "image/image"
    slug = i.slug()
    i.update()
    if slug.endswith('.jpg') or slug.endswith('.jpeg'):
        mime = "image/jpeg"
    elif slug.endswith('.png'):
        mime = "image/jpeg"
    elif slug.endswith('.gif'):
        mime = "image/jpeg"
    elif slug.endswith('.svg'):
        mime = "image/svg+xml"
    r = HttpResponse(mimetype=mime)
    if download:
        r['Content-Disposition'] = 'attachment; filename=%s' % reqslug
    else:
        r['Content-Disposition'] = 'filename=%s' % reqslug
    f = i.getfile()
    t = f.readlines()
    r.write(i.contents)
    return r

def olditem(request, hash):
    i = get_object_or_404(Item, id=hash)
    i.update()
    return render_to_response('git_browse/olditem.html',
                      dict(item=i))

def view_commit(request, hash):
    (heads, tags) = reposcan()
    c = Commit(id=hash)
    c.update()

    from pygments import highlight
    from pygments.lexers import DiffLexer
    from pygments.formatters import HtmlFormatter
    
    c.pretty_diff = highlight(c.rawdiff, DiffLexer(), HtmlFormatter())

    return render_to_response('git_wiki/commit.html',
                      dict(heads=heads, tags=tags,
                      commit=c))