Mango / main.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
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
# -*- coding: utf-8 -*-

from __future__ import with_statement
from functools import partial
import math
import os
import re

try:
    from itertools import zip_longest as izip_longest
except ImportError:
    from itertools import izip_longest

import lxml.html
from markdown import Markdown

from django.core import urlresolvers
from django.core.cache import cache
from django.template import Context, loader
from django.utils.encoding import smart_unicode
from django.utils.safestring import mark_safe

import mango.settings
from mango.template import Script, StyleSheet
from mango.template.embed import embed
from mango.templatetags.mango import convert_html_chars
from mango.utils import (logger, nonstringiterable, normalizelinebreaks,
                         parsedocdate, replace, slugify, validfilenames)


_alias_canon_match = re.compile(r'^(0*(?P<alias>.*?)=)?(?P<canon>.+)$').match

class Resource(object):
    def __init__(self, path):
        super(Resource, self).__init__()
        canon_fragments, short_fragments = [], []
        head, tail = os.path.split(path)
        while tail:
            match = _alias_canon_match(tail)
            if match:
                canon = match.group('canon')
                if not canon_fragments and not os.path.isdir(path):
                    canon = os.path.splitext(canon)[0]  # strip extension
                canon_fragments.insert(0, canon)
                short_fragments.insert(0, match.group('alias') or canon)
            head, tail = os.path.split(head)
        mount_point = urlresolvers.reverse('mango.views.index')
        repl = (mango.settings.UNIX_DOCUMENTS_PATH, u'', 1)
        canon_path = u'%s%s/' % (mount_point, '/'.join(canon_fragments))
        canon_path = canon_path.replace(*repl).lower()
        short_path = u'%s%s/' % (mount_point, '/'.join(short_fragments))
        short_path = short_path.replace(*repl).lower()
        self.urls = {
            'canon': {
                'rel': canon_path,
                'abs': u'%s%s' % (mango.settings.BASE_URL, canon_path[1:]),
            },
            'short': {
                'rel': short_path,
                'abs': u'%s%s' % (mango.settings.SHORT_URL_BASE or
                                  mango.settings.BASE_URL, short_path[1:]),
            },
        }

        aliases = [u'']
        fragments = zip(canon_path.split(u'/')[1:], short_path.split(u'/')[1:])
        for canon_fragment, short_fragment in fragments:
            # append the canonical fragment to each alias
            updated = [u'/'.join([alias, canon_fragment]) for alias in aliases]
            if short_fragment != canon_fragment:
                # branch each alias and append the short fragment
                # to the new branches
                updated += [u'/'.join([alias, short_fragment])
                            for alias in aliases]
            aliases = updated
        self._aliases = aliases
        self._slug = canon_fragments[-1]
        self._references = {}

    def identifier(self):
        return self.urls['canon']['rel']

    def permalink(self):
        return self.urls['canon']['abs']

    def shorturl(self):
        return self.urls['short']['abs']

    def has_shorturl(self):
        return self.shorturl() != self.permalink()

    def required_files(self):
        urlpaths = []
        for key in self.meta.get('require', []):
            try:
                items = mango.settings.STATIC_FILES[key]
            except KeyError:
                logger.warning('STATIC_FILES does not contain the key "%s"'
                               % key)
            else:
                for urlpath in nonstringiterable(items):
                    urlpaths.append(urlpath)
        return urlpaths

    def scripts(self):
        return [Script(path) for path in self.required_files()
                if path.endswith('.js')]

    def stylesheets(self):
        return [StyleSheet(path) for path in self.required_files()
                if path.endswith('.css')]

    def _setreferences(self, references):
        self._references = references.copy()
    references = property(lambda self: self._references.copy(), _setreferences)

    _subhandcraftedexcerpt = re.compile(
        r'''^
        (?:                                 # optional metadata
          [ ]{,3}[-\w]+:.*\n                # "key: value" pair
          (?:[ ]{4,}.*\n)*                  # value may wrap
        )*
        (?P<excerpt>                        # arbitrary excerpt
          (?:
            (?![ ]{,3}(?:\*[ ]?){3,}\s*\n)  # section delimiters not allowed
            [^\n]*\n
          )+?
        )
        (?= \#(?!\#) | .+\n={3,} )          # followed by an h1 of either type
        ''', re.VERBOSE).sub

    def _pluckhandcraftedexcerpt(self):
        def repl(match):
            excerpt = match.group('excerpt')
            self._excerpt = self._convert(excerpt) + '\n'
            return ''
        return self._subhandcraftedexcerpt(repl, self.source)

    def _plucktitle():
        subcodetags = re.compile(r'<code>(.*?)</code>').sub
        matchheading = re.compile(r'\s*<h1[^>]*>(?P<title>.+?)</h1>$'
                                  r'(?P<html>[\s\S]*)', re.MULTILINE).match
        def plucktitle(self):
            self.title_text = self.meta.get('title', u'')
            self.title = convert_html_chars(self.title_text)

            if not self.title_text:
                match = matchheading(self.html)
                if match:
                    self.html = match.group('html')
                    self.title = match.group('title')
                    self.title_text = subcodetags(r'`\1`', self.title)
                    self.title_text = lxml.html.fromstring(self.title_text)
                    # convert `lxml.etree._ElementUnicodeResult` to `unicode`
                    # for pickling
                    self.title_text = unicode(self.title_text.text_content())
            self.title = mark_safe(self.title)
        return plucktitle
    _plucktitle = _plucktitle()


def processmetalists(meta):
    for key, value in meta.items():
        if len(value) != 1:  # note: `value` is always a list
            meta[key] = value
        elif key in mango.settings.META_LISTS:
            meta[key] = [item.strip() for item in value[0].split(',')]
        else:
            meta[key] = value[0].strip()
    return meta

class Category(Resource):
    def __init__(self, dirpath, use_cache=True):
        super(Category, self).__init__(path=dirpath)
        self._dirpath = dirpath
        match = _alias_canon_match(os.path.basename(dirpath))
        self.name = match.group('canon')
        self._pages = []
        self._posts = []
        self.subcategories = []

        try:
            with open(os.path.join(dirpath, '_index')) as f:
                self.source = smart_unicode(f.read())
        except IOError:
            self.html = self.source = None
            self.meta = {}
        else:
            md.reset()
            self.html = md.convert(self.source)
            self.meta = processmetalists(getattr(md, 'Meta', {}))
            self._plucktitle()
            if self.title:
                self.name = self.title

        for name in validfilenames(os.listdir(dirpath)):
            path = os.path.join(dirpath, name)
            if os.path.isdir(path):
                self.subcategories.append(Category(path))
            else:
                self.add_document(path, use_cache)

        self.subcategories.sort(key=lambda category: category.name)
        self._pages.sort(key=lambda page: page.title_text)

    def add_document(self, filepath, use_cache=True):
        if use_cache:
            document = Document.get(filepath)
        else:
            document = Document(filepath)

        if document.type == 'page':
            self._pages.append(document)
        else:
            length = len(self._posts)
            for index, post in enumerate(self._posts):
                if document.datetime < post.datetime:
                    break
            else:
                index = length

            prev_index = index - 1
            next_index = index

            if 0 <= prev_index < length:
                self._posts[prev_index].next = document
                document.previous = self._posts[prev_index]

            if 0 <= next_index < length:
                self._posts[next_index].previous = document
                document.next = self._posts[next_index]

            self._posts.insert(index, document)

        return self

    def _descendants(self, include_pages):
        posts = self._posts[:]
        pages = self._pages[:] if include_pages else []

        for subcategory in self.subcategories:
            posts_, pages_ = subcategory._descendants(include_pages)
            posts.extend(posts_)
            pages.extend(pages_)

        return posts, pages

    def descendants(self, include_pages=False):
        posts, pages = self._descendants(include_pages)
        posts.sort(key=lambda post: post.datetime, reverse=True)
        pages.sort(key=lambda page: page.title_text)
        return posts + pages

    def archives(self):
        archives = []
        posts = self.descendants()
        if posts:
            year = posts[0].datetime.year
            month = posts[0].datetime.month
            these_posts = []
            for post in posts:
                if post.datetime.year == year and post.datetime.month == month:
                    these_posts.append(post)
                else:
                    archives.append((year, month, these_posts))
                    year, month = post.datetime.year, post.datetime.month
                    these_posts = [post]
            archives.append((year, month, these_posts))
        return archives

    def find_match(self, urlpath):
        if urlpath in self._aliases:
            return self
        for document in self._pages + self._posts:
            if urlpath in document._aliases:
                return document
        for subcategory in self.subcategories:
            match = subcategory.find_match(urlpath)
            if match:
                return match

    def _documents_in_index_order(self, documents, kind):
        if kind not in self.meta:
            return documents

        docs = []
        for slug in self.meta[kind]:
            for document in documents:
                if document._slug == slug:
                    docs.append(document)
                    break
        return docs

    def pages(self):
        return self._documents_in_index_order(self._pages, 'page')

    def posts(self):
        return self._documents_in_index_order(self._posts, 'post')

    def _tags(self):
        tags = []
        for document in self._pages + self._posts:
            if document.tags():
                tags += document.tags(alphabetical=False)  # no need to sort
        for subcategory in self.subcategories:
            tags += subcategory._tags()
        return tags

    def tags(self):
        tags = {}
        for tag in self._tags():
            try:
                tag, count = tags[tag.name]
            except KeyError:
                tags[tag.name] = (tag, 1)
            else:
                tags[tag.name] = (tag, count + 1)
        keys = tags.keys()
        keys.sort(key=lambda key: key.lower())
        return [tags[key] for key in keys]

    def uncache(self):
        for document in self.descendants(include_pages=True):
            document.uncache()
        return self

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name


class Index(Category):
    @staticmethod
    def cache_key():
        return 'mango:toplevel:%s' % mango.settings.BASE_URL

    @classmethod
    def get(cls):
        if mango.settings.INDEX_CACHE_SECONDS == 0:
            return Index(use_cache=True)

        cache_key = Index.cache_key()
        index = cache.get(cache_key)

        if index is not None:
            logger.debug('Document tree retrieved from cache')
            return index

        index = Index(use_cache=True)
        cache.set(cache_key, index, mango.settings.INDEX_CACHE_SECONDS)
        logger.debug('Document tree created and cached')
        mango.sitemaps.ping_google()
        return index

    def __init__(self, use_cache=False):
        super(Index, self).__init__(dirpath=mango.settings.DOCUMENTS_PATH,
                                    use_cache=use_cache)

    def uncache(self, uncache_documents=False):
        cache.delete(Index.cache_key())
        logger.debug('Document tree purged from cache')
        if uncache_documents:
            super(Index, self).uncache()
        return self


stripskips = partial(re.compile(r'</?skip>').sub, '')

md = Markdown(extensions=('meta',) + mango.settings.MARKDOWN_EXTENSIONS)
_renderupdate = loader.get_template('update.html').render

def pairer(pattern):
    fn = re.compile(pattern, re.MULTILINE).split
    def grouper(*args, **kwargs):
        return izip_longest(fillvalue='', *([iter(fn(*args, **kwargs))] * 2))
    return grouper

itersections = pairer(r'([\s\S]+?)'.join([r'^[ ]{,3}(?:\*[ ]?){3,}\s*?\n'] * 2))

matchupdate = re.compile(
    r'''^(?:\s*\n)?                    # zero or more empty lines
    (?P<list>(\*\s+)|(\d+\.\s+)|\s*)?  # optionally include a list or indent
    (?P<level>\#{1,6})[ \t]*           # one or more number signs
    update\b                           # "update" (case insensitive)
    (?P<metadata>[^\n]+)\n+            # date, time, and time zone
    (?P<body>.+)$                      # the update's body
    ''',
    re.DOTALL | re.IGNORECASE | re.VERBOSE).match

_finddate = re.compile(r'\b(?:[1-9]|[12]\d|3[01]) [a-zA-Z]+ \d{4}\b').search
_findtime = re.compile(r'\b(?:[1-9]|1[0-2]):\d\d[ap]m\b').search
_findzone = re.compile(r'\b[a-zA-Z_]+(?:/[a-zA-Z_-]+){1,2}\b').search

def renderupdate(resource, match):
    metadata = match.group('metadata')

    date = _finddate(metadata)
    time = _findtime(metadata)
    zone = _findzone(metadata)

    if not date or not time or not zone:
        return

    date, time, zone = date.group(0), time.group(0), zone.group(0)

    for text in (date, time, zone):
        metadata = metadata.replace(text, '', 1)

    # Leftover commas, dashes, parentheses, etc. are fine. Bail
    # in the unlikely event that -- having stripped date, time,
    # and zone -- `metadata` contains "significant" characters.
    if re.search(r'\w', metadata):
        return

    update = Update()
    try:
        update.datetime = parsedocdate(date, time, zone)
    except ValueError:
        logger.exception('Update date/time/zone incorrectly formatted')
        return

    update.headinglevel = len(match.group('level'))
    update.html = mark_safe(resource._convert(match.group('body')))

    return _renderupdate(Context({'update': update}))

class Document(Resource):
    @classmethod
    def get(cls, filepath):
        if mango.settings.POST_CACHE_SECONDS == 0:
            return Document(filepath)

        cache_key = 'mango:%s' % filepath
        lastmod = os.path.getmtime(filepath)
        document = cache.get(cache_key)

        if isinstance(document, Document) and document.lastmod == lastmod:
            logger.debug('Document object retrieved from cache: %s' % filepath)
        else:
            document = Document(filepath)
            document.lastmod = lastmod
            cache.set(cache_key, document, mango.settings.POST_CACHE_SECONDS)
            logger.debug('Document object created and cached: %s' % filepath)

        return document

    def __init__(self, filepath=None):
        self.source = None
        if filepath is not None:
            super(Document, self).__init__(path=filepath)
            with open(filepath) as f:
                self.source = smart_unicode(f.read())

        self._filepath = filepath
        self._tags = None
        self._thread_id = None

        self.lastmod = None
        self.previous = None
        self.next = None

        self.convert()

    def _convert():
        sub = re.compile(r'^[ ]{,3}(?:\*[ ]?){3,}[ \t]*$', re.MULTILINE).sub
        def warn(match):
            logger.warning('Horizontal rules comprised of '
                           'asterisks delimit excerpts/updates '
                           '(use hyphens or underscores instead)')
            return ''
        def render(self, text):
            md.reset()
            md.references = self.references
            return md.convert(sub(warn, text))
        return render
    _convert = _convert()

    def convert(self, source=None):
        if source is not None:
            self.source = source

        if self.source is None:
            return self

        self.source = normalizelinebreaks(self.source) + '\n'

        md.reset()
        # discern link definitions
        md.convert(self.source)
        self.references = md.references

        self.meta = processmetalists(getattr(md, 'Meta', {}))

        self.html = self._excerpt = ''

        source = self._pluckhandcraftedexcerpt()

        updates = []
        interspersed = ""
        MANGO_PLACEHOLDER = "MangoUpdatePlaceholderxxz"

        for nonsection, section in itersections(source):
            interspersed += nonsection
            
            match = matchupdate(section)
            if match:
                update = renderupdate(self, match)
                if update:
                    interspersed += match.group('list') or ''
                    interspersed += MANGO_PLACEHOLDER + '\n'
                    updates.append(update)
                    continue
                else:
                    logger.warning(
                      'Section looking like an update failed to render, may be due to '
                      'insufficient/incorrect metadata or an excerpt starting with '
                      'the word "Update". Section=%s'
                      %section)

            if section:
                interspersed += section
                self._excerpt += self._convert(section) + '\n'

        self.html += self._convert(interspersed)

        # We will only sometimes have it wrapped in <p> tags, rely on the <div> for formatting
        self.html = self.html.replace('<p>' + MANGO_PLACEHOLDER + '</p>', MANGO_PLACEHOLDER)
        for s in updates:
            self.html = self.html.replace(MANGO_PLACEHOLDER, s, 1)

        self._excerpt = mark_safe(replace(self._excerpt.rstrip('\n')))

        if 'tags' in mango.settings.META_LISTS and 'tags' in self.meta:
            self._tags = [Tag(tag) for tag in self.meta['tags']]

        author_name = self.meta.get('author')
        if author_name:
            self.author = {
                'name': author_name,
                'url': mango.settings.AUTHORS.get(author_name),
            }

        self.datetime = None
        if all(key in self.meta for key in ('date', 'time', 'zone')):
            try:
                self.datetime = parsedocdate(self.meta['date'],
                                             self.meta['time'],
                                             self.meta['zone'])
            except ValueError:
                logger.exception('Document date/time/zone '
                                 'incorrectly formatted')

        self._plucktitle()
        self.html = embed(self.html.rstrip())
        self.html = mark_safe(stripskips(replace(self.html.lstrip('\n'))))
        self.type = self.meta.get('type', 'post' if self.datetime else 'page')

        return self

    def _thread(self):
        if self.type == 'page':
            return

        # Import the module now that we know that commenting is enabled.
        from mango import disqus

        thread = None
        cache_key = disqus.thread.cache_key
        identifier = self.identifier()
        title = self.title_text

        if self._thread_id is None:
            try:
                self._thread_id = disqus.thread.id_from_identifier(identifier)
            except disqus.APIError, error:
                logger.warning('Disqus API error: %s' % error)
                return

        if self._thread_id is not None:
            thread = cache.get(cache_key(self._thread_id))
            if thread is not None:
                logger.debug('Disqus thread for "%s" retrieved from cache'
                             % title)
                return thread

            try:
                thread = disqus.thread.fetch(self._thread_id)
            except disqus.APIError, error:
                logger.warning('Disqus API error: %s' % error)
                return

        if thread is None:
            thread = disqus.thread.create(title=title, slug=self.safe_slug(),
                                          identifier=identifier)
            logger.debug('Disqus thread for "%s" created' % title)
            # Threads created via the Disqus API are
            # not necessarily immediately available.
            if thread is None:
                return

        # In theory, threads could be cached indefinitely since cache keys
        # are invalidated when required in response to comment moderation.
        cache.set(cache_key(thread.id), thread, 24 * 60 * 60)
        logger.debug('Disqus thread for "%s" cached' % title)
        self._thread_id = thread.id
        return thread

    def comments(self):
        if mango.settings.DISQUS:
            thread = self._thread()
            if thread is not None:
                return thread.posts
        return []

    def excerpt(self):
        return self._excerpt or self.html

    def has_tag(self, tag):
        return tag in self.meta.get('tags', [])

    def related(self, documents=None):
        if documents is None:
            documents = Index.get().descendants()

        cache_key = None
        if self._filepath:
            cache_key = 'mango:%s:related' % self._filepath
            related = cache.get(cache_key)
            if related is not None:
                return related

        related = []
        set1 = set(self.tags(alphabetical=False) or [])

        for document in documents:
            if document == self:
                continue

            set2 = set(document.tags(alphabetical=False) or [])
            similarity = len(set1 & set2) / math.sqrt(len(set1 | set2))
            if (similarity >= 0.5):
                related.append((similarity, document))

        related.sort(reverse=True)
        related = [document for similarity, document in related]
        if cache_key:
            cache.set(cache_key, related, 15 * 60)
        return related

    def safe_slug(self):
        return re.sub(r'\W', '-', self._slug)

    def tags(self, alphabetical=True):
        return (sorted(self._tags, key=lambda tag: tag.name.lower())
                if alphabetical and self._tags else self._tags)

    def uncache(self):
        if self._filepath:
            cache.delete('mango:%s' % self._filepath)
            logger.debug('Document object purged from cache: %s'
                         % self._filepath)
        return self

    def __eq__(self, other):
        return self._filepath and self._filepath == other._filepath

    def __ne__(self, other):
        return not self.__eq__(other)

    def __str__(self):
        return self.__unicode__().encode('utf-8')

    def __unicode__(self):
        return getattr(self, 'title', 'Untitled Document')


class Update(object):
    pass


class Tag(object):
    def __init__(self, name):
        self.name = name
        self.slug = slugify(name)

    def __eq__(self, other):
        return self.name == other.name

    def __ne__(self, other):
        return not self.__eq__(other)

    def __hash__(self):
        return hash(self.name)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name
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.