Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/source/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ The page attempt to keep a clear list of breaking/non-breaking changes and new f
:local:
:backlinks: none


v0.16.0
-----------
Bug Fixes
###########
* Fix Cloudflare 403 by updating curl_cffi
* Clear cookies on logout to avoid issues with re-login
* Use `Client.get_cookies` to retrieve cookies from the client session instead of `Client.cookies` which is now deprecated

v0.15.0
-----------
New Features
Expand Down
12 changes: 4 additions & 8 deletions moddb/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import requests
from curl_adapter import CurlCffiAdapter

from .base import (
front_page,
get_freeman_cookie,
Expand All @@ -15,13 +12,11 @@
from .client import Client, Thread, TwoFactorAuthClient
from .enums import *
from .pages import *
from .utils import BASE_URL, LOGGER, Object, get_page, request, soup
from .utils import BASE_URL, LOGGER, Object, create_session, get_page, request, set_ratelimits, soup

SESSION = requests.Session()
SESSION.mount("http://", CurlCffiAdapter())
SESSION.mount("https://", CurlCffiAdapter())
SESSION = create_session()

__version__ = "0.15.0"
__version__ = "0.16.0"

__all__ = [
"front_page",
Expand All @@ -41,5 +36,6 @@
"Object",
"get_page",
"request",
"set_ratelimits",
"soup",
]
4 changes: 2 additions & 2 deletions moddb/boxes.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def __init__(self, html: BeautifulSoup):
self.visits, self.today = get_views(visits)

rank = normalize(html.find("h5", string="Rank").parent.a.string).split("of")
self.rank = int(rank[0].replace(",", ""))
self.rank = int(rank[0].replace(",", "")) if rank[0].strip() != "-" else 0
self.total = int(rank[1].replace(",", ""))

try:
Expand Down Expand Up @@ -903,7 +903,7 @@ def get(parent):

try:
rank = normalize(html.find("h5", string="Rank").parent.span.string).split("of")
self.rank = int(rank[0].replace(",", ""))
self.rank = int(rank[0].replace(",", "")) if rank[0].strip() != "-" else 0
self.total = int(rank[1].replace(",", ""))
except AttributeError:
self.rank = 0
Expand Down
36 changes: 18 additions & 18 deletions moddb/client.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
from __future__ import annotations

import random
import re
import sys
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union

import requests
from bs4 import BeautifulSoup
from curl_adapter import CurlCffiAdapter
from requests import utils

from .base import parse_page
Expand All @@ -19,10 +17,11 @@
BASE_URL,
COMMENT_LIMITER,
GLOBAL_LIMITER,
GLOBAL_THROTLE,
GLOBAL_THROTTLE,
LOGGER,
concat_docs,
create_login_payload,
create_session,
generate_hash,
generate_login_cookies,
get,
Expand All @@ -37,7 +36,6 @@
raise_for_status,
ratelimit,
soup,
user_agent_list,
)

if TYPE_CHECKING:
Expand Down Expand Up @@ -304,9 +302,7 @@ class Client:
"""

def __init__(self, username: str = None, password: str = None, freeman_cookie: str = None):
session = requests.Session()
session.mount("http://", CurlCffiAdapter())
session.mount("https://", CurlCffiAdapter())
session = create_session()

if freeman_cookie:
username = login_with_freeman_cookie(freeman_cookie, session=session)
Expand Down Expand Up @@ -339,21 +335,27 @@ def get_freeman_cookie(self) -> Optional[str]:
"""Return the `freeman` cookie from this client's session, if available"""
return get_session_freeman_cookie(self._session)

@ratelimit(GLOBAL_THROTLE, GLOBAL_LIMITER)
@ratelimit(GLOBAL_THROTTLE, GLOBAL_LIMITER)
def _request(self, method, url, **kwargs):
"""Making sure we do our request with the cookies from this client rather than the cookies
of the library."""
cookies = utils.dict_from_cookiejar(self._session.cookies)
headers = {
**kwargs.pop("headers", {}),
"User-Agent": random.choice(user_agent_list),
}

req = requests.Request(method, url, headers=headers, cookies=cookies, data=kwargs.pop("data", {}))
req = requests.Request(
method,
url,
headers=kwargs.pop("headers", {}),
cookies=cookies,
data=kwargs.pop("data", {}),
params=kwargs.pop("params", None),
)
prepped = self._session.prepare_request(req)
LOGGER.info("Request: %s", prepped.url)

r = self._session.send(prepped, allow_redirects=kwargs.pop("allow_redirects", True))
allow_redirects = kwargs.pop("allow_redirects", True)
if kwargs:
raise TypeError(f"_request got unexpected arguments: {', '.join(kwargs)}")

r = self._session.send(prepped, allow_redirects=allow_redirects)
raise_for_status(r)

return r
Expand Down Expand Up @@ -1210,9 +1212,7 @@ def __init__(self, username: str = None, password: str = None, freeman_cookie: s
self.username = username
self.password = password

session = requests.Session()
session.mount("http://", CurlCffiAdapter())
session.mount("https://", CurlCffiAdapter())
session = create_session()
self._session = session
self.member: Member = None

Expand Down
77 changes: 59 additions & 18 deletions moddb/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import functools
import inspect
import logging
import random
import re
import ssl
import sys
Expand All @@ -14,6 +13,7 @@
import bs4
import requests
from bs4 import BeautifulSoup, Tag
from curl_adapter import CurlCffiAdapter
from requests import utils

from .enums import MediaCategory, ThumbnailType
Expand All @@ -33,15 +33,12 @@
"econd": 1,
}

user_agent_list = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.2792.65",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edge/44.18363.8131",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 OPR/114.0.0.0",
"Mozilla/5.0 (Windows NT 10.0; WOW64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 OPR/114.0.0.0",
]
# The User-Agent must match the impersonated browser, curl_adapter only impersonates the TLS
# fingerprint and leaves the headers to requests
BROWSER_TYPE = "chrome150"
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36"
)


def concat_docs(cls):
Expand Down Expand Up @@ -78,6 +75,16 @@ def get_docs(parent):
return cls


def create_session() -> requests.Session:
"""Create a session that impersonates a Chrome browser"""
session = requests.Session()
session.headers["User-Agent"] = USER_AGENT
session.mount("http://", CurlCffiAdapter(impersonate_browser_type=BROWSER_TYPE))
session.mount("https://", CurlCffiAdapter(impersonate_browser_type=BROWSER_TYPE))

return session


class SSLAdapter(requests.adapters.HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
ssl_context = ssl.create_default_context()
Expand All @@ -88,7 +95,7 @@ def init_poolmanager(self, *args, **kwargs):


class Ratelimit:
def __init__(self, rate: float, per: float, sleep: Optional[None] = None):
def __init__(self, rate: float, per: float, sleep: Optional[float] = None):
self.rate = rate
self.per = per
self.sleep = sleep
Expand All @@ -115,11 +122,11 @@ def call(self):
if self.call_count + 1 > self.rate:
remaining = (expiry - now).total_seconds()
if self.sleep is not None and remaining <= self.sleep:
LOGGER.info("Ratelimited! Sleeping for %s", remaining)
LOGGER.warning("Ratelimited! Sleeping for %.0f seconds", remaining)
time.sleep(remaining)
self.reset(now)
else:
raise Ratelimited(f"Ratelimited please try again in {remaining}", remaining)
raise Ratelimited(f"Ratelimited, please try again in {remaining:.0f} seconds", remaining)

self.call_count += 1

Expand All @@ -139,11 +146,47 @@ def wrapper(*args, **kwargs):


GLOBAL_LIMITER = Ratelimit(40, 300, sleep=300)
GLOBAL_THROTLE = Ratelimit(5, 1, sleep=1)
GLOBAL_THROTTLE = Ratelimit(5, 1, sleep=1)
COMMENT_LIMITER = Ratelimit(1, 60)
LOGIN_LIMITER = Ratelimit(1, 5)


def set_ratelimits(
*,
rate: Optional[float] = None,
per: Optional[float] = None,
throttle_rate: Optional[float] = None,
throttle_per: Optional[float] = None,
):
"""Adjust the library-wide ratelimits. Only the arguments passed are
changed. Lowering the defaults is a good idea for long-running batch
jobs to reduce the load on the website.

Parameters
-----------
rate : Optional[float]
Number of requests allowed by the global limiter per `per` seconds
(default 40)
per : Optional[float]
Length in seconds of the global limiter window (default 300)
throttle_rate : Optional[float]
Number of requests allowed by the burst throttle per `throttle_per`
seconds (default 5)
throttle_per : Optional[float]
Length in seconds of the burst throttle window (default 1)
"""
if rate is not None:
GLOBAL_LIMITER.rate = rate
if per is not None:
GLOBAL_LIMITER.per = per
GLOBAL_LIMITER.sleep = per
if throttle_rate is not None:
GLOBAL_THROTTLE.rate = throttle_rate
if throttle_per is not None:
GLOBAL_THROTTLE.per = throttle_per
GLOBAL_THROTTLE.sleep = throttle_per


def get_date(d: str) -> datetime.datetime:
"""A helper function that takes a ModDB string representation of time and returns an equivalent
datetime.datetime object. This can range from a datetime with the full year to
Expand Down Expand Up @@ -181,9 +224,6 @@ def prepare_request(req: requests.Request, session: requests.Session):
else:
req.cookies = cookies

if "User-Agent" not in req.headers:
req.headers["User-Agent"] = random.choice(user_agent_list)

return session.prepare_request(req)


Expand Down Expand Up @@ -266,6 +306,7 @@ def login_with_freeman_cookie(freeman_cookie: str, session: requests.Session = N
session.cookies.set("freeman", freeman_cookie, domain="www.moddb.com", path="/")
member_nameid = get_logged_in_member_nameid(session)
if member_nameid is None:
session.cookies.clear(domain="www.moddb.com", path="/", name="freeman")
raise ValueError("Invalid freeman cookie")

return member_nameid
Expand Down Expand Up @@ -302,7 +343,7 @@ def create_login_payload(username: str, password: str, session: requests.Session
return data, resp


@ratelimit(GLOBAL_THROTLE, GLOBAL_LIMITER)
@ratelimit(GLOBAL_THROTTLE, GLOBAL_LIMITER)
def request(req: requests.Request):
"""Helper function to make get/post requests with the current SESSION object.

Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
beautifulsoup4 == 4.*
requests == 2.*
curl_adapter == 1.*
curl_adapter >= 1.2.3, < 2
curl_cffi >= 0.16
packaging == 26.*
Loading
Loading