Skip to content

Commit

Permalink
Merge tag '1.0.5' into develop
Browse files Browse the repository at this point in the history
v1.0.5
  • Loading branch information
XayOn committed Sep 27, 2017
2 parents c249eda + dad3c82 commit 857a463
Show file tree
Hide file tree
Showing 6 changed files with 89 additions and 22 deletions.
6 changes: 6 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
CHANGES
=======

* Fixed bot options

1.0.4
-----

* Added token\_file option for dockerizing
* Minor change
* Fixed katbot tests
* Fixed tests
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
FROM python:3.6.2
RUN pip install katcr
CMD ["katcr_bot", "--token_file", "/volume/token"]
CMD katcr_bot --token-file /volume/token
48 changes: 32 additions & 16 deletions katcr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ def search_magnets(self, query: str, page: int):
proxies.insert(0, [self.url, None])
for site, _ in proxies:
self.logger.debug("Searching in %s", site)
with suppress(requests.exceptions.ReadTimeout, AssertionError):
with suppress(requests.exceptions.ReadTimeout,
requests.exceptions.SSLError, AssertionError):
http = '' if site.startswith('http') else 'http://'
self.browser.open(self.url_format.format(
http, site, query, page))
Expand Down Expand Up @@ -150,6 +151,19 @@ def limit_terminal_size(what, limit=-20):
return what[:Terminal().width + limit]


def search_in_engines(logger, engines, search_term, pages):
"""Search in engines."""
search_res = None

if engines == ["All"]:
engines = ("Katcr", "ThePirateBay")

for engine in engines:
search_res = list(globals()[engine](logger).search(search_term, pages))
if search_res:
return search_res


def main():
"""Search in multiple torrent sites.
Expand All @@ -161,27 +175,29 @@ def main():
- ThePirateBay
Options:
-e --search-engine=<SearchEngine> Torrent search engine to use
[default: Katcr].
-p --pages=<PAGES_NUM> Number of pages to lookup
[default: 1]
-d --disable-shortener Disable url shortener
-s --shortener=<SHORTENER_URL> Use given magnet shortener to
prettify urls.
[default: http://www.shortmag.net]
-e --search-engines=<SearchEngine> Torrent search engine to use
Options: Katcr, ThePirateBay
[default: All].
-p --pages=<PAGES_NUM> Number of pages to lookup
[default: 1]
-d --disable-shortener Disable url shortener
-s --shortener=<SHORTENER_URL> Use given magnet shortener to
prettify urls.
[default: http://www.shortmag.net]
Interactive Options:
-i --interactive Enable interactive mode
-o --open Launch with default torrent app
in interactive mode [default: True]
-h --help Show this help screen
-v --verbose Enable debug mode
-i --interactive Enable interactive mode
-o --open Launch with default torrent app
in interactive mode [default: True]
-h --help Show this help screen
-v --verbose Enable debug mode
"""
opt = docopt(main.__doc__, version="0.0.1")
logger = Gogo(__name__, verbose=opt.get('--verbose')).logger

search_res = list(globals()[opt['--search-engine'][0]](logger).search(
opt["<SEARCH_TERM>"], int(opt.get("--pages")[0])))
search_res = search_in_engines(logger, opt['--search-engine'],
opt["<SEARCH_TERM>"],
int(opt.get("--pages")[0]))

if not opt['--disable-shortener']:
search_res = list(get_from_short(opt['--shortener'][0], search_res))
Expand Down
16 changes: 12 additions & 4 deletions katcr/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from pathlib import Path

from katcr import Katcr
from katcr import ThePirateBay
from katcr import get_short

from docopt import docopt
Expand All @@ -18,12 +19,15 @@ class KATBot(telepot.Bot):

def __init__(self, opts):
"""Initialize of KATBot."""
super().__init__(
opts.get('--token', Path(opts.get('--token-file')).read_text()))
token = opts.get('--token')
if not token:
token = Path(opts.get('--token-file')).read_text().strip()
super().__init__(token)
self.logger = Gogo(__name__, verbose=True).logger
self.logger.debug("Starting service.")
self.shortener = opts['--shortener']
self.katcr = Katcr(self.logger)
self.thepiratebay = ThePirateBay(self.logger)
self.responses = {}

# pylint: disable=too-few-public-methods
Expand All @@ -33,7 +37,11 @@ def on_chat_message(self, msg):
return

chat_id = telepot.glance(msg)[2]
res = tuple(self.katcr.search(msg['text'], 1))

for engine in (self.katcr, self.thepiratebay):
res = tuple(engine.search(msg['text'], 1))
if res:
break

keyboard = InlineKeyboardMarkup(inline_keyboard=list(
[InlineKeyboardButton(text=k, callback_data=str(r))]
Expand All @@ -60,7 +68,7 @@ def main():
Options:
--token=<BOT_TOKEN> Telegram bot token
--token_file=<FILE> Telegram bot token file
--token-file=<FILE> Telegram bot token file
--shortener=<URL_SHORTENER> Url shortener to use
[default: http://shortmag.net]
"""
Expand Down
27 changes: 27 additions & 0 deletions tests/unit/test_katbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,27 @@ def test_katbot_main():
bot.assert_called_with({'--token': 'foo'})


def test_katbot_main_file():
"""Test argument parsing and calling."""
from katcr.bot import main

from unittest.mock import patch
import os
import tempfile

with tempfile.NamedTemporaryFile(mode='w', delete=False) as tmpfile:
tmpfile.write('foobar')

opts = {'--token': None, '--shortener': None,
'--token-file': tmpfile.name}
with patch('katcr.bot.docopt', side_effect=(opts,)):
with patch('katcr.bot.MessageLoop'):
with patch('katcr.bot.telepot.Bot.__init__') as mock:
main()
mock.assert_called_with('foobar')
os.unlink(tmpfile.name)


def test_on_chat_message_start():
"""Test on chat message handler."""
from katcr.bot import KATBot
Expand Down Expand Up @@ -53,6 +74,7 @@ def __init__(self, token):
"""Set token."""
self.token = token
self.katcr = MagicMock()
self.thepiratebay = MagicMock()
self.katcr.search.return_value = (('foo', '3', 'bar'),)
self.shortener = "http://foo"
self.responses = {}
Expand Down Expand Up @@ -88,6 +110,7 @@ def __init__(self, token):
"""Set token."""
self.token = token
self.katcr = MagicMock()
self.thepiratebay = MagicMock()
self.shortener = "http://foo"
self.responses = {}
self.sendMessage = MagicMock()
Expand Down Expand Up @@ -125,3 +148,7 @@ def __init__(self, token):
assert fkb.sendMessage.call_args[0][0] == 1
assert 'href' in fkb.sendMessage.call_args[0][1]
assert fkb.sendMessage.call_args[1]['parse_mode'] == 'html'


def test_katbot_tokenfile():
"""Test katbot tokenfile."""
12 changes: 11 additions & 1 deletion tests/unit/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def test_main():
with patch('katcr.docopt', side_effect=(opts,)):
main()
mock().search.assert_called_with(opts['<SEARCH_TERM>'], 1)
short_mock.assert_called_with('bar', [])
short_mock.assert_called_with('bar', None)

class Foo:
text = "foo"
Expand Down Expand Up @@ -146,3 +146,13 @@ def test_cli_help():
from katcr import main
result = subprocess.check_output(['katcr', '--help'])
assert main.__doc__.encode() in result


def test_search_in_engines():
"""Test search_in_engines function."""
from unittest.mock import patch, MagicMock

with patch('katcr.Katcr.search', side_effect=(tuple(),)):
with patch('katcr.ThePirateBay.search', side_effect=(tuple(),)):
from katcr import search_in_engines
search_in_engines(MagicMock(), ["All"], "test", 1)

0 comments on commit 857a463

Please sign in to comment.