forked from ltsdw/gofile-downloader
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gofile-downloader.py
executable file
·290 lines (197 loc) · 8.06 KB
/
gofile-downloader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
#! /usr/bin/env python3
from os import path, mkdir, getcwd, chdir, getenv
from sys import exit, stdout, stderr
from typing import Dict, List
from requests import get
from concurrent.futures import ThreadPoolExecutor
from platform import system
from hashlib import sha256
from uuid import uuid4
from shutil import move, rmtree
NEW_LINE: str = "\n" if system() != "Windows" else "\r\n"
def die(_str: str) -> None:
"""
Display a message of error and exit.
:param _str: a string to be printed.
:return:
"""
stderr.write(_str + NEW_LINE)
stderr.flush()
exit(-1)
def _print(_str: str) -> None:
"""
Print a message.
:param _str: a string to be printed.
:return:
"""
stdout.write(_str)
stdout.flush()
# increase max_workers for parallel downloads
# defaults to 5 download at time
class Main:
def __init__(self, url: str, password: str | None = None, max_workers: int = 5) -> None:
try:
if not url.split("/")[-2] == "d":
die(f"The url probably doesn't have an id in it: {url}")
self._id: str = url.split("/")[-1]
except IndexError:
die(f"Something is wrong with the url: {url}.")
self._downloaddir: str | None = getenv("GF_DOWNLOADDIR")
if self._downloaddir and path.exists(self._downloaddir):
chdir(self._downloaddir)
self._root_dir: str = path.join(getcwd(), self._id)
self._token: str = self._getToken()
self._url: str = f"https://api.gofile.io/getContent?contentId={self._id}&token={self._token}&websiteToken=12345&cache=true"
self._password: str | None = sha256(password.encode()).hexdigest() if password else None
self._max_workers: int = max_workers
# list of files and its respective path, uuid, filename and link
self._files_link_list: List[Dict] = []
self._createDir(self._id)
self._parseLinks(self._id, self._token, self._password)
self._threadedDownloads()
def _threadedDownloads(self) -> None:
"""
Parallelize the downloads.
:return:
"""
chdir(self._root_dir)
self._createDir("tmp-dir")
with ThreadPoolExecutor(max_workers=self._max_workers) as executor:
for item in self._files_link_list:
executor.submit(self._downloadContent, item, self._token)
with ThreadPoolExecutor(max_workers=self._max_workers) as executor:
for item in self._files_link_list:
if path.exists(item["uuid"]):
move(item["uuid"], item["path"])
chdir(self._root_dir)
rmtree("tmp-dir")
def _createDir(self, dirname: str) -> None:
"""
creates a directory where the files will be saved if doesn't exist and change to it.
:param dirname: name of the directory to be created.
:return:
"""
current_dir: str = getcwd()
filepath: str = path.join(current_dir, dirname)
try:
mkdir(path.join(filepath))
# if the directory already exist is safe to do nothing
except FileExistsError:
pass
chdir(filepath)
@staticmethod
def _getToken() -> str:
"""
Gets the access token of account created.
:return: The access token of an account. Or exit if account creation fail.
"""
create_account_response: Dict = get("https://api.gofile.io/createAccount").json()
api_token = create_account_response["data"]["token"]
account_response: Dict = get("https://api.gofile.io/getAccountDetails?token=" + api_token).json()
if account_response["status"] != 'ok':
die("Account creation failed!")
return api_token
@staticmethod
def _downloadContent(file_info: Dict, token: str, chunk_size: int = 4096) -> None:
"""
Download a file.
:param file_info: a dictionary with information about a file to be downloaded.
:param token: the access token of the account.
:param chunk_size: the number of bytes it should read into memory.
:return:
"""
uuid: str = file_info["uuid"]
filename: str = file_info["filename"]
url: str = file_info["link"]
if path.exists(file_info["path"]):
if path.getsize(file_info["path"]) > 0:
_print(f"{filename} already exist, skipping." + NEW_LINE)
return
headers: Dict = {
"Cookie": "accountToken=" + token,
"Accept-Encoding": "gzip, deflate, br",
"User-Agent": "Mozilla/5.0",
"Accept": "*/*",
"Referer": url + ("/" if not url.endswith("/") else ""),
"Origin": url,
"Connection": "keep-alive",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-site",
"Pragma": "no-cache",
"Cache-Control": "no-cache"
}
with get(url, headers=headers, stream=True) as response_handler:
if response_handler.status_code in (403, 404, 405, 500):
_print(
f"Couldn't download the file from {url}."
+ NEW_LINE
+ "Status code: {response_handler.status_code}"
+ NEW_LINE
)
return
with open(uuid, 'wb+') as handler:
has_size: str | None = response_handler.headers.get('Content-Length')
total_size: float
if has_size:
total_size = float(has_size)
else:
return
for i, chunk in enumerate(response_handler.iter_content(chunk_size=chunk_size)):
progress: float = i * chunk_size / total_size * 100
handler.write(chunk)
_print(f"\rDownloading {filename}: {round(progress, 1)}%")
_print(f"\rDownloaded {filename}: 100.0%!" + NEW_LINE)
def _parseLinks(self, _id: str, token: str, password: str | None = None) -> None:
"""
Parses for possible links recursively and populate a list with file's info.
:param _id: url to the content.
:param token: access token.
:param password: content's password.
:return:
"""
url: str = f"https://api.gofile.io/getContent?contentId={_id}&token={token}&websiteToken=12345&cache=true"
if password:
url = url + f"&password={password}"
response: Dict = get(url).json()
data: Dict = response["data"]
if "contents" in data.keys():
contents: Dict = data["contents"]
for content in contents.values():
if content["type"] == "folder":
self._createDir(content["name"])
self._parseLinks(content["id"], token, password)
chdir(path.pardir)
else:
self._files_link_list.append(
{
"path": path.join(getcwd(), content["name"]),
"uuid": str(uuid4()),
"filename": content["name"],
"link": content["link"]
}
)
else:
die(f"Failed to get a link as response from the {url}")
if __name__ == '__main__':
try:
from sys import argv
url: str | None = None
password: str | None = None
argc: int = len(argv)
if argc > 1:
url = argv[1]
if argc > 2:
password = argv[2]
# Run
_print('Starting, please wait...' + NEW_LINE)
Main(url=url, password=password)
else:
die("Usage:"
+ NEW_LINE
+ "python gofile-downloader.py https://gofile.io/d/contentid"
+ NEW_LINE
+ "python gofile-downloader.py https://gofile.io/d/contentid password"
)
except KeyboardInterrupt:
exit(1)