diff options
author | mrDoctorWho <mrdoctorwho@gmail.com> | 2015-02-21 13:48:54 +0300 |
---|---|---|
committer | mrDoctorWho <mrdoctorwho@gmail.com> | 2015-02-21 13:48:54 +0300 |
commit | a1704abb3a3e6e5bae07bc423a70cfc53422ecca (patch) | |
tree | 09fdf25ec1a0e7bd46517865e810cef7029bd0c4 | |
parent | 922019d49c54710351629dcdbfbdc056192b7bfb (diff) |
Fixed registration form strings
Completed "Check an API token" option in adhoc
Little refactoring in mod_iq_disco
Added translation feature to adhoc items, but those are still in english. Translators are
welcome!
-rw-r--r-- | extensions/.example.py | 10 | ||||
-rw-r--r-- | extensions/groupchats.py | 11 | ||||
-rw-r--r-- | gateway.py | 45 | ||||
-rw-r--r-- | library/stext.py | 20 | ||||
-rw-r--r-- | library/utils.py | 2 | ||||
-rw-r--r-- | locales/locale.ru | 12 | ||||
-rw-r--r-- | modules/mod_iq_disco.py | 141 | ||||
-rw-r--r-- | modules/mod_iq_register.py | 2 |
8 files changed, 171 insertions, 72 deletions
diff --git a/extensions/.example.py b/extensions/.example.py index 2a5db55..d81b09b 100644 --- a/extensions/.example.py +++ b/extensions/.example.py @@ -5,6 +5,16 @@ # Rename it to "example.py" if you wanna test it # Please notice that plugins are working in globals() so names must be unique +## Events (not finished yet so not sorted): +# 01 - transport's start (threaded), no args +# 02 - transport's shutdown (linear) +# 03 - user deletion (linear) +# 04 - captcha (linear) +# 05 - user became online (threaded) +# 06 - user became offline (linear) +# 07 - user is logging in (linear, before the friends are received) +## Messages: 01 outgoing (vk->xmpp), 02 incoming (xmpp), 03 is used to modify message (xmpp) +## Presences: 01 incoming presence, 02 - is used to modify outgoing presence (xmpp) def evt01_handler(): """ diff --git a/extensions/groupchats.py b/extensions/groupchats.py index 22b051f..9f88895 100644 --- a/extensions/groupchats.py +++ b/extensions/groupchats.py @@ -128,6 +128,7 @@ class Chat(object): self.raw_users = users self.created = False self.invited = False + self.xmpp_owner = None self.topic = topic self.errors = [] self.creation_date = date @@ -368,6 +369,8 @@ def handleChatPresences(source, prs): makeOutcast(source, jid, TransportID, _("Get the hell outta here!")) else: leaveChat(source, jid, _("I am not welcomed here")) + if (prs.getRole(), prs.getAffiliation()) == ("moderator", "owner"): + chat.xmpp_owner = jid def exterminateChats(user): @@ -383,7 +386,13 @@ def exterminateChats(user): if ConferenceServer: - GLOBAL_USER_SETTINGS["show_all_chat_users"] = {"label": "Show all chat users (only active ones by default)", "value": 0} + + GLOBAL_USER_SETTINGS["show_all_chat_users"] = {"label": "Show all chat users", + "desc": "If set, transport will show ALL users in a conference, even you", "value": 0} + + GLOBAL_USER_SETTINGS["groupchats"] = {"label": "Handle groupchats", + "desc": "If set, transport would create xmpp-chatrooms for VK Multi-Dialogs", "value": 1} + logger.info("extension groupchats is loaded") TransportFeatures.append(xmpp.NS_GROUPCHAT) registerHandler("msg01", outgoingChatMessageHandler) @@ -84,13 +84,6 @@ THREAD_STACK_SIZE = 0 USER_LIMIT = 0 VK_ACCESS = 69638 -GLOBAL_USER_SETTINGS = {"groupchats": {"label": "Handle groupchats", "value": 1}, - "keep_onlne": {"label": "Keep my status online", "value": 1}, - "i_am_ghost": {"label": "I am a ghost", "value": 0}} - -TRANSPORT_SETTINGS = {"send_unavailable": {"label": "Send unavailable from "\ - "friends when user log off", "value": 0}} - # used files pidFile = "pidFile.txt" logFile = "vk4xmpp.log" @@ -142,8 +135,18 @@ formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(name)s %(message)s", loggerHandler.setFormatter(formatter) logger.addHandler(loggerHandler) +# Setting variables: DefLang for language id, root for translations directory setVars(DefLang, root) + +# Settings +GLOBAL_USER_SETTINGS = {"keep_onlne": {"label": "Keep my status online", "value": 1}, + "i_am_ghost": {"label": "I am a ghost", "value": 0}} + +TRANSPORT_SETTINGS = {"send_unavailable": {"label": "Send unavailable from "\ + "friends when user log off", "value": 0}} + + if THREAD_STACK_SIZE: threading.stack_size(THREAD_STACK_SIZE) del formatter, loggerHandler @@ -151,16 +154,7 @@ del formatter, loggerHandler OS = "{0} {2:.16} [{4}]".format(*os.uname()) Python = "{0} {1}.{2}.{3}".format(sys.subversion[0], *sys.version_info) -## Events (not finished yet so not sorted): -# 01 - start (threaded), no args -# 02 - shutdown (linear) -# 03 - user deletion (linear) -# 04 - captcha (linear) -# 05 - user became online (threaded) -# 06 - user became offline (linear) -# 07 - user is logging in (linear, before the friends are received) -## Messages: 01 outgoing (vk->xmpp), 02 incoming (xmpp), 03 is used to modify message (xmpp) -## Presences: 01 incoming presence, 02 - is used to modify outgoing presence (xmpp) +# See extensions/.example.py for more information about handlers Handlers = {"msg01": [], "msg02": [], "msg03": [], "evt01": [], "evt02": [], "evt03": [], @@ -313,12 +307,17 @@ class Settings(object): self.settings = deepcopy(GLOBAL_USER_SETTINGS) else: self.settings = TRANSPORT_SETTINGS - self.settings.update(eval(rFile(self.filename))) ## better use json.load() instead + userSettings = eval(rFile(self.filename)) or {} + for key, values in userSettings.iteritems(): + if key in self.settings: + self.settings[key]["value"] = values["value"] + self.keys = self.settings.keys self.items = self.settings.items self.source = source save = lambda self: wFile(self.filename, str(self.settings)) + __getitem__ = lambda self, key: self.settings[key] def __setitem__(self, key, value): @@ -477,6 +476,9 @@ class VK(object): try: result = self.engine.method(method, args, nodecode) except (api.InternalServerError, api.AccessDenied) as e: + # To prevent returning True from checkData() + if force: + raise pass except api.NetworkNotFound as e: @@ -573,10 +575,11 @@ class VK(object): Otherwise will request method users.get Default fields is ["screen_name"] """ - user = Transport[self.source] if not fields: - if uid in user.friends: - return user.friends[uid] + if self.source in Transport: + user = Transport[self.source] + if uid in user.friends: + return user.friends[uid] fields = ["screen_name"] data = self.method("users.get", {"fields": ",".join(fields), "user_ids": uid}) or {} if not data: diff --git a/library/stext.py b/library/stext.py index 668d4c7..c7f0860 100644 --- a/library/stext.py +++ b/library/stext.py @@ -11,12 +11,14 @@ def setVars(lang, path): def _(what): - name = "%s/locales/locale.%s" % (path, locale) - what = what.replace("\n", "\\n") - if locale != "en" and os.path.exists(name): - data = open(name).readlines() - for line in data: - if line.startswith(what): - what = line.split("=")[1].strip() - break - return what.replace("\\n", "\n") + if what: + name = "%s/locales/locale.%s" % (path, locale) + what = what.replace("\n", "\\n") + if locale != "en" and os.path.exists(name): + data = open(name).readlines() + for line in data: + if line.startswith(what): + what = line.split("=")[1].strip() + break + return what.replace("\\n", "\n") + diff --git a/library/utils.py b/library/utils.py index 561aeb5..9f510b5 100644 --- a/library/utils.py +++ b/library/utils.py @@ -31,6 +31,8 @@ def buildDataForm(form=None, type="form", fields=[], title=None, data=[]): title: form title data: advanced data for form. e.g. instructions (if string in the list), look at xmpp/protocol.py:1326 """ + if title and form: + form.setTitle(title) form = form or xmpp.DataForm(type, data, title) for key in fields: field = form.setField(key["var"], key.get("value"), diff --git a/locales/locale.ru b/locales/locale.ru index 2768a22..d25b2fe 100644 --- a/locales/locale.ru +++ b/locales/locale.ru @@ -33,4 +33,14 @@ Transport's admins limited registrations, sorry.=Нам очень жаль, н Sorry but we have failed to send this image. Seems you haven't enough permissions. Your token should be updated, register again.=Очень жаль, но отправить изображение не удалось. Похоже, ваш access-token должен быть обновлён для получения прав на отправку изображений. Your image was successfully sent.=Ваше изображение было успешно отправлено! The record in database about you was EXTERMINATED! If you weren't asked for it, then let us know.=Запись в базе данных о вас была УНИЧТОЖЕНА! Если вы этого не просили, то дайте нам знать об этом возмутительном происшествии. -Not enough permissions to publish your status on the site. Please, register again.=Недостаточно прав для публикации статуса на сайте. Пожалуйста, зарегистрируйтесь заново.
\ No newline at end of file +Not enough permissions to publish your status on the site. Please, register again.=Недостаточно прав для публикации статуса на сайте. Пожалуйста, зарегистрируйтесь заново. +# groupchats, lables +Handle groupchats=Обрабатывать сообщения из конференций +Show all chat users=Показывать ВСЕХ пользователей в конференции +# descs +If set, transport would create xmpp-chatrooms for VK Multi-Dialogs=Если включено, транспорт будет создавать jabber-конференции для мультидиалогов ВКонтакте +If set, transport will show ALL users in a conference, even you=Если включено, транспорт будет показывать всех пользователей в jabber-конференциях, даже вас +# kernel, labels +Keep my status online=Поддерживать статус online +# global settings, labels +Send unavailable from friends when user log off=Отправлять unavailable от пользователей, когда юзер отключается diff --git a/modules/mod_iq_disco.py b/modules/mod_iq_disco.py index e3e9207..882a3ed 100644 --- a/modules/mod_iq_disco.py +++ b/modules/mod_iq_disco.py @@ -3,6 +3,9 @@ # © simpleApps, 2014 — 2015. from __main__ import * +from __main__ import _ +from utils import buildDataForm as buildForm +from xmpp import DataForm as getForm NODES = {"admin": ("Delete users", "Global message", @@ -12,6 +15,7 @@ NODES = {"admin": ("Delete users", "Check an API token"), "user": ("Edit settings",)} +FORM_TYPES = ("text-single", "text-multi", "jid-multi") def disco_handler(cl, iq): source = iq.getFrom().getStripped() @@ -91,6 +95,45 @@ def sendGlobalMessage(text): sendMessage(Component, jid[0], TransportID, text) +def checkAPIToken(token): + vk = VK() + try: + auth = vk.auth(token, True, False) + if not auth: # in case if VK() won't raise an exception + raise api.AuthError("Auth failed") + else: + vk.online = True + userID = vk.getUserID() + name = vk.getUserData(userID) + data = {"auth": auth, "name": name, "id": str(userID), "friends_count": len(vk.getFriends())} + except Exception: + data = wException() + return data + + +def dictToDataForm(_dict, _fields=None): + _fields = _fields or [] + for key, value in _dict.iteritems(): + result = {"var": key, "value": value} + if isinstance(value, int) and not isinstance(value, bool): + type = "text-signle" + + elif isinstance(value, bool): + print key, value + type = "boolean" + value = utils.normalizeValue(value) + print key,value + + elif isinstance(value, dict): + dictToDataForm(value, _fields) + elif isinstance(value, str): + type = "text-single" + if "\n" in value: + type = "text-multi" + _fields.append({"var": key, "label": key, "value": value, "type": type}) + return _fields + + def commands_handler(cl, iq): source = iq.getFrom().getStripped() cmd = iq.getTag("command", namespace=xmpp.NS_COMMANDS) @@ -101,31 +144,28 @@ def commands_handler(cl, iq): form = cmd.getTag("x", namespace=xmpp.NS_DATA) action = cmd.getAttr("action") completed = False + 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: - form = utils.buildDataForm(None, None, - [{"var": "FORM_TYPE", "type": "hidden", "value": xmpp.NS_ADMIN}, - {"var": "jids", "type": "jid-multi", "label": "Jabber ID's", "required": True}], - "Type JabberIDs in lines to remove them from db") - commandTag.addChild(node=form) + simpleForm = buildForm(simpleForm, + fields=[{"var": "jids", "type": "jid-multi", "label": _("Jabber ID's"), "required": True}]) else: - form = xmpp.DataForm(node=form).asDict() - if form.has_key("jids") and form["jids"]: + form = getForm(node=form).asDict() + if form.get("jids"): runThread(deleteUsers, (form["jids"],)) completed = True elif node == "Global message": if not form: - form = utils.buildDataForm(None, None, - [{"var": "FORM_TYPE", "type": "hidden", "value": xmpp.NS_ADMIN}, - {"var": "text", "type": "text-multi", "label": "Message", "required": True}], "Type a message text" ) - commandTag.addChild(node=form) + simpleForm = buildForm(simpleForm, + fields=[{"var": "text", "type": "text-multi", "label": _("Message"), "required": True}], + title=_("Enter the message text")) else: - form = xmpp.DataForm(node=form).asDict() + form = getForm(node=form).asDict() if form.has_key("text"): text = "\n".join(form["text"]) runThread(sendGlobalMessage, (text,)) @@ -133,53 +173,72 @@ def commands_handler(cl, iq): elif node == "Show crashlogs": if not form: - form = utils.buildDataForm(None, None, - [{"var": "FORM_TYPE", "type": "hidden", "value": xmpp.NS_ADMIN}, - {"var": "filename", "type": "list-single", "label": "Filename", "options": os.listdir("crash") if os.path.exists("crash") else []}], "Choose wisely") - commandTag.addChild(node=form) + simpleForm = buildForm(simpleForm, + fields=[{"var": "filename", "type": "list-single", "label": "Filename", + "options": os.listdir("crash") if os.path.exists("crash") else []}], + title="Choose wisely") + else: - form = xmpp.DataForm(node=form).asDict() - if form.has_key("filename") and form["filename"]: + form = getForm(node=form).asDict() + if form.get("filename"): filename = "crash/%s" % form["filename"] body = None if os.path.exists(filename): body = rFile(filename) commandTag = result.setTag("command", {"status": "executing", "node": node, "sessionid": sessionid}, xmpp.NS_COMMANDS) - form = utils.buildDataForm(None, None, - [{"var": "FORM_TYPE", "type": "hidden", "value": xmpp.NS_ADMIN}, - {"var": "body", "type": "text-multi", "label": "Error body", "value": body}] - ) - commandTag.addChild(node=form) + simpleForm = buildForm(simpleForm, + fields=[{"var": "body", "type": "text-multi", "label": "Error body", "value": body}] ) + commandTag.addChild(node=simpleForm) completed = True elif node == "Check an API token": - pass + + 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) + # {'friends_count': 5, 'name': {u'uid': 218855826, 'name': u'Some User', u'screen_name': u'some_user'}, 'auth': True, 'id': 218855826} + + 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 elif node == "Reload config": try: execfile(Config, globals()) except Exception: ## commandTag = result.setTag("command", {"status": "executing", "node": node, "sessionid": sessionid}, xmpp.NS_COMMANDS) - form = utils.buildDataForm(None, None, - [{"var": "FORM_TYPE", "type": "hidden", "value": xmpp.NS_ADMIN}, - {"var": "body", "type": "text-multi", "label": "Error while loading the config file", "value": wException()}]) - commandTag.addChild(node=form) + simpleForm = buildForm(simpleForm, + fields=[{"var": "body", "type": "text-multi", "label": "Error while loading the config file", "value": wException()}]) + completed = True elif node == "Global Transport settings": config = transportSettings.settings if not form: - form_fields = [{"var": "FORM_TYPE", "type": "hidden"}] + _fields = [] for key, values in config.items(): - form_fields.append({"var": key, "label": values["label"], "type": values.get("type", "boolean"), "value": values["value"]}) ## todo: Add support for list-multi and others? + _fields.append({"var": key, "label": _(values["label"]), + "type": values.get("type", "boolean"), + "value": values["value"], "desc": _(values.get("desc"))}) + simpleForm = buildForm(simpleForm, fields=_fields, title="Choose wisely") - form = utils.buildDataForm(None, None, form_fields, "Choose wisely") - commandTag.addChild(node=form) elif form and source in Transport: - form = xmpp.DataForm(node=form).asDict() + form = getForm(node=form).asDict() for key in form.keys(): if key in config.keys(): - transportSettings.settings[key] = utils.normalizeValue(form[key]) + transportSettings.settings[key]["value"] = utils.normalizeValue(form[key]) completed = True if node == "Edit settings" and source in Transport: @@ -187,14 +246,16 @@ def commands_handler(cl, iq): config = Transport[source].settings if not form: user = Transport[source] - form_fields = [{"var": "FORM_TYPE", "type": "hidden"}] + _fields = [] for key, values in config.items(): - form_fields.append({"var": key, "label": values["label"], "type": values.get("type", "boolean"), "value": values["value"]}) ## todo: Add support for list-multi and others? + _fields.append({"var": key, "label": _(values["label"]), + "type": values.get("type", "boolean"), + "value": values["value"], "desc": _(values.get("desc"))}) + + simpleForm = buildForm(simpleForm, fields=_fields, title="Choose wisely") - form = utils.buildDataForm(None, None, form_fields, "Choose wisely") - commandTag.addChild(node=form) elif form and source in Transport: - form = xmpp.DataForm(node=form).asDict() + form = getForm(node=form).asDict() for key in form.keys(): if key in config.keys(): Transport[source].settings[key] = utils.normalizeValue(form[key]) @@ -202,6 +263,8 @@ def commands_handler(cl, iq): if completed: result.setTag("command", {"status": "completed", "node": node, "sessionid": sessionid}, namespace=xmpp.NS_COMMANDS) + elif not form: + commandTag.addChild(node=simpleForm) sender(cl, result) diff --git a/modules/mod_iq_register.py b/modules/mod_iq_register.py index 1a3d789..097d13f 100644 --- a/modules/mod_iq_register.py +++ b/modules/mod_iq_register.py @@ -55,7 +55,7 @@ def register_handler(cl, iq): {"var": "link", "type": "text-single", "label": _("Autorization page"), "desc": ("If you won't get access-token automatically, please, follow authorization link and authorize app,\n"\ "and then paste url to password field."), "value": URL_ACCEPT_APP}, - {"var": "phone", "type": "text-single", "desc": _("Enter phone number in format +71234567890"), "value": "+"}, + {"var": "phone", "type": "text-single", "label": _("Phone number"), "desc": _("Enter phone number in format +71234567890"), "value": "+"}, {"var": "use_password", "type": "boolean", "label": _("Get access-token automatically"), "desc": _("Tries to get access-token automatically. (NOT recommended, password required!)")}, {"var": "password", "type": "text-private", "label": _("Password/Access-token"), "desc": _("Type password, access-token or url (recommended)")}], data = [_("Type data in fields")]) |