webui sync r165

This commit is contained in:
Marcos Pinto 2007-12-05 22:06:31 +00:00
parent 2324fdca83
commit 68f9a3f265
8 changed files with 207 additions and 56 deletions

View File

@ -260,11 +260,14 @@ class ConfigDialog(gtk.Dialog):
show_popup_warning(self,_("Confirmed Password <> New Password\n"
+ "Password was not changed"))
else:
salt = str(random.getrandbits(500))
sm = md5()
sm.update(random.getrandbits(5000))
salt = sm.digest()
self.config.set("pwd_salt", salt)
#
m = md5()
m.update(salt)
m.update(unicode(self.pwd1.get_text()))
self.config.set("pwd_salt", salt)
self.config.set("pwd_md5", m.digest())
self.config.set("port", int(self.port.get_value()))

View File

@ -58,7 +58,7 @@ urls = (
"/resume_all", "resume_all",
"/refresh/set", "refresh_set",
"/refresh/(.*)", "refresh",
"/config", "config",
"/config", "config_",
"/home", "home",
"/about", "about",
"/logout", "logout",
@ -99,7 +99,6 @@ class index:
@auto_refreshed
def GET(self, name):
vars = web.input(sort=None, order=None ,filter=None , category=None)
torrent_list = [get_torrent_status(torrent_id)
for torrent_id in ws.proxy.get_session_state()]
all_torrents = torrent_list[:]
@ -162,8 +161,6 @@ class torrent_stop:
ws.proxy.pause_torrent(torrent_ids)
do_redirect()
class torrent_reannounce:
@check_session
def POST(self, torrent_id):
@ -184,11 +181,10 @@ class torrent_add:
*posting of data as string(for greasemonkey-private)
"""
vars = web.input(url = None, torrent = {},
torrent_name=None, torrent_data = None)
vars = web.input(url = None, torrent = {})
torrent_name = vars.torrent_name
torrent_data = vars.torrent_data
torrent_name = None
torrent_data = None
if vars.torrent.filename:
torrent_name = vars.torrent.filename
torrent_data = vars.torrent.file.read()
@ -209,17 +205,25 @@ class torrent_add:
class remote_torrent_add:
"""
For use in remote scripts etc.
POST pwd and torrent
curl ->POST pwd and torrent as file
greasemonkey: POST pwd torrent_name and data_b64
"""
@remote
def POST(self, name):
vars = web.input(pwd = None, torrent = {})
vars = web.input(pwd = None, torrent = {},
data_b64 = None , torrent_name= None)
if not check_pwd(vars.pwd):
return 'error:wrong password'
data_b64 = base64.b64encode(vars.torrent.file.read())
ws.proxy.add_torrent_filecontent(vars.torrent.filename, data_b64)
if vars.data_b64: #b64 post (greasemonkey)
data_b64 = unicode(vars.data_b64)
torrent_name = vars.torrent_name
else: #file-post (curl)
data_b64 = base64.b64encode(vars.torrent.file.read())
torrent_name = vars.torrent.filename
ws.proxy.add_torrent_filecontent(torrent_name, data_b64)
return 'ok'
class torrent_delete:
@ -299,10 +303,12 @@ class refresh_set:
else:
error_page(_('refresh must be > 0'))
class config:
class config_: #namespace clash?
"""core config
TODO:good validation.
"""
"""
SOMEHOW ONLY BREAKS 0.6 ??
cfg_form = web.form.Form(
web.form.Dropdown('max_download', ws.SPEED_VALUES,
description=_('Download Speed Limit'),
@ -323,6 +329,7 @@ class config:
#self.config.set("max_download_speed", float(str_bwdown))
raise NotImplementedError('todo')
"""
class home:
@check_session
@ -356,9 +363,11 @@ class downloads(static_handler):
return static_handler.GET(self, name)
#/pages
def WebServer():
return create_webserver(urls, globals())
def run():
server = WebServer()
try:

View File

@ -1 +1 @@
160
165

View File

@ -11,20 +11,27 @@
// @include *
// ==/UserScript==
//http://userscripts.org/scripts/show/12639
//This script is based on : "Add Torrents To utorrent" by Julien Couvreur
//Thanks Julian!
//modified by:
//mvoncken
//these 2 parameters need to be edited before using the script
//url-based submit and parsing based on : "Add Torrents To utorrent" by Julien Couvreur
//binary magic,contains from http://mgran.blogspot.com/2006/08/downloading-binary-streams-with.html
//these parameters need to be edited before using the script
// Server address
var host = "localhost";
// Server port
var port = "8112";
//open_page: "_blank" for a new window or "deluge_webui" for window re-use
//(not for private=1)
var open_page = "_blank"
//Private-trackers 0/1
//different behavior, gets torrent-data from (private) site and pops up a message.
var private_submit = 1;
//deluge_password, only needed if private_submit = 1.
var deluge_password = 'deluge';
//========================
if (host == "") { alert('You need to configure the "Add Torrents To Deluge" user script with your uTorrent WebUI parameters before using it.'); }
if (host == "") { alert('You need to configure the "Add Torrents To Deluge" user script with your WebUI parameters before using it.'); }
@ -34,9 +41,12 @@ function scanLinks() {
for (var i=0; i < links.length; i++){
var link = links[i];
if (match(link.href)) {
var uTorrentLink = makeUTorrentLink(link);
link.parentNode.insertBefore(uTorrentLink, link.nextSibling);
if (private_submit) {
makeUTorrentLink_private(link,i);
}
else {
makeUTorrentLink(link);
}
}
}
}
@ -44,13 +54,85 @@ function scanLinks() {
function makeUTorrentLink(link) {
var uTorrentLink = document.createElement('a');
uTorrentLink.setAttribute("href", makeUTorrentUrl(link.href));
uTorrentLink.setAttribute("target", "_blank");
uTorrentLink.setAttribute("target", open_page);
uTorrentLink.style.paddingLeft = "5px";
uTorrentLink.innerHTML = "<img src=\"" + image + "\" style='border: 0px' />";
return uTorrentLink;
link.parentNode.insertBefore(uTorrentLink, link.nextSibling);
return uTorrentLink
}
function makeUTorrentUrl(url) {
var uTorrentUrl = "http://"+host+":"+port+"/torrent/add?redir_after_login=1";
return uTorrentUrl + "&url=" + escape(url);
}
function makeUTorrentLink_private(link,i) {
var id = 'deluge_link' + i;
var uTorrentLink = document.createElement('a');
uTorrentLink.setAttribute("href", '#');
uTorrentLink.setAttribute("id", id);
uTorrentLink.style.paddingLeft = "5px";
uTorrentLink.innerHTML = "<img src=\"" + image + "\" style='border: 0px' />";
link.parentNode.insertBefore(uTorrentLink, link.nextSibling);
ulink = document.getElementById(id)
ulink.addEventListener("click", evt_private_submit_factory(link.href),false);
return uTorrentLink
}
function evt_private_submit_factory(url) {
//can this be done without magic?
function evt_private_submit(evt) {
GM_xmlhttpRequest({ method: 'GET', url: url,
overrideMimeType: 'text/plain; charset=x-user-defined',
onload: function(xhr) {
var stream = translateToBinaryString(xhr.responseText);
var data_b64 = window.btoa(stream);
post_to_webui(url, data_b64);
},
onerror:function(xhr) {
alert('error fetching torrent file');
}
});
return false;
}
return evt_private_submit;
}
function post_to_webui(url,data_b64){
//alert('here1');
//data contains the content of the .torrent-file.
var POST_data = ('pwd=' + encodeURIComponent(deluge_password) +
'&torrent_name=' + encodeURIComponent(url) + '.torrent' + //+.torrent is a clutch!
'&data_b64=' + encodeURIComponent(data_b64) );
//alert(POST_data);
GM_xmlhttpRequest({ method: 'POST',
url: "http://"+host+":"+port+"/remote/torrent/add",
headers:{'Content-type':'application/x-www-form-urlencoded'},
data: POST_data,
onload: function(xhr) {
if (xhr.responseText == 'ok\n') {
alert('Added torrent to webui : \n' + url);
}
else {
alert('Error adding torrent to webui:\n"' + xhr.responseText + '"');
}
},
onerror:function(xhr) {
alert('error submitting torrent file');
}
});
}
function match(url) {
// isohunt format
@ -96,10 +178,6 @@ function match(url) {
return false;
}
function makeUTorrentUrl(url) {
var uTorrentUrl = "http://"+host+":"+port+"/torrent/add?redir_after_login=1";
return uTorrentUrl + "&url=" + escape(url);
}
function getLinks() {
var doc_links = document.links;
@ -112,5 +190,18 @@ function getLinks() {
var image = "data:image/gif;base64,R0lGODlhEAAQAMZyAB1CdihAYx5CdiBEeCJGeSZJfChKfChLfSpPgTBRgThRdDRUgzRVhDVWhDZWhThYhjtbiD1ciD5diT5eiz9eikBeiUFeiT5fjT1gjkBfjERijkdjiUhljkVnlEdolUxokExqkk5qkU9rklBrklFtk1BullFulk5vmlZymFx3nE97rVZ5pUx8sl54nlt5oVl6pE5/tWJ6nVp9qFqArWOEq1uIuW6EpGCItl2Ku26Gp2KKuGuIrF+MvWaLtl+Nv3KJqG+KrGaOu2aQv2SRwnGOs2uQvGqSwICOpoCQqm6Ww3OVvHKWv3iWuoKWsn+XtnacxXaeynifyXigzICewn2gxnqizoqfunujzpWesX6l0IyivYijw4+jvpOiuoOp0puktY2x2I6y2Y+z2pG02pW43Ze42pa43Z/A4qjG56jH56nI6KzJ6a/M67nR67zW8sLa9cff+M/k+P///////////////////////////////////////////////////////yH+FUNyZWF0ZWQgd2l0aCBUaGUgR0lNUAAh+QQBCgB/ACwAAAAAEAAQAAAHkIB/goOEhYaCX1iHhkdIXU2LgzFARExbkYInCBcvRVSRHgQNEiYoPUmHGAkjO1FSSilBNYYQFTllY2BeSzJChg4iWmhpZ2JXOjgqhBMFH1xvbmtmWUMwM4QZBws/cXBsZFU+LCuFDwIhVm1qYVA8Nx2FEQQDHDZOU09GNIcWDAAGFEC0cBEpwAYNJUgowMQwEAA7";
scanLinks();
/*
binary magic,contains code taken from
http://mgran.blogspot.com/2006/08/downloading-binary-streams-with.html
*/
function translateToBinaryString(text){
var out;
out='';
for(i=0;i<text.length;i++){
//*bugfix* by Marcus Granado 2006 [http://mgran.blogspot.com] adapted by Thomas Belot
out+=String.fromCharCode(text.charCodeAt(i) & 0xff);
}
return out;
}

View File

@ -46,18 +46,6 @@ $:render.header(_('Torrent list'))
</div>
<!--
$if getcookie('auto_refresh') == '1':
<a href='#' onclick=' toolbar_post("/refresh/off/")'>[Auto Refresh:disable]</a>
<a href='#' onclick=' toolbar_get("/refresh/set/")'>[Auto Refresh:set]</a>
$else:
<a href='#' onclick=' toolbar_post("/refresh/on/")'>[Auto Refresh:enable]</a>
$#end
-->
<div id="tableContainer" class="tableContainer">
<table class="torrent_list" border=1 id="torrent_list">
<thead class="fixedHeader">
@ -67,7 +55,8 @@ $#end
$:(sort_head('name', _('Name')))
$:(sort_head('total_size', _('Size')))
$:(sort_head('progress', _('Progress')))
$:(sort_head('category', _('Tracker')))
$if (not get('category')):
$:(sort_head('category', _('Tracker')))
$:(sort_head('num_seeds', _('Seeders')))
$:(sort_head('num_peers', _('Peers')))
$:(sort_head('download_rate', _('Download')))
@ -100,7 +89,8 @@ $for torrent in torrent_list:
</div>
</div>
</td>
<td>$torrent.category</td>
$if (not get('category')):
<td>$torrent.category</td>
<td>$torrent.num_seeds ($torrent.total_seeds)</td>
<td>$torrent.num_peers ($torrent.total_peers)</td>
<td>

View File

@ -1,5 +1,5 @@
revision-id: mvoncken@gmail.com-20070930083408-sv8mo0mi1rbjnfvk
date: 2007-11-26 15:10:08 +0200
build-date: 2007-11-26 15:34:50 +0200
revno: 160
date: 2007-12-05 15:10:08 +0200
build-date: 2007-12-05 15:34:50 +0200
revno: 165
branch-nick: WebUi

View File

@ -40,17 +40,30 @@ import deluge
import random
import pickle
import sys
import base64
from webpy022 import template
random.seed()
webui_path = os.path.dirname(__file__)
ENV = 'UNKNOWN'
config_defaults = {
"port":8112,
"button_style":2,
"auto_refresh":False,
"auto_refresh_secs": 10,
"template":"advanced",
"pwd_salt":"2540626806573060601127357001536142078273646936492343724296134859793541603059837926595027859394922651189016967573954758097008242073480355104215558310954",
"pwd_md5":"\xea\x8d\x90\x98^\x9f\xa9\xe2\x19l\x7f\x1a\xca\x82u%",
"cache_templates":False,
"use_https":False
}
try:
_('translate something')
except:
import gettext
gettext.install('~/') #no translations :(
gettext.install('~/')
#log.error('no translations :(')
try:
config_dir = deluge.common.CONFIG_DIR
@ -88,20 +101,54 @@ def init_process():
def init_06():
import deluge.ui.client as proxy
from deluge.log import LOG as log
globals()['log'] = log
proxy.set_core_uri('http://localhost:58846') #How to configure this?
def add_torrent_filecontent(name , data_b64):
log.debug('monkeypatched add_torrent_filecontent:%s,len(data:%s))' %
(name , len(data_b64)))
name = name.replace('\\','/')
name = 'deluge06_' + str(random.random()) + '_' + name.split('/')[-1]
filename = os.path.join('/tmp', name)
log.debug('write: %s' % filename)
f = open(filename,"wb")
f.write(base64.b64decode(data_b64))
f.close()
proxy.add_torrent_file([filename])
proxy.add_torrent_filecontent = add_torrent_filecontent
log.debug('cfg-file %s' % config_file)
if not os.path.exists(config_file):
log.debug('create cfg file %s' % config_file)
#load&save defaults.
f = file(config_file,'wb')
pickle.dump(config_defaults,f)
f.close()
init_process()
globals()['proxy'] = proxy
globals()['ENV'] = '0.6'
def init_05():
import dbus
init_process()
bus = dbus.SessionBus()
proxy = bus.get_object("org.deluge_torrent.dbusplugin"
, "/org/deluge_torrent/DelugeDbusPlugin")
globals()['proxy'] = proxy
globals()['ENV'] = '0.5_process'
init_logger()
def init_gtk_05():
#appy possibly changed config-vars, only called in when runing inside gtk.
@ -111,7 +158,13 @@ def init_gtk_05():
globals()['render'] = subclassed_render(config.get('template'),
config.get('cache_templates'))
globals()['ENV'] = '0.5_gtk'
init_logger()
def init_logger():
#only for 0.5..
import logging
logging.basicConfig(level=logging.DEBUG,format="[%(levelname)-8s] %(module)s:%(lineno)d %(message)s")
globals()['log'] = logging
#hacks to determine environment, TODO: clean up.

View File

@ -59,7 +59,7 @@ from md5 import md5
from urlparse import urlparse
from deluge import common
from webserver_common import REVNO, VERSION
from webserver_common import REVNO, VERSION, log
import webserver_common as ws
from debugerror import deluge_debugerror
@ -74,6 +74,7 @@ def setcookie(key, val):
#really simple sessions, to bad i had to implement them myself.
def start_session():
log.debug('start session')
session_id = str(random.random())
ws.SESSIONS.append(session_id)
#if len(ws.SESSIONS) > 20: #save max 20 sessions?
@ -134,6 +135,7 @@ def deluge_page_noauth(func):
web.header("Cache-Control", "no-cache, must-revalidate")
res = func(self, name)
print res
deco.__name__ = func.__name__
return deco
def check_session(func):
@ -142,6 +144,7 @@ def check_session(func):
return func if session is valid, else redirect to login page.
"""
def deco(self, name = None):
log.debug('%s.%s(name=%s)' % (self.__class__.__name__,func.__name__,name))
vars = web.input(redir_after_login = None)
ck = cookies()
if ck.has_key("session_id") and ck["session_id"] in ws.SESSIONS:
@ -163,6 +166,7 @@ def auto_refreshed(func):
web.header("Refresh", "%i ; url=%s" %
(int(getcookie('auto_refresh_secs',10)),self_url()))
return func(self, name)
deco.__name__ = func.__name__
return deco
def remote(func):
@ -174,6 +178,7 @@ def remote(func):
print 'error:' + e.message
print '-'*20
print traceback.format_exc()
deco.__name__ = func.__name__
return deco
#utils:
@ -387,4 +392,4 @@ __all__ = ['deluge_page_noauth', 'deluge_page', 'remote',
'do_redirect', 'error_page','start_session','getcookie'
,'setcookie','create_webserver','end_session',
'get_torrent_status', 'check_pwd','static_handler','get_categories'
,'template','filter_torrent_state']
,'template','filter_torrent_state','log']