Ejemplo n.º 1
0
 def onTransferUpdate(self, api: MegaApi, transfer: MegaTransfer):
     if self.is_cancelled:
         api.cancelTransfer(transfer, None)
         self.continue_event.set()
         return
     self.__speed = transfer.getSpeed()
     self.__bytes_transferred = transfer.getTransferredBytes()
Ejemplo n.º 2
0
 def add_download(mega_link: str, path: str, listener):
     if MEGA_API_KEY is None:
         raise MegaDownloaderException(
             'Mega API KEY not provided! Cannot mirror mega links')
     executor = AsyncExecutor()
     api = MegaApi(MEGA_API_KEY, None, None, 'telegram-mirror-bot')
     global listeners
     mega_listener = MegaAppListener(executor.continue_event, listener)
     listeners.append(mega_listener)
     with download_dict_lock:
         download_dict[listener.uid] = MegaDownloadStatus(
             mega_listener, listener)
     os.makedirs(path)
     api.addListener(mega_listener)
     if MEGA_EMAIL_ID is not None and MEGA_PASSWORD is not None:
         executor.do(api.login, (MEGA_EMAIL_ID, MEGA_PASSWORD))
     link_type = get_mega_link_type(mega_link)
     if link_type == "file":
         executor.do(api.getPublicNode, (mega_link, ))
         node = mega_listener.public_node
     else:
         LOGGER.info("Logging into mega folder")
         folder_api = MegaApi(MEGA_API_KEY, None, None, 'TgBot')
         folder_api.addListener(mega_listener)
         executor.do(folder_api.loginToFolder, (mega_link, ))
         node = folder_api.authorizeNode(mega_listener.node)
     if mega_listener.error is not None:
         return listener.onDownloadError(str(mega_listener.error))
     gid = ''.join(random.SystemRandom().choices(string.ascii_letters +
                                                 string.digits,
                                                 k=8))
     mega_listener.setValues(node.getName(), api.getSize(node), gid)
     executor.do(api.startDownload, (node, path))
Ejemplo n.º 3
0
 def add_download(self, mega_link: str, path: str, listener):
     executor = AsyncExecutor()
     api = MegaApi(MEGA_API_KEY, None, None, 'telegram-mirror-bot')
     mega_listener = MegaAppListener(executor.continue_event, listener)
     os.makedirs(path)
     api.addListener(mega_listener)
     executor.do(api.getPublicNode, (mega_link, ))
     node = mega_listener.node
     if node is None:
         executor.do(api.loginToFolder, (mega_link, ))
         node = mega_listener.node
     if mega_listener.error is not None:
         return listener.onDownloadError(str(mega_listener.error))
     mega_listener.setValues(node.getName(), api.getSize(node),
                             mega_link.split("!", 1)[-1].split("!", 1)[0])
     with download_dict_lock:
         download_dict[listener.uid] = MegaDownloadStatus(
             mega_listener, listener)
     threading.Thread(target=executor.do,
                      args=(api.startDownload, (node, path))).start()
     update_all_messages()
Ejemplo n.º 4
0
 def add_download(mega_link: str, path: str, listener):
     if MEGA_API_KEY is None:
         raise MegaDownloaderException('Mega API KEY not provided! Cannot mirror mega links')
     executor = AsyncExecutor()
     api = MegaApi(MEGA_API_KEY, None, None, 'telegram-mirror-bot')
     mega_listener = MegaAppListener(executor.continue_event, listener)
     os.makedirs(path)
     api.addListener(mega_listener)
     if MEGA_EMAIL_ID is not None and MEGA_PASSWORD is not None:
         executor.do(api.login, (MEGA_EMAIL_ID, MEGA_PASSWORD))
     executor.do(api.getPublicNode, (mega_link,))
     node = mega_listener.node
     if node is None:
         executor.do(api.loginToFolder, (mega_link,))
         node = mega_listener.node
     if mega_listener.error is not None:
         return listener.onDownloadError(str(mega_listener.error))
     gid = ''.join(random.SystemRandom().choices(string.ascii_letters + string.digits, k=8))
     mega_listener.setValues(node.getName(), api.getSize(node), gid)
     with download_dict_lock:
         download_dict[listener.uid] = MegaDownloadStatus(mega_listener, listener)
     threading.Thread(target=executor.do, args=(api.startDownload, (node, path))).start()
     update_all_messages()
Ejemplo n.º 5
0
def main():
    """
    Sets up all that is needed to make (asynchronous) calls on the Mega API,
    then executs the worker to perform the desired operations.
    """
    # Get credentials.
    logging.info('Obtaining Mega login credentials.')
    credentials = {}
    if os.path.exists(CREDENTIALS_FILE):
        credentials = json.load(open(CREDENTIALS_FILE))
    else:
        credentials['user'] = raw_input('User: '******'password'] = getpass.getpass()
    
    # Create the required Mega API objects.
    api = MegaApi(APP_KEY, None, None, 'Python CRUD example')
    listener = AppListener()
    api.addListener(listener)

    # Run the operations.
    start_time = time.time()
    worker(api, listener, credentials)
    logging.info('Total time taken: {} s'.format(time.time() - start_time))
Ejemplo n.º 6
0
def main():
    """
    Sets up all that is needed to make (asynchronous) calls on the Mega API,
    then executs the worker to perform the desired operations.
    """
    # Get credentials.
    logging.info('Obtaining Mega login credentials.')
    credentials = {}
    if os.path.exists(CREDENTIALS_FILE):
        credentials = json.load(open(CREDENTIALS_FILE))
    else:
        credentials['user'] = raw_input('User: '******'password'] = getpass.getpass()
    
    # Create the required Mega API objects.
    api = MegaApi(APP_KEY, None, None, 'Python CRUD example')
    listener = AppListener()
    api.addListener(listener)

    # Run the operations.
    start_time = time.time()
    worker(api, listener, credentials)
    logging.info('Total time taken: {} s'.format(time.time() - start_time))
Ejemplo n.º 7
0
 def add_download(mega_link: str, path: str, listener):
     if MEGA_API_KEY is None:
         raise MegaDownloaderException(
             'Mega API KEY not provided! Cannot mirror Mega links')
     executor = AsyncExecutor()
     api = MegaApi(MEGA_API_KEY, None, None, 'telegram-mirror-bot')
     global listeners
     mega_listener = MegaAppListener(executor.continue_event, listener)
     listeners.append(mega_listener)
     api.addListener(mega_listener)
     if MEGA_EMAIL_ID is not None and MEGA_PASSWORD is not None:
         executor.do(api.login, (MEGA_EMAIL_ID, MEGA_PASSWORD))
     link_type = get_mega_link_type(mega_link)
     if link_type == "file":
         LOGGER.info(
             "File. If your download didn't start, then check your link if it's available to download"
         )
         executor.do(api.getPublicNode, (mega_link, ))
         node = mega_listener.public_node
     else:
         LOGGER.info(
             "Folder. If your download didn't start, then check your link if it's available to download"
         )
         folder_api = MegaApi(MEGA_API_KEY, None, None, 'TgBot')
         folder_api.addListener(mega_listener)
         executor.do(folder_api.loginToFolder, (mega_link, ))
         node = folder_api.authorizeNode(mega_listener.node)
     if mega_listener.error is not None:
         return listener.onDownloadError(str(mega_listener.error))
     if STOP_DUPLICATE_MEGA:
         LOGGER.info(f'Checking File/Folder if already in Drive')
         mname = node.getName()
         if listener.isTar:
             mname = mname + ".tar"
         elif listener.extract:
             smsg = None
         else:
             gd = GoogleDriveHelper()
             smsg, button = gd.drive_list(mname)
         if smsg:
             msg1 = "File/Folder is already available in Drive.\nHere are the search results:"
             sendMarkup(msg1, listener.bot, listener.update, button)
             return
     if MEGA_LIMIT is not None or TAR_UNZIP_LIMIT is not None:
         limit = None
         LOGGER.info(f'Checking File/Folder Size')
         if TAR_UNZIP_LIMIT is not None and (listener.isTar
                                             or listener.extract):
             limit = TAR_UNZIP_LIMIT
             msg3 = f'Failed, Tar/Unzip limit is {TAR_UNZIP_LIMIT}.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
         elif MEGA_LIMIT is not None and limit is None:
             limit = MEGA_LIMIT
             msg3 = f'Failed, Mega limit is {MEGA_LIMIT}.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
         if limit is not None:
             limit = limit.split(' ', maxsplit=1)
             limitint = int(limit[0])
             if 'G' in limit[1] or 'g' in limit[1]:
                 if api.getSize(node) > limitint * 1024**3:
                     sendMessage(msg3, listener.bot, listener.update)
                     return
             elif 'T' in limit[1] or 't' in limit[1]:
                 if api.getSize(node) > limitint * 1024**4:
                     sendMessage(msg3, listener.bot, listener.update)
                     return
     with download_dict_lock:
         download_dict[listener.uid] = MegaDownloadStatus(
             mega_listener, listener)
     os.makedirs(path)
     gid = ''.join(random.SystemRandom().choices(string.ascii_letters +
                                                 string.digits,
                                                 k=8))
     mega_listener.setValues(node.getName(), api.getSize(node), gid)
     sendStatusMessage(listener.update, listener.bot)
     executor.do(api.startDownload, (node, path))
Ejemplo n.º 8
0
        if not self._api.isLoggedIn():
            print('INFO: Not logged in')
            return

        if args[1] != args[2]:
            print('Mismatch, please try again')
            return

        self._api.changePassword(args[0], args[1])

    def do_quit(self, arg):
        """Usage: quit"""
        del self._api
        print('Bye!')
        exit()

    def do_exit(self, arg):
        """Usage: exit"""
        del self._api
        print('Bye!')
        exit()


if __name__ == '__main__':
    api = MegaApi('ox8xnQZL', None, None, 'Python megacli')
    shell = MegaShell(api)
    listener = AppListener(shell)
    api.addListener(listener)
    api = None
    shell.cmdloop()
Ejemplo n.º 9
0
 def add_download(mega_link: str, path: str, listener):
     if MEGA_API_KEY is None:
         raise MegaDownloaderException(
             'Mega API KEY not provided! Cannot mirror Mega links')
     executor = AsyncExecutor()
     api = MegaApi(MEGA_API_KEY, None, None, 'telegram-mirror-bot')
     global listeners
     mega_listener = MegaAppListener(executor.continue_event, listener)
     listeners.append(mega_listener)
     api.addListener(mega_listener)
     if MEGA_EMAIL_ID is not None and MEGA_PASSWORD is not None:
         executor.do(api.login, (MEGA_EMAIL_ID, MEGA_PASSWORD))
     link_type = get_mega_link_type(mega_link)
     if link_type == "file":
         executor.do(api.getPublicNode, (mega_link, ))
         node = mega_listener.public_node
     else:
         LOGGER.info("Logging into Mega folder")
         folder_api = MegaApi(MEGA_API_KEY, None, None, 'TgBot')
         folder_api.addListener(mega_listener)
         executor.do(folder_api.loginToFolder, (mega_link, ))
         node = folder_api.authorizeNode(mega_listener.node)
     if mega_listener.error is not None:
         return listener.onDownloadError(str(mega_listener.error))
     if STOP_DUPLICATE_MEGA:
         msg = sendMessage('Check the File/Folder if already in Drive...',
                           listener.bot, listener.update)
         LOGGER.info(f'Check the File/Folder if already in Drive')
         mname = node.getName()
         if listener.isTar:
             mname = mname + ".tar"
         if listener.extract:
             smsg = None
         else:
             gd = GoogleDriveHelper()
             smsg, button = gd.drive_list(mname)
         if smsg:
             deleteMessage(listener.bot, msg)
             msg1 = "<b>File/Folder is already available in Drive.</b>\n<b>Here are the search results:</b>"
             sendMarkup(msg1, listener.bot, listener.update, button)
             return
         else:
             deleteMessage(listener.bot, msg)
     if MEGA_LIMIT is not None:
         msg2 = sendMessage('Check the File/Folder size...', listener.bot,
                            listener.update)
         LOGGER.info(f'Check the File/Folder size')
         limit = MEGA_LIMIT
         limit = limit.split(' ', maxsplit=1)
         limitint = int(limit[0])
         msg3 = f'<b>Failed, Mega limit is {MEGA_LIMIT}.</b>\n<b>Your File/Folder size is {get_readable_file_size(api.getSize(node))}.</b>'
         if 'GB' in limit or 'gb' in limit:
             if api.getSize(node) > limitint * 1024**3:
                 deleteMessage(listener.bot, msg2)
                 sendMessage(msg3, listener.bot, listener.update)
                 return
             else:
                 deleteMessage(listener.bot, msg2)
         elif 'TB' in limit or 'tb' in limit:
             if api.getSize(node) > limitint * 1024**4:
                 deleteMessage(listener.bot, msg2)
                 sendMessage(msg3, listener.bot, listener.update)
                 return
             else:
                 deleteMessage(listener.bot, msg2)
     with download_dict_lock:
         download_dict[listener.uid] = MegaDownloadStatus(
             mega_listener, listener)
     os.makedirs(path)
     gid = ''.join(random.SystemRandom().choices(string.ascii_letters +
                                                 string.digits,
                                                 k=8))
     mega_listener.setValues(node.getName(), api.getSize(node), gid)
     sendStatusMessage(listener.update, listener.bot)
     executor.do(api.startDownload, (node, path))
Ejemplo n.º 10
0
        self._api.changePassword(args[0], args[1])

    def do_quit(self, arg):
        """Usage: quit"""
        del self._api
        print("Bye!")
        return True

    def do_exit(self, arg):
        """Usage: exit"""
        del self._api
        print("Bye!")
        return True


if __name__ == "__main__":
    # Set up logging.
    logging.basicConfig(
        level=logging.INFO,
        # filename='runner.log',
        format="%(levelname)s\t%(asctime)s %(message)s",
    )
    # Do the work.
    api = MegaApi("ox8xnQZL", None, None, "Python megacli")
    shell = MegaShell(api)
    listener = AppListener(shell)
    api.addListener(listener)
    api = None
    shell.cmdloop()
Ejemplo n.º 11
0
def add_mega_download(mega_link: str, path: str, listener):
    executor = AsyncExecutor()
    api = MegaApi(MEGA_API_KEY, None, None, 'mirror-leech-telegram-bot')
    mega_listener = MegaAppListener(executor.continue_event, listener)
    global listeners
    api.addListener(mega_listener)
    listeners.append(mega_listener)
    if MEGA_EMAIL_ID is not None and MEGA_PASSWORD is not None:
        executor.do(api.login, (MEGA_EMAIL_ID, MEGA_PASSWORD))
    link_type = get_mega_link_type(mega_link)
    if link_type == "file":
        LOGGER.info(
            "File. If your download didn't start, then check your link if it's available to download"
        )
        executor.do(api.getPublicNode, (mega_link, ))
        node = mega_listener.public_node
    else:
        LOGGER.info(
            "Folder. If your download didn't start, then check your link if it's available to download"
        )
        folder_api = MegaApi(MEGA_API_KEY, None, None, 'mltb')
        folder_api.addListener(mega_listener)
        executor.do(folder_api.loginToFolder, (mega_link, ))
        node = folder_api.authorizeNode(mega_listener.node)
    if mega_listener.error is not None:
        return sendMessage(str(mega_listener.error), listener.bot,
                           listener.update)
    if STOP_DUPLICATE and not listener.isLeech:
        LOGGER.info('Checking File/Folder if already in Drive')
        mname = node.getName()
        if listener.isZip:
            mname = mname + ".zip"
        elif listener.extract:
            try:
                mname = get_base_name(mname)
            except:
                mname = None
        if mname is not None:
            smsg, button = GoogleDriveHelper().drive_list(mname, True)
            if smsg:
                msg1 = "File/Folder is already available in Drive.\nHere are the search results:"
                return sendMarkup(msg1, listener.bot, listener.update, button)
    if any([STORAGE_THRESHOLD, ZIP_UNZIP_LIMIT, MEGA_LIMIT]):
        size = api.getSize(node)
        arch = any([listener.isZip, listener.extract])
        if STORAGE_THRESHOLD is not None:
            acpt = check_storage_threshold(size, arch)
            if not acpt:
                msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.'
                msg += f'\nYour File/Folder size is {get_readable_file_size(size)}'
                return sendMessage(msg, listener.bot, listener.update)
        limit = None
        if ZIP_UNZIP_LIMIT is not None and arch:
            msg3 = f'Failed, Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
            limit = ZIP_UNZIP_LIMIT
        elif MEGA_LIMIT is not None:
            msg3 = f'Failed, Mega limit is {MEGA_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
            limit = MEGA_LIMIT
        if limit is not None:
            LOGGER.info('Checking File/Folder Size...')
            if size > limit * 1024**3:
                return sendMessage(msg3, listener.bot, listener.update)
    with download_dict_lock:
        download_dict[listener.uid] = MegaDownloadStatus(
            mega_listener, listener)
    makedirs(path)
    gid = ''.join(random.SystemRandom().choices(string.ascii_letters +
                                                string.digits,
                                                k=8))
    mega_listener.setValues(node.getName(), api.getSize(node), gid)
    sendStatusMessage(listener.update, listener.bot)
    executor.do(api.startDownload, (node, path))