Debian Codegraph @

recipes/wsj_news.recipe

raw
1 #!/usr/bin/env python
2 # vim:fileencoding=utf-8
3 import json
4 import time
5 from datetime import datetime, timedelta
6 from itertools import zip_longest
7
8 from calibre.ebooks.BeautifulSoup import BeautifulSoup
9 from calibre.web.feeds.news import BasicNewsRecipe, classes
10
11
12 class WSJ(BasicNewsRecipe):
13 title = 'WSJ News'
14 __author__ = 'unkn0wn'
15 description = (
16 'The Wall Street Journal is your source for breaking news, analysis and insights from the U.S. and '
17 "around the world, the world's leading business and finance publication. Get the Latest News here."
18 )
19 language = 'en_US'
20 masthead_url = 'https://s.wsj.net/media/wsj_amp_masthead_lg.png'
21 encoding = 'utf-8'
22 no_javascript = True
23 no_stylesheets = True
24 remove_attributes = ['style', 'height', 'width']
25 resolve_internal_links = True
26 ignore_duplicate_articles = {'url', 'title'}
27 remove_empty_feeds = True
28 oldest_article = 1.2 # days
29
30 recipe_specific_options = {
31 'days': {
32 'short': 'Oldest article to download from this news source. In days ',
33 'long': 'For example, 0.5, gives you articles from the past 12 hours',
34 'default': str(oldest_article),
35 },
36 'res': {
37 'short': 'For hi-res images, select a resolution from the\nfollowing options: 800, 1000, 1200 or 1500',
38 'long': 'This is useful for non e-ink devices, and for a lower file size\nthan the default, use 400 or 300.',
39 'default': '600',
40 },
41 }
42
43 def __init__(self, *args, **kwargs):
44 BasicNewsRecipe.__init__(self, *args, **kwargs)
45 d = self.recipe_specific_options.get('days')
46 if d and isinstance(d, str):
47 self.oldest_article = float(d)
48
49 extra_css = '''
50 #subhed, em { font-style:italic; color:#202020; }
51 #byline, #time-to-read, #orig-pubdate-string, .article-byline, time, #flashline { font-size:small; }
52 .figc { font-size:small; text-align:center; }
53 img {display:block; margin:0 auto;}
54 '''
55
56 remove_tags = [
57 dict(name='panel', attrs={'id': 'summary-image'}),
58 dict(name='panel', attrs={'layout': 'inline'}),
59 dict(name='panel', attrs={'embed': 'inner-article-ad'}),
60 dict(name='span', attrs={'embed': 'ticker'}),
61 classes('lamrelated-articles-inset-panel'),
62 dict(
63 name='p',
64 attrs={
65 'id': [
66 'keywords',
67 'orig-pubdate-number',
68 'type',
69 'is-custom-flashline',
70 'grouphed',
71 'author-ids',
72 'article-manifest',
73 'body-extract',
74 'category',
75 'sub-category',
76 'socialhed',
77 'summary',
78 'deckline',
79 'article-flashline',
80 ]
81 },
82 ),
83 ]
84
85 remove_tags_before = [dict(name='p', attrs={'id': 'orig-pubdate-string'})]
86
87 def media_bucket(self, x):
88 res = '?width=600'
89 w = self.recipe_specific_options.get('res')
90 if w and isinstance(w, str):
91 res = '?width=' + w
92 if x.get('type', '') == 'image':
93 if x.get('subtype', '') == 'graphic' or 'images.wsj.net' not in x['manifest-url']:
94 return '<br><img src="{}"><div class="figc">{}</div>\n'.format(x['manifest-url'], x['caption'] + '<i> ' + x['credit'] + '</i>')
95 return '<br><img src="{}"><div class="figc">{}</div>\n'.format(x['manifest-url'].split('?')[0] + res, x['caption'] + '<i> ' + x['credit'] + '</i>')
96 if x.get('type', '') == 'video':
97 return '<br><a href="{}"><img src="{}"></a><div class="figc">{}</div>\n'.format(
98 x['share_link'], x['thumbnail_url'].split('?')[0] + res, x['caption'] + '<i> ' + x['credit'] + '</i>'
99 )
100 return
101
102 def preprocess_html(self, soup):
103 jpml = soup.find('jpml')
104 if jpml:
105 jpml.name = 'article'
106 h1 = soup.find('p', attrs={'id': 'headline'})
107 if h1:
108 h1.name = 'h1'
109 for h2 in soup.findAll('h2'):
110 h2.name = 'h4'
111 dt = soup.find('p', attrs={'id': 'orig-pubdate-string'})
112 read = soup.find('p', attrs={'id': 'time-to-read'})
113 byl = soup.find('p', attrs={'id': 'byline'})
114 fl = soup.find('p', attrs={'id': 'flashline'})
115 if dt and byl and read and fl:
116 dt.name = read.name = byl.name = fl.name = 'div'
117 byl.insert(0, dt)
118 byl.insert(0, read)
119 url = soup.find('p', attrs={'id': 'share-link'})
120 if url:
121 url.name = 'div'
122 url['title'] = self.tag_to_string(url).strip()
123 url.string = ''
124 panel = soup.find('panel', attrs={'id': 'metadata'})
125 if panel:
126 buck = panel.find('p', attrs={'id': 'media-bucket'})
127 if buck:
128 data = json.loads(buck.string)
129 buck.extract()
130 i_lst = [self.media_bucket(x) for x in data['items']]
131 m_itm = soup.findAll('panel', attrs={'class': 'media-item'})
132 if i_lst and m_itm:
133 for x, y in list(zip_longest(m_itm, i_lst)):
134 x.insert_after(BeautifulSoup(y, 'html.parser'))
135 return soup
136
137 def postprocess_html(self, soup, first_fetch):
138 for pan in soup.findAll('panel'):
139 pan.name = 'div'
140 return soup
141
142 def _download_cover(self):
143 import os
144 from contextlib import closing
145
146 from calibre import browser
147 from calibre.utils.img import save_cover_data_to
148
149 br = browser()
150 raw = br.open('https://frontpages.freedomforum.org/newspapers/wsj-The_Wall_Street_Journal')
151 soup = BeautifulSoup(raw.read())
152 cu = soup.find(
153 'img',
154 attrs={
155 'alt': 'Front Page Image',
156 'src': lambda x: x and x.endswith('front-page-large.jpg'),
157 },
158 )['src'].replace('-large', '-medium')
159 self.report_progress(1, _('Downloading cover from %s') % cu)
160 with closing(br.open(cu, timeout=self.timeout)) as r:
161 cdata = r.read()
162 cpath = os.path.join(self.output_dir, 'cover.jpg')
163 save_cover_data_to(cdata, cpath)
164 self.cover_path = cpath
165
166 def get_browser(self, *args, **kw):
167 kw['user_agent'] = 'okhttp/4.10.0'
168 br = BasicNewsRecipe.get_browser(self, *args, **kw)
169 br.addheaders += [
170 ('Accept-Encoding', 'gzip'),
171 ('cache-control', 'no-cache'),
172 ('x-api-key', ('eb2408cd27f8913d421fa3d5c3d07ccf034cb448')), # noqa: ISC001
173 ]
174 return br
175
176 def parse_index(self):
177 index = 'https://bartender.mobile.dowjones.io'
178 catalog = json.loads(self.index_to_soup(index + '/catalogs/v1/wsj/us/catalog.json', raw=True))
179 for itm in catalog['items']:
180 if itm['key'] == 'NOW':
181 manifest = itm['manifest']
182 break
183
184 feeds = []
185
186 manif = json.loads(self.index_to_soup(index + manifest, raw=True))
187 for itm in manif['items']:
188 for k, v in itm.items():
189 if '-pages_' in k:
190 section = k.split('-pages_')[0].replace('_', ' ')
191 self.log(section)
192
193 articles = []
194
195 sec_parse = json.loads(self.index_to_soup(index + v, raw=True))
196 data = sec_parse['articles']
197 for art in data:
198 try:
199 tme = data[art]['pubdateNumber']
200 except Exception:
201 tme = data[art]['origPubdateNumber']
202 dt = datetime.fromtimestamp(tme + time.timezone)
203 if (datetime.now() - dt) > timedelta(self.oldest_article):
204 continue
205 title = data[art]['headline']
206 desc = data[art]['summary']
207 url = index + manifest.rsplit('/', 1)[0] + '/' + data[art]['filename']
208 self.log(' ', title, '\n\t', desc)
209 articles.append({'title': title, 'description': desc, 'url': url})
210 feeds.append((section, articles))
211 return feeds
212
213 def preprocess_raw_html(self, raw, url):
214 return BeautifulSoup(raw).prettify()
215
216 def populate_article_metadata(self, article, soup, first):
217 lnk = soup.find('div', attrs={'id': 'share-link'})
218 if lnk:
219 article.url = lnk['title']