-
Notifications
You must be signed in to change notification settings - Fork 18
/
tools.py
238 lines (191 loc) · 6.21 KB
/
tools.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
import re
from io import BytesIO
from urllib.parse import parse_qs, urlparse
import requests
from telethon import TelegramClient
def check_url_patterns(url: str) -> bool:
"""
Check if the given URL matches any of the known URL patterns for code hosting services.
Parameters:
url (str): The URL to be checked.
Returns:
bool: True if the URL matches a known pattern, False otherwise.
"""
patterns = [
r"ww\.mirrobox\.com",
r"www\.nephobox\.com",
r"freeterabox\.com",
r"www\.freeterabox\.com",
r"1024tera\.com",
r"4funbox\.co",
r"www\.4funbox\.com",
r"mirrobox\.com",
r"nephobox\.com",
r"terabox\.app",
r"terabox\.com",
r"www\.terabox\.ap",
r"www\.terabox\.com",
r"www\.1024tera\.co",
r"www\.momerybox\.com",
r"teraboxapp\.com",
r"momerybox\.com",
r"tibibox\.com",
r"www\.tibibox\.com",
r"www\.teraboxapp\.com",
]
for pattern in patterns:
if re.search(pattern, url):
return True
return False
def extract_code_from_url(url: str) -> str | None:
"""
Extracts the code from a URL.
Parameters:
url (str): The URL to extract the code from.
Returns:
str: The extracted code, or None if the URL does not contain a code.
"""
pattern1 = r"/s/(\w+)"
pattern2 = r"surl=(\w+)"
match = re.search(pattern1, url)
if match:
return match.group(1)
match = re.search(pattern2, url)
if match:
return match.group(1)
return None
def get_urls_from_string(string: str) -> str | None:
"""
Extracts all URLs from a given string.
Parameters:
string (str): The input string.
Returns:
str: The first URL found in the input string, or None if no URLs were found.
"""
pattern = r"(https?://\S+)"
urls = re.findall(pattern, string)
urls = [url for url in urls if check_url_patterns(url)]
if not urls:
return
return urls[0]
def extract_surl_from_url(url: str) -> str:
"""
Extracts the surl from a URL.
Parameters:
url (str): The URL to extract the surl from.
Returns:
str: The extracted surl, or None if the URL does not contain a surl.
"""
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query)
surl = query_params.get("surl", [])
if surl:
return surl[0]
else:
return False
def get_formatted_size(size_bytes: int) -> str:
"""
Returns a human-readable file size from the given number of bytes.
Parameters:
size_bytes (int): The number of bytes to be converted to a file size.
Returns:
str: The file size in a human-readable format.
"""
if size_bytes >= 1024 * 1024:
size = size_bytes / (1024 * 1024)
unit = "MB"
elif size_bytes >= 1024:
size = size_bytes / 1024
unit = "KB"
else:
size = size_bytes
unit = "b"
return f"{size:.2f} {unit}"
def convert_seconds(seconds: int) -> str:
"""
Convert seconds into a human-readable format.
Parameters:
seconds (int): The number of seconds to convert.
Returns:
str: The seconds converted to a human-readable format.
"""
seconds = int(seconds)
hours = seconds // 3600
remaining_seconds = seconds % 3600
minutes = remaining_seconds // 60
remaining_seconds_final = remaining_seconds % 60
if hours > 0:
return f"{hours}h:{minutes}m:{remaining_seconds_final}s"
elif minutes > 0:
return f"{minutes}m:{remaining_seconds_final}s"
else:
return f"{remaining_seconds_final}s"
async def is_user_on_chat(bot: TelegramClient, chat_id: int, user_id: int) -> bool:
"""
Check if a user is present in a specific chat.
Parameters:
bot (TelegramClient): The Telegram client instance.
chat_id (int): The ID of the chat.
user_id (int): The ID of the user.
Returns:
bool: True if the user is present in the chat, False otherwise.
"""
try:
check = await bot.get_permissions(chat_id, user_id)
return check
except:
return False
async def download_file(
url: str,
filename: str,
callback=None,
) -> str | bool:
"""
Download a file from a URL to a specified location.
Args:
url (str): The URL of the file to download.
filename (str): The location to save the file to.
callback (function, optional): A function that will be called
with progress updates during the download. The function should
accept three arguments: the number of bytes downloaded so far,
the total size of the file, and a status message.
Returns:
str: The filename of the downloaded file, or False if the download
failed.
Raises:
requests.exceptions.HTTPError: If the server returns an error.
OSError: If there is an error opening or writing to the file.
"""
try:
response = requests.get(url, stream=True)
response.raise_for_status()
with open(filename, "wb") as file:
for chunk in response.iter_content(chunk_size=1024):
file.write(chunk)
if callback:
downloaded_size = file.tell()
total_size = int(response.headers.get("content-length", 0))
await callback(downloaded_size, total_size, "Downloading")
return filename
except Exception as e:
print(f"Error downloading file: {e}")
return False
def download_image_to_bytesio(url: str, filename: str) -> BytesIO | None:
"""
Downloads an image from a URL and returns it as a BytesIO object.
Args:
url (str): The URL of the image to download.
filename (str): The filename to save the image as.
Returns:
BytesIO: The image data as a BytesIO object, or None if the download failed.
"""
try:
response = requests.get(url)
if response.status_code == 200:
image_bytes = BytesIO(response.content)
image_bytes.name = filename
return image_bytes
else:
return None
except:
return None