summaryrefslogtreecommitdiff
path: root/megapixels/app/site/parser.py
blob: ca6ac77b701f91dadf875c9096c4904de6274e63 (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
236
237
import os
import re
import glob
import simplejson as json
import mistune

import app.settings.app_cfg as cfg
import app.site.s3 as s3

renderer = mistune.Renderer(escape=False)
markdown = mistune.Markdown(renderer=renderer)

def fix_images(lines, s3_path):
  """
  do our own tranformation of the markdown around images to handle wide images etc
  lines: markdown lines
  """
  real_lines = []
  block = "\n\n".join(lines)
  for line in block.split("\n"):
    if "![" in line:
      line = line.replace('![', '')
      alt_text, tail = line.split('](', 1)
      url, tail = tail.split(')', 1)
      if ':' in alt_text:
        tail, alt_text = alt_text.split(':', 1)
      img_tag = "<img src='{}' alt='{}'>".format(s3_path + url, alt_text.replace("'", ""))
      if len(alt_text):
        line = "<div class='image'>{}<div class='caption'>{}</div></div>".format(img_tag, alt_text)
      else:
        line = "<div class='image'>{}</div>".format(img_tag, alt_text)
    real_lines.append(line)
  return "\n".join(real_lines)

def format_section(lines, s3_path, type=''):
  """
  format a normal markdown section
  """
  if len(lines):
    lines = fix_images(lines, s3_path)
    if type:
      return "<section class='{}'>{}</section>".format(type, markdown(lines))
    else:
      return "<section>" + markdown(lines) + "</section>"
  return ""

def format_metadata(section):
  """
  format a metadata section (+ key: value pairs)
  """
  meta = []
  for line in section.split('\n'):
    key, value = line[2:].split(': ', 1)
    meta.append("<div><div class='gray'>{}</div><div>{}</div></div>".format(key, value))
  return "<section><div class='meta'>{}</div></section>".format(''.join(meta)) 

def format_applet(section, s3_path):
  # print(section)
  payload = section.strip('```').strip().strip('```').strip().split('\n')
  applet = {}
  print(payload)
  if ': ' in payload[0]:
    command, opt = payload[0].split(': ')
  else:
    command = payload[0]
    opt = None
  if command == 'python':
    return format_section([ section ], s3_path)

  applet['command'] = command
  if opt:
    applet['opt'] = opt
  if command == 'load file':
    if opt[0] != '/':
      applet['opt'] = s3_path + opt
    applet['fields'] = payload[1]
  return "<section><div class='applet' data-payload='{}'></div></section>".format(json.dumps(applet))

def parse_markdown(sections, s3_path, skip_h1=False):
  """
  parse page into sections, preprocess the markdown to handle our modifications
  """
  groups = []
  current_group = []
  for section in sections:
    if skip_h1 and section.startswith('# '):
      continue
    elif section.startswith('```'):
      groups.append(format_section(current_group, s3_path))
      current_group = []
      current_group.append(section)
      if section.endswith('```'):
        groups.append(format_applet("\n\n".join(current_group), s3_path))
        current_group = []
    elif section.endswith('```'):
      current_group.append(section)
      groups.append(format_applet("\n\n".join(current_group), s3_path))
      current_group = []
    elif section.startswith('+ '):
      groups.append(format_section(current_group, s3_path))
      groups.append(format_metadata(section))
      current_group = []
    elif '![wide:' in section:
      groups.append(format_section(current_group, s3_path))
      groups.append(format_section([section], s3_path, type='wide'))
      current_group = []
    elif '![' in section:
      groups.append(format_section(current_group, s3_path))
      groups.append(format_section([section], s3_path, type='images'))
      current_group = []
    else:
      current_group.append(section)
  groups.append(format_section(current_group, s3_path))
  content = "".join(groups)
  return content

def parse_research_index(research_posts):
  """
  Generate an index file for the research pages
  """
  content = "<div class='research_index'>"
  for post in research_posts:
    s3_path = s3.make_s3_path(cfg.S3_SITE_PATH, post['path'])
    if 'image' in post:
      post_image = s3_path + post['image']
    else:
      post_image = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='
    row = "<a href='{}'><section class='wide'><img src='{}' alt='Research post' /><section><h1>{}</h1><h2>{}</h2></section></section></a>".format(
      post['path'],
      post_image,
      post['title'],
      post['tagline'])
    content += row
  content += '</div>'
  return content

def read_metadata(fn):
  """
  Read in read a markdown file and extract the metadata
  """
  with open(fn, "r") as file:
    data = file.read()
    data = data.replace("\n ", "\n")
    if "\n" in data:
      data = data.replace("\r", "")
    else:
      data = data.replace("\r", "\n")
    sections = data.split("\n\n")
  return parse_metadata(fn, sections)

default_metadata = {
  'status': 'published',
  'title': 'Untitled Page',
  'desc': '',
  'slug': '',
  'published': '2018-12-31',
  'updated': '2018-12-31',
  'authors': 'Adam Harvey',
  'sync': 'true',
  'tagline': '',
}

def parse_metadata_section(metadata, section):
  """
  parse a metadata key: value pair
  """
  for line in section.split("\n"):
    if ': ' not in line:
      continue
    key, value = line.split(': ', 1)
    metadata[key.lower()] = value

def parse_metadata(fn, sections):
  """
  parse the metadata headers in a markdown file
  (everything before the second ---------)
  also generates appropriate urls for this page :)
  """
  found_meta = False
  metadata = {}
  valid_sections = []
  for section in sections:
    if not found_meta and ': ' in section:
      found_meta = True
      parse_metadata_section(metadata, section)
      continue
    if '-----' in section:
      continue
    if found_meta:
      valid_sections.append(section)

  if 'title' not in metadata:
    print('warning: {} has no title'.format(fn))
  for key in default_metadata:
    if key not in metadata:
      metadata[key] = default_metadata[key]

  basedir = os.path.dirname(fn.replace(cfg.DIR_SITE_CONTENT, ''))
  basename = os.path.basename(fn)
  if basedir == '/':
    metadata['path'] = '/'
    metadata['url'] = '/'
  elif basename == 'index.md':
    metadata['path'] = basedir + '/'
    metadata['url'] = metadata['path']
  else:
    metadata['path'] = basedir + '/'
    metadata['url'] = metadata['path'] + basename.replace('.md', '') + '/'

  if metadata['status'] == 'published|draft|private':
    metadata['status'] = 'published'

  metadata['sync'] = metadata['sync'] != 'false'

  metadata['author_html'] = '<br>'.join(metadata['authors'].split(','))

  return metadata, valid_sections

def read_research_post_index():
  """
  Generate an index of the research (blog) posts
  """
  posts = []
  for fn in sorted(glob.glob('../site/content/research/*/index.md')):
    metadata, valid_sections = read_metadata(fn)
    if metadata is None or metadata['status'] == 'private' or metadata['status'] == 'draft':
      continue
    posts.append(metadata)
  if not len(posts):
    posts.append({
      'title': 'Placeholder',
      'slug': 'placeholder',
      'date': 'Placeholder',
      'url': '/',
    })
  return posts