antidetect 2.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
antidetect/__init__.py ADDED
@@ -0,0 +1,29 @@
1
+ from loguru import logger
2
+
3
+ from antidetect.library import Antidetect, AsyncAntidetect
4
+ from antidetect.manager import ProfileManager
5
+ from antidetect.store import Store
6
+ from antidetect.structures import (
7
+ BrowserKind,
8
+ Profile,
9
+ ProxyEntry,
10
+ Settings,
11
+ WebRtcPolicy,
12
+ )
13
+
14
+ __version__ = '2.1.0'
15
+
16
+ # A library stays quiet until the app enables it: logger.enable('antidetect').
17
+ logger.disable('antidetect')
18
+
19
+ __all__ = [
20
+ 'Antidetect',
21
+ 'AsyncAntidetect',
22
+ 'BrowserKind',
23
+ 'Profile',
24
+ 'ProfileManager',
25
+ 'ProxyEntry',
26
+ 'Settings',
27
+ 'Store',
28
+ 'WebRtcPolicy',
29
+ ]
antidetect/__main__.py ADDED
@@ -0,0 +1,19 @@
1
+ from antidetect.cli import Cli
2
+
3
+
4
+ def main():
5
+ """
6
+ Run the command line.
7
+ """
8
+ Cli().run()
9
+
10
+
11
+ def main_gui():
12
+ """
13
+ Open the GUI of a shortcut, in a window of its own when pywebview is installed.
14
+ """
15
+ Cli().run(['gui', '--native'] if Cli.is_native_available() else ['gui'])
16
+
17
+
18
+ if __name__ == '__main__':
19
+ main()
antidetect/browser.py ADDED
@@ -0,0 +1,389 @@
1
+ import json
2
+ import os
3
+ import random
4
+ import re
5
+ import shutil
6
+ import sys
7
+ from functools import lru_cache
8
+ from pathlib import Path
9
+
10
+ import patchright
11
+ from loguru import logger
12
+ from patchright._impl._driver import compute_driver_executable
13
+
14
+ from antidetect.constants import (
15
+ BROWSERS_DIR,
16
+ BROWSERS_PATH_ENV,
17
+ CHROME_PATHS_BY_PLATFORM,
18
+ CHROMIUM_MISSING_HINT,
19
+ INSTALLATION_MARKER_FILE,
20
+ MISSING_EXECUTABLE_TEXT,
21
+ NO_SANDBOX_ENV,
22
+ PATCHRIGHT_FEATURES_END,
23
+ PATCHRIGHT_FEATURES_START,
24
+ REMOVED_DEFAULT_ARGS,
25
+ WEBRTC_PROXY_ONLY_POLICY,
26
+ WINDOW_SIZES,
27
+ )
28
+ from antidetect.geo import GeoLocator
29
+ from antidetect.store import Store
30
+ from antidetect.structures import (
31
+ BrowserKind,
32
+ GeoInfo,
33
+ LaunchOptions,
34
+ LaunchPlan,
35
+ Profile,
36
+ Proxy,
37
+ Settings,
38
+ WebRtcPolicy,
39
+ )
40
+
41
+
42
+ class BrowserUnavailableError(RuntimeError):
43
+ """
44
+ Browser of the profile is not installed.
45
+ """
46
+
47
+
48
+ class ChromeSetup:
49
+ """
50
+ Chrome switches, preferences and launch options of a profile.
51
+ """
52
+
53
+ def __init__(self, settings: Settings):
54
+ self.settings: Settings = settings
55
+
56
+ @staticmethod
57
+ @lru_cache(maxsize=1)
58
+ def determine_default_disable_features() -> str | None:
59
+ """
60
+ Return the --disable-features switch that patchright adds to every launch.
61
+ """
62
+ bundle_path: Path = Path(patchright.__file__).parent / 'driver/package/lib/coreBundle.js'
63
+ bundle: str = bundle_path.read_text(encoding='utf-8')
64
+ start: int = bundle.find(PATCHRIGHT_FEATURES_START)
65
+ end: int = bundle.find(PATCHRIGHT_FEATURES_END, start)
66
+ if start < 0 or end < 0:
67
+ return None
68
+
69
+ # '// See https://github.com/...\n "HttpsUpgrades",' -> 'HttpsUpgrades'
70
+ features_block: str = re.sub(r'//[^\n]*', '', bundle[start:end])
71
+ features: list[str] = [
72
+ feature
73
+ for feature in re.findall(r'"([A-Za-z0-9_]+)"', features_block)
74
+ if feature != 'MediaRouter'
75
+ ]
76
+
77
+ return f'--disable-features={",".join(features)}'
78
+
79
+ @staticmethod
80
+ def is_sandbox_allowed() -> bool:
81
+ """
82
+ Check if Chrome may keep its sandbox.
83
+ """
84
+ if os.environ.get(NO_SANDBOX_ENV) == '1':
85
+ return False
86
+
87
+ return not (sys.platform.startswith('linux') and os.geteuid() == 0)
88
+
89
+ @staticmethod
90
+ def is_webrtc_restricted(plan: LaunchPlan) -> bool:
91
+ """
92
+ Check if WebRTC must use the proxy only.
93
+ """
94
+ if plan.profile.webrtc is WebRtcPolicy.DISABLED:
95
+ return True
96
+
97
+ return plan.profile.webrtc is WebRtcPolicy.PROXY_ONLY and bool(
98
+ plan.browser_proxy,
99
+ )
100
+
101
+ def find_chrome_path(self) -> str | None:
102
+ """
103
+ Return the path of the installed Google Chrome.
104
+ """
105
+ if self.settings.chrome_path:
106
+ return self.settings.chrome_path
107
+
108
+ for candidate in CHROME_PATHS_BY_PLATFORM.get(sys.platform, ()):
109
+ chrome_path: str = os.path.expandvars(candidate)
110
+ if Path(chrome_path).exists():
111
+ return chrome_path
112
+
113
+ return shutil.which('google-chrome') or shutil.which('google-chrome-stable')
114
+
115
+ def determine_default_browser(self) -> BrowserKind:
116
+ """
117
+ Return Google Chrome when it is installed, else Chromium.
118
+ """
119
+ if self.find_chrome_path():
120
+ return BrowserKind.CHROME
121
+
122
+ return BrowserKind.CHROMIUM
123
+
124
+ @staticmethod
125
+ def determine_browsers_path() -> Path:
126
+ """
127
+ Return the folder where the patchright driver keeps downloaded browsers.
128
+ """
129
+ env_path: str | None = os.environ.get(BROWSERS_PATH_ENV)
130
+ if env_path == '0':
131
+ return Path(patchright.__file__).parent / 'driver/package/.local-browsers'
132
+
133
+ if env_path:
134
+ return Path(env_path).expanduser()
135
+
136
+ if sys.platform == 'win32':
137
+ local_path: str = os.environ.get('LOCALAPPDATA') or str(
138
+ Path.home() / 'AppData' / 'Local',
139
+ )
140
+ return Path(local_path) / BROWSERS_DIR
141
+
142
+ if sys.platform == 'darwin':
143
+ return Path.home() / 'Library' / 'Caches' / BROWSERS_DIR
144
+
145
+ cache_path: str = os.environ.get('XDG_CACHE_HOME') or str(Path.home() / '.cache')
146
+
147
+ return Path(cache_path) / BROWSERS_DIR
148
+
149
+ @staticmethod
150
+ @lru_cache(maxsize=1)
151
+ def determine_chromium_revision() -> str:
152
+ """
153
+ Return the Chromium revision of this patchright: browsers.json -> '1248'.
154
+ """
155
+ package_path: Path = Path(patchright.__file__).parent / 'driver/package'
156
+ browsers_file: Path = package_path / 'browsers.json'
157
+ payload: dict = json.loads(browsers_file.read_text(encoding='utf-8'))
158
+
159
+ return next(
160
+ browser['revision']
161
+ for browser in payload['browsers']
162
+ if browser['name'] == 'chromium'
163
+ )
164
+
165
+ def is_chromium_ready(self) -> bool:
166
+ """
167
+ Check if the driver finished the download of the Chromium of this patchright.
168
+ """
169
+ revision: str = self.determine_chromium_revision()
170
+ chromium_path: Path = self.determine_browsers_path() / f'chromium-{revision}'
171
+
172
+ return (chromium_path / INSTALLATION_MARKER_FILE).exists()
173
+
174
+ @staticmethod
175
+ def generate_install_command() -> list[str]:
176
+ """
177
+ Return the driver command that downloads Chromium without the old headless shell.
178
+ """
179
+ node_path, cli_path = compute_driver_executable()
180
+
181
+ return [node_path, cli_path, 'install', '--no-shell', 'chromium']
182
+
183
+ def check_browser(self, browser: BrowserKind) -> str | None:
184
+ """
185
+ Return why the browser cannot start, None when it can.
186
+ """
187
+ if browser is BrowserKind.CHROME and not self.find_chrome_path():
188
+ return 'Google Chrome is not installed: install it or set its path in Settings'
189
+
190
+ if browser is BrowserKind.CHROMIUM and not self.is_chromium_ready():
191
+ return CHROMIUM_MISSING_HINT
192
+
193
+ return None
194
+
195
+ @staticmethod
196
+ def is_browser_missing(error: Exception) -> bool:
197
+ """
198
+ Check if a launch error of patchright says its Chromium is not downloaded.
199
+ """
200
+ return MISSING_EXECUTABLE_TEXT in str(error)
201
+
202
+ def determine_window(
203
+ self,
204
+ profile: Profile,
205
+ user_data_dir: Path,
206
+ headless: bool,
207
+ ) -> tuple[int, int] | None:
208
+ """
209
+ Return the window size: the profile's own, a seeded one on the first start, else none.
210
+ """
211
+ if profile.window_width and profile.window_height:
212
+ return profile.window_width, profile.window_height
213
+
214
+ is_first_start: bool = not (user_data_dir / 'Local State').exists()
215
+ if not is_first_start and not headless:
216
+ return None
217
+
218
+ return random.Random(profile.seed).choice(WINDOW_SIZES)
219
+
220
+ def generate_plan(
221
+ self,
222
+ profile: Profile,
223
+ user_data_dir: Path,
224
+ proxy: Proxy | None,
225
+ browser_proxy: str | None,
226
+ geo: GeoInfo | None,
227
+ headless: bool,
228
+ cdp: bool,
229
+ extension_paths: list[str],
230
+ ) -> LaunchPlan:
231
+ """
232
+ Generate the plan of one launch from the profile and the location of its exit IP.
233
+ """
234
+ languages: list[str] = []
235
+ if profile.language or geo:
236
+ languages = GeoLocator.determine_languages(
237
+ country_code=geo.country_code if geo else None,
238
+ language=profile.language,
239
+ )
240
+ geolocation: tuple[float, float] | None = None
241
+ is_located: bool = (
242
+ profile.geolocation
243
+ and geo is not None
244
+ and geo.latitude is not None
245
+ and geo.longitude is not None
246
+ )
247
+ if is_located:
248
+ geolocation = (geo.latitude, geo.longitude)
249
+
250
+ window: tuple[int, int] | None = self.determine_window(
251
+ profile=profile,
252
+ user_data_dir=user_data_dir,
253
+ headless=headless,
254
+ )
255
+
256
+ return LaunchPlan(
257
+ profile=profile,
258
+ settings=self.settings,
259
+ user_data_dir=user_data_dir,
260
+ proxy=proxy,
261
+ browser_proxy=browser_proxy,
262
+ timezone=profile.timezone or (geo.timezone if geo else None),
263
+ languages=languages,
264
+ geolocation=geolocation,
265
+ window=window,
266
+ headless=headless,
267
+ cdp=cdp or profile.cdp,
268
+ extension_paths=extension_paths if profile.extensions else [],
269
+ )
270
+
271
+ def generate_args(self, plan: LaunchPlan) -> list[str]:
272
+ """
273
+ Generate Chrome switches of a launch.
274
+ """
275
+ args: list[str] = []
276
+ if plan.window:
277
+ args.append(f'--window-size={plan.window[0]},{plan.window[1]}')
278
+ # Chrome on macOS takes the UI language from the system and ignores --lang.
279
+ if plan.languages and sys.platform != 'darwin':
280
+ args.append(f'--lang={plan.languages[0]}')
281
+ if plan.cdp:
282
+ args.append('--remote-debugging-port=0')
283
+ # Chrome hides its bar about unsupported switches with --test-type: patchright passes
284
+ # --disable-blink-features=AutomationControlled and --no-sandbox, both raise it.
285
+ if not plan.headless:
286
+ args.append('--test-type')
287
+ if plan.extension_paths:
288
+ joined_paths: str = ','.join(plan.extension_paths)
289
+ args += [
290
+ f'--disable-extensions-except={joined_paths}',
291
+ f'--load-extension={joined_paths}',
292
+ ]
293
+ # Google Chrome 158 ignores --load-extension. --disable-extensions-except loads the folders
294
+ # once this feature is off.
295
+ if plan.extension_paths and plan.profile.browser is BrowserKind.CHROME:
296
+ args.append('--disable-features=DisableDisableExtensionsExceptCommandLineSwitch')
297
+
298
+ return args
299
+
300
+ @staticmethod
301
+ def generate_env(plan: LaunchPlan) -> dict[str, str]:
302
+ """
303
+ Generate the environment: TZ sets the timezone of every Chrome process except on Windows.
304
+ """
305
+ env: dict[str, str] = dict(os.environ)
306
+ if plan.timezone and sys.platform != 'win32':
307
+ env['TZ'] = plan.timezone
308
+
309
+ return env
310
+
311
+ def write_preferences(self, plan: LaunchPlan):
312
+ """
313
+ Write languages and the WebRTC policy into Default/Preferences the way Chrome keeps them.
314
+ """
315
+ preferences_path: Path = plan.user_data_dir / 'Default' / 'Preferences'
316
+ preferences: dict = {}
317
+ if preferences_path.exists():
318
+ try:
319
+ preferences = json.loads(preferences_path.read_text(encoding='utf-8'))
320
+
321
+ except ValueError:
322
+ # Chrome itself starts over with defaults when its Preferences file is broken.
323
+ logger.warning('Broken Chrome preferences replaced', path=str(preferences_path))
324
+ if plan.languages:
325
+ intl_preferences: dict = preferences.setdefault('intl', {})
326
+ intl_preferences['accept_languages'] = ','.join(plan.languages)
327
+ intl_preferences['selected_languages'] = ','.join(plan.languages)
328
+ # Chrome 158 ignores --force-webrtc-ip-handling-policy, only this preference sets it.
329
+ webrtc_preferences: dict = preferences.setdefault('webrtc', {})
330
+ if self.is_webrtc_restricted(plan):
331
+ webrtc_preferences['ip_handling_policy'] = WEBRTC_PROXY_ONLY_POLICY
332
+ webrtc_preferences['multiple_routes_enabled'] = False
333
+ webrtc_preferences['nonproxied_udp_enabled'] = False
334
+ else:
335
+ webrtc_preferences['ip_handling_policy'] = 'default'
336
+ webrtc_preferences.pop('multiple_routes_enabled', None)
337
+ webrtc_preferences.pop('nonproxied_udp_enabled', None)
338
+ # Without a clean exit Chrome greets the next start with "Restore pages?".
339
+ profile_preferences: dict = preferences.setdefault('profile', {})
340
+ profile_preferences['exit_type'] = 'Normal'
341
+ profile_preferences['exited_cleanly'] = True
342
+ Store.write_atomic(path=preferences_path, text=json.dumps(preferences))
343
+
344
+ def determine_executable(self, browser: BrowserKind) -> str | None:
345
+ """
346
+ Return the binary to start, None for the channel or the bundled Chromium of patchright.
347
+ """
348
+ if browser is BrowserKind.CHROME:
349
+ return self.settings.chrome_path
350
+
351
+ return None
352
+
353
+ def generate_options(self, plan: LaunchPlan) -> LaunchOptions:
354
+ """
355
+ Generate keyword arguments of launch_persistent_context for a plan.
356
+ """
357
+ removed_args: list[str] = list(REMOVED_DEFAULT_ARGS)
358
+ disable_features: str | None = self.determine_default_disable_features()
359
+ if disable_features:
360
+ removed_args.append(disable_features)
361
+ options: LaunchOptions = LaunchOptions(
362
+ user_data_dir=str(plan.user_data_dir),
363
+ headless=plan.headless,
364
+ no_viewport=True,
365
+ args=self.generate_args(plan),
366
+ env=self.generate_env(plan),
367
+ ignore_default_args=removed_args,
368
+ chromium_sandbox=self.is_sandbox_allowed(),
369
+ )
370
+ executable: str | None = self.determine_executable(plan.profile.browser)
371
+ if executable:
372
+ options['executable_path'] = executable
373
+ elif plan.profile.browser is BrowserKind.CHROME:
374
+ options['channel'] = 'chrome'
375
+ elif plan.profile.browser is BrowserKind.CHROMIUM:
376
+ # Headless Chromium without a channel is chrome-headless-shell, the old headless mode.
377
+ options['channel'] = 'chromium'
378
+ if plan.browser_proxy:
379
+ options['proxy'] = {'server': plan.browser_proxy}
380
+ # Windows Chrome ignores TZ: the timezone goes through CDP emulation there.
381
+ if plan.timezone and sys.platform == 'win32':
382
+ options['timezone_id'] = plan.timezone
383
+ if plan.geolocation:
384
+ options['geolocation'] = {
385
+ 'latitude': plan.geolocation[0],
386
+ 'longitude': plan.geolocation[1],
387
+ }
388
+
389
+ return options