homeassistant-addons/screenshotter/rootfs/app/app.py

79 lines
3.3 KiB
Python

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from PIL import Image
import time, os
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import yaml
import datetime
import croniter
image_path = os.environ.get("SCREEN_IMAGE_PATH", default='/tmp')
config_file = os.environ.get("SCREEN_CONFIG", default="/app/config.yaml")
width = os.environ.get("SCREEN_WIDTH", default="640")
height = os.environ.get("SCREEN_HEIGHT", default="480")
rotate = os.environ.get("SCREEN_ROTATE", default="0")
wait = os.environ.get("SCREEN_WAIT", default="5")
ha_url = os.environ.get("SCREEN_HA_URL", default="")
ha_token = os.environ.get("SCREEN_HA_TOKEN", default="")
ha_language = os.environ.get("SCREEN_HA_LANGUAGE", default="en")
# enable browser logging
d = DesiredCapabilities.CHROME
d['loggingPrefs'] = {'browser': 'ALL'}
# Open another headless browser with height extracted above
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument(f"--window-size={width},{height}")
chrome_options.add_argument(f"--lang={ha_language}")
chrome_options.add_argument("--hide-scrollbars")
chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
'like Gecko) Chrome/68.0.3440.84 Safari/537.36')
chrome_options.add_experimental_option('prefs', {'intl.accept_languages': ha_language})
config = None
with open(config_file, "r") as stream:
config = yaml.safe_load(stream)
tasks = []
for image in config["images"]:
now = datetime.datetime.now()
image["croniter"] = croniter.croniter(image["cron"], now)
image["next_execution"] = image["croniter"].get_next(datetime.datetime)
print(f"First execution of {image['name']} at {image['next_execution']}.")
tasks += [image]
while True:
for i, task in enumerate(tasks):
if task["next_execution"] > datetime.datetime.now():
continue
print(f"Running {task['name']}")
driver = webdriver.Chrome(options=chrome_options, desired_capabilities=d)
driver.implicitly_wait(10)
driver.get(task["url"])
time.sleep(int(wait))
if task.get("ha_auth"):
print("Doing HA Auth")
driver.execute_script(f"window.localStorage.setItem('hassTokens', JSON.stringify({{hassUrl: '{ha_url}', access_token: '{ha_token}', token_type: 'Bearer'}}));")
driver.execute_script(f"window.localStorage.setItem('selectedLanguage', '\"{ha_language}\"');")
driver.get(task["url"])
time.sleep(int(wait))
print("Making screenshot")
# save screenshot
file_name = f'/tmp/{task["name"]}.png'
driver.save_screenshot(file_name)
# print messages
for entry in driver.get_log('browser'):
print(entry)
image = Image.open(file_name)
image = image.rotate(int(rotate), expand=True)
file_name = f'{image_path}/{task["name"]}.png'
image.save(file_name)
tasks[i]["next_execution"] = task["croniter"].get_next(datetime.datetime)
print(f"Task finished, next execution: {tasks[i]['next_execution']}")
time.sleep(1)