From 83a7da2bcf73e540bc32ab63dcdfa4e4813d5263 Mon Sep 17 00:00:00 2001 From: JackDandy Date: Sat, 31 Jul 2021 08:52:29 +0100 Subject: [PATCH] Change add compatibility for Transmission 3.00 client with label support. Change ensure cookies are split only into 2 parts at the lhs of multiple occurrences of '='. Remove provider Skytorrents. --- CHANGES.md | 9 +- gui/slick/images/providers/skytorrents.png | Bin 134 -> 0 bytes gui/slick/js/configSearch.js | 2 +- sickbeard/clients/transmission.py | 72 +++++++++---- sickbeard/providers/__init__.py | 2 +- sickbeard/providers/generic.py | 2 +- sickbeard/providers/skytorrents.py | 156 ----------------------------- 7 files changed, 63 insertions(+), 180 deletions(-) delete mode 100644 gui/slick/images/providers/skytorrents.png delete mode 100644 sickbeard/providers/skytorrents.py diff --git a/CHANGES.md b/CHANGES.md index 19c9fcd..6b98acf 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,4 +1,11 @@ -### 0.24.13 (2021-07-27 02:20:00 UTC) +### 0.24.14 (2021-07-31 08:50:00 UTC) + +* Change add compatibility for Transmission 3.00 client with label support +* Change ensure cookies are split only into 2 parts at the lhs of multiple occurrences of '=' +* Remove provider Skytorrents + + +### 0.24.13 (2021-07-27 02:20:00 UTC) * Fix incorrect reporting of missing provider detail diff --git a/gui/slick/images/providers/skytorrents.png b/gui/slick/images/providers/skytorrents.png deleted file mode 100644 index 2e032738554bab58ec54d353bd283031a166a97a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 134 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!D3?x-;bCrM;TYyi9>wgA@|Ns9x%9;oQMXWtt z978JNl7IZ4|L|jdTk(6zXLHkUluu8*AJta7i>G!c&v_9^ySJ%7N~b-%9^B?{FFC8u g_>cXW5C82Mq8%iwKRwG-2O7iR>FVdQ&MBb@0A&_0kN^Mx diff --git a/gui/slick/js/configSearch.js b/gui/slick/js/configSearch.js index 04759bd..f42b1c4 100644 --- a/gui/slick/js/configSearch.js +++ b/gui/slick/js/configSearch.js @@ -118,7 +118,7 @@ $(document).ready(function(){ $([hostDescDeluge, verifyCertOption, labelWarningDeluge].join(',')).show(); break; case 'transmission': - client = 'Transmission'; hideLabelOption = !0; hidePathBlank = !0; + client = 'Transmission'; hideLabelOption = !1; hidePathBlank = !0; $([transmission, highBandwidthOption].join(',')).show(); break; case 'qbittorrent': diff --git a/sickbeard/clients/transmission.py b/sickbeard/clients/transmission.py index 9b5868e..42ec03b 100755 --- a/sickbeard/clients/transmission.py +++ b/sickbeard/clients/transmission.py @@ -26,35 +26,54 @@ from _23 import b64encodestring class TransmissionAPI(GenericClient): + # RPC spec; https://github.com/transmission/transmission/blob/master/extras/rpc-spec.txt + def __init__(self, host=None, username=None, password=None): super(TransmissionAPI, self).__init__('Transmission', host, username, password) self.url = self.host + 'transmission/rpc' self.blankable, self.download_dir = None, None + self.rpc_version = 0 def _get_auth(self): + auth = None try: response = self.session.post(self.url, json={'method': 'session-get'}, timeout=120, verify=sickbeard.TORRENT_VERIFY_CERT) - self.auth = re.search(r'(?i)X-Transmission-Session-Id:\s*(\w+)', response.text).group(1) + auth = re.search(r'(?i)X-Transmission-Session-Id:\s*(\w+)', response.text).group(1) except (BaseException, Exception): - return None + try: + # noinspection PyUnboundLocalVariable + auth = response.headers.get('X-Transmission-Session-Id') + if not auth: + resp = response.json() + auth = resp['arguments']['session-id'] + except (BaseException, Exception): + pass + + if not self.auth: + if not auth: + return False + self.auth = auth self.session.headers.update({'x-transmission-session-id': self.auth}) # Validating Transmission authorization response = self._request(method='post', json={'method': 'session-get', 'arguments': {}}) + resp = {} try: resp = response.json() self.blankable = 14386 >= int(re.findall(r'.*[(](\d+)', resp.get('arguments', {}).get('version', '(0)'))[0]) - self.download_dir = resp.get('arguments', {}).get('download-dir', '') except (BaseException, Exception): pass - return self.auth + self.rpc_version = resp.get('arguments', {}).get('rpc-version', 0) + self.download_dir = resp.get('arguments', {}).get('download-dir', '') + client_text = '%s %s' % (self.name, resp.get('arguments', {}).get('version', '0').split()[0] or '') + return True, 'Success: Connected and authenticated to %s' % client_text def _add_torrent_uri(self, result): @@ -66,6 +85,11 @@ class TransmissionAPI(GenericClient): def _add_torrent(self, t_object): + # populate blankable and download_dir + if not self._get_auth(): + logger.log('%s: Authentication failed' % self.name, logger.ERROR) + return False + download_dir = None if sickbeard.TORRENT_PATH or self.blankable: download_dir = sickbeard.TORRENT_PATH @@ -82,6 +106,13 @@ class TransmissionAPI(GenericClient): return 'success' == response.json().get('result', '') + def _rpc_torrent_set(self, arguments): + try: + response = self._request(method='post', json={'method': 'torrent-set', 'arguments': arguments}) + return 'success' == response.json().get('result', '') + except(BaseException, Exception): + return False + def _set_torrent_ratio(self, result): ratio, mode = (result.ratio, None)[not result.ratio], 0 @@ -91,43 +122,44 @@ class TransmissionAPI(GenericClient): elif 0 <= float(ratio): ratio, mode = float(ratio), 1 # Stop seeding at seedRatioLimit - response = self._request(method='post', json={ - 'method': 'torrent-set', - 'arguments': {'ids': [result.hash], 'seedRatioLimit': ratio, 'seedRatioMode': mode}}) - - return 'success' == response.json().get('result', '') + return self._rpc_torrent_set(dict(ids=[result.hash], seedRatioLimit=ratio, seedRatioMode=mode)) def _set_torrent_seed_time(self, result): if result.provider.seed_time or (sickbeard.TORRENT_SEED_TIME and -1 != sickbeard.TORRENT_SEED_TIME): seed_time = result.provider.seed_time or sickbeard.TORRENT_SEED_TIME - response = self._request(method='post', json={ - 'method': 'torrent-set', - 'arguments': {'ids': [result.hash], 'seedIdleLimit': int(seed_time) * 60, 'seedIdleMode': 1}}) + return self._rpc_torrent_set(dict(ids=[result.hash], seedIdleLimit=int(seed_time) * 60, seedIdleMode=1)) - return 'success' == response.json().get('result', '') return True def _set_torrent_priority(self, result): - arguments = {'ids': [result.hash]} + arguments = dict(ids=[result.hash]) + level = 'priority-normal' if -1 == result.priority: - arguments['priority-low'] = [] + level = 'priority-low' elif 1 == result.priority: # set high priority for all files in torrent - arguments['priority-high'] = [] + level = 'priority-high' # move torrent to the top if the queue arguments['queuePosition'] = 0 if sickbeard.TORRENT_HIGH_BANDWIDTH: arguments['bandwidthPriority'] = 1 - else: - arguments['priority-normal'] = [] - response = self._request(method='post', json={'method': 'torrent-set', 'arguments': arguments}) + arguments[level] = [] - return 'success' == response.json().get('result', '') + return self._rpc_torrent_set(arguments) + + def _set_torrent_label(self, search_result): + + label = sickbeard.TORRENT_LABEL + + if 16 > self.rpc_version or not label: + return super(TransmissionAPI, self)._set_torrent_label(search_result) + + return self._rpc_torrent_set(dict(ids=[search_result.hash], labels=label.split(','))) api = TransmissionAPI() diff --git a/sickbeard/providers/__init__.py b/sickbeard/providers/__init__.py index b5b1133..989acc1 100755 --- a/sickbeard/providers/__init__.py +++ b/sickbeard/providers/__init__.py @@ -42,7 +42,7 @@ __all__ = [ 'hdbits', 'hdme', 'hdspace', 'hdtorrents', 'immortalseed', 'iptorrents', 'limetorrents', 'magnetdl', 'milkie', 'morethan', 'nebulance', 'ncore', 'nyaa', 'pretome', 'privatehd', 'ptf', - 'rarbg', 'revtt', 'scenehd', 'scenetime', 'shazbat', 'showrss', 'skytorrents', 'snowfl', 'speedapp', 'speedcd', + 'rarbg', 'revtt', 'scenehd', 'scenetime', 'shazbat', 'showrss', 'snowfl', 'speedapp', 'speedcd', 'thepiratebay', 'torlock', 'torrentday', 'torrenting', 'torrentleech', 'tvchaosuk', 'xspeeds', 'zooqle', # anime diff --git a/sickbeard/providers/generic.py b/sickbeard/providers/generic.py index f398ddb..a7ed1e7 100644 --- a/sickbeard/providers/generic.py +++ b/sickbeard/providers/generic.py @@ -1357,7 +1357,7 @@ class GenericProvider(object): dict(p=self.name, r='\'%s\'' % reqd) cj = requests.utils.add_dict_to_cookiejar(self.session.cookies, - dict([x.strip().split('=') for x in cookies.split(';') + dict([x.strip().split('=', 1) for x in cookies.split(';') if '' != x])), for item in cj: if not isinstance(item, requests.cookies.RequestsCookieJar): diff --git a/sickbeard/providers/skytorrents.py b/sickbeard/providers/skytorrents.py deleted file mode 100644 index 8e544b9..0000000 --- a/sickbeard/providers/skytorrents.py +++ /dev/null @@ -1,156 +0,0 @@ -# coding=utf-8 -# -# This file is part of SickGear. -# -# SickGear is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# SickGear is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with SickGear. If not, see . - -import re -import traceback - -from . import generic -from .. import logger -from ..helpers import try_int -from bs4_parser import BS4Parser - -from _23 import unidecode -from six import iteritems - - -class SkytorrentsProvider(generic.TorrentProvider): - - def __init__(self): - - generic.TorrentProvider.__init__(self, 'Skytorrents') - - self.url_home = ['https://skytorrents.%s/' % tld for tld in ('org', 'to', 'net')] - - self.url_vars = {'search': '?search=%s&sort=created&page=%s'} - self.url_tmpl = {'config_provider_home_uri': '%(home)s', 'search': '%(home)s%(vars)s'} - - self.minseed, self.minleech = 2 * [None] - - @staticmethod - def _has_signature(data=None): - return data and re.search(r'Sky\sTorrents', data[23:1024:]) - - def _search_provider(self, search_params, **kwargs): - results = [] - self.session.headers['Cache-Control'] = 'max-age=0' - last_recent_search = self.last_recent_search - last_recent_search = '' if not last_recent_search else last_recent_search.replace('id-', '') - for mode in search_params: - urls = [] - for search_string in search_params[mode]: - urls += [[]] - search_string = unidecode(search_string) - search_string = search_string if 'Cache' == mode else search_string.replace('.', ' ') - for page in range((3, 5)['Cache' == mode])[1:]: - urls[-1] += [self.urls['search'] % (search_string, page)] - results += self._search_urls(mode, last_recent_search, urls) - last_recent_search = '' - - return results - - def _search_urls(self, mode, last_recent_search, urls): - - results = [] - items = {'Cache': [], 'Season': [], 'Episode': [], 'Propers': []} - - rc = dict([(k, re.compile('(?i)' + v)) for (k, v) in iteritems({ - 'info': r'(^(info|torrent)/|/[\w+]{40,}\s*$)', 'get': '^magnet:.*?btih:([^&]+)'})]) - - lrs_found = False - lrs_new = True - for search_urls in urls: # this intentionally iterates once to preserve indentation - for search_url in search_urls: - html = self.get_url(search_url) - if self.should_skip(): - return results - - cnt = len(items[mode]) - cnt_search = 0 - try: - if not html or self._has_no_results(html): - raise generic.HaltParseException - - parse_only = dict(table={'class': (lambda at: at and 'is-striped' in at)}) - with BS4Parser(html, parse_only=parse_only, preclean=True) as tbl: - tbl_rows = [] if not tbl else tbl.find_all('tr') - - if 2 > len(tbl_rows): - raise generic.HaltParseException - - head = None - for tr in tbl_rows[1:]: - cells = tr.find_all('td') - if 5 > len(cells): - continue - cnt_search += 1 - try: - head = head if None is not head else self._header_row(tr) - - dl = tr.find('a', href=rc['get'])['href'] - dl_id = rc['get'].findall(dl)[0] - lrs_found = dl_id == last_recent_search - if lrs_found: - break - - seeders, leechers, size = [try_int(n, n) for n in [ - cells[head[x]].get_text().strip() for x in ('seed', 'leech', 'size')]] - if self._reject_item(seeders, leechers): - continue - - info = tr.select_one( - '[alt*="magnet"], [title*="magnet"]') \ - or tr.find('a', href=rc['info']) - title = re.sub(r'(^www\.\w+\.\w{3}\s[^0-9A-Za-z]\s|\s(using|use|magnet|link))', '', ( - info.attrs.get('title') or info.attrs.get('alt'))).strip() - download_url = self._link(dl) - except (AttributeError, TypeError, ValueError, KeyError): - continue - - if title and download_url: - items[mode].append((title, download_url, seeders, self._bytesizer(size))) - - except generic.HaltParseException: - pass - except (BaseException, Exception): - logger.log(u'Failed to parse. Traceback: %s' % traceback.format_exc(), logger.ERROR) - - self._log_search(mode, len(items[mode]) - cnt, search_url) - - if self.is_search_finished(mode, items, cnt_search, rc['get'], last_recent_search, lrs_new, lrs_found): - break - lrs_new = False - - results = self._sort_seeding(mode, results + items[mode]) - - return results - - def _cache_data(self, **kwargs): - result_1 = self._search_provider({'Cache': ['x264']}) - lrs_1 = self.last_recent_search - - self.last_recent_search = None - name_1 = self.name - self.name += '2' - result_2 = self._search_provider({'Cache': ['x265']}) - - self.name = name_1 - self.last_recent_search = lrs_1 - - return result_1 + result_2 - - -provider = SkytorrentsProvider()