Debian Codegraph @

recipes/barrons.recipe

raw
1 #!/usr/bin/env python
2 # vim:fileencoding=utf-8
3
4 import base64
5 import json
6 import re
7 from collections import defaultdict
8
9 from calibre.web.feeds.news import BasicNewsRecipe
10
11
12 def range(r_, otxt):
13 return otxt[r_['rangeStart'] : r_['rangeStart'] + r_['rangeLength']]
14
15
16 def make_hlinks(zx):
17 otxt = zx['body']['text']
18 txt = otxt
19 if zx['body'].get('inlineTextStyles'):
20 for sty in zx['body']['inlineTextStyles']:
21 rtxt = range(sty, otxt)
22 if 'Italic' in sty['textStyle']['fontName']:
23 txt = txt.replace(rtxt, f'<em>{rtxt}</em>')
24 if 'Bold' in sty['textStyle']['fontName']:
25 txt = txt.replace(rtxt, f'<b>{rtxt}</b>')
26 if sty['textStyle'].get('fontSize', '') == 16:
27 txt = txt.replace(rtxt, f'<b><u>{rtxt}</u></b>')
28 if zx['body'].get('additions'):
29 for ad in zx['body']['additions']:
30 if ad.get('type', '') == 'link' and ad.get('value'):
31 n_txt = range(ad, otxt)
32 lnk = ad['value']
33 lnk_txt = f'<a href="{lnk}">{n_txt}</a>'
34 txt = txt.replace(n_txt, lnk_txt)
35 return txt.replace('\n', '<br>')
36
37
38 def make_html(a):
39 typ = a.get('type', '')
40 if typ == 'byline':
41 if 'article-logo' in a['byline'].get('textStyleID', ''):
42 return ''
43 st = ' style="font-size:small;"'
44 return f'<div {st}>{a["byline"]["text"]}</div>'
45 if typ == 'title':
46 return f'<h1>{a["title"]["text"]}</h1>'
47 if typ == 'body':
48 if 'body-h' in a['body'].get('textStyleID', ''):
49 return f'<h4>{a["body"]["text"]}</h4>'
50 if 'article-summary' in a['body'].get('textStyleID', ''):
51 return f'<p><i>{a["body"]["text"]}</i></p>'
52 return f'<p>{make_hlinks(a)}</p>'
53 if typ == 'image':
54 return f'<img src={a["image"]["url"]}>'
55 if typ == 'caption':
56 st = ' style="font-size:small; text-align: center;"'
57 return f'<div {st}>{a["caption"]["text"]}</div>'
58 if typ == 'listelement':
59 return f'<li>{make_hlinks(a)}</li>'
60 if typ == 'dynamicinset':
61 if a.get('webview') and 'datawrapper-chart-' in a['webview']['value']:
62 dw = re.search(r'datawrapper-chart-(.{5})', a['webview']['value']).group(1)
63 return f'<img src=https://datawrapper.dwcdn.net/{dw}/full.png>'
64 return ''
65
66
67 keys = [
68 'ZXlKaGJHY2lPaUpTVXpJMU5pSjk=',
69 'V0Zac2FITjNNWGQzU213MFYza3dSWEJ6Y2xR',
70 'cXd3QmVkQVVOWEhUUWNob3dRWjV6TXdtblhxREtlTWhvUkpsa0I3ZHJqV21iMGt0WkNTY0locTVscElpV2FNeU5KQQ==',
71 'T0RZZ0hBZklvaTdES1drUzhnOEd1bkZOQVhwSkRVT0xkSTJydFFrVEVp',
72 'RTNvOTByZFpIdW5QUjdwMFVMalJtSENuRG9mQWRwVFFkSnRUWGpROWVFRFpUMnhvb29WR2RCcG9WS2hF',
73 ]
74
75
76 class Barrons(BasicNewsRecipe):
77 title = "Barron's Magazine"
78 __author__ = 'unkn0wn'
79 description = (
80 "Barron's is an American weekly magazine/newspaper published by Dow Jones & Company. Founded in 1921 as a sister "
81 "publication to The Wall Street Journal, Barron's covers U.S. financial information, market developments, and "
82 'relevant statistics.'
83 )
84 language = 'en_US'
85 encoding = 'utf-8'
86 ignore_duplicate_articles = {'url'}
87 masthead_url = 'https://www.barrons.com/asset/barrons/images/barrons-logo.png'
88 resolve_internal_links = True
89 delay = 0.5
90
91 recipe_specific_options = {
92 'date': {
93 'short': 'The date of the edition to download (MMM DD, YYYY format)',
94 'long': 'For example, Dec 30, 2024',
95 },
96 }
97
98 def parse_index(self):
99 index = 'https://barrons.djmedia.djservices.io'
100 theatre = '/apps/barrons/theaters/'
101 archive = self.index_to_soup(
102 index + theatre + 'magazine-archive?screen_ids=magazine-archive',
103 raw=True,
104 )
105
106 scrn = json.loads(archive)['screens'][0]['frames']
107 self.log(
108 'Available Editions: ',
109 ' | '.join(x['screenIds'][0]['name'][6:] for x in scrn),
110 )
111 for frme in scrn:
112 edition_date = self.recipe_specific_options.get('date')
113 if edition_date and isinstance(edition_date, str):
114 nme = frme['screenIds'][0]['name']
115 if edition_date.lower() not in nme.lower():
116 continue
117 nme = frme['screenIds'][0]['name']
118 cid = frme['screenIds'][0]['id']
119 bseurl = frme['baseUrl']
120 self.cover_url = frme['image']['url']
121 self.log('Downloading ', nme)
122 self.timefmt = ' [' + nme[6:] + ']'
123 break
124
125 feeds_dict = defaultdict(list)
126
127 data = json.loads(self.index_to_soup(index + bseurl, raw=True))
128 for x in data['screens'][0]['frames']:
129 if x['type'] != 'article':
130 continue
131 url = index + theatre + cid + '?screen_ids=' + x['articleId']
132 title = x['title']['text']
133 section = 'Articles'
134 if x.get('label'):
135 section = x['label'].get('text', 'Articles').split('|')[0].strip()
136 desc = ''
137 if x.get('summary'):
138 desc = x['summary']['text']
139 if x.get('byline'):
140 desc = x['byline']['text'] + ' | ' + desc
141 self.log(' ', title, '\n\t', desc)
142 feeds_dict[section].append({'title': title, 'url': url, 'description': desc})
143 return list(feeds_dict.items())
144
145 def preprocess_raw_html(self, raw, url):
146 rdata = json.loads(raw)
147 body = ''
148 for x in rdata['screens'][0]['frames']:
149 body += '\n' + make_html(x)
150 return '<html><body>' + body.replace(' _', '') + '</body></html>'
151
152 def get_browser(self, *args, **kw):
153 kw['user_agent'] = 'okhttp/4.12.0'
154 br = BasicNewsRecipe.get_browser(self, *args, **kw)
155 k2 = '.'.join(base64.b64decode(b).decode() for b in keys[:3])
156 k3 = '_'.join(base64.b64decode(v).decode() for v in keys[3:])
157 br.addheaders += [
158 ('Accept-Encoding', 'gzip'),
159 ('App-Identifier', 'com.news.screens'),
160 ('App-Version', 1),
161 ('Device-Type', 'phone'),
162 ('Os-Name', 'Android'),
163 ('X-Access-Token', k2 + '_' + k3),
164 ]
165 return br
166
167 def populate_article_metadata(self, article, soup, first):
168 article.url = 'https://www.barrons.com/articles/' + article.url.split('=')[-1]