Skip to content

Commit

Permalink
Moving browser util back to correct place
Browse files Browse the repository at this point in the history
  • Loading branch information
Yomguithereal committed Oct 27, 2023
1 parent 912fc2e commit 0f5d40b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 43 deletions.
43 changes: 42 additions & 1 deletion minet/browser/utils.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from typing import Union
from typing import Union, Callable, Awaitable

import asyncio
from tempfile import gettempdir
from os.path import expanduser, join
from playwright.async_api import (
Error as PlaywrightError,
TimeoutError as PlaywrightTimeoutError,
Page,
Response,
)

from minet.exceptions import (
Expand Down Expand Up @@ -75,3 +78,41 @@ def get_browsers_path() -> str:

def get_temp_persistent_context_path() -> str:
return join(gettempdir(), "minet-browser-temporary-persistent-context")


async def try_expect_response(
page: Page,
action: Callable[[Page], Awaitable[None]],
response_predicate: Callable[[Response], bool],
) -> Response:
selected_response = None
event = asyncio.Event()

def release() -> None:
page.remove_listener("response", listener)
event.set()

def listener(response: Response) -> None:
nonlocal selected_response

if not response_predicate(response):
return

selected_response = response

release()

async def guarded_action() -> None:
try:
await action(page)
except Exception:
release()
raise

page.on("response", listener)

await asyncio.gather(guarded_action(), event.wait())

assert selected_response is not None

return selected_response
42 changes: 0 additions & 42 deletions minet/facebook/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,7 @@
#
# Miscellaneous helpers used by the minet.facebook namespace.
#
from typing import Callable, Awaitable

import asyncio
from http.cookies import SimpleCookie
from playwright.async_api import Page, Response

from minet.cookies import coerce_cookie_for_url_from_browser
from minet.facebook.constants import FACEBOOK_URL
Expand Down Expand Up @@ -36,41 +32,3 @@ def grab_facebook_cookie(source):
return None

return fix_cookie(cookie)


async def try_expect_response(
page: Page,
action: Callable[[Page], Awaitable[None]],
response_predicate: Callable[[Response], bool],
) -> Response:
selected_response = None
event = asyncio.Event()

def release() -> None:
page.remove_listener("response", listener)
event.set()

def listener(response: Response) -> None:
nonlocal selected_response

if not response_predicate(response):
return

selected_response = response

release()

async def guarded_action() -> None:
try:
await action(page)
except Exception:
release()
raise

page.on("response", listener)

await asyncio.gather(guarded_action(), event.wait())

assert selected_response is not None

return selected_response

0 comments on commit 0f5d40b

Please sign in to comment.