async def register_torrent(entity,
                           message,
                           user_msg=None,
                           magnet=False,
                           file=False):
    client = await get_client()

    #refresh message
    message = await message.client.get_messages(message.chat_id,
                                                ids=message.id)
    if user_msg is None:
        omess = await message.get_reply_message()
    else:
        omess = user_msg

    if magnet:
        torlog.info(magnet)
        torrent = await add_torrent_magnet(entity, message)
        if torrent.progress == 1:
            await message.edit(
                "The provided torrent was already completly downloaded.")
            return True
        else:

            pincode = randint(1000, 9999)
            db = tor_db
            db.add_torrent(torrent.hash, pincode)

            pincodetxt = f"getpin {torrent.hash} {omess.sender_id}"

            data = "torcancel {} {}".format(torrent.hash, omess.sender_id)
            base = get_val("BASE_URL_OF_BOT")

            urll = f"{base}/tortk/files/{torrent.hash}"

            message = await message.edit(
                "Download will be automatically started after 180s of no action.",
                buttons=[
                    [
                        KeyboardButtonUrl("Select files📁", urll),
                        KeyboardButtonCallback("💠Generate Code💠",
                                               data=pincodetxt.encode("UTF-8"))
                    ],
                    [
                        KeyboardButtonCallback(
                            "Start 🚀",
                            data=f"doneselection {omess.sender_id} {omess.id}".
                            encode("UTF-8"))
                    ]
                ])

            await get_confirm(omess)

            message = await message.edit(buttons=[
                KeyboardButtonCallback("⚠️ Cancel", data=data.encode("UTF-8"))
            ])

            db.disable_torrent(torrent.hash)

            return await update_progress(client, message, torrent)
    if file:
        torrent = await add_torrent_file(entity, message)
        if torrent.progress == 1:
            await message.edit(
                "The provided torrent was already completly downloaded.")
            return True
        else:
            pincode = randint(1000, 9999)
            db = tor_db
            db.add_torrent(torrent.hash, pincode)

            pincodetxt = f"getpin {torrent.hash} {omess.sender_id}"

            data = "torcancel {} {}".format(torrent.hash, omess.sender_id)

            base = get_val("BASE_URL_OF_BOT")

            urll = f"{base}/tortk/files/{torrent.hash}"

            message = await message.edit(buttons=[
                [
                    KeyboardButtonUrl("Select files📁", urll),
                    KeyboardButtonCallback("Get Pincode",
                                           data=pincodetxt.encode("UTF-8"))
                ],
                [
                    KeyboardButtonCallback(
                        "Start 🚀",
                        data=f"doneselection {omess.sender_id} {omess.id}".
                        encode("UTF-8"))
                ]
            ])

            await get_confirm(omess)

            message = await message.edit(buttons=[
                KeyboardButtonCallback("⚠️ Cancel", data=data.encode("UTF-8"))
            ])

            db.disable_torrent(torrent.hash)

            return await update_progress(client, message, torrent)
Esempio n. 2
0
async def rclone_upload(path, message, user_msg, dest_drive, dest_base,
                        edit_time, conf_path, task):
    # this function will need a driver for him :o
    if not os.path.exists(path):
        torlog.info(f"Returning none cuz the path {path} not found")
        await task.set_inactive(f"Returning none cuz the path {path} not found"
                                )
        return None
    omsg = user_msg
    await task.set_original_message(omsg)
    upload_db.register_upload(omsg.chat_id, omsg.id)
    data = "upcancel {} {} {}".format(omsg.chat_id, omsg.id, omsg.sender_id)
    buts = [KeyboardButtonCallback("Cancel upload.", data.encode("UTF-8"))]

    msg = await message.reply(
        "<b>Uploading to configured drive.... will be updated soon.",
        parse_mode="html",
        buttons=buts)
    await task.set_message(msg)

    if os.path.isdir(path):
        # handle dirs
        new_dest_base = os.path.join(dest_base, os.path.basename(path))
        # buffer size needs more testing though #todo
        if get_val("RSTUFF"):
            rclone_copy_cmd = [
                get_val("RSTUFF"), 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]
        else:
            rclone_copy_cmd = [
                'rclone', 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]

        # spawn a process # attempt 1 # test 2
        rclone_pr = subprocess.Popen(rclone_copy_cmd, stdout=subprocess.PIPE)
        rcres = await rclone_process_display(rclone_pr, edit_time, msg,
                                             message, omsg, task)

        if rcres is False:
            await message.edit(message.text + "\nCanceled Rclone Upload")
            await msg.delete()
            rclone_pr.kill()
            task.cancel = True
            await task.set_inactive("Canceled Rclone Upload")
            return task

        torlog.info("Upload complete")
        gid = await get_glink(dest_drive, dest_base, os.path.basename(path),
                              conf_path)
        torlog.info(f"Upload folder id :- {gid}")

        folder_link = f"https://drive.google.com/folderview?id={gid[0]}"

        buttons = []
        buttons.append([KeyboardButtonUrl("Drive URL", folder_link)])
        gd_index = get_val("GD_INDEX_URL")
        if gd_index:
            index_link = "{}/{}/".format(gd_index.strip("/"), gid[1])
            index_link = requote_uri(index_link)
            torlog.info("index link " + str(index_link))
            buttons.append([KeyboardButtonUrl("Index URL", index_link)])

        txtmsg = "<a href='tg://user?id={}'>Done</a>\n#uploads\nUPLOADED FOLDER :-<code>{}</code>\nTo Drive.".format(
            omsg.sender_id, os.path.basename(path))

        await omsg.reply(txtmsg, buttons=buttons, parse_mode="html")
        await msg.delete()

    else:
        new_dest_base = dest_base
        # buffer size needs more testing though #todo
        if get_val("RSTUFF"):
            rclone_copy_cmd = [
                get_val("RSTUFF"), 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]
        else:
            rclone_copy_cmd = [
                'rclone', 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]

        # spawn a process # attempt 1 # test 2
        rclone_pr = subprocess.Popen(rclone_copy_cmd, stdout=subprocess.PIPE)
        rcres = await rclone_process_display(rclone_pr, edit_time, msg,
                                             message, omsg, task)

        if rcres is False:
            await message.edit(message.text + "\nCanceled Rclone Upload")
            await msg.delete()
            rclone_pr.kill()
            task.cancel = True
            await task.set_inactive("Canceled Rclone Upload")
            return task

        torlog.info("Upload complete")
        gid = await get_glink(dest_drive, dest_base, os.path.basename(path),
                              conf_path, False)
        torlog.info(f"Upload folder id :- {gid}")

        buttons = []

        file_link = f"https://drive.google.com/file/d/{gid[0]}/view"
        buttons.append([KeyboardButtonUrl("Drive URL", file_link)])
        gd_index = get_val("GD_INDEX_URL")
        if gd_index:
            index_link = "{}/{}".format(gd_index.strip("/"), gid[1])
            index_link = requote_uri(index_link)
            torlog.info("index link " + str(index_link))
            buttons.append([KeyboardButtonUrl("Index URL", index_link)])

        txtmsg = "<a href='tg://user?id={}'>Done</a>\n#uploads\nUPLOADED FILE :-<code>{}</code>\nTo Drive.".format(
            omsg.sender_id, os.path.basename(path))

        await omsg.reply(txtmsg, buttons=buttons, parse_mode="html")
        await msg.delete()

    upload_db.deregister_upload(message.chat_id, message.id)
    await task.set_inactive()
    return task
Esempio n. 3
0
async def print_files(e, files):

    msg = "#uploads\n"
    if len(files) == 0:
        return

    chat_id = e.chat_id

    for i in files.keys():
        link = f'https://t.me/c/{str(chat_id)[4:]}/{files[i]}'
        msg += f'🚩 <a href="{link}">{i}</a>\n'

    rmsg = await e.client.get_messages(e.chat_id, ids=e.message_id)
    rmsg = await rmsg.get_reply_message()
    if rmsg is None:
        #msg += "\n<a href='tg://user?id={}'>Done<a>".format(rmsg.sender_id)
        msg += "\n<a href='tg://user?id={}'>Done</a>".format(e.sender_id)
        await e.reply(msg, parse_mode="html")
    else:
        msg += "\n<a href='tg://user?id={}'>Done</a>".format(rmsg.sender_id)
        await rmsg.reply(msg, parse_mode="html")

    if len(files) < 2:
        return

    ids = list()
    for i in files.keys():
        ids.append(files[i])

    msgs = await e.client.get_messages(e.chat_id, ids=ids)
    for i in msgs:
        index = None
        for j in range(0, len(msgs)):
            index = j
            if ids[j] == i.id:
                break
        nextt, prev = "", ""
        chat_id = str(e.chat_id)[4:]
        buttons = []
        if index == 0:
            nextt = f'https://t.me/c/{chat_id}/{ids[index+1]}'
            buttons.append(KeyboardButtonUrl("Next", nextt))
            nextt = f'<a href="{nextt}">Next</a>\n'
        elif index == len(msgs) - 1:
            prev = f'https://t.me/c/{chat_id}/{ids[index-1]}'
            buttons.append(KeyboardButtonUrl("Prev", prev))
            prev = f'<a href="{prev}">Prev</a>\n'
        else:
            nextt = f'https://t.me/c/{chat_id}/{ids[index+1]}'
            buttons.append(KeyboardButtonUrl("Next", nextt))
            nextt = f'<a href="{nextt}">Next</a>\n'

            prev = f'https://t.me/c/{chat_id}/{ids[index-1]}'
            buttons.append(KeyboardButtonUrl("Prev", prev))
            prev = f'<a href="{prev}">Prev</a>\n'

        try:
            #await i.edit("{} {} {}".format(prev,i.text,nextt),parse_mode="html")
            await i.edit(buttons=buttons)
        except:
            pass
        await asyncio.sleep(1)
async def register_torrent(entity,message,user_msg=None,magnet=False,file=False):
    client = await get_client()

    #refresh message
    message = await message.client.get_messages(message.chat_id,ids=message.id)
    if user_msg is None:
        omess = await message.get_reply_message()
    else:
        omess = user_msg

    if magnet:
        torlog.info(f"magnet :- {magnet}")
        torrent = await add_torrent_magnet(entity,message)
        if isinstance(torrent,bool):
            return False
        torlog.info(torrent)
        if torrent.progress == 1 and torrent.completion_on > 1:
            await message.edit("The provided torrent was already completly downloaded.")
            return True
        else:
            
            pincode = randint(1000,9999)
            db = tor_db
            db.add_torrent(torrent.hash,pincode)
            
            pincodetxt = f"getpin {torrent.hash} {omess.sender_id}"

            data = "torcancel {} {}".format(torrent.hash, omess.sender_id)
            base = get_val("BASE_URL_OF_BOT")

            urll = f"{base}/tortk/files/{torrent.hash}"

            message = await message.edit("Download will be automatically started after 180s of no action.",buttons=[
                [
                    KeyboardButtonUrl("Choose File from link",urll),
                    KeyboardButtonCallback("Get Pincode",data=pincodetxt.encode("UTF-8"))
                ],
                [
                    KeyboardButtonCallback("Done Selecting Files.",data=f"doneselection {omess.sender_id} {omess.id}".encode("UTF-8"))
                ]
            ])

            await get_confirm(omess)

            message = await message.edit(buttons=[KeyboardButtonCallback("Cancel Leech",data=data.encode("UTF-8"))])

            db.disable_torrent(torrent.hash)
            

            task = QBTask(torrent, message, client)
            await task.set_original_mess(omess)
            return await update_progress(client,message,torrent, task)
    if file:
        torrent = await add_torrent_file(entity,message)
        if isinstance(torrent,bool):
            return False
        torlog.info(torrent)
        
        if torrent.progress == 1:
            await message.edit("The provided torrent was already completly downloaded.")
            return True
        else:
            pincode = randint(1000,9999)
            db = tor_db
            db.add_torrent(torrent.hash,pincode)
            
            pincodetxt = f"getpin {torrent.hash} {omess.sender_id}"

            data = "torcancel {} {}".format(torrent.hash, omess.sender_id)

            base = get_val("BASE_URL_OF_BOT")

            urll = f"{base}/tortk/files/{torrent.hash}"

            message = await message.edit(buttons=[
                [
                    KeyboardButtonUrl("Choose File from link",urll),
                    KeyboardButtonCallback("Get Pincode",data=pincodetxt.encode("UTF-8"))
                ],
                [
                    KeyboardButtonCallback("Done Selecting Files.",data=f"doneselection {omess.sender_id} {omess.id}".encode("UTF-8"))
                ]
            ])

            await get_confirm(omess)

            message = await message.edit(buttons=[KeyboardButtonCallback("Cancel Leech",data=data.encode("UTF-8"))])

            db.disable_torrent(torrent.hash)
            
            task = QBTask(torrent, message, client)
            await task.set_original_mess(omess)
            return await update_progress(client,message,torrent, task)
async def rclone_upload(path, message, user_msg, dest_drive, dest_base,
                        edit_time, conf_path):
    # this function will need a driver for him :o
    if not os.path.exists(path):
        torlog.info(f"Returning none cuz the path {path} not found")
        return None
    omsg = user_msg
    upload_db.register_upload(omsg.chat_id, omsg.id)
    data = "upcancel {} {} {}".format(omsg.chat_id, omsg.id, omsg.sender_id)
    buts = [KeyboardButtonCallback("Cancel upload.", data.encode("UTF-8"))]

    msg = await message.reply(
        "<b>Uploading to configured drive in background mode........",
        parse_mode="html",
        buttons=buts)
    if os.path.isdir(path):
        # handle dirs
        new_dest_base = os.path.join(dest_base, os.path.basename(path))
        # buffer size needs more testing though #todo
        if get_val("RSTUFF"):
            rclone_copy_cmd = [
                get_val("RSTUFF"), 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]
        else:
            rclone_copy_cmd = [
                'rclone', 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]

        # spawn a process # attempt 1 # test 2
        rclone_pr = subprocess.Popen(rclone_copy_cmd, stdout=subprocess.PIPE)
        rcres = await rclone_process_display(rclone_pr, edit_time, msg,
                                             message, omsg)

        if rcres is False:
            await message.edit(message.text + "\nCanceled Rclone Upload")
            await msg.delete()
            rclone_pr.kill()
            return True

        torlog.info("Upload complete")
        gid = await get_glink(dest_drive, dest_base, os.path.basename(path),
                              conf_path)
        torlog.info(f"Upload folder id :- {gid}")

        folder_link = f"https://drive.google.com/folderview?id={gid}"
        txtmsg = "<a href='tg://user?id={}'>Done</a>\n<a href='https://groups.google.com/g/troymods'>Join This Link to Download From Google Drive</a>\n#uploads\nUPLOADED FOLDER :-<code>{}</code>\nTo Drive.".format(
            omsg.sender_id, os.path.basename(path))

        await omsg.reply(
            txtmsg,
            buttons=[[KeyboardButtonUrl("Drive URL", folder_link)]],
            parse_mode="html")
        await msg.delete()

    else:
        new_dest_base = dest_base
        # buffer size needs more testing though #todo
        if get_val("RSTUFF"):
            rclone_copy_cmd = [
                get_val("RSTUFF"), 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]
        else:
            rclone_copy_cmd = [
                'rclone', 'copy', f'--config={conf_path}',
                str(path), f'{dest_drive}:{new_dest_base}', '-f', '- *.!qB',
                '--buffer-size=1M', '-P'
            ]

        # spawn a process # attempt 1 # test 2
        rclone_pr = subprocess.Popen(rclone_copy_cmd, stdout=subprocess.PIPE)
        rcres = await rclone_process_display(rclone_pr, edit_time, msg,
                                             message, omsg)

        if rcres is False:
            await message.edit(message.text + "\nCanceled Rclone Upload")
            await msg.delete()
            rclone_pr.kill()
            return True

        torlog.info("Upload complete")
        gid = await get_glink(dest_drive, dest_base, os.path.basename(path),
                              conf_path, False)
        torlog.info(f"Upload folder id :- {gid}")

        file_link = f"https://drive.google.com/file/d/{gid}/view"

        txtmsg = "<a href='tg://user?id={}'>Done</a>\n#uploads\nUPLOADED FILE :-<code>{}</code>\nTo Drive.".format(
            omsg.sender_id, os.path.basename(path))

        await omsg.reply(txtmsg,
                         buttons=[[KeyboardButtonUrl("Drive URL", file_link)]],
                         parse_mode="html")
        await msg.delete()

    upload_db.deregister_upload(message.chat_id, message.id)
    return True