Debian Codegraph @

recipes/economist_news.recipe

raw
1 #!/usr/bin/env python
2 # License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>
3
4 import json
5 import time
6 from datetime import datetime, timedelta
7 from urllib.parse import quote, urlencode
8 from uuid import uuid4
9
10 from html5_parser import parse
11 from lxml import etree
12 from mechanize import Request
13
14 from calibre import browser
15 from calibre.ptempfile import PersistentTemporaryFile
16 from calibre.web.feeds.news import BasicNewsRecipe
17
18
19 def safe_dict(data, *names):
20 ans = data
21 for x in names:
22 ans = ans.get(x) or {}
23 return ans
24
25
26 def process_web_list(li_node):
27 li_html = ''
28 for li in li_node['items']:
29 if li.get('textHtml'):
30 li_html += f'<li>{li["textHtml"]}</li>'
31 elif li.get('textJson'):
32 li_html += f'<li>{parse_textjson(li["textJson"])}</li>'
33 else:
34 li_html += f'<li>{li.get("text", "")}</li>'
35 return '<ul>' + li_html + '</ul>'
36
37
38 def process_info_box(bx):
39 info = ''
40 for x in safe_dict(bx, 'components'):
41 info += f'<blockquote>{process_web_node(x)}</blockquote>'
42 return info
43
44
45 def parse_txt(ty):
46 typ = ty.get('type', '')
47 children = ty.get('children', [])
48 href = '#'
49 attributes = ty.get('attributes') or ()
50 for a in attributes:
51 if a.get('name') == 'href':
52 href = a.get('value', href)
53 break
54
55 tag_map = {
56 'text': lambda: [ty.get('value', '')],
57 'scaps': lambda: [
58 f'<span style="text-transform: uppercase; font-size: 0.85em; letter-spacing: 0.05em;">{"".join(parse_txt(c))}</span>' for c in children
59 ],
60 'bold': lambda: [f'<b>{"".join(parse_txt(c))}</b>' for c in children],
61 'drop_caps': lambda: [f'<b>{"".join(parse_txt(c))}</b>' for c in children],
62 'italic': lambda: [f'<i>{"".join(parse_txt(c))}</i>' for c in children],
63 'linebreak': lambda: ['<br>'],
64 'external_link': lambda: [f'<a href="{href}">{"".join(parse_txt(c))}</a>' for c in children],
65 'internal_link': lambda: [f'<a href="{href}">{"".join(parse_txt(c))}</a>' for c in children],
66 'ufinish': lambda: [text for c in children for text in parse_txt(c)],
67 'subscript': lambda: [f'<sub>{"".join(parse_txt(c))}</sub>' for c in children],
68 'superscript': lambda: [f'<sup>{"".join(parse_txt(c))}</sup>' for c in children],
69 }
70
71 if typ in tag_map:
72 yield from tag_map[typ]()
73 else:
74 print('** ', typ)
75
76
77 def parse_textjson(nt):
78 return ''.join(''.join(parse_txt(n)) for n in nt)
79
80
81 def process_web_node(node):
82 ntype = node.get('type', '')
83 if ntype == 'CROSSHEAD':
84 if node.get('textHtml'):
85 return f'<h4>{node.get("textHtml")}</h4>'
86 return f'<h4>{node.get("text", "")}</h4>'
87 elif ntype in ['PARAGRAPH', 'BOOK_INFO']:
88 if node.get('textHtml'):
89 return f'\n<p>{node.get("textHtml")}</p>'
90 if node.get('textJson'):
91 return f'\n<p>{parse_textjson(node["textJson"])}</p>'
92 return f'\n<p>{node.get("text", "")}</p>'
93 elif (ntype == 'IMAGE') or (node.get('__typename', '') == 'ImageComponent'):
94 alt = '' if node.get('altText') is None else node.get('altText')
95 cap = ''
96 if node.get('caption'):
97 if node['caption'].get('textHtml') is not None:
98 cap = node['caption']['textHtml']
99 elif node['caption'].get('textJson') is not None:
100 cap = parse_textjson(node['caption']['textJson'])
101 elif node['caption'].get('text') is not None:
102 cap = node['caption']['text']
103 return f'<div><img src="{node["url"]}" title="{alt}"></div><div style="text-align:center; font-size:small;">{cap}</div>'
104 elif ntype == 'PULL_QUOTE':
105 if node.get('textHtml'):
106 return f'<blockquote>{node.get("textHtml")}</blockquote>'
107 if node.get('textJson'):
108 return f'<blockquote>{parse_textjson(node["textJson"])}</blockquote>'
109 return f'<blockquote>{node.get("text", "")}</blockquote>'
110 elif ntype == 'BLOCK_QUOTE':
111 if node.get('textHtml'):
112 return f'<blockquote><i>{node.get("textHtml")}</i></blockquote>'
113 if node.get('textJson'):
114 return f'<blockquote><i>{parse_textjson(node["textJson"])}</i></blockquote>'
115 return f'<blockquote><i>{node.get("text", "")}</i></blockquote>'
116 elif ntype == 'DIVIDER':
117 return '<hr>'
118 elif ntype == 'INFOGRAPHIC':
119 if node.get('fallback'):
120 return process_web_node(node['fallback'])
121 elif ntype == 'INFOBOX':
122 return process_info_box(node)
123 elif ntype == 'UNORDERED_LIST':
124 if node.get('items'):
125 return process_web_list(node)
126 elif ntype:
127 print('** ', ntype)
128 return ''
129
130
131 def load_article_from_web_json(raw):
132 # open('/t/raw.json', 'w').write(raw)
133 body = ''
134 data = json.loads(raw)['data']['findArticleByUrl']
135 body += f'<div style="color: red; font-size:small; font-weight:bold;">{data.get("flyTitle", "")}</div>'
136 body += f'<h1>{data["headline"]}</h1>'
137 if data.get('rubric') and data.get('rubric') is not None:
138 body += f'<div style="font-style: italic; color:#202020;">{data.get("rubric", "")}</div>'
139 try:
140 date = data['dateModified']
141 except Exception:
142 date = data['datePublished']
143 dt = datetime.fromisoformat(date[:-1]) + timedelta(seconds=time.timezone)
144 dt = dt.strftime('%b %d, %Y %I:%M %p')
145 if data.get('dateline') is None:
146 body += f'<p style="color: gray; font-size: small;">{dt}</p>'
147 else:
148 body += f'<p style="color: gray; font-size: small;">{dt + " | " + (data["dateline"])}</p>'
149 main_image_url = safe_dict(data, 'leadComponent') or ''
150 if main_image_url:
151 body += process_web_node(data['leadComponent'])
152 if data.get('byline'):
153 if data['byline'] is not None:
154 body += f'<p style="color: gray; font-size: small;"><i>{"By " + data["byline"]}</i></p>'
155 for node in data.get('body'):
156 body += process_web_node(node)
157 return '<html><body><article>' + body + '</article></body></html>'
158
159
160 class NoArticles(Exception):
161 pass
162
163
164 def get_content(url_):
165
166 headers = {
167 'User-Agent': 'TheEconomist-Liskov-android',
168 'accept': 'multipart/mixed; deferSpec=20220824, application/json',
169 'accept-encoding': 'gzip',
170 'content-type': 'application/json',
171 'x-app-trace-id': str(uuid4()),
172 'x-economist-consumer': 'TheEconomist-Liskov-android',
173 'x-teg-client-name': 'Economist-Android',
174 'x-teg-client-os': 'Android',
175 'x-teg-client-version': '4.40.0',
176 }
177 br = browser()
178 req = Request(
179 url_,
180 headers=headers,
181 )
182 res = br.open(req)
183 return res.read()
184
185
186 def process_url(url):
187 if url.startswith('/'):
188 url = 'https://www.economist.com' + url
189 return url
190
191
192 class EconomistNews(BasicNewsRecipe):
193 title = 'The Economist News'
194 language = 'en_GB'
195 encoding = 'utf-8'
196 masthead_url = 'https://www.livemint.com/lm-img/dev/economist-logo-oneline.png'
197
198 __author__ = 'unkn0wn'
199 description = 'Global news and current affairs from a European perspective. Get the latest articles here.'
200 extra_css = '''
201 em, blockquote { color:#202020; }
202 img {display:block; margin:0 auto;}
203 '''
204
205 cover_url = 'https://m.media-amazon.com/images/M/MV5BNzJiZGYzNzgtNWY5Yi00NWYyLThmZGUtODQyM2ZkOWVlMDI1XkEyXkFqcGc@.jpg'
206 oldest_article = 15
207 resolve_internal_links = True
208
209 # economist.com has started throttling after about 60% of the total has
210 # downloaded with connection reset by peer (104) errors.
211 delay = 1
212
213 remove_empty_feeds = True
214 ignore_duplicate_articles = {'title'}
215
216 browser_type = 'webengine'
217
218 needs_subscription = False
219
220 recipe_specific_options = {
221 'days': {
222 'short': 'Oldest article to download from this news source. In days ',
223 'long': 'For example, 0.5, gives you articles from the past 12 hours',
224 'default': str(oldest_article),
225 },
226 'res': {
227 'short': 'For hi-res images, select a resolution from the\nfollowing options: 834, 960, 1096, 1280, 1424',
228 'long': 'This is useful for non e-ink devices, and for a lower file size\nthan the default, use from 480, 384, 360, 256.',
229 'default': '600',
230 },
231 }
232
233 def __init__(self, *args, **kwargs):
234 BasicNewsRecipe.__init__(self, *args, **kwargs)
235 d = self.recipe_specific_options.get('days')
236 if d and isinstance(d, str):
237 self.oldest_article = float(d)
238
239 def get_browser(self, *args, **kwargs):
240 kwargs['user_agent'] = 'okhttp/4.12.0'
241 br = BasicNewsRecipe.get_browser(self, *args, **kwargs)
242 return br
243
244 def economist_test_article(self):
245 return [('Articles', [{'title': 'test', 'url': 'https://www.economist.com/letters/2025/07/17/the-politicisation-of-the-federal-reserve'}])]
246
247 def economist_return_index(self, ans):
248 if not ans:
249 raise NoArticles(
250 'Could not find any articles, either the '
251 'economist.com server is having trouble and you should '
252 'try later or the website format has changed and the '
253 'recipe needs to be updated.'
254 )
255 return ans
256
257 def parse_index(self):
258 # return self.economist_test_article()
259 query = {
260 'operationName': 'FindHomepage',
261 'variables': '{"homepageType":"MOBILE"}',
262 'query': 'query FindHomepage($homepageType: HomepageType!) { findHomepage(homepageType: $homepageType) { __typename ...HomepageFragment } } fragment CtaFragment on Cta { link text } fragment ContentIdentityFragment on ContentIdentity { articleType forceAppWebView leadMediaType } fragment ImageTeaserFragment on ImageComponent { altText height imageType source url width } fragment NarrationFragment on Narration { album bitrate duration filename id provider url } fragment PodcastAudioFragment on PodcastEpisode { id audio { url durationInSeconds } } fragment ArticleTeaserFragment on Article { id tegId url rubric headline flyTitle brand byline dateFirstPublished dateline dateModified datePublished dateRevised estimatedReadTime wordCount printHeadline contentIdentity { __typename ...ContentIdentityFragment } section { tegId name } teaserImage { __typename type ...ImageTeaserFragment } leadComponent { __typename type ...ImageTeaserFragment } narration { __typename ...NarrationFragment } podcast { __typename ...PodcastAudioFragment } } fragment OverridesFragment on Overrides { flyTitle headline rubric teaserImage { __typename ...ImageTeaserFragment } } fragment CollectionItemFragment on CollectionItem { __typename type ... on CollectionArticleItem { article { __typename ...ArticleTeaserFragment } overrides { __typename ...OverridesFragment } } ... on CollectionRelatedArticleItem { article { __typename ...ArticleTeaserFragment } overrides { __typename ...OverridesFragment } } ... on CollectionExternalLinkItem { url overrides { __typename ...OverridesFragment } } } fragment HomepageFragment on Homepage { components { __typename id headline type ... on StandardCollection { cta { __typename ...CtaFragment } items { __typename ...CollectionItemFragment } } ... on TakeoverCollection { cta { __typename ...CtaFragment } items { __typename ...CollectionItemFragment } } ... on DiscoverRailCollection { cta { __typename ...CtaFragment } items { __typename ...CollectionItemFragment } } ... on TopStoriesCollection { cta { __typename ...CtaFragment } items { __typename ...CollectionItemFragment } } ... on EmbedsCollection { cta { __typename ...CtaFragment } items { __typename ...CollectionItemFragment } } ... on CarouselCollection { cta { __typename ...CtaFragment } items { __typename ...CollectionItemFragment } imageLayout variant } ... on VideoCarouselCollection { cta { __typename ...CtaFragment } playlistId source fallbackStoryLink { sourceId } } ... on CoverPackageCollection { cta { __typename ...CtaFragment } items { __typename ...CollectionItemFragment } } ... on LatestEditionCollection { cta { __typename ...CtaFragment } items { __typename ...CollectionItemFragment } } ... on Newsletter { slug items { __typename ...CollectionItemFragment } } } }', # noqa: E501
263 }
264 url = 'https://cp2-graphql-gateway.p.aws.economist.com/graphql?' + urlencode(query, safe='()!', quote_via=quote)
265 raw = get_content(url)
266 ans = self.economist_parse_index(raw)
267 return self.economist_return_index(ans)
268
269 def economist_parse_index(self, raw):
270 data = json.loads(raw)['data']['findHomepage']['components']
271
272 feeds = []
273
274 for part in data:
275 if not part.get('items'):
276 continue
277 section = part.get('headline', 'Articles')
278 self.log(section)
279
280 articles = []
281
282 for art in part['items']:
283 if not art.get('article'):
284 continue
285 arts = art['article']
286 title = safe_dict(arts, 'headline')
287 desc = safe_dict(arts, 'rubric') or ''
288 sub = safe_dict(arts, 'flyTitle') or ''
289 if sub and section != sub:
290 desc = sub + ' :: ' + desc
291 date_ = arts['datePublished']
292 dt = datetime.fromisoformat(date_[:-1]) + timedelta(seconds=time.timezone)
293 if (datetime.now() - dt) > timedelta(self.oldest_article):
294 continue
295 url = process_url(arts['url'])
296 articles.append({'title': title, 'url': url, 'description': desc})
297 self.log('\t', title, '\n\t\t', desc)
298 if articles:
299 feeds.append((section, articles))
300 return feeds
301
302 def preprocess_html(self, soup):
303 width = '600'
304 w = self.recipe_specific_options.get('res')
305 if w and isinstance(w, str):
306 width = w
307 for img in soup.findAll('img', src=True):
308 qua = 'economist.com/cdn-cgi/image/width=' + width + ',quality=80,format=auto/'
309 img['src'] = img['src'].replace('economist.com/', qua)
310 return soup
311
312 def preprocess_raw_html(self, raw, url):
313 # open('/t/raw.html', 'wb').write(raw.encode('utf-8'))
314 html = load_article_from_web_json(raw)
315 root = parse(html)
316 # the economist uses <small> for small caps with a custom font
317 for init in root.xpath('//span[@data-caps="initial"]'):
318 init.set('style', 'font-weight:bold;')
319 for x in root.xpath('//small'):
320 if x.text and len(x) == 0:
321 x.text = x.text.upper()
322 x.tag = 'span'
323 x.set('style', 'text-transform: uppercase; font-size: 0.85em; letter-spacing: 0.05em;')
324 for h2 in root.xpath('//h2'):
325 h2.tag = 'h4'
326 for x in root.xpath('//figcaption'):
327 x.set('style', 'text-align:center; font-size:small;')
328 for x in root.xpath('//cite'):
329 x.tag = 'blockquote'
330 x.set('style', 'color:#404040;')
331 raw = etree.tostring(root, encoding='unicode')
332 return raw
333
334 def get_article(self, url):
335 query = {
336 'operationName': 'ArticleDeeplinkQuery',
337 'variables': '{{"ref":"{}"}}'.format(url),
338 'query': 'query ArticleDeeplinkQuery($ref: String!, $includeRelatedArticles: Boolean = true ) { findArticleByUrl(url: $ref) { __typename ...ArticleDataFragment } } fragment ContentIdentityFragment on ContentIdentity { articleType forceAppWebView leadMediaType } fragment NarrationFragment on Narration { album bitrate duration filename id provider url isAiGenerated fileHash } fragment ImageTeaserFragment on ImageComponent { altText height imageType source url width } fragment PodcastAudioFragment on PodcastEpisode { id audio { url durationInSeconds } } fragment ArticleTeaserFragment on Article { id tegId url rubric headline flyTitle brand byline dateFirstPublished dateline dateModified datePublished dateRevised estimatedReadTime wordCount printHeadline contentIdentity { __typename ...ContentIdentityFragment } section { tegId name } teaserImage { __typename type ...ImageTeaserFragment } leadComponent { __typename type ...ImageTeaserFragment } narration(selectionMethod: PREFER_ACTOR_NARRATION) { __typename ...NarrationFragment } podcast { __typename ...PodcastAudioFragment } } fragment AnnotatedTextFragment on AnnotatedText { text textJson annotations { type length index attributes { name value } } } fragment ImageComponentFragment on ImageComponent { altText caption { __typename ...AnnotatedTextFragment } credit height imageType mode source url width } fragment BlockQuoteComponentFragment on BlockQuoteComponent { text textJson annotations { type length index attributes { name value } } } fragment BookInfoComponentFragment on BookInfoComponent { text textJson annotations { type length index attributes { name value } } } fragment ParagraphComponentFragment on ParagraphComponent { text textJson annotations { type length index attributes { name value } } } fragment PullQuoteComponentFragment on PullQuoteComponent { text textJson annotations { type length index attributes { name value } } } fragment CrossheadComponentFragment on CrossheadComponent { text } fragment OrderedListComponentFragment on OrderedListComponent { items { __typename ...AnnotatedTextFragment } } fragment UnorderedListComponentFragment on UnorderedListComponent { items { __typename ...AnnotatedTextFragment } } fragment VideoComponentFragment on VideoComponent { url title thumbnailImage } fragment InfoboxComponentFragment on InfoboxComponent { components { __typename type ...BlockQuoteComponentFragment ...BookInfoComponentFragment ...ParagraphComponentFragment ...PullQuoteComponentFragment ...CrossheadComponentFragment ...OrderedListComponentFragment ...UnorderedListComponentFragment ...VideoComponentFragment } } fragment InfographicComponentFragment on InfographicComponent { url title width fallback { __typename ...ImageComponentFragment } altText height width } fragment ArticleDataFragment on Article { id url brand byline rubric headline layout { headerStyle } contentIdentity { __typename ...ContentIdentityFragment } dateline dateFirstPublished dateModified datePublished dateRevised estimatedReadTime narration(selectionMethod: PREFER_ACTOR_NARRATION) { __typename ...NarrationFragment } printFlyTitle printHeadline printRubric flyTitle wordCount section { tegId name articles(pagingInfo: { pagingType: OFFSET pageSize: 6 pageNumber: 1 } ) @include(if: $includeRelatedArticles) { edges { node { __typename ...ArticleTeaserFragment } } } } teaserImage { __typename type ...ImageComponentFragment } tegId leadComponent { __typename type ...ImageComponentFragment } body { __typename type ...BlockQuoteComponentFragment ...BookInfoComponentFragment ...ParagraphComponentFragment ...PullQuoteComponentFragment ...CrossheadComponentFragment ...OrderedListComponentFragment ...UnorderedListComponentFragment ...InfoboxComponentFragment ...ImageComponentFragment ...VideoComponentFragment ...InfographicComponentFragment } footer { __typename type ...ParagraphComponentFragment } tags { name } ads { adData } podcast { __typename ...PodcastAudioFragment } }', # noqa: E501
339 }
340 deep_url = 'https://cp2-graphql-gateway.p.aws.economist.com/graphql?' + urlencode(query, safe='()!', quote_via=quote)
341 raw = get_content(deep_url)
342 return raw
343
344 def print_version(self, url):
345 art_cont = self.get_article(url)
346 pt = PersistentTemporaryFile('.html')
347 pt.write(art_cont)
348 pt.close()
349 return 'file:///' + pt.name