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: 0d1226b81d8d4cce331cd154b6654ec7d3542813 (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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# 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
from traceback import format_exc

import xmpp
import modulemanager


class Node(object):
	"""
	Ad-Hoc nodes
	"""
	DELETE_USERS = "Delete users"
	GLOBAL_MESSAGE = "Global message"
	SHOW_CRASH_LOGS = "Show crash logs"
	RELOAD_CONFIG = "Reload config"
	GLOBAL_SETTINGS = "Global Transport Settings"
	CHECK_API_TOKEN = "Check an API token"
	UNLOAD_MODULES = "Unload modules"
	RELOAD_MODULES = "(Re)load modules"
	RELOAD_EXTENSIONS = "Reload extensions"
	EDIT_SETTINGS = "Edit settings"
	EXTERMINATE_CHATS = "Exterminate chats"
	USERS_ONLINE = "Online users"
	USERS_TOTAL = "All users"


NODES = {"admin": (Node.DELETE_USERS,
					Node.GLOBAL_MESSAGE,
					Node.SHOW_CRASH_LOGS,
					Node.RELOAD_CONFIG,
					Node.GLOBAL_SETTINGS,
					Node.CHECK_API_TOKEN,
					Node.UNLOAD_MODULES,
					Node.RELOAD_MODULES,
					Node.RELOAD_EXTENSIONS),
		"user": (Node.EDIT_SETTINGS,
				Node.EXTERMINATE_CHATS)}


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": Node.USERS_ONLINE, "name": Node.USERS_ONLINE, "jid": TransportID}))
		payload.append(xmpp.Node("item", {"node": Node.USERS_TOTAL, "name": Node.USERS_TOTAL, "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 = Users.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 = Users.keys()
	else:
		users = getUsersList()
	for user in users:
		sendAnnouncement(user[0], 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.getUserPreferences()[0]
			name = vk.getName(userID)
			data = {"auth": auth, "name": name, "friends_count": len(vk.getFriends())}
	except (api.VkApiError, Exception):
		data = format_exc()
	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):
			fieldType = "text-single"

		elif isinstance(value, bool):
			fieldType = "boolean"
			value = utils.normalizeValue(value)

		elif isinstance(value, dict):
			dictToDataForm(value, _fields)

		elif isinstance(value, (str, unicode)):
			fieldType = "text-single"
			if "\n" in value:
				fieldType = "text-multi"
		else:
			logger.warning("unknown type \"%s\" for value %s", type(value), value)
			fieldType = "text-single"
		_fields.append({"var": key, "label": key, "value": value, "type": fieldType})
	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"))})
	fields = sorted(fields, key=lambda x: x["label"])
	return fields


def getUserChats(source):
	result = runDatabaseQuery("select jid, owner, user from groupchats where user=?", (source,), many=True)
	return result


@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 = DataForm(node=form).asDict()
			if source in ADMIN_JIDS:
				if node == 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 == 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 == 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 == Node.CHECK_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 == Node.RELOAD_CONFIG:
					simpleForm = None
					completed = True
					try:
						execfile(Config, globals())
						note = "Reloaded well. You might need to reload modules for the settings to take effect"
					except Exception:
						note = format_exc()

				elif node == Node.RELOAD_EXTENSIONS:
					simpleForm = None
					completed = True
					try:
						loadExtensions("extensions")
						note = "Reloaded well."
					except Exception:
						note = format_exc()

				elif node == Node.GLOBAL_SETTINGS:
					config = Transport.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():
								config[key]["value"] = utils.normalizeValue(dictForm[key])
						note = "The settings were changed."
						simpleForm = None
						completed = True

				elif node == Node.RELOAD_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 == 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 == Node.EDIT_SETTINGS and source in Users:
				logger.info("user want to edit their settings (jid: %s)" % source)
				config = Users[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:
							config[key] = utils.normalizeValue(dictForm[key])
					note = "The settings were changed."
					simpleForm = None
					completed = True

			elif node == Node.EXTERMINATE_CHATS:
				if not form:
					chats = getUserChats(source)
					if chats:
						_fields = dictToDataForm(dict([(chat[0], False) for chat in chats]))
						simpleForm = buildForm(simpleForm, fields=_fields, title="Delete chats")
					else:
						note = "Nothing to delete"
						completed = True
						simpleForm = None
				elif form:
					# all user's chats
					chats = getUserChats(source)
					newChats = dictForm.keys()
					exterminateChats(chats=filter(lambda chat: chat[0] in newChats, chats))
					note = "Yay! Everything deleted!"
					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")