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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from uuid import uuid4
|
| 6 |
+
|
| 7 |
+
import telethon
|
| 8 |
+
from telethon import Button, TelegramClient, events, utils
|
| 9 |
+
from telethon.events.newmessage import NewMessage
|
| 10 |
+
from telethon.tl.functions.channels import GetMessagesRequest
|
| 11 |
+
from telethon.tl.functions.messages import ForwardMessagesRequest
|
| 12 |
+
from telethon.tl.patched import Message
|
| 13 |
+
from telethon.tl.types import Document
|
| 14 |
+
from telethon.types import UpdateEditMessage
|
| 15 |
+
|
| 16 |
+
from cansend import CanSend
|
| 17 |
+
from config import BOT_USERNAME, PRIVATE_CHAT_ID
|
| 18 |
+
from FastTelethon import upload_file
|
| 19 |
+
from redis_db import db
|
| 20 |
+
from tools import (
|
| 21 |
+
convert_seconds,
|
| 22 |
+
download_file,
|
| 23 |
+
download_image_to_bytesio,
|
| 24 |
+
extract_code_from_url,
|
| 25 |
+
get_formatted_size,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class VideoSender:
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
client: TelegramClient,
|
| 34 |
+
message: NewMessage.Event,
|
| 35 |
+
edit_message: Message,
|
| 36 |
+
url: str,
|
| 37 |
+
data,
|
| 38 |
+
):
|
| 39 |
+
self.client = client
|
| 40 |
+
self.data = data
|
| 41 |
+
self.url = url
|
| 42 |
+
self.edit_message = edit_message
|
| 43 |
+
self.message = message
|
| 44 |
+
self.uuid = str(uuid4())
|
| 45 |
+
self.stop_sending = False
|
| 46 |
+
self.thumbnail = self.get_thumbnail()
|
| 47 |
+
self.can_send = CanSend()
|
| 48 |
+
self.start_time = time.time()
|
| 49 |
+
self.task = None
|
| 50 |
+
self.client.add_event_handler(
|
| 51 |
+
self.stop, events.CallbackQuery(pattern=f"^stop{self.uuid}")
|
| 52 |
+
)
|
| 53 |
+
self.caption = f"""
|
| 54 |
+
File Name: `{self.data['file_name']}`
|
| 55 |
+
Size: **{self.data["size"]}**
|
| 56 |
+
|
| 57 |
+
@Teracinee_bot
|
| 58 |
+
"""
|
| 59 |
+
self.caption2 = f"""
|
| 60 |
+
Downloading `{self.data['file_name']}`
|
| 61 |
+
Size: **{self.data["size"]}**
|
| 62 |
+
|
| 63 |
+
@Teracinee_bot
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
async def progress_bar(self, current_downloaded, total_downloaded, state="Sending"):
|
| 67 |
+
if not self.can_send.can_send():
|
| 68 |
+
return
|
| 69 |
+
|
| 70 |
+
bar_length = 20
|
| 71 |
+
percent = current_downloaded / total_downloaded
|
| 72 |
+
arrow = "█" * int(percent * bar_length)
|
| 73 |
+
spaces = "░" * (bar_length - len(arrow))
|
| 74 |
+
|
| 75 |
+
elapsed_time = time.time() - self.start_time
|
| 76 |
+
|
| 77 |
+
head_text = f"{state} `{self.data['file_name']}`"
|
| 78 |
+
progress_bar = f"[{arrow + spaces}] {percent:.2%}"
|
| 79 |
+
upload_speed = current_downloaded / elapsed_time if elapsed_time > 0 else 0
|
| 80 |
+
speed_line = f"Speed: **{get_formatted_size(upload_speed)}/s**"
|
| 81 |
+
|
| 82 |
+
time_remaining = (
|
| 83 |
+
(total_downloaded - current_downloaded) / upload_speed
|
| 84 |
+
if upload_speed > 0
|
| 85 |
+
else 0
|
| 86 |
+
)
|
| 87 |
+
time_line = f"Time Remaining: `{convert_seconds(time_remaining)}`"
|
| 88 |
+
size_line = f"Size: **{get_formatted_size(current_downloaded)}** / **{get_formatted_size(total_downloaded)}**"
|
| 89 |
+
|
| 90 |
+
await self.edit_message.edit(
|
| 91 |
+
f"{head_text}\n{progress_bar}\n{speed_line}\n{time_line}\n{size_line}",
|
| 92 |
+
parse_mode="markdown",
|
| 93 |
+
buttons=[Button.inline("Stop", data=f"stop{self.uuid}")],
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
async def send_media(self, shorturl):
|
| 97 |
+
try:
|
| 98 |
+
self.thumbnail.seek(0) if self.thumbnail else None
|
| 99 |
+
spoiler_media = (
|
| 100 |
+
await self.client._file_to_media(
|
| 101 |
+
self.data["direct_link"],
|
| 102 |
+
supports_streaming=True,
|
| 103 |
+
progress_callback=self.progress_bar,
|
| 104 |
+
thumb=self.thumbnail,
|
| 105 |
+
)
|
| 106 |
+
)[1]
|
| 107 |
+
spoiler_media.spoiler = True
|
| 108 |
+
file = await self.client.send_file(
|
| 109 |
+
self.message.chat.id,
|
| 110 |
+
file=spoiler_media,
|
| 111 |
+
caption=self.caption,
|
| 112 |
+
allow_cache=True,
|
| 113 |
+
force_document=False,
|
| 114 |
+
parse_mode="markdown",
|
| 115 |
+
reply_to=self.message.id,
|
| 116 |
+
supports_streaming=True,
|
| 117 |
+
background=True,
|
| 118 |
+
buttons=[
|
| 119 |
+
[
|
| 120 |
+
Button.url(
|
| 121 |
+
"Direct Link",
|
| 122 |
+
url=f"https://{BOT_USERNAME}.t.me?start={self.uuid}",
|
| 123 |
+
),
|
| 124 |
+
],
|
| 125 |
+
[
|
| 126 |
+
Button.url("Channel ", url="https://t.me/TeracineeChannel"),
|
| 127 |
+
Button.url("Group ", url="https://t.me/+EtHQEItJyzE4YzU0"),
|
| 128 |
+
],
|
| 129 |
+
],
|
| 130 |
+
)
|
| 131 |
+
try:
|
| 132 |
+
if self.edit_message:
|
| 133 |
+
await self.edit_message.delete()
|
| 134 |
+
except Exception as e:
|
| 135 |
+
pass
|
| 136 |
+
|
| 137 |
+
except telethon.errors.rpcerrorlist.WebpageCurlFailedError:
|
| 138 |
+
path = Path(self.data["file_name"])
|
| 139 |
+
if not os.path.exists(path):
|
| 140 |
+
try:
|
| 141 |
+
download_task = asyncio.create_task(
|
| 142 |
+
download_file(
|
| 143 |
+
self.data["direct_link"],
|
| 144 |
+
self.data["file_name"],
|
| 145 |
+
self.progress_bar,
|
| 146 |
+
)
|
| 147 |
+
)
|
| 148 |
+
download = await asyncio.gather(download_task)
|
| 149 |
+
except:
|
| 150 |
+
await self.edit_message.edit("Failed to Download the media. trying again.")
|
| 151 |
+
try:
|
| 152 |
+
download_task = asyncio.create_task(
|
| 153 |
+
download_file(
|
| 154 |
+
self.data["link"],
|
| 155 |
+
self.data["file_name"],
|
| 156 |
+
self.progress_bar,
|
| 157 |
+
)
|
| 158 |
+
)
|
| 159 |
+
download = await asyncio.gather(download_task)
|
| 160 |
+
except:
|
| 161 |
+
return await self.handle_failed_download()
|
| 162 |
+
else:
|
| 163 |
+
download = [path]
|
| 164 |
+
if not download or not download[0] or not os.path.exists(download[0]):
|
| 165 |
+
return await self.handle_failed_download()
|
| 166 |
+
self.download = Path(download[0])
|
| 167 |
+
try:
|
| 168 |
+
with open(self.download, "rb") as out:
|
| 169 |
+
res = await upload_file(
|
| 170 |
+
self.client, out, self.progress_bar, self.data["file_name"]
|
| 171 |
+
)
|
| 172 |
+
attributes, mime_type = utils.get_attributes(
|
| 173 |
+
self.download,
|
| 174 |
+
)
|
| 175 |
+
file = await self.client.send_file(
|
| 176 |
+
self.message.chat.id,
|
| 177 |
+
file=res,
|
| 178 |
+
caption=self.caption,
|
| 179 |
+
background=True,
|
| 180 |
+
reply_to=self.message.id,
|
| 181 |
+
allow_cache=True,
|
| 182 |
+
force_document=False,
|
| 183 |
+
parse_mode="markdown",
|
| 184 |
+
supports_streaming=True,
|
| 185 |
+
thumb=self.thumbnail,
|
| 186 |
+
# attributes=attributes,
|
| 187 |
+
mime_type=mime_type,
|
| 188 |
+
buttons=[
|
| 189 |
+
[
|
| 190 |
+
Button.url(
|
| 191 |
+
"Direct Link",
|
| 192 |
+
url=f"https://{BOT_USERNAME}.t.me?start={self.uuid}",
|
| 193 |
+
),
|
| 194 |
+
],
|
| 195 |
+
[
|
| 196 |
+
Button.url("Channel ", url="https://t.me/+LsECfdEyaVU4OGY8"),
|
| 197 |
+
Button.url(
|
| 198 |
+
"Group ", url="https://t.me/+EtHQEItJyzE4YzU0"
|
| 199 |
+
),
|
| 200 |
+
],
|
| 201 |
+
],
|
| 202 |
+
)
|
| 203 |
+
try:
|
| 204 |
+
os.unlink(self.download)
|
| 205 |
+
except Exception:
|
| 206 |
+
pass
|
| 207 |
+
try:
|
| 208 |
+
os.unlink(self.data["file_name"])
|
| 209 |
+
except Exception:
|
| 210 |
+
pass
|
| 211 |
+
except Exception as e:
|
| 212 |
+
self.client.remove_event_handler(
|
| 213 |
+
self.stop, events.CallbackQuery(pattern=f"^stop{self.uuid}")
|
| 214 |
+
)
|
| 215 |
+
try:
|
| 216 |
+
os.unlink(self.download)
|
| 217 |
+
except Exception:
|
| 218 |
+
pass
|
| 219 |
+
try:
|
| 220 |
+
os.unlink(self.data["file_name"])
|
| 221 |
+
except Exception:
|
| 222 |
+
pass
|
| 223 |
+
return await self.handle_failed_download()
|
| 224 |
+
|
| 225 |
+
await self.save_forward_file(file, shorturl)
|
| 226 |
+
|
| 227 |
+
async def handle_failed_download(self):
|
| 228 |
+
try:
|
| 229 |
+
os.unlink(self.data["file_name"])
|
| 230 |
+
except Exception:
|
| 231 |
+
pass
|
| 232 |
+
try:
|
| 233 |
+
os.unlink(self.download)
|
| 234 |
+
except Exception:
|
| 235 |
+
pass
|
| 236 |
+
try:
|
| 237 |
+
await self.edit_message.edit(
|
| 238 |
+
f"Sorry! Download Failed but you can download it from [here]({self.data['direct_link']}) or [here]({self.data['link']}).",
|
| 239 |
+
parse_mode="markdown",
|
| 240 |
+
buttons=[Button.url("Download", data=self.data["direct_link"])],
|
| 241 |
+
|
| 242 |
+
)
|
| 243 |
+
except Exception:
|
| 244 |
+
pass
|
| 245 |
+
|
| 246 |
+
async def save_forward_file(self, file, shorturl):
|
| 247 |
+
forwarded_message = await self.client.forward_messages(
|
| 248 |
+
PRIVATE_CHAT_ID,
|
| 249 |
+
[file],
|
| 250 |
+
from_peer=self.message.chat.id,
|
| 251 |
+
with_my_score=True,
|
| 252 |
+
background=True,
|
| 253 |
+
)
|
| 254 |
+
if forwarded_message[0].id:
|
| 255 |
+
db.set_key(self.uuid, forwarded_message[0].id)
|
| 256 |
+
db.set_key(f"mid_{forwarded_message[0].id}", self.uuid)
|
| 257 |
+
db.set_key(shorturl, forwarded_message[0].id)
|
| 258 |
+
self.client.remove_event_handler(
|
| 259 |
+
self.stop, events.CallbackQuery(pattern=f"^stop{self.uuid}")
|
| 260 |
+
)
|
| 261 |
+
try:
|
| 262 |
+
await self.edit_message.delete()
|
| 263 |
+
except Exception:
|
| 264 |
+
pass
|
| 265 |
+
try:
|
| 266 |
+
os.unlink(self.data["file_name"])
|
| 267 |
+
except Exception:
|
| 268 |
+
pass
|
| 269 |
+
try:
|
| 270 |
+
os.unlink(self.download)
|
| 271 |
+
except Exception:
|
| 272 |
+
pass
|
| 273 |
+
db.set(self.message.sender_id, time.monotonic(), ex=60)
|
| 274 |
+
# await self.forward_file(
|
| 275 |
+
# self.client, forwarded_message[0].id, self.message, self.edit_message
|
| 276 |
+
# )
|
| 277 |
+
|
| 278 |
+
async def send_video(self):
|
| 279 |
+
self.thumbnail = download_image_to_bytesio(self.data["thumb"], "thumbnail.png")
|
| 280 |
+
shorturl = extract_code_from_url(self.url)
|
| 281 |
+
if not shorturl:
|
| 282 |
+
return await self.edit_message.edit("Seems like your link is invalid.")
|
| 283 |
+
|
| 284 |
+
try:
|
| 285 |
+
if self.edit_message:
|
| 286 |
+
await self.edit_message.delete()
|
| 287 |
+
except Exception as e:
|
| 288 |
+
pass
|
| 289 |
+
db.set(self.message.sender_id, time.monotonic(), ex=60)
|
| 290 |
+
self.edit_message = await self.message.reply(
|
| 291 |
+
self.caption2, file=self.thumbnail, parse_mode="markdown"
|
| 292 |
+
)
|
| 293 |
+
self.task = asyncio.create_task(self.send_media(shorturl))
|
| 294 |
+
|
| 295 |
+
async def stop(self, event):
|
| 296 |
+
self.task.cancel()
|
| 297 |
+
self.client.remove_event_handler(
|
| 298 |
+
self.stop, events.CallbackQuery(pattern=f"^stop{self.uuid}")
|
| 299 |
+
)
|
| 300 |
+
await event.answer("Process stopped.")
|
| 301 |
+
try:
|
| 302 |
+
os.unlink(self.data["file_name"])
|
| 303 |
+
except Exception:
|
| 304 |
+
pass
|
| 305 |
+
try:
|
| 306 |
+
os.unlink(self.download)
|
| 307 |
+
except Exception:
|
| 308 |
+
pass
|
| 309 |
+
try:
|
| 310 |
+
await self.edit_message.delete()
|
| 311 |
+
except Exception:
|
| 312 |
+
pass
|
| 313 |
+
|
| 314 |
+
def get_thumbnail(self):
|
| 315 |
+
return download_image_to_bytesio(self.data["thumb"], "thumbnail.png")
|
| 316 |
+
|
| 317 |
+
@staticmethod
|
| 318 |
+
async def forward_file(
|
| 319 |
+
client: TelegramClient,
|
| 320 |
+
file_id: int,
|
| 321 |
+
message: Message,
|
| 322 |
+
edit_message: UpdateEditMessage = None,
|
| 323 |
+
uid: str = None,
|
| 324 |
+
):
|
| 325 |
+
if edit_message:
|
| 326 |
+
try:
|
| 327 |
+
await edit_message.delete()
|
| 328 |
+
except Exception:
|
| 329 |
+
pass
|
| 330 |
+
result = await client(
|
| 331 |
+
GetMessagesRequest(channel=PRIVATE_CHAT_ID, id=[int(file_id)])
|
| 332 |
+
)
|
| 333 |
+
msg: Message = result.messages[0] if result and result.messages else None
|
| 334 |
+
if not msg:
|
| 335 |
+
return False
|
| 336 |
+
media: Document = (
|
| 337 |
+
msg.media.document if hasattr(msg, "media") and msg.media.document else None
|
| 338 |
+
)
|
| 339 |
+
try:
|
| 340 |
+
await message.reply(
|
| 341 |
+
message=msg.message,
|
| 342 |
+
file=media,
|
| 343 |
+
# entity=msg.entities,
|
| 344 |
+
background=True,
|
| 345 |
+
reply_to=message.id,
|
| 346 |
+
force_document=False,
|
| 347 |
+
buttons=[
|
| 348 |
+
[
|
| 349 |
+
Button.url(
|
| 350 |
+
"Direct Link",
|
| 351 |
+
url=f"https://{BOT_USERNAME}.t.me?start={uid}",
|
| 352 |
+
),
|
| 353 |
+
],
|
| 354 |
+
# [
|
| 355 |
+
# Button.url("Channel ", url="https://t.me/+LsECfdEyaVU4OGY8"),
|
| 356 |
+
# Button.url("Group ", url="https://t.me/+EtHQEItJyzE4YzU0"),
|
| 357 |
+
# ],
|
| 358 |
+
],
|
| 359 |
+
parse_mode="markdown",
|
| 360 |
+
)
|
| 361 |
+
db.set(message.sender_id, time.monotonic(), ex=60)
|
| 362 |
+
db.incr(
|
| 363 |
+
f"check_{message.sender_id}",
|
| 364 |
+
1,
|
| 365 |
+
)
|
| 366 |
+
return True
|
| 367 |
+
except Exception:
|
| 368 |
+
return False
|