[Blocklist] Flake8 and bump version

This commit is contained in:
Calum Lind 2014-08-04 18:43:07 +01:00
commit 936ae3b171
10 changed files with 200 additions and 414 deletions

View file

@ -1,53 +1,29 @@
# # -*- coding: utf-8 -*-
# blocklist/__init__.py
# #
# Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com> # Copyright (C) 2007-2009 Andrew Resch <andrewresch@gmail.com>
# #
# # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# Deluge is free software. # the additional special exception to link portions of this program with the OpenSSL library.
# # See LICENSE for more details.
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# 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.
#
# #
from deluge.plugins.init import PluginInitBase from deluge.plugins.init import PluginInitBase
class CorePlugin(PluginInitBase): class CorePlugin(PluginInitBase):
def __init__(self, plugin_name): def __init__(self, plugin_name):
from core import Core as _plugin_cls from core import Core as _plugin_cls
self._plugin_cls = _plugin_cls self._plugin_cls = _plugin_cls
super(CorePlugin, self).__init__(plugin_name) super(CorePlugin, self).__init__(plugin_name)
class GtkUIPlugin(PluginInitBase): class GtkUIPlugin(PluginInitBase):
def __init__(self, plugin_name): def __init__(self, plugin_name):
from gtkui import GtkUI as _plugin_cls from gtkui import GtkUI as _plugin_cls
self._plugin_cls = _plugin_cls self._plugin_cls = _plugin_cls
super(GtkUIPlugin, self).__init__(plugin_name) super(GtkUIPlugin, self).__init__(plugin_name)
class WebUIPlugin(PluginInitBase): class WebUIPlugin(PluginInitBase):
def __init__(self, plugin_name): def __init__(self, plugin_name):
from webui import WebUI as _plugin_cls from webui import WebUI as _plugin_cls

View file

@ -1,67 +1,37 @@
# # -*- coding: utf-8 -*-
# common.py
# #
# Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
# #
# Deluge is free software. # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
# #
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# 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.
#
#
import pkg_resources import pkg_resources
import os.path import os.path
from functools import wraps from functools import wraps
from sys import exc_info from sys import exc_info
def get_resource(filename): def get_resource(filename):
return pkg_resources.resource_filename("deluge.plugins.blocklist", return pkg_resources.resource_filename("deluge.plugins.blocklist",
os.path.join("data", filename)) os.path.join("data", filename))
def raisesErrorsAs(error):
""" def raises_errors_as(error):
Factory class that returns a decorator which wraps """Factory class that returns a decorator which wraps the decorated
the decorated function to raise all exceptions as function to raise all exceptions as the specified error type.
the specified error type
""" """
def decorator(func): def decorator(func):
""" """Returns a function which wraps the given func to raise all exceptions as error."""
Returns a function which wraps the given func
to raise all exceptions as error
"""
@wraps(func) @wraps(func)
def wrapper(self, *args, **kwargs): def wrapper(self, *args, **kwargs):
""" """Wraps the function in a try..except block and calls it with the specified args.
Wraps the function in a try..except block
and calls it with the specified args Raises:
Any exceptions as error preserving the message and traceback.
Raises any exceptions as error preserving the
message and traceback
""" """
try: try:
return func(self, *args, **kwargs) return func(self, *args, **kwargs)
@ -71,23 +41,26 @@ def raisesErrorsAs(error):
return wrapper return wrapper
return decorator return decorator
def remove_zeros(ip): def remove_zeros(ip):
""" """Removes unneeded zeros from ip addresses.
Removes unneeded zeros from ip addresses.
Example: 000.000.000.003 -> 0.0.0.3 Args:
ip (str): The ip address.
:param ip: the ip address Returns:
:type ip: string str: The ip address without the unneeded zeros.
:returns: the ip address without the unneeded zeros Example:
:rtype: string 000.000.000.003 -> 0.0.0.3
""" """
return ".".join([part.lstrip("0").zfill(1) for part in ip.split(".")]) return ".".join([part.lstrip("0").zfill(1) for part in ip.split(".")])
class BadIP(Exception): class BadIP(Exception):
_message = None _message = None
def __init__(self, message): def __init__(self, message):
self.message = message self.message = message
@ -100,8 +73,10 @@ class BadIP(Exception):
message = property(__get_message, __set_message) message = property(__get_message, __set_message)
del __get_message, __set_message del __get_message, __set_message
class IP(object): class IP(object):
__slots__ = ('q1', 'q2', 'q3', 'q4', '_long') __slots__ = ('q1', 'q2', 'q3', 'q4', '_long')
def __init__(self, q1, q2, q3, q4): def __init__(self, q1, q2, q3, q4):
self.q1 = q1 self.q1 = q1
self.q2 = q2 self.q2 = q2
@ -125,9 +100,9 @@ class IP(object):
q1, q2, q3, q4 = [int(q) for q in ip.split('.')] q1, q2, q3, q4 = [int(q) for q in ip.split('.')]
except ValueError: except ValueError:
raise BadIP(_("The IP address \"%s\" is badly formed" % ip)) raise BadIP(_("The IP address \"%s\" is badly formed" % ip))
if q1<0 or q2<0 or q3<0 or q4<0: if q1 < 0 or q2 < 0 or q3 < 0 or q4 < 0:
raise BadIP(_("The IP address \"%s\" is badly formed" % ip)) raise BadIP(_("The IP address \"%s\" is badly formed" % ip))
elif q1>255 or q2>255 or q3>255 or q4>255: elif q1 > 255 or q2 > 255 or q3 > 255 or q4 > 255:
raise BadIP(_("The IP address \"%s\" is badly formed" % ip)) raise BadIP(_("The IP address \"%s\" is badly formed" % ip))
return cls(q1, q2, q3, q4) return cls(q1, q2, q3, q4)

View file

@ -1,37 +1,11 @@
# # -*- coding: utf-8 -*-
# core.py
# #
# Copyright (C) 2008 Andrew Resch <andrewresch@gmail.com> # Copyright (C) 2008 Andrew Resch <andrewresch@gmail.com>
# Copyright (C) 2009-2010 John Garland <johnnybg+deluge@gmail.com> # Copyright (C) 2009-2010 John Garland <johnnybg+deluge@gmail.com>
# #
# Deluge is free software. # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# # the additional special exception to link portions of this program with the OpenSSL library.
# You may redistribute it and/or modify it under the terms of the # See LICENSE for more details.
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# 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.
#
# #
import os import os
@ -78,6 +52,7 @@ DEFAULT_PREFS = {
ALLOW_RANGE = 0 ALLOW_RANGE = 0
BLOCK_RANGE = 1 BLOCK_RANGE = 1
class Core(CorePluginBase): class Core(CorePluginBase):
def enable(self): def enable(self):
log.debug('Blocklist: Plugin enabled...') log.debug('Blocklist: Plugin enabled...')
@ -138,14 +113,14 @@ class Core(CorePluginBase):
## Exported RPC methods ### ## Exported RPC methods ###
@export @export
def check_import(self, force=False): def check_import(self, force=False):
""" """Imports latest blocklist specified by blocklist url.
Imports latest blocklist specified by blocklist url
Only downloads/imports if necessary or forced Args:
force (bool, optional): Force the download/import, default is False.
Returns:
Deferred: A Deferred which fires when the blocklist has been imported.
:param force: optional argument to force download/import
:type force: boolean
:returns: a Deferred which fires when the blocklist has been imported
:rtype: Deferred
""" """
# Reset variables # Reset variables
@ -173,21 +148,21 @@ class Core(CorePluginBase):
@export @export
def get_config(self): def get_config(self):
""" """Gets the blocklist config dictionary.
Returns the config dictionary
Returns:
dict: The config dictionary.
:returns: the config dictionary
:rtype: dict
""" """
return self.config.config return self.config.config
@export @export
def set_config(self, config): def set_config(self, config):
""" """Sets the blocklist config.
Sets the config based on values in 'config'
Args:
config (dict): config to set.
:param config: config to set
:type config: dictionary
""" """
needs_blocklist_import = False needs_blocklist_import = False
for key in config.keys(): for key in config.keys():
@ -252,11 +227,11 @@ class Core(CorePluginBase):
@export @export
def get_status(self): def get_status(self):
""" """Get the status of the plugin.
Returns the status of the plugin
Returns:
dict: The status dict of the plugin.
:returns: the status dict of the plugin
:rtype: dict
""" """
status = {} status = {}
if self.is_downloading: if self.is_downloading:
@ -282,13 +257,14 @@ class Core(CorePluginBase):
#### ####
def update_info(self, blocklist): def update_info(self, blocklist):
""" """Updates blocklist info.
Updates blocklist info
Args:
blocklist (str): Path of blocklist.
Returns:
str: Path of blocklist.
:param blocklist: path of blocklist
:type blocklist: string
:returns: path of blocklist
:rtype: string
""" """
log.debug("Updating blocklist info: %s", blocklist) log.debug("Updating blocklist info: %s", blocklist)
self.config["last_update"] = time.time() self.config["last_update"] = time.time()
@ -297,13 +273,14 @@ class Core(CorePluginBase):
return blocklist return blocklist
def download_list(self, url=None): def download_list(self, url=None):
""" """Downloads the blocklist specified by 'url' in the config.
Downloads the blocklist specified by 'url' in the config
Args:
url (str, optional): url to download from, defaults to config value.
Returns:
Deferred: a Deferred which fires once the blocklist has been downloaded.
:param url: optional url to download from, defaults to config value
:type url: string
:returns: a Deferred which fires once the blocklist has been downloaded
:rtype: Deferred
""" """
def on_retrieve_data(data, current_length, total_length): def on_retrieve_data(data, current_length, total_length):
if total_length: if total_length:
@ -334,27 +311,28 @@ class Core(CorePluginBase):
) )
def on_download_complete(self, blocklist): def on_download_complete(self, blocklist):
""" """Runs any download clean up functions.
Runs any download clean up functions
Args:
blocklist (str): Path of blocklist.
Returns:
Deferred: a Deferred which fires when clean up is done.
:param blocklist: path of blocklist
:type blocklist: string
:returns: a Deferred which fires when clean up is done
:rtype: Deferred
""" """
log.debug("Blocklist download complete: %s", blocklist) log.debug("Blocklist download complete: %s", blocklist)
self.is_downloading = False self.is_downloading = False
return threads.deferToThread(self.update_info, blocklist) return threads.deferToThread(self.update_info, blocklist)
def on_download_error(self, f): def on_download_error(self, f):
""" """Recovers from download error.
Recovers from download error
Args:
f (Failure): Failure that occurred.
Returns:
Deferred or Failure: A Deferred if recovery was possible else original Failure.
:param f: failure that occurred
:type f: Failure
:returns: a Deferred if recovery was possible
else the original failure
:rtype: Deferred or Failure
""" """
self.is_downloading = False self.is_downloading = False
error_msg = f.getErrorMessage() error_msg = f.getErrorMessage()
@ -383,18 +361,20 @@ class Core(CorePluginBase):
return d return d
def import_list(self, blocklist): def import_list(self, blocklist):
""" """Imports the downloaded blocklist into the session.
Imports the downloaded blocklist into the session
Args:
blocklist (str): path of blocklist.
Returns:
Deferred: A Deferred that fires when the blocklist has been imported.
:param blocklist: path of blocklist
:type blocklist: string
:returns: a Deferred that fires when the blocklist has been imported
:rtype: Deferred
""" """
log.trace("on import_list") log.trace("on import_list")
def on_read_ip_range(start, end): def on_read_ip_range(start, end):
"""Add ip range to blocklist""" """Add ip range to blocklist"""
# log.trace("Adding ip range %s - %s to ipfilter as blocked", start, end) #~ log.trace("Adding ip range %s - %s to ipfilter as blocked", start, end)
self.blocklist.add_rule(start.address, end.address, BLOCK_RANGE) self.blocklist.add_rule(start.address, end.address, BLOCK_RANGE)
self.num_blocked += 1 self.num_blocked += 1
@ -436,20 +416,21 @@ class Core(CorePluginBase):
log.debug("Importing using reader: %s", self.reader) log.debug("Importing using reader: %s", self.reader)
log.debug("Reader type: %s compression: %s", self.config["list_type"], self.config["list_compression"]) log.debug("Reader type: %s compression: %s", self.config["list_type"], self.config["list_compression"])
log.debug("Clearing current ip filtering") log.debug("Clearing current ip filtering")
# self.blocklist.add_rule("0.0.0.0", "255.255.255.255", ALLOW_RANGE) #~ self.blocklist.add_rule("0.0.0.0", "255.255.255.255", ALLOW_RANGE)
d = threads.deferToThread(self.reader(blocklist).read, on_read_ip_range) d = threads.deferToThread(self.reader(blocklist).read, on_read_ip_range)
d.addCallback(on_finish_read).addErrback(on_reader_failure) d.addCallback(on_finish_read).addErrback(on_reader_failure)
return d return d
def on_import_complete(self, blocklist): def on_import_complete(self, blocklist):
""" """Runs any import clean up functions.
Runs any import clean up functions
Args:
blocklist (str): Path of blocklist.
Returns:
Deferred: A Deferred that fires when clean up is done.
:param blocklist: path of blocklist
:type blocklist: string
:returns: a Deferred that fires when clean up is done
:rtype: Deferred
""" """
log.trace("on_import_list_complete") log.trace("on_import_list_complete")
d = blocklist d = blocklist
@ -467,14 +448,14 @@ class Core(CorePluginBase):
return d return d
def on_import_error(self, f): def on_import_error(self, f):
""" """Recovers from import error.
Recovers from import error
Args:
f (Failure): Failure that occurred.
Returns:
Deferred or Failure: A Deferred if recovery was possible else original Failure.
:param f: failure that occurred
:type f: Failure
:returns: a Deferred if recovery was possible
else the original failure
:rtype: Deferred or Failure
""" """
log.trace("on_import_error: %s", f) log.trace("on_import_error: %s", f)
d = f d = f
@ -501,12 +482,14 @@ class Core(CorePluginBase):
return d return d
def auto_detect(self, blocklist): def auto_detect(self, blocklist):
""" """Attempts to auto-detect the blocklist type.
Tries to auto-detect the blocklist type
Args:
blocklist (str): Path of blocklist.
Raises:
UnknownFormatError: If the format cannot be detected.
:param blocklist: path of blocklist to auto-detect
:type blocklist: string
:raises UnknownFormatError: if the format cannot be detected
""" """
self.config["list_compression"] = detect_compression(blocklist) self.config["list_compression"] = detect_compression(blocklist)
self.config["list_type"] = detect_format(blocklist, self.config["list_compression"]) self.config["list_type"] = detect_format(blocklist, self.config["list_compression"])
@ -517,7 +500,6 @@ class Core(CorePluginBase):
else: else:
self.reader = create_reader(self.config["list_type"], self.config["list_compression"]) self.reader = create_reader(self.config["list_type"], self.config["list_compression"])
def pause_session(self): def pause_session(self):
if not self.core.session.is_paused(): if not self.core.session.is_paused():
self.core.session.pause() self.core.session.pause()

View file

@ -1,39 +1,16 @@
# # -*- coding: utf-8 -*-
# decompressers.py
# #
# Copyright (C) 2009-2010 John Garland <johnnybg+deluge@gmail.com> # Copyright (C) 2009-2010 John Garland <johnnybg+deluge@gmail.com>
# #
# Deluge is free software. # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# # the additional special exception to link portions of this program with the OpenSSL library.
# You may redistribute it and/or modify it under the terms of the # See LICENSE for more details.
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# 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.
#
# #
import gzip, zipfile, bz2 import gzip
import zipfile
import bz2
def Zipped(reader): def Zipped(reader):
"""Blocklist reader for zipped blocklists""" """Blocklist reader for zipped blocklists"""
@ -49,6 +26,7 @@ def Zipped(reader):
reader.open = open reader.open = open
return reader return reader
def GZipped(reader): def GZipped(reader):
"""Blocklist reader for gzipped blocklists""" """Blocklist reader for gzipped blocklists"""
def open(self): def open(self):
@ -56,6 +34,7 @@ def GZipped(reader):
reader.open = open reader.open = open
return reader return reader
def BZipped2(reader): def BZipped2(reader):
"""Blocklist reader for bzipped2 blocklists""" """Blocklist reader for bzipped2 blocklists"""
def open(self): def open(self):

View file

@ -1,68 +1,45 @@
# # -*- coding: utf-8 -*-
# detect.py
# #
# Copyright (C) 2009-2010 John Garland <johnnybg+deluge@gmail.com> # Copyright (C) 2009-2010 John Garland <johnnybg+deluge@gmail.com>
# #
# Deluge is free software. # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# # the additional special exception to link portions of this program with the OpenSSL library.
# You may redistribute it and/or modify it under the terms of the # See LICENSE for more details.
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# 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.
#
# #
from decompressers import Zipped, GZipped, BZipped2 from decompressers import Zipped, GZipped, BZipped2
from readers import EmuleReader, SafePeerReader, PeerGuardianReader from readers import EmuleReader, SafePeerReader, PeerGuardianReader
COMPRESSION_TYPES = { COMPRESSION_TYPES = {
"PK" : "Zip", "PK": "Zip",
"\x1f\x8b" : "GZip", "\x1f\x8b": "GZip",
"BZ" : "BZip2" "BZ": "BZip2"
} }
DECOMPRESSERS = { DECOMPRESSERS = {
"Zip" : Zipped, "Zip": Zipped,
"GZip" : GZipped, "GZip": GZipped,
"BZip2" : BZipped2 "BZip2": BZipped2
} }
READERS = { READERS = {
"Emule" : EmuleReader, "Emule": EmuleReader,
"SafePeer" : SafePeerReader, "SafePeer": SafePeerReader,
"PeerGuardian" : PeerGuardianReader "PeerGuardian": PeerGuardianReader
} }
class UnknownFormatError(Exception): class UnknownFormatError(Exception):
pass pass
def detect_compression(filename): def detect_compression(filename):
f = open(filename, "rb") f = open(filename, "rb")
magic_number = f.read(2) magic_number = f.read(2)
f.close() f.close()
return COMPRESSION_TYPES.get(magic_number, "") return COMPRESSION_TYPES.get(magic_number, "")
def detect_format(filename, compression=""): def detect_format(filename, compression=""):
format = "" format = ""
for reader in READERS: for reader in READERS:
@ -71,6 +48,7 @@ def detect_format(filename, compression=""):
break break
return format return format
def create_reader(format, compression=""): def create_reader(format, compression=""):
reader = READERS.get(format) reader = READERS.get(format)
if reader and compression: if reader and compression:

View file

@ -1,36 +1,10 @@
# # -*- coding: utf-8 -*-
# gtkui.py
# #
# Copyright (C) 2008 Andrew Resch <andrewresch@gmail.com> # Copyright (C) 2008 Andrew Resch <andrewresch@gmail.com>
# #
# Deluge is free software. # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# # the additional special exception to link portions of this program with the OpenSSL library.
# You may redistribute it and/or modify it under the terms of the # See LICENSE for more details.
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# 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.
#
# #
import logging import logging
@ -46,6 +20,7 @@ import common
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class GtkUI(GtkPluginBase): class GtkUI(GtkPluginBase):
def enable(self): def enable(self):
log.debug("Blocklist GtkUI enable..") log.debug("Blocklist GtkUI enable..")
@ -147,7 +122,7 @@ class GtkUI(GtkPluginBase):
config["url"] = self.glade.get_widget("entry_url").get_text() config["url"] = self.glade.get_widget("entry_url").get_text()
config["check_after_days"] = self.glade.get_widget("spin_check_days").get_value_as_int() config["check_after_days"] = self.glade.get_widget("spin_check_days").get_value_as_int()
config["load_on_start"] = self.glade.get_widget("chk_import_on_start").get_active() config["load_on_start"] = self.glade.get_widget("chk_import_on_start").get_active()
config["whitelisted"] = [ip[0] for ip in self.whitelist_model if ip[0]!='IP HERE'] config["whitelisted"] = [ip[0] for ip in self.whitelist_model if ip[0] != 'IP HERE']
client.blocklist.set_config(config) client.blocklist.set_config(config)
def _on_button_check_download_clicked(self, widget): def _on_button_check_download_clicked(self, widget):
@ -218,8 +193,8 @@ class GtkUI(GtkPluginBase):
self.whitelist_treeview.set_model(self.whitelist_model) self.whitelist_treeview.set_model(self.whitelist_model)
def on_cell_edited(self, cell, path_string, new_text, model): def on_cell_edited(self, cell, path_string, new_text, model):
# iter = model.get_iter_from_string(path_string) #~ iter = model.get_iter_from_string(path_string)
# path = model.get_path(iter)[0] #~ path = model.get_path(iter)[0]
try: try:
ip = common.IP.parse(new_text) ip = common.IP.parse(new_text)
model.set(model.get_iter_from_string(path_string), 0, ip.address) model.set(model.get_iter_from_string(path_string), 0, ip.address)
@ -229,7 +204,6 @@ class GtkUI(GtkPluginBase):
d = dialogs.ErrorDialog(_("Bad IP address"), e.message) d = dialogs.ErrorDialog(_("Bad IP address"), e.message)
d.run() d.run()
def on_whitelist_treeview_selection_changed(self, selection): def on_whitelist_treeview_selection_changed(self, selection):
model, selected_connection_iter = selection.get_selected() model, selected_connection_iter = selection.get_selected()
if selected_connection_iter: if selected_connection_iter:
@ -247,12 +221,12 @@ class GtkUI(GtkPluginBase):
selection = treeview.get_selection() selection = treeview.get_selection()
model, iter = selection.get_selected() model, iter = selection.get_selected()
if iter: if iter:
# path = model.get_path(iter)[0] #~ path = model.get_path(iter)[0]
model.remove(iter) model.remove(iter)
def populate_whitelist(self, whitelist): def populate_whitelist(self, whitelist):
self.whitelist_model.clear() self.whitelist_model.clear()
for ip in whitelist: for ip in whitelist:
self.whitelist_model.set( self.whitelist_model.set(
self.whitelist_model.append(),0, ip, 1, True self.whitelist_model.append(), 0, ip, 1, True
) )

View file

@ -1,18 +1,25 @@
## # -*- coding: utf-8 -*-
# Copyright 2007 Steve 'Tarka' Smith (tarka@internode.on.net) #
# Distributed under the same terms as Deluge # Copyright (C) 2007 Steve 'Tarka' Smith (tarka@internode.on.net)
## #
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
#
import logging import logging
from exceptions import Exception from exceptions import Exception
from struct import unpack from struct import unpack
import gzip, socket import gzip
import socket
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class PGException(Exception): class PGException(Exception):
pass pass
# Incrementally reads PeerGuardian blocklists v1 and v2. # Incrementally reads PeerGuardian blocklists v1 and v2.
# See http://wiki.phoenixlabs.org/wiki/P2B_Format # See http://wiki.phoenixlabs.org/wiki/P2B_Format
class PGReader: class PGReader:
@ -22,14 +29,14 @@ class PGReader:
try: try:
self.fd = gzip.open(filename, "rb") self.fd = gzip.open(filename, "rb")
except IOError, e: except IOError:
log.debug("Blocklist: PGReader: Incorrect file type or list is corrupt") log.debug("Blocklist: PGReader: Incorrect file type or list is corrupt")
# 4 bytes, should be 0xffffffff # 4 bytes, should be 0xffffffff
buf = self.fd.read(4) buf = self.fd.read(4)
hdr = unpack("l", buf)[0] hdr = unpack("l", buf)[0]
if hdr != -1: if hdr != -1:
raise PGException(_("Invalid leader") + " %d"%hdr) raise PGException(_("Invalid leader") + " %d" % hdr)
magic = self.fd.read(3) magic = self.fd.read(3)
if magic != "P2B": if magic != "P2B":
@ -40,9 +47,7 @@ class PGReader:
if ver != 1 and ver != 2: if ver != 1 and ver != 2:
raise PGException(_("Invalid version") + " %d" % ver) raise PGException(_("Invalid version") + " %d" % ver)
def next(self): def next(self):
# Skip over the string # Skip over the string
buf = -1 buf = -1
while buf != 0: while buf != 0:

View file

@ -1,47 +1,23 @@
# # -*- coding: utf-8 -*-
# readers.py
# #
# Copyright (C) 2009-2010 John Garland <johnnybg+deluge@gmail.com> # Copyright (C) 2009-2010 John Garland <johnnybg+deluge@gmail.com>
# #
# Deluge is free software. # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# # the additional special exception to link portions of this program with the OpenSSL library.
# You may redistribute it and/or modify it under the terms of the # See LICENSE for more details.
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# 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.
#
# #
import logging import logging
from common import raisesErrorsAs, IP, BadIP from common import raises_errors_as, IP, BadIP
import re import re
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class ReaderParseError(Exception): class ReaderParseError(Exception):
pass pass
class BaseReader(object): class BaseReader(object):
"""Base reader for blocklist files""" """Base reader for blocklist files"""
def __init__(self, file): def __init__(self, file):
@ -63,7 +39,6 @@ class BaseReader(object):
callback(IP.parse(start), IP.parse(end)) callback(IP.parse(start), IP.parse(end))
except BadIP, e: except BadIP, e:
log.error("Failed to parse IP: %s", e) log.error("Failed to parse IP: %s", e)
# log.exception(e)
return self.file return self.file
def is_ignored(self, line): def is_ignored(self, line):
@ -89,7 +64,7 @@ class BaseReader(object):
blocklist.close() blocklist.close()
return valid return valid
@raisesErrorsAs(ReaderParseError) @raises_errors_as(ReaderParseError)
def readranges(self): def readranges(self):
"""Yields each ip range from the file""" """Yields each ip range from the file"""
blocklist = self.open() blocklist = self.open()
@ -98,16 +73,19 @@ class BaseReader(object):
yield self.parse(line) yield self.parse(line)
blocklist.close() blocklist.close()
class EmuleReader(BaseReader): class EmuleReader(BaseReader):
"""Blocklist reader for emule style blocklists""" """Blocklist reader for emule style blocklists"""
def parse(self, line): def parse(self, line):
return line.strip().split(" , ")[0].split(" - ") return line.strip().split(" , ")[0].split(" - ")
class SafePeerReader(BaseReader): class SafePeerReader(BaseReader):
"""Blocklist reader for SafePeer style blocklists""" """Blocklist reader for SafePeer style blocklists"""
def parse(self, line): def parse(self, line):
return line.strip().split(":")[-1].split("-") return line.strip().split(":")[-1].split("-")
class PeerGuardianReader(SafePeerReader): class PeerGuardianReader(SafePeerReader):
"""Blocklist reader for PeerGuardian style blocklists""" """Blocklist reader for PeerGuardian style blocklists"""
pass pass

View file

@ -1,58 +1,23 @@
# # -*- coding: utf-8 -*-
# blocklist/webui.py
# #
# Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com> # Copyright (C) 2008 Martijn Voncken <mvoncken@gmail.com>
#
# Deluge is free software.
#
# You may redistribute it and/or modify it under the terms of the
# GNU General Public License, as published by the Free Software
# Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# deluge is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with deluge. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# 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.
# #
# This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# the additional special exception to link portions of this program with the OpenSSL library.
# See LICENSE for more details.
# #
import os
import logging import logging
from deluge.ui.client import client
from deluge import component
from deluge.plugins.pluginbase import WebPluginBase from deluge.plugins.pluginbase import WebPluginBase
from common import get_resource from common import get_resource
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
#import deluge.ui.webui.lib.newforms_plus as forms
#config_page_manager = component.get("ConfigPageManager")
FORMAT_LIST = [ FORMAT_LIST = [
('gzmule',_("Emule IP list (GZip)")), ('gzmule', _("Emule IP list (GZip)")),
('spzip',_("SafePeer Text (Zipped)")), ('spzip', _("SafePeer Text (Zipped)")),
('pgtext',_("PeerGuardian Text (Uncompressed)")), ('pgtext', _("PeerGuardian Text (Uncompressed)")),
('p2bgz',_("PeerGuardian P2B (GZip)")) ('p2bgz', _("PeerGuardian P2B (GZip)"))
] ]

View file

@ -1,42 +1,18 @@
# setup.py # -*- coding: utf-8 -*-
# #
# Copyright (C) 2008 Andrew Resch <andrewresch@gmail.com> # Copyright (C) 2009 Andrew Resch <andrewresch@gmail.com>
# #
# This program is free software; you can redistribute it and/or modify # This file is part of Deluge and is licensed under GNU General Public License 3.0, or later, with
# it under the terms of the GNU General Public License as published by # the additional special exception to link portions of this program with the OpenSSL library.
# the Free Software Foundation; either version 3, or (at your option) # See LICENSE for more details.
# any later version.
# #
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
# 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.
#
#
from setuptools import setup, find_packages from setuptools import setup, find_packages
__plugin_name__ = "Blocklist" __plugin_name__ = "Blocklist"
__author__ = "John Garland" __author__ = "John Garland"
__author_email__ = "johnnybg+deluge@gmail.com" __author_email__ = "johnnybg+deluge@gmail.com"
__version__ = "1.2" __version__ = "1.3"
__url__ = "http://deluge-torrent.org" __url__ = "http://deluge-torrent.org"
__license__ = "GPLv3" __license__ = "GPLv3"
__description__ = "Download and import IP blocklists" __description__ = "Download and import IP blocklists"
@ -53,11 +29,9 @@ setup(
license=__license__, license=__license__,
zip_safe=False, zip_safe=False,
long_description=__long_description__, long_description=__long_description__,
packages=find_packages(), packages=find_packages(),
namespace_packages = ["deluge", "deluge.plugins"], namespace_packages=["deluge", "deluge.plugins"],
package_data = __pkg_data__, package_data=__pkg_data__,
entry_points=""" entry_points="""
[deluge.plugin.core] [deluge.plugin.core]
%s = deluge.plugins.%s:CorePlugin %s = deluge.plugins.%s:CorePlugin