mirror of https://github.com/YGGverse/qBt_SE.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
312 lines
11 KiB
312 lines
11 KiB
4 years ago
|
# VERSION: 2.8
|
||
6 years ago
|
# AUTHORS: imDMG [imdmgg@gmail.com]
|
||
6 years ago
|
|
||
|
# NoNaMe-Club search engine plugin for qBittorrent
|
||
|
|
||
5 years ago
|
import base64
|
||
6 years ago
|
import json
|
||
6 years ago
|
import logging
|
||
|
import re
|
||
5 years ago
|
import socket
|
||
4 years ago
|
import sys
|
||
6 years ago
|
import time
|
||
5 years ago
|
from concurrent.futures import ThreadPoolExecutor
|
||
5 years ago
|
from html import unescape
|
||
5 years ago
|
from http.cookiejar import Cookie, MozillaCookieJar
|
||
4 years ago
|
from pathlib import Path
|
||
|
from tempfile import NamedTemporaryFile
|
||
5 years ago
|
from urllib.error import URLError, HTTPError
|
||
|
from urllib.parse import urlencode, unquote
|
||
|
from urllib.request import build_opener, HTTPCookieProcessor, ProxyHandler
|
||
|
|
||
4 years ago
|
try:
|
||
|
from novaprinter import prettyPrinter
|
||
|
except ImportError:
|
||
|
sys.path.insert(0, str(Path(__file__).parent.parent.absolute()))
|
||
|
from novaprinter import prettyPrinter
|
||
6 years ago
|
|
||
5 years ago
|
# default config
|
||
|
config = {
|
||
|
"torrentDate": True,
|
||
|
"username": "USERNAME",
|
||
|
"password": "PASSWORD",
|
||
|
"proxy": False,
|
||
|
"proxies": {
|
||
|
"http": "",
|
||
|
"https": ""
|
||
|
},
|
||
|
"magnet": True,
|
||
|
"ua": "Mozilla/5.0 (X11; Linux i686; rv:38.0) Gecko/20100101 Firefox/38.0 "
|
||
|
}
|
||
|
|
||
4 years ago
|
FILE = Path(__file__)
|
||
|
BASEDIR = FILE.parent.absolute()
|
||
5 years ago
|
|
||
4 years ago
|
FILENAME = FILE.name[:-3]
|
||
|
FILE_J, FILE_C = [BASEDIR / (FILENAME + fl) for fl in ['.json', '.cookie']]
|
||
|
|
||
|
PAGES = 50
|
||
5 years ago
|
|
||
|
|
||
|
def rng(t):
|
||
4 years ago
|
return range(PAGES, -(-t // PAGES) * PAGES, PAGES)
|
||
5 years ago
|
|
||
|
|
||
4 years ago
|
RE_TORRENTS = re.compile(
|
||
|
r'topictitle"\shref="(.+?)"><b>(.+?)</b>.+?href="(d.+?)".+?<u>(\d+?)</u>.+?'
|
||
4 years ago
|
r'<b>(\d+)</b>.+?<b>(\d+)</b>.+?<u>(\d+)</u>', re.S
|
||
|
)
|
||
4 years ago
|
RE_RESULTS = re.compile(r'TP_VER">(?:Результатов\sпоиска:\s(\d{1,3}))?\s', re.S)
|
||
4 years ago
|
RE_CODE = re.compile(r'name="code"\svalue="(.+?)"', re.S)
|
||
|
PATTERNS = ('%stracker.php?nm=%s&%s', "%s&start=%s")
|
||
5 years ago
|
|
||
|
# base64 encoded image
|
||
|
ICON = ("AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAAAAAAAAAAAAA"
|
||
|
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaQicAXRQFADICAQAHAAAA"
|
||
|
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADz4QA8PizAP"
|
||
|
"u3XQDpjEIBtgkCABoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||
|
"BAIAEuyUAP3/8AD//akA//+hAP92SgCVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFA"
|
||
|
"AAAAAAAAAAAAAAAAEAADjLiQD8//wA//7RFP//+lX/WlsPlwAAAAMAAAAGAAAAAAAAAAAA"
|
||
|
"AAAAEAgAQqNBAP99HADfIAYAfgAAABQAAAAX21UC///4AP///Sj/+/Z//lZcMJOOjQCrqI"
|
||
|
"EAwQ4CADAAAAAAAAAAAGEXAM39oAD//7oA/9ucAP94Gw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rEEAAaxBAACsQQAArEEBAKxBg/+sQQP/rEED/6xBg/+sQYf/rEGH/6xBj/+sQQ==")
|
||
|
|
||
|
# setup logging
|
||
|
logging.basicConfig(
|
||
|
format="%(asctime)s %(name)-12s %(levelname)-8s %(message)s",
|
||
4 years ago
|
datefmt="%m-%d %H:%M",
|
||
4 years ago
|
level=logging.DEBUG
|
||
|
)
|
||
4 years ago
|
|
||
5 years ago
|
logger = logging.getLogger(__name__)
|
||
|
|
||
|
try:
|
||
4 years ago
|
config = json.loads(FILE_J.read_text())
|
||
5 years ago
|
logger.debug("Config is loaded.")
|
||
|
except OSError as e:
|
||
|
logger.error(e)
|
||
|
# if file doesn't exist, we'll create it
|
||
4 years ago
|
FILE_J.write_text(json.dumps(config, indent=4, sort_keys=False))
|
||
5 years ago
|
# also write/rewrite ico file
|
||
4 years ago
|
(BASEDIR / (FILENAME + '.ico')).write_bytes(base64.b64decode(ICON))
|
||
5 years ago
|
logger.debug("Write files.")
|
||
|
|
||
6 years ago
|
|
||
4 years ago
|
class NNMClub:
|
||
6 years ago
|
name = 'NoNaMe-Club'
|
||
5 years ago
|
url = 'https://nnmclub.to/forum/'
|
||
5 years ago
|
url_dl = 'https://nnm-club.ws/'
|
||
4 years ago
|
url_login = url + 'login.php'
|
||
6 years ago
|
supported_categories = {'all': '-1',
|
||
|
'movies': '14',
|
||
|
'tv': '27',
|
||
|
'music': '16',
|
||
|
'games': '17',
|
||
|
'anime': '24',
|
||
|
'software': '21'}
|
||
|
|
||
|
def __init__(self):
|
||
5 years ago
|
# error message
|
||
|
self.error = None
|
||
5 years ago
|
|
||
|
# establish connection
|
||
|
self.session = build_opener()
|
||
6 years ago
|
|
||
6 years ago
|
# add proxy handler if needed
|
||
5 years ago
|
if config['proxy']:
|
||
|
if any(config['proxies'].values()):
|
||
|
self.session.add_handler(ProxyHandler(config['proxies']))
|
||
|
logger.debug("Proxy is set!")
|
||
|
else:
|
||
|
self.error = "Proxy enabled, but not set!"
|
||
6 years ago
|
|
||
|
# change user-agent
|
||
4 years ago
|
self.session.addheaders = [('User-Agent', config['ua'])]
|
||
6 years ago
|
|
||
5 years ago
|
# load local cookies
|
||
5 years ago
|
mcj = MozillaCookieJar()
|
||
|
try:
|
||
|
mcj.load(FILE_C, ignore_discard=True)
|
||
5 years ago
|
key = 'phpbb2mysql_4_data'
|
||
|
if [True for c in mcj if c.name == key and c.expires > time.time()]:
|
||
5 years ago
|
logger.info("Local cookies is loaded")
|
||
5 years ago
|
self.session.add_handler(HTTPCookieProcessor(mcj))
|
||
|
else:
|
||
5 years ago
|
logger.info("Local cookies expired or bad")
|
||
|
logger.debug(f"That we have: {[cookie for cookie in mcj]}")
|
||
5 years ago
|
mcj.clear()
|
||
5 years ago
|
self.login(mcj)
|
||
|
except FileNotFoundError:
|
||
|
self.login(mcj)
|
||
|
|
||
|
def search(self, what, cat='all'):
|
||
|
if self.error:
|
||
|
self.pretty_error(what)
|
||
4 years ago
|
return None
|
||
5 years ago
|
c = self.supported_categories[cat]
|
||
4 years ago
|
query = PATTERNS[0] % (self.url, what.replace(" ", "+"),
|
||
5 years ago
|
"f=-1" if c == "-1" else "c=" + c)
|
||
|
|
||
|
# make first request (maybe it enough)
|
||
|
t0, total = time.time(), self.searching(query, True)
|
||
|
if self.error:
|
||
|
self.pretty_error(what)
|
||
4 years ago
|
return None
|
||
5 years ago
|
# do async requests
|
||
4 years ago
|
if total > PAGES:
|
||
4 years ago
|
qrs = [PATTERNS[1] % (query, x) for x in rng(total)]
|
||
5 years ago
|
with ThreadPoolExecutor(len(qrs)) as executor:
|
||
|
executor.map(self.searching, qrs, timeout=30)
|
||
|
|
||
|
logger.debug(f"--- {time.time() - t0} seconds ---")
|
||
|
logger.info(f"Found torrents: {total}")
|
||
|
|
||
|
def download_torrent(self, url: str):
|
||
|
# Download url
|
||
|
response = self._catch_error_request(url)
|
||
|
if self.error:
|
||
|
self.pretty_error(url)
|
||
4 years ago
|
return None
|
||
5 years ago
|
|
||
|
# Create a torrent file
|
||
4 years ago
|
with NamedTemporaryFile(suffix='.torrent', delete=False) as fd:
|
||
4 years ago
|
fd.write(response)
|
||
5 years ago
|
|
||
4 years ago
|
# return file path
|
||
|
logger.debug(fd.name + " " + url)
|
||
|
print(fd.name + " " + url)
|
||
5 years ago
|
|
||
|
def login(self, mcj):
|
||
|
if self.error:
|
||
4 years ago
|
return None
|
||
5 years ago
|
# if we wanna use https we mast add ssl=enable_ssl to cookie
|
||
5 years ago
|
mcj.set_cookie(Cookie(0, "ssl", "enable_ssl", None, False,
|
||
|
".nnmclub.to", True, False, "/", True,
|
||
|
False, None, False, None, None, {}))
|
||
5 years ago
|
self.session.add_handler(HTTPCookieProcessor(mcj))
|
||
|
|
||
4 years ago
|
response = self._catch_error_request(self.url_login)
|
||
5 years ago
|
if not response:
|
||
|
return None
|
||
4 years ago
|
code = RE_CODE.search(response.decode('cp1251'))[1]
|
||
5 years ago
|
form_data = {"username": config['username'],
|
||
|
"password": config['password'],
|
||
|
"autologin": "on",
|
||
|
"code": code,
|
||
|
"login": "Вход"}
|
||
|
# so we first encode vals to cp1251 then do default decode whole string
|
||
|
data_encoded = urlencode(
|
||
4 years ago
|
{k: v.encode('cp1251') for k, v in form_data.items()}
|
||
|
).encode()
|
||
5 years ago
|
|
||
4 years ago
|
self._catch_error_request(self.url_login, data_encoded)
|
||
5 years ago
|
if self.error:
|
||
4 years ago
|
return None
|
||
5 years ago
|
logger.debug(f"That we have: {[cookie for cookie in mcj]}")
|
||
|
if 'phpbb2mysql_4_sid' in [cookie.name for cookie in mcj]:
|
||
|
mcj.save(FILE_C, ignore_discard=True, ignore_expires=True)
|
||
|
logger.info('We successfully authorized')
|
||
|
else:
|
||
|
self.error = "We not authorized, please check your credentials!"
|
||
|
logger.warning(self.error)
|
||
6 years ago
|
|
||
6 years ago
|
def draw(self, html: str):
|
||
4 years ago
|
torrents = RE_TORRENTS.findall(html)
|
||
6 years ago
|
|
||
|
for tor in torrents:
|
||
5 years ago
|
torrent_date = ""
|
||
5 years ago
|
if config['torrentDate']:
|
||
|
_loc = time.localtime(int(tor[6]))
|
||
|
torrent_date = f'[{time.strftime("%y.%m.%d", _loc)}] '
|
||
|
|
||
|
prettyPrinter({
|
||
|
"engine_url": self.url,
|
||
|
"desc_link": self.url + tor[0],
|
||
5 years ago
|
"name": torrent_date + unescape(tor[1]),
|
||
5 years ago
|
"link": self.url + tor[2],
|
||
4 years ago
|
"size": tor[3],
|
||
5 years ago
|
"seeds": tor[4],
|
||
|
"leech": tor[5]
|
||
|
})
|
||
6 years ago
|
del torrents
|
||
6 years ago
|
|
||
6 years ago
|
def searching(self, query, first=False):
|
||
|
response = self._catch_error_request(query)
|
||
5 years ago
|
if not response:
|
||
|
return None
|
||
4 years ago
|
page, torrents_found = response.decode('cp1251'), -1
|
||
|
if first:
|
||
|
# check login status
|
||
|
if f'Выход [ {config["username"]} ]' not in page:
|
||
|
logger.debug("Looks like we lost session id, lets login")
|
||
|
self.login(MozillaCookieJar())
|
||
|
if self.error:
|
||
|
return None
|
||
|
# firstly we check if there is a result
|
||
|
torrents_found = int(RE_RESULTS.search(page)[1] or 0)
|
||
|
if not torrents_found:
|
||
|
return 0
|
||
6 years ago
|
self.draw(page)
|
||
|
|
||
4 years ago
|
return torrents_found
|
||
6 years ago
|
|
||
4 years ago
|
def _catch_error_request(self, url=None, data=None, repeated=False):
|
||
5 years ago
|
url = url or self.url
|
||
6 years ago
|
|
||
5 years ago
|
try:
|
||
4 years ago
|
with self.session.open(url, data, 5) as r:
|
||
|
# checking that tracker isn't blocked
|
||
|
if r.url.startswith((self.url, self.url_dl)):
|
||
|
return r.read()
|
||
5 years ago
|
raise URLError(f"{self.url} is blocked. Try another proxy.")
|
||
|
except (socket.error, socket.timeout) as err:
|
||
4 years ago
|
if not repeated:
|
||
5 years ago
|
return self._catch_error_request(url, data, True)
|
||
|
logger.error(err)
|
||
|
self.error = f"{self.url} is not response! Maybe it is blocked."
|
||
|
if "no host given" in err.args:
|
||
|
self.error = "Proxy is bad, try another!"
|
||
|
except (URLError, HTTPError) as err:
|
||
|
logger.error(err.reason)
|
||
|
self.error = err.reason
|
||
|
if hasattr(err, 'code'):
|
||
|
self.error = f"Request to {url} failed with status: {err.code}"
|
||
6 years ago
|
|
||
5 years ago
|
return None
|
||
6 years ago
|
|
||
5 years ago
|
def pretty_error(self, what):
|
||
|
prettyPrinter({"engine_url": self.url,
|
||
|
"desc_link": "https://github.com/imDMG/qBt_SE",
|
||
|
"name": f"[{unquote(what)}][Error]: {self.error}",
|
||
|
"link": self.url + "error",
|
||
|
"size": "1 TB", # lol
|
||
|
"seeds": 100,
|
||
|
"leech": 100})
|
||
6 years ago
|
|
||
5 years ago
|
self.error = None
|
||
6 years ago
|
|
||
|
|
||
4 years ago
|
# pep8
|
||
|
nnmclub = NNMClub
|
||
|
|
||
6 years ago
|
if __name__ == "__main__":
|
||
4 years ago
|
if BASEDIR.parent.joinpath('settings_gui.py').exists():
|
||
|
from settings_gui import EngineSettingsGUI
|
||
|
|
||
|
EngineSettingsGUI(FILENAME)
|
||
5 years ago
|
engine = nnmclub()
|
||
|
engine.search('doctor')
|