Path: blob/master/docker/platerec_installer/installer_helpers.py
1091 views
import os1import platform2import subprocess3import sys4import webbrowser5from pathlib import Path6from ssl import SSLError78from stream_config import DEFAULT_CONFIG, base_config910try:11from urllib.error import URLError12from urllib.request import Request, urlopen13except ImportError:14from urllib2 import Request, URLError, urlopen # type: ignore151617def get_os():18os_system = platform.system()19if os_system == "Windows":20return "Windows"21elif os_system == "Linux":22return "Linux"23elif os_system == "Darwin":24return "Mac OS"25return os_system262728class DockerPermissionError(Exception):29pass303132def verify_docker_install():33try:34subprocess.check_output(35"docker info".split(), stderr=subprocess.STDOUT36).decode()37return True38except subprocess.CalledProcessError as exc:39output = exc.output.decode()40perm_error = "Got permission denied while trying to connect"41if perm_error in output:42raise DockerPermissionError(output) from exc43return False444546def get_container_id(image):47cmd = f"docker ps -q --filter ancestor={image}"48output = subprocess.check_output(cmd.split())49return output.decode()505152def stop_container(image):53container_id = get_container_id(image)54if container_id:55cmd = f"docker stop {container_id}"56os.system(cmd)57return container_id585960def get_home(product="stream"):61return str(Path.home() / product)626364def get_image(image):65images = (66subprocess.check_output(67["docker", "images", "--format", '"{{.Repository}}:{{.Tag}}"', image]68)69.decode()70.split("\n")71)72return images[0].replace('"', "")737475def pull_docker(image):76if get_container_id(image):77stop_container(image)78pull_cmd = f"docker pull {image}"79os.system(pull_cmd)808182def read_config(home):83try:84config = Path(home) / "config.ini"85conf = ""86f = open(config)87for line in f:88conf += line89f.close()90return conf91except OSError: # file not found92return DEFAULT_CONFIG939495def write_config(home, config):96try:97path = Path(home) / "config.ini"98os.makedirs(os.path.dirname(path), exist_ok=True)99result, error = base_config(path, config)100if error:101return False, error102with open(path, "w+") as conf:103for line in config:104conf.write(line)105return True, ""106except Exception:107return (108False,109f"The Installation Directory is not valid. Please enter a valid folder, such as {get_home()}",110)111112113def verify_token(token, license_key, get_license=True, product="stream"):114path = "stream/license" if product == "stream" else "sdk-webhooks"115if not (token and license_key):116return False, "API token and license key is required."117try:118req = Request(119f"https://api.platerecognizer.com/v1/{path}/{license_key.strip()}/"120)121req.add_header("Authorization", f"Token {token.strip()}")122urlopen(req).read()123return True, None124except SSLError:125req = Request(126f"http://api.platerecognizer.com/v1/{path}/{license_key.strip()}/"127)128req.add_header("Authorization", f"Token {token.strip()}")129urlopen(req).read()130return True, None131except URLError as e:132if "404" in str(e) and get_license:133return (134False,135"The License Key cannot be found. Please use the correct License Key.",136)137elif str(403) in str(e):138return False, "The API Token cannot be found. Please use the correct Token."139else:140return True, None141142143def is_valid_port(port):144try:145return 0 <= int(port) <= 65535146except ValueError:147return False148149150def resource_path(relative_path):151# get absolute path to resource152try:153# PyInstaller creates a temp folder and stores path in _MEIPASS154base_path = sys._MEIPASS155except Exception:156base_path = os.path.abspath(".")157158return os.path.join(base_path, relative_path)159160161def uninstall_docker_image(hardware):162container_id = get_container_id(hardware)163if container_id:164cmd = f"docker container rm {container_id}"165os.system(cmd)166cmd = f'docker rmi "{hardware}" -f'167os.system(cmd)168cmd = "docker image prune -f"169os.system(cmd)170return [None, "Image successfully uninstalled."]171172173def launch_browser(url):174os_platform = get_os()175if os_platform in ["Windows", "Darwin"]:176return webbrowser.open(url)177elif os_platform == "Linux":178opener = "xdg-open"179# remove all environment variables that contain the 'tmp' directory.180my_env = dict(os.environ)181to_delete = []182for k, v in my_env.items():183if k != "PATH" and "tmp" in v:184to_delete.append(k)185for k in to_delete:186my_env.pop(k, None)187try:188subprocess.call([opener, url], env=my_env, shell=False)189except (190FileNotFoundError191): # [Errno 2] No such file or directory: 'xdg-open': 'xdg-open'192print(f"Unable to launch browser: {opener} command not found")193else:194raise Exception(f"Unrecognized OS platform: {os_platform}")195196197