Debian Codegraph @

recipes/economist_free.recipe

raw
1 #!/usr/bin/env python
2 import json
3 import time
4 from datetime import datetime, timedelta
5 from urllib.parse import quote, urlencode
6 from uuid import uuid4
7
8 from html5_parser import parse
9 from lxml import etree
10 from mechanize import Request
11
12 from calibre import browser
13 from calibre.utils.date import local_tz
14 from calibre.web.feeds.news import BasicNewsRecipe
15
16
17 def safe_dict(data, *names):
18 ans = data
19 for x in names:
20 ans = ans.get(x) or {}
21 return ans
22
23
24 def process_web_list(li_node):
25 li_html = ''
26 for li in li_node['items']:
27 if li.get('textHtml'):
28 li_html += f'<li>{li["textHtml"]}</li>'
29 elif li.get('textJson'):
30 li_html += f'<li>{parse_textjson(li["textJson"])}</li>'
31 else:
32 li_html += f'<li>{li.get("text", "")}</li>'
33 return '<ul>' + li_html + '</ul>'
34
35
36 def process_info_box(bx):
37 info = ''
38 for x in safe_dict(bx, 'components'):
39 info += f'<blockquote>{process_web_node(x)}</blockquote>'
40 return info
41
42
43 def parse_txt(ty):
44 typ = ty.get('type', '')
45 children = ty.get('children', [])
46 href = '#'
47 attributes = ty.get('attributes') or ()
48 for a in attributes:
49 if a.get('name') == 'href':
50 href = a.get('value', href)
51 break
52
53 tag_map = {
54 'text': lambda: [ty.get('value', '')],
55 'scaps': lambda: [
56 f'<span style="text-transform: uppercase; font-size: 0.85em; letter-spacing: 0.05em;">{"".join(parse_txt(c))}</span>' for c in children
57 ],
58 'bold': lambda: [f'<b>{"".join(parse_txt(c))}</b>' for c in children],
59 'drop_caps': lambda: [f'<b>{"".join(parse_txt(c))}</b>' for c in children],
60 'italic': lambda: [f'<i>{"".join(parse_txt(c))}</i>' for c in children],
61 'linebreak': lambda: ['<br>'],
62 'external_link': lambda: [f'<a href="{href}">{"".join(parse_txt(c))}</a>' for c in children],
63 'internal_link': lambda: [f'<a href="{href}">{"".join(parse_txt(c))}</a>' for c in children],
64 'ufinish': lambda: [text for c in children for text in parse_txt(c)],
65 'subscript': lambda: [f'<sub>{"".join(parse_txt(c))}</sub>' for c in children],
66 'superscript': lambda: [f'<sup>{"".join(parse_txt(c))}</sup>' for c in children],
67 }
68
69 if typ in tag_map:
70 yield from tag_map[typ]()
71 else:
72 print('** ', typ)
73
74
75 def parse_textjson(nt):
76 return ''.join(''.join(parse_txt(n)) for n in nt)
77
78
79 def process_web_node(node):
80 ntype = node.get('type', '')
81 if ntype == 'CROSSHEAD':
82 if node.get('textHtml'):
83 return f'<h4>{node.get("textHtml")}</h4>'
84 return f'<h4>{node.get("text", "")}</h4>'
85 elif ntype in ['PARAGRAPH', 'BOOK_INFO']:
86 if node.get('textHtml'):
87 return f'\n<p>{node.get("textHtml")}</p>'
88 elif node.get('textJson'):
89 return f'\n<p>{parse_textjson(node["textJson"])}</p>'
90 return f'\n<p>{node.get("text", "")}</p>'
91 elif (ntype == 'IMAGE') or (node.get('__typename', '') == 'ImageComponent'):
92 alt = '' if node.get('altText') is None else node.get('altText')
93 cap = ''
94 if node.get('caption'):
95 if node['caption'].get('textHtml') is not None:
96 cap = node['caption']['textHtml']
97 elif node['caption'].get('textJson') is not None:
98 cap = parse_textjson(node['caption']['textJson'])
99 elif node['caption'].get('text') is not None:
100 cap = node['caption']['text']
101 return f'<div><img src="{node["url"]}" title="{alt}"></div><div style="text-align:center; font-size:small;">{cap}</div>'
102 elif ntype == 'PULL_QUOTE':
103 if node.get('textHtml'):
104 return f'<blockquote>{node.get("textHtml")}</blockquote>'
105 elif node.get('textJson'):
106 return f'<blockquote>{parse_textjson(node["textJson"])}</blockquote>'
107 return f'<blockquote>{node.get("text", "")}</blockquote>'
108 elif ntype == 'BLOCK_QUOTE':
109 if node.get('textHtml'):
110 return f'<blockquote><i>{node.get("textHtml")}</i></blockquote>'
111 elif node.get('textJson'):
112 return f'<blockquote><i>{parse_textjson(node["textJson"])}</i></blockquote>'
113 return f'<blockquote><i>{node.get("text", "")}</i></blockquote>'
114 elif ntype == 'DIVIDER':
115 return '<hr>'
116 elif ntype == 'INFOGRAPHIC':
117 if node.get('fallback'):
118 return process_web_node(node['fallback'])
119 elif ntype == 'INFOBOX':
120 return process_info_box(node)
121 elif ntype == 'UNORDERED_LIST':
122 if node.get('items'):
123 return process_web_list(node)
124 elif ntype:
125 print('** ', ntype)
126 return ''
127
128
129 def load_article_from_json(raw):
130 # open('/t/raw.json', 'w').write(raw)
131 body = ''
132 try:
133 data = json.loads(raw)['data']['findArticleByUrl']
134 except Exception:
135 try:
136 data = json.loads(raw)['props']['pageProps']['cp2Content']
137 except Exception:
138 data = json.loads(raw)['props']['pageProps']['content']
139
140 body += f'<div style="color: red; font-size:small; font-weight:bold;">{data.get("flyTitle", "")}</div>'
141 body += f'<h1>{data["headline"]}</h1>'
142 if data.get('rubric') and data.get('rubric') is not None:
143 body += f'<div style="font-style: italic; color:#202020;">{data.get("rubric", "")}</div>'
144 try:
145 date = data['dateModified']
146 except Exception:
147 date = data['datePublished']
148 dt = datetime.fromisoformat(date[:-1]) + timedelta(seconds=time.timezone)
149 dt = dt.strftime('%b %d, %Y %I:%M %p')
150 if data.get('dateline') is None:
151 body += f'<p style="color: gray; font-size: small;">{dt}</p>'
152 else:
153 body += f'<p style="color: gray; font-size: small;">{dt + " | " + (data["dateline"])}</p>'
154 main_image_url = safe_dict(data, 'leadComponent') or ''
155 if main_image_url:
156 body += process_web_node(data['leadComponent'])
157 if data.get('byline'):
158 if data['byline'] is not None:
159 body += f'<p style="color: gray; font-size: small;"><i>{"By " + data["byline"]}</i></p>'
160 for node in data.get('body'):
161 body += process_web_node(node)
162 return '<html><body><article>' + body + '</article></body></html>'
163
164
165 class NoArticles(Exception):
166 pass
167
168
169 def get_content(url):
170 headers = {
171 'user-agent': 'Mozilla/5.0 (Linux; Android 16) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.7871.124 Mobile Safari/537.36 Liskov',
172 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
173 'x-requested-with': 'com.economist.lamarr',
174 'blaize_session': str(uuid4()),
175 'sec-ch-ua-mobile': '?1',
176 'sec-ch-ua-platform': 'Android',
177 'upgrade-insecure-requests': '1',
178 }
179 br = browser()
180 req = Request(
181 url + '?app=core%2Cfocused&no-chrome=key&no-adverts=key&webview=liskov',
182 headers=headers,
183 )
184 res = br.open(req)
185 return res.read()
186
187
188 def process_url(url):
189 if url.startswith('/'):
190 url = 'https://www.economist.com' + url
191 return url
192
193
194 def get_edition(issue_date=None):
195 if issue_date:
196 operation_name = 'EditionByDateQuery'
197 operation_args = '($issueDate: Date!)'
198 resolver = 'findEditionByDate(issueDate: $issueDate, editionType: WEEKLY)'
199 variables = {'issueDate': issue_date}
200 else:
201 operation_name = 'LatestEditionQuery'
202 operation_args = ''
203 resolver = 'findLatestEdition(editionType: [WEEKLY])'
204 variables = {}
205 graphql = (
206 'query ' + operation_name + operation_args + ' {'
207 ' edition: ' + resolver + ' {'
208 ' id issueDate datePublished url headline flyTitle rubric'
209 ' cover { url }'
210 ' sections { id name articles { id url headline flyTitle rubric } }'
211 ' }'
212 '}'
213 )
214 query = {
215 'operationName': operation_name,
216 'variables': json.dumps(variables, separators=(',', ':')),
217 'query': graphql,
218 }
219 url = 'https://cp2-graphql-gateway.p.aws.economist.com/graphql?' + urlencode(query, safe='()!', quote_via=quote)
220 return safe_dict(json.loads(get_content(url)), 'data', 'edition')
221
222
223 class Economist(BasicNewsRecipe):
224 title = 'The Economist'
225 language = 'en_GB'
226 encoding = 'utf-8'
227 masthead_url = 'https://www.livemint.com/lm-img/dev/economist-logo-oneline.png'
228
229 __author__ = 'Kovid Goyal, unkn0wn'
230 description = 'Global news and current affairs from a European perspective. Best downloaded away from Friday to avoid being blocked.'
231 extra_css = '''
232 em { color:#202020; }
233 img {display:block; margin:0 auto;}
234 '''
235
236 resolve_internal_links = True
237
238 delay = 2
239 # browser_type = 'webengine'
240 recipe_specific_options = {
241 'date': {
242 'short': 'The date of the edition to download (YYYY-MM-DD format)',
243 'long': 'For example, 2024-07-19',
244 },
245 'res': {
246 'short': 'For hi-res images, select a resolution from the\nfollowing options: 834, 960, 1096, 1280, 1424',
247 'long': 'This is useful for non e-ink devices, and for a lower file size\nthan the default, use from 480, 384, 360, 256.',
248 'default': '600',
249 },
250 }
251
252 def get_browser(self, *args, **kwargs):
253 # from calibre.utils.random_ua import common_english_word_ua
254 #
255 # self.last_used_ua = kwargs['user_agent'] = kwargs.get('user_agent', common_english_word_ua())
256
257 self.last_used_ua = kwargs['user_agent'] = (
258 'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.103 Mobile Safari/537.36 Liskov'
259 )
260 br = BasicNewsRecipe.get_browser(self, *args, **kwargs)
261 return br
262
263 def canonicalize_internal_url(self, url, is_link=True):
264 if url.endswith('/print'):
265 url = url.rpartition('/')[0]
266 return BasicNewsRecipe.canonicalize_internal_url(self, url, is_link=is_link)
267
268 def publication_date(self):
269 edition_date = self.recipe_specific_options.get('date')
270 if isinstance(edition_date, str):
271 edition_date = edition_date.strip()
272 if edition_date and isinstance(edition_date, str):
273 return datetime.strptime(edition_date, '%Y-%m-%d').replace(tzinfo=local_tz)
274 try:
275 url = self.browser.open('https://www.economist.com/printedition').geturl()
276 date_str = url.split('/')[-1]
277 return datetime.strptime(date_str, '%Y-%m-%d').replace(tzinfo=local_tz)
278 except Exception as e:
279 self.log('Failed to fetch publication date from website with error: ' + str(e))
280 try:
281 edition = self.economist_get_edition()
282 return datetime.strptime(edition['issueDate'][:10], '%Y-%m-%d').replace(tzinfo=local_tz)
283 except Exception as e:
284 self.log('Failed to fetch publication date from GraphQL with error: ' + str(e))
285 return super().publication_date()
286
287 def economist_get_edition(self, edition_date=None):
288 cache = getattr(self, '_edition_cache', {})
289 if edition_date not in cache:
290 cache[edition_date] = get_edition(edition_date)
291 self._edition_cache = cache
292 return cache[edition_date]
293
294 def get_obfuscated_article(self, url):
295 return {'data': get_content(url), 'url': url}
296
297 def economist_return_index(self, ans):
298 if not ans:
299 raise NoArticles(
300 'Could not find any articles, either the '
301 'economist.com server is having trouble and you should '
302 'try later or the website format has changed and the '
303 'recipe needs to be updated.'
304 )
305 return ans
306
307 def economist_test_article(self):
308 return [('Articles', [{'title': 'test', 'url': 'https://www.economist.com/international/2026/07/23/the-geopolitics-of-air-conditioning'}])]
309
310 def parse_index(self):
311 # return self.economist_test_article()
312 edition_date = self.recipe_specific_options.get('date')
313 if isinstance(edition_date, str):
314 edition_date = edition_date.strip()
315 if edition_date and isinstance(edition_date, str):
316 url = 'https://www.economist.com/weeklyedition/' + edition_date
317 self.timefmt = ' [' + edition_date + ']'
318 else:
319 edition_date = None
320 url = 'https://www.economist.com/weeklyedition'
321 try:
322 ans = self.economist_parse_index(url)
323 except Exception as e:
324 self.log('Failed to get index from website with error:', e)
325 ans = []
326 if not ans:
327 self.log('Falling back to GraphQL for the edition index')
328 try:
329 ans = self.economist_parse_graphql_index(self.economist_get_edition(edition_date))
330 except Exception as e:
331 self.log('Failed to get index from GraphQL with error:', e)
332 ans = []
333 return self.economist_return_index(ans)
334
335 def economist_parse_index(self, url):
336 soup = self.index_to_soup(get_content(url))
337 script_tag = soup.find('script', id='__NEXT_DATA__')
338 if script_tag is None:
339 self.log('Failed to get index with UA:', self.last_used_ua)
340 from calibre.utils.random_ua import random_common_chrome_user_agent
341
342 user_agent = random_common_chrome_user_agent()
343 self.log('Retrying with UA:', user_agent)
344 time.sleep(1)
345 self.browser = self.get_browser(user_agent=user_agent)
346 soup = self.index_to_soup(url)
347 script_tag = soup.find('script', id='__NEXT_DATA__')
348 if script_tag is None:
349 return []
350 data = json.loads(script_tag.string)
351 # open('/t/raw.json', 'w').write(json.dumps(data, indent=2, sort_keys=True))
352
353 self.description = safe_dict(data, 'props', 'pageProps', 'content', 'headline')
354 self.timefmt = ' [' + safe_dict(data, 'props', 'pageProps', 'content', 'formattedIssueDate') + ']'
355 self.cover_url = (
356 safe_dict(data, 'props', 'pageProps', 'content', 'cover', 'url')
357 .replace(
358 'economist.com/',
359 'economist.com/cdn-cgi/image/width=960,quality=80,format=auto/',
360 )
361 .replace('SQ_', '')
362 .replace('_AS', '_AP')
363 )
364 self.log('Got cover:', self.cover_url)
365
366 feeds = []
367 seen = set()
368 for component in safe_dict(data, 'props', 'pageProps', 'content', 'components'):
369 match component.get('type'):
370 case 'AD':
371 continue
372 case 'COLLECTION':
373 articles = []
374 section = component['name']
375 self.log(section)
376 for article in component['articles']:
377 for article in component['articles']:
378 if article['id'] in seen:
379 continue
380 seen.add(article['id'])
381 title = article['headline']
382 url = process_url(article['url'])
383 sub = article.get('flyTitle') or ''
384 desc = article.get('rubric') or ''
385 if sub and section != sub:
386 desc = sub + ' :: ' + desc
387 self.log('\t', title, '\n\t', desc, '\n\t\t', url)
388 articles.append({'title': title, 'url': url, 'description': desc})
389 if articles:
390 feeds.append((section, articles))
391
392 return feeds
393
394 def economist_parse_graphql_index(self, edition):
395 if not edition:
396 return []
397 self.description = edition.get('headline') or self.description
398 self.timefmt = ' [' + edition['issueDate'][:10] + ']'
399 cover_url = safe_dict(edition, 'cover', 'url')
400 if cover_url:
401 self.cover_url = (
402 cover_url
403 .replace(
404 'economist.com/',
405 'economist.com/cdn-cgi/image/width=960,quality=80,format=auto/',
406 )
407 .replace('SQ_', '')
408 .replace('_AS', '_AP')
409 )
410 self.log('Got cover:', self.cover_url)
411
412 feeds = []
413 seen = set()
414 for component in edition.get('sections') or ():
415 articles = []
416 section = component.get('name') or ''
417 self.log(section)
418 for article in component.get('articles') or ():
419 url = process_url(article.get('url') or '')
420 article_id = article.get('id') or url
421 title = article.get('headline') or ''
422 if not article_id or article_id in seen or not title or not url:
423 continue
424 seen.add(article_id)
425 sub = article.get('flyTitle') or ''
426 desc = article.get('rubric') or ''
427 if sub and section != sub:
428 desc = sub + (' :: ' + desc if desc else '')
429 self.log('\t', title, '\n\t', desc, '\n\t\t', url)
430 articles.append({'title': title, 'url': url, 'description': desc})
431 if articles:
432 feeds.append((section, articles))
433
434 return feeds
435
436 def preprocess_html(self, soup):
437 width = '600'
438 w = self.recipe_specific_options.get('res')
439 if w and isinstance(w, str):
440 width = w
441 for img in soup.findAll('img', src=True):
442 qua = 'economist.com/cdn-cgi/image/width=' + width + ',quality=80,format=auto/'
443 img['src'] = img['src'].replace('economist.com/', qua)
444 return soup
445
446 def preprocess_raw_html(self, raw_html, url):
447 # open('/t/raw.html', 'wb').write(raw.encode('utf-8'))
448 if '/interactive/' in url:
449 return '<html><body><article><h1>Article not available.</h1><em>This article is supposed to be read in a browser.</em></article></body></html>'
450 root_ = parse(raw_html)
451 script = root_.xpath('//script[@id="__NEXT_DATA__"]')
452 html = load_article_from_json(script[0].text)
453 root = parse(html)
454
455 for x in root.xpath('//*[name()="script" or name()="style" or name()="source" or name()="meta"]'):
456 x.getparent().remove(x)
457 # the economist uses <small> for small caps with a custom font
458 for init in root.xpath('//span[@data-caps="initial"]'):
459 init.set('style', 'font-weight:bold;')
460 for x in root.xpath('//small'):
461 if x.text and len(x) == 0:
462 x.text = x.text.upper()
463 x.tag = 'span'
464 x.set(
465 'style',
466 'text-transform: uppercase; font-size: 0.85em; letter-spacing: 0.05em;',
467 )
468 for h2 in root.xpath('//h2'):
469 h2.tag = 'h4'
470 for x in root.xpath('//figcaption'):
471 x.set('style', 'text-align:center; font-size:small;')
472 for x in root.xpath('//cite'):
473 x.tag = 'blockquote'
474 x.set('style', 'color:#404040;')
475 raw = etree.tostring(root, encoding='unicode')
476 return raw