Exemplo n.º 1
0
def mp3_down(url: str):
    ydl_opts = {
        'outtmpl':
        os.path.join("temp_music_dir", '%(title)s.%(ext)s'),
        'prefer_ffmpeg':
        True,
        'format':
        'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '320',
        }, {
            'key': 'FFmpegMetadata'
        }]
    }

    with ytdl.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=False)

        if info.get("duration") > Config.MAX_DURATION:
            return False

        ydl.download([url])

    return info.get("title"), time_formatter(info.get("duration"))
Exemplo n.º 2
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 = "**HIZ** >> {}/s\n**Tahmini Bitiş** >> {}\n".format(
             humanbytes(speed), time_formatter(eta))
         out += f'**Dosya Adı** >> `{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"İşleniyor >> {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))
Exemplo n.º 3
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))
Exemplo n.º 4
0
 def __progress(data: dict):
     if (time() - startTime) % 4 <= 3.9:
         return
     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((Config.FINISHED_PROGRESS_STR
                          for _ in range(floor(percentage / 5)))),
                 ''.join((Config.UNFINISHED_PROGRESS_STR
                          for _ in range(20 - floor(percentage / 5)))))
         if message.text != out:
             try:
                 asyncio.get_event_loop().run_until_complete(message.edit(out))
             except TypeError:
                 pass
Exemplo n.º 5
0
async def handle_afk_incomming(message: Message) -> None:
    """handle incomming messages when you afk"""
    if not message.from_user:
        return
    user_id = message.from_user.id
    chat = message.chat
    user_dict = await message.client.get_user_dict(user_id)
    afk_time = time_formatter(round(time.time() - TIME))
    coro_list = []
    if user_id in USERS:
        if not (USERS[user_id][0] + USERS[user_id][1]) % randint(2, 4):
            if REASON:
                out_str = (
                    f"I'm still **AFK**.\nReason: <code>{REASON}</code>\n"
                    f"Last Seen: `{afk_time} ago`")
            else:
                out_str = choice(AFK_REASONS)
            coro_list.append(message.reply(out_str))
        if chat.type == "private":
            USERS[user_id][0] += 1
        else:
            USERS[user_id][1] += 1
    else:
        if REASON:
            out_str = (
                f"I'm **AFK** right now.\nReason: <code>{REASON}</code>\n"
                f"Last Seen: `{afk_time} ago`")
        else:
            out_str = choice(AFK_REASONS)
        coro_list.append(message.reply(out_str))
        if chat.type == "private":
            USERS[user_id] = [1, 0, user_dict["mention"]]
        else:
            USERS[user_id] = [0, 1, user_dict["mention"]]
    if chat.type == "private":
        coro_list.append(
            CHANNEL.log(f"#PRIVATE\n{user_dict['mention']} send you\n\n"
                        f"{message.text}"))
    else:
        coro_list.append(
            CHANNEL.log(
                "#GROUP\n"
                f"{user_dict['mention']} tagged you in [{chat.title}](http://t.me/{chat.username})\n\n"
                f"{message.text}\n\n"
                f"[goto_msg](https://t.me/c/{str(chat.id)[4:]}/{message.message_id})"
            ))
    coro_list.append(
        AFK_COLLECTION.update_one(
            {"_id": user_id},
            {
                "$set": {
                    "pcount": USERS[user_id][0],
                    "gcount": USERS[user_id][1],
                    "men": USERS[user_id][2],
                }
            },
            upsert=True,
        ))
    await asyncio.gather(*coro_list)
Exemplo n.º 6
0
async def handle_afk_incomming(message: Message) -> None:
    """ handle incomming messages when you afk """
    user_id = message.from_user.id
    chat = message.chat
    user_dict = await message.client.get_user_dict(user_id)
    afk_time = time_formatter(round(time.time() - TIME))
    coro_list = []
    if user_id in USERS:
        if not (USERS[user_id][0] + USERS[user_id][1]) % randint(2, 4):
            if REASON:
                out_str = (
                    f"Saya **OFFLINE** Sekarang.\nKarena: <code>{REASON}</code>\n"
                    f"Sejak: `{afk_time} Lalu`")
            else:
                out_str = choice(AFK_REASONS)
            coro_list.append(message.reply(out_str))
        if chat.type == 'private':
            USERS[user_id][0] += 1
        else:
            USERS[user_id][1] += 1
    else:
        if REASON:
            out_str = (
                f"Saya **OFFLINE** Sekarang.\nKarena: <code>{REASON}</code>\n"
                f"Sejak: `{afk_time} Lalu`")
        else:
            out_str = choice(AFK_REASONS)
        coro_list.append(message.reply(out_str))
        if chat.type == 'private':
            USERS[user_id] = [1, 0, user_dict['mention']]
        else:
            USERS[user_id] = [0, 1, user_dict['mention']]
    if chat.type == 'private':
        coro_list.append(
            CHANNEL.log(f"#PRIVATE\n{user_dict['mention']} send you\n\n"
                        f"{message.text}"))
    else:
        coro_list.append(
            CHANNEL.log(
                "#GROUP\n"
                f"{user_dict['mention']} tagged you in [{chat.title}](http://t.me/{chat.username})\n\n"
                f"{message.text}\n\n"
                f"[goto_msg](https://t.me/c/{str(chat.id)[4:]}/{message.message_id})"
            ))
    coro_list.append(
        AFK_COLLECTION.update_one({'_id': user_id}, {
            "$set": {
                'pcount': USERS[user_id][0],
                'gcount': USERS[user_id][1],
                'men': USERS[user_id][2]
            }
        },
                                  upsert=True))
    await asyncio.gather(*coro_list)
Exemplo n.º 7
0
async def handle_afk_incomming(message: Message):
    user_id = message.from_user.id
    chat = message.chat
    user_dict = await userge.get_user_dict(user_id)
    afk_time = time_formatter(round(time.time() - TIME))

    if user_id in USERS:
        if not (USERS[user_id][0] + USERS[user_id][1]) % randint(2, 4):
            if REASON:
                out_str = f"I'm still **AFK**.\nReason: `{REASON}`\nLast Seen: `{afk_time} ago`"
            else:
                out_str = choice(AFK_REASONS)

            await message.reply(out_str)

        if chat.type == 'private':
            USERS[user_id][0] += 1

        else:
            USERS[user_id][1] += 1

    else:
        if REASON:
            out_str = f"I'm **AFK** right now.\nReason: `{REASON}`\nLast Seen: `{afk_time} ago`"
        else:
            out_str = choice(AFK_REASONS)

        await message.reply(out_str)

        if chat.type == 'private':
            USERS[user_id] = [1, 0, user_dict['mention']]

        else:
            USERS[user_id] = [0, 1, user_dict['mention']]

    if chat.type == 'private':
        await CHANNEL.log(f"#PRIVATE\n{user_dict['mention']} send you\n\n"
                          f"{message.text}")

    else:
        await CHANNEL.log(
            "#GROUP\n"
            f"{user_dict['mention']} tagged you in [{chat.title}](http://t.me/{chat.username})\n\n"
            f"{message.text}\n\n[goto_msg](https://t.me/c/{str(chat.id)[4:]}/{message.message_id})"
        )

    AFK_COLLECTION.update_one({'_id': user_id}, {
        "$set": {
            'pcount': USERS[user_id][0],
            'gcount': USERS[user_id][1],
            'men': USERS[user_id][2]
        }
    },
                              upsert=True)
Exemplo n.º 8
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(num_retries=5)
             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"])
Exemplo n.º 9
0
async def handle_afk_outgoing(message: Message):
    global IS_AFK

    IS_AFK = False
    afk_time = time_formatter(round(time.time() - TIME))

    replied: Message = await message.reply(f"`I'm no longer AFK!`",
                                           log=__name__)

    if USERS:
        p_msg = ''
        g_msg = ''
        p_count = 0
        g_count = 0

        for pcount, gcount, men in USERS.values():
            if pcount:
                p_msg += f"👤 {men} ✉️ **{pcount}**\n"
                p_count += pcount

            if gcount:
                g_msg += f"👥 {men} ✉️ **{gcount}**\n"
                g_count += gcount

        await replied.edit(
            f"`You recieved {p_count + g_count} messages while you were away. "
            f"Check log for more details.`\n\n**AFK time** : __{afk_time}__",
            del_in=3)

        out_str = f"You've recieved **{p_count + g_count}** messages " + \
            f"from **{len(USERS)}** users while you were away!\n\n**AFK time** : __{afk_time}__\n"

        if p_count:
            out_str += f"\n**{p_count} Private Messages:**\n\n{p_msg}"

        if g_count:
            out_str += f"\n**{g_count} Group Messages:**\n\n{g_msg}"

        await CHANNEL.log(out_str)
        USERS.clear()

    else:
        await asyncio.sleep(3)
        await replied.delete()

    AFK_COLLECTION.drop()
    SAVED_SETTINGS.update_one({'_id': 'AFK'}, {"$set": {
        'on': False
    }},
                              upsert=True)
Exemplo n.º 10
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=100*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(["█" for i in range(math.floor(percentage / 5))]),
                        "".join(["░" 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: {} ID: {} ".format(name, kwargs['id']))
Exemplo n.º 11
0
async def handle_afk_outgoing(message: Message) -> None:
    """handle outgoing messages when you afk"""
    global IS_AFK  # pylint: disable=global-statement
    IS_AFK = False
    afk_time = time_formatter(round(time.time() - TIME))
    replied: Message = await message.reply("`I'm no longer AFK!`",
                                           log=__name__)
    coro_list = []
    if USERS:
        p_msg = ""
        g_msg = ""
        p_count = 0
        g_count = 0
        for pcount, gcount, men in USERS.values():
            if pcount:
                p_msg += f"👤 {men} ✉️ **{pcount}**\n"
                p_count += pcount
            if gcount:
                g_msg += f"👥 {men} ✉️ **{gcount}**\n"
                g_count += gcount
        coro_list.append(
            replied.edit(
                f"`You recieved {p_count + g_count} messages while you were away. "
                f"Check log for more details.`\n\n**AFK time** : __{afk_time}__",
                del_in=3,
            ))
        out_str = (
            f"You've recieved **{p_count + g_count}** messages " +
            f"from **{len(USERS)}** users while you were away!\n\n**AFK time** : __{afk_time}__\n"
        )
        if p_count:
            out_str += f"\n**{p_count} Private Messages:**\n\n{p_msg}"
        if g_count:
            out_str += f"\n**{g_count} Group Messages:**\n\n{g_msg}"
        coro_list.append(CHANNEL.log(out_str))
        USERS.clear()
    else:
        await asyncio.sleep(3)
        coro_list.append(replied.delete())
    coro_list.append(
        asyncio.gather(
            AFK_COLLECTION.drop(),
            SAVED_SETTINGS.update_one({"_id": "AFK"}, {"$set": {
                "on": False
            }},
                                      upsert=True),
        ))
    await asyncio.gather(*coro_list)
Exemplo n.º 12
0
async def handle_afk_outgoing(message: Message) -> None:
    """ handle outgoing messages when you afk """
    global IS_AFK  # pylint: disable=global-statement
    IS_AFK = False
    afk_time = time_formatter(round(time.time() - TIME))
    replied: Message = await message.reply("`Aing Kembali 🐨 Kangen gak?`",
                                           log=__name__)
    coro_list = []
    if USERS:
        p_msg = ""
        g_msg = ""
        p_count = 0
        g_count = 0
        for pcount, gcount, men in USERS.values():
            if pcount:
                p_msg += f"🐨 {men} ✉️ **{pcount}**\n"
                p_count += pcount
            if gcount:
                g_msg += f"🌐 {men} ✉️ **{gcount}**\n"
                g_count += gcount
        coro_list.append(
            replied.edit(
                f"`Anda Menerima Pesan {p_count + g_count} Ketika Anda Sibuk. "
                f"Check Channel Log Untuk Info Lebih Lanjut.`\n\n**Lama Sibuk** : __{afk_time}__",
                del_in=3,
            ))
        out_str = (
            f"Anda Menerima Pesan **{p_count + g_count}** Pesan " +
            f"Dari **{len(USERS)}** Ketika Anda Sibuk!\n\n**Waktu Sibuk** : __{afk_time}__\n"
        )
        if p_count:
            out_str += f"\n**{p_count} Private Messages:**\n\n{p_msg}"
        if g_count:
            out_str += f"\n**{g_count} Group Messages:**\n\n{g_msg}"
        coro_list.append(CHANNEL.log(out_str))
        USERS.clear()
    else:
        await asyncio.sleep(3)
        coro_list.append(replied.delete())
    coro_list.append(
        asyncio.gather(
            AFK_COLLECTION.drop(),
            SAVED_SETTINGS.update_one({"_id": "AFK"}, {"$set": {
                "on": False
            }},
                                      upsert=True),
        ))
    await asyncio.gather(*coro_list)
Exemplo n.º 13
0
def get_track_info(track: pylast.Track) -> Optional[str]:
    try:
        duration = time_formatter(int(track.get_duration()) / 1000)
        _tags = track.get_tags()
        tags = " ".join([f'`{i}`'
                         for i in _tags]) if len(_tags) > 0 else '`None`'
        out = f'''__LastFm's__ [{track.get_correction()}]({unquote(track.get_url())})

__Duration:__ `{duration if duration else None}`
__Is_Loved:__ `{bool(track.get_userloved())}`
__Is_Streamable:__ `{bool(track.is_streamable())}`
__Tags:__ {tags}
'''
    except pylast.WSError:
        return None
    else:
        return out
Exemplo n.º 14
0
async def handle_afk_outgoing(message: Message) -> None:
    """ handle outgoing messages when you afk """
    global IS_AFK  # pylint: disable=global-statement
    IS_AFK = False
    afk_time = time_formatter(round(time.time() - TIME))
    replied: Message = await message.reply("`Eu não estou mais AFK!`",
                                           log=__name__)
    coro_list = []
    if USERS:
        p_msg = ''
        g_msg = ''
        p_count = 0
        g_count = 0
        for pcount, gcount, men in USERS.values():
            if pcount:
                p_msg += f"👤 {men} ✉️ **{pcount}**\n"
                p_count += pcount
            if gcount:
                g_msg += f"👥 {men} ✉️ **{gcount}**\n"
                g_count += gcount
        coro_list.append(
            replied.edit(
                f"`Você recebeu {p_count + g_count} mensagens enquanto você estava fora. "
                f"Check log for more details.`\n\n**AFK time** : __{afk_time}__",
                del_in=3))
        out_str = f"Voce recebeu **{p_count + g_count}** mensagens " + \
            f"de **{len(USERS)}** usuários enquanto você estava fora!\n\n**AFK time** : __{afk_time}__\n"
        if p_count:
            out_str += f"\n**{p_count} Mensagens privadas:**\n\n{p_msg}"
        if g_count:
            out_str += f"\n**{g_count} Mensagens de Grupo:**\n\n{g_msg}"
        coro_list.append(CHANNEL.log(out_str))
        USERS.clear()
    else:
        await asyncio.sleep(3)
        coro_list.append(replied.delete())
    coro_list.append(
        asyncio.gather(
            AFK_COLLECTION.drop(),
            SAVED_SETTINGS.update_one({'_id': 'AFK'}, {"$set": {
                'on': False
            }},
                                      upsert=True)))
    await asyncio.gather(*coro_list)
Exemplo n.º 15
0
async def handle_afk_outgoing(message: Message) -> None:
    """ atur pesan keluar ketika lu afk """
    global IS_AFK  # pylint: disable=global-statement
    IS_AFK = False
    afk_time = time_formatter(round(time.time() - TIME))
    replied: Message = await message.reply("`gua udah ON!`", log=__name__)
    coro_list = []
    if USERS:
        p_msg = ''
        g_msg = ''
        p_count = 0
        g_count = 0
        for pcount, gcount, men in USERS.values():
            if pcount:
                p_msg += f"👤 {men} ✉️ **{pcount}**\n"
                p_count += pcount
            if gcount:
                g_msg += f"👥 {men} ✉️ **{gcount}**\n"
                g_count += gcount
        coro_list.append(replied.edit(
            f"`lu nerima {p_count + g_count} pesan ketika AFK. "
            f"cek log detail ngab.`\n\n**waktu AFK** : __{afk_time}__", del_in=10))
        out_str = f"lu nerima **{p_count + g_count}** pesan " + \
            f"dari **{len(USERS)}** user ketika lu AFK!\n\n**waktu AFK** : __{afk_time}__\n"
        if p_count:
            out_str += f"\n**{p_count} Pesan Pribadi:**\n\n{p_msg}"
        if g_count:
            out_str += f"\n**{g_count} Pesan Grup:**\n\n{g_msg}"
        coro_list.append(CHANNEL.log(out_str))
        USERS.clear()
    else:
        await asyncio.sleep(3)
        coro_list.append(replied.delete())
    coro_list.append(asyncio.gather(
        AFK_COLLECTION.drop(),
        SAVED_SETTINGS.update_one(
            {'_id': 'AFK'}, {"$set": {'on': False}}, upsert=True)))
    await asyncio.gather(*coro_list)
Exemplo n.º 16
0
def mp3_down(url: str):
    ydl_opts = {
        "outtmpl":
        os.path.join("temp_music_dir", "%(title)s.%(ext)s"),
        "prefer_ffmpeg":
        True,
        "format":
        "bestaudio/best",
        "postprocessors": [
            {
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            },
            {
                "key": "FFmpegMetadata"
            },
        ],
    }

    with ytdl.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url)

    return info.get("title"), time_formatter(info.get("duration"))
Exemplo n.º 17
0
 def uptime(self) -> str:
     """ returns userge uptime """
     return time_formatter(time.time() - _START_TIME)
Exemplo n.º 18
0
 def eta(self) -> str:
     """Returns eta"""
     return time_formatter((self._file_size - self._cmp_size) /
                           self.speed if self.speed else 0)
Exemplo n.º 19
0
 def uptime(self) -> str:
     """ returns KampangUsergay uptime """
     return time_formatter(time.time() - _START_TIME)
Exemplo n.º 20
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
Exemplo n.º 21
0
 def uptime(self) -> str:
     """ returns USERGE-X uptime """
     return time_formatter(time.time() - _START_TIME)