forked from akkana/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlosalamosmtgs.py
More file actions
executable file
·495 lines (400 loc) · 17.5 KB
/
losalamosmtgs.py
File metadata and controls
executable file
·495 lines (400 loc) · 17.5 KB
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
#!/usr/bin/env python3
# Scrape the Los Alamos meetings page to be alerted to what's on
# the agenda at upcoming meetings.
# Make it available via RSS.
# Suggestion: run this script via crontab:
# Use crontab -e to add a line like:
# 45 15 * * * python3 /path/tp/htdocs/losalamosmtgs.py > /path/to/htdocs/los-alamos-meetings/LOG 2>&1
import requests
from bs4 import BeautifulSoup
import datetime
from urllib.parse import urljoin
import io
import string
import subprocess
import tempfile
import json
import os, sys
########## CONFIGURATION ##############
# You can also pass in RSS_URL RSS_DIR as two optional arguments
# Where to start: the public legistar meeting list
MEETING_LIST_URL = "http://losalamos.legistar.com/Calendar.aspx"
# The place where the RSS will be hosted. Must end with a slash.
# The RSS file will be this/index.rss.
RSS_URL = "http://localhost/los-alamos-meetings/"
# Where to put the generated RSS file. Customize this for your website.
RSS_DIR = os.path.expanduser("~/web/los-alamos-meetings")
if not os.path.exists(RSS_DIR):
os.makedirs(RSS_DIR)
######## END CONFIGURATION ############
# Make a timezone-aware datetime for now:
now = datetime.datetime.now().astimezone()
# and save the timezone
localtz = now.tzinfo
# Format for dates in RSS:
# This has to be GMT, not %Z, because datetime.strptime just
# throws away any %Z info anyway rather than parsing it.
# Better to get an error if we see any time that's not GMT.
RSS_DATE_FORMAT = "%a, %d %b %Y %H:%M GMT"
# Where temp files will be created. pdftohtml can only write to a file.
tempdir = tempfile.mkdtemp()
def parse_meeting_list(only_past=False):
"""Parse the HTML page listing meetings,
returning a list of dictionaries for each upcoming meeting
(but not past ones).
"""
r = requests.get(MEETING_LIST_URL, timeout=30)
soup = BeautifulSoup(r.text, 'lxml')
# Remove a bunch of spurious tags
for badtag in [ "font", "span", "div" ]:
badtags = soup.find_all(badtag)
for tag in badtags:
tag.replace_with_children()
caltbl = soup.find("table",
id="ctl00_ContentPlaceHolder1_gridCalendar_ctl00")
# The legend is in the thead
fieldnames = []
for i, field in enumerate(caltbl.thead.findAll("th")):
if field.text:
fieldnames.append(field.text.strip())
else:
fieldnames.append(str(i))
upcoming = []
# Loop over meetings, rows in the table:
for row in caltbl.tbody.findAll("tr"):
dic = {}
# Loop over columns describing this meeting:
for i, field in enumerate(row.findAll("td")):
if fieldnames[i].startswith("Agenda"):
# If there's an Agenda URL, make it absolute.
a = field.find("a")
href = a.get("href")
if href:
dic[fieldnames[i]] = urljoin(MEETING_LIST_URL, href)
else:
dic[fieldnames[i]] = None
elif fieldnames[i] == 'Meeting Location':
# The Location field has simple formatting
# such as <br>, so can't just take .text, alas.
dic[fieldnames[i]] = ' '.join([str(c).strip()
for c in field.contents]) \
.strip()
# The little calendar icon somehow comes out with a name of '2'.
# Skip it.
elif fieldnames[i] == '2' or not fieldnames[i]:
continue
# Most fields are simple and won't have any formatting.
# They are full of nbsps '\u00a0', though.
else:
dic[fieldnames[i]] = field.text.replace('\u00a0', ' ').strip()
if "Meeting Date" in dic and "Meeting Time" in dic:
mtg_datetime = meeting_datetime(dic)
if only_past and mtg_datetime < utcnow:
continue
upcoming.append(dic)
return upcoming
def meeting_datetime(mtg):
"""Parse the meeting date and time and return an aware localtime.
"""
# The parsed time is in the local time and is unaware,
# because strptime can't create a timezone aware object (see above).
unaware = datetime.datetime.strptime(mtg["Meeting Date"] + " "
+ mtg["Meeting Time"],
'%m/%d/%Y %I:%M %p')
# Make it aware in localtime
localtime = unaware.astimezone(localtz)
return localtime
def get_html_agenda_pdftohtml(agendaloc, save_pdf_filename):
"""Convert a PDF agenda to text and/or HTML using pdftohtml,
removing the idiotic dark grey background pdftohtml has hardcoded in.
save_pdf_name is for debugging: if set, save the PDF there
and don't delete it.
Returns bytes, not str.
"""
r = requests.get(agendaloc, timeout=30)
with open(save_pdf_filename, "wb") as pdf_fp:
pdf_fp.write(r.content)
htmlfile = save_pdf_filename + ".html"
print("Calling", ' '.join(["pdftohtml", "-c", "-s", "-i", "-noframes",
"-enc", "utf-8",
save_pdf_filename, htmlfile]))
subprocess.call(["pdftohtml", "-c", "-s", "-i", "-noframes",
save_pdf_filename, htmlfile])
with open(htmlfile, 'rb') as htmlfp:
# The files produced by pdftohtml contain '\240' characters,
# which are ISO-8859-1 for nbsp.
# Adding "-enc", "utf-8" doesn't change that.
# If they aren't decoded, BeautifulSoup will freak out
# and won't see anything in the file at all.
html_bytes = htmlfp.read().decode('ISO-8859-1')
# Make some changes. Primarily,
# replace the grey background that htmltotext wires in
soup = BeautifulSoup(html_bytes, "lxml")
body = soup.body
# Sometimes pdftohtml mysteriously doesn't work, and gives
# a basically empty HTML file: everything is using position:absolute
# and that makes it invisible to BeautifulSoup.
# This seems to be
# https://gitlab.freedesktop.org/poppler/poppler/-/issues/417
# Check for that.
# If all else fails, htmltotext works to extract the text,
# and might produce cleaner output anyway.
# Or there may be some way to get BS to find those
# <p style="position:absolute" tags that it isn't seeing.
bodylen = len(body.text.strip())
if bodylen == 0:
print("** Yikes! Empty HTML from pdftohtml", htmlfile)
return html
else:
print(bodylen, "characters in body text")
if bodylen < 10:
print(f"Body text is: '{body.text}'")
del body["bgcolor"]
del body["vlink"]
del body["link"]
# Remove all the fixed pixel width styles
for tag in soup.findAll('style'):
tag.extract()
for tag in soup.findAll('div'):
del tag["style"]
for tag in soup.findAll('p'):
del tag["style"]
# Consider also deleting tag["class"]
# Or maybe the above changes were what removed the body contents?
if not body.text:
print("**Yikes! Our changes to", save_pdf_file,
"made the HTML empty. Saving original instead.")
with open(os.path.join(RSS_DIR, save_pdf_filename + "_cleaned.html"),
"w") as savfp:
print(soup.prettify(encoding='utf-8'), file=savfp)
return html
return soup.prettify(encoding='utf-8')
VALID_FILENAME_CHARS = "-_." + string.ascii_letters + string.digits
def clean_filename(badstr):
return ''.join(c for c in badstr if c in VALID_FILENAME_CHARS)
NO_AGENDA = b"<html><body><p>No agenda available.</body></html>"
def write_rss20_file(mtglist):
"""Take a list meeting dictionaries and make an RSS file from it.
"""
print("\n==== Generating RSS for", len(mtglist), "meetings")
active_meetings = ["index.rss"]
for mtg in mtglist:
lastmod = None
changestr = ""
mtg['cleanname'] = mtgdic_to_cleanname(mtg)
print(mtg["cleanname"])
if mtg["Agenda"]:
print(mtg["cleanname"], "has an agenda: fetching it")
# XXX TEMPORARY: save the PDF filename, because sometimes
# pdftohtml produces an HTML file with no content even
# though there's content in the PDF.
pdfout = os.path.join(RSS_DIR, mtg['cleanname'] + ".pdf")
agenda_html = get_html_agenda_pdftohtml(mtg["Agenda"],
save_pdf_filename=pdfout)
# RSS doesn't deal well with feeds where some items have
# a <link> and others don't. So make an empty file to keep
# RSS readers happy.
else:
agenda_html = b"NO AGENDA YET"
# Does the agenda file need to be (re)written?
write_agenda_file = False
# See if there was already an agenda file left from previous runs:
agendafile = os.path.join(RSS_DIR, mtg['cleanname'] + ".html")
if os.path.exists(agendafile):
with open(agendafile, "rb") as oldfp:
oldhtml = oldfp.read()
if oldhtml == NO_AGENDA: # no agenda previously
if agenda_html: # but there is now
write_agenda_file = True
changestr += "<p><b>There is now an agenda.</b>"
else: # there was a previous agenda
if not agenda_html: # ... which is gone now
changestr += \
"<p><b>An earlier agenda has been removed!</b>" \
"<p><b>Agenda saved here is the previous agenda.</b>"
# don't write over the old agenda file
elif agenda_html != oldhtml: # changed agenda
write_agenda_file = True
changestr += "<p><b>The agenda has changed.</b>"
else: # No agenda file there previously, probably a new meeting
write_agenda_file = True
if write_agenda_file:
if agenda_html:
lastmod = now
else:
agenda_html = NO_AGENDA
print("Writing a new agenda file")
with open(agendafile, 'wb') as outfp:
outfp.write(agenda_html)
jsonfile = os.path.join(RSS_DIR, mtg['cleanname'] + ".json")
if os.path.exists(jsonfile):
try:
with open(jsonfile) as jsonfp:
oldmtg = json.loads(jsonfp.read())
# mtg doesn't have lastmod, so to make sure that
# doesn't trigger a change, copy it:
mtg['lastmod'] = oldmtg['lastmod']
changed_keys = {key for key in oldmtg.keys() & mtg
if oldmtg[key] != mtg[key]}
if changed_keys:
lastmod = now
changestr += "<p>Changed: " + ', '.join(changed_keys) \
+ "</p>"
print("Keys changed:", changed_keys, "lastmod is", lastmod)
elif not lastmod:
print("Nothing has changed, keeping lastmod")
lastmod = datetime.datetime.strptime(oldmtg['lastmod'],
RSS_DATE_FORMAT)
except RuntimeError:
print("Error reading jsonfile")
changestr += "Error reading jsonfile<p>"
lastmod = now
else:
print("It's a new meeting, no previous jsonfile")
lastmod = now
mtg['lastmod'] = lastmod.strftime(RSS_DATE_FORMAT)
mtg['GUID'] = mtg['cleanname'] + '.' + lastmod.strftime("%Y%m%d-%H%M")
# Either way, this meeting is still listed:
# note it so it won't be cleaned from the directory.
active_meetings.append(mtg['cleanname'])
# If the meeting is new or something has changed,
# (re)write the JSON file. Don't save the changestr.
if "changestr" in mtg:
del mtg["changestr"]
with open(jsonfile, 'w') as jsonfp:
jsonfp.write(json.dumps(mtg, indent=4))
# The meeting has been saved to JSON,
# so it's safe to add other keys to it now.
# Save the change string to put it in the RSS later.
mtg['changestr'] = changestr
##############
# Finally, generate the index HTML and RSS files.
# The meeting list is in date/time order, latest first.
# Better to list them in the other order, starting with
# meetings today, then meetings tomorrow, etc.
# Could sort by keys, 'Meeting Date' and 'Meeting Time',
# but since it's already sorted, it's easier just to reverse.
mtglist.reverse()
# Open both the RSS and HTML files:
outrssfilename = os.path.join(RSS_DIR, "index.rss")
outhtmlfilename = os.path.join(RSS_DIR, "index.html")
with open(outrssfilename, 'w') as rssfp, \
open(outhtmlfilename, 'w') as htmlfp:
gendate = now.strftime(RSS_DATE_FORMAT)
print(f"""<?xml version="1.0" encoding="iso-8859-1" ?>
<rss version="2.0"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<channel>
<title>Los Alamos County Government Meetings</title>
<link>{RSS_URL}losalamosmeetings</link>
<description>An Unofficial, Non-Sanctioned Listing of Los Alamos Government Meetings, provided by Akkana Peck.</description>
<language>en</language>
<copyright>Public Domain</copyright>
<ttl>14</ttl>
<pubDate>{gendate}</pubDate>
<managingEditor>akk at shallowsky dot com (Akkana Peck)</managingEditor>
<generator>losalamosmtgs</generator>
""",
file=rssfp)
print(f"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Los Alamos County Government Meetings</title>
<link rel="alternate" type="application/rss+xml"
title="Los Alamos Meetings Feed"
href="{RSS_URL}index.rss" />
</head>
<body>
<h1>Los Alamos County Government Meetings</h1>
As of: {gendate}
.......... <a href="{RSS_URL}index.rss">Los Alamos Meetings RSS2.0 Feed</a>.
""", file=htmlfp)
for mtg in mtglist:
# Is the meeting in the future? Don't list past meetings.
meetingtime = meeting_datetime(mtg)
if meetingtime < now:
print("Skipping", mtg["Name"], mtg["Meeting Date"],
"because", meetingtime, "<", now)
continue
mtgtitle = f"""{mtg['Name']} on {mtg["Meeting Date"]}"""
desc = f"""{mtg['Name']}: {mtg['Meeting Date']} at {mtg['Meeting Time']}<br />
"""
if mtg['Meeting Location']:
desc += "<br>Location:" + mtg['Meeting Location']
link = f"{RSS_URL}{mtg['cleanname']}.html"
if mtg["Agenda"]:
withagenda = " (WITH AGENDA)"
desc = f"""{desc}<p>
<a href="{mtg["Agenda"]}">Agenda PDF</a><br>
</p>
"""
else:
desc += "<p>No agenda is available.</p>\n"
withagenda = " (no agenda)"
if mtg['changestr']:
desc += "<p>" + mtg['changestr'] + '\n'
if mtg["Agenda Packets"]:
# The agenda packet links tend to have & in them
# and so need to be escaped with CDATA
if 'http' in mtg["Agenda Packets"]:
desc += f"""<p><a href="{mtg["Agenda Packets"]}">Agenda Packet PDF</a></p>\n"""
else:
desc = f"""<p>Agenda packet: {mtg["Agenda Packets"]}</p>\n"""
print("GUID will be", mtg['GUID'], "lastmod is", mtg['lastmod'])
# Add the item to the RSS
print(f"""<item>
<title>{mtgtitle} {withagenda}</title>
<guid isPermaLink="false">{mtg['GUID']}</guid>
<link>{link}</link>
<description><![CDATA[ {desc} ]]>
</description>
<pubDate>{mtg['lastmod']}</pubDate>
</item>""", file=rssfp)
# And add it to the HTML
print(f"<p><h2>{mtgtitle} {withagenda}</h2>", file=htmlfp)
if mtg["Agenda"]:
print(f'<p><b><a href="{link}">Agenda: {mtgtitle}</a></b>',
file=htmlfp)
else:
print("<p>No agenda yet", file=htmlfp)
print(f"""<p>
{desc}
<p>(Last modified: {gendate}.)
""",
file=htmlfp)
print("</channel>\n</rss>", file=rssfp)
print("</body></html>", file=htmlfp)
print("Wrote", outrssfilename, "and", outhtmlfilename)
# Remove obsolete files for meetings no longer listed.
for f in os.listdir(RSS_DIR):
# Only clean up .json, .rss, .html:
if not f.endswith('.json') and not f.endswith('.rss') \
and not f.endswith('.html'):
continue
if f.startswith("index"):
continue
def is_active(f):
for act in active_meetings:
if f.startswith(act):
return True
return False
if not is_active(f):
print("removing", f)
os.unlink(os.path.join(RSS_DIR, f))
def mtgdic_to_cleanname(mtgdic):
"""A standard way to turn date and committee name into something
that can be used for filenames or URLs.
Will be used both for the agenda file and for RSS entries.
"""
return meeting_datetime(mtgdic).strftime("%Y-%m-%d") + '-' \
+ clean_filename(mtgdic["Name"])
if __name__ == '__main__':
if len(sys.argv) > 1:
RSS_URL = sys.argv[1]
# RSS_URL is a directory and must end with a slash
if not RSS_URL.endswith('/'):
RSS_URL += '/'
if len(sys.argv) > 2:
RSS_DIR = sys.argv[2]
meetings = parse_meeting_list()
write_rss20_file(meetings)