Updated script that can be controled by Nodejs web app

This commit is contained in:
mac OS
2024-11-25 12:24:18 +07:00
parent c440eda1f4
commit 8b0ab2bd3a
8662 changed files with 1803808 additions and 34 deletions

View File

@ -0,0 +1,16 @@
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.

View File

@ -0,0 +1,115 @@
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import typing
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.options import ArgOptions
class _SafariOptionsDescriptor:
"""_SafariOptionsDescriptor is an implementation of Descriptor protocol:
: Any look-up or assignment to the below attributes in `Options` class will be intercepted
by `__get__` and `__set__` method respectively.
- `automatic_inspection`
- `automatic_profiling`
- `use_technology_preview`
: When an attribute lookup happens,
Example:
`self.automatic_inspection`
`__get__` method does a dictionary look up in the dictionary `_caps` of `Options` class
and returns the value of key `safari:automaticInspection`
: When an attribute assignment happens,
Example:
`self.automatic_inspection` = True
`__set__` method sets/updates the value of the key `safari:automaticInspection` in `_caps`
dictionary in `Options` class.
"""
def __init__(self, name, expected_type):
self.name = name
self.expected_type = expected_type
def __get__(self, obj, cls):
if self.name == "Safari Technology Preview":
return obj._caps.get("browserName") == self.name
return obj._caps.get(self.name)
def __set__(self, obj, value):
if not isinstance(value, self.expected_type):
raise TypeError(f"{self.name} must be of type {self.expected_type}")
if self.name == "Safari Technology Preview":
obj._caps["browserName"] = self.name if value else "safari"
else:
obj._caps[self.name] = value
class Options(ArgOptions):
# @see https://developer.apple.com/documentation/webkit/about_webdriver_for_safari
AUTOMATIC_INSPECTION = "safari:automaticInspection"
AUTOMATIC_PROFILING = "safari:automaticProfiling"
SAFARI_TECH_PREVIEW = "Safari Technology Preview"
# creating descriptor objects
automatic_inspection = _SafariOptionsDescriptor(AUTOMATIC_INSPECTION, bool)
"""Get or Set Automatic Inspection value:
Usage
-----
- Get
- `self.automatic_inspection`
- Set
- `self.automatic_inspection` = `value`
Parameters
----------
`value`: `bool`
"""
automatic_profiling = _SafariOptionsDescriptor(AUTOMATIC_PROFILING, bool)
"""Get or Set Automatic Profiling value:
Usage
-----
- Get
- `self.automatic_profiling`
- Set
- `self.automatic_profiling` = `value`
Parameters
----------
`value`: `bool`
"""
use_technology_preview = _SafariOptionsDescriptor(SAFARI_TECH_PREVIEW, bool)
"""Get and Set Technology Preview:
Usage
-----
- Get
- `self.use_technology_preview`
- Set
- `self.use_technology_preview` = `value`
Parameters
----------
`value`: `bool`
"""
@property
def default_capabilities(self) -> typing.Dict[str, str]:
return DesiredCapabilities.SAFARI.copy()

View File

@ -0,0 +1,23 @@
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""The Permission implementation."""
class Permission:
"""Set of supported permissions."""
GET_USER_MEDIA = "getUserMedia"

View File

@ -0,0 +1,45 @@
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from typing import Optional
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.remote.client_config import ClientConfig
from selenium.webdriver.remote.remote_connection import RemoteConnection
class SafariRemoteConnection(RemoteConnection):
browser_name = DesiredCapabilities.SAFARI["browserName"]
def __init__(
self,
remote_server_addr: str,
keep_alive: bool = True,
ignore_proxy: Optional[bool] = False,
client_config: Optional[ClientConfig] = None,
) -> None:
client_config = client_config or ClientConfig(
remote_server_addr=remote_server_addr, keep_alive=keep_alive, timeout=120
)
super().__init__(
ignore_proxy=ignore_proxy,
client_config=client_config,
)
self._commands["GET_PERMISSIONS"] = ("GET", "/session/$sessionId/apple/permissions")
self._commands["SET_PERMISSIONS"] = ("POST", "/session/$sessionId/apple/permissions")
self._commands["ATTACH_DEBUGGER"] = ("POST", "/session/$sessionId/apple/attach_debugger")

View File

@ -0,0 +1,76 @@
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import typing
from selenium.webdriver.common import service
class Service(service.Service):
"""A Service class that is responsible for the starting and stopping of
`safaridriver` This is only supported on MAC OSX.
:param executable_path: install path of the safaridriver executable, defaults to `/usr/bin/safaridriver`.
:param port: Port for the service to run on, defaults to 0 where the operating system will decide.
:param service_args: (Optional) List of args to be passed to the subprocess when launching the executable.
:param env: (Optional) Mapping of environment variables for the new process, defaults to `os.environ`.
:param enable_logging: (Optional) Enable logging of the service. Logs can be located at `~/Library/Logs/com.apple.WebDriver/`
"""
def __init__(
self,
executable_path: str = None,
port: int = 0,
service_args: typing.Optional[typing.List[str]] = None,
env: typing.Optional[typing.Mapping[str, str]] = None,
reuse_service=False,
enable_logging: bool = False,
driver_path_env_key: str = None,
**kwargs,
) -> None:
self.service_args = service_args or []
driver_path_env_key = driver_path_env_key or "SE_SAFARIDRIVER"
if enable_logging:
self.service_args.append("--diagnose")
self.reuse_service = reuse_service
super().__init__(
executable_path=executable_path,
port=port,
env=env,
driver_path_env_key=driver_path_env_key,
**kwargs,
)
def command_line_args(self) -> typing.List[str]:
return ["-p", f"{self.port}"] + self.service_args
@property
def service_url(self) -> str:
"""Gets the url of the SafariDriver Service."""
return f"http://localhost:{self.port}"
@property
def reuse_service(self) -> bool:
return self._reuse_service
@reuse_service.setter
def reuse_service(self, reuse: bool) -> None:
if not isinstance(reuse, bool):
raise TypeError("reuse must be a boolean")
self._reuse_service = reuse

View File

@ -0,0 +1,109 @@
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.remote.client_config import ClientConfig
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
from ..common.driver_finder import DriverFinder
from .options import Options
from .remote_connection import SafariRemoteConnection
from .service import Service
class WebDriver(RemoteWebDriver):
"""Controls the SafariDriver and allows you to drive the browser."""
def __init__(
self,
keep_alive=True,
options: Options = None,
service: Service = None,
) -> None:
"""Creates a new Safari driver instance and launches or finds a running
safaridriver service.
:Args:
- keep_alive - Whether to configure SafariRemoteConnection to use
HTTP keep-alive. Defaults to True.
- options - Instance of ``options.Options``.
- service - Service object for handling the browser driver if you need to pass extra details
"""
self.service = service if service else Service()
options = options if options else Options()
self.service.path = self.service.env_path() or DriverFinder(self.service, options).get_driver_path()
if not self.service.reuse_service:
self.service.start()
client_config = ClientConfig(remote_server_addr=self.service.service_url, keep_alive=keep_alive, timeout=120)
executor = SafariRemoteConnection(
ignore_proxy=options._ignore_local_proxy,
client_config=client_config,
)
try:
super().__init__(command_executor=executor, options=options)
except Exception:
self.quit()
raise
self._is_remote = False
def quit(self):
"""Closes the browser and shuts down the SafariDriver executable."""
try:
super().quit()
except Exception:
# We don't care about the message because something probably has gone wrong
pass
finally:
if not self.service.reuse_service:
self.service.stop()
# safaridriver extension commands. The canonical command support matrix is here:
# https://developer.apple.com/library/content/documentation/NetworkingInternetWeb/Conceptual/WebDriverEndpointDoc/Commands/Commands.html
# First available in Safari 11.1 and Safari Technology Preview 41.
def set_permission(self, permission, value):
if not isinstance(value, bool):
raise WebDriverException("Value of a session permission must be set to True or False.")
payload = {permission: value}
self.execute("SET_PERMISSIONS", {"permissions": payload})
# First available in Safari 11.1 and Safari Technology Preview 41.
def get_permission(self, permission):
payload = self.execute("GET_PERMISSIONS")["value"]
permissions = payload["permissions"]
if not permissions:
return None
if permission not in permissions:
return None
value = permissions[permission]
if not isinstance(value, bool):
return None
return value
# First available in Safari 11.1 and Safari Technology Preview 42.
def debug(self):
self.execute("ATTACH_DEBUGGER")
self.execute_script("debugger;")