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.
361 lines
19 KiB
361 lines
19 KiB
1 year ago
|
# HTML to TEXT/JSON DIFFERENCE self.fetcher
|
||
2 years ago
|
|
||
4 years ago
|
import hashlib
|
||
2 years ago
|
import json
|
||
3 years ago
|
import os
|
||
3 years ago
|
import re
|
||
3 years ago
|
import urllib3
|
||
|
|
||
6 months ago
|
from changedetectionio.processors import difference_detection_processor
|
||
|
from changedetectionio.html_tools import PERL_STYLE_REGEX, cdata_in_document_to_text
|
||
11 months ago
|
from changedetectionio import html_tools, content_fetchers
|
||
2 years ago
|
from changedetectionio.blueprint.price_data_follower import PRICE_DATA_TRACK_ACCEPT, PRICE_DATA_TRACK_REJECT
|
||
12 months ago
|
from loguru import logger
|
||
4 years ago
|
|
||
4 years ago
|
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
||
4 years ago
|
|
||
1 year ago
|
name = 'Webpage Text/HTML, JSON and PDF changes'
|
||
2 years ago
|
description = 'Detects all text changes where possible'
|
||
6 months ago
|
|
||
6 months ago
|
json_filter_prefixes = ['json:', 'jq:', 'jqraw:']
|
||
1 year ago
|
|
||
2 years ago
|
class FilterNotFoundInResponse(ValueError):
|
||
6 months ago
|
def __init__(self, msg, screenshot=None, xpath_data=None):
|
||
6 months ago
|
self.screenshot = screenshot
|
||
6 months ago
|
self.xpath_data = xpath_data
|
||
2 years ago
|
ValueError.__init__(self, msg)
|
||
|
|
||
1 year ago
|
|
||
2 years ago
|
class PDFToHTMLToolNotFound(ValueError):
|
||
|
def __init__(self, msg):
|
||
|
ValueError.__init__(self, msg)
|
||
|
|
||
2 years ago
|
|
||
4 years ago
|
# Some common stuff here that can be moved to a base class
|
||
2 years ago
|
# (set_proxy_from_list)
|
||
2 years ago
|
class perform_site_check(difference_detection_processor):
|
||
4 years ago
|
|
||
6 months ago
|
def run_changedetection(self, watch, skip_when_checksum_same=True):
|
||
4 years ago
|
changed_detected = False
|
||
1 year ago
|
html_content = ""
|
||
3 years ago
|
screenshot = False # as bytes
|
||
3 years ago
|
stripped_text_from_html = ""
|
||
4 years ago
|
|
||
2 years ago
|
if not watch:
|
||
2 years ago
|
raise Exception("Watch no longer exists.")
|
||
3 years ago
|
|
||
3 years ago
|
# Unset any existing notification error
|
||
3 years ago
|
update_obj = {'last_notification_error': False, 'last_error': False}
|
||
4 years ago
|
|
||
2 years ago
|
url = watch.link
|
||
2 years ago
|
|
||
1 year ago
|
self.screenshot = self.fetcher.screenshot
|
||
|
self.xpath_data = self.fetcher.xpath_data
|
||
2 years ago
|
|
||
2 years ago
|
# Track the content type
|
||
1 year ago
|
update_obj['content_type'] = self.fetcher.get_all_headers().get('content-type', '').lower()
|
||
2 years ago
|
|
||
2 years ago
|
# Watches added automatically in the queue manager will skip if its the same checksum as the previous run
|
||
|
# Saves a lot of CPU
|
||
1 year ago
|
update_obj['previous_md5_before_filters'] = hashlib.md5(self.fetcher.content.encode('utf-8')).hexdigest()
|
||
2 years ago
|
if skip_when_checksum_same:
|
||
|
if update_obj['previous_md5_before_filters'] == watch.get('previous_md5_before_filters'):
|
||
11 months ago
|
raise content_fetchers.exceptions.checksumFromPreviousCheckWasTheSame()
|
||
2 years ago
|
|
||
3 years ago
|
# Fetching complete, now filters
|
||
|
|
||
|
# @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() ?
|
||
|
|
||
1 year ago
|
is_json = 'application/json' in self.fetcher.get_all_headers().get('content-type', '').lower()
|
||
3 years ago
|
is_html = not is_json
|
||
1 year ago
|
is_rss = False
|
||
|
|
||
1 year ago
|
ctype_header = self.fetcher.get_all_headers().get('content-type', '').lower()
|
||
1 year ago
|
# Go into RSS preprocess for converting CDATA/comment to usable text
|
||
|
if any(substring in ctype_header for substring in ['application/xml', 'application/rss', 'text/xml']):
|
||
1 year ago
|
if '<rss' in self.fetcher.content[:100].lower():
|
||
|
self.fetcher.content = cdata_in_document_to_text(html_content=self.fetcher.content)
|
||
1 year ago
|
is_rss = True
|
||
3 years ago
|
|
||
|
# source: support, basically treat it as plaintext
|
||
1 year ago
|
if watch.is_source_type_url:
|
||
3 years ago
|
is_html = False
|
||
|
is_json = False
|
||
|
|
||
1 year ago
|
inline_pdf = self.fetcher.get_all_headers().get('content-disposition', '') and '%PDF-1' in self.fetcher.content[:10]
|
||
|
if watch.is_pdf or 'application/pdf' in self.fetcher.get_all_headers().get('content-type', '').lower() or inline_pdf:
|
||
2 years ago
|
from shutil import which
|
||
|
tool = os.getenv("PDF_TO_HTML_TOOL", "pdftohtml")
|
||
|
if not which(tool):
|
||
|
raise PDFToHTMLToolNotFound("Command-line `{}` tool was not found in system PATH, was it installed?".format(tool))
|
||
|
|
||
|
import subprocess
|
||
|
proc = subprocess.Popen(
|
||
|
[tool, '-stdout', '-', '-s', 'out.pdf', '-i'],
|
||
|
stdout=subprocess.PIPE,
|
||
|
stdin=subprocess.PIPE)
|
||
1 year ago
|
proc.stdin.write(self.fetcher.raw_content)
|
||
2 years ago
|
proc.stdin.close()
|
||
1 year ago
|
self.fetcher.content = proc.stdout.read().decode('utf-8')
|
||
2 years ago
|
proc.wait(timeout=60)
|
||
|
|
||
|
# Add a little metadata so we know if the file changes (like if an image changes, but the text is the same
|
||
|
# @todo may cause problems with non-UTF8?
|
||
|
metadata = "<p>Added by changedetection.io: Document checksum - {} Filesize - {} bytes</p>".format(
|
||
1 year ago
|
hashlib.md5(self.fetcher.raw_content).hexdigest().upper(),
|
||
|
len(self.fetcher.content))
|
||
2 years ago
|
|
||
1 year ago
|
self.fetcher.content = self.fetcher.content.replace('</body>', metadata + '</body>')
|
||
2 years ago
|
|
||
2 years ago
|
# Better would be if Watch.model could access the global data also
|
||
|
# and then use getattr https://docs.python.org/3/reference/datamodel.html#object.__getitem__
|
||
|
# https://realpython.com/inherit-python-dict/ instead of doing it procedurely
|
||
6 months ago
|
include_filters_from_tags = self.datastore.get_tag_overrides_for_watch(uuid=watch.get('uuid'), attr='include_filters')
|
||
11 months ago
|
|
||
|
# 1845 - remove duplicated filters in both group and watch include filter
|
||
10 months ago
|
include_filters_rule = list(dict.fromkeys(watch.get('include_filters', []) + include_filters_from_tags))
|
||
2 years ago
|
|
||
6 months ago
|
subtractive_selectors = [*self.datastore.get_tag_overrides_for_watch(uuid=watch.get('uuid'), attr='subtractive_selectors'),
|
||
2 years ago
|
*watch.get("subtractive_selectors", []),
|
||
|
*self.datastore.data["settings"]["application"].get("global_subtractive_selectors", [])
|
||
|
]
|
||
3 years ago
|
|
||
2 years ago
|
# Inject a virtual LD+JSON price tracker rule
|
||
2 years ago
|
if watch.get('track_ldjson_price_data', '') == PRICE_DATA_TRACK_ACCEPT:
|
||
1 year ago
|
include_filters_rule += html_tools.LD_JSON_PRODUCT_OFFER_SELECTORS
|
||
2 years ago
|
|
||
2 years ago
|
has_filter_rule = len(include_filters_rule) and len(include_filters_rule[0].strip())
|
||
|
has_subtractive_selectors = len(subtractive_selectors) and len(subtractive_selectors[0].strip())
|
||
3 years ago
|
|
||
|
if is_json and not has_filter_rule:
|
||
2 years ago
|
include_filters_rule.append("json:$")
|
||
3 years ago
|
has_filter_rule = True
|
||
|
|
||
2 years ago
|
if is_json:
|
||
|
# Sort the JSON so we dont get false alerts when the content is just re-ordered
|
||
|
try:
|
||
1 year ago
|
self.fetcher.content = json.dumps(json.loads(self.fetcher.content), sort_keys=True)
|
||
2 years ago
|
except Exception as e:
|
||
|
# Might have just been a snippet, or otherwise bad JSON, continue
|
||
|
pass
|
||
|
|
||
3 years ago
|
if has_filter_rule:
|
||
2 years ago
|
for filter in include_filters_rule:
|
||
|
if any(prefix in filter for prefix in json_filter_prefixes):
|
||
1 year ago
|
stripped_text_from_html += html_tools.extract_json_as_string(content=self.fetcher.content, json_filter=filter)
|
||
2 years ago
|
is_html = False
|
||
3 years ago
|
|
||
1 year ago
|
if is_html or watch.is_source_type_url:
|
||
2 years ago
|
|
||
3 years ago
|
# CSS Filter, extract the HTML that matches and feed that into the existing inscriptis::get_text
|
||
1 year ago
|
self.fetcher.content = html_tools.workarounds_for_obfuscations(self.fetcher.content)
|
||
|
html_content = self.fetcher.content
|
||
3 years ago
|
|
||
|
# If not JSON, and if it's not text/plain..
|
||
1 year ago
|
if 'text/plain' in self.fetcher.get_all_headers().get('content-type', '').lower():
|
||
3 years ago
|
# Don't run get_text or xpath/css filters on plaintext
|
||
|
stripped_text_from_html = html_content
|
||
4 years ago
|
else:
|
||
2 years ago
|
# Does it have some ld+json price data? used for easier monitoring
|
||
1 year ago
|
update_obj['has_ldjson_price_data'] = html_tools.has_ldjson_product_info(self.fetcher.content)
|
||
2 years ago
|
|
||
3 years ago
|
# Then we assume HTML
|
||
|
if has_filter_rule:
|
||
2 years ago
|
html_content = ""
|
||
2 years ago
|
|
||
2 years ago
|
for filter_rule in include_filters_rule:
|
||
|
# For HTML/XML we offer xpath as an option, just start a regular xPath "/.."
|
||
|
if filter_rule[0] == '/' or filter_rule.startswith('xpath:'):
|
||
|
html_content += html_tools.xpath_filter(xpath_filter=filter_rule.replace('xpath:', ''),
|
||
1 year ago
|
html_content=self.fetcher.content,
|
||
|
append_pretty_line_formatting=not watch.is_source_type_url,
|
||
1 year ago
|
is_rss=is_rss)
|
||
1 year ago
|
elif filter_rule.startswith('xpath1:'):
|
||
|
html_content += html_tools.xpath1_filter(xpath_filter=filter_rule.replace('xpath1:', ''),
|
||
1 year ago
|
html_content=self.fetcher.content,
|
||
|
append_pretty_line_formatting=not watch.is_source_type_url,
|
||
1 year ago
|
is_rss=is_rss)
|
||
2 years ago
|
else:
|
||
|
# CSS Filter, extract the HTML that matches and feed that into the existing inscriptis::get_text
|
||
|
html_content += html_tools.include_filters(include_filters=filter_rule,
|
||
1 year ago
|
html_content=self.fetcher.content,
|
||
|
append_pretty_line_formatting=not watch.is_source_type_url)
|
||
2 years ago
|
|
||
|
if not html_content.strip():
|
||
6 months ago
|
raise FilterNotFoundInResponse(msg=include_filters_rule, screenshot=self.fetcher.screenshot, xpath_data=self.fetcher.xpath_data)
|
||
3 years ago
|
|
||
3 years ago
|
if has_subtractive_selectors:
|
||
|
html_content = html_tools.element_removal(subtractive_selectors, html_content)
|
||
3 years ago
|
|
||
1 year ago
|
if watch.is_source_type_url:
|
||
2 years ago
|
stripped_text_from_html = html_content
|
||
|
else:
|
||
3 years ago
|
# extract text
|
||
2 years ago
|
do_anchor = self.datastore.data["settings"]["application"].get("render_anchor_tag_content", False)
|
||
3 years ago
|
stripped_text_from_html = \
|
||
|
html_tools.html_to_text(
|
||
1 year ago
|
html_content=html_content,
|
||
|
render_anchor_tag_content=do_anchor,
|
||
1 year ago
|
is_rss=is_rss # #1874 activate the <title workaround hack
|
||
3 years ago
|
)
|
||
|
|
||
11 months ago
|
if watch.get('sort_text_alphabetically') and stripped_text_from_html:
|
||
|
# Note: Because a <p>something</p> will add an extra line feed to signify the paragraph gap
|
||
|
# we end up with 'Some text\n\n', sorting will add all those extra \n at the start, so we remove them here.
|
||
|
stripped_text_from_html = stripped_text_from_html.replace('\n\n', '\n')
|
||
|
stripped_text_from_html = '\n'.join( sorted(stripped_text_from_html.splitlines(), key=lambda x: x.lower() ))
|
||
|
|
||
3 years ago
|
# Re #340 - return the content before the 'ignore text' was applied
|
||
|
text_content_before_ignored_filter = stripped_text_from_html.encode('utf-8')
|
||
|
|
||
2 years ago
|
# @todo whitespace coming from missing rtrim()?
|
||
|
# stripped_text_from_html could be based on their preferences, replace the processed text with only that which they want to know about.
|
||
|
# Rewrite's the processing text based on only what diff result they want to see
|
||
|
if watch.has_special_diff_filter_options_set() and len(watch.history.keys()):
|
||
|
# Now the content comes from the diff-parser and not the returned HTTP traffic, so could be some differences
|
||
6 months ago
|
from changedetectionio import diff
|
||
2 years ago
|
# needs to not include (added) etc or it may get used twice
|
||
|
# Replace the processed text with the preferred result
|
||
6 months ago
|
rendered_diff = diff.render_diff(previous_version_file_contents=watch.get_last_fetched_text_before_filters(),
|
||
1 year ago
|
newest_version_file_contents=stripped_text_from_html,
|
||
|
include_equal=False, # not the same lines
|
||
|
include_added=watch.get('filter_text_added', True),
|
||
|
include_removed=watch.get('filter_text_removed', True),
|
||
|
include_replaced=watch.get('filter_text_replaced', True),
|
||
|
line_feed_sep="\n",
|
||
|
include_change_type_prefix=False)
|
||
2 years ago
|
|
||
6 months ago
|
watch.save_last_text_fetched_before_filters(text_content_before_ignored_filter)
|
||
2 years ago
|
|
||
|
if not rendered_diff and stripped_text_from_html:
|
||
|
# We had some content, but no differences were found
|
||
|
# Store our new file as the MD5 so it will trigger in the future
|
||
|
c = hashlib.md5(text_content_before_ignored_filter.translate(None, b'\r\n\t ')).hexdigest()
|
||
|
return False, {'previous_md5': c}, stripped_text_from_html.encode('utf-8')
|
||
|
else:
|
||
|
stripped_text_from_html = rendered_diff
|
||
|
|
||
3 years ago
|
# Treat pages with no renderable text content as a change? No by default
|
||
|
empty_pages_are_a_change = self.datastore.data['settings']['application'].get('empty_pages_are_a_change', False)
|
||
|
if not is_json and not empty_pages_are_a_change and len(stripped_text_from_html.strip()) == 0:
|
||
11 months ago
|
raise content_fetchers.exceptions.ReplyWithContentButNoText(url=url,
|
||
1 year ago
|
status_code=self.fetcher.get_last_status_code(),
|
||
6 months ago
|
screenshot=self.fetcher.screenshot,
|
||
1 year ago
|
has_filters=has_filter_rule,
|
||
6 months ago
|
html_content=html_content,
|
||
|
xpath_data=self.fetcher.xpath_data
|
||
1 year ago
|
)
|
||
3 years ago
|
|
||
3 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.
|
||
|
|
||
1 year ago
|
update_obj["last_check_status"] = self.fetcher.get_last_status_code()
|
||
3 years ago
|
|
||
|
# If there's text to skip
|
||
|
# @todo we could abstract out the get_text() to handle this cleaner
|
||
|
text_to_ignore = watch.get('ignore_text', []) + self.datastore.data['settings']['application'].get('global_ignore_text', [])
|
||
|
if len(text_to_ignore):
|
||
|
stripped_text_from_html = html_tools.strip_ignore_text(stripped_text_from_html, text_to_ignore)
|
||
|
else:
|
||
|
stripped_text_from_html = stripped_text_from_html.encode('utf8')
|
||
3 years ago
|
|
||
3 years ago
|
# 615 Extract text by regex
|
||
|
extract_text = watch.get('extract_text', [])
|
||
|
if len(extract_text) > 0:
|
||
|
regex_matched_output = []
|
||
|
for s_re in extract_text:
|
||
2 years ago
|
# incase they specified something in '/.../x'
|
||
1 year ago
|
if re.search(PERL_STYLE_REGEX, s_re, re.IGNORECASE):
|
||
|
regex = html_tools.perl_style_slash_enclosed_regex_to_options(s_re)
|
||
|
result = re.findall(regex.encode('utf-8'), stripped_text_from_html)
|
||
|
|
||
|
for l in result:
|
||
|
if type(l) is tuple:
|
||
|
# @todo - some formatter option default (between groups)
|
||
|
regex_matched_output += list(l) + [b'\n']
|
||
|
else:
|
||
|
# @todo - some formatter option default (between each ungrouped result)
|
||
|
regex_matched_output += [l] + [b'\n']
|
||
|
else:
|
||
|
# Doesnt look like regex, just hunt for plaintext and return that which matches
|
||
|
# `stripped_text_from_html` will be bytes, so we must encode s_re also to bytes
|
||
|
r = re.compile(re.escape(s_re.encode('utf-8')), re.IGNORECASE)
|
||
|
res = r.findall(stripped_text_from_html)
|
||
|
if res:
|
||
|
for match in res:
|
||
|
regex_matched_output += [match] + [b'\n']
|
||
3 years ago
|
|
||
2 years ago
|
# Now we will only show what the regex matched
|
||
|
stripped_text_from_html = b''
|
||
|
text_content_before_ignored_filter = b''
|
||
3 years ago
|
if regex_matched_output:
|
||
2 years ago
|
# @todo some formatter for presentation?
|
||
|
stripped_text_from_html = b''.join(regex_matched_output)
|
||
3 years ago
|
text_content_before_ignored_filter = stripped_text_from_html
|
||
|
|
||
3 years ago
|
# Re #133 - if we should strip whitespaces from triggering the change detected comparison
|
||
|
if self.datastore.data['settings']['application'].get('ignore_whitespace', False):
|
||
|
fetched_md5 = hashlib.md5(stripped_text_from_html.translate(None, b'\r\n\t ')).hexdigest()
|
||
|
else:
|
||
|
fetched_md5 = hashlib.md5(stripped_text_from_html).hexdigest()
|
||
4 years ago
|
|
||
3 years ago
|
############ Blocking rules, after checksum #################
|
||
3 years ago
|
blocked = False
|
||
3 years ago
|
|
||
2 years ago
|
trigger_text = watch.get('trigger_text', [])
|
||
|
if len(trigger_text):
|
||
3 years ago
|
# Assume blocked
|
||
|
blocked = True
|
||
3 years ago
|
# Filter and trigger works the same, so reuse it
|
||
3 years ago
|
# It should return the line numbers that match
|
||
2 years ago
|
# Unblock flow if the trigger was found (some text remained after stripped what didnt match)
|
||
3 years ago
|
result = html_tools.strip_ignore_text(content=str(stripped_text_from_html),
|
||
2 years ago
|
wordlist=trigger_text,
|
||
3 years ago
|
mode="line numbers")
|
||
3 years ago
|
# Unblock if the trigger was found
|
||
3 years ago
|
if result:
|
||
3 years ago
|
blocked = False
|
||
3 years ago
|
|
||
2 years ago
|
text_should_not_be_present = watch.get('text_should_not_be_present', [])
|
||
|
if len(text_should_not_be_present):
|
||
3 years ago
|
# If anything matched, then we should block a change from happening
|
||
|
result = html_tools.strip_ignore_text(content=str(stripped_text_from_html),
|
||
2 years ago
|
wordlist=text_should_not_be_present,
|
||
3 years ago
|
mode="line numbers")
|
||
|
if result:
|
||
|
blocked = True
|
||
|
|
||
|
# The main thing that all this at the moment comes down to :)
|
||
2 years ago
|
if watch.get('previous_md5') != fetched_md5:
|
||
3 years ago
|
changed_detected = True
|
||
3 years ago
|
|
||
3 years ago
|
# Looks like something changed, but did it match all the rules?
|
||
|
if blocked:
|
||
|
changed_detected = False
|
||
|
|
||
6 months ago
|
logger.debug(f"Watch UUID {watch.get('uuid')} content check - Previous MD5: {watch.get('previous_md5')}, Fetched MD5 {fetched_md5}")
|
||
11 months ago
|
|
||
3 years ago
|
if changed_detected:
|
||
|
if watch.get('check_unique_lines', False):
|
||
|
has_unique_lines = watch.lines_contain_something_unique_compared_to_history(lines=stripped_text_from_html.splitlines())
|
||
|
# One or more lines? unsure?
|
||
|
if not has_unique_lines:
|
||
6 months ago
|
logger.debug(f"check_unique_lines: UUID {watch.get('uuid')} didnt have anything new setting change_detected=False")
|
||
3 years ago
|
changed_detected = False
|
||
|
else:
|
||
6 months ago
|
logger.debug(f"check_unique_lines: UUID {watch.get('uuid')} had unique content")
|
||
3 years ago
|
|
||
3 years ago
|
# Always record the new checksum
|
||
|
update_obj["previous_md5"] = fetched_md5
|
||
|
|
||
|
# On the first run of a site, watch['previous_md5'] will be None, set it the current one.
|
||
|
if not watch.get('previous_md5'):
|
||
|
watch['previous_md5'] = fetched_md5
|
||
|
|
||
2 years ago
|
return changed_detected, update_obj, text_content_before_ignored_filter
|