summaryrefslogtreecommitdiff
path: root/app/pages/models.py
blob: 3ef1a717c2bfc22b323d93c60bc31683db8dc9b9 (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
from django.db import models
from django.contrib.sitemaps import Sitemap
import markdown


import os
import yaml
from django.conf import settings
from django.template.loader import render_to_string
from django.template import Context
from mdx_attr_list.mdx_attr_list import AttrListExtension


def markdown_processor(txt):
    md = markdown.Markdown(
        extensions=[AttrListExtension(),'footnotes',],
        output_format='html5',
        safe_mode=False
    )
    return md.convert(txt)
'''
class Page(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField()
    body_html = models.TextField(blank=True)
    body_markdown = models.TextField()
    meta_description = models.CharField(max_length=256, null=True, blank=True)

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return "/%s/" % (self.slug)

    def save(self):
        #run markdown
        self.body_html = markdown_processor(self.body_markdown)
        super(Page, self).save()
'''

class PageSitemap(Sitemap):
    changefreq = "never"
    priority = 1.0
    protocol = "https"

    def items(self):
        p = PageGenerator(settings.PROJ_ROOT + '_pages')
        return p.objects(include_in_sitemap=True)
        #return Page.objects.all()


class PageGenerator(object):

    def __init__(self, path, *args, **kwargs):
        self._objects = []
        for (dirpath, dirnames, filenames) in os.walk(path):
            self.dirpath = dirpath
            self.file_list = filter(lambda item: not (item.startswith('.') or item.endswith('~') or item.endswith('.md')), filenames)
            self.get_files()

    def get_files(self):
        for f in self.file_list:
            p = Page(self.dirpath + '/' + f)
            self._objects.append(p)

    def objects(self, *args, **kwargs):
        filtered_list = []
        if kwargs:
            for item in self._objects:
                found = False
                for k, v in kwargs.items():
                    if getattr(item, k) == v and not found:
                        found = True
                        filtered_list.append(item)
                    elif getattr(item, k) != v and found:
                        filtered_list.remove(item)
            return filtered_list
        return self._objects

    def write_files(self):
        for obj in self.objects():
            c = Context({'object': obj, 'SITE_URL': settings.SITE_URL})
            t = render_to_string(["details/%s.html" % obj.template], c)
            s = render_to_string('details/page.txt', c)
            _FileWriter('', t, ext="html", filename=obj.slug)
            _FileWriter('', s, ext="txt", filename=obj.slug)


class _FileWriter(object):
    """
    Given a path and text object; write the page to disc
    """
    def __init__(self, path, text_object, ext='html', filename='index'):
        self.path = '%s%s' % (settings.FLATFILES_ROOT, path)
        if not os.path.isdir(self.path):
            os.makedirs(self.path)
        fpath = '%s%s.%s' % (self.path, filename, ext)
        self.write(fpath, text_object)

    def write(self, fpath, text_object):
        file = open(fpath, 'wb')
        file.write(text_object.encode('utf-8'))
        file.close()


class _FileLoader(object):

    def __init__(self, filename, *args, **kwargs):
        self.filename = filename
        metadata = self.read()
        for k, v in metadata.items():
            setattr(self, k, v)
        if self.body_markdown:
            self.body_html = markdown_processor(self.body_markdown)

    def read(self):
        with open(self.filename, "r", encoding="utf-8") as f:
            contents = f.read()
        metayaml, self.body_markdown = contents.split('\n---')
        return yaml.load(metayaml)

class Page(_FileLoader):
    pass