]> git.scottworley.com Git - paperdoorknob/blame - paperdoorknob.py
entries() convenience method
[paperdoorknob] / paperdoorknob.py
CommitLineData
92b11a10
SW
1# paperdoorknob: Print glowfic
2#
3# This program is free software: you can redistribute it and/or modify it
4# under the terms of the GNU General Public License as published by the
5# Free Software Foundation, version 3.
6
7
8from argparse import ArgumentParser
55958ec0 9import itertools
ba3b7c52 10import os.path
a0d30541
SW
11
12from typing import Iterable
13
136277e3 14from bs4 import BeautifulSoup
6409066b 15from bs4.element import Tag
b25a2f90 16import requests
b34a368f 17import requests_cache
ba3b7c52 18from xdg_base_dirs import xdg_cache_home
92b11a10
SW
19
20
6409066b
SW
21class Post:
22 def __init__(self, html: BeautifulSoup) -> None:
23 self._html = html
24
25 def text(self) -> Tag:
26 body = self._html.body
27 assert body
28 text = body.find_next("div", class_="post-post")
29 assert isinstance(text, Tag)
30 return text
31
a0d30541
SW
32 def replies(self) -> Iterable[Tag]:
33 replies = self._html.find_all("div", class_="post-reply")
34 assert all(isinstance(r, Tag) for r in replies)
35 return replies
36
55958ec0
SW
37 def entries(self) -> Iterable[Tag]:
38 return itertools.chain([self.text()], self.replies())
39
6409066b 40
92b11a10
SW
41def command_line_parser() -> ArgumentParser:
42 parser = ArgumentParser(prog='paperdoorknob', description='Print glowfic')
ba3b7c52
SW
43 parser.add_argument(
44 '--cache_path',
45 metavar='PATH',
46 help='Where to keep the http cache (instead of %(default)s)',
47 default=os.path.join(xdg_cache_home(), "paperdoorknob"))
b25a2f90
SW
48 parser.add_argument(
49 '--timeout',
50 help='How long to wait for HTTP requests, in seconds',
51 default=30)
52 parser.add_argument('url', help='URL to retrieve')
92b11a10
SW
53 return parser
54
55
136277e3 56def fetch(url: str, session: requests.Session, timeout: int) -> BeautifulSoup:
e138a9b4
SW
57 with session.get(url, timeout=timeout) as r:
58 r.raise_for_status()
136277e3 59 return BeautifulSoup(r.text, 'html.parser')
b25a2f90
SW
60
61
92b11a10 62def main() -> None:
b25a2f90 63 args = command_line_parser().parse_args()
4c1cf54e 64 with requests_cache.CachedSession(args.cache_path, cache_control=True) as session:
6409066b
SW
65 html = fetch(args.url, session, args.timeout)
66 Post(html)
92b11a10
SW
67
68
69if __name__ == '__main__':
70 main()