summaryrefslogtreecommitdiffstats
path: root/module/plugins/hooks/IRCInterface.py
diff options
context:
space:
mode:
Diffstat (limited to 'module/plugins/hooks/IRCInterface.py')
-rw-r--r--module/plugins/hooks/IRCInterface.py158
1 files changed, 86 insertions, 72 deletions
diff --git a/module/plugins/hooks/IRCInterface.py b/module/plugins/hooks/IRCInterface.py
index 760c1a4df..efd4e411d 100644
--- a/module/plugins/hooks/IRCInterface.py
+++ b/module/plugins/hooks/IRCInterface.py
@@ -1,73 +1,62 @@
# -*- coding: utf-8 -*-
-"""
- 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 3 of the License,
- or (at your option) 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, see <http://www.gnu.org/licenses/>.
-
- @author: RaNaN
- @author: jeix
- @interface-version: 0.2
-"""
+import re
+import socket
+import ssl
+import time
+from pycurl import FORM_FILE
from select import select
-import socket
from threading import Thread
-import time
from time import sleep
from traceback import print_exc
-import re
-from pycurl import FORM_FILE
-from module.plugins.Hook import Hook
+from module.Api import PackageDoesNotExists, FileDoesNotExists
from module.network.RequestFactory import getURL
+from module.plugins.Hook import Hook
from module.utils import formatSize
-from module.Api import PackageDoesNotExists, FileDoesNotExists
class IRCInterface(Thread, Hook):
- __name__ = "IRCInterface"
- __version__ = "0.11"
- __description__ = """Connect to irc and let owner perform different tasks"""
- __config__ = [("activated", "bool", "Activated", False),
- ("host", "str", "IRC-Server Address", "Enter your server here!"),
+ __name__ = "IRCInterface"
+ __type__ = "hook"
+ __version__ = "0.13"
+
+ __config__ = [("host", "str", "IRC-Server Address", "Enter your server here!"),
("port", "int", "IRC-Server Port", 6667),
("ident", "str", "Clients ident", "pyload-irc"),
("realname", "str", "Realname", "pyload-irc"),
+ ("ssl", "bool", "Use SSL", False),
("nick", "str", "Nickname the Client will take", "pyLoad-IRC"),
("owner", "str", "Nickname the Client will accept commands from", "Enter your nick here!"),
("info_file", "bool", "Inform about every file finished", False),
("info_pack", "bool", "Inform about every package finished", True),
("captcha", "bool", "Send captcha requests", True)]
- __author_name__ = "Jeix"
- __author_mail__ = "Jeix@hasnomail.com"
+
+ __description__ = """Connect to irc and let owner perform different tasks"""
+ __license__ = "GPLv3"
+ __authors__ = [("Jeix", "Jeix@hasnomail.com")]
+
def __init__(self, core, manager):
Thread.__init__(self)
Hook.__init__(self, core, manager)
self.setDaemon(True)
- # self.sm = core.server_methods
- self.api = core.api # todo, only use api
- def coreReady(self):
- self.new_package = {}
- self.abort = False
+ #@TODO: Remove in 0.4.10
+ def initPeriodical(self):
+ pass
- self.links_added = 0
+
+ def coreReady(self):
+ self.abort = False
self.more = []
+ self.new_package = {}
self.start()
+
def packageFinished(self, pypack):
try:
if self.getConfig("info_pack"):
@@ -75,6 +64,7 @@ class IRCInterface(Thread, Hook):
except:
pass
+
def downloadFinished(self, pyfile):
try:
if self.getConfig("info_file"):
@@ -83,6 +73,7 @@ class IRCInterface(Thread, Hook):
except:
pass
+
def newCaptchaTask(self, task):
if self.getConfig("captcha") and task.isTextual():
task.handler.append(self)
@@ -95,19 +86,24 @@ class IRCInterface(Thread, Hook):
self.response(_("New Captcha Request: %s") % url)
self.response(_("Answer with 'c %s text on the captcha'") % task.id)
+
def run(self):
# connect to IRC etc.
self.sock = socket.socket()
host = self.getConfig("host")
self.sock.connect((host, self.getConfig("port")))
+
+ if self.getConfig("ssl"):
+ self.sock = ssl.wrap_socket(self.sock, cert_reqs=ssl.CERT_NONE) #@TODO: support certificate
+
nick = self.getConfig("nick")
self.sock.send("NICK %s\r\n" % nick)
self.sock.send("USER %s %s bla :%s\r\n" % (nick, host, nick))
for t in self.getConfig("owner").split():
if t.strip().startswith("#"):
self.sock.send("JOIN %s\r\n" % t.strip())
- self.logInfo("pyLoad IRC: Connected to %s!" % host)
- self.logInfo("pyLoad IRC: Switching to listening mode!")
+ self.logInfo(_("Connected to"), host)
+ self.logInfo(_("Switching to listening mode!"))
try:
self.main_loop()
@@ -116,6 +112,7 @@ class IRCInterface(Thread, Hook):
print_exc()
self.sock.close()
+
def main_loop(self):
readbuffer = ""
while True:
@@ -154,34 +151,35 @@ class IRCInterface(Thread, Hook):
self.handle_events(msg)
+
def handle_events(self, msg):
- if not msg["origin"].split("!", 1)[0] in self.getConfig("owner").split():
+ if not msg['origin'].split("!", 1)[0] in self.getConfig("owner").split():
return
- if msg["target"].split("!", 1)[0] != self.getConfig("nick"):
+ if msg['target'].split("!", 1)[0] != self.getConfig("nick"):
return
- if msg["action"] != "PRIVMSG":
+ if msg['action'] != "PRIVMSG":
return
# HANDLE CTCP ANTI FLOOD/BOT PROTECTION
- if msg["text"] == "\x01VERSION\x01":
- self.logDebug("Sending CTCP VERSION.")
+ if msg['text'] == "\x01VERSION\x01":
+ self.logDebug("Sending CTCP VERSION")
self.sock.send("NOTICE %s :%s\r\n" % (msg['origin'], "pyLoad! IRC Interface"))
return
- elif msg["text"] == "\x01TIME\x01":
- self.logDebug("Sending CTCP TIME.")
+ elif msg['text'] == "\x01TIME\x01":
+ self.logDebug("Sending CTCP TIME")
self.sock.send("NOTICE %s :%d\r\n" % (msg['origin'], time.time()))
return
- elif msg["text"] == "\x01LAG\x01":
- self.logDebug("Received CTCP LAG.") # don't know how to answer
+ elif msg['text'] == "\x01LAG\x01":
+ self.logDebug("Received CTCP LAG") #: don't know how to answer
return
trigger = "pass"
args = None
try:
- temp = msg["text"].split()
+ temp = msg['text'].split()
trigger = temp[0]
if len(temp) > 1:
args = temp[1:]
@@ -192,9 +190,10 @@ class IRCInterface(Thread, Hook):
try:
res = handler(args)
for line in res:
- self.response(line, msg["origin"])
+ self.response(line, msg['origin'])
except Exception, e:
- self.logError("pyLoad IRC: " + repr(e))
+ self.logError(e)
+
def response(self, msg, origin=""):
if origin == "":
@@ -203,13 +202,15 @@ class IRCInterface(Thread, Hook):
else:
self.sock.send("PRIVMSG %s :%s\r\n" % (origin.split("!", 1)[0], msg))
+
#### Events
def event_pass(self, args):
return []
+
def event_status(self, args):
- downloads = self.api.statusDownloads()
+ downloads = self.core.api.statusDownloads()
if not downloads:
return ["INFO: There are no active downloads currently."]
@@ -233,8 +234,9 @@ class IRCInterface(Thread, Hook):
))
return lines
+
def event_queue(self, args):
- ps = self.api.getQueueData()
+ ps = self.core.api.getQueueData()
if not ps:
return ["INFO: There are no packages in queue."]
@@ -245,8 +247,9 @@ class IRCInterface(Thread, Hook):
return lines
+
def event_collector(self, args):
- ps = self.api.getCollectorData()
+ ps = self.core.api.getCollectorData()
if not ps:
return ["INFO: No packages in collector!"]
@@ -256,27 +259,29 @@ class IRCInterface(Thread, Hook):
return lines
+
def event_info(self, args):
if not args:
- return ['ERROR: Use info like this: info <id>']
+ return ["ERROR: Use info like this: info <id>"]
info = None
try:
- info = self.api.getFileData(int(args[0]))
+ info = self.core.api.getFileData(int(args[0]))
except FileDoesNotExists:
return ["ERROR: Link doesn't exists."]
return ['LINK #%s: %s (%s) [%s][%s]' % (info.fid, info.name, info.format_size, info.statusmsg, info.plugin)]
+
def event_packinfo(self, args):
if not args:
- return ['ERROR: Use packinfo like this: packinfo <id>']
+ return ["ERROR: Use packinfo like this: packinfo <id>"]
lines = []
pack = None
try:
- pack = self.api.getPackageData(int(args[0]))
+ pack = self.core.api.getPackageData(int(args[0]))
except PackageDoesNotExists:
return ["ERROR: Package doesn't exists."]
@@ -300,6 +305,7 @@ class IRCInterface(Thread, Hook):
return lines
+
def event_more(self, args):
if not self.more:
return ["No more information to display."]
@@ -310,20 +316,21 @@ class IRCInterface(Thread, Hook):
return lines
- def event_start(self, args):
- self.api.unpauseServer()
+ def event_start(self, args):
+ self.core.api.unpauseServer()
return ["INFO: Starting downloads."]
- def event_stop(self, args):
- self.api.pauseServer()
+ def event_stop(self, args):
+ self.core.api.pauseServer()
return ["INFO: No new downloads will be started."]
+
def event_add(self, args):
if len(args) < 2:
return ['ERROR: Add links like this: "add <packagename|id> links". ',
- 'This will add the link <link> to to the package <package> / the package with id <id>!']
+ "This will add the link <link> to to the package <package> / the package with id <id>!"]
pack = args[0].strip()
links = [x.strip() for x in args[1:]]
@@ -332,58 +339,62 @@ class IRCInterface(Thread, Hook):
count_failed = 0
try:
id = int(pack)
- pack = self.api.getPackageData(id)
+ pack = self.core.api.getPackageData(id)
if not pack:
return ["ERROR: Package doesn't exists."]
#TODO add links
- return ["INFO: Added %d links to Package %s [#%d]" % (len(links), pack["name"], id)]
+ return ["INFO: Added %d links to Package %s [#%d]" % (len(links), pack['name'], id)]
except:
# create new package
- id = self.api.addPackage(pack, links, 1)
+ id = self.core.api.addPackage(pack, links, 1)
return ["INFO: Created new Package %s [#%d] with %d links." % (pack, id, len(links))]
+
def event_del(self, args):
if len(args) < 2:
return ["ERROR: Use del command like this: del -p|-l <id> [...] (-p indicates that the ids are from packages, -l indicates that the ids are from links)"]
if args[0] == "-p":
- ret = self.api.deletePackages(map(int, args[1:]))
+ ret = self.core.api.deletePackages(map(int, args[1:]))
return ["INFO: Deleted %d packages!" % len(args[1:])]
elif args[0] == "-l":
- ret = self.api.delLinks(map(int, args[1:]))
+ ret = self.core.api.delLinks(map(int, args[1:]))
return ["INFO: Deleted %d links!" % len(args[1:])]
else:
return ["ERROR: Use del command like this: del <-p|-l> <id> [...] (-p indicates that the ids are from packages, -l indicates that the ids are from links)"]
+
def event_push(self, args):
if not args:
return ["ERROR: Push package to queue like this: push <package id>"]
id = int(args[0])
try:
- info = self.api.getPackageInfo(id)
+ info = self.core.api.getPackageInfo(id)
except PackageDoesNotExists:
return ["ERROR: Package #%d does not exist." % id]
- self.api.pushToQueue(id)
+ self.core.api.pushToQueue(id)
return ["INFO: Pushed package #%d to queue." % id]
+
def event_pull(self, args):
if not args:
return ["ERROR: Pull package from queue like this: pull <package id>."]
id = int(args[0])
- if not self.api.getPackageData(id):
+ if not self.core.api.getPackageData(id):
return ["ERROR: Package #%d does not exist." % id]
- self.api.pullFromQueue(id)
+ self.core.api.pullFromQueue(id)
return ["INFO: Pulled package #%d from queue to collector." % id]
+
def event_c(self, args):
""" captcha answer """
if not args:
@@ -396,6 +407,7 @@ class IRCInterface(Thread, Hook):
task.setResult(" ".join(args[1:]))
return ["INFO: Result %s saved." % " ".join(args[1:])]
+
def event_help(self, args):
lines = ["The following commands are available:",
"add <package|packid> <links> [...] Adds link to package. (creates new package if it does not exist)",
@@ -415,8 +427,10 @@ class IRCInterface(Thread, Hook):
class IRCError(Exception):
+
def __init__(self, value):
self.value = value
+
def __str__(self):
return repr(self.value)