Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 122 lines (81 sloc) 3.61 KB
#!/usr/bin/env python
'''Module rt_broswer presents RutrackerBrowser.
It allows getting .torrent files from RuTracker.Org.'''
import cookielib
import re
import urllib
import urllib2
class RutrackerBrowserError(RuntimeError):
'''RutrackerBrowserError raise on runtime errors.'''
class RutrackerBrowser(object):
'''Class RutrackerBrowser presents browser for RuTracker.Org.
It allows logging in and getting .torrent files from RuTracker.Org.'''
_topic_re = re.compile('[\s/?&]t=(\d+)')
def __init__(self, login, password):
'''Initialises browser, stores RuTracker.Org's login and password.
login - login;
password - password.'''
self._login = login
self._password = password
self._cookie_jar = cookielib.CookieJar()
self._url_opener = urllib2.build_opener(
def login(self):
'''Logs in RuTracker.Org.
This method should be called before any attempts to get some
.torrent files.'''
data = {
'login_username': self._login,
'login_password': self._password,
'login' : '%C2%F5%EE%E4'
resp =
if not resp:
raise RutrackerBrowserError('could not login')
if 'login.php' in resp.geturl():
raise RutrackerBrowserError('could not login: %s\n\n%s' %
def check_topic_url(topic_url):
'''Raises exception if topic_url is not valid.'''
match =
if not match:
mess = "'%s' is not a valid topic url" % topic_url
raise RutrackerBrowserError(mess)
def open_topic_url(self, topic_url):
'''Returns filelike object on succesfull topic getting.
topic_url - url with viewtopic.php?t=3656915.
Not necessary method.'''
req = urllib2.Request(topic_url)
req.add_header('Referer', '')
res =
return res
def get_torrent(self, topic_url):
'''Returns filelike object with .torrent as its contents.
topic_url - url with viewtopic.php?t=3656915.
Use this method only for logined browser.'''
res = self.open_topic_url(topic_url)
# I need to get smth from auth cookie,
# combine this parts + bb_dl=%(topic_id)s
match =
topic_id =
dl_url = '' % topic_id
req = urllib2.Request(dl_url)
req.add_header('Referer', topic_url)
self._cookie_jar.set_cookie(cookielib.Cookie(version=0, name='bb_dl', value=topic_id, port=None, port_specified=False, domain='', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False))
res =
return res
#if __name__ == '__main__':
# b = RutrackerBrowser('login', 'password')
# b.login()
# res = b.get_torrent('')
# with open('test.torrent', 'wb') as f:
# f.write(