Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Partial Downloads #6

Merged
merged 7 commits into from
May 16, 2023
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -166,5 +166,7 @@ poetry.toml
# ruff
.ruff_cache/

# Script Created Files
src/urls.txt
captcha.png
session
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ With this tool you can download multiple items at once, to download items copy t
| - | - | - |
| downloadDirectory | Path to a directory where the files will be downloaded to. | string |
| maxActiveDownloads | Limits the max amount of active downloads to the value set. | integer |
| saveDownloadQueue | Toggles saving & loading of active downloads & queued downloads. | boolean |
| debug | Toggles debug messages from the logger. | boolean |

## Installing Requirements
Expand Down
33 changes: 26 additions & 7 deletions src/TSRDownload.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import requests, time
import requests, time, os, re
from TSRUrl import TSRUrl
from logger import logger
from exceptions import *
Expand All @@ -22,17 +22,36 @@ def download(self, downloadPath: str) -> str:
time.sleep(timeToSleep / 1000)

downloadUrl = self.__getDownloadUrl()
request = self.session.get(downloadUrl, stream=True)
fileName = request.headers["Content-Disposition"][
22:-1
] # Remove 'attachment; filename="' from header
file = open(f"{downloadPath}/{fileName}", "wb")
fileName = self.__getFileName(downloadUrl)

for chunk in request.iter_content(1024 * 1024):
startingBytes = (
os.path.getsize(f"{downloadPath}/{fileName}.part")
if os.path.exists(f"{downloadPath}/{fileName}.part")
else 0
)
request = self.session.get(
downloadUrl,
stream=True,
headers={"Range": f"bytes={startingBytes}-"},
)
file = open(f"{downloadPath}/{fileName}.part", "wb")

for chunk in request.iter_content(1024 * 128):
file.write(chunk)
file.close()
os.rename(
f"{downloadPath}/{fileName}.part",
f"{downloadPath}/{fileName}",
)
return fileName

@classmethod
def __getFileName(self, downloadUrl: str) -> str:
return re.search(
'(?<=filename=").+(?=")',
requests.get(downloadUrl, stream=True).headers["Content-Disposition"],
)[0]

@classmethod
def __getDownloadUrl(self) -> str:
response = self.session.get(
Expand Down
1 change: 1 addition & 0 deletions src/config.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"downloadDirectory": "./",
"maxActiveDownloads": 4,
"saveDownloadQueue": true,
"debug": false
}
8 changes: 7 additions & 1 deletion src/config.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import json, os, typing

CONFIG_DICT = typing.TypedDict(
"Config Dict", {"downloadDirectory": str, "maxActiveDownloads": int, "debug": bool}
"Config Dict",
{
"downloadDirectory": str,
"maxActiveDownloads": int,
"saveDownloadQueue": bool,
"debug": bool,
},
)
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG: CONFIG_DICT = json.load(open(CURRENT_DIR + "/config.json", "r"))
24 changes: 24 additions & 0 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,18 @@ def processTarget(url: TSRUrl, tsrdlsession: str, downloadPath: str):

def callback(url: TSRUrl):
runningDownloads.remove(url.url)
updateUrlFile()
if len(runningDownloads) == 0:
logger.info("All downloads have been completed")


def updateUrlFile():
if CONFIG["saveDownloadQueue"]:
open(CURRENT_DIR + "/urls.txt", "w").write(
"\n".join([*runningDownloads, *downloadQueue])
)


if __name__ == "__main__":
lastPastedText = ""
runningDownloads: list[str] = []
Expand Down Expand Up @@ -49,6 +57,12 @@ def callback(url: TSRUrl):
)
sessionId = None

if os.path.exists(CURRENT_DIR + "/urls.txt") and CONFIG["saveDownloadQueue"]:
for url in open(CURRENT_DIR + "/urls.txt", "r").read().split("\n"):
if url.strip() == "" or url in downloadQueue:
continue
downloadQueue.append(url.strip())

while True:
pastedText = clipboard.paste()
if lastPastedText == pastedText:
Expand Down Expand Up @@ -91,6 +105,15 @@ def callback(url: TSRUrl):
logger.info(f"{url.url} has {len(requirements)} requirements")

for url in [url, *requirements]:
if url.url in runningDownloads:
logger.info(f"Url is already being downloaded: {url.url}")
continue
if url.url in downloadQueue:
logger.info(
f"Url is already in queue (#{downloadQueue.index(url.url)}): {url.url}"
)
continue

if len(runningDownloads) == CONFIG["maxActiveDownloads"]:
logger.info(
f"Added url to queue (#{len(downloadQueue)}): {url.url}"
Expand All @@ -108,6 +131,7 @@ def callback(url: TSRUrl):
],
callback=callback,
)
updateUrlFile()
except InvalidURL:
pass

Expand Down