Kapitan 9361bc0363
All checks were successful
Gitea/kapitanbooru-uploader/pipeline/head This commit looks good
Translations, suggestion box, UX
2025-03-03 00:47:38 +01:00

128 lines
4.1 KiB
Python

import subprocess
from bs4 import BeautifulSoup
import requests
from .I18N import _
from .settings import Settings
def open_tag_wiki_url(tag: str, settings: Settings):
"""Otwiera w przeglądarce URL strony wiki dla podanego tagu."""
# Usuń prefiksy
for prefix in [
"character:",
"artist:",
"meta:",
"copyright:",
"general:",
]:
if tag.startswith(prefix):
tag = tag[len(prefix) :]
break
url = "https://danbooru.donmai.us/wiki_pages/" + tag
open_webbrowser(url, settings)
def open_webbrowser(url, settings: Settings):
"""Otwiera URL w wybranej przeglądarce (lub domyślnej)."""
if settings.browser:
try:
subprocess.run([settings.browser, url], check=True)
return
except Exception as e:
print(_("Błąd przy otwieraniu przeglądarki:"), e)
import webbrowser
webbrowser.open(url)
def login(settings: Settings):
"""
Log in to the server using settings and return a session with cookies.
settings should have:
- base_url (e.g., "https://example.com")
- username
- password
"""
# Construct the full URL for login
url = settings.base_url.rstrip("/") + "/user_admin/login"
# Prepare the payload for URL-encoded form data
payload = {"user": settings.username, "pass": settings.password}
# Set the proper header
headers = {"Content-Type": "application/x-www-form-urlencoded"}
# Use a session so that cookies are automatically stored for future requests.
session = requests.Session()
# Send the POST request and prevent automatic redirects,
# so we can capture the 302 response with Set-Cookie headers.
response = session.post(url, data=payload, headers=headers, allow_redirects=False)
if response.status_code == 302:
# The session's cookie jar should now contain the cookies set by the server.
shm_user = session.cookies.get("shm_user")
shm_session = session.cookies.get("shm_session")
if not (shm_user and shm_session):
raise Exception(_("Login succeeded, but expected cookies were not set."))
print(_("Login successful. Cookies stored in session."))
return session
else:
raise Exception(
f"{_('Login failed:')} {response.status_code} - {response.text}"
)
def get_auth_token(session: requests.Session, settings: Settings) -> str:
"""
Given a logged-in session and settings, fetch the user page
and extract the auth_token from the hidden input field.
settings should have:
- base_url (e.g., "https://example.com")
The session should contain the 'shm_user' cookie.
"""
# Retrieve the user identifier from cookies
shm_user = session.cookies.get("shm_user")
if not shm_user:
raise Exception(_("shm_user cookie not found; login might have failed."))
# Build the URL to fetch, e.g., /user/<shm_user>
user_url = f"{settings.base_url.rstrip('/')}/user/{shm_user}"
# Option 1: Simply allow redirects (if your server sends 302 and eventually a 200)
# response = session.get(user_url) # redirects allowed by default
# Option 2: If you want to control redirection manually, disable them:
# response = session.get(user_url, allow_redirects=False)
# Then you might have to follow the redirects manually.
# For simplicity, we'll allow redirects:
response = session.get(user_url)
if response.status_code != 200:
raise Exception(
_("Failed to load {user_url}, status code: {code}").format(
user_url=user_url, code=response.status_code
)
)
# Parse the returned HTML with BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
# Look for the hidden input with name "auth_token"
auth_input = soup.find("input", {"name": "auth_token"})
if auth_input and auth_input.has_attr("value"):
auth_token = auth_input["value"]
print(_("Found auth_token:"), auth_token)
return auth_token
else:
raise Exception(_("auth_token not found in the HTML page."))