Skip to content

Commit

Permalink
completely changed upload.py
Browse files Browse the repository at this point in the history
Signed-off-by: Udith <[email protected]>
  • Loading branch information
uaudith committed Mar 21, 2020
1 parent 4d1e94c commit 6c3847f
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 189 deletions.
24 changes: 12 additions & 12 deletions userge/plugins/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from googletrans import Translator, LANGUAGES
from search_engine_parser import GoogleSearch
from userge import userge, Config
from userge.utils import humanbytes
from userge.utils.progress import humanbytes


@userge.on_cmd("ping", about="__check how long it takes to ping your userbot__")
Expand Down Expand Up @@ -63,15 +63,15 @@ async def search(_, message):


@userge.on_cmd("json",
about="""__message object to json__
about="""__message object to json__
**Usage:**
reply `.json` to any message""")
async def jsonify(_, message):
the_real_message = str(message.reply_to_message) \
if message.reply_to_message \
else str(message)
else str(message)

if len(the_real_message) > Config.MAX_MESSAGE_LENGTH:
await userge.send_output_as_file(
Expand Down Expand Up @@ -108,7 +108,7 @@ async def del_msg(_, message):


@userge.on_cmd("ids",
about="""__display ids__
about="""__display ids__
**Usage:**
Expand Down Expand Up @@ -149,7 +149,7 @@ async def getids(_, message):


@userge.on_cmd("admins",
about="""__View or mention admins in chat__
about="""__View or mention admins in chat__
**Available Flags:**
`-m` : __mention all admins__
Expand Down Expand Up @@ -211,7 +211,7 @@ async def mentionadmins(_, message):


@userge.on_cmd("ub",
about="""__Searches Urban Dictionary for the query__
about="""__Searches Urban Dictionary for the query__
**Usage:**
Expand Down Expand Up @@ -257,7 +257,7 @@ async def urban_dict(_, message):


@userge.on_cmd("tr",
about=f"""__Translate the given text using Google Translate__
about=f"""__Translate the given text using Google Translate__
**Supported Languages:**
__{dumps(LANGUAGES, indent=4, sort_keys=True)}__
Expand Down Expand Up @@ -346,7 +346,7 @@ async def speedtst(_, message):

test.results.share()
result = test.results.dict()

except Exception as e:
await message.edit(str(e))
return
Expand Down Expand Up @@ -384,7 +384,7 @@ async def speedtst(_, message):


@userge.on_cmd("sd (\\d+) (.+)",
about="""__make self-destructable messages__
about="""__make self-destructable messages__
**Usage:**
Expand All @@ -400,7 +400,7 @@ async def selfdestruct(_, message):


@userge.on_cmd("google",
about="""__do a Google search__
about="""__do a Google search__
**Available Flags:**
Expand Down Expand Up @@ -464,7 +464,7 @@ async def gsearch(_, message):


@userge.on_cmd("wiki",
about="""__do a Wikipedia search__
about="""__do a Wikipedia search__
**Available Flags:**
Expand Down Expand Up @@ -519,4 +519,4 @@ async def wiki_pedia(_, message):
)

else:
await message.edit(OUTPUT, disable_web_page_preview=True)
await message.edit(OUTPUT, disable_web_page_preview=True)
137 changes: 26 additions & 111 deletions userge/plugins/upload.py
Original file line number Diff line number Diff line change
@@ -1,140 +1,55 @@
import time
from datetime import datetime
from userge.utils import progress
from userge import userge
from pathlib import Path
from pyrogram import Message
from pyrogram.errors.exceptions import FloodWait

from userge.utils import (
progress,
take_screen_shot,
extractMetadata,
createParser
)

LOGGER = userge.getLogger(__name__)


@userge.on_cmd("upload", about="upload files to telegram")
async def uploadtotg(_, message):
async def uploadtotg(_, message: Message):
try:
string = Path(message.text.split(" ", maxsplit=1)[1])

except IndexError:
await message.edit("wrong syntax\n`.upload <path>`")
else:
await message.delete()
await explorer(string, message)
await explorer(string, message.chat.id)


async def explorer(path: Path, message: Message):
async def explorer(path: Path, chatid):
if path.is_file():
try:
await upload(path, message.chat.id)
await upload(path, chatid)
except FloodWait as x:
time.sleep(x.x) # asyncio sleep ?
await message.edit(f"`Floodwait occured for {x.x} seconds")
elif path.is_dir():
for i in path.iterdir():
await explorer(i, message)
await explorer(i, chatid)


async def upload(path: Path, chat_id: int):

message = await userge.send_message(chat_id, "`Starting ...`")
message_id = message.message_id
size = path.stat().st_size
if int(size) > (1024 * 1024 * 1500):
await message.edit('<i>File Size Too Large(' + str(round(int(size) / (1024 * 1024), 0)) + 'MB)</i> \U0001f61e')
return

LOGGER.info(path.name)
metadata = extractMetadata(createParser(str(path)))
duration = 0
width = 0
height = 0
title = None
artist = None
thumb = 'resources/userge(8).png'
caption = path.name
if metadata:
if metadata.has("duration"):
duration = metadata.get('duration').seconds
if metadata.has("width"):
width = metadata.get("width")
if metadata.has("height"):
height = metadata.get("height")
if metadata.has("title"):
title = metadata.get("title")
if metadata.has("artist"):
artist = metadata.get("artist")
filename = str(path)
if filename.endswith((".mkv", ".mp4", ".webm")) and duration:
thumb = await take_screen_shot(f'./{filename}', duration)
start_time = time.time()
await message.edit('<i>Trying To Upload......</i> \U0001f9D0')
try:
if filename.endswith((".mp3", ".flac", ".wav", ".m4a")):
await userge.send_audio(
chat_id=chat_id,
audio=filename,
caption=caption,
duration=duration,
title=title,
performer=artist,
thumb=thumb,
progress=progress,
progress_args=(
userge,
message_id,
chat_id,
start_time,
'<i>Uploading......</i>\U0001f60E'
)
)
elif filename.endswith((".mkv", ".mp4", ".webm")):
await userge.send_video(
chat_id=chat_id,
video=filename,
caption=caption,
duration=duration,
width=width,
height=height,
thumb=thumb,
supports_streaming=True,
progress=progress,
progress_args=(
userge,
message_id,
chat_id,
start_time,
'<i>Uploading......</i>\U0001f60E'
)
)
else:
await userge.send_document(
chat_id=chat_id,
document=filename,
thumb=thumb,
caption=caption,
progress=progress,
progress_args=(
userge,
message_id,
chat_id,
start_time,
'<i>Uploading......</i>\U0001f60E'
)
)

await userge.edit_message_text(
chat_id=chat_id,
message_id=message_id,
text='<i>Uploaded Successfully</i> \U0001f618'
)
except Exception as e:
LOGGER.exception("Exception occurred")
await userge.edit_message_text(
chat_id=chat_id,
message_id=message_id,
text=f"<b>ERROR:</b> <i>{e}</i>"
thumb_image_path = 'resources/userge(8).png'
message = await userge.send_message(chat_id, f"`Uploading {path.name} ...`")
start_t = datetime.now()
c_time = time.time()
doc_caption = path.name
the_real_download_location = await userge.send_document(
chat_id=chat_id,
document=str(path),
thumb=thumb_image_path,
caption=doc_caption,
parse_mode="html",
disable_notification=True,
progress=progress,
progress_args=(
"uploading", message, c_time
)
)
end_t = datetime.now()
ms = (end_t - start_t).seconds
await message.edit(f"Uploaded in {ms} seconds")
2 changes: 0 additions & 2 deletions userge/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
from .progress import progress

from .tools import (
humanbytes,
TimeFormatter,
take_screen_shot,
createParser,
extractMetadata,
Expand Down
86 changes: 53 additions & 33 deletions userge/utils/progress.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,72 @@
import time
import math
import asyncio
from .tools import humanbytes, TimeFormatter
import time


async def progress(current, total, client, message_id, chat_id, start, status):
async def progress(
current,
total,
ud_type,
message,
start
):
now = time.time()
diff = now - start

if current == total or round(diff % 15) == 0:
if round(diff % 10.00) == 0 or current == total:
# if round(current / total * 100, 0) % 5 == 0:
percentage = current * 100 / total
speed = current / diff

elapsed_time = round(diff) * 1000
time_to_completion = round((total - current) / speed) * 1000
estimated_total_time = elapsed_time + time_to_completion
time_to_completion = await TimeFormatter(milliseconds=time_to_completion)
estimated_total_time = await TimeFormatter(milliseconds=estimated_total_time)

progress = "<code>{}{}</code>\n<i>{}%</i> | <i>{}ps\n{}</i> | <i>{}</i>\n<b>Total:</b> <i>{}</i>\n<b>Rem:</b> <i>{}</i>".format(
elapsed_time = time_formatter(milliseconds=elapsed_time)
estimated_total_time = time_formatter(milliseconds=estimated_total_time)

progress = "[{0}{1}] \nP: {2}%\n".format(
''.join(["█" for i in range(math.floor(percentage / 5))]),
''.join(["░" for i in range(20 - math.floor(percentage / 5))]),
round(percentage, 2),
await humanbytes(speed),
await humanbytes(current),
await humanbytes(total),
estimated_total_time if estimated_total_time != '' else "0s",
time_to_completion if time_to_completion != '' else "0s"
)
round(percentage, 2))

tmp = progress + "{0} of {1}\nSpeed: {2}/s\nETA: {3}\n".format(
humanbytes(current),
humanbytes(total),
humanbytes(speed),
# elapsed_time if elapsed_time != '' else "0 s",
estimated_total_time if estimated_total_time != '' else "0 s"
)
try:
if current == total:
await client.edit_message_text(
chat_id,
message_id,
text="<i>Completing Process...</i>\n<b>Please Wait !</b>"
await message.edit(
text="{}\n {}".format(
ud_type,
tmp
)
)
except:
pass

await asyncio.sleep(1)

await client.edit_message_text(
chat_id,
message_id,
text="{}\n{}".format(
status,
progress
)
)
def humanbytes(size):
# https://stackoverflow.com/a/49361727/4723940
# 2**10 = 1024
if not size:
return ""
power = 2**10
n = 0
Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'}
while size > power:
size /= power
n += 1
return str(round(size, 2)) + " " + Dic_powerN[n] + 'B'


except Exception:
pass
def time_formatter(milliseconds: int) -> str:
seconds, milliseconds = divmod(int(milliseconds), 1000)
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
tmp = ((str(days) + "d, ") if days else "") + \
((str(hours) + "h, ") if hours else "") + \
((str(minutes) + "m, ") if minutes else "") + \
((str(seconds) + "s, ") if seconds else "") + \
((str(milliseconds) + "ms, ") if milliseconds else "")
return tmp[:-2]
Loading

0 comments on commit 6c3847f

Please sign in to comment.