Skip to content

Commit

Permalink
fix(captcha): add captcha support
Browse files Browse the repository at this point in the history
  • Loading branch information
Xientraa authored Mar 27, 2023
1 parent a8bb2d1 commit c5a8ff9
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 5 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -165,3 +165,6 @@ poetry.toml

# ruff
.ruff_cache/

captcha.png
session
5 changes: 4 additions & 1 deletion src/TSRDownload.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import requests, time, json, os
from TSRSession import TSRSession
from TSRUrl import TSRUrl
from logger import Logger
from exceptions import *
Expand All @@ -11,8 +12,10 @@

class TSRDownload:
@classmethod
def __init__(self, url: TSRUrl):
def __init__(self, url: TSRUrl, session: TSRSession):
self.session: requests.Session = requests.Session()
self.session.cookies.set("tsrdlsession", session.tsrdlsession)

self.url: TSRUrl = url
self.ticketInitializedTime: float = -1.0
self.__getTSRDLTicketCookie()
Expand Down
79 changes: 79 additions & 0 deletions src/TSRSession.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import requests, webbrowser, os
from exceptions import InvalidCaptchaCode
from typing import Optional

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))


class TSRSession:
@classmethod
def __init__(self, sessionId: Optional[str] = None) -> None:
self.session = requests.Session()
if sessionId is not None:
if self.__isValidSessionId(sessionId):
self.tsrdlsession = sessionId
return

self.__getTSRDLTicketCookie()
self.__saveCaptchaImage()
self.__openImageInBrowser()
self.tsrdlsession = None

print("Please enter captcha code:")
captchaInput = input(">> ")
if self.__tryCaptchaCode(captchaInput):
self.tsrdlsession = self.session.cookies.get_dict().get("tsrdlsession")
else:
raise InvalidCaptchaCode

@classmethod
def __tryCaptchaCode(self, code: str) -> bool:
r = self.session.post(
"https://www.thesimsresource.com/downloads/session/itemId/1646133",
data={"captchavalue": code},
headers={
"Content-Type": "application/x-www-form-urlencoded",
"Origin": "https://www.thesimsresource.com",
},
allow_redirects=True,
)
return (
r.url == "https://www.thesimsresource.com/downloads/download/itemId/1646133"
)

@classmethod
def __isValidSessionId(self, sessionId: str) -> bool:
self.__getTSRDLTicketCookie()
r = self.session.get(
"https://www.thesimsresource.com/downloads/download/itemId/1646133",
cookies={"tsrdlsession": sessionId},
)
return (
r.url == "https://www.thesimsresource.com/downloads/download/itemId/1646133"
)

@classmethod
def __getCaptchaImage(self) -> requests.Request:
self.session.get(
"https://www.thesimsresource.com/downloads/session/itemId/1646133"
)
return self.session.get(
"https://www.thesimsresource.com/downloads/captcha-image"
)

@classmethod
def __saveCaptchaImage(self):
with open(f"{CURRENT_DIR}/captcha.png", "wb") as f:
for chunk in self.__getCaptchaImage().iter_content(1024 * 1024):
f.write(chunk)

@classmethod
def __openImageInBrowser(self) -> None:
webbrowser.open_new_tab(f"{CURRENT_DIR}/captcha.png")

@classmethod
def __getTSRDLTicketCookie(self) -> str:
response = self.session.get(
f"https://www.thesimsresource.com/ajax.php?c=downloads&a=initDownload&itemid=1646133&format=zip"
)
return response.cookies.get("tsrdlticket")
4 changes: 4 additions & 0 deletions src/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,7 @@ class InvalidDownloadTicket(Exception):
def __init__(self, url: str, cookies: RequestsCookieJar):
self.url = url
self.cookies = cookies


class InvalidCaptchaCode(Exception):
pass
21 changes: 17 additions & 4 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
from exceptions import *
from typings import *
from multiprocessing import Pool
from TSRSession import TSRSession
import clipboard, time, json, os


def processTarget(url: TSRUrl):
downloader = TSRDownload(url)
downloader = TSRDownload(url, session)
if downloader.download():
Logger.info(f"Completed download for: {url.url}")

Expand All @@ -22,13 +23,25 @@ def callback(url: TSRUrl):


if __name__ == "__main__":
CONFIG: CONFIG_DICT = json.load(
open(os.path.dirname(os.path.abspath(__file__)) + "/config.json", "r")
)
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG: CONFIG_DICT = json.load(open(CURRENT_DIR + "/config.json", "r"))
lastPastedText = ""
runningDownloads: list[str] = []
downloadQueue: list[str] = []

session = None
sessionId = None
if os.path.exists(CURRENT_DIR + "/session"):
sessionId = open(CURRENT_DIR + "/session", "r").read()

while session is None:
try:
session = TSRSession(sessionId)
if hasattr(session, "tsrdlsession"):
open(CURRENT_DIR + "/session", "w").write(session.tsrdlsession)
except InvalidCaptchaCode:
sessionId = None

while True:
pastedText = clipboard.paste()
if lastPastedText == pastedText:
Expand Down

0 comments on commit c5a8ff9

Please sign in to comment.