This repository has been archived by the owner on Jun 27, 2023. It is now read-only.
/
utils.py
232 lines (177 loc) · 6.2 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import re
import hashlib
import urlparse
import json
from datetime import datetime
import feedparser
import requests
from lxml import etree
from goose import Goose
from feedgen.feed import FeedGenerator
from cache import pylibmc_client
TITLES_FOR_ERROR_PAGES = [
'301 moved permanently',
'302 found',
'303 see other',
'307 temporary redirect',
'400 bad request',
'401 authorization required',
'402 payment required',
'403 forbidden',
'404 not found',
'405 not allowed',
'406 not acceptable',
'409 conflict',
'410 gone',
'411 length required',
'412 precondition failed',
'413 request entity too large',
'415 unsupported media type',
'416 requested range not satisfiable',
'400 request header or cookie too large',
'400 the ssl certificate error',
'400 no required ssl certificate was sent',
'400 the plain http request was sent to https port',
'500 internal server error',
'501 not implemented',
'502 bad gateway',
'503 service temporarily unavailable',
'507 insufficient storage'
]
def generate_key_for_text(text):
return hashlib.sha512(text).hexdigest()
def fetch_title_for_url(url):
try:
response = requests.get(url)
root = etree.HTML(response.text)
title = root.find(".//title").text
if response.status_code != 200 or title.lower().strip() in TITLES_FOR_ERROR_PAGES:
return ''
return title
except:
return ''
def fetch_content_for_url(url):
try:
g = Goose()
article = g.extract(url=url)
return article.cleaned_text
except:
return ''
def get_title_for_url(url):
key = generate_key_for_text(url)
# get from cache
title = pylibmc_client.get(key)
if title is None:
title = fetch_title_for_url(url)
pylibmc_client.set(key, title, time=0)
return title
def get_content_for_url(url):
key = "content:{}".format(generate_key_for_text(url))
# get from cache
content = pylibmc_client.get(key)
if content is None:
content = fetch_content_for_url(url)
pylibmc_client.set(key, content, time=0)
return content
def _filter_fb_rss_feeed(url):
parsed_feed = feedparser.parse(url)
filtered_entries = filter(
lambda x: ' shared a link: "' in x.title, parsed_feed.entries)
fg = FeedGenerator()
fg.id('https://fb-notifications-to-pocket.herokuapp.com/')
fg.title('Facebook Notifications to Pocket')
fg.author({'name': 'Pankaj Singh', 'email': 'psjinx@gmail.com'})
fg.description(
'''Filter FB notifications which contain a link and generate a new rss feed which will be used by IFTTT''')
fg.link(href='https://fb-notifications-to-pocket.herokuapp.com/')
for entry in filtered_entries:
root = etree.HTML(entry.summary_detail.value)
title = entry.title.split(" shared a link: ")[1].strip()[1:-2]
author_name = entry.title.split(" shared a link: ")[0].strip()
url = urlparse.parse_qs(
urlparse.urlparse(root.findall(".//a")[-1].attrib["href"]).query)["u"][0]
title = get_title_for_url(url) or title
fe = fg.add_entry()
fe.id(entry.id)
fe.link(href=url)
fe.published(entry.published)
fe.author({'name': author_name})
fe.title(title)
return fg.atom_str(pretty=True)
def filter_fb_rss_feeed(url):
key = generate_key_for_text(url)
# get from cache
atom_str = pylibmc_client.get(key)
if atom_str is None:
atom_str = _filter_fb_rss_feeed(url)
pylibmc_client.set(key, atom_str, time=600)
return atom_str
def _extract_links_from_a_tweet(url):
response = requests.get(url)
if response.status_code != 200:
return []
root = etree.HTML(response.text)
try:
p = root.xpath(".//p[@class='js-tweet-text tweet-text']")[0]
except IndexError:
return []
links = map(lambda a: a.attrib["data-expanded-url"], p.xpath(".//a[@rel='nofollow']"))
return links
def extract_links_from_a_tweet(url):
key = "tweet:{}".format(generate_key_for_text(url))
# get from cache
links_json = pylibmc_client.get(key)
if links_json is None:
links = _extract_links_from_a_tweet(url)
links_json = json.dumps(links)
pylibmc_client.set(key, links_json, time=0)
else:
links = json.loads(links_json)
return links
def get_twitter_handle_from_twitrss_cdata(s):
try:
return re.findall(r"<!\[CDATA\[@([\w]+):\s+", s)[0]
except:
return ''
def _transform_twitrss_feed_to_link_feed(url):
# Add timestamp to url
# This will disable caching
url = "{}&replies={}&replies=off".format(url, datetime.now().toordinal())
parsed_feed = feedparser.parse(url)
fg = FeedGenerator()
fg.id('https://fb-notifications-to-pocket.herokuapp.com/')
fg.title('Twitter Feed to Pocket')
fg.author({'name': 'Pankaj Singh', 'email': 'psjinx@gmail.com'})
fg.description(
'''Transform TwitRSS.me feed to a new rss feed which will be used by IFTTT''')
fg.link(href='https://fb-notifications-to-pocket.herokuapp.com/')
all_links = []
for entry in parsed_feed.entries:
links = extract_links_from_a_tweet(entry.link)
if not links:
continue
for link in links:
if link in all_links:
continue
else:
all_links.append(link)
title = get_title_for_url(link) or entry.title
# content = get_content_for_url(link) or entry.content
author_name = get_twitter_handle_from_twitrss_cdata(entry.title)
fe = fg.add_entry()
id = generate_key_for_text(link)
fe.id(id)
fe.link(href=link)
fe.published(entry.published)
fe.author({'name': author_name})
fe.title(title)
# fe.content(content)
return fg.atom_str(pretty=True)
def transform_twitrss_feed_to_link_feed(url):
key = generate_key_for_text(url)
# get from cache
atom_str = pylibmc_client.get(key)
if atom_str is None:
atom_str = _transform_twitrss_feed_to_link_feed(url)
pylibmc_client.set(key, atom_str, time=300)
return atom_str