qotnews/apiserver/feed.py

129 lines
4.2 KiB
Python
Raw Normal View History

2019-08-24 08:49:11 +00:00
import logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.DEBUG)
2019-08-24 08:49:11 +00:00
import requests
2019-08-25 23:49:08 +00:00
import time
2019-10-19 07:33:06 +00:00
from bs4 import BeautifulSoup
2019-08-24 08:49:11 +00:00
import settings
2020-12-12 05:26:33 +00:00
from feeds import hackernews, reddit, tildes, manual, lobsters
2019-08-24 08:49:11 +00:00
2020-11-19 21:37:59 +00:00
INVALID_DOMAINS = ['youtube.com', 'bloomberg.com', 'wsj.com', 'sec.gov']
2019-11-08 21:50:33 +00:00
TWO_DAYS = 60*60*24*2
2019-08-24 08:49:11 +00:00
def list():
feed = []
if settings.NUM_HACKERNEWS:
feed += [(x, 'hackernews') for x in hackernews.feed()[:settings.NUM_HACKERNEWS]]
2020-12-12 05:26:33 +00:00
if settings.NUM_LOBSTERS:
feed += [(x, 'lobsters') for x in lobsters.feed()[:settings.NUM_LOBSTERS]]
if settings.NUM_REDDIT:
feed += [(x, 'reddit') for x in reddit.feed()[:settings.NUM_REDDIT]]
if settings.NUM_TILDES:
feed += [(x, 'tildes') for x in tildes.feed()[:settings.NUM_TILDES]]
2019-08-24 08:49:11 +00:00
return feed
def get_article(url):
2022-03-05 22:04:25 +00:00
if not settings.READER_URL:
logging.info('Readerserver not configured, aborting.')
return ''
if url.startswith('https://twitter.com'):
logging.info('Replacing twitter.com url with nitter.net')
url = url.replace('twitter.com', 'nitter.net')
2019-08-24 08:49:11 +00:00
try:
2022-03-05 22:04:25 +00:00
r = requests.post(settings.READER_URL, data=dict(url=url), timeout=20)
2019-08-24 08:49:11 +00:00
if r.status_code != 200:
2019-08-25 23:49:08 +00:00
raise Exception('Bad response code ' + str(r.status_code))
2019-08-24 08:49:11 +00:00
return r.text
except KeyboardInterrupt:
raise
2019-08-24 08:49:11 +00:00
except BaseException as e:
logging.error('Problem getting article: {}'.format(str(e)))
return ''
2020-06-25 23:36:47 +00:00
def get_content_type(url):
try:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0'}
2020-11-03 20:27:43 +00:00
return requests.get(url, headers=headers, timeout=5).headers['content-type']
2020-06-25 23:36:47 +00:00
except:
return ''
try:
headers = {
'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'X-Forwarded-For': '66.249.66.1',
}
2020-08-14 03:57:43 +00:00
return requests.get(url, headers=headers, timeout=10).headers['content-type']
except:
pass
2020-06-25 23:36:47 +00:00
def update_story(story, is_manual=False):
2019-08-24 08:49:11 +00:00
res = {}
2024-03-16 20:41:24 +00:00
try:
if story['source'] == 'hackernews':
res = hackernews.story(story['ref'])
elif story['source'] == 'lobsters':
res = lobsters.story(story['ref'])
elif story['source'] == 'reddit':
res = reddit.story(story['ref'])
elif story['source'] == 'tildes':
res = tildes.story(story['ref'])
elif story['source'] == 'manual':
res = manual.story(story['ref'])
except BaseException as e:
utils.alert_tanner('Problem updating {} story, ref {}: {}'.format(story['source'], story['ref'], str(e)))
logging.exception(e)
return False
2019-08-24 08:49:11 +00:00
if res:
story.update(res) # join dicts
else:
logging.info('Story not ready yet')
return False
if story['date'] and not is_manual and story['date'] + TWO_DAYS < time.time():
logging.info('Story too old, removing. Date: {}'.format(story['date']))
2019-11-08 21:50:33 +00:00
return False
2019-08-24 08:49:11 +00:00
if story.get('url', '') and not story.get('text', ''):
2020-06-25 23:36:47 +00:00
if not get_content_type(story['url']).startswith('text/'):
logging.info('URL invalid file type / content type:')
logging.info(story['url'])
return False
if any([domain in story['url'] for domain in INVALID_DOMAINS]):
2020-06-25 23:36:47 +00:00
logging.info('URL invalid domain:')
logging.info(story['url'])
return False
logging.info('Getting article ' + story['url'])
story['text'] = get_article(story['url'])
if not story['text']: return False
return True
if __name__ == '__main__':
2019-10-08 08:00:50 +00:00
#test_news_cache = {}
#nid = 'jean'
#ref = 20802050
#source = 'hackernews'
#test_news_cache[nid] = dict(id=nid, ref=ref, source=source)
#news_story = test_news_cache[nid]
#update_story(news_story)
2019-10-19 07:33:06 +00:00
#print(get_article('https://www.bloomberg.com/news/articles/2019-09-23/xi-s-communists-under-pressure-as-high-prices-hit-china-workers'))
a = get_content_type('https://tefkos.comminfo.rutgers.edu/Courses/e530/Readings/Beal%202008%20full%20text%20searching.pdf')
2019-10-19 07:33:06 +00:00
print(a)
2019-10-08 08:00:50 +00:00
print('done')