Skip to content

Instantly share code, notes, and snippets.

@andmatand
Last active November 14, 2015 06:07
Show Gist options
  • Save andmatand/20dce747d387d8828865 to your computer and use it in GitHub Desktop.
Save andmatand/20dce747d387d8828865 to your computer and use it in GitHub Desktop.
Library for adding specific torrent magnet links from an RSS feed to Transmission
#!/usr/bin/env python3
import re
import sys
import subprocess
import urllib.request
from xml.etree import ElementTree
from gzip import GzipFile
from io import BytesIO
def get_feed_xml(url):
response = urllib.request.urlopen(url)
data = response.read()
if response.info().get('Content-Encoding') == 'gzip':
buf = BytesIO(data)
f = GzipFile(fileobj=buf)
data = f.read()
text = data.decode('utf-8')
return ElementTree.fromstring(text)
# Return any magnet links in the feed
# titleFilter:
# A function which is called for each item and given the item's title
# as a parameter. If the function returns true, the item's magnet link
# is added to the list of returned magnet links.
def get_magnet_links(feedXml, titleFilter = None, tag = 'link'):
links = []
channel = feedXml[0]
for item in channel.findall('item'):
title = item.find('title').text
# If a titleFilter was given
if titleFilter:
titleIsOkay = titleFilter(title)
else:
# Otherwise accept all titles
titleIsOkay = true
if titleIsOkay:
link = item.find(tag)
if link != None:
links.append(link.text)
if len(links) > 0:
return links
else:
return None
def get_hash(magnetLink):
prog = re.compile('xt=urn:btih:([0-9A-Fa-f]{40})')
match = prog.search(magnetLink)
if match:
return match.group(1)
else:
return None
def torrent_exists(magnetLink):
# Get the hash part of the magnet link
torrentHash = get_hash(magnetLink)
if torrentHash == None: return false
output = subprocess.check_output(['transmission-remote',
'-t', torrentHash,
'--info'])
if output.strip():
return True
else:
return False
def add_torrent(magnetLink, downloadDirectory):
# If the torrent has not already been added to Transmission
if not torrent_exists(magnetLink):
subprocess.call(['transmission-remote',
'--download-dir', downloadDirectory,
'--add', magnetLink])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment