Welcome to mirror list, hosted at ThFree Co, Russian Federation.

mod_iq_disco.py « modules - github.com/mrDoctorWho/vk4xmpp.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 61b89e33ed0a5b7948b5e27445917b0e0b7ad5da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# coding: utf-8
# This file is a part of VK4XMPP transport
# © simpleApps, 2014 — 2015.
# Warning: This module contains not optimal and really ugly code.


from __main__ import *
from __main__ import _
from utils import buildDataForm as buildForm, buildIQError
from xmpp import DataForm as getForm
import modulemanager

NODES = {"admin": ("Delete users",
					"Global message",
					"Show crash logs",
					"Reload config",
					"Global Transport settings",
					"Check an API token",
					"Unload modules",
					"(Re)load modules",
					"Reload extensions"),
		"user": ("Edit settings",)}


def getFeatures(destination, source, ns, disco=False):
	if destination == TransportID:
		features = TransportFeatures
	else:
		features = UserFeatures
	payload = [xmpp.Node("identity", IDENTIFIER)]
	if source in ADMIN_JIDS and disco:
		payload.append(xmpp.Node("item", {"node": "Online users", "name": "Online users", "jid": TransportID}))
		payload.append(xmpp.Node("item", {"node": "All users", "name": "All users", "jid": TransportID}))
	if ns == xmpp.NS_DISCO_INFO:
		for key in features:
			node = xmpp.Node("feature", {"var": key})
			payload.append(node)
	return payload


def disco_handler(cl, iq):
	source = iq.getFrom().getStripped()
	destination = iq.getTo().getStripped()
	ns = iq.getQueryNS()
	node = iq.getTagAttr("query", "node")
	result = iq.buildReply("result")
	payload = []
	if node:
		if source in ADMIN_JIDS:
			users = []
			if node == "Online users":
				users = Transport.keys()
			elif node == "All users":
				users = getUsersList()
				users = [user[0] for user in users]

			for user in users:
				payload.append(xmpp.Node("item", {"name": user, "jid": user}))

		if node == xmpp.NS_COMMANDS:
			nodes = NODES["user"]
			if source in ADMIN_JIDS:
				nodes += NODES["admin"]
			for node in nodes:
				payload.append(xmpp.Node("item", {"node": node, "name": node, "jid": TransportID}))

		elif CAPS_NODE in node:
			payload = getFeatures(destination, source, ns)

		elif not payload:
			result = buildIQError(iq, xmpp.ERR_BAD_REQUEST)

	else:
		payload = getFeatures(destination, source, ns, True)

	if payload:
		result.setQueryPayload(payload)
	sender(cl, result)


getUsersList = lambda: runDatabaseQuery("select jid from users", many=True)
deleteUsers = lambda jids: [utils.execute(removeUser, (key,), False) for key in jids]


def sendAnnouncement(destination, body, subject):
	msg = xmpp.Message(destination, body, "normal", frm=TransportID)
	timestamp = time.gmtime(time.time())
	msg.setSubject(subject)
	msg.setTimestamp(time.strftime("%Y%m%dT%H:%M:%S", timestamp))
	sender(Component, msg)


def sendGlobalMessage(body, subject, online):
	if online:
		users = Transport.keys()
	else:
		users = getUsersList()
	for user in users:
		sendAnnouncement(user, body, subject)


def checkAPIToken(token):
	"""
	Checks API token, returns dict or error
	"""
	vk = VK(token)
	try:
		auth = vk.auth()
		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, "friends_count": len(vk.getFriends())}
	except (api.VkApiError, Exception):
		data = wException()
	return data


def dictToDataForm(_dict, _fields=None):
	"""
	Makes a buildForm()-compatible dict from a random key-value dict
	converts boolean types to a boolean field,
	converts multiline string to a text-multi field and so on.
	"""
	_fields = _fields or []
	for key, value in _dict.iteritems():
		if isinstance(value, int) and not isinstance(value, bool):
			type = "text-signle"

		elif isinstance(value, bool):
			type = "boolean"
			value = utils.normalizeValue(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 getConfigFields(config):
	fields = []
	for key, values in config.items():
		fields.append({"var": key, "label": _(values["label"]),
			"type": values.get("type", "boolean"),
			"value": values["value"], "desc": _(values.get("desc"))})
	return fields


@utils.safe
def commands_handler(cl, iq):
	source = iq.getFrom().getStripped()
	cmd = iq.getTag("command", namespace=xmpp.NS_COMMANDS)
	if cmd:
		result = iq.buildReply("result")
		node = iq.getTagAttr("command", "node")
		sessionid = iq.getTagAttr("command", "sessionid")
		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":
			dictForm = getForm(node=form).asDict()
			if source in ADMIN_JIDS:
				if node == "Delete users":
					if not form:
						simpleForm = buildForm(simpleForm,
							fields=[{"var": "jids", "type": "jid-multi", "label": _("Jabber ID's"), "required": True}])
					else:
						if dictForm.get("jids"):
							utils.runThread(deleteUsers, (dictForm["jids"],))
						simpleForm = None
						completed = True

				elif node == "Global message":
					if not form:
						simpleForm = buildForm(simpleForm,
							fields=[
								{"var": "subject", "type": "text-single", "label": _("Subject"), "value": "Announcement"},
								{"var": "body", "type": "text-multi", "label": _("Message"), "required": True},
								{"var": "online", "type": "boolean", "label": "Online users only"}
							],
							title=_("Enter the message text"))
					else:
						body = "\n".join(dictForm["body"])
						subject = dictForm["subject"]
						online = dictForm["online"]
						utils.runThread(sendGlobalMessage, (body, subject, online))
						note = "The message was sent."
						simpleForm = None
						completed = True

				elif node == "Show crash logs":
					if not 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:
						if dictForm.get("filename"):
							filename = "crash/%s" % dictForm["filename"]
							body = None
							if os.path.exists(filename):
								body = rFile(filename)
							simpleForm = buildForm(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:
						if dictForm.get("token"):
							token = dictForm["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:
						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
					if not form:
						simpleForm = buildForm(simpleForm, fields=getConfigFields(config), title="Choose wisely")

					elif form:
						for key in dictForm.keys():
							if key in config.keys():
								transportSettings.settings[key]["value"] = utils.normalizeValue(dictForm[key])
						note = "The settings were changed."
						simpleForm = None
						completed = True

				elif node == "(Re)load modules":
					Manager = modulemanager.ModuleManager
					modules = Manager.list()
					if not form:
						_fields = dictToDataForm(dict([(mod, mod in Manager.loaded) for mod in modules]))
						simpleForm = buildForm(simpleForm, fields=_fields, title="(Re)load modules",
							data=[_("Modules can be loaded or reloaded if they already loaded")])

					elif form:
						keys = []
						for key in dictForm.keys():
							if key in modules and utils.normalizeValue(dictForm[key]):
								keys.append(key)

						loaded, errors = Manager.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":
					Manager = modulemanager.ModuleManager
					modules = Manager.loaded.copy()
					modules.remove("mod_iq_disco")
					if not form:
						_fields = dictToDataForm(dict([(mod, False) for mod in modules]))
						if _fields:
							simpleForm = buildForm(simpleForm, fields=_fields, title="Unload modules")
						else:
							note = "Nothing to unload."
							completed = True
							simpleForm = None

					elif form:
						keys = []
						for key in dictForm.keys():
							if key in Manager.loaded and utils.normalizeValue(dictForm[key]):
								keys.append(key)

						unload = Manager.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
				if not form:
					simpleForm = buildForm(simpleForm, fields=getConfigFields(config), title="Choose wisely")

				elif form:
					for key in dictForm.keys():
						if key in config.keys():
							Transport[source].settings[key] = utils.normalizeValue(dictForm[key])
					note = "The settings were changed."
					simpleForm = None
					completed = True

			if completed:
				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)


MOD_TYPE = "iq"
MOD_FEATURES = [xmpp.NS_COMMANDS, xmpp.NS_DISCO_INFO, xmpp.NS_DISCO_ITEMS, xmpp.NS_DATA]
MOD_FEATURES_USER = [xmpp.NS_DISCO_INFO]
MOD_HANDLERS = ((disco_handler, "get", [xmpp.NS_DISCO_INFO, xmpp.NS_DISCO_ITEMS], False), (commands_handler, "set", "", False))
FORM_TYPES = ("text-single", "text-multi", "jid-multi")