-
Notifications
You must be signed in to change notification settings - Fork 8
/
make_markdown_files.py
executable file
·322 lines (271 loc) · 8.55 KB
/
make_markdown_files.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
#!/usr/bin/env python
import json
import glob
import os
import re
from datetime import datetime
import sqlite3
month_file_header = """\
---
layout: default
---
# {} {}
_Dates are calculated as the UTC date. The "raw date" from \
the email dump is included in brackets. The date may be inconsistent \
with the raw date because of the time difference with UTC time._
_Ordering by UTC time ensures true chronological ordering._
## Threads
"""
author_file_header = """\
---
layout: default
sender_id: {}
post_count: {}
---
# {} ({} {})
_Be aware that many list participants used multiple email addresses \
over their time active on the list. As such this page may not contain \
all threads available._
## Threads
"""
message_page_template = """\
---
layout: default
---
# {} - {}
## Header Data
From: {}<br>
To: {}<br>
Message Hash: {}<br>
Message ID: {}<br>
Reply To: {}<br>
UTC Datetime: {}<br>
Raw Date: {}<br>
## Raw message
```
{}
```
## Thread
{}
{}
"""
author_index_template = """\
---
layout: default
permalink: /authors/
---
# Authors by Number of Posts (Highest First)
_Be aware that many list participants used multiple email addresses over \
their time active on the list. As such an email address page may not contain \
all threads available for that person._
"""
month_name_map = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
]
def make_id_from_email(email):
email = email.replace('@', '_at_')
email = re.sub('[<>\(\)\.\s]+', '_', email)
email = re.sub('\W+', '', email)
return email.lower()
def escape_chevrons(text):
if text:
return text.encode('utf-8').replace('<', '\\<').replace('>', '\\>')
else:
return "_N/A_"
def make_back_to_links(thread):
def get_months(months, message):
if not message['date']:
return []
parsed_date = datetime.utcfromtimestamp(message['date'])
months.add((parsed_date.year, parsed_date.month))
for child in message['children']:
get_months(months, child)
return months
def get_authors(authors, message):
sender_id = make_id_from_email(message['from'])
authors.add((sender_id, message['from']))
for child in message['children']:
get_authors(authors, child)
return authors
months = get_months(set(), thread)
authors = get_authors(set(), thread)
link_text = ""
for year, month in sorted(months):
link_text += "+ Return to [{} {}](/archive/{}/{})\n".format(
month_name_map[month - 1],
year,
year,
str(month).zfill(2)
)
link_text += "\n"
for sender_id, email_from in sorted(authors):
link_text += "+ Return to \"[{}](/authors/{})\"\n".format(
email_from.encode('utf-8').replace('@', '<span>@</span>'),
sender_id
)
return link_text
def create_message_pages(thread, message=None):
if not message:
message = thread
if message['date']:
parsed_date = datetime.utcfromtimestamp(message['date'])
path = "emails_test/{}/".format(parsed_date.strftime('%Y/%m'))
iso_date = parsed_date.date().isoformat()
utc_formatted_date = parsed_date.strftime('%Y-%m-%d %H:%M:%S UTC')
raw_date = message["raw_date"].encode('utf-8')
else:
path = "emails_test/{}/unknown/".format(message['file_year'])
iso_date = "(Unknown Date)"
utc_formatted_date = "(Unknown Date)"
raw_date = "_N/A_"
if not os.path.exists(path):
os.makedirs(path)
thread_tree = make_markdown_thread_tree(thread, message["message_hash"])
with open("raw_messages/{}/{}.txt".format(
message['file_year'], message["message_hash"]
)) as f:
raw_message = "{% raw %}" + f.read() + "{% endraw %}"
with open("{}/{}.md".format(path, message["message_hash"]), "w") as o:
o.write(message_page_template.format(
iso_date,
message["subject"].encode('utf-8'),
escape_chevrons(message["from"]).replace('@', '<span>@</span>'),
escape_chevrons(message["to"]),
message["message_hash"],
escape_chevrons(message["message_id"]),
escape_chevrons(message["reply_to"]),
utc_formatted_date,
raw_date,
raw_message,
make_back_to_links(thread),
thread_tree
))
for child in message["children"]:
create_message_pages(thread, child)
def make_thread_list_item(message, offset, show_link=True):
def make_link(subject, formatted_date, message_hash):
return "[{}](/archive/{}/{})".format(
subject,
formatted_date,
message_hash
)
if message['date']:
parsed_date = datetime.utcfromtimestamp(message['date'])
path = parsed_date.strftime('%Y/%m')
iso_date = parsed_date.date().isoformat()
else:
path = str(message['file_year']) + "/unknown"
iso_date = "(Unknown Date)"
if show_link:
subject = make_link(
message['subject'].encode('utf-8'),
path,
message['message_hash']
)
else:
subject = message['subject'].encode('utf-8')
return "{}+ {} ({}) - {} - _{}_\n".format(
" " * offset,
iso_date,
message['raw_date'],
subject,
message['from'].encode('utf-8').replace('<', '\\<').replace('>', '\\>')
)
def make_markdown_thread_tree(message, message_hash=None, offset=0):
show_link = message_hash != message['message_hash']
if message['no_parent']:
text = "+ _Unknown thread root_\n"
offset += 1
else:
text = ""
text += make_thread_list_item(message, offset, show_link)
for child in message['children']:
text += make_markdown_thread_tree(child, message_hash, offset + 1)
return text
def make_markdown_thread(thread):
return "### {}\n{}".format(
thread['subject'].encode('utf-8'),
make_markdown_thread_tree(thread)
)
def build_threads_by_month():
for filename in glob.glob('json_months/199*/*.json'):
print filename
with open(filename) as f:
threads = json.loads(f.read())
regex = "json_months/([0-9]+)/([0-9]+|unknown).json"
matches = re.match(regex, filename)
year, month = matches.group(1), matches.group(2)
if not os.path.exists("threads_test/{}/".format(year)):
os.makedirs("threads_test/{}/".format(year))
with open('threads_test/{}/{}.md'.format(
year,
month.zfill(2)
), 'w') as o:
if month != "unknown":
month_name = month_name_map[int(month) - 1]
else:
month_name = "(unknown month)"
o.write(month_file_header.format(
month_name,
year
))
for thread in threads:
create_message_pages(thread)
o.write(make_markdown_thread(thread))
o.write("\n")
def build_author_indices():
if not os.path.exists("authors_test/"):
os.makedirs("authors_test/")
for filename in glob.glob('json_authors/*.json'):
print filename
with open(filename) as f:
author = json.loads(f.read())
with open('authors_test/{}.md'.format(author['sender_id']), 'w') as o:
o.write(author_file_header.format(
author['sender_id'],
author['count'],
author['from'].encode('utf-8').replace('@', '<span>@</span>'),
author['count'],
"posts" if author['count'] > 1 else "post"
))
for thread in author['threads']:
o.write(make_markdown_thread(thread))
o.write("\n")
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
sql = """
SELECT
`from`,
`sender_id`,
count(*) AS `messages`
FROM
`messages`
GROUP BY
`sender_id`
ORDER BY
`messages` DESC;
"""
with open('author_index/authors.md', 'w') as o:
o.write(author_index_template)
for row in cursor.execute(sql):
o.write("+ [{}](/authors/{}/) - _{} posts_\n".format(
row[0].encode('utf-8').replace('@', '<span>@</span>'),
row[1],
row[2],
))
def main():
build_threads_by_month()
build_author_indices()
if __name__ == "__main__":
main()