[Py2to3] Fixes to display Web UI

This commit is contained in:
Calum Lind 2018-07-29 12:19:44 +01:00
commit 0fd3c25684
7 changed files with 39 additions and 34 deletions

View file

@ -715,7 +715,7 @@ def get_magnet_info(uri):
except TypeError as ex: except TypeError as ex:
log.debug('Invalid base32 magnet hash: %s, %s', xt_hash, ex) log.debug('Invalid base32 magnet hash: %s, %s', xt_hash, ex)
break break
info_hash = binascii.hexlify(infohash_str) info_hash = binascii.hexlify(infohash_str).decode()
elif is_infohash(xt_hash): elif is_infohash(xt_hash):
info_hash = xt_hash.lower() info_hash = xt_hash.lower()
else: else:

View file

@ -173,7 +173,7 @@ class WebAPITestCase(WebServerTestBase):
bad_body = b'{ method": "auth.login" }' bad_body = b'{ method": "auth.login" }'
d = yield agent.request( d = yield agent.request(
b'POST', b'POST',
b'http://127.0.0.1:%s/json' % self.webserver_listen_port, b'http://127.0.0.1:%i/json' % self.webserver_listen_port,
Headers({ Headers({
b'User-Agent': [b'Twisted Web Client Example'], b'User-Agent': [b'Twisted Web Client Example'],
b'Content-Type': [b'application/json'], b'Content-Type': [b'application/json'],

View file

@ -18,8 +18,6 @@ from twisted.trial.unittest import SkipTest
from twisted.web.client import Agent, FileBodyProducer from twisted.web.client import Agent, FileBodyProducer
from twisted.web.http_headers import Headers from twisted.web.http_headers import Headers
from deluge.common import utf8_encode_structure
from . import common from . import common
from .common import get_test_data_file from .common import get_test_data_file
from .common_web import WebServerMockBase, WebServerTestBase from .common_web import WebServerMockBase, WebServerTestBase
@ -43,19 +41,19 @@ class WebServerTestCase(WebServerTestBase, WebServerMockBase):
filename = get_test_data_file('filehash_field.torrent') filename = get_test_data_file('filehash_field.torrent')
input_file = '{"params": ["%s"], "method": "web.get_torrent_info", "id": 22}' % filename input_file = '{"params": ["%s"], "method": "web.get_torrent_info", "id": 22}' % filename
headers = { headers = {
'User-Agent': ['Twisted Web Client Example'], b'User-Agent': ['Twisted Web Client Example'],
'Content-Type': ['application/json'], b'Content-Type': ['application/json'],
} }
url = 'http://127.0.0.1:%s/json' % self.webserver_listen_port url = 'http://127.0.0.1:%s/json' % self.webserver_listen_port
d = yield agent.request( d = yield agent.request(
b'POST', url.encode('utf-8'), Headers(utf8_encode_structure(headers)), b'POST',
url.encode('utf-8'),
Headers(headers),
FileBodyProducer(BytesIO(input_file.encode('utf-8'))), FileBodyProducer(BytesIO(input_file.encode('utf-8'))),
) )
try:
body = yield twisted.web.client.readBody(d) body = yield twisted.web.client.readBody(d)
except AttributeError:
raise SkipTest('This test requires "t.w.c.readBody()" in Twisted version >= 13.2')
json = json_lib.loads(body) json = json_lib.loads(body)
self.assertEqual(None, json['error']) self.assertEqual(None, json['error'])

View file

@ -73,7 +73,10 @@ class TermResizeHandler(object):
def on_terminal_size(self, *args): def on_terminal_size(self, *args):
# Get the new rows and cols value # Get the new rows and cols value
rows, cols = struct.unpack('hhhh', ioctl(0, termios.TIOCGWINSZ, '\000' * 8))[0:2] rows, cols = struct.unpack(
'hhhh',
ioctl(0, termios.TIOCGWINSZ, b'\000' * 8)
)[0:2]
curses.resizeterm(rows, cols) curses.resizeterm(rows, cols)
return rows, cols return rows, cols

View file

@ -35,7 +35,7 @@
<script type="text/javascript" src="${base}${script}"></script> <script type="text/javascript" src="${base}${script}"></script>
% endfor % endfor
<script type="text/javascript"> <script type="text/javascript">
Deluge.debug = ${str(debug).lower()}; Deluge.debug = ${debug};
</script> </script>
</head> </head>
<body> <body>

View file

@ -9,7 +9,6 @@
from __future__ import division, unicode_literals from __future__ import division, unicode_literals
import cgi
import json import json
import logging import logging
import os import os
@ -17,6 +16,7 @@ import shutil
import tempfile import tempfile
from base64 import b64encode from base64 import b64encode
from types import FunctionType from types import FunctionType
from xml.sax.saxutils import escape as xml_escape
from twisted.internet import defer, reactor from twisted.internet import defer, reactor
from twisted.internet.defer import Deferred, DeferredList from twisted.internet.defer import Deferred, DeferredList
@ -541,7 +541,7 @@ class WebApi(JSONComponent):
paths = [] paths = []
info = {} info = {}
for index, torrent_file in enumerate(files): for index, torrent_file in enumerate(files):
path = cgi.escape(torrent_file['path']) path = xml_escape(torrent_file['path'])
paths.append(path) paths.append(path)
torrent_file['progress'] = file_progress[index] torrent_file['progress'] = file_progress[index]
torrent_file['priority'] = file_priorities[index] torrent_file['priority'] = file_priorities[index]
@ -583,9 +583,9 @@ class WebApi(JSONComponent):
try: try:
if key == 'peers': if key == 'peers':
for peer in torrent[key]: for peer in torrent[key]:
peer['client'] = cgi.escape(peer['client']) peer['client'] = xml_escape(peer['client'])
else: else:
torrent[key] = cgi.escape(torrent[key]) torrent[key] = xml_escape(torrent[key])
except KeyError: except KeyError:
pass pass
d.callback(torrent) d.callback(torrent)

View file

@ -91,7 +91,7 @@ class MockGetText(resource.Resource):
""" """
def render(self, request): def render(self, request):
request.setHeader(b'content-type', b'text/javascript; encoding=utf-8') request.setHeader(b'content-type', b'text/javascript; encoding=utf-8')
data = 'function _(string) { return string; }' data = b'function _(string) { return string; }'
return compress(data, request) return compress(data, request)
@ -209,10 +209,10 @@ class Flag(resource.Resource):
filename = common.resource_filename('deluge', os.path.join(*path)) filename = common.resource_filename('deluge', os.path.join(*path))
if os.path.exists(filename): if os.path.exists(filename):
request.setHeader( request.setHeader(
'cache-control', b'cache-control',
'public, must-revalidate, max-age=86400', b'public, must-revalidate, max-age=86400',
) )
request.setHeader('content-type', 'image/png') request.setHeader(b'content-type', b'image/png')
with open(filename, 'rb') as _file: with open(filename, 'rb') as _file:
data = _file.read() data = _file.read()
request.setResponseCode(http.OK) request.setResponseCode(http.OK)
@ -250,16 +250,16 @@ class LookupResource(resource.Resource, component.Component):
def render(self, request): def render(self, request):
log.debug('Requested path: %s', request.lookup_path) log.debug('Requested path: %s', request.lookup_path)
path = os.path.dirname(request.lookup_path) path = os.path.dirname(request.lookup_path).decode()
if path in self.__paths: if path in self.__paths:
filename = os.path.basename(request.path) filename = os.path.basename(request.path).decode()
for directory in self.__paths[path]: for directory in self.__paths[path]:
if os.path.join(directory, filename): if os.path.join(directory, filename):
path = os.path.join(directory, filename) path = os.path.join(directory, filename)
log.debug('Serving path: %s', path) log.debug('Serving path: %s', path)
mime_type = mimetypes.guess_type(path) mime_type = mimetypes.guess_type(path)
request.setHeader(b'content-type', mime_type[0]) request.setHeader(b'content-type', mime_type[0].encode())
with open(path, 'rb') as _file: with open(path, 'rb') as _file:
data = _file.read() data = _file.read()
return compress(data, request) return compress(data, request)
@ -396,32 +396,32 @@ class ScriptResource(resource.Resource, component.Component):
def getChild(self, path, request): # NOQA: N802 def getChild(self, path, request): # NOQA: N802
if hasattr(request, 'lookup_path'): if hasattr(request, 'lookup_path'):
request.lookup_path += '/' + path request.lookup_path += b'/' + path
else: else:
request.lookup_path = path request.lookup_path = path
return self return self
def render(self, request): def render(self, request):
log.debug('Requested path: %s', request.lookup_path) log.debug('Requested path: %s', request.lookup_path)
lookup_path = request.lookup_path.decode()
for script_type in ('dev', 'debug', 'normal'): for script_type in ('dev', 'debug', 'normal'):
scripts = self.__scripts[script_type]['scripts'] scripts = self.__scripts[script_type]['scripts']
for pattern in scripts: for pattern in scripts:
if not request.lookup_path.startswith(pattern): if not lookup_path.startswith(pattern):
continue continue
filepath = scripts[pattern] filepath = scripts[pattern]
if isinstance(filepath, tuple): if isinstance(filepath, tuple):
filepath = filepath[0] filepath = filepath[0]
path = filepath + request.lookup_path[len(pattern):] path = filepath + lookup_path[len(pattern):]
if not os.path.isfile(path): if not os.path.isfile(path):
continue continue
log.debug('Serving path: %s', path) log.debug('Serving path: %s', path)
mime_type = mimetypes.guess_type(path) mime_type = mimetypes.guess_type(path)
request.setHeader(b'content-type', mime_type[0]) request.setHeader(b'content-type', mime_type[0].encode())
with open(path, 'rb') as _file: with open(path, 'rb') as _file:
data = _file.read() data = _file.read()
return compress(data, request) return compress(data, request)
@ -516,7 +516,7 @@ class TopLevel(resource.Resource):
self.__debug_scripts.remove(script) self.__debug_scripts.remove(script)
def getChild(self, path, request): # NOQA: N802 def getChild(self, path, request): # NOQA: N802
if path == '': if not path:
return self return self
else: else:
return resource.Resource.getChild(self, path, request) return resource.Resource.getChild(self, path, request)
@ -571,13 +571,16 @@ class TopLevel(resource.Resource):
request.setHeader(b'content-type', b'text/html; charset=utf-8') request.setHeader(b'content-type', b'text/html; charset=utf-8')
web_config = component.get('Web').get_config() web_config = component.get('Web').get_config()
web_config['base'] = request.base web_config['base'] = request.base.decode()
config = {key: web_config[key] for key in UI_CONFIG_KEYS} config = {key: web_config[key] for key in UI_CONFIG_KEYS}
js_config = json.dumps(config) js_config = json.dumps(config)
# Insert the values into 'index.html' and return. # Insert the values into 'index.html' and return.
return template.render( return template.render(
scripts=scripts, stylesheets=self.stylesheets, scripts=scripts,
debug=debug_arg, base=request.base, js_config=js_config, stylesheets=self.stylesheets,
debug=str(debug_arg).lower(),
base=web_config['base'],
js_config=js_config,
) )
@ -618,7 +621,8 @@ class DelugeWeb(component.Component):
if self.base != '/': if self.base != '/':
# Strip away slashes and serve on the base path as well as root path # Strip away slashes and serve on the base path as well as root path
self.top_level.putChild(self.base.strip('/'), self.top_level) self.top_level.putChild(
self.base.strip('/'), self.top_level)
setup_translations(setup_gettext=True, setup_pygtk=False) setup_translations(setup_gettext=True, setup_pygtk=False)