You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
2.9 KiB

from axl.axel import Event
from couchpotato.core.helpers.variable import mergeDicts
14 years ago
from couchpotato.core.logger import CPLog
14 years ago
import inspect
import threading
14 years ago
import traceback
log = CPLog(__name__)
events = {}
14 years ago
def addEvent(name, handler):
if events.get(name):
e = events[name]
else:
e = events[name] = Event(threads = 20, exc_info = True, traceback = True, lock = threading.RLock())
14 years ago
def createHandle(handler, *args, **kwargs):
handler.im_self.isRunning(True)
h = handler(*args, **kwargs)
handler.im_self.isRunning(True)
return h
e += createHandle(handler)
def removeEvent(name, handler):
e = events[name]
e -= handler
def fireEvent(name, *args, **kwargs):
#log.debug('Firing "%s": %s, %s' % (name, args, kwargs))
try:
14 years ago
# Return single handler
single = False
try:
del kwargs['single']
single = True
except: pass
# Merge items
merge = False
try:
del kwargs['merge']
merge = True
except: pass
e = events[name]
e.asynchronous = False
14 years ago
result = e(*args, **kwargs)
14 years ago
if single and not merge:
results = None
# Loop over results, stop when first not None result is found.
for r in result:
if r[0] is True and r[1] is not None:
results = r[1]
break
elif r[1]:
errorHandler(r[1])
else:
log.debug('Assume disabled plugin: %s' % r[2])
14 years ago
else:
results = []
for r in result:
if r[0] == True and r[1]:
14 years ago
results.append(r[1])
elif r[1]:
14 years ago
errorHandler(r[1])
# Merge
if merge and len(results) > 0:
# Dict
if type(results[0]) == dict:
merged = {}
for result in results:
merged = mergeDicts(merged, result)
results = merged
# Lists
elif type(results[0]) == list:
merged = []
for result in results:
merged += result
14 years ago
results = merged
14 years ago
return results
except KeyError, e:
pass
except Exception:
log.error('%s: %s' % (name, traceback.format_exc()))
def fireEventAsync(name, *args, **kwargs):
#log.debug('Async "%s": %s, %s' % (name, args, kwargs))
try:
e = events[name]
e.asynchronous = True
14 years ago
e.error_handler = errorHandler
14 years ago
e(*args, **kwargs)
return True
except Exception, e:
14 years ago
log.error('%s: %s' % (name, e))
def errorHandler(error):
etype, value, tb = error
log.error(''.join(traceback.format_exception(etype, value, tb)))
def getEvent(name):
return events[name]