deluge/src/common.py

279 lines
8.9 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
2006-11-28 22:28:37 +00:00
#
2006-12-08 19:06:49 +00:00
# Copyright (C) Zach Tibbitts 2006 <zach@collegegeek.org>
2007-01-08 19:38:19 +00:00
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
2006-12-08 19:06:49 +00:00
# any later version.
#
2007-01-08 19:38:19 +00:00
# This program is distributed in the hope that it will be useful,
2006-12-08 19:06:49 +00:00
# but WITHOUT ANY WARRANTY; without even the implied warranty of
2007-01-08 19:38:19 +00:00
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
2006-12-08 19:06:49 +00:00
#
# You should have received a copy of the GNU General Public License
2007-01-08 19:38:19 +00:00
# along with this program. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
2007-06-12 16:33:32 +00:00
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the OpenSSL
# library.
# You must obey the GNU General Public License in all respects for all of
# the code used other than OpenSSL. If you modify file(s) with this
# exception, you may extend this exception to your version of the file(s),
# but you are not obligated to do so. If you do not wish to do so, delete
# this exception statement from your version. If you delete this exception
# statement from all source files in the program, then also delete it here.
2006-11-28 22:28:37 +00:00
import os
import xdg.BaseDirectory
2006-12-04 23:59:45 +00:00
PROGRAM_NAME = "Deluge"
PROGRAM_VERSION = "0.5.7.98"
2007-03-26 21:13:14 +00:00
CLIENT_CODE = "DE"
2007-09-04 16:34:58 +00:00
CLIENT_VERSION = "".join(PROGRAM_VERSION.split('.'))+"0"*(4 - len(PROGRAM_VERSION.split('.')))
2007-09-14 22:09:44 +00:00
def windows_check():
import platform
if platform.system() in ('Windows', 'Microsoft'):
return True
else:
return False
2007-09-10 21:26:21 +00:00
import sys
2007-11-01 05:49:06 +00:00
if hasattr(sys, "frozen"):
INSTALL_PREFIX = ''
2007-10-08 16:57:00 +00:00
os.chdir(os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( ))))
2007-11-01 05:49:06 +00:00
else:
# the necessary substitutions are made at installation time
2007-09-10 21:22:10 +00:00
INSTALL_PREFIX = '@datadir@'
if windows_check():
if os.path.isdir(os.path.expanduser("~")):
CONFIG_DIR = os.path.join(os.path.expanduser("~"), 'deluge')
else:
CONFIG_DIR = os.path.join(INSTALL_PREFIX, 'deluge')
if not os.path.exists(CONFIG_DIR):
os.mkdir(CONFIG_DIR)
else:
CONFIG_DIR = xdg.BaseDirectory.save_config_path('deluge')
2007-09-10 21:22:10 +00:00
2007-03-22 21:52:56 +00:00
GLADE_DIR = os.path.join(INSTALL_PREFIX, 'share', 'deluge', 'glade')
PIXMAP_DIR = os.path.join(INSTALL_PREFIX, 'share', 'deluge', 'pixmaps')
PLUGIN_DIR = os.path.join(INSTALL_PREFIX, 'share', 'deluge', 'plugins')
2007-02-12 23:12:08 +00:00
2007-02-12 19:36:16 +00:00
def estimate_eta(state):
try:
2007-11-08 03:17:26 +00:00
return ftime(get_eta(state["total_wanted"], state["total_wanted_done"],
state["download_rate"]))
except ZeroDivisionError:
return _("Infinity")
def get_eta(size, done, speed):
# raise ZeroDivisionError for Infinity in estimate_eta()
if (size - done) == 0:
raise ZeroDivisionError
return (size - done) / speed
2007-02-12 19:36:16 +00:00
2007-02-06 21:21:09 +00:00
# Returns formatted string describing filesize
# fsize_b should be in bytes
# Returned value will be in either KB, MB, or GB
def fsize(fsize_b):
fsize_kb = float (fsize_b / 1024.0)
if fsize_kb < 1000:
2007-07-20 19:03:15 +00:00
return "%.1f %s" % (fsize_kb, _("KiB"))
fsize_mb = float (fsize_kb / 1024.0)
if fsize_mb < 1000:
2007-07-20 19:03:15 +00:00
return "%.1f %s" % (fsize_mb, _("MiB"))
fsize_gb = float (fsize_mb / 1024.0)
2007-08-09 05:35:37 +00:00
if fsize_gb < 1000:
return "%.1f %s" % (fsize_gb, _("GiB"))
fsize_tb = float (fsize_gb / 1024.0)
if fsize_tb < 1000:
return "%.1f %s" % (fsize_tb, _("TiB"))
fsize_pb = float (fsize_tb / 1024.0)
return "%.1f %s" % (fsize_pb, _("PiB"))
2007-02-06 21:21:09 +00:00
# Returns a formatted string representing a percentage
def fpcnt(dec):
return '%.2f%%'%(dec * 100)
2007-02-06 21:21:09 +00:00
# Returns a formatted string representing transfer speed
def fspeed(bps):
return '%s/s'%(fsize(bps))
2007-02-06 21:21:09 +00:00
def fseed(state):
return str(str(state['num_seeds']) + " (" + str(state['total_seeds']) + ")")
2007-02-06 21:21:09 +00:00
def fpeer(state):
return str(str(state['num_peers']) + " (" + str(state['total_peers']) + ")")
2007-02-12 19:36:16 +00:00
def ftime(seconds):
if seconds < 60:
return '%ds'%(seconds)
minutes = int(seconds/60)
seconds = seconds % 60
if minutes < 60:
return '%dm %ds'%(minutes, seconds)
hours = int(minutes/60)
minutes = minutes % 60
if hours < 24:
return '%dh %dm'%(hours, minutes)
days = int(hours/24)
hours = hours % 24
if days < 7:
return '%dd %dh'%(days, hours)
weeks = int(days/7)
days = days % 7
if weeks < 10:
return '%dw %dd'%(weeks, days)
return 'unknown'
2007-02-06 21:21:09 +00:00
2007-07-18 12:47:24 +00:00
def fpriority(priority):
2007-07-27 09:20:27 +00:00
from core import PRIORITY_DICT
2007-07-18 12:47:24 +00:00
return PRIORITY_DICT[priority]
2006-11-28 22:28:37 +00:00
def get_glade_file(fname):
return os.path.join(GLADE_DIR, fname)
2006-11-28 22:28:37 +00:00
def get_pixmap(fname):
return os.path.join(PIXMAP_DIR, fname)
def get_logo(size):
import gtk
2007-12-03 18:10:15 +00:00
if windows_check():
return gtk.gdk.pixbuf_new_from_file_at_size(get_pixmap("deluge.png"), \
size, size)
else:
return gtk.gdk.pixbuf_new_from_file_at_size(get_pixmap("deluge.svg"), \
2007-09-10 09:59:12 +00:00
size, size)
2007-07-16 15:26:37 +00:00
def open_url_in_browser(link):
2007-12-23 02:42:22 +00:00
import pref
config = pref.Preferences(os.path.join(os.path.expanduser("~"), 'deluge', "prefs.state"))
if config.get("use_internal"):
import browser
browser.Browser(link)
else:
import threading
import webbrowser
class BrowserThread(threading.Thread):
def __init__(self, link):
threading.Thread.__init__(self)
self.url = link
def run(self):
webbrowser.open(self.url)
BrowserThread(link).start()
2007-07-16 03:23:36 +00:00
2007-07-16 15:26:37 +00:00
def is_url(url):
import re
return bool(re.search('^(https?|ftp)://', url))
2007-07-16 03:23:36 +00:00
def fetch_url(url):
import urllib
try:
filename, headers = urllib.urlretrieve(url)
except IOError:
print 'Network error while trying to fetch torrent from %s' % url
2007-07-16 03:23:36 +00:00
else:
if filename.endswith(".torrent") or \
headers["content-type"]=="application/x-bittorrent":
return filename
else:
print "URL doesn't appear to be a valid torrent file:", url
return None
2007-07-16 03:23:36 +00:00
def exec_command(executable, *parameters):
import os
command = [executable]
command.extend(parameters)
try:
2007-12-09 19:05:17 +00:00
os.WEXITSTATUS(os.system(command[0] + " \"%s\"" %command[1]))
except OSError:
import gtk
warning = gtk.MessageDialog(parent = None,
flags = gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
buttons= gtk.BUTTONS_OK,
message_format='%s %s %s' % (_("External command"),
executable, _("not found")),
type = gtk.MESSAGE_WARNING)
warning.run()
warning.destroy()
2007-09-07 21:26:50 +00:00
def send_info():
import threading
class Send_Info_Thread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
import urllib
import platform
import gtk
import os
import common
2007-09-07 21:26:50 +00:00
pygtk = '%i.%i.%i' %(gtk.pygtk_version[0],gtk.pygtk_version[1],gtk.pygtk_version[2])
2007-09-07 21:26:50 +00:00
try:
urllib.urlopen("http://download.deluge-torrent.org/stats.php?processor=" + \
platform.machine() + "&python=" + platform.python_version() \
+ "&os=" + platform.system() + "&pygtk=" + pygtk)
except IOError:
print "Network error while trying to send info"
else:
f = open(os.path.join(CONFIG_DIR, 'infosent'), 'w')
f.write("")
f.close
Send_Info_Thread().start()
2007-09-07 21:26:50 +00:00
2007-09-08 01:00:51 +00:00
def new_release_check():
import threading
class ReleaseThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
import urllib
try:
new_release = urllib.urlopen("http://download.deluge-torrent.org/\
2007-09-08 01:00:51 +00:00
version").read().strip()
except IOError:
print "Network error while trying to check for a newer version of \
2007-09-08 01:00:51 +00:00
Deluge"
new_release = ""
2007-09-08 01:00:51 +00:00
2007-12-23 02:42:22 +00:00
if new_release > PROGRAM_VERSION:
import gtk
import dialogs
gtk.gdk.threads_enter()
result = dialogs.show_popup_question(None, _("There is a newer version \
2007-09-08 01:00:51 +00:00
of Deluge. Would you like to be taken to our download site?"))
gtk.gdk.threads_leave()
if result:
open_url_in_browser('http://download.deluge-torrent.org/')
else:
pass
ReleaseThread().start()
2007-12-23 02:42:22 +00:00
return True
2007-09-08 01:00:51 +00:00
# Encryption States
class EncState:
forced, enabled, disabled = range(3)
class EncLevel:
plaintext, rc4, both = range(3)
2007-06-16 10:56:09 +00:00
class ProxyType:
none, socks4, socks5, socks5_pw, http, http_pw = range(6)
2007-08-10 19:28:46 +00:00
class FileManager:
xdg, konqueror, nautilus, thunar = range(4)