Debian Codegraph @

recipes/newrepublicmag.recipe

raw
1 """
2 newrepublic.com
3 """
4
5 import json
6 from functools import cmp_to_key
7 from urllib.parse import urlencode, urljoin, urlparse, urlsplit
8
9 from calibre import iswindows
10 from calibre.ebooks.BeautifulSoup import BeautifulSoup
11 from calibre.utils.date import parse_date
12 from calibre.web.feeds.news import BasicNewsRecipe
13
14 _issue_url = '' # example: https://newrepublic.com/magazine/may-2023
15
16
17 def sort_section(a, b, sections_sort):
18 try:
19 a_index = sections_sort.index(a['section'])
20 except ValueError:
21 a_index = 999
22 try:
23 b_index = sections_sort.index(b['section'])
24 except ValueError:
25 b_index = 999
26
27 if a_index < b_index:
28 return -1
29 if a_index > b_index:
30 return 1
31 if a['section'] == b['section']:
32 return -1 if a['date'] < b['date'] else 1
33 return -1 if a['section'] < b['section'] else 1
34
35
36 class NewRepublicMagazine(BasicNewsRecipe):
37 title = 'The New Republic Magazine'
38 language = 'en'
39 __author__ = 'ping'
40 description = (
41 'Founded in 1914, The New Republic is a media organization dedicated to addressing today’s most critical issues. https://newrepublic.com/magazine'
42 )
43 publication_type = 'magazine'
44 use_embedded_content = False
45 masthead_url = 'https://images.newrepublic.com/f5acdc0030e3212e601040dd24d5c2c0c684b15f.png?w=512&q=65&dpi=1&fit=crop&crop=faces&h=256'
46 remove_attributes = ['height', 'width']
47 ignore_duplicate_articles = {'title', 'url'}
48 remove_empty_feeds = True
49 compress_news_images = True
50 compress_news_images_auto_size = 6
51 requires_version = (5, 0, 0)
52
53 BASE_URL = 'https://newrepublic.com'
54
55 extra_css = '''
56 h1.headline { margin-bottom: 0.4rem; }
57 h2.subheadline { font-style: italic; margin-bottom: 1rem; font-weight: normal; }
58 .article-meta { margin-bottom: 1rem; }
59 .article-meta span { display: inline-block; font-weight: bold; margin-right: 0.5rem; }
60 .article-meta span:last-child { font-weight: normal; }
61 div.pullquote { font-size: 1.25rem; margin-left: 0; text-align: center; }
62 .lede-media img, .article-embed img, img {
63 display: block; margin-bottom: 0.3rem; max-width: 100%; height: auto;
64 box-sizing: border-box;
65 }
66 .lede-media .caption, .article-embed .caption { font-size: 0.8rem; }
67 div.author-bios { margin-top: 2rem; font-style: italic; border-top: solid 1px dimgray; }
68 '''
69
70 def _article_endpoint(self, nid):
71 """
72 Graphql endpoint to fetch full article
73 :param nid:
74 :return:
75 """
76 query = '''
77 query ($id: ID, $nid: ID) {
78 Article(id: $id, nid: $nid) {
79 ...ArticlePageFields
80 }
81 }
82 fragment ArticlePageFields on Article {
83 id
84 nid
85 slug
86 title
87 cleanTitle
88 badge
89 frontPage {
90 id
91 slug
92 title
93 }
94 LinkedSeriesId
95 authors {
96 id
97 name
98 slug
99 blurb
100 meta {
101 twitter
102 }
103 }
104 body
105 publishedAt
106 displayAt
107 publicPublishedDate
108 status
109 ledeImage {
110 id
111 src
112 format
113 width
114 height
115 alt
116 }
117 ledeAltImage {
118 id
119 src
120 format
121 width
122 height
123 alt
124 }
125 url
126 urlFull
127 meta {
128 wordCount
129 template
130 navigationTheme
131 bigLede
132 hideLede
133 cropModeFronts
134 ledeOverrideSource
135 disableAds
136 }
137 ledeImageCredit
138 ledeImageCreditBottom
139 ledeImageRealCaption
140 bylines
141 deck
142 type
143 galleries {
144 id
145 galleryData {
146 captionText
147 creditText
148 image {
149 id
150 src
151 width
152 height
153 }
154 }
155 }
156 tags {
157 id
158 slug
159 label
160 }
161 }'''
162 params = {'query': query, 'variables': json.dumps({'nid': str(nid)})}
163 return f'https://newrepublic.com/graphql?{urlencode(params)}'
164
165 def _resize_image(self, image_url, width, height):
166 """
167 Rewrite the image url to fetch a device appropriate sized one instead
168 of the full-res one
169
170 :param image_url:
171 :param width:
172 :param height:
173 :return:
174 """
175 crop_params = {
176 'auto': 'compress',
177 'ar': f'{width}:{height}',
178 'fm': 'jpg',
179 'fit': 'crop',
180 'crop': 'faces',
181 'ixlib': 'react-9.0.2',
182 'dpr': 1,
183 'q': 65,
184 'w': self.scale_news_images[0] if self.scale_news_images else 800,
185 }
186 url_tuple = urlsplit(image_url)
187 return f'{url_tuple.scheme}://{url_tuple.netloc}{url_tuple.path}?{urlencode(crop_params)}'
188
189 def populate_article_metadata(self, article, soup, first):
190 # pick up the og link from preprocess_raw_html() and set it as url instead of the api endpoint
191 og_link = soup.select('[data-og-link]')
192 if og_link:
193 article.url = og_link[0]['data-og-link']
194
195 def preprocess_raw_html(self, raw_html, url):
196 # formulate the api response into html
197 article = json.loads(raw_html)['data']['Article']
198 # Example: 2022-08-12T10:00:00.000Z
199 date_published_loc = parse_date(article['publishedAt'])
200 # authors
201 author_bios_html = ''
202 post_authors = []
203 try:
204 post_authors = [a['name'] for a in article.get('authors', [])]
205 if post_authors:
206 author_bios_html = ''.join([a.get('blurb', '') for a in article.get('authors', [])])
207 author_bios_html = f'<div class="author-bios">{author_bios_html}</div>'
208 except KeyError, TypeError:
209 pass
210
211 # lede image
212 lede_image_html = ''
213 if article.get('ledeImage'):
214 img = article['ledeImage']
215 lede_img_url = self._resize_image(urljoin(self.BASE_URL, img['src']), img['width'], img['height'])
216 lede_image_caption = ''
217 if article.get('ledeImageRealCaption'):
218 lede_image_caption = f'<span class="caption">{article["ledeImageRealCaption"]}>/span>'
219 lede_image_html = f'''<p class="lede-media">
220 <img src="{lede_img_url}">{lede_image_caption}
221 </p>'''
222
223 body_soup = BeautifulSoup(article['body'], features='html.parser')
224 for img in body_soup.find_all('img', attrs={'data-serialized': True}):
225 try:
226 img_info = json.loads(img['data-serialized'])
227 img_src = self._resize_image(
228 urljoin(self.BASE_URL, img_info['src']),
229 img_info['width'],
230 img_info['height'],
231 )
232 img['src'] = img_src
233 del img['data-serialized']
234 except Exception:
235 pass
236
237 return f'''<html>
238 <head><title>{article["cleanTitle"]}</title></head>
239 <body>
240 <article data-og-link="{article["urlFull"]}">
241 <h1 class="headline">{article["cleanTitle"]}</h1>
242 {('<h2 class="subheadline">' + article["deck"] + "</h2>") if article.get("deck") else ""}
243 <div class="article-meta">
244 {f'<span class="author">{", ".join(post_authors)}</span>' if post_authors else ""}
245 <span class="published-dt">
246 {date_published_loc:{"%b %d, %Y" if iswindows else "%b %-d, %Y"}}
247 </span>
248 </div>
249 {lede_image_html}
250 {body_soup!s}
251 {author_bios_html}
252 </article>
253 </body></html>'''
254
255 def parse_index(self):
256 br = self.get_browser()
257 params = ''
258 if _issue_url:
259 month = urlparse(_issue_url).path.split('/')[-1]
260 params = f'?{urlencode({"magazineTag": month})}'
261 res = br.open_novisit(f'https://newrepublic.com/api/content/magazine{params}')
262 magazine = json.loads(res.read().decode('utf-8'))['data']
263 self.log.debug(f'Found issue: {magazine["metaData"]["issueTag"]["text"]}')
264 self.timefmt = f': {magazine["metaData"]["issueTag"]["text"]}'
265 self.cover_url = urljoin(self.BASE_URL, magazine['metaData']['image']['src'])
266
267 feed_articles = []
268 for k, articles in magazine.items():
269 if not (k.startswith('magazine') and articles):
270 continue
271 try:
272 for article in articles:
273 self.log.debug(f'Found article: {article["title"]}')
274 feed_articles.append({
275 'url': self._article_endpoint(article['nid']),
276 'title': article['title'].replace('\n', ' '),
277 'description': article.get('deck', ''),
278 'date': article['publishedAt'],
279 'section': k[len('magazine') :],
280 })
281 except TypeError:
282 # not iterable
283 pass
284
285 sort_sections = [
286 'Cover',
287 'Editorsnote',
288 'Features',
289 'StateOfTheNation',
290 'ResPublica',
291 'Columns',
292 'Upfront',
293 'Backstory',
294 'SignsAndWonders',
295 'Usandtheworld',
296 'Booksandthearts',
297 'Poetry',
298 'Exposure',
299 ]
300 sort_category_key = cmp_to_key(lambda a, b: sort_section(a, b, sort_sections))
301 return [
302 (
303 magazine['metaData']['issueTag']['text'],
304 sorted(feed_articles, key=sort_category_key),
305 )
306 ]