Add files via upload

This commit is contained in:
FatihMakes authored and GitHub committed 2026-05-02 11:51:56 +03:00
1 parent ff7a982d82
commit c36079104e
17 files changed
+2854 -1210

No files matched your search

+2 -70
View File
@@ -1,15 +1,3 @@
"""
browser_control.py — JARVIS Browser Action Module
====================================================
Desteklenen tarayıcılar : chrome, edge, firefox, opera, operagx, brave, vivaldi, safari (macOS)
Desteklenen platformlar : Windows · macOS · Linux
Her tarayıcı için bağımsız _BrowserSession örneği tutulur.
"switch" action ile aktif tarayıcı değiştirilebilir.
NOT: Tüm tarayıcılar kullanıcının gerçek profiliyle açılır (hesaplar, çerezler korunur).
Gizli/incognito mod kullanılmaz.
"""
from __future__ import annotations
@@ -30,12 +18,8 @@ from playwright.async_api import (
Playwright,
TimeoutError as PlaywrightTimeout,
)
# ── Platform ──────────────────────────────────────────────────────────────────
_OS = platform.system() # "Windows" | "Darwin" | "Linux"
# ── URL normalizer ────────────────────────────────────────────────────────────
def _normalize_url(url: str) -> str:
"""
Bare words like "instagram" → "https://instagram.com"
@@ -53,7 +37,6 @@ def _normalize_url(url: str) -> str:
return "https://" + url
# ── User-Agent ────────────────────────────────────────────────────────────────
def _user_agent() -> str:
if _OS == "Windows":
return (
@@ -74,7 +57,6 @@ def _user_agent() -> str:
)
# ── Gerçek kullanıcı profil dizini (tüm tarayıcılar) ─────────────────────────
def _real_profile_dir(browser: str) -> str:
home = Path.home()
local = os.environ.get("LOCALAPPDATA", "")
@@ -129,8 +111,6 @@ def _real_profile_dir(browser: str) -> str:
print(f"[Browser] ⚠️ Real profile not found for {browser}, using: {fallback}")
return str(fallback)
# ── Firefox gerçek profil dizini ──────────────────────────────────────────────
def _firefox_profile_dir() -> Optional[str]:
home = Path.home()
@@ -170,8 +150,6 @@ def _firefox_profile_dir() -> Optional[str]:
return default_path
return None
# ── Windows: Opera exe tespiti ────────────────────────────────────────────────
def _find_opera_windows() -> Optional[str]:
local = os.environ.get("LOCALAPPDATA", "")
prog = os.environ.get("PROGRAMFILES", "")
@@ -213,8 +191,6 @@ def _find_opera_windows() -> Optional[str]:
return shutil.which("opera") or None
# ── Genel exe arama (Windows registry) ───────────────────────────────────────
def _find_exe_windows(prog_name: str) -> Optional[str]:
try:
import winreg
@@ -237,8 +213,6 @@ def _find_exe_windows(prog_name: str) -> Optional[str]:
pass
return None
# ── Tarayıcı tanım tablosu ────────────────────────────────────────────────────
_BROWSER_SPECS: dict[str, dict] = {
"Windows": {
"chrome": {"engine": "chromium", "channel": "chrome", "bins": []},
@@ -370,8 +344,6 @@ def _detect_default_browser() -> str:
return "chrome"
# ── Tek tarayıcı oturumu ──────────────────────────────────────────────────────
class _BrowserSession:
"""
Bir tarayıcı örneği için tam oturum.
@@ -390,8 +362,6 @@ class _BrowserSession:
self._context: BrowserContext | None = None
self._page: Page | None = None
# ── Yaşam döngüsü ─────────────────────────────────────────────────────────
def start(self):
if self._thread and self._thread.is_alive():
return
@@ -436,8 +406,6 @@ class _BrowserSession:
pass
self._context = self._page = None
# ── Tarayıcı başlatma ──────────────────────────────────────────────────────
async def _launch(self):
"""
Tarayıcıyı gerçek kullanıcı profiliyle başlatır.
@@ -456,7 +424,6 @@ class _BrowserSession:
channel = self._spec["channel"]
engine_obj = getattr(self._pw, engine_name)
# ── Firefox ───────────────────────────────────────────────────────────
if engine_name == "firefox":
profile = _firefox_profile_dir() or str(
Path.home() / ".jarvis_profiles" / "firefox"
@@ -477,14 +444,11 @@ class _BrowserSession:
Path(jarvis).mkdir(parents=True, exist_ok=True)
self._context = await engine_obj.launch_persistent_context(jarvis, **kwargs)
await asyncio.sleep(0.5) # let the browser settle
# Always open a dedicated JARVIS tab instead of grabbing pages[0],
# which may already be about:blank or a stale restored tab.
await asyncio.sleep(0.5)
self._page = await self._context.new_page()
print(f"[Browser] ✅ Firefox launched")
return
# ── Safari (webkit) ───────────────────────────────────────────────────
if engine_name == "webkit":
safari_profile = str(Path.home() / ".jarvis_profiles" / "safari")
Path(safari_profile).mkdir(parents=True, exist_ok=True)
@@ -500,7 +464,6 @@ class _BrowserSession:
print(f"[Browser] ✅ Safari launched")
return
# ── Chromium tabanlı ──────────────────────────────────────────────────
profile = _real_profile_dir(self.browser_name)
kwargs = {
@@ -528,17 +491,15 @@ class _BrowserSession:
+ (f" @ {exe}" if exe else "")
)
# 1) Gerçek profil
try:
self._context = await engine_obj.launch_persistent_context(profile, **kwargs)
await asyncio.sleep(0.5) # let the browser settle before any navigation
await asyncio.sleep(0.5)
self._page = await self._context.new_page()
print(f"[Browser] ✅ Launched [{label}] profile={profile}")
return
except Exception as e:
print(f"[Browser] ⚠️ Real profile failed for {label}: {e}")
# 2) JARVIS fallback profili
jarvis_profile = str(Path.home() / ".jarvis_profiles" / self.browser_name)
Path(jarvis_profile).mkdir(parents=True, exist_ok=True)
print(f"[Browser] Retrying with JARVIS profile: {jarvis_profile}")
@@ -551,7 +512,6 @@ class _BrowserSession:
except Exception as e2:
raise RuntimeError(f"Could not launch {self.browser_name}: {e2}") from e2
# ── Sayfa erişimi ─────────────────────────────────────────────────────────
async def _get_page(self) -> Page:
await self._launch()
@@ -561,18 +521,8 @@ class _BrowserSession:
await asyncio.sleep(0.2)
return self._page
# ── Action'lar ────────────────────────────────────────────────────────────
async def go_to(self, url: str) -> str:
"""
Navigate to a URL.
• Uses a 30-second timeout to handle heavy sites like YouTube.
• On PlaywrightTimeout we check whether the URL actually changed;
if it did, treat it as success so JARVIS won't retry endlessly.
• If the page is still about:blank after navigation, open a fresh tab
and try once more (covers stale-page edge cases in Opera GX etc.).
"""
url = _normalize_url(url)
page = await self._get_page()
prev_url = page.url
@@ -590,7 +540,6 @@ class _BrowserSession:
result_url = await _do_goto(page)
# If page didn't move away from blank, retry on a brand-new tab
if result_url in ("about:blank", "", None, prev_url) and prev_url in ("about:blank", "", None):
print(f"[Browser] Still blank after goto — retrying on new tab: {url}")
try:
@@ -785,9 +734,6 @@ class _BrowserSession:
await self._async_close()
return f"{self.browser_name} closed."
# ── Session registry ──────────────────────────────────────────────────────────
class _SessionRegistry:
"""Tüm aktif tarayıcı oturumlarını yönetir."""
@@ -855,26 +801,12 @@ class _SessionRegistry:
_registry = _SessionRegistry()
# ── Ana fonksiyon ─────────────────────────────────────────────────────────────
def browser_control(
parameters: dict = None,
response=None,
player=None,
session_memory=None,
) -> str:
"""
Desteklenen action'lar:
go_to, search, click, type, scroll, fill_form,
smart_click, smart_type, get_text, get_url, press,
new_tab, close_tab, screenshot, back, forward, reload,
switch, list_browsers, close, close_all
Parametre:
browser : chrome | edge | firefox | opera | operagx | brave | vivaldi | safari
(belirtilmezse aktif tarayıcı kullanılır)
"""
params = parameters or {}
action = params.get("action", "").lower().strip()
browser = params.get("browser", "").lower().strip() or None