Skip to content

Instantly share code, notes, and snippets.

@spaghetti2514
Forked from cburmeister/freeleech.py
Last active December 25, 2015 09:29
Show Gist options
  • Save spaghetti2514/6953953 to your computer and use it in GitHub Desktop.
Save spaghetti2514/6953953 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# freeleech.py originally by tobbez
# Now maintained at github.com/spaghetti2514/What.cd-Freeleech
import os
import re
import sys
import json
import time
import getopt
import requests
import HTMLParser
from getpass import getpass
# Pretend to be IE
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
}
def download_torrent(session, tid, path):
try:
if location in globals():
path = os.path.join(location, path)
except NameError:
pass
if os.path.exists(path):
if not quiet and not daemon:
print '{} already downloaded, skipping'.format(tid)
return
if not hasattr(download_torrent, 'authdata'):
r = session.get('https://what.cd/ajax.php?action=index', headers=headers)
d = json.loads(r.content)
download_torrent.authdata = '&authkey={}&torrent_pass={}'.format(d['response']['authkey'], d['response']['passkey'])
if not quiet:
print 'Downloading {}...'.format(tid),
dl = session.get('https://what.cd/torrents.php?action=download&id={}{}'.format(tid, download_torrent.authdata), headers=headers)
with open(path, 'wb') as f:
for chunk in dl.iter_content(1024*1024):
f.write(chunk)
print 'Done'
def main(argv):
global quiet, daemon
quiet, daemon = False, False
try:
opts, args = getopt.getopt(argv, "qu:p:l:d:", ["quiet", "user=", "pass=", "location=", "daemonize="])
except getopt.GetoptError:
print "usage: freeleech.py [-(-q)uiet -(-u)ser <username> -(-p)ass <password> -(-l)ocation <path> -(-d)aemonize <seconds to pause>]"
sys.exit(2)
for opt, arg in opts:
if opt in ("-q", "--quiet"):
quiet = True
elif opt in ("-d", "--daemonize"):
daemon = True
daelay = arg
elif opt in ("-u", "--user"):
user = arg
elif opt in ("-p", "--pass"):
password = arg
elif opt in ("-l", "--location"):
global location
location = arg
if not os.path.exists(location):
os.mkdir(location)
try:
user
except NameError:
user = raw_input("What.CD Username: ")
try:
password
except NameError:
password = getpass("What.CD Password: ")
search_params = 'search=&freetorrent=1'
html_parser = HTMLParser.HTMLParser()
fcre = re.compile('''[/\\?*:|"<>]''')
clean_fn = lambda x: fcre.sub('', html_parser.unescape(x))
s = requests.session()
r = s.post('https://what.cd/login.php', data={'username': user, 'password': password}, headers=headers)
if r.url != u'https://what.cd/index.php':
print "Login failed"
return
page = 1
while True:
r = s.get('https://what.cd/ajax.php?action=browse&' + search_params + "&page={}".format(page), headers=headers)
data = json.loads(r.content)
for group in data['response']['results']:
if 'torrents' in group:
for torrent in group['torrents']:
if not torrent['isFreeleech']:
continue
fn = clean_fn('{}. {} - {} - {} ({} - {} - {}).torrent'.format(torrent['torrentId'], group['artist'][:50], group['groupYear'], group['groupName'][:50], torrent['media'], torrent['format'], torrent['encoding']))
download_torrent(s, torrent['torrentId'], fn)
else:
fn = clean_fn('{}. {}.torrent'.format(group['torrentId'], group['groupName'][:100]))
download_torrent(s, group['torrentId'], fn)
time.sleep(2)
page += 1
if page > data['response']['pages']:
if daemon:
page = 1
time.sleep(float(daelay))
else:
break
if not quiet:
print "Done"
if __name__ == '__main__':
main(sys.argv[1:])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment