torrentbytes.py 6.75 KB
Newer Older
1
# Author: echel0n <[email protected]>
echel0n's avatar
echel0n committed
2
# URL: https://sickrage.ca
root's avatar
root committed
3
#
4
# This file is part of SickRage.
root's avatar
root committed
5
6
7
8
9
10
11
12
13
#
# SickRage 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.
#
# SickRage 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
14
# GNU General Public License for more details.
root's avatar
root committed
15
16
17
18
#
# You should have received a copy of the GNU General Public License
# along with SickRage.  If not, see <http://www.gnu.org/licenses/>.

19
20
from __future__ import unicode_literals

root's avatar
root committed
21
import re
echel0n's avatar
echel0n committed
22
23
24
from urlparse import urljoin

from requests.utils import dict_from_cookiejar
25

26
import sickrage
echel0n's avatar
echel0n committed
27
from sickrage.core.caches.tv_cache import TVCache
28
from sickrage.core.helpers import bs4_parser, convert_size, try_int
29
from sickrage.providers import TorrentProvider
root's avatar
root committed
30
31


32
class TorrentBytesProvider(TorrentProvider):
root's avatar
root committed
33
    def __init__(self):
echel0n's avatar
echel0n committed
34
        super(TorrentBytesProvider, self).__init__("TorrentBytes", 'https://www.torrentbytes.net', True)
root's avatar
root committed
35

36
        self.urls.update({
echel0n's avatar
echel0n committed
37
            'login': '{base_url}/takelogin.php'.format(**self.urls),
echel0n's avatar
echel0n committed
38
            'search': '{base_url}/browse.php'.format(**self.urls),
39
        })
root's avatar
root committed
40

echel0n's avatar
echel0n committed
41
42
43
44
45
46
47
        self.username = None
        self.password = None

        self.minseed = None
        self.minleech = None
        self.freeleech = False

Dustyn Gibson's avatar
Dustyn Gibson committed
48
49
        self.proper_strings = ['PROPER', 'REPACK']

echel0n's avatar
echel0n committed
50
        self.cache = TVCache(self, min_time=20)
Dustyn Gibson's avatar
Dustyn Gibson committed
51

echel0n's avatar
echel0n committed
52
    def login(self):
echel0n's avatar
echel0n committed
53
54
        if any(dict_from_cookiejar(sickrage.srCore.srWebSession.cookies).values()):
            return True
root's avatar
root committed
55
56
57

        login_params = {'username': self.username,
                        'password': self.password,
58
                        'login': 'Log in!'}
root's avatar
root committed
59

60
        try:
61
            response = sickrage.srCore.srWebSession.post(self.urls['login'], data=login_params, timeout=30).text
62
        except Exception:
63
            sickrage.srCore.srLogger.warning("[{}]: Unable to connect to provider".format(self.name))
root's avatar
root committed
64
65
            return False

66
        if re.search('Username or password incorrect', response):
echel0n's avatar
echel0n committed
67
68
            sickrage.srCore.srLogger.warning(
                "[{}]: Invalid username or password. Check your settings".format(self.name))
root's avatar
root committed
69
70
71
72
            return False

        return True

73
    def search(self, search_strings, age=0, ep_obj=None):
root's avatar
root committed
74
75
        results = []

echel0n's avatar
echel0n committed
76
        if not self.login():
77
            return results
root's avatar
root committed
78

echel0n's avatar
echel0n committed
79
80
81
82
83
        search_params = {
            "Episode": {"c33": 1, "c38": 1, "c32": 1, "c37": 1},
            "Season": {"c41": 1}
        }

84
        for mode in search_strings:
85
            sickrage.srCore.srLogger.debug("Search Mode: %s" % mode)
86
            for search_string in search_strings[mode]:
87
                if mode != 'RSS':
88
                    sickrage.srCore.srLogger.debug("Search string: %s " % search_string)
root's avatar
root committed
89

echel0n's avatar
echel0n committed
90
                search_params[mode]["search"] = search_string
root's avatar
root committed
91

92
                try:
echel0n's avatar
echel0n committed
93
                    data = sickrage.srCore.srWebSession.get(self.urls['search'], params=search_params).text
94
                except Exception:
95
                    sickrage.srCore.srLogger.debug("No data returned from provider")
root's avatar
root committed
96
97
98
                    continue

                try:
99
                    with bs4_parser(data) as html:
echel0n's avatar
echel0n committed
100
101
102
103
104
                        torrent_table = html.find("table", border="1")
                        torrent_rows = torrent_table("tr") if torrent_table else []

                        # Continue only if at least one Release is found
                        if len(torrent_rows) < 2:
105
                            sickrage.srCore.srLogger.debug("Data returned from provider does not contain any torrents")
root's avatar
root committed
106
107
                            continue

echel0n's avatar
echel0n committed
108
109
                        # "Type", "Name", Files", "Comm.", "Added", "TTL", "Size", "Snatched", "Seeders", "Leechers"
                        labels = [label.get_text(strip=True) for label in torrent_rows[0]("td")]
110

111
                        for result in torrent_rows[1:]:
echel0n's avatar
echel0n committed
112
113
                            try:
                                cells = result("td")
114

echel0n's avatar
echel0n committed
115
116
                                link = cells[labels.index("Name")].find("a", href=re.compile(r"download.php\?id="))["href"]
                                download_url = urljoin(self.urls['base_url'], link)
117

echel0n's avatar
echel0n committed
118
119
120
121
                                title_element = cells[labels.index("Name")].find("a", href=re.compile(r"details.php\?id="))
                                title = title_element.get("title", "") or title_element.get_text(strip=True)
                                if not all([title, download_url]):
                                    continue
122

echel0n's avatar
echel0n committed
123
124
125
126
127
                                if self.freeleech:
                                    # Free leech torrents are marked with green [F L] in the title (i.e. <font color=green>[F&nbsp;L]</font>)
                                    freeleech = cells[labels.index("Name")].find("font", color="green")
                                    if not freeleech or freeleech.get_text(strip=True) != "[F\xa0L]":
                                        continue
128

echel0n's avatar
echel0n committed
129
130
                                seeders = try_int(cells[labels.index("Seeders")].get_text(strip=True))
                                leechers = try_int(cells[labels.index("Leechers")].get_text(strip=True))
131

echel0n's avatar
echel0n committed
132
133
134
135
136
137
138
                                # Filter unseeded torrent
                                if seeders < self.minseed or leechers < self.minleech:
                                    if mode != "RSS":
                                        sickrage.srCore.srLogger.debug(
                                            "Discarding torrent because it doesn't meet the minimum seeders or leechers: "
                                            "{} (S:{} L:{})".format(title, seeders, leechers))
                                        continue
fernandog's avatar
fernandog committed
139

echel0n's avatar
echel0n committed
140
141
                                torrent_size = cells[labels.index("Size")].get_text(strip=True)
                                size = convert_size(torrent_size, -1)
root's avatar
root committed
142

echel0n's avatar
echel0n committed
143
144
                                item = {'title': title, 'link': download_url, 'size': size, 'seeders': seeders,
                                        'leechers': leechers, 'hash': ''}
root's avatar
root committed
145

echel0n's avatar
echel0n committed
146
147
                                if mode != "RSS":
                                    sickrage.srCore.srLogger.debug("Found result: {}".format(title))
root's avatar
root committed
148

echel0n's avatar
echel0n committed
149
150
151
                                results.append(item)
                            except (AttributeError, TypeError, ValueError):
                                continue
152
153
                except Exception:
                    sickrage.srCore.srLogger.error("Failed parsing provider.")
root's avatar
root committed
154

155
156
        # Sort all the items by seeders if available
        results.sort(key=lambda k: try_int(k.get('seeders', 0)), reverse=True)
root's avatar
root committed
157
158

        return results