diff options
author | mrDoctorWho <mrdoctorwho@gmail.com> | 2015-03-21 15:08:30 +0300 |
---|---|---|
committer | mrDoctorWho <mrdoctorwho@gmail.com> | 2015-03-21 15:08:30 +0300 |
commit | 92ab5fc6b9cc9dd9401d095f93fd981ae08a5ce0 (patch) | |
tree | 8b4eac42854a4b57975def99e89ce606b69f774d | |
parent | 0190703dd132e810c89e5e8551478d15b5726afd (diff) |
Updated description for "tie_chat_to_nickname" user config field
Fixed a typo in mod_iq_vcard
New admin feature: now you can easy (re)/(un)load any transport's module and reload extensions
Little code cleanup in mod_iq_disco and added a warning about it's code
-rw-r--r-- | extensions/groupchats.py | 10 | ||||
-rw-r--r-- | gateway.py | 76 | ||||
-rw-r--r-- | modules/mod_iq_disco.py | 134 | ||||
-rw-r--r-- | modules/mod_iq_vcard.py | 2 |
4 files changed, 142 insertions, 80 deletions
diff --git a/extensions/groupchats.py b/extensions/groupchats.py index c8ad7a8..146c3b1 100644 --- a/extensions/groupchats.py +++ b/extensions/groupchats.py @@ -508,16 +508,15 @@ if isdef("ConferenceServer") and ConferenceServer: "desc": "If set, transport will show ALL users in a conference, even you", "value": 0} GLOBAL_USER_SETTINGS["tie_chat_to_nickname"] = {"label": "Tie chat to my nickname (tip: enable timestamp for groupchats)", - "desc": "If set, your messages will be sent only from your nickname "\ - "(there is no way to determine whether a message was sent from you or from the transport, so this setting might help, but"\ - "it will bring one bug: you wont be able to send any message if chat is not initialized. " - "Chat initializes when first message received after transport's boot", "value": 1} + "desc": "If set, your messages will be sent only from your nickname\n"\ + "(there is no way to determine whether a message was sent\nfrom you or from the transport, so this setting might help,\nbut"\ + " it will bring one bug: you wont be able to send any message if chat is not initialized. " + "\nChat initializes when first message received after transport's boot", "value": 1} GLOBAL_USER_SETTINGS["force_vk_date_group"] = {"label": "Force VK timestamp for groupchat messages", "value": 1} TRANSPORT_SETTINGS["destroy_on_leave"] = {"label": "Destroy groupchat if user leaves it", "value": 0} - logger.info("extension groupchats is loaded") TransportFeatures.add(xmpp.NS_GROUPCHAT) registerHandler("msg01", outgoingChatMessageHandler) registerHandler("msg02", incomingChatMessageHandler) @@ -525,6 +524,7 @@ if isdef("ConferenceServer") and ConferenceServer: registerHandler("prs01", handleChatPresences) registerHandler("evt01", initChatExtension) registerHandler("evt03", exterminateChats) + logger.info("extension groupchats is loaded") else: del sendIQ, makeMember, makeOutcast, inviteUser, joinChat, leaveChat, \ @@ -92,7 +92,7 @@ Config = args.config logger = logging.getLogger("vk4xmpp") logger.setLevel(LOG_LEVEL) loggerHandler = logging.FileHandler(logFile) -formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(name)s %(message)s", "[%d.%m.%Y %H:%M:%S]") +formatter = logging.Formatter("%(asctime)s %(levelname)s: %(name)s: %(message)s"), "%d.%m.%Y %H:%M:%S") loggerHandler.setFormatter(formatter) logger.addHandler(loggerHandler) @@ -1202,18 +1202,6 @@ def loadExtensions(dir): execfile("%s/%s" % (dir, file), globals()) -def getModulesList(): - """ - Makes a list of modules could be found in modules folder - """ - modules = [] - for file in os.listdir("modules"): - name, ext = os.path.splitext(file) - if ext == ".py": - modules.append(name) - return modules - - class ModuleLoader: """ @@ -1229,26 +1217,51 @@ class ModuleLoader: def __register(cls, module): if hasattr(module, "load"): module.load() - ModuleLoader.loaded.add(module) + ModuleLoader.loaded.add(module.__name__) @classmethod def __unregister(self, module): if hasattr(module, "unload"): module.unload() - ModuleLoader.loaded.remove(module) + ModuleLoader.loaded.remove(module.__name__) + + @classmethod + def list(cls): + modules = [] + for file in os.listdir("modules"): + name, ext = os.path.splitext(file) + if ext == ".py": + modules.append(name) + return modules + + @classmethod + def reload(cls, name): + if name in sys.modules: + module = sys.modules[name] + cls.__unregister(module) + reload(module) + return module + @classmethod def load(cls, list=[]): - result =[] + result = [] + errors = [] for name in list: - try: - module = __import__(name, globals(), locals()) - except Exception: - crashlog("module_loader") + if name in cls.loaded: + try: module = cls.reload(name) + except Exception: errors.append(name); continue else: - result.append(name) - cls.__register(module) - return result + try: + module = __import__(name, globals(), locals()) + except Exception: + crashLog("module_loader") + errors.append(name) + continue + + result.append(name) + cls.__register(module) + return (result, errors) @classmethod def unload(cls, list=[]): @@ -1260,21 +1273,6 @@ class ModuleLoader: result.append(name) return result - @classmethod - def reload(cls, list=[]): - result = [] - for name in list: - if name in sys.modules: - module = sys.modules[name] - cls.__unregister(module) - try: - cls.__register(reload(module)) - except Exception: - crashlog("module_loader") - else: - result.append(name) - return result - def connect(): """ @@ -1322,7 +1320,7 @@ def runMainActions(): runThread(event, (), "extension-%d" % num) runThread(Poll.process, (), "longPoll") runThread(updateCron, (), "updateCron") - ModuleLoader.load(getModulesList()) + ModuleLoader.load(ModuleLoader.list()) def main(): diff --git a/modules/mod_iq_disco.py b/modules/mod_iq_disco.py index 7c1c78d..d3957ed 100644 --- a/modules/mod_iq_disco.py +++ b/modules/mod_iq_disco.py @@ -1,6 +1,8 @@ # coding: utf-8 # This file is a part of VK4XMPP transport # © simpleApps, 2014 — 2015. +# Warning: This module contains non-optimal and really bad code. + from __main__ import * from __main__ import _ @@ -12,7 +14,10 @@ NODES = {"admin": ("Delete users", "Show crashlogs", "Reload config", "Global Transport settings", - "Check an API token"), + "Check an API token", + "Unload modules", + "(Re)load modules", + "Reload extensions"), "user": ("Edit settings",)} FORM_TYPES = ("text-single", "text-multi", "jid-multi") @@ -22,7 +27,6 @@ def disco_handler(cl, iq): destination = iq.getTo().getStripped() ns = iq.getQueryNS() node = iq.getTagAttr("query", "node") - if not node: payload = [] if destination == TransportID: @@ -149,10 +153,9 @@ def commands_handler(cl, iq): form = cmd.getTag("x", namespace=xmpp.NS_DATA) action = cmd.getAttr("action") completed = False + note = None simpleForm = buildForm(fields=[dict(var="FORM_TYPE", type="hidden", value=xmpp.NS_ADMIN)]) if node and action != "cancel": - if not form: - commandTag = result.setTag("command", {"status": "executing", "node": node, "sessionid": iq.getID()}, xmpp.NS_COMMANDS) if source in ADMIN_JIDS: if node == "Delete users": if not form: @@ -162,6 +165,7 @@ def commands_handler(cl, iq): form = getForm(node=form).asDict() if form.get("jids"): runThread(deleteUsers, (form["jids"],)) + simpleForm = None completed = True elif node == "Global message": @@ -174,6 +178,8 @@ def commands_handler(cl, iq): if form.has_key("text"): text = "\n".join(form["text"]) runThread(sendGlobalMessage, (text,)) + note = "The message was sent." + simpleForm = None completed = True elif node == "Show crashlogs": @@ -190,43 +196,46 @@ def commands_handler(cl, iq): body = None if os.path.exists(filename): body = rFile(filename) - commandTag = result.setTag("command", {"status": "executing", "node": node, "sessionid": sessionid}, xmpp.NS_COMMANDS) simpleForm = buildForm(simpleForm, - fields=[{"var": "body", "type": "text-multi", "label": "Error body", "value": body}] ) - commandTag.addChild(node=simpleForm) + fields=[{"var": "body", "type": "text-multi", "label": "Error body", "value": body}]) completed = True elif node == "Check an API token": - - if not form: - simpleForm = buildForm(simpleForm, - fields=[{"var": "token", "type": "text-single", "label": "API Token"}], - title=_("Enter the API token")) - else: - commandTag = result.setTag("command", {"status": "executing", "node": node, "sessionid": sessionid}, xmpp.NS_COMMANDS) - form = getForm(node=form).asDict() - if form.get("token"): - token = form["token"] - _result = checkAPIToken(token) - - if isinstance(_result, dict): - _fields = dictToDataForm(_result) - else: - _fields = [{"var": "body", "value": str(_result), "type": "text-multi"}] - - simpleForm = buildForm(simpleForm, fields=_fields) - commandTag.addChild(node=simpleForm) - completed = True - + if not form: + simpleForm = buildForm(simpleForm, + fields=[{"var": "token", "type": "text-single", "label": "API Token"}], + title=_("Enter the API token")) + else: + form = getForm(node=form).asDict() + if form.get("token"): + token = form["token"] + _result = checkAPIToken(token) + + if isinstance(_result, dict): + _fields = dictToDataForm(_result) + else: + _fields = [{"var": "body", "value": str(_result), "type": "text-multi"}] + + simpleForm = buildForm(simpleForm, fields=_fields) + completed = True + elif node == "Reload config": + simpleForm = None + completed = True try: execfile(Config, globals()) + note = "Reloaded well." except Exception: -## commandTag = result.setTag("command", {"status": "executing", "node": node, "sessionid": sessionid}, xmpp.NS_COMMANDS) - simpleForm = buildForm(simpleForm, - fields=[{"var": "body", "type": "text-multi", "label": "Error while loading the config file", "value": wException()}]) - + note = wException() + + elif node == "Reload extensions": + simpleForm = None completed = True + try: + loadExtensions("extensions") + note = "Reloaded well." + except Exception: + note = wException() elif node == "Global Transport settings": config = transportSettings.settings @@ -243,8 +252,55 @@ def commands_handler(cl, iq): for key in form.keys(): if key in config.keys(): transportSettings.settings[key]["value"] = utils.normalizeValue(form[key]) + note = "The settings were changed." + simpleForm = None + completed = True + + elif node == "(Re)load modules": + modules = ModuleLoader.list() + if not form: + _fields = dictToDataForm(dict(map(lambda mod: (mod, mod in ModuleLoader.loaded), modules))) + simpleForm = buildForm(simpleForm, fields=_fields, title="(Re)load modules", + data=[_("Modules can be loaded or reloaded if they already loaded")]) + + elif form: + form = getForm(node=form).asDict() + keys = [] + for key in form.keys(): + if key in modules and utils.normalizeValue(form[key]): + keys.append(key) + + loaded, errors = ModuleLoader.load(list=keys) + _fields = [] + if loaded: + _fields.append({"var": "loaded", "label": "loaded", "type": "text-multi", "value": str.join("\n", loaded)}) + if errors: + _fields.append({"var": "errors", "label": "errors", "type": "text-multi", "value": str.join("\n", errors)}) + + simpleForm = buildForm(simpleForm, fields=_fields, title="Result") + completed = True + + elif node == "Unload modules": + modules = ModuleLoader.loaded.copy() + modules.remove("mod_iq_disco") + if not form: + _fields = dictToDataForm(dict(map(lambda mod: (mod, False), modules))) + simpleForm = buildForm(simpleForm, fields=_fields, title="Unload modules") + + elif form: + form = getForm(node=form).asDict() + keys = [] + for key in form.keys(): + if key in ModuleLoader.loaded and utils.normalizeValue(form[key]): + keys.append(key) + + unload = ModuleLoader.unload(list=keys) + _fields = [{"var": "loaded", "label": "unloaded", "type": "text-multi", "value": str.join("\n", unload)}] + + simpleForm = buildForm(simpleForm, fields=_fields, title="Result") completed = True + if node == "Edit settings" and source in Transport: logger.info("user want to edit their settings (jid: %s)" % source) config = Transport[source].settings @@ -263,13 +319,21 @@ def commands_handler(cl, iq): for key in form.keys(): if key in config.keys(): Transport[source].settings[key] = utils.normalizeValue(form[key]) + note = "The settings were changed." + simpleForm = None completed = True if completed: - result.setTag("command", {"status": "completed", "node": node, "sessionid": sessionid}, namespace=xmpp.NS_COMMANDS) - elif not form: + commandTag = result.setTag("command", {"status": "completed", "node": node, "sessionid": sessionid}, namespace=xmpp.NS_COMMANDS) + if simpleForm: + commandTag.addChild(node=simpleForm) + if note: + commandTag.setTag("note", {"type": "info"}) + commandTag.setTagData("note", note) + + elif not form and simpleForm: + commandTag = result.setTag("command", {"status": "executing", "node": node, "sessionid": sessionid}, namespace=xmpp.NS_COMMANDS) commandTag.addChild(node=simpleForm) - sender(cl, result) diff --git a/modules/mod_iq_vcard.py b/modules/mod_iq_vcard.py index d263822..17a07ad 100644 --- a/modules/mod_iq_vcard.py +++ b/modules/mod_iq_vcard.py @@ -73,5 +73,5 @@ def load(): def unload(): - TransportFeautres.remove(xmpp.NS_VCARD) + TransportFeatures.remove(xmpp.NS_VCARD) Component.UnregisterHandler("iq", vcard_handler, "get", xmpp.NS_VCARD)
\ No newline at end of file |