-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathneedtoknow.py
executable file
·285 lines (251 loc) · 9 KB
/
needtoknow.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
#!/usr/bin/env python3
import argparse
import bz2
import collections
import fcntl
import imaplib
import importlib
import json
import logging
import numbers
import pickle
import re
import socket
import sys
import urllib.error
import urllib.request
from pathlib import Path
from feeders.base import SyncRequest
from output import sender
# How many times to attempt reconnecting to our output mailbox when the
# connection is dropped.
RECONNECT_ATTEMPTS = 3
def get_resource_path(root: str, name: str) -> Path:
return Path(root) / f"cache/{name}.pickle.bz2"
def construct_feeder(root, name, log, debug: bool):
try:
mod = importlib.import_module(f"feeders.{name}")
except Exception as e:
log.warning(f"failed to import feeder {name}: {e}")
return None
respath = get_resource_path(root, name)
if respath.exists():
with bz2.open(respath, "rb") as f:
resource = pickle.load(f)
else:
resource = {}
return mod.Feeder(resource, log, debug)
def online():
try:
urllib.request.urlopen("http://www.google.com", timeout=5)
return True
except urllib.error.URLError:
return False
def main():
parser = argparse.ArgumentParser("Monitor RSS and other feeds")
parser.add_argument(
"--disable",
"-d",
action="append",
default=[],
help="disable a particular feeder by name",
)
parser.add_argument(
"--enable",
"-e",
action="append",
default=[],
help="enable a particular feeder by name",
)
parser.add_argument(
"--exclude",
"-x",
action="append",
default=[],
help="exclude a particular feed by name",
)
parser.add_argument(
"--include",
"-i",
action="append",
default=[],
help="include a particular feed by name",
)
parser.add_argument(
"--check-connection",
action="store_true",
help="check whether we have an internet connection first",
)
parser.add_argument(
"--config",
default=str(Path("~/.needtoknow").expanduser()),
help="configuration location",
)
parser.add_argument(
"--dry-run", action="store_true", help="scan feeds but don't send any updates"
)
parser.add_argument(
"--debug",
action="store_true",
help="instead of catching exceptions, let them dump a back trace",
)
opts = parser.parse_args()
log = logging.getLogger("needtoknow")
log.addHandler(logging.StreamHandler(sys.stderr))
# Determine whether we are running interactively.
if sys.stdout.isatty():
if opts.debug:
log.setLevel(logging.DEBUG)
else:
log.setLevel(logging.INFO)
else:
log.setLevel(logging.WARNING)
# Check whether we're already running, to prevent multiple instances running
# at once. Multiple running instances can interfere with each other when
# saving state.
me = open(Path(__file__).resolve(), "rt")
try:
fcntl.flock(me, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
log.error("needtoknow is already running; exiting\n")
return -1
if opts.check_connection and not online():
log.info("no network connection; exiting")
return 0
try:
with open(Path(opts.config) / "conf.json", "rt", encoding="utf-8") as f:
conf = json.load(f)
if not isinstance(conf, collections.abc.Mapping):
raise TypeError("configuration is not a JSON object")
if not all(isinstance(v, (str, numbers.Integral)) for v in conf.values()):
raise TypeError("configuration values are not all strings or numbers")
except Exception as e:
if opts.debug:
raise
log.error(f"Failed to parse config: {e}")
return -1
try:
with open(Path(opts.config) / "feeds.json", "rt", encoding="utf-8") as f:
feeds = json.load(f)
if not isinstance(feeds, collections.abc.Mapping):
raise TypeError("feeds is not a JSON object")
if not all(isinstance(v, collections.abc.Mapping) for v in feeds.values()):
raise TypeError("feed values are not all JSON objects")
except Exception as e:
if opts.debug:
raise
log.error(f"Failed to parse feeds: {e}")
return -1
feeders = {}
log.info("Loading feeders...")
for s, v in feeds.items():
f = v.get("feeder")
if f not in feeders:
log.info(f" Loading {f}...")
feeders[f] = construct_feeder(opts.config, f, log, opts.debug)
if feeders[f] is None:
log.warning(f" Warning: No feeder named {f} (referenced by {s}).")
else:
if s in opts.include or (opts.include == [] and s not in opts.exclude):
feeders[f].add(s, v)
# Set timeout on socket connections to 60 seconds. Without this, some
# platforms have no timeout (even on the kernel side) and socket connections
# can stall forever.
socket.setdefaulttimeout(60)
out = sender.Sender(conf)
try:
out.connect()
except Exception as e:
if opts.debug:
raise
log.error(f"Failed to connect to mail server: {e}")
return -1
ret = 0
log.info("Looking for updates...")
for f in feeders:
def commit_changes():
if not opts.dry_run:
log.info(" Committing resource changes...")
respath = get_resource_path(opts.config, f)
respath.parent.mkdir(exist_ok=True)
tmp = Path(f"{respath}.tmp")
with bz2.open(tmp, "wb") as fobj:
pickle.dump(feeders[f].resource, fobj)
tmp.rename(respath)
if feeders[f] is None:
# We failed to load this feeder.
continue
if f in opts.disable or (opts.enable != [] and f not in opts.enable):
continue
try:
log.info(f" Scanning {f}...")
for entry in feeders[f]:
if isinstance(entry, Exception):
if opts.debug:
raise entry
log.warning(f" Feeder '{f}' threw exception: {entry}")
ret = -1
continue
elif isinstance(entry, SyncRequest):
commit_changes()
continue
# Check if we should discard this entry.
assert (
entry.name in feeders[f].feeds
), f"feeder '{f}' yielded entry from unknown feed '{entry.name}'"
skip = False
for blocklist in feeders[f].feeds[entry.name].get("blocklist", []):
try:
if re.search(blocklist, entry.subject) is not None:
log.info(
f" Discarding '[{entry.name}] {entry.subject}' as blocklisted"
)
skip = True
break
except Exception as e:
if opts.debug:
raise
log.error(
f" Failed to run regex blocklist '{blocklist}' "
f"against {entry.name}: {e}"
)
ret = -1
if skip:
continue
if opts.dry_run:
log.info(f" skipping '{entry.subject}' send due to --dry-run")
continue
try:
for i in range(RECONNECT_ATTEMPTS + 1):
try:
out.send(entry, log, i == 0)
break
except ConnectionResetError:
if i == RECONNECT_ATTEMPTS:
raise
log.info(" connection reset by peer; reconnecting...")
except imaplib.IMAP4.error as err:
if i == RECONNECT_ATTEMPTS:
raise
log.info(f" IMAP4 error {err}; reconnecting...")
except (socket.timeout, TimeoutError):
if i == RECONNECT_ATTEMPTS:
raise
log.info(" socket timeout; reconnecting...")
out.connect()
except Exception as e:
if opts.debug:
raise
log.error(
f" Failed to send update for {entry.name} '{entry.subject}': {e}"
)
ret = -1
except Exception as e:
if opts.debug:
raise
log.warning(f" Feeder '{f}' threw exception: {e}")
commit_changes()
out.disconnect()
return ret
if __name__ == "__main__":
sys.exit(main())