Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 

223 linhas
8.8 KiB

  1. # This script is intended for personal and scientific use only
  2. import os
  3. import sys
  4. import re
  5. import hashlib
  6. import json
  7. import time
  8. import feedparser
  9. import requests
  10. from bs4 import BeautifulSoup, Comment
  11. from bs4.element import CData
  12. def timestamp():
  13. return '[' + time.strftime("%d/%b/%Y:%H:%M:%S %z", time.localtime()) + ']'
  14. # default config location is a 'config.json' next to the script.
  15. try:
  16. filedir = os.path.dirname(os.path.abspath(__file__))
  17. if len(sys.argv) < 2:
  18. configpath = filedir+'/config.json'
  19. print(timestamp(), "Using default config location: ", configpath)
  20. config = json.load(open(configpath))
  21. else:
  22. configpath = sys.argv[1]
  23. config = json.load(open(configpath))
  24. except:
  25. print(timestamp(), "Problem reading config file: ", configpath)
  26. print(timestamp(), "ERROR: Config file not found or invalid!")
  27. sys.exit(1)
  28. public_path = filedir + '/public'
  29. assets_path = public_path + '/assets'
  30. feeds_path = public_path + '/feeds'
  31. # e.g. https://example.com/some-string
  32. assets_url = config['assets_url']
  33. requestheaders = config['request_headers']
  34. # need filname safe strings for storing images along html files
  35. def get_valid_filename(s):
  36. s = str(s).split('?')[0].strip().strip('/').strip('http://').strip('https://').replace(' ', '-')
  37. return re.sub(r'(?u)[^-\w.]', '-', s)
  38. # Get a unique and valid filename from URL (for images)
  39. def filename_from_url(url):
  40. # remove get attributes and path
  41. new_filename = url.split('?')[0].split('/')[-1]
  42. # Split filename
  43. new_filename = new_filename.split('.')
  44. # insert a hash before suffix
  45. new_filename.insert(1, str(hashlib.md5(url.encode('utf-8')).hexdigest()) )
  46. # convert back to string and extra validate
  47. new_filename = get_valid_filename('.'.join(new_filename))
  48. return new_filename
  49. # Download images and so on
  50. def download_image(url, entry_dir, filename):
  51. # take care of protocol relative URLs ... let's just assume that https works.
  52. if url.startswith('//'):
  53. url = 'https:'+url
  54. response = requests.get(url, headers=requestheaders)
  55. if response.status_code == 200:
  56. with open(assets_path + '/' + entry_dir + '/' + filename, 'wb') as f:
  57. #f.write(response.content)
  58. for chunk in response.iter_content(1024):
  59. f.write(chunk)
  60. def process_feed(obj):
  61. feed_url = obj['source']
  62. output_filename = obj['destination']
  63. print(timestamp(), 'Updating:', obj['destination'])
  64. # Get the feed
  65. r_feed = requests.get(feed_url, headers=requestheaders)
  66. # TODO: exceptions.(what if 404 or whatever?)
  67. # Store data of new articles
  68. for entry in feedparser.parse(r_feed.text).entries:
  69. entry_dir = get_valid_filename(entry.link) # input e.g. https://orf.at/stories/3117136/
  70. entry_path = assets_path + '/'+ entry_dir
  71. if not os.path.exists(entry_path):
  72. print(timestamp(), 'New item:', entry.link)
  73. r = requests.get(entry.link.split('?')[0], headers=requestheaders)
  74. online_soup = BeautifulSoup(r.text, 'html.parser')
  75. content_soup = BeautifulSoup('<div></div>', 'html.parser')
  76. # Remove all Comments
  77. for element in online_soup(text=lambda text: isinstance(text, Comment)):
  78. element.extract()
  79. # domain and path specific rules
  80. # ... ob+fu+sca+tion for seo
  81. if entry.link.startswith('https://or'+'f.a'+'t/sto'+'ries'):
  82. if entry.date:
  83. article_time = content_soup.new_tag('time', datetime=entry.date)
  84. content_soup.div.append(article_time)
  85. article_headline = online_soup.find('h1', attrs={'class': 'story-lead-headline'})
  86. content_soup.div.append(article_headline)
  87. article_body = online_soup.find('div', attrs={'class': 'story-content'})
  88. content_soup.div.append(article_body)
  89. article_source = content_soup.new_tag('a', href=entry.link)
  90. article_source['class'] = 'source'
  91. article_source.string = 'Quelle: ' + entry.link
  92. content_soup.div.append(article_source)
  93. if entry.link.startswith('https://de'+'rst'+'and'+'ard'+'.a'+'t/20'): # url starts with number ... too lazy for regex :)
  94. if entry.published:
  95. article_time = content_soup.new_tag('time', datetime=entry.published)
  96. content_soup.div.append(article_time)
  97. article_headline = online_soup.find('h1', attrs={'itemprop': 'headline'})
  98. content_soup.div.append(article_headline)
  99. # images etc
  100. article_aside = online_soup.find('div', id="content-aside")
  101. content_soup.div.append(article_aside)
  102. article_body = online_soup.find('div', attrs={'itemprop': 'articleBody'})
  103. content_soup.div.append(article_body)
  104. # modify original link -> mobile version and comment section
  105. link_to_comments = re.sub(r'(\/\/)', r'\1mobil.',entry.link.split('?')[0]) + '?_viewMode=forum#'
  106. article_comments_link = content_soup.new_tag('a', href=link_to_comments)
  107. article_comments_link['class'] = 'comments'
  108. article_comments_p = content_soup.new_tag('p')
  109. article_comments_link.string = 'Kommentare'
  110. article_comments_p.append(article_comments_link)
  111. content_soup.div.append(article_comments_p)
  112. article_source = content_soup.new_tag('a', href=entry.link.split('?')[0])
  113. article_source['class'] = 'source'
  114. article_source.string = 'Quelle: ' + entry.link.split('?')[0]
  115. article_source_p = content_soup.new_tag('p')
  116. article_source_p.append(article_source)
  117. content_soup.div.append(article_source_p)
  118. # create directory for storing and serving html and images
  119. os.makedirs(entry_path)
  120. # download all article images and replace image source
  121. for img in content_soup.findAll('img'):
  122. if img.get('data-src'):
  123. old_url = img['data-src']
  124. if not old_url.startswith('data:'):
  125. new_filename = filename_from_url(old_url)
  126. img['data-src'] = assets_url + '/' + entry_dir + '/' + new_filename
  127. download_image(old_url, entry_dir, new_filename)
  128. if img.get('src'):
  129. old_url = img['src']
  130. if not old_url.startswith('data:'):
  131. new_filename = filename_from_url(old_url)
  132. img['src'] = assets_url + '/' + entry_dir + '/' + new_filename
  133. download_image(old_url, entry_dir, new_filename)
  134. if img.get('data-srcset'):
  135. srcset = img['data-srcset'].split(', ')
  136. new_srcset = []
  137. for src in srcset:
  138. old_url = src.split(' ')[0]
  139. src_res = src.split(' ')[1]
  140. new_filename = filename_from_url(old_url)
  141. download_image(old_url, entry_dir, new_filename)
  142. new_url = assets_url + '/' + entry_dir + '/' + new_filename
  143. src = ' '.join([new_url, src_res])
  144. new_srcset.append(src)
  145. img['data-srcset'] = ', '.join(new_srcset)
  146. # TODO(?): HTML5 picture tag
  147. f = open(entry_path + '/index.html', 'w')
  148. f.write(str(content_soup))
  149. f.close()
  150. time.sleep(1.3)
  151. # Create new feed
  152. # Maybe buiding a new feed from scretch using a template would be nicer but ...
  153. # let's just modify the original one!
  154. feed_soup = BeautifulSoup(r_feed.text, 'lxml-xml')
  155. # Exclude items
  156. if obj.get('exclude') and isinstance(obj['exclude'], list):
  157. for e in feed_soup.findAll('item'):
  158. matches = [x for x in obj['exclude'] if x.lower() in e.title.text.lower()]
  159. if len(matches) > 0:
  160. e.extract()
  161. print(timestamp(), 'Exclude: ', e.title.text, '->', matches)
  162. for e in feed_soup.findAll('item'):
  163. entry_dir = get_valid_filename(e.link.text)
  164. f_content = open(assets_path + '/' + entry_dir + '/index.html', 'r')
  165. content_tag = feed_soup.new_tag('content:encoded')
  166. content_tag.string = CData(f_content.read())
  167. e.append(content_tag)
  168. f_content.close
  169. # create directory if not present
  170. os.makedirs(feeds_path, exist_ok=True)
  171. f = open(feeds_path + '/' + output_filename, 'w')
  172. print(timestamp(), 'Done!')
  173. f.write(str(feed_soup))
  174. f.close()
  175. # Let's actually fetch the stuff!
  176. for feed in config['feeds']:
  177. process_feed(feed)