-
Notifications
You must be signed in to change notification settings - Fork 152
/
Copy pathtools.py
290 lines (234 loc) · 7.38 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
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
290
import os
import re
import traceback
import uuid
from contextlib import suppress
from io import BytesIO
from urllib.parse import parse_qs, urlparse
import requests
from PIL import Image
from telethon import TelegramClient
from config import BOT_USERNAME, PUBLIC_EARN_API
from redis_db import db
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 Exception:
return False
async def download_file(
url: str,
filename: str,
callback=None,
) -> str | bool:
try:
response = requests.get(url, stream=True)
response.raise_for_status()
with suppress(
requests.exceptions.ChunkedEncodingError,
):
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")
# await asyncio.sleep(2)
return filename
except Exception as e:
traceback.print_exc()
print(f"Error downloading file: {e}")
raise Exception(e)
def save_image_from_bytesio(image_bytesio, filename):
try:
image_bytesio.seek(0)
image = Image.open(image_bytesio)
image.save(filename)
image.close()
return filename
except Exception as e:
print(f"Error saving image: {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)
content = BytesIO()
content.name = filename
if response.status_code == 200:
for chunk in response.iter_content(chunk_size=1024):
content.write(chunk)
else:
return None
content.seek(0)
return content
except Exception:
return None
def remove_all_videos():
current_directory = os.getcwd()
video_extensions = [".mp4", ".mkv", ".webm"]
try:
for file_name in os.listdir(current_directory):
if any(file_name.lower().endswith(ext) for ext in video_extensions):
file_path = os.path.join(current_directory, file_name)
os.remove(file_path)
except Exception as e:
print(f"Error: {e}")
def generate_shortenedUrl(
sender_id: int,
):
try:
uid = str(uuid.uuid4())
data = requests.get(
"https://publicearn.com/api",
params={
"api": PUBLIC_EARN_API,
"url": f"https://t.me/{BOT_USERNAME}?start=token_{uid}",
"alias": uid.split("-", maxsplit=2)[0],
},
)
data.raise_for_status()
data_json = data.json()
if data_json.get("status") == "success":
url = data_json.get("shortenedUrl")
db.set(f"token_{uid}", f"{sender_id}|{url}", ex=21600)
return url
else:
return None
except Exception as e:
return None