# Code Custodian File ID: 4D9F7BD7-5957-462B-A852-76FD51FCD05F import socket import json import urllib.request import struct import os import sys import time import subprocess CHROME_PATH = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" CHROME_PROFILE = "/Volumes/FACTORY_SSD/warezfactory/Art_Cannon/Chrome/chrome_automation_profile" PRIMARY_URL = "https://app.artistly.ai" def is_chrome_running(port=9222): try: with urllib.request.urlopen(f"http://127.0.0.1:{port}/json", timeout=1) as resp: return resp.status == 200 except Exception: return False def ensure_chrome_running(port=9222): if is_chrome_running(port): return True print(f"Chrome remote debugging port {port} not responsive. Launching Chrome...") args = [ CHROME_PATH, f"--remote-debugging-port={port}", f"--user-data-dir={CHROME_PROFILE}", "--no-first-run", "--no-default-browser-check", PRIMARY_URL ] subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) start_time = time.time() while time.time() - start_time < 6.0: time.sleep(0.5) if is_chrome_running(port): print(f"Chrome successfully launched and listening on port {port}.") return True raise ConnectionError(f"Timed out after 6 seconds waiting for Chrome on port {port}.") class ArtistlyCDP: def __init__(self, port=9222, target_keyword="app.artistly.ai", auto_boot=True): self.port = port self.target_keyword = target_keyword self.auto_boot = auto_boot self.sock = None self.cmd_id = 0 self.target = None self.connect() def connect(self): if self.auto_boot: ensure_chrome_running(self.port) try: with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json", timeout=3) as resp: targets = json.loads(resp.read().decode("utf-8")) except Exception as e: raise ConnectionError(f"Failed to connect to Chrome on port {self.port}: {e}") # Filter page targets strictly for type == "page" page_targets = [t for t in targets if t.get("type") == "page"] # Rogue Tab Hygiene: Identify and close rogue/stray popups valid_artistly_targets = [] for t in page_targets: url = t.get("url", "") target_id = t.get("id") # Strict filter: target must be app.artistly.ai and not a stray support/redirect popup is_app_artistly = "app.artistly.ai" in url and "artistly.ai/support" not in url if not is_app_artistly: print(f"Closing rogue/stray target [{target_id}]: {t.get('title', 'Unknown')} ({url})") try: with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json/close/{target_id}", timeout=3) as _: pass except Exception as err: print(f"Warning: Failed to close target {target_id}: {err}") else: valid_artistly_targets.append(t) # Re-fetch targets if all pages were closed or if valid targets were found if not valid_artistly_targets: # Check if there is any target or if we need to open primary URL try: with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json", timeout=3) as resp: fresh_targets = json.loads(resp.read().decode("utf-8")) valid_artistly_targets = [t for t in fresh_targets if t.get("type") == "page" and "app.artistly.ai" in t.get("url", "")] except Exception: pass # Target Lock: Match target_keyword first, otherwise fallback to any app.artistly.ai page if self.target_keyword: self.target = next((t for t in valid_artistly_targets if self.target_keyword in t.get("url", "")), None) if not self.target and valid_artistly_targets: self.target = valid_artistly_targets[0] if not self.target: raise ValueError(f"No valid Artistly page target found matching '{self.target_keyword}'.") page_id = self.target["id"] # Activate and bring primary page tab to the foreground try: with urllib.request.urlopen(f"http://127.0.0.1:{self.port}/json/activate/{page_id}", timeout=3) as _: pass except Exception as e: print(f"Warning: Failed to activate target {page_id}: {e}") # Establish WebSocket strictly to activated primary target path = f"/devtools/page/{page_id}" self.sock = socket.create_connection(("127.0.0.1", self.port), timeout=10) self.sock.settimeout(10.0) key = "dGhlIHNhbXBsZSBub25jZQ==" req = ( f"GET {path} HTTP/1.1\r\n" f"Host: 127.0.0.1:{self.port}\r\n" f"Upgrade: websocket\r\n" f"Connection: Upgrade\r\n" f"Sec-WebSocket-Key: {key}\r\n" f"Sec-WebSocket-Version: 13\r\n\r\n" ) self.sock.sendall(req.encode("utf-8")) resp_header = b"" while b"\r\n\r\n" not in resp_header: chunk = self.sock.recv(1024) if not chunk: break resp_header += chunk if b"101" not in resp_header: raise ConnectionError("WebSocket upgrade failed.") def send(self, method, params=None): self.cmd_id += 1 cmd_dict = {"id": self.cmd_id, "method": method, "params": params or {}} payload_bytes = json.dumps(cmd_dict).encode("utf-8") length = len(payload_bytes) mask_key = os.urandom(4) masked_payload = bytearray(length) for i in range(length): masked_payload[i] = payload_bytes[i] ^ mask_key[i % 4] if length <= 125: header = struct.pack("!BB", 0x81, 0x80 | length) + mask_key elif length <= 65535: header = struct.pack("!BBH", 0x81, 0x80 | 126, length) + mask_key else: header = struct.pack("!BBQ", 0x81, 0x80 | 127, length) + mask_key self.sock.sendall(header + masked_payload) raw_resp = self.sock.recv(2) b1, b2 = struct.unpack("!BB", raw_resp) payload_len = b2 & 0x7F if payload_len == 126: ext = self.sock.recv(2) payload_len = struct.unpack("!H", ext)[0] elif payload_len == 127: ext = self.sock.recv(8) payload_len = struct.unpack("!Q", ext)[0] response_data = b"" while len(response_data) < payload_len: chunk = self.sock.recv(min(4096, payload_len - len(response_data))) if not chunk: break response_data += chunk return json.loads(response_data.decode("utf-8")) def evaluate(self, js_code): res = self.send("Runtime.evaluate", {"expression": js_code, "returnByValue": True}) return res.get("result", {}).get("result", {}).get("value") def dismiss_modals(self): for _ in range(3): self.send("Input.dispatchKeyEvent", {"type": "rawKeyDown", "windowsVirtualKeyCode": 27}) time.sleep(0.05) self.send("Input.dispatchKeyEvent", {"type": "keyUp", "windowsVirtualKeyCode": 27}) time.sleep(0.1) time.sleep(0.3) def navigate(self, url): self.send("Page.navigate", {"url": url}) time.sleep(3) self.dismiss_modals() def click_coordinate(self, x, y): self.send("Input.dispatchMouseEvent", {"type": "mouseMoved", "x": x, "y": y}) time.sleep(0.03) self.send("Input.dispatchMouseEvent", {"type": "mousePressed", "x": x, "y": y, "button": "left", "clickCount": 1}) time.sleep(0.03) self.send("Input.dispatchMouseEvent", {"type": "mouseReleased", "x": x, "y": y, "button": "left", "clickCount": 1}) def click_element_by_text(self, text_target): js = f""" (() => {{ const all = Array.from(document.querySelectorAll('*')); const el = all.find(e => e.children.length === 0 && e.innerText && e.innerText.trim() === {json.dumps(text_target)}); if (!el) return null; const clickable = el.closest('button, [role="button"], .cursor-pointer') || el; clickable.scrollIntoView({{ behavior: 'instant', block: 'center' }}); const rect = clickable.getBoundingClientRect(); return {{ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2, width: rect.width, height: rect.height, visible: rect.width > 0 && rect.height > 0 }}; }})() """ coords = self.evaluate(js) if not coords or not coords.get("visible"): return False, f"Element with text '{text_target}' not visible or not found." time.sleep(0.1) self.click_coordinate(int(coords["x"]), int(coords["y"])) return True, coords def inject_prompt(self, prompt_text): js = f""" (() => {{ const textarea = document.querySelector('textarea'); if (!textarea) return false; textarea.focus(); const setter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set; setter.call(textarea, {json.dumps(prompt_text)}); textarea.dispatchEvent(new Event('input', {{ bubbles: true }})); textarea.dispatchEvent(new Event('change', {{ bubbles: true }})); return textarea.value; }})() """ return self.evaluate(js) def close(self): if self.sock: self.sock.close() def check(): print("Executing Artistly CDP Health Check, Target Lock & Tab Hygiene...") try: cdp = ArtistlyCDP(auto_boot=True) title = cdp.target.get("title", "Unknown") url = cdp.target.get("url", "Unknown") target_id = cdp.target.get("id", "Unknown") print(f"[SUCCESS] Target Locked: {title}") print(f" URL: {url}") print(f" Target ID: {target_id}") cdp.close() return 0 except Exception as e: print(f"[ERROR] Health check failed: {e}", file=sys.stderr) return 1 if __name__ == "__main__": if len(sys.argv) == 1 or sys.argv[1] in ("--check", "-c"): sys.exit(check()) else: print(f"Usage: {sys.argv[0]} [--check]") sys.exit(1)