def connect_device_usb() -> NoReturn: global device, device_is_connected, device_name, device_android_version, device_user if not os.path.exists(cfg.adb_key_file_path): keygen(cfg.adb_key_file_path) log_info(f"[ADB] generated and stored a new adb-RSA-key (was missing)", logger="debuglog") with open(cfg.adb_key_file_path) as f: priv = f.read() with open(cfg.adb_key_file_path + '.pub') as f: pub = f.read() signer = PythonRSASigner(pub, priv) try: device = AdbDeviceUsb( ) # TODO: there can be more than one phone, determine with "available", "list" or similar except UsbDeviceNotFoundError: device = None log_error( f"[ADB] is the device connected and ADB activated on device?", logger="debuglog") except DevicePathInvalidError: device = None log_error( "[ADB] installation seems incomplete, adb-shell[usb] is missing (or not working as intended) or adb-server is still running on your system", logger="debuglog") if device is not None: device.connect(rsa_keys=[signer], auth_timeout_s=30) if not is_device_available(): return device_is_connected = True log_info(f"[ADB] connected to USB-Device", logger="debuglog") update_device_properties()
def add_error_message(message: str): """Log message for error. Args: message (str): message to display """ core.log_error(message, logger='##log_message')
def visit_source_web_page(): """ Open Github repository of this project. """ try: webbrowser.open(GITHUB_LINK, new=2) except Exception as e: core.log_error('HelloScreenView - Failed to visit source page with exception : [%s]' % (e))
def _delete_file(self, file_path): try: core.log_debug('DuplicateImagesController - deleting file [%s]' % (file_path)) os.remove(file_path) except Exception as e: core.log_error( 'DuplicateImagesController - delete file [%s] failed with exception [%s]' % (file_path, e))
def load_dataframe(path: str) -> pd.DataFrame: try: data = pd.read_csv(path, sep=cfg.csv_delimiter, encoding=cfg.csv_encoding, decimal=cfg.csv_decimal) except FileNotFoundError: log_error(f"[CSV] '{path}' could not be opened -> does it excist?", logger="debuglog") data = pd.DataFrame() return data
def _start_scan_click_handler(self, sender: str, scan_directories: [str]) -> None: """ Click callback for start scan button """ if len(scan_directories) == 0: core.log_error('View: - scan dirs list is empty') return core.log_debug('View: Starting scan on dirs: %s' % self._scan_directories) self._start_scan_callback(self._scan_directories)
def save_dataframe(df: pd.DataFrame, path: str) -> bool: # TODO: refactor to proper fn with try catch, used at least 3x try: df.to_csv(path, sep=cfg.csv_delimiter, encoding=cfg.csv_encoding, decimal=cfg.csv_decimal) except PermissionError: log_error( f"[CSV] '{path}' could not be saved -> open in another program?", logger="debuglog") return True
def save_to_log(_device: str, package: str, action: str, response: str) -> NoReturn: try: with open(cfg.adb_log_file_path, 'a') as file: timestamp = datetime.now().strftime("%Y-%m-%d_%H:%M:%S") file.write(f"{timestamp} - {_device} - {package} - '{action}': ") file.write( response.replace("\n", ";").replace("\r", ";").strip("\t") + "\n") except PermissionError: log_error( f"[LOG] '{cfg.adb_log_file_path}' could not be modified -> open in another program?", logger="debuglog")
def pull_file_from_device(_remote_file_path: str, _local_file_path: str) -> int: global device if not is_device_available(): return 0 mode, size, mtime = device.stat(_remote_file_path) if size > 0: device.pull(_remote_file_path, _local_file_path) log_info( f"[ADB] pulled file '{_remote_file_path}' from device, size = {size} byte", logger="debuglog") else: log_error(f"[ADB] failed pulling file ({_remote_file_path})", logger="debuglog") return size
def _draw_duplicates_set(self, duplicate_images_list: FileMetaDataList) -> None: """ Draw a single image and all the files containing it. All the files in duplicate_images_list containg duplicate of same image. """ try: file_path = duplicate_images_list[0].GetPath() core.add_drawing( file_path, width=100, height=100, parent=self._window_name) core.draw_image( file_path, file_path, [0, 0], pmax=[100, 100], uv_min=[0, 0], uv_max=[1, 1], tag="image") for file in duplicate_images_list: file_path = file.GetPath() core.add_button( 'Delete ##'+file_path, callback=self._delete_file_button_click_handler, callback_data=file, parent=self._window_name) core.add_same_line(parent=self._window_name) core.add_text( file_path, parent=self._window_name) core.add_separator(parent=self._window_name) except Exception as e: core.log_error('View::_draw_duplicates_set - Exception : [%s]' % (e))
def parse_point(self, s: str): t = time.time() t_str = time.strftime("%T", time.localtime(t)) s = s.strip() raw_str = f"{t_str}: {s}" if (self.raw_log_window != ""): log(raw_str, logger=self.raw_log_window) self.data["raw"].append(raw_str) if s[0] == "#": # parse as a number a = s.strip("#;") a = a.split(":") name = a[0] val = float(a[1]) if name in self.data["plots"]: if len(self.data["plots"][name]["x"]) >= self.maxlen: self.data["plots"][name]["x"].pop(0) self.data["plots"][name]["t"].pop(0) self.data["plots"][name]["x"].append(val) self.data["plots"][name]["t"].append(t) else: self.data["plots"][name] = { "x": (self.maxlen - 1) * [0.] + [val], "t": self.maxlen * [t] } elif s[0] == "!": # parse as error error_msg = f"{t_str}: {s.strip('!;')}" log_error(error_msg, logger=self.log_window) self.data["errors"].append(error_msg) elif s[0] == "?": # parse as warning warning_msg = f"{t_str}: {s.strip('?;')}" log_warning(warning_msg, logger=self.log_window) self.data["warnings"].append(warning_msg) else: info_msg = f"{t_str}: {s.strip(';')}" log_info(info_msg, logger=self.log_window) self.data["messages"].append(info_msg)
def create_new_user_data(sender, data) -> None: initial_data = { "User Name": gg.get_value("##user_name"), "Start Balance": gg.get_value("##balance_input") } if not initial_data["User Name"].isalpha(): gg.add_label_text("Error", color=[255, 0, 0], before="##balance_input", label="Username must be alphabetical") gg.log_error("User-name must be only alphabets") return elif initial_data["User Name"] + ".db" in os.listdir(): gg.add_label_text("Error", color=[255, 0, 0], before="##balance_input",label="Username already exists!") gg.log_error("User-name must be unique") return if initial_data["Start Balance"] <= 0: gg.add_label_text("Error_start_balance", color=[255, 0, 0], before="Proceed",label="Balance must be greater than 0$") gg.log_error("Balance must be greater than 0$!") return create_database(initial_data["User Name"] + ".db", initial_data["Start Balance"]) gg.delete_item("Main") initial_screen()
def update_device_properties() -> int: global device, device_name, device_android_sdk, device_android_version, device_user if not is_device_available(): return 0 manufacturer = device.shell("getprop ro.product.manufacturer").strip( "\n\r") product_name = device.shell("getprop ro.product.device").strip("\n\r") device_name = manufacturer + " " + product_name device_android_version = device.shell( "getprop ro.build.version.release").strip("\n\r") device_android_sdk = int( device.shell("getprop ro.build.version.sdk").strip("\n\r")) log_info( f"[ADB] read device properties, '{device_name}', android {device_android_version}, sdk={device_android_sdk}", logger="debuglog") users = get_device_users() if len(users) > 1: log_info( "[ADB] NOTE - there are several users, will choose first one in list!", logger="debuglog") log_info(str(users), logger="debuglog") device_user = users["index"].iloc[0] if device_android_sdk < 26: log_error("[ADB] Your android version is old (< 8.0).", logger="debuglog") log_error("[ADB] Uninstalled packages can't be restored.", logger="debuglog") log_error("[ADB] The GUI won't stop you from doing so.", logger="debuglog") return device_android_sdk
def log_error(self, message): """ Logs at error level """ c.log_error(message=message, logger=self.logger)