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

commands.py « common « src - dev.gajim.org/gajim/gajim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 51d075b15a728e0bc431e9472f6895263645aac5 (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
404
405
406
407
408
409
410
411
412
413
414
415
416
##
## Copyright (C) 2006 Gajim Team
##
## This file is part of Gajim.
##
## Gajim is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published
## by the Free Software Foundation; version 3 only.
##
## Gajim is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with Gajim.  If not, see <http://www.gnu.org/licenses/>.
##

import xmpp
import helpers
import dataforms
import gajim

class AdHocCommand:
	commandnode = 'command'
	commandname = 'The Command'
	commandfeatures = (xmpp.NS_DATA,)

	@staticmethod
	def isVisibleFor(samejid):
		''' This returns True if that command should be visible and invokable
		for others.
		samejid - True when command is invoked by an entity with the same bare 
		jid.'''
		return True

	def __init__(self, conn, jid, sessionid):
		self.connection = conn
		self.jid = jid
		self.sessionid = sessionid

	def buildResponse(self, request, status = 'executing', defaultaction = None,
	actions = None):
		assert status in ('executing', 'completed', 'canceled')

		response = request.buildReply('result')
		cmd = response.addChild('command', {
			'xmlns': xmpp.NS_COMMANDS,
			'sessionid': self.sessionid,
			'node': self.commandnode,
			'status': status})
		if defaultaction is not None or actions is not None:
			if defaultaction is not None:
				assert defaultaction in ('cancel', 'execute', 'prev', 'next',
					'complete')
				attrs = {'action': defaultaction}
			else:
				attrs = {}

			cmd.addChild('actions', attrs, actions)
		return response, cmd

	def badRequest(self, stanza):
		self.connection.connection.send(xmpp.Error(stanza, xmpp.NS_STANZAS + \
			' bad-request'))

	def cancel(self, request):
		response, cmd = self.buildResponse(request, status = 'canceled')
		self.connection.connection.send(response)
		return False	# finish the session

class ChangeStatusCommand(AdHocCommand):
	commandnode = 'change-status'
	commandname = _('Change status information')

	@staticmethod
	def isVisibleFor(samejid):
		''' Change status is visible only if the entity has the same bare jid. '''
		return samejid

	def execute(self, request):
		# first query...
		response, cmd = self.buildResponse(request, defaultaction = 'execute',
			actions = ['execute'])
		
		cmd.addChild(node = dataforms.SimpleDataForm(
			title = _('Change status'),
			instructions = _('Set the presence type and description'),
			fields = [
				dataforms.Field('list-single',
					var = 'presence-type',
					label = 'Type of presence:',
					options = [
						(u'free-for-chat', _('Free for chat')),
						(u'online', _('Online')),
						(u'away', _('Away')),
						(u'xa', _('Extended away')),
						(u'dnd', _('Do not disturb')),
						(u'offline', _('Offline - disconnect'))],
					value = 'online',
					required = True),
				dataforms.Field('text-multi',
					var = 'presence-desc',
					label = _('Presence description:'))]))

		self.connection.connection.send(response)

		# for next invocation
		self.execute = self.changestatus
		
		return True	# keep the session

	def changestatus(self, request):
		# check if the data is correct
		try:
			form = dataforms.SimpleDataForm(extend = request.getTag('command').\
				getTag('x'))
		except:
			self.badRequest(request)
			return False

		try:
			presencetype = form['presence-type'].value
			if not presencetype in \
			('free-for-chat', 'online', 'away', 'xa', 'dnd', 'offline'):
				self.badRequest(request)
				return False
		except:	# KeyError if there's no presence-type field in form or
			# AttributeError if that field is of wrong type
			self.badRequest(request)
			return False

		try:
			presencedesc = form['presence-desc'].value
		except:	# same exceptions as in last comment
			presencedesc = u''

		response, cmd = self.buildResponse(request, status = 'completed')
		cmd.addChild('note', {}, _('The status has been changed.'))

		# if going offline, we need to push response so it won't go into
		# queue and disappear
		self.connection.connection.send(response, now = presencetype == 'offline')

		# send new status
		gajim.interface.roster.send_status(self.connection.name, presencetype,
			presencedesc)

		return False	# finish the session

def find_current_groupchats(account):
	import message_control
	rooms = []
	for gc_control in gajim.interface.msg_win_mgr.get_controls(
	message_control.TYPE_GC):
		acct = gc_control.account
		# check if account is the good one
		if acct != account:
			continue
		room_jid = gc_control.room_jid
		nick = gc_control.nick
		if gajim.gc_connected[acct].has_key(room_jid) and \
		gajim.gc_connected[acct][room_jid]:
			rooms.append((room_jid, nick,))
	return rooms


class LeaveGroupchatsCommand(AdHocCommand):
	commandnode = 'leave-groupchats'
	commandname = _('Leave Groupchats')

	@staticmethod
	def isVisibleFor(samejid):
		''' Change status is visible only if the entity has the same bare jid. '''
		return samejid

	def execute(self, request):
		# first query...
		response, cmd = self.buildResponse(request, defaultaction = 'execute',
			actions=['execute'])
		options = []
		account = self.connection.name
		for gc in find_current_groupchats(account):
			options.append((u'%s' %(gc[0]), _('%(nickname)s on %(room_jid)s') % \
				{'nickname': gc[1], 'room_jid': gc[0]}))
		if not len(options):
			response, cmd = self.buildResponse(request, status = 'completed')
			cmd.addChild('note', {}, _('You have not joined a groupchat.'))
		
			self.connection.connection.send(response)
			return False

		cmd.addChild(node=dataforms.SimpleDataForm(
			title = _('Leave Groupchats'),
			instructions = _('Choose the groupchats you want to leave'),
			fields=[
				dataforms.Field('list-multi',
					var = 'groupchats',
					label = _('Groupchats'),
					options = options,
					required = True)]))

		self.connection.connection.send(response)

		# for next invocation
		self.execute = self.leavegroupchats

		return True	# keep the session

	def leavegroupchats(self, request):
		# check if the data is correct
		try:
			form = dataforms.SimpleDataForm(extend = request.getTag('command').\
				getTag('x'))
		except:
			self.badRequest(request)
			return False

		try:
			gc = form['groupchats'].values
		except:	# KeyError if there's no presence-type field in form or
			# AttributeError if that field is of wrong type
			self.badRequest(request)
			return False
		account = self.connection.name
		try:
			for room_jid in gc:
				gc_control = gajim.interface.msg_win_mgr.get_gc_control(room_jid,
					account)
				gc_control.parent_win.remove_tab(gc_control, None, force = True)
		except:	# KeyError if there's no presence-type field in form or
			self.badRequest(request)
			return False
		response, cmd = self.buildResponse(request, status = 'completed')
		note = _('You left the following groupchats:')
		for room_jid in gc:
			note += '\n\t' + room_jid
		cmd.addChild('note', {}, note)

		self.connection.connection.send(response)
		return False


class ForwardMessagesCommand(AdHocCommand):
	# http://www.xmpp.org/extensions/xep-0146.html#forward
	commandnode = 'forward-messages'
	commandname = _('Forward unread messages')

	@staticmethod
	def isVisibleFor(samejid):
		''' Change status is visible only if the entity has the same bare jid. '''
		return samejid

	def execute(self, request):
		account = self.connection.name
		# Forward messages
		events = gajim.events.get_events(account, types=['chat', 'normal'])
		j, resource = gajim.get_room_and_nick_from_fjid(self.jid)
		for jid in events:
			for event in events[jid]:
				self.connection.send_message(j, event.parameters[0], '',
					type=event.type_, subject=event.parameters[1],
					resource=resource, forward_from=jid)

		# Inform other client of completion
		response, cmd = self.buildResponse(request, status = 'completed')
		cmd.addChild('note', {}, _('All unread messages have been forwarded.'))

		self.connection.connection.send(response)

		return False	# finish the session

class ConnectionCommands:
	''' This class depends on that it is a part of Connection() class. '''
	def __init__(self):
		# a list of all commands exposed: node -> command class
		self.__commands = {}
		for cmdobj in (ChangeStatusCommand, ForwardMessagesCommand,
		LeaveGroupchatsCommand):
			self.__commands[cmdobj.commandnode] = cmdobj

		# a list of sessions; keys are tuples (jid, sessionid, node)
		self.__sessions = {}

	def getOurBareJID(self):
		return gajim.get_jid_from_account(self.name)

	def isSameJID(self, jid):
		''' Tests if the bare jid given is the same as our bare jid. '''
		return xmpp.JID(jid).getStripped() == self.getOurBareJID()

	def commandListQuery(self, con, iq_obj):
		iq = iq_obj.buildReply('result')
		jid = helpers.get_full_jid_from_iq(iq_obj)
		q = iq.getTag('query')
		# buildReply don't copy the node attribute. Re-add it
		q.setAttr('node', xmpp.NS_COMMANDS)

		for node, cmd in self.__commands.iteritems():
			if cmd.isVisibleFor(self.isSameJID(jid)):
				q.addChild('item', {
					# TODO: find the jid
					'jid': self.getOurBareJID() + u'/' + self.server_resource,
					'node': node,
					'name': cmd.commandname})

		self.connection.send(iq)

	def commandInfoQuery(self, con, iq_obj):
		''' Send disco#info result for query for command (JEP-0050, example 6.).
		Return True if the result was sent, False if not. '''
		jid = helpers.get_full_jid_from_iq(iq_obj)
		node = iq_obj.getTagAttr('query', 'node')

		if node not in self.__commands: return False

		cmd = self.__commands[node]
		if cmd.isVisibleFor(self.isSameJID(jid)):
			iq = iq_obj.buildReply('result')
			q = iq.getTag('query')
			q.addChild('identity', attrs = {'type': 'command-node',
				'category': 'automation',
				'name': cmd.commandname})
			q.addChild('feature', attrs = {'var': xmpp.NS_COMMANDS})
			for feature in cmd.commandfeatures:
				q.addChild('feature', attrs = {'var': feature})

			self.connection.send(iq)
			return True

		return False

	def commandItemsQuery(self, con, iq_obj):
		''' Send disco#items result for query for command.
		Return True if the result was sent, False if not. '''
		jid = helpers.get_full_jid_from_iq(iq_obj)
		node = iq_obj.getTagAttr('query', 'node')

		if node not in self.__commands: return False

		cmd = self.__commands[node]
		if cmd.isVisibleFor(self.isSameJID(jid)):
			iq = iq_obj.buildReply('result')
			self.connection.send(iq)
			return True

		return False

	def _CommandExecuteCB(self, con, iq_obj):
		jid = helpers.get_full_jid_from_iq(iq_obj)

		cmd = iq_obj.getTag('command')
		if cmd is None: return

		node = cmd.getAttr('node')
		if node is None: return

		sessionid = cmd.getAttr('sessionid')
		if sessionid is None:
			# we start a new command session... only if we are visible for the jid
			# and command exist
			if node not in self.__commands.keys():
				self.connection.send(
					xmpp.Error(iq_obj, xmpp.NS_STANZAS + ' item-not-found'))
				raise xmpp.NodeProcessed

			newcmd = self.__commands[node]
			if not newcmd.isVisibleFor(self.isSameJID(jid)):
				return

			# generate new sessionid
			sessionid = self.connection.getAnID()

			# create new instance and run it
			obj = newcmd(conn = self, jid = jid, sessionid = sessionid)
			rc = obj.execute(iq_obj)
			if rc:
				self.__sessions[(jid, sessionid, node)] = obj
			raise xmpp.NodeProcessed
		else:
			# the command is already running, check for it
			magictuple = (jid, sessionid, node)
			if magictuple not in self.__sessions:
				# we don't have this session... ha!
				return

			action = cmd.getAttr('action')
			obj = self.__sessions[magictuple]

			try:
				if action == 'cancel':
					rc = obj.cancel(iq_obj)
				elif action == 'prev':
					rc = obj.prev(iq_obj)
				elif action == 'next':
					rc = obj.next(iq_obj)
				elif action == 'execute' or action is None:
					rc = obj.execute(iq_obj)
				elif action == 'complete':
					rc = obj.complete(iq_obj)
				else:
					# action is wrong. stop the session, send error
					raise AttributeError
			except AttributeError:
				# the command probably doesn't handle invoked action...
				# stop the session, return error
				del self.__sessions[magictuple]
				return

			# delete the session if rc is False
			if not rc:
				del self.__sessions[magictuple]

			raise xmpp.NodeProcessed

# vim: se ts=3: