Refactor GlobalCommon methods to be static

This commit is contained in:
Guthrie McAfee Armstrong 2022-06-04 17:36:27 -04:00
parent 616ba55db7
commit 30065371e3
No known key found for this signature in database
GPG key ID: ED4DAE89F08242D2
4 changed files with 45 additions and 39 deletions

View file

@ -1,6 +1,11 @@
import os
import sys
import appdirs
CONTAINER_NAME = "dangerzone.rocks/dangerzone"
APPDATA_PATH = appdirs.user_config_dir("dangerzone")
if "DANGERZONE_MODE" in os.environ:
mode = os.environ["DANGERZONE_MODE"]
else:

View file

@ -1,17 +1,15 @@
import sys
import os
import inspect
import appdirs
import platform
import subprocess
import shutil
import json
import gzip
import colorama
from colorama import Fore, Back, Style
from . import CONTAINER_NAME
from .settings import Settings
from .container import convert
class GlobalCommon(object):
@ -32,12 +30,6 @@ class GlobalCommon(object):
# Initialize terminal colors
colorama.init(autoreset=True)
# App data folder
self.appdata_path = appdirs.user_config_dir("dangerzone")
# Container
self.container_name = "dangerzone.rocks/dangerzone"
# Languages supported by tesseract
self.ocr_languages = {
"Afrikaans": "ar",
@ -203,7 +195,7 @@ class GlobalCommon(object):
}
# Load settings
self.settings = Settings(self)
self.settings = Settings()
def display_banner(self):
"""
@ -380,13 +372,15 @@ class GlobalCommon(object):
)
print(Back.BLACK + Fore.YELLOW + Style.DIM + "╰──────────────────────────╯")
def get_container_runtime(self):
@staticmethod
def get_container_runtime():
if platform.system() == "Linux":
return shutil.which("podman")
else:
return shutil.which("docker")
def get_resource_path(self, filename):
@staticmethod
def get_resource_path(filename):
if getattr(sys, "dangerzone_dev", False):
# Look for resources directory relative to python file
prefix = os.path.join(
@ -411,7 +405,8 @@ class GlobalCommon(object):
resource_path = os.path.join(prefix, filename)
return resource_path
def get_subprocess_startupinfo(self):
@staticmethod
def get_subprocess_startupinfo():
if platform.system() == "Windows":
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
@ -419,24 +414,25 @@ class GlobalCommon(object):
else:
return None
def install_container(self):
@staticmethod
def install_container():
"""
Make sure the podman container is installed. Linux only.
"""
if self.is_container_installed():
if GlobalCommon.is_container_installed():
return
# Load the container into podman
print("Installing Dangerzone container image...")
p = subprocess.Popen(
[self.get_container_runtime(), "load"],
[GlobalCommon.get_container_runtime(), "load"],
stdin=subprocess.PIPE,
startupinfo=self.get_subprocess_startupinfo(),
startupinfo=GlobalCommon.get_subprocess_startupinfo(),
)
chunk_size = 10240
compressed_container_path = self.get_resource_path("container.tar.gz")
compressed_container_path = GlobalCommon.get_resource_path("container.tar.gz")
with gzip.open(compressed_container_path) as f:
while True:
chunk = f.read(chunk_size)
@ -446,34 +442,35 @@ class GlobalCommon(object):
break
p.communicate()
if not self.is_container_installed():
if not GlobalCommon.is_container_installed():
print("Failed to install the container image")
return False
print("Container image installed")
return True
def is_container_installed(self):
@staticmethod
def is_container_installed():
"""
See if the podman container is installed. Linux only.
"""
# Get the image id
with open(self.get_resource_path("image-id.txt")) as f:
with open(GlobalCommon.get_resource_path("image-id.txt")) as f:
expected_image_id = f.read().strip()
# See if this image is already installed
installed = False
found_image_id = subprocess.check_output(
[
self.get_container_runtime(),
GlobalCommon.get_container_runtime(),
"image",
"list",
"--format",
"{{.ID}}",
self.container_name,
CONTAINER_NAME,
],
text=True,
startupinfo=self.get_subprocess_startupinfo(),
startupinfo=GlobalCommon.get_subprocess_startupinfo(),
)
found_image_id = found_image_id.strip()
@ -486,8 +483,8 @@ class GlobalCommon(object):
try:
subprocess.check_output(
[self.get_container_runtime(), "rmi", "--force", found_image_id],
startupinfo=self.get_subprocess_startupinfo(),
[GlobalCommon.get_container_runtime(), "rmi", "--force", found_image_id],
startupinfo=GlobalCommon.get_subprocess_startupinfo(),
)
except:
print("Couldn't delete old container image, so leaving it there")

View file

@ -17,8 +17,6 @@ elif platform.system() == "Linux":
import getpass
from xdg.DesktopEntry import DesktopEntry # type: ignore
from ..settings import Settings
class GuiCommon(object):
"""
@ -41,11 +39,12 @@ class GuiCommon(object):
# Are we done waiting (for Docker Desktop to be installed, or for container to install)
self.is_waiting_finished = False
def get_window_icon(self):
@staticmethod
def get_window_icon():
if platform.system() == "Windows":
path = self.global_common.get_resource_path("dangerzone.ico")
path = GlobalCommon.get_resource_path("dangerzone.ico")
else:
path = self.global_common.get_resource_path("icon.png")
path = GlobalCommon.get_resource_path("icon.png")
return QtGui.QIcon(path)
def open_pdf_viewer(self, filename: str):
@ -111,7 +110,12 @@ class GuiCommon(object):
class Alert(QtWidgets.QDialog):
def __init__(
self, gui_common, global_common, message, ok_text="Ok", extra_button_text=None
self,
gui_common: GuiCommon,
global_common: GlobalCommon,
message: str,
ok_text="Ok",
extra_button_text=None,
):
super(Alert, self).__init__()
self.global_common = global_common
@ -121,8 +125,8 @@ class Alert(QtWidgets.QDialog):
self.setWindowIcon(self.gui_common.get_window_icon())
self.setModal(True)
flags = (
QtCore.Qt.CustomizeWindowHint
flags = ( # TODO Mypy: unsupported left operand type for | ("WindowType")
QtCore.Qt.CustomizeWindowHint # type: ignore
| QtCore.Qt.WindowTitleHint
| QtCore.Qt.WindowSystemMenuHint
| QtCore.Qt.WindowCloseButtonHint

View file

@ -1,12 +1,12 @@
import os
import json
import appdirs
from dangerzone import APPDATA_PATH
class Settings:
def __init__(self, common):
self.common = common
self.settings_filename = os.path.join(self.common.appdata_path, "settings.json")
def __init__(self):
self.settings_filename = os.path.join(APPDATA_PATH, "settings.json")
self.default_settings = {
"save": True,
"ocr": True,
@ -47,6 +47,6 @@ class Settings:
self.save()
def save(self):
os.makedirs(self.common.appdata_path, exist_ok=True)
os.makedirs(APPDATA_PATH, exist_ok=True)
with open(self.settings_filename, "w") as settings_file:
json.dump(self.settings, settings_file, indent=4)