Beispiel #1
0
 def test_print_color(self):
     printer = Printer(False)
     with patch('pirate.print.builtins.print') as mock_print:
         printer.print('abc', color='zebra_1')
         mock_print.assert_called_once_with('abc')
     printer = Printer(True)
     with patch('pirate.print.builtins.print') as mock_print:
         printer.print('abc', color='zebra_1')
         mock_print.assert_called_once_with('\x1b[34mabc', '\x1b[0m')
Beispiel #2
0
    def test_print_descriptions(self):
        printer = Printer(False)
        printer.print = MagicMock()

        class MockRequest():
            add_header = MagicMock()

        request_obj = MockRequest()

        class MockResponse():
            read = MagicMock(
                return_value=
                '<html><div class="nfo"><pre>stuff <a href="href">link</a></pre></div></html>'
                .encode('utf8'))
            info = MagicMock()

        response_obj = MockResponse()
        with patch('urllib.request.Request',
                   return_value=request_obj) as request:
            with patch('urllib.request.urlopen',
                       return_value=response_obj) as urlopen:
                printer.descriptions([0], [{
                    'id': '1',
                    'magnet': 'dn=name'
                }], 'example.com')
                printer.print.assert_has_calls([
                    call('Description for "name":', color='zebra_1'),
                    call('stuff [link](href)', color='zebra_0')
                ])
Beispiel #3
0
    def test_print_results_local2(self):
        class MockTable:
            add_row = MagicMock()
            align = {}

        mock = MockTable()
        printer = Printer(True)
        printer.print = MagicMock()
        with patch('veryprettytable.VeryPrettyTable',
                   return_value=mock) as prettytable:
            results = [{
                'magnet': 'dn=name',
                'date': '1',
                'size': '1',
            }, {
                'magnet': 'dn=name2',
                'date': '2',
                'size': '2',
            }]
            printer.search_results(results, local=True)
            prettytable.assert_called_once_with(
                ['LINK', 'DATE', 'SIZE', 'NAME'])
            mock.add_row.assert_has_calls([
                call([0, '1', '1', 'name']),
                call([1, '2', '2', 'name2'], fore_color='blue')
            ])
Beispiel #4
0
    def test_print_file_lists(self):
        printer = Printer(False)
        printer.print = MagicMock()

        class MockRequest():
            add_header = MagicMock()

        request_obj = MockRequest()

        class MockResponse():
            read = MagicMock(
                return_value=
                '<html><tr><td align="left">1.</td><td align="right">filename</tr></html>'
                .encode('utf8'))
            info = MagicMock()

        response_obj = MockResponse()
        with patch('urllib.request.Request',
                   return_value=request_obj) as request:
            with patch('urllib.request.urlopen',
                       return_value=response_obj) as urlopen:
                printer.file_lists([0], [{
                    'id': '1',
                    'magnet': 'dn=name'
                }], 'example.com')
                printer.print.assert_has_calls([
                    call('Files in "name":', color='zebra_1'),
                    call('         1.  filename', color='zebra_0')
                ])
Beispiel #5
0
    def test_print_descriptions(self):
        printer = Printer(False)
        printer.print = MagicMock()

        class MockRequest():
            add_header = MagicMock()

        request_obj = MockRequest()

        class MockResponse():
            read = MagicMock(
                return_value=json.dumps({
                    'name': 'cool torrent',
                    'descr': 'A fake torrent.\n'
                }))
            info = MagicMock()

        response_obj = MockResponse()

        with patch('urllib.request.Request', return_value=request_obj):
            with patch('urllib.request.urlopen', return_value=response_obj):
                printer.descriptions([0], [{
                    'id': '1',
                    'name': 'name'
                }], 'example.com', 9)
                printer.print.assert_has_calls([
                    call('Description for "name":', color='zebra_1'),
                    call('A fake torrent.\n', color='zebra_0')
                ])
Beispiel #6
0
 def test_print_file_lists(self):
     printer = Printer(False)
     printer.print = MagicMock()
     class MockRequest():
         add_header = MagicMock()
     request_obj = MockRequest()
     class MockResponse():
         read = MagicMock(return_value='<html><tr><td align="left">1.</td><td align="right">filename</tr></html>'.encode('utf8'))
         info = MagicMock()
     response_obj = MockResponse()
     with patch('urllib.request.Request', return_value=request_obj) as request:
         with patch('urllib.request.urlopen', return_value=response_obj) as urlopen:
             printer.file_lists([0], [{'id': '1', 'magnet': 'dn=name'}], 'example.com')
             printer.print.assert_has_calls([call('Files in "name":', color='zebra_1'),call('         1.  filename', color='zebra_0')])
Beispiel #7
0
 def test_print_descriptions(self):
     printer = Printer(False)
     printer.print = MagicMock()
     class MockRequest():
         add_header = MagicMock()
     request_obj = MockRequest()
     class MockResponse():
         read = MagicMock(return_value='<html><div class="nfo"><pre>stuff <a href="href">link</a></pre></div></html>'.encode('utf8'))
         info = MagicMock()
     response_obj = MockResponse()
     with patch('urllib.request.Request', return_value=request_obj) as request:
         with patch('urllib.request.urlopen', return_value=response_obj) as urlopen:
             printer.descriptions([0], [{'id': '1', 'magnet': 'dn=name'}], 'example.com')
             printer.print.assert_has_calls([call('Description for "name":', color='zebra_1'),call('stuff [link](href)', color='zebra_0')])
Beispiel #8
0
 def test_print_results_remote(self):
     class MockTable:
         add_row = MagicMock()
         align = {}
     mock = MockTable()
     printer = Printer(False)
     printer.print = MagicMock()
     with patch('veryprettytable.VeryPrettyTable', return_value=mock) as prettytable:
         results = [{
             'magnet': 'dn=name',
             'seeds': 1,
             'leechers': 2,
             'size': ['3','MiB'],
             'uploaded': 'never'
         }]
         printer.search_results(results)
         prettytable.assert_called_once_with(['LINK', 'SEED', 'LEECH', 'RATIO', 'SIZE', '', 'UPLOAD', 'NAME'])
         mock.add_row.assert_has_calls([call([0, 1, 2, '0.5', '3.0', 'MiB', 'never', 'name'])])
Beispiel #9
0
 def test_print_results_local(self):
     class MockTable:
         add_row = MagicMock()
         align = {}
     mock = MockTable()
     printer = Printer(True)
     printer.print = MagicMock()
     with patch('veryprettytable.VeryPrettyTable', return_value=mock) as prettytable:
         results = [{
             'magnet': 'dn=name',
             'Name': 'name',
         },{
             'magnet': 'dn=name2',
             'Name': 'name2',
         }]
         printer.search_results(results, local=True)
         prettytable.assert_called_once_with(['LINK', 'NAME'])
         mock.add_row.assert_has_calls([call([0, 'name']), call([1, 'name2'], fore_color='blue')])
Beispiel #10
0
    def test_print_file_lists(self):
        printer = Printer(False)
        printer.print = MagicMock()

        class MockRequest():
            add_header = MagicMock()
            info = MagicMock()

        request_obj = MockRequest()

        class MockResponse():
            read = MagicMock(return_value=json.dumps([{
                'name': ['readme.txt'],
                'size': [16]
            }, {
                'name': ['a.mkv'],
                'size': [677739464]
            }, {
                'name': ['b.nfo'],
                'size': [61]
            }]))
            info = MagicMock()

        response_obj = MockResponse()

        with patch('urllib.request.Request', return_value=request_obj):
            with patch('urllib.request.urlopen', return_value=response_obj):
                printer.file_lists([0], [{
                    'id': '1',
                    'name': 'name'
                }], 'example.com', 9)
                printer.print.assert_has_calls([
                    call('Files in name:', color='zebra_1'),
                    call('       16 B readme.txt', color='zebra_0'),
                    call('  646.3 MiB a.mkv', color='zebra_1'),
                    call('       61 B b.nfo', color='zebra_0')
                ])
Beispiel #11
0
def pirate_main(args):
    printer = Printer(args.color)

    # print version
    if args.version:
        printer.print('pirate-get, version {}'.format(pirate.data.version))
        sys.exit(0)

    # check it transmission is running
    if args.transmission:
        ret = subprocess.call(args.transmission_command + ['-l'],
                              stdout=subprocess.DEVNULL,
                              stderr=subprocess.DEVNULL)
        if ret != 0:
            printer.print('Transmission is not running.')
            sys.exit(1)

    # non-torrent fetching actions

    if args.action == 'list_categories':
        cur_color = 'zebra_0'
        for key, value in sorted(pirate.data.categories.items()):
            cur_color = 'zebra_0' if cur_color == 'zebra_1' else 'zebra_1'
            printer.print(str(value), '\t', key, sep='', color=cur_color)
        return

    if args.action == 'list_sorts':
        cur_color = 'zebra_0'
        for key, value in sorted(pirate.data.sorts.items()):
            cur_color = 'zebra_0' if cur_color == 'zebra_1' else 'zebra_1'
            printer.print(str(value), '\t', key, sep='', color=cur_color)
        return

    # fetch torrents

    if args.source == 'local_tpb':
        if os.path.isfile(args.database):
            results = pirate.local.search(args.database, args.search)
        else:
            printer.print("Local pirate bay database doesn't exist.",
                          '(%s)' % args.database,
                          color='ERROR')
            sys.exit(1)
    elif args.source == 'tpb':
        try:
            results, site = search_mirrors(printer, args)
        except IOError as e:
            printer.print(e.args[0] + ' :( ', color='ERROR')
            if len(e.args) > 1:
                printer.print(e.args[1])
            sys.exit(1)

    if len(results) == 0:
        printer.print('No results')
        return

    printer.search_results(results, local=args.source == 'local_tpb')

    # number of results to pick
    if args.first:
        printer.print('Choosing first result')
        choices = [0]
    elif args.download_all:
        printer.print('Downloading all results')
        choices = range(len(results))
    else:
        # interactive loop for per-torrent actions
        while True:
            printer.print(
                "\nSelect links (Type 'h' for more options"
                ", 'q' to quit)",
                end='\b',
                color='alt')
            try:
                l = builtins.input(': ')
            except (KeyboardInterrupt, EOFError):
                printer.print('\nCancelled.')
                return

            try:
                code, choices = parse_torrent_command(l)
                # Act on option, if supplied
                printer.print('')
                if code == 'h':
                    printer.print('Options:',
                                  '<links>: Download selected torrents',
                                  '[m<links>]: Save magnets as files',
                                  '[t<links>]: Save .torrent files',
                                  '[d<links>]: Get descriptions',
                                  '[f<links>]: Get files',
                                  '[p] Print search results',
                                  '[q] Quit',
                                  sep='\n')
                elif code == 'q':
                    printer.print('Bye.', color='alt')
                    return
                elif code == 'd':
                    printer.descriptions(choices, results, site)
                elif code == 'f':
                    printer.file_lists(choices, results, site)
                elif code == 'p':
                    printer.search_results(results)
                elif code == 'm':
                    pirate.torrent.save_magnets(printer, choices, results,
                                                args.save_directory)
                elif code == 't':
                    pirate.torrent.save_torrents(printer, choices, results,
                                                 args.save_directory)
                elif not l:
                    printer.print('No links entered!', color='WARN')
                else:
                    break
            except Exception as e:
                printer.print('Exception:', e, color='ERROR')
                return

    # output

    if args.output == 'save_magnet_files':
        printer.print('Saving selected magnets...')
        pirate.torrent.save_magnets(printer, choices, results,
                                    args.save_directory)
        return

    if args.output == 'save_torrent_files':
        printer.print('Saving selected torrents...')
        pirate.torrent.save_torrents(printer, choices, results,
                                     args.save_directory)
        return

    for choice in choices:
        url = results[choice]['magnet']

        if args.output == 'transmission':
            subprocess.call(args.transmission_command + ['--add', url])
        elif args.output == 'open_command':
            cmd = parse_cmd(args.open_command, url)
            printer.print(" ".join(cmd))
            subprocess.call(cmd)
        elif args.output == 'browser_open':
            webbrowser.open(url)

    if args.output == 'transmission':
        subprocess.call(args.transmission_command + ['-l'])
Beispiel #12
0
def pirate_main(args):
    printer = Printer(args.color)

    # check it transmission is running
    if args.transmission:
        ret = subprocess.call(args.transmission_command + ["-l"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if ret != 0:
            printer.print("Transmission is not running.")
            sys.exit(1)

    # non-torrent fetching actions

    if args.action == "list_categories":
        cur_color = "zebra_0"
        for key, value in sorted(pirate.data.categories.items()):
            cur_color = "zebra_0" if cur_color == "zebra_1" else "zebra_1"
            printer.print(str(value), "\t", key, sep="", color=cur_color)
        return

    if args.action == "list_sorts":
        cur_color = "zebra_0"
        for key, value in sorted(pirate.data.sorts.items()):
            cur_color = "zebra_0" if cur_color == "zebra_1" else "zebra_1"
            printer.print(str(value), "\t", key, sep="", color=cur_color)
        return

    # fetch torrents

    if args.source == "local_tpb":
        results = pirate.local.search(args.database, args.search)
    elif args.source == "tpb":
        results, site = search_mirrors(printer, args.pages, args.category, args.sort, args.action, args.search)

    if len(results) == 0:
        printer.print("No results")
        return

    printer.search_results(results, local=args.source == "local_tpb")

    # number of results to pick
    if args.first:
        printer.print("Choosing first result")
        choices = [0]
    elif args.download_all:
        printer.print("Downloading all results")
        choices = range(len(results))
    else:
        # interactive loop for per-torrent actions
        while True:
            printer.print("\nSelect links (Type 'h' for more options" ", 'q' to quit)", end="\b", color="alt")
            try:
                l = builtins.input(": ")
            except (KeyboardInterrupt, EOFError):
                printer.print("\nCancelled.")
                return

            try:
                code, choices = parse_torrent_command(l)
                # Act on option, if supplied
                printer.print("")
                if code == "h":
                    printer.print(
                        "Options:",
                        "<links>: Download selected torrents",
                        "[m<links>]: Save magnets as files",
                        "[t<links>]: Save .torrent files",
                        "[d<links>]: Get descriptions",
                        "[f<links>]: Get files",
                        "[p] Print search results",
                        "[q] Quit",
                        sep="\n",
                    )
                elif code == "q":
                    printer.print("Bye.", color="alt")
                    return
                elif code == "d":
                    printer.descriptions(choices, results, site)
                elif code == "f":
                    printer.file_lists(choices, results, site)
                elif code == "p":
                    printer.search_results(results)
                elif code == "m":
                    pirate.torrent.save_magnets(printer, choices, results, args.save_directory)
                elif code == "t":
                    pirate.torrent.save_torrents(printer, choices, results, args.save_directory)
                elif not l:
                    printer.print("No links entered!", color="WARN")
                else:
                    break
            except Exception as e:
                printer.print("Exception:", e, color="ERROR")
                return

    # output

    if args.output == "save_magnet_files":
        printer.print("Saving selected magnets...")
        pirate.torrent.save_magnets(choices, results, args.save_directory)
        return

    if args.output == "save_torrent_files":
        printer.print("Saving selected torrents...")
        pirate.torrent.save_torrents(choices, results, args.save_directory)
        return

    for choice in choices:
        url = results[choice]["magnet"]

        if args.output == "transmission":
            subprocess.call(args.transmission_command + ["--add", url])
        elif args.output == "open_command":
            cmd = parse_cmd(args.open_command, url)
            printer.print(" ".join(cmd))
            subprocess.call(cmd)
        elif args.output == "browser_open":
            webbrowser.open(url)

    if args.output == "transmission":
        subprocess.call(args.transmission_command + ["-l"])
Beispiel #13
0
def pirate_main(args):
    printer = Printer(args.color)

    # check it transmission is running
    if args.transmission:
        ret = subprocess.call(args.transmission_command + ['-l'],
                              stdout=subprocess.DEVNULL,
                              stderr=subprocess.DEVNULL)
        if ret != 0:
            printer.print('Transmission is not running.')
            sys.exit(1)

    # non-torrent fetching actions

    if args.action == 'list_categories':
        cur_color = 'zebra_0'
        for key, value in sorted(pirate.data.categories.items()):
            cur_color = 'zebra_0' if cur_color == 'zebra_1' else 'zebra_1'
            printer.print(str(value), '\t', key, sep='', color=cur_color)
        return

    if args.action == 'list_sorts':
        cur_color = 'zebra_0'
        for key, value in sorted(pirate.data.sorts.items()):
            cur_color = 'zebra_0' if cur_color == 'zebra_1' else 'zebra_1'
            printer.print(str(value), '\t', key, sep='', color=cur_color)
        return

    # fetch torrents

    if args.source == 'local_tpb':
        results = pirate.local.search(args.database, args.search)
    elif args.source == 'tpb':
        results, site = search_mirrors(printer, args.pages, args.category,
                                       args.sort, args.action, args.search)

    if len(results) == 0:
        printer.print('No results')
        return

    printer.search_results(results, local=args.source == 'local_tpb')

    # number of results to pick
    if args.first:
        printer.print('Choosing first result')
        choices = [0]
    elif args.download_all:
        printer.print('Downloading all results')
        choices = range(len(results))
    else:
        # interactive loop for per-torrent actions
        while True:
            printer.print("\nSelect links (Type 'h' for more options"
                          ", 'q' to quit)", end='\b', color='alt')
            try:
                l = builtins.input(': ')
            except (KeyboardInterrupt, EOFError):
                printer.print('\nCancelled.')
                return

            try:
                code, choices = parse_torrent_command(l)
                # Act on option, if supplied
                printer.print('')
                if code == 'h':
                    printer.print('Options:',
                                  '<links>: Download selected torrents',
                                  '[m<links>]: Save magnets as files',
                                  '[t<links>]: Save .torrent files',
                                  '[d<links>]: Get descriptions',
                                  '[f<links>]: Get files',
                                  '[p] Print search results',
                                  '[q] Quit', sep='\n')
                elif code == 'q':
                    printer.print('Bye.', color='alt')
                    return
                elif code == 'd':
                    printer.descriptions(choices, results, site)
                elif code == 'f':
                    printer.file_lists(choices, results, site)
                elif code == 'p':
                    printer.search_results(results)
                elif code == 'm':
                    pirate.torrent.save_magnets(printer, choices, results,
                                                args.save_directory)
                elif code == 't':
                    pirate.torrent.save_torrents(printer, choices, results,
                                                 args.save_directory)
                elif not l:
                    printer.print('No links entered!', color='WARN')
                else:
                    break
            except Exception as e:
                printer.print('Exception:', e, color='ERROR')
                return

    # output

    if args.output == 'save_magnet_files':
        printer.print('Saving selected magnets...')
        pirate.torrent.save_magnets(choices, results, args.save_directory)
        return

    if args.output == 'save_torrent_files':
        printer.print('Saving selected torrents...')
        pirate.torrent.save_torrents(choices, results, args.save_directory)
        return

    for choice in choices:
        url = results[choice]['magnet']

        if args.output == 'transmission':
            subprocess.call(args.transmission_command + ['--add', url])
        elif args.output == 'open_command':
            cmd = parse_cmd(args.open_command, url)
            printer.print(" ".join(cmd))
            subprocess.call(cmd)
        elif args.output == 'browser_open':
            webbrowser.open(url)

    if args.output == 'transmission':
        subprocess.call(args.transmission_command + ['-l'])