From bebe60aef3f58868c801f7b42fe9b94fae9ee0fd Mon Sep 17 00:00:00 2001 From: Ace Date: Wed, 8 Nov 2023 20:22:50 +0100 Subject: [PATCH] text-module enhancement This allows an improved approach to load text from URL Also improved the function to check for a connection by attempting three times before giving up --- inkycal/custom/functions.py | 23 +++++----- .../modules/inkycal_textfile_to_display.py | 11 +++-- inkycal/tests/config.py | 2 + .../tests/test_inkycal_textfile_to_display.py | 43 ++++++++----------- requirements.txt | 1 + 5 files changed, 37 insertions(+), 43 deletions(-) diff --git a/inkycal/custom/functions.py b/inkycal/custom/functions.py index 046e8fd..a092007 100644 --- a/inkycal/custom/functions.py +++ b/inkycal/custom/functions.py @@ -6,12 +6,12 @@ Inkycal custom-functions for ease-of-use Copyright by aceinnolab """ import logging -import traceback - -from PIL import Image, ImageDraw, ImageFont, ImageColor -import requests import os import time +import traceback + +import requests +from PIL import Image, ImageDraw, ImageFont logs = logging.getLogger(__name__) logs.setLevel(level=logging.INFO) @@ -267,13 +267,14 @@ def internet_available(): >>> if internet_available(): >>> #...do something that requires internet connectivity """ - - try: - requests.get('https://google.com', timeout=5) - return True - except: - print(f"Network could not be reached: {traceback.print_exc()}") - return False + for attempt in range(3): + try: + requests.get('https://google.com', timeout=5) + return True + except: + print(f"Network could not be reached: {traceback.print_exc()}") + time.sleep(5) + return False def draw_border(image, xy, size, radius=5, thickness=1, shrinkage=(0.1, 0.1)): diff --git a/inkycal/modules/inkycal_textfile_to_display.py b/inkycal/modules/inkycal_textfile_to_display.py index 3d4617e..cd522d9 100644 --- a/inkycal/modules/inkycal_textfile_to_display.py +++ b/inkycal/modules/inkycal_textfile_to_display.py @@ -65,12 +65,6 @@ class TextToDisplay(inkycal_module): im_black = Image.new('RGB', size=im_size, color='white') im_colour = Image.new('RGB', size=im_size, color='white') - # Check if internet is available - if internet_available(): - logger.info('Connection test passed') - else: - raise NetworkNotReachableError - # Set some parameters for formatting feeds line_spacing = 4 text_bbox_height = self.font.getbbox("hg") @@ -87,6 +81,11 @@ class TextToDisplay(inkycal_module): if self.make_request: logger.info("Detected http path, making request") + # Check if internet is available + if internet_available(): + logger.info('Connection test passed') + else: + raise NetworkNotReachableError file_content = urlopen(self.filepath).read().decode('utf-8') else: # Create list containing all lines diff --git a/inkycal/tests/config.py b/inkycal/tests/config.py index cddb6eb..3b846fc 100644 --- a/inkycal/tests/config.py +++ b/inkycal/tests/config.py @@ -28,6 +28,8 @@ class Config: # inkycal_todoist_test TODOIST_API_KEY = get("TODOIST_API_KEY") + TEMP_PATH = f"{basedir}/tmp" + diff --git a/inkycal/tests/test_inkycal_textfile_to_display.py b/inkycal/tests/test_inkycal_textfile_to_display.py index 92afb74..a667af1 100644 --- a/inkycal/tests/test_inkycal_textfile_to_display.py +++ b/inkycal/tests/test_inkycal_textfile_to_display.py @@ -3,14 +3,16 @@ import logging import os import sys import unittest -from inkycal.modules import TextToDisplay as Module +from inkycal.modules import TextToDisplay as Module from inkycal.modules.inky_image import Inkyimage from inkycal.tests import Config + preview = Inkyimage.preview merge = Inkyimage.merge -file_path = None + +temp_path = f"{Config.TEMP_PATH}/temp.txt" dummy_data = [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', ' Donec feugiat facilisis neque vel blandit.', @@ -56,7 +58,7 @@ tests = [ "name": "TextToFile", "config": { "size": [500, 100], - "filepath": file_path, + "filepath": temp_path, "padding_x": 10, "padding_y": 10, "fontsize": 12, @@ -68,7 +70,7 @@ tests = [ "name": "TextToFile", "config": { "size": [500, 400], - "filepath": file_path, + "filepath": "https://de.wikipedia.org/wiki/Nationale_Rotkreuz-_und_Rothalbmond-Gesellschaft", "padding_x": 10, "padding_y": 10, "fontsize": 12, @@ -80,31 +82,19 @@ tests = [ class TestTextToDisplay(unittest.TestCase): + def setUp(self): + self.temp_path = temp_path + if not os.path.exists(self.temp_path): + print("could not find temporary file, creating now.") + with open(self.temp_path, encoding="utf-8", mode="w") as file: + file.writelines(dummy_data) + def test_get_config(self): print('getting data for web-ui...', end="") Module.get_config() print('OK') def test_generate_image(self): - delete_file_after_parse = False - - if not file_path: - delete_file_after_parse = True - print("Filepath does not exist. Creating dummy file") - - tmp_path = "tmp.txt" - with open(tmp_path, mode="w", encoding="utf-8") as file: - file.writelines(dummy_data) - - # update tests with new temp path - for test in tests: - test["config"]["filepath"] = tmp_path - - else: - make_request = bool(file_path.startswith("https://")) - if not make_request and not os.path.exists(file_path): - raise FileNotFoundError("Your text file could not be found") - for test in tests: print(f'test {tests.index(test) + 1} generating image..') module = Module(test) @@ -113,9 +103,10 @@ class TestTextToDisplay(unittest.TestCase): if Config.USE_PREVIEW: preview(merge(im_black, im_colour)) - if delete_file_after_parse: - print("cleaning up temp file") - os.remove("tmp.txt") + def tearDown(self): + if os.path.exists(self.temp_path): + print("deleting temporary file.") + os.remove(self.temp_path) if __name__ == '__main__': diff --git a/requirements.txt b/requirements.txt index 81cc8bb..2bdd099 100644 --- a/requirements.txt +++ b/requirements.txt @@ -23,3 +23,4 @@ typing_extensions==4.8.0 urllib3==2.0.7 python-dotenv==1.0.0 setuptools==68.2.2 +html2text==2020.1.16