You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
пре 5 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. # Add a link to original article
  90. article_source = content_soup.new_tag('a', href=entry.link)
  91. article_source['class'] = 'source'
  92. article_source.string = 'Quelle: ' + entry.link
  93. content_soup.div.append(article_source)
  94. if entry.link.startswith('https://de'+'rst'+'and'+'ard'+'.a'+'t/20'): # url starts with number ... too lazy for regex :)
  95. if entry.published:
  96. article_time = content_soup.new_tag('time', datetime=entry.published)
  97. content_soup.div.append(article_time)
  98. article_headline = online_soup.find('h1', attrs={'itemprop': 'headline'})
  99. content_soup.div.append(article_headline)
  100. # images etc
  101. article_aside = online_soup.find('div', id="content-aside")
  102. content_soup.div.append(article_aside)
  103. article_body = online_soup.find('div', attrs={'itemprop': 'articleBody'})
  104. content_soup.div.append(article_body)
  105. # Add a link to comments
  106. # modify original link -> mobile version and comment section
  107. link_to_comments = re.sub(r'(\/\/)', r'\1mobil.',entry.link.split('?')[0]) + '?_viewMode=forum#'
  108. article_comments_link = content_soup.new_tag('a', href=link_to_comments)
  109. article_comments_link['class'] = 'comments'
  110. article_comments_p = content_soup.new_tag('p')
  111. article_comments_link.string = 'Kommentare'
  112. article_comments_p.append(article_comments_link)
  113. content_soup.div.append(article_comments_p)
  114. # Add a link to original article
  115. article_source = content_soup.new_tag('a', href=entry.link.split('?')[0])
  116. article_source['class'] = 'source'
  117. article_source.string = 'Quelle: ' + entry.link.split('?')[0]
  118. article_source_p = content_soup.new_tag('p')
  119. article_source_p.append(article_source)
  120. content_soup.div.append(article_source_p)
  121. # create directory for storing and serving html and images
  122. os.makedirs(entry_path)
  123. # download all article images and replace image source
  124. for img in content_soup.findAll('img'):
  125. if img.get('data-src'):
  126. old_url = img['data-src']
  127. if not old_url.startswith('data:'):
  128. new_filename = filename_from_url(old_url)
  129. img['data-src'] = assets_url + '/' + entry_dir + '/' + new_filename
  130. download_image(old_url, entry_dir, new_filename)
  131. if img.get('src'):
  132. old_url = img['src']
  133. if not old_url.startswith('data:'):
  134. new_filename = filename_from_url(old_url)
  135. img['src'] = assets_url + '/' + entry_dir + '/' + new_filename
  136. download_image(old_url, entry_dir, new_filename)
  137. if img.get('data-srcset'):
  138. srcset = img['data-srcset'].split(', ')
  139. new_srcset = []
  140. for src in srcset:
  141. old_url = src.split(' ')[0]
  142. src_res = src.split(' ')[1]
  143. new_filename = filename_from_url(old_url)
  144. download_image(old_url, entry_dir, new_filename)
  145. new_url = assets_url + '/' + entry_dir + '/' + new_filename
  146. src = ' '.join([new_url, src_res])
  147. new_srcset.append(src)
  148. img['data-srcset'] = ', '.join(new_srcset)
  149. # TODO(?): HTML5 picture tag
  150. f = open(entry_path + '/index.html', 'w')
  151. f.write(str(content_soup))
  152. f.close()
  153. time.sleep(1.3)
  154. # Create new feed
  155. # Maybe buiding a new feed from scretch using a template would be nicer but ...
  156. # let's just modify the original one!
  157. feed_soup = BeautifulSoup(r_feed.text, 'lxml-xml')
  158. # Exclude items
  159. if obj.get('exclude') and isinstance(obj['exclude'], list):
  160. for e in feed_soup.findAll('item'):
  161. matches = [x for x in obj['exclude'] if x.lower() in e.title.text.lower()]
  162. if len(matches) > 0:
  163. e.extract()
  164. print(timestamp(), 'Exclude: ', e.title.text, '->', matches)
  165. for e in feed_soup.findAll('item'):
  166. entry_dir = get_valid_filename(e.link.text)
  167. f_content = open(assets_path + '/' + entry_dir + '/index.html', 'r')
  168. content_tag = feed_soup.new_tag('content:encoded')
  169. content_tag.string = CData(f_content.read())
  170. e.append(content_tag)
  171. f_content.close
  172. # create directory if not present
  173. os.makedirs(feeds_path, exist_ok=True)
  174. f = open(feeds_path + '/' + output_filename, 'w')
  175. print(timestamp(), 'Done!')
  176. f.write(str(feed_soup))
  177. f.close()
  178. # Let's actually fetch the stuff!
  179. for feed in config['feeds']:
  180. process_feed(feed)