diff --git a/src/letscode/leetcode.py b/src/letscode/leetcode.py index 5a3f8dd..c2cd20d 100644 --- a/src/letscode/leetcode.py +++ b/src/letscode/leetcode.py @@ -4,6 +4,7 @@ import logging from typing import Any import httpx +from pydantic import ValidationError from .constants import USER_AGENT from .model.leetcode import LeetCodeQuestion, LeetCodeQuestionList @@ -13,30 +14,206 @@ logger = logging.getLogger(__name__) class LeetCodeFetcher: - BASE_URL = "https://leetcode-api-pied.vercel.app" + BASE_URL = "https://leetcode.com" + GRAPHQL_PATH = "/graphql" REQUEST_TIMEOUT = 15.0 + QUESTION_DATA_QUERY = """\ +query questionData($titleSlug: String!) { + question(titleSlug: $titleSlug) { + questionId + questionFrontendId + title + titleSlug + content + difficulty + hints + isPaidOnly + } +} +""" + QUESTION_LIST_QUERY = """\ +query problemsetQuestionList( + $categorySlug: String + $limit: Int + $skip: Int + $filters: QuestionListFilterInput +) { + problemsetQuestionList: questionList( + categorySlug: $categorySlug + limit: $limit + skip: $skip + filters: $filters + ) { + total: totalNum + questions: data { + frontendQuestionId: questionFrontendId + title + titleSlug + difficulty + paidOnly: isPaidOnly + hasSolution + } + } +} +""" + LEGACY_QUESTION_LIST_QUERY = """\ +query problemsetQuestionList( + $categorySlug: String + $limit: Int + $skip: Int + $filters: QuestionListFilterInput +) { + problemsetQuestionList( + categorySlug: $categorySlug + limit: $limit + skip: $skip + filters: $filters + ) { + total + questions { + frontendQuestionId + title + titleSlug + difficulty + paidOnly + hasSolution + } + } +} +""" - def __init__(self, base_url: str = BASE_URL) -> None: + def __init__( + self, + base_url: str = BASE_URL, + *, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: self.base_url = base_url + self.transport = transport async def get_all_problems( self, limit: int = 20, skip: int = 0 ) -> LeetCodeQuestionList | None: - response = await self._request("GET", "/problems") - - if response is None: + questions = await self._get_problemset_questions(limit=limit, skip=skip) + if questions is None: return None - problems = LeetCodeQuestionList.model_validate_json(response.text).root - return LeetCodeQuestionList(problems[skip : skip + limit]) + return LeetCodeQuestionList( + [self._normalize_question_list_item(question) for question in questions] + ) async def get_problem(self, question_slug: int | str) -> LeetCodeQuestion | None: - response = await self._request("GET", f"/problem/{question_slug}") + title_slug = await self._resolve_title_slug(question_slug) + if title_slug is None: + return None + + data = await self._graphql( + query=self.QUESTION_DATA_QUERY, + variables={"titleSlug": title_slug}, + operation_name="questionData", + ) + question = data.get("question") if data is not None else None + if not isinstance(question, dict): + return None + + try: + return LeetCodeQuestion.model_validate(self._normalize_question(question)) + except ValidationError as error: + logger.warning("LeetCode GraphQL question payload is invalid: %s", error) + return None + + async def _resolve_title_slug(self, question_slug: int | str) -> str | None: + if isinstance(question_slug, str) and not question_slug.isdecimal(): + return question_slug + + question_id = int(question_slug) + questions = await self._get_problemset_questions( + limit=50, + skip=0, + filters={"searchKeywords": str(question_id)}, + ) + if questions is None: + return None + + for question in questions: + if ( + self._normalize_question_id(question.get("frontendQuestionId")) + == question_id + ): + title_slug = question.get("titleSlug") + if isinstance(title_slug, str) and title_slug: + return title_slug + + return None + + async def _get_problemset_questions( + self, + *, + limit: int, + skip: int, + filters: dict[str, Any] | None = None, + ) -> list[dict[str, Any]] | None: + variables = { + "categorySlug": "", + "limit": limit, + "skip": skip, + "filters": filters or {}, + } + data = await self._graphql( + query=self.QUESTION_LIST_QUERY, + variables=variables, + operation_name="problemsetQuestionList", + ) + if data is None: + data = await self._graphql( + query=self.LEGACY_QUESTION_LIST_QUERY, + variables=variables, + operation_name="problemsetQuestionList", + ) + problemset = data.get("problemsetQuestionList") if data is not None else None + questions = ( + problemset.get("questions") if isinstance(problemset, dict) else None + ) + if not isinstance(questions, list): + return None + + return [question for question in questions if isinstance(question, dict)] + + async def _graphql( + self, + *, + query: str, + variables: dict[str, Any], + operation_name: str, + ) -> dict[str, Any] | None: + response = await self._request( + "POST", + self.GRAPHQL_PATH, + json={ + "query": query, + "variables": variables, + "operationName": operation_name, + }, + ) if response is None: return None - return LeetCodeQuestion.model_validate_json(response.text) + try: + payload = response.json() + except ValueError: + logger.warning("LeetCode GraphQL returned invalid JSON") + return None + + if "errors" in payload: + logger.warning("LeetCode GraphQL returned errors: %s", payload["errors"]) + return None + + data = payload.get("data") + if not isinstance(data, dict): + return None + + return data async def _request( self, @@ -44,13 +221,19 @@ class LeetCodeFetcher: path: str, **kwargs: Any, ) -> httpx.Response | None: - headers = {"User-Agent": USER_AGENT, "Content-Type": "application/json"} + headers = { + "User-Agent": USER_AGENT, + "Content-Type": "application/json", + "Origin": self.BASE_URL, + "Referer": f"{self.BASE_URL}/problemset/", + } try: async with httpx.AsyncClient( base_url=self.base_url, headers=headers, timeout=self.REQUEST_TIMEOUT, + transport=self.transport, ) as client: response = await client.request(method, path, **kwargs) except httpx.HTTPError as error: @@ -67,3 +250,36 @@ class LeetCodeFetcher: return None return response + + def _normalize_question(self, question: dict[str, Any]) -> dict[str, Any]: + normalized = dict(question) + question_id = self._normalize_question_id(question.get("questionFrontendId")) + if question_id == 0: + question_id = self._normalize_question_id(question.get("questionId")) + + normalized["questionId"] = question_id + normalized["hints"] = question.get("hints") or [] + return normalized + + def _normalize_question_list_item( + self, + question: dict[str, Any], + ) -> dict[str, Any]: + title_slug = str(question.get("titleSlug", "")) + return { + "frontend_id": self._normalize_question_id( + question.get("frontendQuestionId") + ), + "title": str(question.get("title", "")), + "title_slug": title_slug, + "difficulty": str(question.get("difficulty", "")), + "url": f"https://leetcode.com/problems/{title_slug}/", + "paid_only": bool(question.get("paidOnly")), + "has_solution": bool(question.get("hasSolution")), + } + + def _normalize_question_id(self, value: Any) -> int: + try: + return int(str(value)) + except (TypeError, ValueError): + return 0 diff --git a/tests/test_leetcode.py b/tests/test_leetcode.py new file mode 100644 index 0000000..1f6bab5 --- /dev/null +++ b/tests/test_leetcode.py @@ -0,0 +1,151 @@ +import asyncio +import json +import unittest + +import httpx + +from letscode.leetcode import LeetCodeFetcher + + +class LeetCodeFetcherTest(unittest.TestCase): + def test_get_problem_resolves_numeric_id_through_graphql(self) -> None: + requests: list[dict[str, object]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + self.assertEqual(request.method, "POST") + self.assertEqual(request.url.path, "/graphql") + payload = json.loads(request.content) + requests.append(payload) + + if payload["operationName"] == "problemsetQuestionList": + self.assertEqual( + payload["variables"]["filters"], + {"searchKeywords": "1"}, + ) + return httpx.Response( + 200, + json={ + "data": { + "problemsetQuestionList": { + "questions": [ + { + "frontendQuestionId": "1", + "title": "Two Sum", + "titleSlug": "two-sum", + "difficulty": "Easy", + "paidOnly": False, + "hasSolution": True, + } + ] + } + } + }, + ) + + return httpx.Response( + 200, + json={ + "data": { + "question": { + "questionId": "1", + "questionFrontendId": "1", + "title": "Two Sum", + "titleSlug": "two-sum", + "content": "
Return indices.
", + "difficulty": "Easy", + "hints": ["Use a map.
"], + "isPaidOnly": False, + } + } + }, + ) + + fetcher = LeetCodeFetcher(transport=httpx.MockTransport(handler)) + + question = asyncio.run(fetcher.get_problem(1)) + + self.assertIsNotNone(question) + self.assertEqual(question.questionId, 1) + self.assertEqual(question.title, "Two Sum") + self.assertEqual(question.hints, ["Use a map.
"]) + self.assertEqual( + [request["operationName"] for request in requests], + ["problemsetQuestionList", "questionData"], + ) + + def test_get_problem_uses_slug_directly(self) -> None: + requests: list[dict[str, object]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + payload = json.loads(request.content) + requests.append(payload) + self.assertEqual(payload["operationName"], "questionData") + self.assertEqual(payload["variables"]["titleSlug"], "two-sum") + return httpx.Response( + 200, + json={ + "data": { + "question": { + "questionId": "1", + "questionFrontendId": "1", + "title": "Two Sum", + "titleSlug": "two-sum", + "content": "Return indices.
", + "difficulty": "Easy", + "hints": [], + "isPaidOnly": False, + } + } + }, + ) + + fetcher = LeetCodeFetcher(transport=httpx.MockTransport(handler)) + + question = asyncio.run(fetcher.get_problem("two-sum")) + + self.assertIsNotNone(question) + self.assertEqual(question.questionId, 1) + self.assertEqual(len(requests), 1) + + def test_get_all_problems_maps_graphql_list_items(self) -> None: + def handler(request: httpx.Request) -> httpx.Response: + payload = json.loads(request.content) + self.assertEqual(payload["operationName"], "problemsetQuestionList") + self.assertEqual(payload["variables"]["limit"], 1) + self.assertEqual(payload["variables"]["skip"], 5) + return httpx.Response( + 200, + json={ + "data": { + "problemsetQuestionList": { + "questions": [ + { + "frontendQuestionId": "2", + "title": "Add Two Numbers", + "titleSlug": "add-two-numbers", + "difficulty": "Medium", + "paidOnly": False, + "hasSolution": True, + } + ] + } + } + }, + ) + + fetcher = LeetCodeFetcher(transport=httpx.MockTransport(handler)) + + problems = asyncio.run(fetcher.get_all_problems(limit=1, skip=5)) + + self.assertIsNotNone(problems) + problem = problems.root[0] + self.assertEqual(problem.questionId, 2) + self.assertEqual(problem.title_slug, "add-two-numbers") + self.assertEqual( + problem.url, + "https://leetcode.com/problems/add-two-numbers/", + ) + + +if __name__ == "__main__": + unittest.main()