Source

EricFromCanada.bitbucket.org / python / restview / src / restview / restviewhttp.py

Full commit
  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
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
HTTP-based ReStructuredText viewer.

Usage:
    restviewhttp [options] filename.rst
or
    restviewhttp [options] directory
or
    restviewhttp [options] -e "command"
or
    restviewhttp [options] --long-description
or
    restviewhttp --help

Needs docutils and a web browser.  Will syntax-highlight code or doctest blocks
if you have pygments installed.
"""
from __future__ import print_function

import os
import re
import sys
import socket
import optparse
import threading
import webbrowser

try:
    import BaseHTTPServer
except ImportError:
    import http.server as BaseHTTPServer

try:
    import SocketServer
except ImportError:
    import socketserver as SocketServer

import cgi

try:
    from urllib import unquote
except ImportError:
    from urllib.parse import unquote

try:
    from urlparse import parse_qs
except ImportError:
    from urllib.parse import parse_qs

from docutils import core
from docutils.writers import html4css1
import time

try:
    import pygments
    from pygments import lexers, formatters
except ImportError:
    pygments = None


try:
    unicode
except NameError:
    unicode = str


__version__ = "1.3.0dev"


class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    """HTTP request handler that renders ReStructuredText on the fly."""

    server_version = "restviewhttp/" + __version__
    last_atime = 0

    def do_GET(self):
        content = self.do_GET_or_HEAD()
        if content:
            self.wfile.write(content)

    def do_HEAD(self):
        content = self.do_GET_or_HEAD()

    def do_GET_or_HEAD(self):
        self.path = unquote(self.path)
        root = self.server.renderer.root
        command = self.server.renderer.command
        if self.path == '/':
            if command:
                return self.handle_command(command)
            elif isinstance(root, str):
                if os.path.isdir(root):
                    return self.handle_dir(root)
                else:
                    return self.handle_rest_file(root)
            else:
                return self.handle_list(root)
        elif self.path.startswith('/polling?'):
            saved_atime = last_atime
            self.path = parse_qs(self.path.split('?', 1)[-1])['pathname'][0]
            if self.path == '/':
                self.path = os.path.basename(root)
            self.server.renderer.root_mtime = os.stat(self.translate_path()).st_mtime
            while last_atime == saved_atime:
                if os.stat(self.translate_path()).st_mtime != self.server.renderer.root_mtime:
                    try:
                        self.send_response(200)
                        self.send_header("Cache-Control", "no-cache, no-store, max-age=0")
                        self.end_headers()
                        self.server.renderer.root_mtime = os.stat(self.translate_path()).st_mtime
                    except Exception, e:
                        self.log_error('%s (client closed "%s" before acknowledgement)', e, self.path)
                    finally:
                        return
                time.sleep(0.2)
            try:
                self.send_response(204)
                self.end_headers()
            except Exception, e:
                self.log_error('%s (client closed "%s" before cancellation)', e, self.path)
            finally:
                return
        elif '/..' in self.path:
            self.send_error(400, "Bad request") # no hacking!
        elif self.path.endswith('.gif'):
            return self.handle_image(self.translate_path(), 'image/gif')
        elif self.path.endswith('.png'):
            return self.handle_image(self.translate_path(), 'image/png')
        elif self.path.endswith('.jpg') or self.path.endswith('.jpeg'):
            return self.handle_image(self.translate_path(), 'image/jpeg')
        elif self.path.endswith('.txt') or self.path.endswith('.rst'):
            return self.handle_rest_file(self.translate_path())
        else:
            self.send_error(501, 'File type not supported: %s' % self.path)

    def translate_path(self):
        root = self.server.renderer.root
        path = self.path.lstrip('/')
        if not isinstance(root, str):
            (idx, path) = path.split('/', 1)
            root = root[int(idx)]
        if not os.path.isdir(root):
            root = os.path.dirname(root)
        return os.path.join(root, path)

    def handle_image(self, filename, ctype):
        try:
            data = file(filename, 'rb').read()
        except IOError:
            self.send_error(404, 'File not found: %s' % self.path)
        else:
            self.send_response(200)
            self.send_header("Content-Type", ctype)
            self.send_header("Content-Length", str(len(data)))
            self.end_headers()
            return data

    def handle_rest_file(self, filename):
        try:
            f = open(filename)
            global last_atime
            last_atime = time.time()
            try:
                return self.handle_rest_data(f.read())
            finally:
                f.close()
        except IOError as e:
            self.log_error('%s', e)
            self.send_error(404, 'File not found: %s' % self.path)

    def handle_command(self, command):
        try:
            f = os.popen(command)
            try:
                return self.handle_rest_data(f.read())
            finally:
                f.close()
        except OSError as e:
            self.log_error('%s' % e)
            self.send_error(500, 'Command execution failed')

    def handle_rest_data(self, data):
        html = self.server.renderer.rest_to_html(data)
        if isinstance(html, unicode):
            html = html.encode('UTF-8')
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=UTF-8")
        self.send_header("Content-Length", str(len(html)))
        self.send_header("Cache-Control", "no-cache, no-store, max-age=0")
        self.end_headers()
        return html

    def collect_files(self, dirname):
        if not dirname.endswith('/'):
            dirname += '/'
        files = []
        for (dirpath, dirnames, filenames) in os.walk(dirname):
            dirnames[:] = [dn for dn in dirnames
                           if not dn.startswith('.')
                           and not dn.endswith('.egg-info')]
            for fn in filenames:
                if fn.endswith('.txt') or fn.endswith('.rst'):
                    prefix = dirpath[len(dirname):]
                    files.append(os.path.join(prefix, fn))
        files.sort(key=str.lower)
        return files

    def handle_dir(self, dirname):
        files = [(fn, fn) for fn in self.collect_files(dirname)]
        html = self.render_dir_listing('RST files in %s' % os.path.abspath(dirname), files)
        if isinstance(html, unicode):
            html = html.encode('UTF-8')
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=UTF-8")
        self.send_header("Content-Length", str(len(html)))
        self.end_headers()
        return html

    def handle_list(self, list_of_files_or_dirs):
        files = []
        for (idx, fn) in enumerate(list_of_files_or_dirs):
            if os.path.isdir(fn):
                files.extend([(os.path.join(str(idx), f),
                               os.path.join(fn, f))
                               for f in self.collect_files(fn)])
            else:
                files.append((os.path.join(str(idx), os.path.basename(fn)),
                              fn))
        html = self.render_dir_listing('RST files', files)
        if isinstance(html, unicode):
            html = html.encode('UTF-8')
        self.send_response(200)
        self.send_header("Content-Type", "text/html; charset=UTF-8")
        self.send_header("Content-Length", str(len(html)))
        self.end_headers()
        return html

    def render_dir_listing(self, title, files):
        files = ''.join([FILE_TEMPLATE.replace('$href', cgi.escape(href))
                                      .replace('$file', cgi.escape(fn))
                         for (href, fn) in files])
        return (DIR_TEMPLATE.replace('$title', cgi.escape(title))
                            .replace('$files', files))


DIR_TEMPLATE = """\
<!DOCTYPE html>
<html>
<head><title>$title</title></head>
<body>
<h1>$title</h1>
<ul>
$files</ul>
</body>
</html>
"""

FILE_TEMPLATE = """\
  <li><a href="$href">$file</a></li>
"""

AJAX_STR = """
<script type="text/javascript">
var xmlHttp = null;
window.onload = function () {
    setTimeout(function () {
        if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == '200') {
                window.location.reload(true);
            }
        }
        xmlHttp.open('HEAD', '/polling?pathname=' + location.pathname, true);
        xmlHttp.send(null);
    }, 0);
}
window.onbeforeunload = function () {
    xmlHttp.abort();
}
</script>
"""

ERROR_TEMPLATE = """\
<!DOCTYPE html>
<html>
<head><title>$title</title></head>
<style type="text/css">
pre.error {
    border-left: 3px double red;
    margin-left: 19px;
    padding-left: 19px;
    padding-top: 10px;
    padding-bottom: 10px;
    color: red;
}
</style>
<body>
<h1>$title</h1>
<pre class="error">
$error
</pre>
<pre>
$source
</pre>
</body>
</html>
"""


class ThreadingHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
    daemon_threads = True

    # tone down exception messages in the console
    def handle_error(self, request, client_address):
        print 'Exception detected during processing of request from',
        print client_address


class RestViewer(object):
    """Web server that renders ReStructuredText on the fly."""

    server_class = ThreadingHTTPServer
    handler_class = MyRequestHandler

    local_address = ('localhost', 0)

    # only set one of those
    css_url = None
    css_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                            'default.css')

    def __init__(self, root, command=None):
        self.root = root
        self.command = command

    def listen(self):
        """Start listening on a TCP port.

        Returns the port number.
        """
        self.server = self.server_class(self.local_address, self.handler_class)
        self.server.renderer = self
        return self.server.socket.getsockname()[1]

    def serve(self):
        """Wait for HTTP requests and serve them.

        This function does not return.
        """
        self.server.serve_forever()

    def rest_to_html(self, rest_input):
        """Render ReStructuredText."""
        writer = html4css1.Writer()
        if pygments is not None:
            writer.translator_class = SyntaxHighlightingHTMLTranslator
        if self.css_url:
            settings_overrides = {'stylesheet': self.css_url,
                                  'stylesheet_path': None,
                                  'embed_stylesheet': False}
        elif self.css_path:
            settings_overrides = {'stylesheet': self.css_path,
                                  'stylesheet_path': None,
                                  'embed_stylesheet': True}
        else:
            settings_overrides = {}
        try:
            core.publish_string(rest_input, writer=writer,
                                settings_overrides=settings_overrides)
        except Exception as e:
            return self.render_exception(e.__class__.__name__, str(e),
                                         rest_input)
        return self.return_markup(writer.output)

    def render_exception(self, title, error, source):
        html = (ERROR_TEMPLATE.replace('$title', cgi.escape(title))
                              .replace('$error', cgi.escape(error))
                              .replace('$source', cgi.escape(source)))
        return self.return_markup(html)

    def return_markup(self, markup):
        if self.command is None:
            return markup.replace('</body>', AJAX_STR + '</body>')
        else:
            return markup.replace('</title>', cgi.escape(self.command) + '</title>')


class SyntaxHighlightingHTMLTranslator(html4css1.HTMLTranslator):

    in_doctest = False
    in_text = False
    in_reference = False
    formatter_styles = formatters.HtmlFormatter(style='trac').get_style_defs('pre')

    def __init__(self, document):
        html4css1.HTMLTranslator.__init__(self, document)
        self.body_prefix[:0] = ['<style type="text/css">\n', self.formatter_styles, '\n</style>\n']

    def visit_doctest_block(self, node):
        html4css1.HTMLTranslator.visit_doctest_block(self, node)
        self.in_doctest = True

    def depart_doctest_block(self, node):
        html4css1.HTMLTranslator.depart_doctest_block(self, node)
        self.in_doctest = False

    def visit_Text(self, node):
        if self.in_doctest:
            text = node.astext()
            lexer = lexers.PythonConsoleLexer()
            formatter = formatters.HtmlFormatter(nowrap=True)
            self.body.append(pygments.highlight(text, lexer, formatter))
        else:
            text = node.astext()
            self.in_text = True
            encoded = self.encode(text)
            self.in_text = False
            if self.in_mailto and self.settings.cloak_email_addresses:
                encoded = self.cloak_email(encoded)
            self.body.append(encoded)

    def visit_literal(self, node):
        self.in_text = True
        html4css1.HTMLTranslator.visit_literal(self, node)
        self.in_text = False

    def visit_reference(self, node):
        self.in_reference = True
        html4css1.HTMLTranslator.visit_reference(self, node)

    def depart_reference(self, node):
        html4css1.HTMLTranslator.depart_reference(self, node)
        self.in_reference = False

    def encode(self, text):
        encoded = html4css1.HTMLTranslator.encode(self, text)
        if self.in_text and not self.in_reference:
            encoded = self.link_local_files(encoded)
        return encoded

    @staticmethod
    def link_local_files(text):
        """Replace filenames with hyperlinks.

            >>> link_local_files = SyntaxHighlightingHTMLTranslator.link_local_files
            >>> link_local_files('e.g. see README.txt for more info')
            'e.g. see <a href="README.txt">README.txt</a> for more info'

        """
        # jwz was right...
        text = re.sub("([-_a-zA-Z0-9]+[.]txt)", r'<a href="\1">\1</a>', text)
        return text


def parse_address(addr):
    """Parse a socket address.

        >>> parse_address('1234')
        ('localhost', 1234)

        >>> parse_address('example.com:1234')
        ('example.com', 1234)

        >>> parse_address('*:1234')
        ('', 1234)

        >>> try: parse_address('notanumber')
        ... except ValueError as e: print(e)
        Invalid address: notanumber

        >>> try: parse_address('la:la:la')
        ... except ValueError as e: print(e)
        Invalid address: la:la:la

    """
    if ':' in addr:
        try:
            (host, port) = addr.split(':')
        except ValueError:
            raise ValueError('Invalid address: %s' % addr)
    else:
        (host, port) = ('localhost', addr)
    if host == '*':
        host = '' # any
    try:
        return (host, int(port))
    except ValueError:
        raise ValueError('Invalid address: %s' % addr)


def get_host_name(listen_on):
    """Convert a listening interface name to a host name.

    The important part is to convert 0.0.0.0 to the system hostname, everything
    else can be left as is.
    """
    try:
        ip_addr = socket.inet_aton(listen_on)
    except socket.error: # probably a hostname or ''
        ip_addr = None
    if listen_on == '' or ip_addr == '\0\0\0\0':
        return socket.gethostname()
    else:
        return listen_on


def main():
    progname = os.path.basename(sys.argv[0])
    parser = optparse.OptionParser("%prog [options] filename-or-directory [...]",
                    description="Serve ReStructuredText files over HTTP.",
                    prog=progname)
    parser.add_option('-l', '--listen',
                      help='listen on a given port (or interface:port,'
                           ' e.g. *:8080) [default: random port on localhost]',
                      default=None)
    parser.add_option('-b', '--browser',
                      help='open a web browser [default: only if -l'
                           ' was not specified]',
                      action='store_true', default=None)
    parser.add_option('-e', '--execute',
                      help='run a command to produce ReStructuredText',
                      default=None)
    parser.add_option('--long-description',
                      help='run "python setup.py --long-description" to produce ReStructuredText',
                      action='store_const', dest='execute',
                      const='python setup.py --long-description')
    parser.add_option('--css',
                      help='use the specified stylesheet',
                      action='store', dest='css_path', default=None)
    (opts, args) = parser.parse_args(sys.argv[1:])
    if not args and not opts.execute:
        parser.error("at least one argument expected")
    if args and opts.execute:
        parser.error("specify a command (-e) or a file/directory, but not both")
    if opts.browser is None:
        opts.browser = opts.listen is None
    if opts.execute:
        server = RestViewer('.', command=opts.execute)
    elif len(args) == 1:
        server = RestViewer(args[0])
    else:
        server = RestViewer(args)
    if opts.css_path:
        if (opts.css_path.startswith('http://') or
            opts.css_path.startswith('https://')):
            server.css_url = opts.css_path
            server.css_path = None
        else:
            server.css_path = opts.css_path
            server.css_url = None
    if opts.listen:
        try:
            server.local_address = parse_address(opts.listen)
        except ValueError as e:
            sys.exit(str(e))
    host = get_host_name(server.local_address[0])
    port = server.listen()
    url = 'http://%s:%d/' % (host, port)
    print("Listening on %s" % url)
    if opts.browser:
        # launch the web browser in the background as it may block
        t = threading.Thread(target=webbrowser.open, args=(url, ))
        t.setDaemon(True)
        t.start()
    try:
        server.serve()
    except KeyboardInterrupt:
        pass


if __name__ == '__main__':
    main()