Debian Codegraph @

recipes/discover_magazine_monthly.recipe

raw
1 #!/usr/bin/env python
2 from __future__ import unicode_literals
3
4 __license__ = 'GPL v3'
5 __copyright__ = '2015 Michael Marotta <mikefm at gmail.net>'
6 # Written April 2015
7 # Last edited 4/17/15
8 '''
9 discovermagazine.com
10 '''
11 import json
12 import re
13
14 try:
15 from http.cookiejar import Cookie
16 except ImportError:
17 from cookielib import Cookie
18 import mechanize
19
20 from calibre.web.feeds.news import BasicNewsRecipe
21
22
23 class DiscoverMagazine(BasicNewsRecipe):
24 title = 'Discover Magazine Monthly'
25 __author__ = 'Kovid Goyal'
26 description = 'Monthly magazine version of Discover Magazine (not rss feed).'
27 language = 'en'
28 encoding = 'utf-8'
29 simultaneous_downloads = 20
30 tags = 'news, technology, science'
31 INDEX = 'http://discovermagazine.com'
32
33 keep_only_tags = [
34 {'attrs': {'class': ['headline', 'deck', 'belowDeck', 'mediaContainer', 'segment', 'cover']}},
35 ]
36 remove_tags = [dict(name='div', attrs={'class': ['ladder', 'mobile', 'popular', 'open', 'scistarter']})]
37
38 # Login {{{
39 needs_subscription = True
40
41 def get_browser(self):
42 br = BasicNewsRecipe.get_browser(self)
43 rq = mechanize.Request(
44 'https://secure.kalmbach.com/kserv/api/authentication/login',
45 headers={
46 'Content-Type': 'application/json; charset=UTF-8',
47 'Referer': 'http://discovermagazine.com',
48 'Accept': 'application/json, text/javascript, */*; q=0.01',
49 'Accept-Language': 'en-US,en;q=0.5',
50 'Origin': 'http://discovermagazine.com',
51 },
52 data=json.dumps({'appId': '2', 'email': self.username, 'password': self.password}),
53 )
54 br.set_debug_http(True)
55 br.open(rq)
56 data = json.loads(br.open(rq).read())
57 if not data.get('success'):
58 raise ValueError('Failed to login')
59 session_id = data['sessionId']
60 if hasattr(br, 'set_cookie'):
61 br.set_cookie('KSERV', session_id, 'discovermagazine.com')
62 else:
63 c = Cookie(None, 'KSERV', session_id, None, False, 'discovermagazine.com', True, False, '/', True, False, None, False, None, None, None)
64 br.cookiejar.set_cookie(c)
65 res = br.open('http://discovermagazine.com')
66 br.set_debug_http(False)
67 raw = res.read()
68 if b'>Logout<' not in raw:
69 raise ValueError('Failed to login')
70 return br
71
72 # End login }}}
73
74 no_stylesheets = True
75 preprocess_regexps = [(re.compile(r'<br[ ]*/>', re.IGNORECASE), lambda m: ''), (re.compile(r'<br[ ]*clear.*/>', re.IGNORECASE), lambda m: '')]
76
77 extra_css = '''body { font-family: helvetica, sans-serif; }
78 .belowdeck {font-style: italic; padding=bottom: 10px; max-width: none}
79 .caption {font-style: italic; padding=bottom: 10px; max-width: none}
80 .caption1 {font-style: italic; padding=bottom: 10px; max-width: none}
81 h2 { text-align: left; font-size: 1em; font-weight: bold; }}'''
82
83 def parse_index(self):
84 # gets current month from homepage and append to index
85 soup = self.index_to_soup(self.INDEX)
86 c = soup.find(name=['a'], attrs={'title': ['See inside the current issue of Discover Magazine']})
87 currentMonth = self.tag_to_string(c['href'])
88 self.INDEX = self.INDEX + currentMonth
89 # continue parsing
90 soup = self.index_to_soup(self.INDEX)
91 col = soup.find(attrs={'class': 'issue'})
92 current_section, current_articles = None, []
93 feeds = []
94 # find cover
95 cover = soup.find('div', attrs={'class': 'cover'})
96 if cover is not None:
97 img = cover.find('img', src=True)
98 if img is not None:
99 self.cover_url = 'http://www.discovermagazine.com' + img['src'].replace(' ', '%20') # [:-7]
100 # parse articles
101 for tag in col.findAll(name=['h3', 'div'], attrs={'class': ['bottomBorder', 'headline']}):
102 if tag.name == 'h3':
103 if current_section and current_articles:
104 feeds.append((current_section, current_articles))
105 current_section = self.tag_to_string(tag).capitalize()
106 current_articles = []
107 self.log('Found section:', current_section)
108 elif current_section:
109 a = tag.find('a', href=True)
110 if a is not None:
111 title = self.tag_to_string(a)
112 url = 'http://www.discovermagazine.com' + a['href']
113 if title and url:
114 p = tag.find('div', attrs={'class': 'snippet'})
115 desc = self.tag_to_string(p) if p is not None else ''
116 current_articles.append({'title': title, 'url': url, 'description': desc})
117 self.log('\tArticle:', title, '[%s]' % url)
118 self.log('\t\t', desc)
119 if current_section and current_articles:
120 feeds.append((current_section, current_articles))
121 return feeds