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.
179 lines
7.3 KiB
179 lines
7.3 KiB
4 years ago
|
import time
|
||
3 years ago
|
from changedetectionio import content_fetcher
|
||
4 years ago
|
import hashlib
|
||
4 years ago
|
from inscriptis import get_text
|
||
4 years ago
|
import urllib3
|
||
3 years ago
|
from . import html_tools
|
||
3 years ago
|
import re
|
||
4 years ago
|
|
||
3 years ago
|
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||
3 years ago
|
|
||
|
|
||
4 years ago
|
# Some common stuff here that can be moved to a base class
|
||
|
class perform_site_check():
|
||
4 years ago
|
|
||
4 years ago
|
def __init__(self, *args, datastore, **kwargs):
|
||
4 years ago
|
super().__init__(*args, **kwargs)
|
||
|
self.datastore = datastore
|
||
4 years ago
|
|
||
4 years ago
|
def strip_ignore_text(self, content, list_ignore_text):
|
||
3 years ago
|
import re
|
||
4 years ago
|
ignore = []
|
||
3 years ago
|
ignore_regex = []
|
||
4 years ago
|
for k in list_ignore_text:
|
||
3 years ago
|
|
||
|
# Is it a regex?
|
||
|
if k[0] == '/':
|
||
|
ignore_regex.append(k.strip(" /"))
|
||
|
else:
|
||
|
ignore.append(k)
|
||
4 years ago
|
|
||
4 years ago
|
output = []
|
||
4 years ago
|
for line in content.splitlines():
|
||
|
|
||
4 years ago
|
# Always ignore blank lines in this mode. (when this function gets called)
|
||
|
if len(line.strip()):
|
||
3 years ago
|
regex_matches = False
|
||
|
|
||
|
# if any of these match, skip
|
||
|
for regex in ignore_regex:
|
||
|
try:
|
||
|
if re.search(regex, line, re.IGNORECASE):
|
||
|
regex_matches = True
|
||
|
except Exception as e:
|
||
|
continue
|
||
|
|
||
|
if not regex_matches and not any(skip_text in line for skip_text in ignore):
|
||
|
output.append(line.encode('utf8'))
|
||
4 years ago
|
|
||
|
return "\n".encode('utf8').join(output)
|
||
4 years ago
|
|
||
4 years ago
|
|
||
|
|
||
4 years ago
|
def run(self, uuid):
|
||
|
timestamp = int(time.time()) # used for storage etc too
|
||
3 years ago
|
|
||
4 years ago
|
changed_detected = False
|
||
3 years ago
|
stripped_text_from_html = ""
|
||
4 years ago
|
|
||
3 years ago
|
watch = self.datastore.data['watching'][uuid]
|
||
|
|
||
4 years ago
|
update_obj = {'previous_md5': self.datastore.data['watching'][uuid]['previous_md5'],
|
||
|
'history': {},
|
||
|
"last_checked": timestamp
|
||
|
}
|
||
|
|
||
|
extra_headers = self.datastore.get_val(uuid, 'headers')
|
||
4 years ago
|
|
||
|
# Tweak the base config with the per-watch ones
|
||
3 years ago
|
request_headers = self.datastore.data['settings']['headers'].copy()
|
||
4 years ago
|
request_headers.update(extra_headers)
|
||
4 years ago
|
|
||
4 years ago
|
# https://github.com/psf/requests/issues/4525
|
||
|
# Requests doesnt yet support brotli encoding, so don't put 'br' here, be totally sure that the user cannot
|
||
|
# do this by accident.
|
||
|
if 'Accept-Encoding' in request_headers and "br" in request_headers['Accept-Encoding']:
|
||
|
request_headers['Accept-Encoding'] = request_headers['Accept-Encoding'].replace(', br', '')
|
||
|
|
||
3 years ago
|
# @todo check the failures are really handled how we expect
|
||
4 years ago
|
|
||
3 years ago
|
else:
|
||
|
timeout = self.datastore.data['settings']['requests']['timeout']
|
||
4 years ago
|
url = self.datastore.get_val(uuid, 'url')
|
||
|
|
||
3 years ago
|
# Pluggable content fetcher
|
||
3 years ago
|
prefer_backend = watch['fetch_backend']
|
||
3 years ago
|
if hasattr(content_fetcher, prefer_backend):
|
||
|
klass = getattr(content_fetcher, prefer_backend)
|
||
|
else:
|
||
|
# If the klass doesnt exist, just use a default
|
||
|
klass = getattr(content_fetcher, "html_requests")
|
||
|
|
||
4 years ago
|
|
||
3 years ago
|
fetcher = klass()
|
||
|
fetcher.run(url, timeout, request_headers)
|
||
|
# Fetching complete, now filters
|
||
|
# @todo move to class / maybe inside of fetcher abstract base?
|
||
3 years ago
|
|
||
3 years ago
|
# @note: I feel like the following should be in a more obvious chain system
|
||
|
# - Check filter text
|
||
|
# - Is the checksum different?
|
||
|
# - Do we convert to JSON?
|
||
|
# https://stackoverflow.com/questions/41817578/basic-method-chaining ?
|
||
|
# return content().textfilter().jsonextract().checksumcompare() ?
|
||
|
|
||
3 years ago
|
is_html = True
|
||
3 years ago
|
css_filter_rule = watch['css_filter']
|
||
3 years ago
|
if css_filter_rule and len(css_filter_rule.strip()):
|
||
3 years ago
|
if 'json:' in css_filter_rule:
|
||
3 years ago
|
stripped_text_from_html = html_tools.extract_json_as_string(content=fetcher.content, jsonpath_filter=css_filter_rule)
|
||
3 years ago
|
is_html = False
|
||
|
else:
|
||
|
# CSS Filter, extract the HTML that matches and feed that into the existing inscriptis::get_text
|
||
3 years ago
|
stripped_text_from_html = html_tools.css_filter(css_filter=css_filter_rule, html_content=fetcher.content)
|
||
3 years ago
|
|
||
|
if is_html:
|
||
3 years ago
|
# CSS Filter, extract the HTML that matches and feed that into the existing inscriptis::get_text
|
||
|
html_content = fetcher.content
|
||
|
if css_filter_rule and len(css_filter_rule.strip()):
|
||
|
html_content = html_tools.css_filter(css_filter=css_filter_rule, html_content=fetcher.content)
|
||
4 years ago
|
|
||
3 years ago
|
# get_text() via inscriptis
|
||
|
stripped_text_from_html = get_text(html_content)
|
||
4 years ago
|
|
||
4 years ago
|
# We rely on the actual text in the html output.. many sites have random script vars etc,
|
||
|
# in the future we'll implement other mechanisms.
|
||
4 years ago
|
|
||
3 years ago
|
update_obj["last_check_status"] = fetcher.get_last_status_code()
|
||
4 years ago
|
update_obj["last_error"] = False
|
||
4 years ago
|
|
||
|
|
||
4 years ago
|
# If there's text to skip
|
||
|
# @todo we could abstract out the get_text() to handle this cleaner
|
||
3 years ago
|
if len(watch['ignore_text']):
|
||
|
stripped_text_from_html = self.strip_ignore_text(stripped_text_from_html, watch['ignore_text'])
|
||
4 years ago
|
else:
|
||
3 years ago
|
stripped_text_from_html = stripped_text_from_html.encode('utf8')
|
||
|
|
||
4 years ago
|
|
||
3 years ago
|
fetched_md5 = hashlib.md5(stripped_text_from_html).hexdigest()
|
||
4 years ago
|
|
||
3 years ago
|
blocked_by_not_found_trigger_text = False
|
||
|
|
||
|
if len(watch['trigger_text']):
|
||
|
blocked_by_not_found_trigger_text = True
|
||
|
for line in watch['trigger_text']:
|
||
|
# Because JSON wont serialize a re.compile object
|
||
|
if line[0] == '/' and line[-1] == '/':
|
||
|
regex = re.compile(line.strip('/'), re.IGNORECASE)
|
||
|
# Found it? so we don't wait for it anymore
|
||
|
r = re.search(regex, str(stripped_text_from_html))
|
||
|
if r:
|
||
|
blocked_by_not_found_trigger_text = False
|
||
|
break
|
||
|
|
||
|
elif line.lower() in str(stripped_text_from_html).lower():
|
||
|
# We found it don't wait for it.
|
||
|
blocked_by_not_found_trigger_text = False
|
||
|
break
|
||
|
|
||
|
|
||
4 years ago
|
# could be None or False depending on JSON type
|
||
3 years ago
|
# On the first run of a site, watch['previous_md5'] will be an empty string
|
||
|
if not blocked_by_not_found_trigger_text and watch['previous_md5'] != fetched_md5:
|
||
4 years ago
|
changed_detected = True
|
||
4 years ago
|
|
||
4 years ago
|
# Don't confuse people by updating as last-changed, when it actually just changed from None..
|
||
4 years ago
|
if self.datastore.get_val(uuid, 'previous_md5'):
|
||
|
update_obj["last_changed"] = timestamp
|
||
4 years ago
|
|
||
4 years ago
|
update_obj["previous_md5"] = fetched_md5
|
||
4 years ago
|
|
||
3 years ago
|
# Extract title as title
|
||
3 years ago
|
if is_html and self.datastore.data['settings']['application']['extract_title_as_title']:
|
||
3 years ago
|
if not watch['title'] or not len(watch['title']):
|
||
3 years ago
|
update_obj['title'] = html_tools.extract_element(find='title', html_content=fetcher.content)
|
||
3 years ago
|
|
||
|
|
||
4 years ago
|
return changed_detected, update_obj, stripped_text_from_html
|