Skip to content

Commit

Permalink
reverseproxy and rcp url
Browse files Browse the repository at this point in the history
  • Loading branch information
Hellowlol committed Oct 26, 2014
1 parent e1d37b3 commit 0074eda
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 21 deletions.
3 changes: 1 addition & 2 deletions interfaces/default/html/transmission.html
Expand Up @@ -3,12 +3,11 @@
<div class="container">
<div class="content">
<h1 class="page-header page-title">
<a href="http://${settings.get('transmission_host')}:${settings.get('transmission_port')}" target="_blank">${settings.get('transmission_name', 'Transmission')}</a>
<a href="http://${settings.get('transmission_host')}:${settings.get('transmission_port')}${settings.get('transmission_revproxy', '/')}" target="_blank">${settings.get('transmission_name', 'Transmission')}</a>
<small>
<i class="icon-arrow-down"></i> <span id="queue_download"></span>
<i class="icon-arrow-up"></i> <span id="queue_upload"></span>
</small>

<div class="btn-group pull-right">
<a class="btn btn-mini dropdown-toggle" data-toggle="dropdown" href="#">Actions <span class="caret"></span></a>
<ul class="dropdown-menu">
Expand Down
119 changes: 100 additions & 19 deletions modules/transmission.py
Expand Up @@ -9,6 +9,7 @@
import logging
from cherrypy.lib.auth2 import require


class Transmission:
# Transmission Session ID
sessionId = ''
Expand All @@ -22,18 +23,20 @@ def __init__(self):
'fields': [
{'type': 'bool', 'label': 'Enable', 'name': 'transmission_enable'},
{'type': 'text', 'label': 'Menu name', 'name': 'transmission_name'},
{'type': 'text', 'label': 'IP / Host', 'placeholder':'localhost', 'name': 'transmission_host'},
{'type': 'text', 'label': 'Port', 'placeholder':'9091', 'name': 'transmission_port'},
{'type': 'text', 'label': 'IP / Host', 'placeholder': 'localhost', 'name': 'transmission_host'},
{'type': 'text', 'label': 'Port', 'placeholder': '9091', 'name': 'transmission_port'},
{'type': 'text', 'label': 'Reverse Proxy', 'placeholder': '', 'name': 'transmission_revproxy'},
{'type': 'text', 'label': 'Rpc url', 'placeholder': '', 'name': 'transmission_rpcbasepath'},
{'type': 'text', 'label': 'Username', 'name': 'transmission_username'},
{'type': 'password', 'label': 'Password', 'name': 'transmission_password'}
]})
]
})

@cherrypy.expose()
@require()
def index(self):
return htpc.LOOKUP.get_template('transmission.html').render(scriptname='transmission')


@cherrypy.expose()
@require()
@cherrypy.tools.json_out()
Expand All @@ -50,9 +53,77 @@ def stats(self):
@cherrypy.expose()
@require()
@cherrypy.tools.json_out()
def start(self, torrentId = False):
def ping(self, **kwargs):
""" Test connection to Transmission """
host = kwargs["transmission_host"]
port = kwargs["transmission_port"]
username = kwargs["transmission_username"]
password = kwargs["transmission_password"]
basepath = kwargs["transmission_rpcbasepath"]

if basepath:
if not basepath.startswith('/'):
basepath = '/%s' % basepath
if not basepath.endswith('/'):
basepath += '/'
else:
# Default basepath is transmission
basepath = '/transmission/'

url = 'http://' + host + ':' + str(port) + basepath + 'rpc/'

# format post data
data = {'method': 'session-get'}
data = dumps(data)

# Set Header
header = {
'X-Transmission-Session-Id': self.sessionId,
'Content-Type': 'json; charset=UTF-8'
}

# Add authentication
if username and password:
authentication = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
header['Authorization'] = "Basic %s" % authentication

try:
request = urllib2.Request(url, data=data, headers=header)
response = urllib2.urlopen(request).read()
return loads(response)
except urllib2.HTTPError, e:
# Fetching url failed Maybe Transmission session must be renewed
if (e.getcode() == 409 and e.headers['X-Transmission-Session-Id']):
self.logger.debug("Setting new session ID provided by Transmission")

# If response is 409 re-set session id from header
self.sessionId = e.headers['X-Transmission-Session-Id']

self.logger.debug("Retry Transmission api with new session id.")
try:
header['X-Transmission-Session-Id'] = self.sessionId

req = urllib2.Request(url, data=data, headers=header)
response = urllib2.urlopen(req).read()
return loads(response)
except:
self.logger.error("Unable access Transmission api with new session id.")
return
except Exception:
self.logger.error("Unable to fetch information from: " + url)
return

@cherrypy.expose()
@cherrypy.tools.json_out()
def session(self):
return self.fetch('session-get')

@cherrypy.expose()
@require()
@cherrypy.tools.json_out()
def start(self, torrentId=False):

if (torrentId == False) :
if torrentId is False:
return self.fetch('torrent-start-now')

try:
Expand All @@ -64,9 +135,9 @@ def start(self, torrentId = False):
@cherrypy.expose()
@require()
@cherrypy.tools.json_out()
def stop(self, torrentId = False):
def stop(self, torrentId=False):

if (torrentId == False) :
if torrentId is False:
return self.fetch('torrent-stop')

try:
Expand All @@ -79,8 +150,8 @@ def stop(self, torrentId = False):
@require()
@cherrypy.tools.json_out()
def Add(self, filename):
return self.fetch('torrent-add', {'filename': filename})
return self.fetch('torrent-add', {'filename': filename})

@cherrypy.expose()
@require()
@cherrypy.tools.json_out()
Expand All @@ -95,17 +166,28 @@ def remove(self, torrentId):
# If the first call fails, there probably is no valid Session ID so we try it again
def fetch(self, method, arguments=''):
""" Do request to Transmission api """
self.logger.debug("Request transmission method: "+method)
self.logger.debug("Request transmission method: " + method)

host = htpc.settings.get('transmission_host', '')
port = str(htpc.settings.get('transmission_port', ''))

url = 'http://' + host + ':' + str(port) + '/transmission/rpc/'
# Default basepath is transmission
basepath = htpc.settings.get('transmission_rpcbasepath', '/transmission/')

if basepath:
if not basepath.startswith('/'):
basepath = '/%s' % basepath
if not basepath.endswith('/'):
basepath += '/'
else:
basepath = '/transmission/'

url = 'http://' + host + ':' + str(port) + basepath + 'rpc/'

# format post data
data = {'method': method}
if (arguments != ''):
data['arguments'] = arguments
if arguments:
data['arguments'] = arguments
data = dumps(data)

# Set Header
Expand All @@ -116,7 +198,7 @@ def fetch(self, method, arguments=''):

# Add authentication
authentication = self.auth()
if (authentication) :
if authentication:
header['Authorization'] = "Basic %s" % authentication

try:
Expand All @@ -125,7 +207,7 @@ def fetch(self, method, arguments=''):
return loads(response)
except urllib2.HTTPError, e:
# Fetching url failed Maybe Transmission session must be renewed
if (e.getcode() == 409 and e.headers['X-Transmission-Session-Id']) :
if (e.getcode() == 409 and e.headers['X-Transmission-Session-Id']):
self.logger.debug("Setting new session ID provided by Transmission")

# If response is 409 re-set session id from header
Expand All @@ -145,7 +227,6 @@ def fetch(self, method, arguments=''):
self.logger.error("Unable to fetch information from: " + url)
return


# Construct url with login details
def auth(self):
""" Generate a base64 HTTP auth string based on settings """
Expand All @@ -154,7 +235,7 @@ def auth(self):
password = htpc.settings.get('transmission_password', '')
username = htpc.settings.get('transmission_username', '')

if username != '' and password != '':
if username and password:
return base64.encodestring('%s:%s' % (username, password)).replace('\n', '')

return False
return False

0 comments on commit 0074eda

Please sign in to comment.