Exemple #1
0
async def split_(message: Message) -> None:
    """ split files """
    split_size = int(message.matches[0].group(1))
    file_path = str(message.matches[0].group(2))
    if not file_path:
        await message.err("missing file path!")
        return
    if not isfile(file_path):
        await message.err("file path not exists!")
        return
    await message.edit("`processing...`")
    start_t = datetime.now()
    s_obj = SCLib(file_path)
    s_obj.split(split_size)
    tmp = \
        "__Splitting file path...__\n" + \
        "```{}({}%)```\n" + \
        "**File Path** : `{}`\n" + \
        "**Dest** : `{}`\n" + \
        "**Completed** : `{}`\n" + \
        "**Total** : `{}`\n" + \
        "**Speed** : `{}/s`\n" + \
        "**ETA** : `{}`\n" + \
        "**Completed Files** : `{}/{}`"
    count = 0
    while not s_obj.finished:
        if message.process_is_canceled:
            s_obj.cancel()
        count += 1
        if count >= Config.EDIT_SLEEP_TIMEOUT:
            count = 0
            await message.try_to_edit(
                tmp.format(s_obj.progress, s_obj.percentage, file_path,
                           s_obj.final_file_path, humanbytes(s_obj.completed),
                           humanbytes(s_obj.total), humanbytes(s_obj.speed),
                           s_obj.eta, s_obj.completed_files,
                           s_obj.total_files))
        await sleep(1)
    if s_obj.output:
        await message.err(s_obj.output)
    else:
        end_t = datetime.now()
        m_s = (end_t - start_t).seconds
        await message.edit(
            f"**split** `{file_path}` into `{s_obj.final_file_path}` "
            f"in `{m_s}` seconds.",
            log=__name__)
Exemple #2
0
async def audio_upload(message: Message, path, del_path: bool = False,
                       extra: str = '', with_thumb: bool = True):
    title = None
    artist = None
    thumb = None
    duration = 0
    str_path = str(path)
    file_size = humanbytes(os.stat(str_path).st_size)
    if with_thumb:
        try:
            album_art = stagger.read_tag(str_path)
            if album_art.picture and not os.path.lexists(Config.THUMB_PATH):
                bytes_pic_data = album_art[stagger.id3.APIC][0].data
                bytes_io = io.BytesIO(bytes_pic_data)
                image_file = Image.open(bytes_io)
                image_file.save("album_cover.jpg", "JPEG")
                thumb = "album_cover.jpg"
        except stagger.errors.NoTagError:
            pass
        if not thumb:
            thumb = await get_thumb(str_path)
    metadata = extractMetadata(createParser(str_path))
    if metadata and metadata.has("title"):
        title = metadata.get("title")
    if metadata and metadata.has("artist"):
        artist = metadata.get("artist")
    if metadata and metadata.has("duration"):
        duration = metadata.get("duration").seconds
    sent: Message = await message.client.send_message(
        message.chat.id, f"`Uploading {str_path} as audio ... {extra}`")
    start_t = datetime.now()
    await message.client.send_chat_action(message.chat.id, "upload_audio")
    try:
        msg = await message.client.send_audio(
            chat_id=message.chat.id,
            audio=str_path,
            thumb=thumb,
            caption=f"<code>{path.name} [ {file_size} ]</code>",
            title=title,
            performer=artist,
            duration=duration,
            parse_mode="html",
            disable_notification=True,
            progress=progress,
            progress_args=(message, f"uploading {extra}", str_path)
        )
    except ValueError as e_e:
        await sent.edit(f"Skipping `{str_path}` due to {e_e}")
    except Exception as u_e:
        await sent.edit(str(u_e))
        raise u_e
    else:
        await sent.delete()
        await finalize(message, msg, start_t)
        if os.path.exists(str_path) and del_path:
            os.remove(str_path)
    finally:
        if os.path.lexists("album_cover.jpg"):
            os.remove("album_cover.jpg")
Exemple #3
0
 def _search(
     self,
     search_query: str,
     flags: list,
     parent_id: str = "",
     list_root: bool = False,
 ) -> str:
     force = "-f" in flags
     pid = parent_id or self._parent_id
     if pid and not force:
         query = f"'{pid}' in parents and (name contains '{search_query}')"
     else:
         query = f"name contains '{search_query}'"
     page_token = None
     limit = int(flags.get("-l", 20))
     page_size = limit if limit < 50 else 50
     fields = "nextPageToken, files(id, name, mimeType, size)"
     results = []
     msg = ""
     while True:
         response = (self._service.files().list(
             supportsTeamDrives=True,
             includeTeamDriveItems=True,
             q=query,
             spaces="drive",
             corpora="allDrives",
             fields=fields,
             pageSize=page_size,
             orderBy="modifiedTime desc",
             pageToken=page_token,
         ).execute())
         for file_ in response.get("files", []):
             if len(results) >= limit:
                 break
             if file_.get("mimeType") == G_DRIVE_DIR_MIME_TYPE:
                 msg += G_DRIVE_FOLDER_LINK.format(file_.get("id"),
                                                   file_.get("name"))
             else:
                 msg += G_DRIVE_FILE_LINK.format(
                     file_.get("id"),
                     file_.get("name"),
                     humanbytes(int(file_.get("size", 0))),
                 )
             msg += "\n"
             results.append(file_)
         if len(results) >= limit:
             break
         page_token = response.get("nextPageToken", None)
         if page_token is None:
             break
     if not msg:
         return "`Not Found!`"
     if parent_id and not force:
         out = f"**List GDrive Folder** : `{parent_id}`\n"
     elif list_root and not force:
         out = f"**List GDrive Root Folder** : `{self._parent_id}`\n"
     else:
         out = f"**GDrive Search Query** : `{search_query}`\n"
     return out + f"**Limit** : `{limit}`\n\n__Results__ : \n\n" + msg
Exemple #4
0
 def _download_file(self, path: str, name: str, **kwargs) -> None:
     request = self._service.files().get_media(fileId=kwargs['id'],
                                               supportsTeamDrives=True)
     with io.FileIO(os.path.join(path, name), 'wb') as d_f:
         d_file_obj = MediaIoBaseDownload(d_f,
                                          request,
                                          chunksize=50 * 1024 * 1024)
         c_time = time.time()
         done = False
         while done is False:
             status, done = d_file_obj.next_chunk()
             if self._is_canceled:
                 raise ProcessCanceled
             if status:
                 f_size = status.total_size
                 diff = time.time() - c_time
                 downloaded = status.resumable_progress
                 percentage = downloaded / f_size * 100
                 speed = round(downloaded / diff, 2)
                 eta = round((f_size - downloaded) / speed)
                 tmp = \
                     "__Downloading From GDrive...__\n" + \
                     "```[{}{}]({}%)```\n" + \
                     "**File Name** : `{}`\n" + \
                     "**File Size** : `{}`\n" + \
                     "**Downloaded** : `{}`\n" + \
                     "**Completed** : `{}/{}`\n" + \
                     "**Speed** : `{}/s`\n" + \
                     "**ETA** : `{}`"
                 self._progress = tmp.format(
                     "".join([Config.FINISHED_PROGRESS_STR \
                         for i in range(math.floor(percentage / 5))]),
                     "".join([Config.UNFINISHED_PROGRESS_STR \
                         for i in range(20 - math.floor(percentage / 5))]),
                     round(percentage, 2),
                     name,
                     humanbytes(f_size),
                     humanbytes(downloaded),
                     self._completed,
                     self._list,
                     humanbytes(speed),
                     time_formatter(eta))
     self._completed += 1
     _LOG.info("Downloaded Google-Drive File => Name: %s ID: %s", name,
               kwargs['id'])
Exemple #5
0
async def url_download(message: Message, url: str) -> Tuple[str, int]:
    """ download from link """
    await message.edit("`Downloading From URL...`")
    start_t = datetime.now()
    custom_file_name = unquote_plus(os.path.basename(url))
    if "|" in url:
        url, c_file_name = url.split("|", maxsplit=1)
        url = url.strip()
        if c_file_name:
            custom_file_name = c_file_name.strip()
    dl_loc = os.path.join(Config.DOWN_PATH, custom_file_name)
    downloader = SmartDL(url, dl_loc, progress_bar=False)
    downloader.start(blocking=False)
    with message.cancel_callback(downloader.stop):
        while not downloader.isFinished():
            total_length = downloader.filesize if downloader.filesize else 0
            downloaded = downloader.get_dl_size()
            percentage = downloader.get_progress() * 100
            speed = downloader.get_speed(human=True)
            estimated_total_time = downloader.get_eta(human=True)
            progress_str = \
                "__{}__\n" + \
                "```[{}{}]```\n" + \
                "**Progress** : `{}%`\n" + \
                "**URL** : `{}`\n" + \
                "**FILENAME** : `{}`\n" + \
                "**Completed** : `{}`\n" + \
                "**Total** : `{}`\n" + \
                "**Speed** : `{}`\n" + \
                "**ETA** : `{}`"
            progress_str = progress_str.format(
                "trying to download", ''.join(
                    (Config.FINISHED_PROGRESS_STR
                     for _ in range(math.floor(percentage / 5)))), ''.join(
                         (Config.UNFINISHED_PROGRESS_STR
                          for _ in range(20 - math.floor(percentage / 5)))),
                round(percentage, 2), url, custom_file_name,
                humanbytes(downloaded), humanbytes(total_length), speed,
                estimated_total_time)
            await message.edit(progress_str, disable_web_page_preview=True)
            await asyncio.sleep(Config.EDIT_SLEEP_TIMEOUT)
    if message.process_is_canceled:
        raise ProcessCanceled
    return dl_loc, (datetime.now() - start_t).seconds
Exemple #6
0
async def audio_upload(message: Message, path, del_path: bool):
    title = None
    artist = None
    thumb = None
    duration = 0
    strpath = str(path)
    file_size = humanbytes(os.stat(strpath).st_size)
    try:
        album_art = stagger.read_tag(strpath)
        if (album_art.picture and not os.path.lexists(THUMB_PATH)):
            bytes_pic_data = album_art[stagger.id3.APIC][0].data
            bytes_io = io.BytesIO(bytes_pic_data)
            image_file = Image.open(bytes_io)
            image_file.save("album_cover.jpg", "JPEG")
            thumb = "album_cover.jpg"
    except stagger.errors.NoTagError:
        pass
    metadata = extractMetadata(createParser(strpath))
    if metadata and metadata.has("title"):
        title = metadata.get("title")
    if metadata and metadata.has("artist"):
        artist = metadata.get("artist")
    if metadata and metadata.has("duration"):
        duration = metadata.get("duration").seconds
    sent: Message = await message.client.send_message(
        message.chat.id, f"`Uploading {path.name} as audio ...`")
    start_t = datetime.now()
    c_time = time.time()
    await message.client.send_chat_action(message.chat.id, "upload_audio")
    try:
        msg = await message.client.send_audio(
            chat_id=message.chat.id,
            audio=strpath,
            thumb=thumb,
            caption=f"{path.name} [ {file_size} ]",
            title=title,
            performer=artist,
            duration=duration,
            parse_mode="html",
            disable_notification=True,
            progress=progress,
            progress_args=(
                "uploading", userge, message, c_time, str(path.name)
            )
        )
    except Exception as u_e:
        await sent.edit(u_e)
        raise u_e
    else:
        await sent.delete()
        await finalize(message, msg, start_t)
    finally:
        if os.path.lexists("album_cover.jpg"):
            os.remove("album_cover.jpg")
        if os.path.exists(str(path)) and del_path:
            os.remove(str(path))
Exemple #7
0
async def media_h(message: Message):
    reply = message.reply_to_message
    if not reply:
        return await message.err("reply to a User")
    start = time.time()
    await message.edit(
        'This process takes soo much F*ing Time 😂 so here\'s a quote 🙆‍♀️\n\n`"All you gotta do is chill out... Let go of control and chill out... Let it be, Trust."`\n- **Esther Hicks**'
    )
    x = PrettyTable()
    media_dict = {}
    # Generate json
    for m in TYPES:
        media_dict[m] = {}
        media_dict[m]["file_size"] = 0
        media_dict[m]["count"] = 0
        media_dict[m]["max_size"] = 0
        media_dict[m]["max_file_link"] = ""
    # Count
    msg_count = 0
    x.title = "File Summary:"
    x.field_names = ["Media", "Count", "File size"]
    largest = "   <b>Largest Size</b>\n"
    u_mention = mention_html(reply.from_user.id, reply.from_user.first_name)
    async for msg in userge.search_messages(
        message.chat.id, "", from_user=reply.from_user.id
    ):
        msg_count += 1
        for media in TYPES:
            if msg[media]:
                media_dict[media]["file_size"] += msg[media].file_size
                media_dict[media]["count"] += 1
                if msg[media].file_size > media_dict[media]["max_size"]:
                    media_dict[media]["max_size"] = msg[media].file_size
                    media_dict[media]["max_file_link"] = msg.link

    for mediax in TYPES:
        x.add_row(
            [
                mediax,
                media_dict[mediax]["count"],
                humanbytes(media_dict[mediax]["file_size"]),
            ]
        )
        if media_dict[mediax]["count"] != 0:
            largest += f"•  [{mediax}]({media_dict[mediax]['max_file_link']}) : <code>{humanbytes(media_dict[mediax]['max_size'])}</code>\n"

    result = f"<b>{message.chat.title}</b>\n"
    result += f"👤 <b>User</b> : {u_mention}\n"
    result += f"<code>Total Messages: {msg_count}</code>\n"
    result += f"```{str(x)}```\n"
    result += f"{largest}\n"
    end = time.time()
    result += f"⏳ <code>Process took: {time_formatter(end - start)}</code>."
    await message.edit(result, disable_web_page_preview=True)
Exemple #8
0
def onedrive(link: str) -> str:
    link_without_query = urlparse(link)._replace(query=None).geturl()
    direct_link_encoded = str(standard_b64encode(bytes(link_without_query, "utf-8")), "utf-8")
    direct_link1 = f"https://api.onedrive.com/v1.0/shares/u!{direct_link_encoded}/root/content"
    resp = requests.head(direct_link1)
    if resp.status_code != 302:
        return "`Error: Unauthorized link, the link may be private`"
    dl_link = resp.next.url
    file_name = dl_link.rsplit("/", 1)[1]
    resp2 = requests.head(dl_link)
    dl_size = humanbytes(int(resp2.headers["Content-Length"]))
    return f"[{file_name} ({dl_size})]({dl_link})"
Exemple #9
0
 def _set_perms(self, file_id: str) -> str:
     self._set_permission(file_id)
     drive_file = self._service.files().get(fileId=file_id, supportsTeamDrives=True,
                                            fields="id, name, mimeType, size").execute()
     _LOG.info(
         "Set Permission : for Google-Drive File : %s\n%s", file_id, drive_file)
     mime_type = drive_file['mimeType']
     file_name = drive_file['name']
     file_id = drive_file['id']
     if mime_type == G_DRIVE_DIR_MIME_TYPE:
         return G_DRIVE_FOLDER_LINK.format(file_id, file_name)
     file_size = humanbytes(int(drive_file.get('size', 0)))
     return G_DRIVE_FILE_LINK.format(file_id, file_name, file_size)
Exemple #10
0
 def _search(self,
             search_query: str,
             flags: list,
             parent_id: str = "",
             list_root: bool = False) -> str:
     force = '-f' in flags
     pid = parent_id or self._parent_id
     if pid and not force:
         query = f"'{pid}' in parents and (name contains '{search_query}')"
     else:
         query = f"name contains '{search_query}'"
     page_token = None
     limit = int(flags.get('-l', 20))
     page_size = limit if limit < 50 else 50
     fields = 'nextPageToken, files(id, name, mimeType, size)'
     results = []
     msg = ""
     while True:
         response = self._service.files().list(supportsTeamDrives=True,
                                               includeTeamDriveItems=True,
                                               q=query, spaces='drive',
                                               corpora='allDrives', fields=fields,
                                               pageSize=page_size,
                                               orderBy='modifiedTime desc',
                                               pageToken=page_token).execute()
         for file_ in response.get('files', []):
             if len(results) >= limit:
                 break
             if file_.get('mimeType') == G_DRIVE_DIR_MIME_TYPE:
                 msg += G_DRIVE_FOLDER_LINK.format(file_.get('id'), file_.get('name'))
             else:
                 msg += G_DRIVE_FILE_LINK.format(
                     file_.get('id'), file_.get('name'), humanbytes(int(file_.get('size', 0))))
             msg += '\n'
             results.append(file_)
         if len(results) >= limit:
             break
         page_token = response.get('nextPageToken', None)
         if page_token is None:
             break
     del results
     if not msg:
         return "`Not Found!,Maybe You Can Search By Yourself`\n\n📂 Index Link: [Click here](https://my.gdriveku.workers.dev/0:/BOT%20UPLOAD/)"
     if parent_id and not force:
         out = f"**List GDrive Folder** : `{parent_id}`\n"
     elif list_root and not force:
         out = f"**List GDrive Root Folder** : `{self._parent_id}`\n"
     else:
         out = f"**GDrive Search Query** : `{search_query}`\n"
     return out + f"**Limit** : `{limit}`\n\n__Results__ : \n\n" + msg
Exemple #11
0
 def __progress(data: dict):
     if ((time() - startTime) % 4) > 3.9:
         if data['status'] == "downloading":
             eta = data.get('eta')
             speed = data.get('speed')
             if not (eta and speed):
                 return
             out = "**Speed** >> {}/s\n**ETA** >> {}\n".format(humanbytes(speed), time_formatter(eta))
             out += f'**File Name** >> `{data["filename"]}`\n\n'
             current = data.get('downloaded_bytes')
             total = data.get("total_bytes")
             if current and total:
                 percentage = int(current) * 100 / int(total)
                 out += f"Progress >> {int(percentage)}%\n"
                 out += "[{}{}]".format(''.join(["█" for _ in range(floor(percentage / 5))]),
                                        ''.join(["░" for _ in range(20 - floor(percentage / 5))]))
             if message.text != out:
                 asyncio.get_event_loop().run_until_complete(message.edit(out))
Exemple #12
0
 def _move(self, file_id: str) -> str:
     previous_parents = ",".join(self._service.files().get(
         fileId=file_id, fields='parents', supportsTeamDrives=True).execute()['parents'])
     drive_file = self._service.files().update(fileId=file_id,
                                               addParents=self._parent_id,
                                               removeParents=previous_parents,
                                               fields="id, name, mimeType, size, parents",
                                               supportsTeamDrives=True).execute()
     _LOG.info("Moved file : %s => "
               "from : %s to : {drive_file['parents']} in Google-Drive",
               file_id, previous_parents)
     mime_type = drive_file['mimeType']
     file_name = drive_file['name']
     file_id = drive_file['id']
     if mime_type == G_DRIVE_DIR_MIME_TYPE:
         return G_DRIVE_FOLDER_LINK.format(file_id, file_name)
     file_size = humanbytes(int(drive_file.get('size', 0)))
     return G_DRIVE_FILE_LINK.format(file_id, file_name, file_size)
Exemple #13
0
 def _get_output(self, file_id: str) -> str:
     file_ = self._service.files().get(
         fileId=file_id, fields="id, name, size, mimeType", supportsTeamDrives=True).execute()
     file_id = file_.get('id')
     file_name = file_.get('name')
     file_size = humanbytes(int(file_.get('size', 0)))
     mime_type = file_.get('mimeType')
     if mime_type == G_DRIVE_DIR_MIME_TYPE:
         out = G_DRIVE_FOLDER_LINK.format(file_id, file_name)
     else:
         out = G_DRIVE_FILE_LINK.format(file_id, file_name, file_size)
     if Config.G_DRIVE_INDEX_LINK:
         link = os.path.join(
             Config.G_DRIVE_INDEX_LINK.rstrip('/'),
             quote(self._get_file_path(file_id, file_name)))
         if mime_type == G_DRIVE_DIR_MIME_TYPE:
             link += '/'
         out += f"\n👥 __[Shareable Link]({link})__"
     return out
Exemple #14
0
    def _copy(self, file_id: str) -> None:
        try:
            drive_file = self.__service.files().get(
                fileId=file_id,
                fields="id, name, mimeType",
                supportsTeamDrives=True).execute()

            if drive_file['mimeType'] == G_DRIVE_DIR_MIME_TYPE:
                dir_id = self.__create_drive_dir(drive_file['name'],
                                                 self._parent_id)
                self.__copy_dir(file_id, dir_id)
                ret_id = dir_id
            else:
                ret_id = self.__copy_file(file_id, self._parent_id)

            drive_file = self.__service.files().get(
                fileId=ret_id,
                fields="id, name, mimeType, size",
                supportsTeamDrives=True).execute()

            mime_type = drive_file['mimeType']
            file_name = drive_file['name']
            file_id = drive_file['id']

            if mime_type == G_DRIVE_DIR_MIME_TYPE:
                self.__output = G_DRIVE_FOLDER_LINK.format(file_id, file_name)
            else:
                file_size = humanbytes(int(drive_file.get('size', 0)))
                self.__output = G_DRIVE_FILE_LINK.format(
                    file_id, file_name, file_size)

        except HttpError as h_e:
            LOG.exception(h_e)
            self.__output = h_e

        except ProcessCanceled:
            self.__output = "`Process Canceled!`"

        finally:
            self.__finish()
Exemple #15
0
def cm_ru(url: str) -> str:
    """cloud.mail.ru direct links generator
    Using https://github.com/JrMasterModelBuilder/cmrudl.py"""
    reply = ''
    try:
        link = re.findall(r'\bhttps?://.*cloud\.mail\.ru\S+', url)[0]
    except IndexError:
        reply = "`No cloud.mail.ru links found`\n"
        return reply
    command = f'bin/cmrudl -s {link}'
    result = popen(command).read()  # nosec
    result = result.splitlines()[-1]
    try:
        data = json.loads(result)
    except json.decoder.JSONDecodeError:
        reply += "`Error: Can't extract the link`\n"
        return reply
    dl_url = data['download']
    name = data['file_name']
    size = humanbytes(int(data['file_size']))
    reply += f'[{name} ({size})]({dl_url})\n'
    return reply
Exemple #16
0
 def __progress(data: dict):
     nonlocal edited, c_time
     diff = time() - c_time
     if data["status"] == "downloading" and (
         not edited or diff >= Config.EDIT_SLEEP_TIMEOUT
     ):
         c_time = time()
         edited = True
         eta = data.get("eta")
         speed = data.get("speed")
         if not (eta and speed):
             return
         out = "**Speed** >> {}/s\n**ETA** : {}\n".format(
             humanbytes(speed), time_formatter(eta)
         )
         out += f'**File Name** : `{data["filename"]}`\n\n'
         current = data.get("downloaded_bytes")
         total = data.get("total_bytes")
         if current and total:
             percentage = int(current) * 100 / int(total)
             out += f"Progress : {int(percentage)}%\n"
             out += "[{}{}]".format(
                 "".join(
                     (
                         Config.FINISHED_PROGRESS_STR
                         for _ in range(floor(percentage / 5))
                     )
                 ),
                 "".join(
                     (
                         Config.UNFINISHED_PROGRESS_STR
                         for _ in range(20 - floor(percentage / 5))
                     )
                 ),
             )
         userge.loop.create_task(message.edit(out))
Exemple #17
0
 def _upload_file(self, file_path: str, parent_id: str) -> str:
     if self._is_canceled:
         raise ProcessCanceled
     mime_type = guess_type(file_path)[0] or "text/plain"
     file_name = os.path.basename(file_path)
     file_size = os.path.getsize(file_path)
     body = {"name": file_name, "mimeType": mime_type, "description": "Uploaded using Userge"}
     if parent_id:
         body["parents"] = [parent_id]
     if file_size == 0:
         media_body = MediaFileUpload(file_path, mimetype=mime_type, resumable=False)
         u_file_obj = self._service.files().create(body=body, media_body=media_body,
                                                   supportsTeamDrives=True).execute()
         file_id = u_file_obj.get("id")
     else:
         media_body = MediaFileUpload(file_path, mimetype=mime_type,
                                      chunksize=50*1024*1024, resumable=True)
         u_file_obj = self._service.files().create(body=body, media_body=media_body,
                                                   supportsTeamDrives=True)
         c_time = time.time()
         response = None
         while response is None:
             status, response = u_file_obj.next_chunk(num_retries=5)
             if self._is_canceled:
                 raise ProcessCanceled
             if status:
                 f_size = status.total_size
                 diff = time.time() - c_time
                 uploaded = status.resumable_progress
                 percentage = uploaded / f_size * 100
                 speed = round(uploaded / diff, 2)
                 eta = round((f_size - uploaded) / speed)
                 tmp = \
                     "__Uploading to GDrive...__\n" + \
                     "```[{}{}]({}%)```\n" + \
                     "**File Name** : `{}`\n" + \
                     "**File Size** : `{}`\n" + \
                     "**Uploaded** : `{}`\n" + \
                     "**Completed** : `{}/{}`\n" + \
                     "**Speed** : `{}/s`\n" + \
                     "**ETA** : `{}`"
                 self._progress = tmp.format(
                     "".join((Config.FINISHED_PROGRESS_STR
                              for i in range(math.floor(percentage / 5)))),
                     "".join((Config.UNFINISHED_PROGRESS_STR
                              for i in range(20 - math.floor(percentage / 5)))),
                     round(percentage, 2),
                     file_name,
                     humanbytes(f_size),
                     humanbytes(uploaded),
                     self._completed,
                     self._list,
                     humanbytes(speed),
                     time_formatter(eta))
         file_id = response.get("id")
     if not Config.G_DRIVE_IS_TD:
         self._set_permission(file_id)
     self._completed += 1
     _LOG.info(
         "Created Google-Drive File => Name: %s ID: %s Size: %s", file_name, file_id, file_size)
     return file_id
Exemple #18
0
async def uploadtotg(message: Message):
    """ upload to telegram """
    path_ = message.filtered_input_str
    if not path_:
        await message.edit("invalid input!, check `.help .upload`", del_in=5)
        return
    is_url = re.search(r"(?:https?|ftp)://[^|\s]+\.[^|\s]+", path_)
    del_path = False
    if is_url:
        del_path = True
        await message.edit("`Downloading From URL...`")
        url = is_url[0]
        file_name = unquote_plus(os.path.basename(url))
        if "|" in path_:
            file_name = path_.split("|")[1].strip()
        path_ = os.path.join(Config.DOWN_PATH, file_name)
        try:
            downloader = SmartDL(url, path_, progress_bar=False)
            downloader.start(blocking=False)
            count = 0
            while not downloader.isFinished():
                if message.process_is_canceled:
                    downloader.stop()
                    raise Exception('Process Canceled!')
                total_length = downloader.filesize or 0
                downloaded = downloader.get_dl_size()
                percentage = downloader.get_progress() * 100
                speed = downloader.get_speed(human=True)
                estimated_total_time = downloader.get_eta(human=True)
                progress_str = \
                    "__{}__\n" + \
                    "```[{}{}]```\n" + \
                    "**Progress** : `{}%`\n" + \
                    "**URL** : `{}`\n" + \
                    "**FILENAME** : `{}`\n" + \
                    "**Completed** : `{}`\n" + \
                    "**Total** : `{}`\n" + \
                    "**Speed** : `{}`\n" + \
                    "**ETA** : `{}`"
                progress_str = progress_str.format(
                    "trying to download",
                    ''.join((Config.FINISHED_PROGRESS_STR
                             for i in range(math.floor(percentage / 5)))),
                    ''.join((Config.UNFINISHED_PROGRESS_STR
                             for i in range(20 - math.floor(percentage / 5)))),
                    round(percentage, 2),
                    url,
                    file_name,
                    humanbytes(downloaded),
                    humanbytes(total_length),
                    speed,
                    estimated_total_time)
                count += 1
                if count >= Config.EDIT_SLEEP_TIMEOUT:
                    count = 0
                    await message.try_to_edit(progress_str, disable_web_page_preview=True)
                await asyncio.sleep(1)
        except Exception as d_e:  # pylint: disable=broad-except
            await message.err(d_e)
            return
    if "|" in path_:
        path_, file_name = path_.split("|")
        path_ = path_.strip()
        if os.path.isfile(path_):
            new_path = os.path.join(Config.DOWN_PATH, file_name.strip())
            os.rename(path_, new_path)
            path_ = new_path
    try:
        string = Path(path_)
    except IndexError:
        await message.edit("wrong syntax\n`.upload [path]`")
    else:
        await message.delete()
        await upload_path(message, string, del_path)
Exemple #19
0
async def combine_(message: Message) -> None:
    """combine"""

    file_path = message.input_str
    if not file_path:
        await message.err("missing file path!")
        return

    if not isfile(file_path):
        await message.err("file path not exists!")
        return

    _, ext = splitext(basename(file_path))

    if not ext.lstrip('.').isdigit():
        await message.err("unsupported file!")
        return

    await message.edit("`processing...`")

    start_t = datetime.now()
    c_obj = SCLib(file_path)
    c_obj.combine()

    tmp = \
        "__Combining file path...__\n" + \
        "```{}({}%)```\n" + \
        "**File Path** : `{}`\n" + \
        "**Dest** : `{}`\n" + \
        "**Completed** : `{}`\n" + \
        "**Total** : `{}`\n" + \
        "**Speed** : `{}/s`\n" + \
        "**ETA** : `{}`\n" + \
        "**Completed Files** : `{}/{}`"

    while not c_obj.finished:
        if message.process_is_canceled:
            c_obj.cancel()

        await message.try_to_edit(tmp.format(c_obj.progress,
                                             c_obj.percentage,
                                             file_path,
                                             c_obj.final_file_path,
                                             humanbytes(c_obj.completed),
                                             humanbytes(c_obj.total),
                                             humanbytes(c_obj.speed),
                                             c_obj.eta,
                                             c_obj.completed_files,
                                             c_obj.total_files))

        await sleep(3)

    if c_obj.output:
        await message.err(c_obj.output)

    else:
        end_t = datetime.now()
        m_s = (end_t - start_t).seconds
        await message.edit(
            f"**combined** `{file_path}` into `{c_obj.final_file_path}` "
            f"in `{m_s}` seconds.", log=True)
Exemple #20
0
async def down_load_media(message: Message):
    await message.edit("`Trying to Download...`")
    if message.reply_to_message and message.reply_to_message.media:
        start_t = datetime.now()
        dl_loc = await message.client.download_media(
            message=message.reply_to_message,
            file_name=Config.DOWN_PATH,
            progress=progress,
            progress_args=(message, "trying to download"))
        if message.process_is_canceled:
            await message.edit("`Process Canceled!`", del_in=5)
        else:
            dl_loc = os.path.join(Config.DOWN_PATH, os.path.basename(dl_loc))
            end_t = datetime.now()
            m_s = (end_t - start_t).seconds
            await message.edit(f"Downloaded to `{dl_loc}` in {m_s} seconds")
    elif message.input_str:
        start_t = datetime.now()
        url = message.input_str
        custom_file_name = unquote_plus(os.path.basename(url))
        if "|" in url:
            url, custom_file_name = url.split("|")
            url = url.strip()
            custom_file_name = custom_file_name.strip()
        download_file_path = os.path.join(Config.DOWN_PATH, custom_file_name)
        try:
            downloader = SmartDL(url, download_file_path, progress_bar=False)
            downloader.start(blocking=False)
            count = 0
            while not downloader.isFinished():
                if message.process_is_canceled:
                    downloader.stop()
                    raise Exception('Process Canceled!')
                total_length = downloader.filesize if downloader.filesize else 0
                downloaded = downloader.get_dl_size()
                percentage = downloader.get_progress() * 100
                speed = downloader.get_speed(human=True)
                estimated_total_time = downloader.get_eta(human=True)
                progress_str = \
                    "__{}__\n" + \
                    "```[{}{}]```\n" + \
                    "**Progress** : `{}%`\n" + \
                    "**URL** : `{}`\n" + \
                    "**FILENAME** : `{}`\n" + \
                    "**Completed** : `{}`\n" + \
                    "**Total** : `{}`\n" + \
                    "**Speed** : `{}`\n" + \
                    "**ETA** : `{}`"
                progress_str = progress_str.format(
                    "trying to download", ''.join(
                        (Config.FINISHED_PROGRESS_STR
                         for i in range(math.floor(percentage / 5)))),
                    ''.join((Config.UNFINISHED_PROGRESS_STR
                             for i in range(20 - math.floor(percentage / 5)))),
                    round(percentage,
                          2), url, custom_file_name, humanbytes(downloaded),
                    humanbytes(total_length), speed, estimated_total_time)
                count += 1
                if count >= Config.EDIT_SLEEP_TIMEOUT:
                    count = 0
                    await message.try_to_edit(progress_str,
                                              disable_web_page_preview=True)
                await asyncio.sleep(1)
        except Exception as e:
            await message.err(e)
        else:
            end_t = datetime.now()
            m_s = (end_t - start_t).seconds
            await message.edit(
                f"Downloaded to `{download_file_path}` in {m_s} seconds")
    else:
        await message.edit("Please read `.help download`", del_in=5)
Exemple #21
0
async def see_info(message: Message):
    cmd_str = message.input_str
    if not cmd_str:
        return await message.err("Provide a Valid Command to Search", del_in=5)
    word = None
    if ";" in cmd_str:
        cmd_str, word = cmd_str.split(";", 1)
    cmd_str = cmd_str.strip()
    other_trigger = [".", Config.SUDO_TRIGGER]
    cmd_list = list(userge.manager.commands)
    found = True
    if not (cmd_str.startswith(Config.CMD_TRIGGER) and (cmd_str in cmd_list)):
        found = False
        for character in other_trigger:
            if cmd_str.startswith(character) and (
                cmd_str.replace(character, Config.CMD_TRIGGER) in cmd_list
            ):
                cmd_str = cmd_str.replace(character, Config.CMD_TRIGGER)
                found = True
                break
        if cmd_str.isalpha() and (Config.CMD_TRIGGER + cmd_str) in cmd_list:
            found = True
            cmd_str = Config.CMD_TRIGGER + cmd_str
    if not found:
        return await message.err("provide a valid command name", del_in=5)
    repo = Repo()
    branch = repo.active_branch.name
    if branch == "master":
        branch = "alpha"
    plugin_name = userge.manager.commands[cmd_str].plugin_name
    plugin_loc = ("/" + userge.manager.plugins[plugin_name].parent).replace(
        "/plugins", ""
    )
    if plugin_loc == "/unofficial":
        unofficial_repo = (
            "https://github.com/ashwinstr/Userge-Plugins/blob/master/plugins/"
        )
        plugin_link = f"{unofficial_repo}/{plugin_name}.py"
    elif plugin_loc == "/temp":
        plugin_link = False
    else:
        plugin_link = "{}/blob/{}/userge/plugins{}/{}.py".format(
            Config.UPSTREAM_REPO, branch, plugin_loc, plugin_name
        )
    local_path = f"userge/plugins{plugin_loc}/{plugin_name}.py"
    f_size = humanbytes(os.stat(local_path).st_size)
    search_path = count_lines(local_path, word)
    result = f"""
<b>•>  CMD:</b>  <code>{cmd_str}</code>

📂  <b>Path :</b>  <code>{local_path}</code><pre>
  - Size on Disk: {f_size}
  - No. of lines: {search_path[0]}</pre>
"""
    if plugin_link:
        result += f"\n💻  <b>[View Code on Github]({plugin_link})</b>"
    if word:
        result += f"\n\n🔎  <b>Matches for:</b> {word}\n"
        s_result = ""
        if len(search_path[1]) == 0:
            s_result += "  ❌  Not Found !"
        else:
            line_c = 0
            for line in search_path[1]:
                line_c += 1
                s_result += f"[#L{line}]({plugin_link}#L{line})  "
                if line_c >= 8:
                    break
        result += "  <b>{}</b>".format(s_result)
    await message.edit(result, disable_web_page_preview=True)
async def labstack(message: Message):
    await message.edit("Initiating...")
    if not os.path.isdir(Config.DOWN_PATH):
        os.mkdir(Config.DOWN_PATH)

    path_ = message.filtered_input_str
    dl_loc = ""
    if path_:
        is_url = re.search(r"(?:https?|ftp)://[^|\s]+\.[^|\s]+", path_)
        if is_url:
            await message.edit("`Downloading From URL...`")
            if not os.path.isdir(Config.DOWN_PATH):
                os.mkdir(Config.DOWN_PATH)
            url = is_url[0]
            file_name = unquote_plus(os.path.basename(url))
            if "|" in path_:
                file_name = path_.split("|")[1].strip()
            path_ = os.path.join(Config.DOWN_PATH, file_name)
            dl_loc = path_
            try:
                downloader = SmartDL(url, path_, progress_bar=False)
                downloader.start(blocking=False)
                count = 0
                while not downloader.isFinished():
                    if message.process_is_canceled:
                        downloader.stop()
                        raise Exception("Process Cancelled!")
                    total_length = downloader.filesize or 0
                    downloaded = downloader.get_dl_size()
                    percentage = downloader.get_progress() * 100
                    speed = downloader.get_speed(human=True)
                    estimated_total_time = downloader.get_eta(human=True)
                    progress_str = ("__{}__\n" + "```[{}{}]```\n" +
                                    "**Progress** : `{}%`\n" +
                                    "**URL** : `{}`\n" +
                                    "**FILENAME** : `{}`\n" +
                                    "**Completed** : `{}`\n" +
                                    "**Total** : `{}`\n" +
                                    "**Speed** : `{}`\n" + "**ETA** : `{}`")
                    progress_str = progress_str.format(
                        "Downloading",
                        "".join((Config.FINISHED_PROGRESS_STR
                                 for i in range(math.floor(percentage / 5)))),
                        "".join(
                            (Config.UNFINISHED_PROGRESS_STR
                             for i in range(20 - math.floor(percentage / 5)))),
                        round(percentage, 2),
                        url,
                        file_name,
                        humanbytes(downloaded),
                        humanbytes(total_length),
                        speed,
                        estimated_total_time,
                    )
                    count += 1
                    if count >= 5:
                        count = 0
                        await message.try_to_edit(
                            progress_str, disable_web_page_preview=True)
                    await asyncio.sleep(1)
            except Exception as d_e:
                await message.err(d_e)
                return
        if "|" in path_:
            path_, file_name = path_.split("|")
            path_ = path_.strip()
            if os.path.isfile(path_):
                new_path = os.path.join(Config.DOWN_PATH, file_name.strip())
                os.rename(path_, new_path)
                dl_loc = new_path

    if message.reply_to_message and message.reply_to_message.media:
        dl_loc = await message.client.download_media(
            message=message.reply_to_message,
            file_name=Config.DOWN_PATH,
            progress=progress,
            progress_args=(message, "Downloading"),
        )

    filesize = os.path.getsize(dl_loc)
    filename = os.path.basename(dl_loc)

    file = {"name": filename, "type": "", "size": int(filesize)}
    user_id = "".join(
        random.choice(string.ascii_lowercase + string.ascii_uppercase +
                      string.digits) for _ in range(16))
    data = {"ttl": 604800, "files": [file]}
    headers = {
        "up-user-id":
        user_id,
        "User-Agent":
        "Mozilla/5.0 (X11; Linux x86_64)"
        "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36",
    }
    r = requests.post("https://up.labstack.com/api/v1/links",
                      json=data,
                      headers=headers).json()

    files = {
        "files": (filename, open(dl_loc, "rb")),
    }
    send_url = "https://up.labstack.com/api/v1/links/{}/send".format(r["code"])
    response = requests.post(send_url, headers=headers, files=files)
    if (response.status_code) == 200:
        link = "https://up.labstack.com/api/v1/links/{}/receive".format(
            r["code"])
        await message.edit(f"**Filename**: `{filename}`\n**Size**: "
                           f"`{humanbytes(filesize)}`\n\n"
                           f"**Link**: {link}\n`Expires in 7 Days`")
    else:
        await message.edit("Request Failed!", del_in=5)
Exemple #23
0
    async def upload(self) -> None:
        """
        Upload from file/folder/link/tg file to GDrive.
        """

        if not os.path.isdir(Config.DOWN_PATH):
            os.mkdir(Config.DOWN_PATH)

        replied = self.__message.reply_to_message
        is_url = re.search(r"(?:https?|ftp):\/\/[\w/\-?=%.]+\.[\w/\-?=%.]+",
                           self.__message.input_str)
        dl_loc = None

        if replied and replied.media:
            await self.__message.edit("`Downloading From TG...`")
            c_time = time.time()

            dl_loc = await userge.download_media(
                message=replied,
                file_name=Config.DOWN_PATH,
                progress=progress,
                progress_args=("trying to download", userge, self.__message,
                               c_time))

            if self.__message.process_is_canceled:
                await self.__message.edit("`Process Canceled!`", del_in=5)
                return

            else:
                dl_loc = os.path.join(Config.DOWN_PATH,
                                      os.path.basename(dl_loc))

        elif is_url:
            await self.__message.edit("`Downloading From URL...`")

            is_url = is_url[0]
            file_name = os.path.basename(is_url)
            dl_loc = os.path.join(Config.DOWN_PATH, file_name)

            try:
                downloader = SmartDL(is_url, dl_loc, progress_bar=False)
                downloader.start(blocking=False)

                while not downloader.isFinished():
                    if self.__message.process_is_canceled:
                        downloader.stop()
                        raise Exception('Process Canceled!')

                    total_length = downloader.filesize if downloader.filesize else 0
                    downloaded = downloader.get_dl_size()
                    percentage = downloader.get_progress() * 100
                    speed = downloader.get_speed(human=True)
                    estimated_total_time = downloader.get_eta(human=True)

                    progress_str = \
                        "__{}__\n" + \
                        "```[{}{}]```\n" + \
                        "**Progress** : `{}%`\n" + \
                        "**URL** : `{}`\n" + \
                        "**FILENAME** : `{}`\n" + \
                        "**Completed** : `{}`\n" + \
                        "**Total** : `{}`\n" + \
                        "**Speed** : `{}`\n" + \
                        "**ETA** : `{}`"

                    progress_str = progress_str.format(
                        "trying to download", ''.join([
                            "█" for i in range(math.floor(percentage / 5))
                        ]), ''.join([
                            "░" for i in range(20 - math.floor(percentage / 5))
                        ]), round(percentage, 2), is_url, file_name,
                        humanbytes(downloaded), humanbytes(total_length),
                        speed, estimated_total_time)

                    await self.__message.try_to_edit(
                        text=progress_str, disable_web_page_preview=True)

                    await asyncio.sleep(3)

            except Exception as d_e:
                await self.__message.err(d_e)
                return

        upload_file_name = dl_loc if dl_loc else self.__message.input_str

        if not os.path.exists(upload_file_name):
            await self.__message.err("invalid file path provided?")
            return

        await self.__message.edit("`Loading GDrive Upload...`")

        Thread(target=self._upload, args=(upload_file_name, )).start()
        start_t = datetime.now()

        while not self._is_finished:
            if self.__message.process_is_canceled:
                self._cancel()

            if self._progress is not None:
                await self.__message.try_to_edit(self._progress)

            await asyncio.sleep(3)

        if dl_loc and os.path.exists(dl_loc):
            os.remove(dl_loc)

        end_t = datetime.now()
        m_s = (end_t - start_t).seconds

        if isinstance(self._output, HttpError):
            out = f"**ERROR** : `{self._output._get_reason()}`"

        elif self._output is not None and not self._is_canceled:
            out = f"**Uploaded Successfully** __in {m_s} seconds__\n\n{self._output}"

        elif self._output is not None and self._is_canceled:
            out = self._output

        else:
            out = "`failed to upload.. check logs?`"

        await self.__message.edit(out, disable_web_page_preview=True, log=True)
Exemple #24
0
async def url_download(message: Message, url: str) -> Tuple[str, int]:
    """ download from link """
    pattern = r"^(?:(?:https|tg):\/\/)?(?:www\.)?(?:t\.me\/|openmessage\?)(?:(?:c\/(\d+))|(\w+)|(?:user_id\=(\d+)))(?:\/|&message_id\=)(\d+)(\?single)?$"  # noqa
    # group 1: private supergroup id, group 2: chat username,
    # group 3: private group/chat id, group 4: message id
    # group 5: check for download single media from media group
    match = re.search(pattern, url.split('|', 1)[0].strip())
    if match:
        chat_id = None
        msg_id = int(match.group(4))
        if match.group(1):
            chat_id = int("-100" + match.group(1))
        elif match.group(2):
            chat_id = match.group(2)
        elif match.group(3):
            chat_id = int(match.group(3))
        if chat_id and msg_id:
            resource = await message.client.get_messages(chat_id, msg_id)
            if resource.media_group_id and not bool(match.group(5)):
                output = await handle_download(message, resource, True)
            elif resource.media:
                output = await tg_download(message, resource, True)
            else:
                raise Exception("given tg link doesn't have any media")
            return output
        raise Exception("invalid telegram message link!")
    await message.edit("`Downloading From URL...`")
    start_t = datetime.now()
    custom_file_name = unquote_plus(os.path.basename(url))
    if "|" in url:
        url, c_file_name = url.split("|", maxsplit=1)
        url = url.strip()
        if c_file_name:
            custom_file_name = c_file_name.strip()
    dl_loc = os.path.join(config.Dynamic.DOWN_PATH, custom_file_name)
    downloader = SmartDL(url, dl_loc, progress_bar=False)
    downloader.start(blocking=False)
    with message.cancel_callback(downloader.stop):
        while not downloader.isFinished():
            total_length = downloader.filesize if downloader.filesize else 0
            downloaded = downloader.get_dl_size()
            percentage = downloader.get_progress() * 100
            speed = downloader.get_speed(human=True)
            estimated_total_time = downloader.get_eta(human=True)
            progress_str = \
                "__{}__\n" + \
                "```[{}{}]```\n" + \
                "**Progress** : `{}%`\n" + \
                "**URL** : `{}`\n" + \
                "**FILENAME** : `{}`\n" + \
                "**Completed** : `{}`\n" + \
                "**Total** : `{}`\n" + \
                "**Speed** : `{}`\n" + \
                "**ETA** : `{}`"
            progress_str = progress_str.format(
                "trying to download", ''.join(
                    (config.FINISHED_PROGRESS_STR
                     for _ in range(math.floor(percentage / 5)))), ''.join(
                         (config.UNFINISHED_PROGRESS_STR
                          for _ in range(20 - math.floor(percentage / 5)))),
                round(percentage, 2), url, custom_file_name,
                humanbytes(downloaded), humanbytes(total_length), speed,
                estimated_total_time)
            await message.edit(progress_str, disable_web_page_preview=True)
            await asyncio.sleep(config.Dynamic.EDIT_SLEEP_TIMEOUT)
    if message.process_is_canceled:
        raise ProcessCanceled
    return dl_loc, (datetime.now() - start_t).seconds
Exemple #25
0
def download_button(vid: str, body: bool = False):
    try:
        vid_data = youtube_dl.YoutubeDL({
            "no-playlist": True
        }).extract_info(BASE_YT_URL + vid, download=False)
    except ExtractorError:
        vid_data = {"formats": []}
    buttons = [[
        InlineKeyboardButton("⭐️ BEST - 📹 MKV",
                             callback_data=f"ytdl_download_{vid}_mkv_v"),
        InlineKeyboardButton(
            "⭐️ BEST - 📹 WebM/MP4",
            callback_data=f"ytdl_download_{vid}_mp4_v",
        ),
    ]]
    # ------------------------------------------------ #
    qual_dict = defaultdict(lambda: defaultdict(int))
    qual_list = ["144p", "240p", "360p", "480p", "720p", "1080p", "1440p"]
    audio_dict = {}
    # ------------------------------------------------ #
    for video in vid_data["formats"]:

        fr_note = video.get("format_note")
        fr_id = int(video.get("format_id"))
        fr_size = video.get("filesize")
        if video.get("ext") == "mp4":
            for frmt_ in qual_list:
                if fr_note in (frmt_, frmt_ + "60"):
                    qual_dict[frmt_][fr_id] = fr_size
        if video.get("acodec") != "none":
            bitrrate = int(video.get("abr", 0))
            if bitrrate != 0:
                audio_dict[
                    bitrrate] = f"🎵 {bitrrate}Kbps ({humanbytes(fr_size) or 'N/A'})"

    video_btns = []
    for frmt in qual_list:
        frmt_dict = qual_dict[frmt]
        if len(frmt_dict) != 0:
            frmt_id = sorted(list(frmt_dict))[-1]
            frmt_size = humanbytes(frmt_dict.get(frmt_id)) or "N/A"
            video_btns.append(
                InlineKeyboardButton(
                    f"📹 {frmt} ({frmt_size})",
                    callback_data=f"ytdl_download_{vid}_{frmt_id}_v",
                ))
    buttons += sublists(video_btns, width=2)
    buttons += [[
        InlineKeyboardButton("⭐️ BEST - 🎵 320Kbps - MP3",
                             callback_data=f"ytdl_download_{vid}_mp3_a")
    ]]
    buttons += sublists(
        [
            InlineKeyboardButton(audio_dict.get(key_),
                                 callback_data=f"ytdl_download_{vid}_{key_}_a")
            for key_ in sorted(audio_dict.keys())
        ],
        width=2,
    )
    if body:
        vid_body = f"<b>[{vid_data.get('title')}]({vid_data.get('webpage_url')})</b>"
        return vid_body, InlineKeyboardMarkup(buttons)
    return InlineKeyboardMarkup(buttons)
Exemple #26
0
async def see_info(message: Message):
    cmd_str = message.input_str
    if not cmd_str:
        return await message.err("Provide a Valid Command to Search", del_in=5)
    word = None
    if "|" in cmd_str:
        cmd_str, word = cmd_str.split("|", 1)
    cmd_str = cmd_str.strip()
    other_trigger = [".", Config.SUDO_TRIGGER]
    cmd_list = list(userge.manager.commands)
    found = True
    if not (cmd_str.startswith(Config.CMD_TRIGGER) and (cmd_str in cmd_list)):
        found = False
        for character in other_trigger:
            if cmd_str.startswith(character) and (cmd_str.replace(
                    character, Config.CMD_TRIGGER) in cmd_list):
                cmd_str = cmd_str.replace(character, Config.CMD_TRIGGER)
                found = True
                break
        if cmd_str.isalpha() and (Config.CMD_TRIGGER + cmd_str) in cmd_list:
            found = True
            cmd_str = Config.CMD_TRIGGER + cmd_str
    if not found:
        return await message.err("provide a valid command name", del_in=5)
    repo = Repo()
    try:
        branch = repo.active_branch.name
    except Exception:
        with open(".git/HEAD", "r") as gitfile:
            branch = gitfile.read().split("/")[-1].strip()
    if branch == "master":
        branch = "alpha"
    plugin_name = userge.manager.commands[cmd_str].plugin_name
    plugin_loc = ("/" + userge.manager.plugins[plugin_name].parent).replace(
        "/plugins", "")
    if plugin_loc == "/xtra":
        extra_plugins = (
            "https://github.com/code-rgb/Userge-Plugins/blob/master/plugins/")
        plugin_link = f"{extra_plugins}/{plugin_name}.py"
    elif plugin_loc == "/custom":
        custom_plugins = (os.environ.get("CUSTOM_PLUGINS_REPO")
                          or "" + "/blob/main/plugins")
        plugin_link = f"{custom_plugins}/{plugin_name}.py"
    elif plugin_loc == "/temp":
        plugin_link = False
    else:
        plugin_link = "{}/blob/{}/userge/plugins{}/{}.py".format(
            Config.UPSTREAM_REPO, branch, plugin_loc, plugin_name)
    local_path = f"userge/plugins{plugin_loc}/{plugin_name}.py"
    f_size = humanbytes(os.stat(local_path).st_size)
    search_path = count_lines(local_path, word)
    result = f"""
<b>•>  CMD:</b>  <code>{cmd_str}</code>

📂  <b>Path :</b>  <code>{local_path}</code><pre>
  - Size on Disk: {f_size}
  - No. of lines: {search_path[0]}</pre>
"""
    if plugin_link:
        result += f"\n💻  <b>[View Code on Github]({plugin_link})</b>"
    if word:
        result += f"\n\n🔎  <b>Matches for:</b> {word}\n"
        s_result = ""
        if len(search_path[1]) == 0:
            s_result += "  ❌  Not Found !"
        else:
            for line_c, line in enumerate(search_path[1], start=1):
                s_result += f"[#L{line}]({plugin_link}#L{line})  "
                if line_c >= 8:
                    break
        result += "  <b>{}</b>".format(s_result)
    await message.edit(result, disable_web_page_preview=True)
Exemple #27
0
 async def upload(self) -> None:
     """ Upload from file/folder/link/tg file to GDrive """
     replied = self._message.reply_to_message
     is_url = re.search(
         r"(?:https?|ftp)://[^\|\s]+\.[^\|\s]+", self._message.input_str)
     dl_loc = None
     if replied and replied.media:
         await self._message.edit("`Downloading From TG...`")
         file_name = Config.DOWN_PATH
         if self._message.input_str:
             file_name = os.path.join(Config.DOWN_PATH, self._message.input_str)
         dl_loc = await self._message.client.download_media(
             message=replied,
             file_name=file_name,
             progress=progress,
             progress_args=(self._message, "trying to download")
         )
         if self._message.process_is_canceled:
             await self._message.edit("`Process Canceled!`", del_in=5)
             return
         dl_loc = os.path.join(Config.DOWN_PATH, os.path.basename(dl_loc))
     elif is_url:
         await self._message.edit("`Downloading From URL...`")
         url = is_url[0]
         file_name = unquote_plus(os.path.basename(url))
         if "|" in self._message.input_str:
             file_name = self._message.input_str.split("|")[1].strip()
         dl_loc = os.path.join(Config.DOWN_PATH, file_name)
         try:
             downloader = SmartDL(url, dl_loc, progress_bar=False)
             downloader.start(blocking=False)
             count = 0
             while not downloader.isFinished():
                 if self._message.process_is_canceled:
                     downloader.stop()
                     raise Exception('Process Canceled!')
                 total_length = downloader.filesize if downloader.filesize else 0
                 downloaded = downloader.get_dl_size()
                 percentage = downloader.get_progress() * 100
                 speed = downloader.get_speed(human=True)
                 estimated_total_time = downloader.get_eta(human=True)
                 progress_str = \
                     "__{}__\n" + \
                     "```[{}{}]```\n" + \
                     "**Progress** : `{}%`\n" + \
                     "**URL** : `{}`\n" + \
                     "**FILENAME** : `{}`\n" + \
                     "**Completed** : `{}`\n" + \
                     "**Total** : `{}`\n" + \
                     "**Speed** : `{}`\n" + \
                     "**ETA** : `{}`"
                 progress_str = progress_str.format(
                     "trying to download",
                     ''.join((Config.FINISHED_PROGRESS_STR
                              for i in range(math.floor(percentage / 5)))),
                     ''.join((Config.UNFINISHED_PROGRESS_STR
                              for i in range(20 - math.floor(percentage / 5)))),
                     round(percentage, 2),
                     url,
                     file_name,
                     humanbytes(downloaded),
                     humanbytes(total_length),
                     speed,
                     estimated_total_time)
                 count += 1
                 if count >= 5:
                     count = 0
                     await self._message.try_to_edit(
                         progress_str, disable_web_page_preview=True)
                 await asyncio.sleep(1)
         except Exception as d_e:
             await self._message.err(d_e)
             return
     file_path = dl_loc if dl_loc else self._message.input_str
     if not os.path.exists(file_path):
         await self._message.err("invalid file path provided?")
         return
     if "|" in file_path:
         file_path, file_name = file_path.split("|")
         new_path = os.path.join(os.path.dirname(file_path.strip()), file_name.strip())
         os.rename(file_path.strip(), new_path)
         file_path = new_path
     await self._message.edit("`Loading GDrive Upload...`")
     pool.submit_thread(self._upload, file_path)
     start_t = datetime.now()
     count = 0
     while not self._is_finished:
         count += 1
         if self._message.process_is_canceled:
             self._cancel()
         if self._progress is not None and count >= 5:
             count = 0
             await self._message.try_to_edit(self._progress)
         await asyncio.sleep(1)
     if dl_loc and os.path.exists(dl_loc):
         os.remove(dl_loc)
     end_t = datetime.now()
     m_s = (end_t - start_t).seconds
     if isinstance(self._output, HttpError):
         out = f"**ERROR** : `{self._output._get_reason()}`"  # pylint: disable=protected-access
     elif self._output is not None and not self._is_canceled:
         out = f"**Uploaded Successfully** __in {m_s} seconds__\n\n{self._output}"
     elif self._output is not None and self._is_canceled:
         out = self._output
     else:
         out = "`failed to upload.. check logs?`"
     await self._message.edit(out, disable_web_page_preview=True, log=__name__)
Exemple #28
0
async def down_load_media(message: Message):
    await message.edit("Trying to Download...")

    if not os.path.isdir(Config.DOWN_PATH):
        os.mkdir(Config.DOWN_PATH)

    if message.reply_to_message is not None:
        start_t = datetime.now()
        c_time = time.time()

        dl_loc = await userge.download_media(
            message=message.reply_to_message,
            file_name=Config.DOWN_PATH,
            progress=progress,
            progress_args=(
                "trying to download", userge, message, c_time
            )
        )
        # await userge.send_chat_action(message.chat.id, "cancel")

        if message.process_is_canceled:
            await message.edit("`Process Canceled!`", del_in=5)

        else:
            dl_loc = os.path.join(Config.DOWN_PATH, os.path.basename(dl_loc))

            end_t = datetime.now()
            ms = (end_t - start_t).seconds

            await message.edit(
                f"Downloaded to `{dl_loc}` in {ms} seconds")

    elif message.input_str:
        start_t = datetime.now()
        url = message.input_str
        custom_file_name = os.path.basename(url)

        if "|" in url:
            url, custom_file_name = url.split("|")
            url = url.strip()
            custom_file_name = custom_file_name.strip()

        download_file_path = os.path.join(Config.DOWN_PATH, custom_file_name)

        try:
            downloader = SmartDL(url, download_file_path, progress_bar=False)
            downloader.start(blocking=False)

            while not downloader.isFinished():
                if message.process_is_canceled:
                    downloader.stop()
                    raise Exception('Process Canceled!')

                total_length = downloader.filesize if downloader.filesize else 0
                downloaded = downloader.get_dl_size()
                percentage = downloader.get_progress() * 100
                speed = downloader.get_speed(human=True)
                estimated_total_time = downloader.get_eta(human=True)

                progress_str = \
                    "__{}__\n" + \
                    "```[{}{}]```\n" + \
                    "**Progress** : `{}%`\n" + \
                    "**URL** : `{}`\n" + \
                    "**FILENAME** : `{}`\n" + \
                    "**Completed** : `{}`\n" + \
                    "**Total** : `{}`\n" + \
                    "**Speed** : `{}`\n" + \
                    "**ETA** : `{}`"

                progress_str = progress_str.format(
                    "trying to download",
                    ''.join(["█" for i in range(math.floor(percentage / 5))]),
                    ''.join(["░" for i in range(20 - math.floor(percentage / 5))]),
                    round(percentage, 2),
                    url,
                    custom_file_name,
                    humanbytes(downloaded),
                    humanbytes(total_length),
                    speed,
                    estimated_total_time)

                await message.try_to_edit(
                    text=progress_str, disable_web_page_preview=True)

                await asyncio.sleep(3)

        except Exception as e:
            await message.err(e)

        else:
            end_t = datetime.now()
            ms = (end_t - start_t).seconds

            await message.edit(f"Downloaded to `{download_file_path}` in {ms} seconds")

    else:
        await message.edit(
            "Reply to a Telegram Media, to download it to local server.", del_in=3)