import re from liveview import liveview_handler, send from django.test import Client from app.public.liveview_handlers.modal import _inject_liveview_submit_page @liveview_handler("navigate") def navigate(consumer, content): url = content.get("data", {}).get("data_url", "/") client = Client() if hasattr(consumer, "scope") and "user" in consumer.scope: user = consumer.scope["user"] if user and user.is_authenticated: client.force_login(user) ws_session = consumer.scope.get("session") if ws_session: session = client.session for key, value in ws_session.items(): if not key.startswith("_auth_user"): session[key] = value session.save() try: response = client.get( url, follow=True, HTTP_X_REQUESTED_WITH="XMLHttpRequest", SERVER_NAME="localhost", ) if response.status_code == 200: html_content = response.content.decode("utf-8") main_match = re.search(r"]*>(.*?)", html_content, re.DOTALL) if main_match: main_content = _inject_liveview_submit_page(main_match.group(1), url) title_match = re.search(r"(.*?)", html_content) page_title = title_match.group(1) if title_match else "Kakebo" script_matches = re.findall( r"]*>(.*?)", html_content, re.DOTALL ) inline_scripts = [] for match in script_matches: script_content = match.strip() if script_content and not script_content.startswith("http"): inline_scripts.append(f"") main_content_with_scripts = main_content if inline_scripts: main_content_with_scripts = ( main_content + "\n" + "\n".join(inline_scripts) ) send( consumer, { "target": "#main-content", "html": main_content_with_scripts, "url": url, "title": page_title, }, ) else: send( consumer, { "target": "#main-content", "html": '
Could not load page content
', }, ) else: send( consumer, { "target": "#main-content", "html": f'
Error {response.status_code}
', }, ) except Exception as e: send( consumer, { "target": "#main-content", "html": f'
{e}
', }, )