summaryrefslogtreecommitdiffstats
path: root/module/plugins/hooks/UpdateManager.py
diff options
context:
space:
mode:
Diffstat (limited to 'module/plugins/hooks/UpdateManager.py')
-rw-r--r--module/plugins/hooks/UpdateManager.py276
1 files changed, 148 insertions, 128 deletions
diff --git a/module/plugins/hooks/UpdateManager.py b/module/plugins/hooks/UpdateManager.py
index c72699228..98d602226 100644
--- a/module/plugins/hooks/UpdateManager.py
+++ b/module/plugins/hooks/UpdateManager.py
@@ -2,81 +2,98 @@
from __future__ import with_statement
+import os
import re
import sys
+import time
from operator import itemgetter
-from os import path, remove, stat
from module.network.RequestFactory import getURL
from module.plugins.Hook import Expose, Hook, threaded
from module.utils import save_join
+# Case-sensitive os.path.exists
+def exists(path):
+ if os.path.exists(path):
+ if os.name == 'nt':
+ dir, name = os.path.split(path)
+ return name in os.listdir(dir)
+ else:
+ return True
+ else:
+ return False
+
+
class UpdateManager(Hook):
__name__ = "UpdateManager"
__type__ = "hook"
- __version__ = "0.42"
+ __version__ = "0.52"
- __config__ = [("activated" , "bool" , "Activated" , True ),
- ("mode" , "pyLoad + plugins;plugins only", "Check updates for" , "pyLoad + plugins"),
- ("interval" , "int" , "Check interval in hours" , 8 ),
- ("autorestart" , "bool" , "Automatically restart pyLoad when required" , True ),
- ("reloadplugins", "bool" , "Monitor plugins for code changes in debug mode", True ),
- ("nodebugupdate", "bool" , "Don't check for updates in debug mode" , True )]
+ __config__ = [("activated" , "bool", "Activated" , True ),
+ ("checkinterval", "int" , "Check interval in hours" , 8 ),
+ ("autorestart" , "bool", "Auto-restart pyLoad when required" , True ),
+ ("checkonstart" , "bool", "Check for updates on startup" , True ),
+ ("checkperiod" , "bool", "Check for updates periodically" , True ),
+ ("reloadplugins", "bool", "Monitor plugin code changes in debug mode", True ),
+ ("nodebugupdate", "bool", "Don't update plugins in debug mode" , False)]
__description__ = """ Check for updates """
__license__ = "GPLv3"
__authors__ = [("Walter Purcaro", "vuolter@gmail.com")]
- # event_list = ["pluginConfigChanged"]
+ interval = 0
- SERVER_URL = "http://updatemanager.pyload.org"
- VERSION = re.compile(r'__version__.*=.*("|\')([\d.]+)')
- MIN_INTERVAL = 3 * 60 * 60 #: 3h minimum check interval (value is in seconds)
+ SERVER_URL = "http://updatemanager.pyload.org"
+ MIN_CHECK_INTERVAL = 3 * 60 * 60 #: 3 hours
- def pluginConfigChanged(self, plugin, name, value):
- if name == "interval":
- interval = value * 60 * 60
- if self.MIN_INTERVAL <= interval != self.interval:
- self.core.scheduler.removeJob(self.cb)
- self.interval = interval
- self.initPeriodical()
- else:
- self.logDebug("Invalid interval value, kept current")
+ def coreReady(self):
+ if self.checkonstart:
+ self.core.api.pauseServer()
+ self.update()
+ if self.do_restart is False:
+ self.core.api.unpauseServer()
- elif name == "reloadplugins":
- if self.cb2:
- self.core.scheduler.removeJob(self.cb2)
- if value is True and self.core.debug:
- self.periodical2()
+ self.initPeriodical()
- def coreReady(self):
- self.pluginConfigChanged(self.__name__, "interval", self.getConfig("interval"))
- x = lambda: self.pluginConfigChanged(self.__name__, "reloadplugins", self.getConfig("reloadplugins"))
- self.core.scheduler.addJob(10, x, threaded=False)
+ def setup(self):
+ self.info = {'pyload': False, 'version': None, 'plugins': False, 'last_check': time.time()}
+ self.mtimes = {} #: store modification time for each plugin
+ self.event_list = ["allDownloadsProcessed"]
- def unload(self):
- self.pluginConfigChanged(self.__name__, "reloadplugins", False)
+ self.interval = 10
+ if self.getConfig('checkonstart'):
+ self.core.api.pauseServer()
+ self.checkonstart = True
+ else:
+ self.checkonstart = False
- def setup(self):
- self.cb2 = None
- self.interval = self.MIN_INTERVAL
- self.updating = False
- self.info = {'pyload': False, 'version': None, 'plugins': False}
- self.mtimes = {} #: store modification time for each plugin
+ self.do_restart = False
- def periodical2(self):
- if not self.updating:
- self.autoreloadPlugins()
+ def allDownloadsProcessed(self):
+ if self.do_restart is True:
+ self.logWarning(_("Downloads are done, restarting pyLoad to reload the updated plugins"))
+ self.core.api.restart()
+
+
+ def periodical(self):
+ if self.core.debug:
+ if self.getConfig('reloadplugins'):
+ self.autoreloadPlugins()
+
+ if self.getConfig('nodebugupdate'):
+ return
- self.cb2 = self.core.scheduler.addJob(4, self.periodical2, threaded=False)
+ if self.getConfig('checkperiod') \
+ and time.time() - max(self.MIN_CHECK_INTERVAL, self.getConfig('checkinterval') * 60 * 60) > self.info['last_check']:
+ self.update()
@Expose
@@ -95,10 +112,10 @@ class UpdateManager(Hook):
id = (type, name)
if type in self.core.pluginManager.plugins:
f = m.__file__.replace(".pyc", ".py")
- if not path.isfile(f):
+ if not os.path.isfile(f):
continue
- mtime = stat(f).st_mtime
+ mtime = os.stat(f).st_mtime
if id not in self.mtimes:
self.mtimes[id] = mtime
@@ -109,105 +126,101 @@ class UpdateManager(Hook):
return True if self.core.pluginManager.reloadPlugins(reloads) else False
- def periodical(self):
- if not self.info['pyload'] and not (self.getConfig("nodebugupdate") and self.core.debug):
- self.updateThread()
-
-
- def server_request(self):
+ def server_response(self):
try:
return getURL(self.SERVER_URL, get={'v': self.core.api.getServerVersion()}).splitlines()
- except:
- self.logWarning(_("Unable to contact server to get updates"))
+ except Exception:
+ self.logWarning(_("Unable to retrieve server to get updates"))
- @threaded
- def updateThread(self):
- self.updating = True
- status = self.update(onlyplugin=self.getConfig("mode") == "plugins only")
-
- if status is 2 and self.getConfig("autorestart"):
- self.core.api.restart()
- else:
- self.updating = False
+ @Expose
+ @threaded
+ def update(self):
+ """ check for updates """
+ if self._update() is 2 and self.getConfig('autorestart'):
+ if not self.core.api.statusDownloads():
+ self.core.api.restart()
+ else:
+ self.do_restart = True
+ self.logWarning(_("Downloads are active, will restart once the download is done"))
+ self.core.api.pauseServer()
- @Expose
- def updatePlugins(self):
- """ simple wrapper for calling plugin update quickly """
- return self.update(onlyplugin=True)
+ def _update(self):
+ data = self.server_response()
- @Expose
- def update(self, onlyplugin=False):
- """ check for updates """
- data = self.server_request()
+ self.info['last_check'] = time.time()
if not data:
exitcode = 0
elif data[0] == "None":
self.logInfo(_("No new pyLoad version available"))
- updates = data[1:]
- exitcode = self._updatePlugins(updates)
+ exitcode = self._updatePlugins(data[1:])
elif onlyplugin:
exitcode = 0
else:
- newversion = data[0]
- self.logInfo(_("*** New pyLoad Version %s available ***") % newversion)
+ self.logInfo(_("*** New pyLoad Version %s available ***") % data[0])
self.logInfo(_("*** Get it here: https://github.com/pyload/pyload/releases ***"))
+ self.info['pyload'] = True
+ self.info['version'] = data[0]
exitcode = 3
- self.info['pyload'] = True
- self.info['version'] = newversion
- return exitcode #: 0 = No plugins updated; 1 = Plugins updated; 2 = Plugins updated, but restart required; 3 = No plugins updated, new pyLoad version available
+ # Exit codes:
+ # -1 = No plugin updated, new pyLoad version available
+ # 0 = No plugin updated
+ # 1 = Plugins updated
+ # 2 = Plugins updated, but restart required
+ return exitcode
- def _updatePlugins(self, updates):
+ def _updatePlugins(self, data):
""" check for plugin updates """
- if self.info['plugins']:
- return False #: plugins were already updated
-
exitcode = 0
updated = []
- url = updates[0]
- schema = updates[1].split('|')
+ url = data[0]
+ schema = data[1].split('|')
- if "BLACKLIST" in updates:
- blacklist = updates[updates.index('BLACKLIST') + 1:]
- updates = updates[2:updates.index('BLACKLIST')]
+ VERSION = re.compile(r'__version__.*=.*("|\')([\d.]+)')
+
+ if "BLACKLIST" in data:
+ blacklist = data[data.index('BLACKLIST') + 1:]
+ updatelist = data[2:data.index('BLACKLIST')]
else:
- blacklist = None
- updates = updates[2:]
+ blacklist = []
+ updatelist = data[2:]
- upgradable = [dict(zip(schema, x.split('|'))) for x in updates]
- blacklisted = [(x.split('|')[0], x.split('|')[1].rsplit('.', 1)[0]) for x in blacklist] if blacklist else []
+ updatelist = [dict(zip(schema, x.split('|'))) for x in updatelist]
+ blacklist = [dict(zip(schema, x.split('|'))) for x in blacklist]
if blacklist:
+ type_plugins = [(plugin['type'], plugin['name'].rsplit('.', 1)[0]) for plugin in blacklist]
+
# Protect UpdateManager from self-removing
try:
- blacklisted.remove(("hook", "UpdateManager"))
- except:
+ type_plugins.remove(("hook", "UpdateManager"))
+ except ValueError:
pass
- for t, n in blacklisted:
- for idx, plugin in enumerate(upgradable):
+ for t, n in type_plugins:
+ for idx, plugin in enumerate(updatelist):
if n == plugin['name'] and t == plugin['type']:
- upgradable.pop(idx)
+ updatelist.pop(idx)
break
- for t, n in self.removePlugins(sorted(blacklisted)):
- self.logInfo(_("Removed blacklisted plugin [%(type)s] %(name)s") % {
+ for t, n in self.removePlugins(sorted(type_plugins)):
+ self.logInfo(_("Removed blacklisted plugin: [%(type)s] %(name)s") % {
'type': t,
'name': n,
})
- for plugin in sorted(upgradable, key=itemgetter("type", "name")):
+ for plugin in sorted(updatelist, key=itemgetter("type", "name")):
filename = plugin['name']
prefix = plugin['type']
version = plugin['version']
@@ -217,7 +230,7 @@ class UpdateManager(Hook):
else:
name = filename.replace(".py", "")
- #@TODO: obsolete after 0.4.10
+ #@TODO: Remove in 0.4.10
if prefix.endswith("s"):
type = prefix[:-1]
else:
@@ -241,7 +254,7 @@ class UpdateManager(Hook):
'newver': newver})
try:
content = getURL(url % plugin)
- m = self.VERSION.search(content)
+ m = VERSION.search(content)
if m and m.group(2) == version:
with open(save_join("userplugins", prefix, filename), "wb") as f:
@@ -252,21 +265,27 @@ class UpdateManager(Hook):
raise Exception, _("Version mismatch")
except Exception, e:
- self.logError(_("Error updating plugin: %s") % filename, str(e))
+ self.logError(_("Error updating plugin: %s") % filename, e)
if updated:
- reloaded = self.core.pluginManager.reloadPlugins(updated)
- if reloaded:
- self.logInfo(_("Plugins updated and reloaded"))
+ self.logInfo(_("*** Plugins updated ***"))
+
+ if self.core.pluginManager.reloadPlugins(updated):
exitcode = 1
else:
- self.logInfo(_("*** Plugins have been updated, but need a pyLoad restart to be reloaded ***"))
+ self.logWarning(_("pyLoad restart required to reload the updated plugins"))
self.info['plugins'] = True
exitcode = 2
+
+ self.manager.dispatchEvent("plugin_updated", updated)
else:
self.logInfo(_("No plugin updates available"))
- return exitcode #: 0 = No plugins updated; 1 = Plugins updated; 2 = Plugins updated, but restart required
+ # Exit codes:
+ # 0 = No plugin updated
+ # 1 = Plugins updated
+ # 2 = Plugins updated, but restart required
+ return exitcode
@Expose
@@ -276,35 +295,36 @@ class UpdateManager(Hook):
if not type_plugins:
return
- self.logDebug("Requested deletion of plugins: %s" % type_plugins)
+ removed = set()
- removed = []
+ self.logDebug("Requested deletion of plugins: %s" % type_plugins)
for type, name in type_plugins:
- err = False
- file = name + ".py"
-
- for root in ("userplugins", path.join(pypath, "module", "plugins")):
+ rootplugins = os.path.join(pypath, "module", "plugins")
- filename = save_join(root, type, file)
- try:
- remove(filename)
- except Exception, e:
- self.logDebug("Error removing: %s" % path.basename(filename), str(e))
- err = True
+ for dir in ("userplugins", rootplugins):
+ py_filename = save_join(dir, type, name + ".py")
+ pyc_filename = py_filename + "c"
- filename += "c"
- if path.isfile(filename):
+ if type == "hook":
try:
- if type == "hook":
- self.manager.deactivateHook(name)
- remove(filename)
+ self.manager.deactivateHook(name)
+
except Exception, e:
- self.logDebug("Error removing: %s" % path.basename(filename), str(e))
- err = True
+ self.logDebug(e)
+
+ for filename in (py_filename, pyc_filename):
+ if not exists(filename):
+ continue
+
+ try:
+ os.remove(filename)
+
+ except OSError, e:
+ self.logError(_("Error removing: %s") % filename, e)
- if not err:
- id = (type, name)
- removed.append(id)
+ else:
+ id = (type, name)
+ removed.add(id)
- return removed #: return a list of the plugins successfully removed
+ return list(removed) #: return a list of the plugins successfully removed