Debian Codegraph @

recipes/irish_times.recipe

raw
1 #!/usr/bin/env python
2 __license__ = 'GPL v3'
3 __copyright__ = "2008, Derry FitzGerald. 2009 Modified by Ray Kinsella and David O'Callaghan, 2011 Modified by Phil Burns, 2013 Tom Scholl, 2016 by leo738"
4 '''
5 irishtimes.com
6 '''
7 import json
8 from uuid import uuid4
9
10 from mechanize import Request
11
12 try:
13 from urllib.parse import urlencode
14 except ImportError:
15 from urllib import urlencode
16
17 from calibre.web.feeds.news import BasicNewsRecipe, classes
18
19
20 class IrishTimes(BasicNewsRecipe):
21 title = 'The Irish Times'
22 __author__ = "Derry FitzGerald, Ray Kinsella, David O'Callaghan, Phil Burns, Tom Scholl, unkn0wn"
23 description = 'Daily news from The Irish Times'
24 needs_subscription = True
25
26 language = 'en_IE'
27
28 masthead_url = 'http://www.irishtimes.com/assets/images/generic/website/logo_theirishtimes.png'
29
30 encoding = 'utf-8'
31 oldest_article = 1.0
32 max_articles_per_feed = 100
33 simultaneous_downloads = 5
34 remove_empty_feeds = True
35 no_stylesheets = True
36 temp_files = []
37
38 keep_only_tags = [
39 classes('b-it-headline b-it-subheadline b-it-byline-block__text b-it-lead-art__wrapper b-it-article-body'),
40 ]
41
42 remove_tags_after = [
43 classes('b-it-article-body'),
44 ]
45
46 remove_tags = [
47 dict(name=['button', 'svg']),
48 classes('b-top-table-list arcad-feature c-unordered-list b-it-article-body__podcast'),
49 ]
50
51 remove_attributes = ['width', 'height', 'style']
52 ignore_duplicate_articles = {'title', 'url'}
53 resolve_internal_links = True
54
55 def get_cover_url(self):
56 soup = self.index_to_soup('https://www.frontpages.com/ireland-newspapers/')
57 for img in soup.findAll('img', src=True):
58 if 'irish-times' in img['src']:
59 return 'https://www.frontpages.com' + img['src']
60
61 def parse_index(self):
62 soup = self.index_to_soup('https://www.irishtimes.com/')
63 section = 'Home page'
64 articles = []
65 feeds = []
66 for x in soup.findAll(name=['h3', 'article']):
67 if x.name == 'h3':
68 if 'writer_description' in x.get('class') or '':
69 continue
70 articles and feeds.append((section, articles))
71 section = self.tag_to_string(x)
72 articles = []
73 self.log('Section:', section)
74 continue
75 a = x.find('a', attrs={'class': lambda x: x and 'primary-font'}, href=True)
76 if a is None:
77 a = x.find('a', attrs={'class': lambda x: x and 'promo-headline' in x}, href=True)
78 if a:
79 q = ''.join(a['class'])
80 if 'secondary-font' in q and section == 'Home page':
81 continue
82 title = self.tag_to_string(a)
83 url = a['href']
84 if url.startswith('/'):
85 url = 'https://www.irishtimes.com' + url
86 articles.append({'title': title, 'url': url})
87 self.log('\t', title)
88 articles and feeds.append((section, articles))
89 return feeds
90
91 def get_browser(self):
92 # To understand the signin logic read signin javascript from submit button from
93 # https://www.irishtimes.com/signin
94
95 br = BasicNewsRecipe.get_browser(self, user_agent='curl/7.80.0')
96 ip_data = json.loads(br.open('https://ipapi.co//json').read())
97 br = BasicNewsRecipe.get_browser(self)
98 url = 'https://www.irishtimes.com/signin'
99 deviceid = str(uuid4()).replace('-', '')
100 # Enable debug stuff?
101 # br.set_debug_http(True)
102 br.open(url).read()
103 from pprint import pprint
104
105 pprint(ip_data)
106 br.set_cookie('IT_country', ip_data['country_code'], '.irishtimes.com')
107 br.set_cookie('IT_eu', 'true' if ip_data['in_eu'] else 'false', '.irishtimes.com')
108 rurl = 'https://www.irishtimes.com/auth-rest-api/v1/paywall/login'
109 rq = Request(
110 rurl,
111 headers={
112 'Accept': '*/*',
113 'Accept-Language': 'en-US,en;q=0.5',
114 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
115 'Origin': 'https://www.irishtimes.com',
116 'Referer': url,
117 'X-Requested-With': 'XMLHttpRequest',
118 'sec-fetch-site': 'same-origin',
119 'sec-fetch-dest': 'empty',
120 'sec-fetch-mode': 'cors',
121 },
122 data=urlencode({'username': self.username, 'password': self.password, 'deviceid': deviceid, 'persistent': 'on', 'rid': ''}),
123 )
124
125 r = br.open(rq)
126 raw = r.read()
127 data = json.loads(raw)
128 # print(data)
129 if r.code != 200 or b'user_id' not in raw:
130 pprint(data)
131 raise ValueError('Failed to log in check username/password')
132
133 # Set cookie
134 br.set_cookie('IT_PW_AUTH', data['varnish_id'], '.irishtimes.com')
135
136 # br.set_debug_http(False)
137 return br
138
139 def preprocess_html(self, soup):
140 h2 = soup.find(**classes('b-it-subheadline'))
141 if h2:
142 h2.name = 'p'
143 for img in soup.findAll('img', attrs={'srcset': True}):
144 img['src'] = img['srcset'].split()[0]
145 return soup