コード例 #1
0
def register_handler(cl, iq):
	source = iq.getFrom().getStripped()
	destination = iq.getTo().getStripped()
	result = iq.buildReply("result")
	if USER_LIMIT:
		count = calcStats()[0]
		if count >= USER_LIMIT and source not in Users:
			sender(cl, utils.buildIQError(iq, xmpp.ERR_NOT_ALLOWED, _("The gateway admins limited registrations, sorry.")))
			raise xmpp.NodeProcessed()

	if destination == TransportID and iq.getQueryChildren():
		phone, password, use_password, token, result = None, None, None, None, None
		query = iq.getTag("query")
		data = query.getTag("x", namespace=xmpp.NS_DATA)
		if data:
			form = xmpp.DataForm(node=data).asDict()
			phone = str(form.get("phone", "")).lstrip("+")
			password = str(form.get("password", ""))
			use_password = utils.normalizeValue(form.get("use_password", ""))  # In case here comes some unknown crap

			if not password:
				result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("The token/password field can't be empty!"))
			else:
				if use_password:
					logger.debug("user want to use a password (jid: %s)" % source)
					if not phone or phone == "+":
						result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Phone is incorrect."))
				else:
					logger.debug("user won't use a password (jid: %s)" % source)
					token = password
					password = None
					# If not using a password, then we need to check if there a link or token. It's possible that user's wrong and that's a password.
					match = api.token_exp.search(token)
					if match:
						token = match.group(0)
					elif phone:
						password = token
					else:
						result = utils.buildIQError(iq, xmpp.ERR_NOT_AUTHORIZED, _("Fill the fields!"))

				# If phone or password (token)
				if token or (phone and password):
					user = User(source)
					initializeUser(user, cl, iq, {"username": phone, "password": password, "token": token})
					result = None

		elif query.getTag("remove"):
			logger.debug("user %s want to remove me..." % source)
			if source in Users:
				user = Users[source]
				result = iq.buildReply("result")
				result.setPayload([], add=False)
				executeHandlers("evt09", (source,))

			elif findUserInDB(source):
				removeUser(source, True, False)
				sendPresence(TransportID, destination, "unsubscribe")
				executeHandlers("evt09", (source,))
	if result:
		sender(cl, result)
コード例 #2
0
ファイル: forms.py プロジェクト: CSRedRat/vk4xmpp
 def getSimpleForm(cls):
     form = []
     form.append({"var": "link", "type": "text-single", "label": _("Autorization page"), "value": URL_ACCEPT_APP})
     form.append(
         {"var": "password", "type": "text-private", "label": _("Access-token"), "desc": _("Enter the access token")}
     )
     return form
コード例 #3
0
def vcard_handler(cl, iq):
	# Vcard feature makes transport hang (especially the photo part)
	# Many clients love to query vcards so much, so the solution was in adding a semaphore here and sleep() at the bottom
	# This is probably not a good idea, but for now this is the best one
	with VCARD_SEMAPHORE:
		jidFrom = iq.getFrom()
		jidTo = iq.getTo()
		source = jidFrom.getStripped()
		destination = jidTo.getStripped()
		result = iq.buildReply("result")

		if destination == TransportID:
			template = VCARD_TEMPLATE.copy()
			template[KEY_URL] = GITHUB_URL
			template[KEY_BDAY] = BIRTHDAY
			vcard = buildVcard(template, template, template)
			result.setPayload([vcard])

		elif source in Users:
			user = Users[source]
			if user.friends:
				id = vk2xmpp(destination)
				args = ("screen_name", "bdate", "city", "country", "contacts", "home_town", PhotoSize)  # todo: a feature to show the user's site instead of their URL?
				data = user.vk.getUserData(id, args)
				data["id"] = id
				if not user.settings.use_nicknames:
					data["screen_name"] = data["name"]
				vCard = buildVcard(data, VCARD_TEMPLATE, VCARD_FIELDS, user)
				result.setPayload([vCard])
			else:
				result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Your friend-list is empty."))
		else:
			result = utils.buildIQError(iq, xmpp.ERR_REGISTRATION_REQUIRED, _("You're not registered for this action."))
		sender(cl, result)
コード例 #4
0
ファイル: mod_iq_vcard.py プロジェクト: KetothXupack/vk4xmpp
def vcard_handler(cl, iq):
	jidFrom = iq.getFrom()
	jidTo = iq.getTo()
	source = jidFrom.getStripped()
	destination = jidTo.getStripped()
	result = iq.buildReply("result")
	_DESC = '\n'.join((DESC, "_" * 16, AdditionalAbout)) if AdditionalAbout else DESC
	if destination == TransportID:
		vcard = buildVcard({"NICKNAME": "VK4XMPP Transport",
							"DESC": _DESC,
							"PHOTO": "https://raw.github.com/mrDoctorWho/vk4xmpp/master/vk4xmpp.png",
							"URL": "http://simpleapps.ru"
							})
		result.setPayload([vcard])

	elif source in Transport:
		user = Transport[source]
		if user.friends:
			id = vk2xmpp(destination)
			json = user.vk.getUserData(id, ["screen_name", PhotoSize])
			values = {"NICKNAME": json.get("name", str(json)),
					"URL": "http://vk.com/id%s" % id,
					"DESC": _("Contact uses VK4XMPP Transport\n%s") % _DESC
					}
			if id in user.friends.keys():
				values["PHOTO"] = json.get(PhotoSize) or URL_VCARD_NO_IMAGE
			vCard = buildVcard(values)
			result.setPayload([vCard])
		else:
			result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Your friend-list is empty."))
	else:
		result = utils.buildIQError(iq, xmpp.ERR_REGISTRATION_REQUIRED, _("You're not registered for this action."))
	sender(cl, result)
コード例 #5
0
ファイル: mod_iq_register.py プロジェクト: tonal/vk4xmpp
def register_handler(cl, iq):
	source = iq.getFrom().getStripped()
	destination = iq.getTo().getStripped()
	result = iq.buildReply("result")
	if USER_LIMIT:
		count = calcStats()[0]
		if count >= USER_LIMIT and not source in Transport:
			sender(cl, utils.buildIQError(iq, xmpp.ERR_NOT_ALLOWED, _("Transport's admins limited registrations, sorry.")))
			raise xmpp.NodeProcessed()

	if destination == TransportID and iq.getQueryChildren():
		phone, password, use_password, token, result = None, None, None, None, None
		query = iq.getTag("query")
		data = query.getTag("x", namespace=xmpp.NS_DATA)
		if data:
			form = xmpp.DataForm(node=data).asDict()
			phone = str(form.get("phone", "")).lstrip("+")
			password = str(form.get("password", ""))
			use_password = utils.normalizeValue(form.get("use_password", ""))  # In case here comes some unknown crap

			if not password:
				result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("The token/password field can't be empty!"))
			else:
				if use_password:
					logger.debug("user want to use a password (jid: %s)" % source)
					if not phone or phone == "+":
						result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Phone is incorrect."))
				else:
					logger.debug("user won't use a password (jid: %s)" % source)
					token = password
					password = None
					# If not using a password, then we need to check if there a link or token. It's possible that user's wrong and that's a password.
					match = api.token_exp.search(token)
					if match:
						token = match.group(0)
					elif phone:
						password = token
					else:
						result = utils.buildIQError(iq, xmpp.ERR_NOT_AUTHORIZED, _("Fill the fields!"))

				# If phone or password (token)
				if token or (phone and password):
					user = User(source)
					initializeUser(user, cl, iq, {"username": phone, "password": password, "token": token})
					result = None

		elif query.getTag("remove"):
			logger.debug("user %s want to remove me..." % source)
			if source in Transport:
				user = Transport[source]
				result = iq.buildReply("result")
				result.setPayload([], add=False)
				executeHandlers("evt09", (source,))

			elif findUserInDB(source):
				removeUser(source, True, False)
				sendPresence(TransportID, destination, "unsubscribe")
				executeHandlers("evt09", (source,))
	if result:
		sender(cl, result)
コード例 #6
0
ファイル: mod_iq_disco.py プロジェクト: CSRedRat/vk4xmpp
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
コード例 #7
0
ファイル: mod_groupchat_prs.py プロジェクト: tonal/vk4xmpp
def handleChatPresences(source, prs):
	"""
	Makes old users leave
	Parameters:
		* source: stanza source
		* prs: xmpp.Presence object
	"""
	jid = prs.getJid() or ""
	if "@" in jid:
		user = Chat.getUserObject(source)
		if user and source in getattr(user, "chats", {}):
			chat = user.chats[source]
			if jid.split("@")[1] == TransportID and chat.created:
				id = vk2xmpp(jid)
				if id != TransportID and id not in chat.users.keys():
					if (time.gmtime().tm_mon, time.gmtime().tm_mday) == (4, 1):
						setAffiliation(source, "outcast", jid, reason=_("Get the hell outta here!"))
					else:
						leaveChat(source, jid, _("I am not welcomed here"))

				if (prs.getRole(), prs.getAffiliation()) == ("moderator", "owner"):
					if jid != TransportID:
						runDatabaseQuery("update groupchats set owner=? where jid=?", (source, jid), set=True)

			if jid.split("/")[0] == user.source:
				chat.owner_nickname = prs.getFrom().getResource()
				runDatabaseQuery("update groupchats set nick=? where jid=? ", (chat.owner_nickname, source), set=True)
			raise xmpp.NodeProcessed()

		elif user and prs.getType() != "unavailable":
			createFakeChat(user, source)
コード例 #8
0
ファイル: mod_msg_main.py プロジェクト: KetothXupack/vk4xmpp
def acceptCaptcha(cl, args, jidTo, source):
	if args:
		answer = None
		user = Transport[source]
		if user.vk.engine.captcha:
			logger.debug("user %s called captcha challenge" % source)
			user.vk.engine.captcha["key"] = args
			success = False
			try:
				logger.debug("retrying for user %s" % source)
				success = user.vk.engine.retry()
			except api.CaptchaNeeded:
				logger.error("retry for user %s failed!" % source)
				user.vk.captchaChallenge()
			if success:
				logger.debug("retry for user %s successed!" % source)
				answer = _("Captcha valid.")
				Presence = xmpp.Presence(source, show=None, frm=TransportID)
				sender(Component, Presence)
				user.tryAgain()
			else:
				answer = _("Captcha invalid.")
		else:
			answer = _("Not now. Ok?")
		if answer:
			sendMessage(cl, source, jidTo, answer)
コード例 #9
0
ファイル: mod_prs_main.py プロジェクト: mikken/vk4xmpp
def initializeUser(source, resource, prs):
	"""
	Initializes user for a first time after he have registered
	"""
	logger.debug("User not in the transport, but a presence received. Searching in database (jid: %s)" % source)
	data = runDatabaseQuery("select jid,username from users where jid=?", (source,), many=False)
	if data:
		sendPresence(source, TransportID, None, IDENTIFIER["name"], caps=True,
			reason=_("You are being initialized, please wait..."), show="xa")
		logger.debug("User has been found in database (jid: %s)" % source)
		jid, phone = data
		Transport[jid] = user = User(jid)
		try:
			connect = user.connect()
		except Exception:
			sendMessage(Component, jid, TransportID, 
				_("Auth failed! If this error repeated, "
					"please register again. This incident will be reported."))
			crashLog("user.connect")
		else:
			user.initialize(send=True, resource=resource)  # probably we need to know resource a bit earlier than this time
			utils.runThread(executeHandlers, ("prs01", (source, prs)))

	if source in USERS_ON_INIT:
		USERS_ON_INIT.remove(source)
コード例 #10
0
ファイル: mod_iq_vcard.py プロジェクト: mrDoctorWho/vk4xmpp
def vcard_handler(cl, iq):
	# Vcard feature makes transport hang (especially the photo part)
	# Many clients love to query vcards so much, so the solution was in adding a semaphore here and sleep() at the bottom
	# This is probably not a good idea, but for now this is the best one
	with VCARD_SEMAPHORE:
		jidFrom = iq.getFrom()
		jidTo = iq.getTo()
		source = jidFrom.getStripped()
		destination = jidTo.getStripped()
		result = iq.buildReply("result")

		logger.debug("got vcard request to %s (jid: %s)", source, destination)
		if destination == TransportID:
			template = VCARD_TEMPLATE.copy()
			template[KEY_URL] = GITHUB_URL
			template[KEY_BDAY] = BIRTHDAY
			vcard = buildVcard(template, template, template)
			result.setPayload([vcard])

		elif source in Users:
			user = Users[source]
			if user.friends:
				id = vk2xmpp(destination)
				args = ("screen_name", "bdate", "city", "country", "contacts", "home_town", PhotoSize)  # todo: a feature to show the user's site instead of their URL?
				data = user.vk.getUserData(id, args)
				data["id"] = id
				if not user.settings.use_nicknames:
					data["screen_name"] = data["name"]
				vCard = buildVcard(data, VCARD_TEMPLATE, VCARD_FIELDS, user)
				result.setPayload([vCard])
			else:
				result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Your friend-list is empty."))
		else:
			result = utils.buildIQError(iq, xmpp.ERR_REGISTRATION_REQUIRED, _("You're not registered for this action."))
		sender(cl, result)
コード例 #11
0
ファイル: mod_xhtml.py プロジェクト: alexeycv/vk4xmpp
def sendPhoto(user, data, type, address, mType):
	mask = user.vk.method("account.getAppPermissions") or 0

	if mType == "chat_id":
		address = address.split("@")[0].split("#")[1]
		send = False
	else:
		destination = address
		address = vk2xmpp(address)
		send = True

	if address == TransportID:
		answer = _("Are you kidding me?")
	elif mask:
		if mask & 4 == 4: ## we have enough access?
			ext = type.split("/")[1]
			name = "vk4xmpp_%s.%s" % (random.randint(1000, 9000), ext)
			server = str(user.vk.method("photos.getMessagesUploadServer")["upload_url"])
			response = json.loads(user.vk.engine.RIP.post(
					server, 
					user.vk.engine.RIP.multipart("photo", str(name), str(type), data),
					urlencode = False)[0])
			
			id = user.vk.method("photos.saveMessagesPhoto", response)[0].get("id", 0)
			user.sendMessage("", address, mType, {"attachment": id})
			logger.debug("sendPhoto: image was successfully sent by user %s" % user.source)
			answer = _("Your image was successfully sent.")
		else:
			answer = _("Sorry but we have failed to send this image."
				 	" Seems you haven't enough permissions. Your token should be updated, register again.")
	else:
		answer = _("Something went wrong. We are so sorry.")
	if send:
		msgSend(Component, user.source, answer, destination, timestamp=1)
コード例 #12
0
ファイル: mod_msg_main.py プロジェクト: korobcov/vk4xmpp
def acceptCaptcha(key, source, destination):
	"""
	Accepts the captcha value in 2 possible ways:
		1. User sent a message
		2. User sent an IQ with the captcha value
	"""
	if args:
		user = Users[source]
		logger.debug("user %s called captcha challenge" % source)
		try:
			user.captchaChallenge(key)
			valid = True
		except api.CaptchaNeeded:
			valid = False
			answer = _("Captcha invalid.")
		else:
			logger.debug("retry for user %s successed!" % source)
			answer = _("Captcha valid.")
			sendPresence(source, TransportID, hash=TRANSPORT_CAPS_HASH)

		sendMessage(source, destination, answer, mtype="normal")
		if not valid:
			executeHandlers("evt04", (user, user.vk.engine.captcha["img"]))
			return False
		return True
	return False
コード例 #13
0
ファイル: mod_iq_disco.py プロジェクト: l29ah/vk4xmpp
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
コード例 #14
0
	def getSimpleForm(cls):
		form = []
		form.append({"var": "link", "type": "text-single",
			"label": _("Autorization page"), "value": URL_ACCEPT_APP})
		form.append({"var": "password", "type": "text-private",
			"label": _("Access-token"),
			"desc": _("Enter the access token")})
		return form
コード例 #15
0
def initializeUser(source, resource, prs):
    """
	Initializes user for the first time after they connected
	"""
    logger.debug("Got a presence. Searching jid in the database. (jid: %s)",
                 source)
    user = User(source)
    try:
        user.connect()
    except RuntimeError:
        pass
    except Exception as e:
        if not isinstance(e, api.TokenError):
            report(crashLog("user.connect"))
        sendMessage(
            source, TransportID,
            _("Auth failed! If this error repeated, "
              "please register again."
              " This incident will be reported.\nCause: %s") % returnExc())
        logger.error("Failed to authenicate user! Error: %s (jid: %s)",
                     e.message, source)
    else:
        user.initialize(
            send=True, resource=resource
        )  # probably we need to know resource a bit earlier than this time
        utils.runThread(executeHandlers, ("prs01", (source, prs)))
    finally:
        if source in USERS_ON_INIT:
            USERS_ON_INIT.remove(source)
コード例 #16
0
ファイル: rostermanager.py プロジェクト: opiums9/vk4xmpp
    def checkRosterx(cls, user, resource):
        """
		Checks if the client supports XEP-0144: Roster Item Exchange
		If it doesn't, or it didn't answer us, then transport will use the old method
		"""
        jid = "%s/%s" % (user.source, resource)
        sendPresence(jid, TransportID, "subscribe", IDENTIFIER["name"])
        sendPresence(jid,
                     TransportID,
                     nick=IDENTIFIER["name"],
                     reason=_("You are being initialized, please wait..."),
                     show="xa")

        def answer(cl, stanza):
            if xmpp.isResultNode(stanza):
                query = stanza.getTag("query")
                if query.getTags("feature", attrs={"var": xmpp.NS_ROSTERX}):
                    logger.debug(
                        "using the RosterX method to add items to user's roster (jid: %s)",
                        jid)
                    cls.manageRoster(user, jid, user.friends)
                else:
                    logger.debug(
                        "using the old method to add items to user's roster (jid: %s)",
                        jid)
                    user.sendSubPresence(user.friends)

        iq = xmpp.Iq("get", to=jid, frm=TransportID)
        iq.addChild("query", namespace=xmpp.NS_DISCO_INFO)
        sender(Component, iq, cb=answer)
コード例 #17
0
ファイル: mod_iq_register.py プロジェクト: alexeycv/vk4xmpp
def initializeUser(user, cl, iq):
	source = user.source
	result = iq.buildReply("result")
	connect = False
	try:
		connect = user.connect(True)
	except api.AuthError, e:
		result = utils.buildIQError(iq, xmpp.ERR_NOT_AUTHORIZED, _(str(e) + " Try to logging in by token."))
コード例 #18
0
ファイル: mod_iq_register.py プロジェクト: opiums9/vk4xmpp
def sendRegisterForm(cl, iq):
    logger.debug("Sending registration form to user (jid: %s)",
                 iq.getFrom().getStripped())
    form = utils.buildDataForm(fields=forms.Forms.getComlicatedForm(),
                               data=[_("Fill the fields below")])
    result = iq.buildReply("result")
    result.setQueryPayload([form])
    sender(cl, result)
コード例 #19
0
def initializeUser(user, cl, iq, kwargs):
	result = iq.buildReply("result")
	connect = False
	resource = iq.getFrom().getResource()
	source = user.source
	try:
		connect = user.connect(**kwargs)
	except (api.TokenError, api.AuthError) as e:
		result = utils.buildIQError(iq, xmpp.ERR_NOT_AUTHORIZED, _(str(e) + " Try logging in by token."))
	else:
		if connect:
			user.initialize(resource=resource)
			executeHandlers("evt08", (source,))
		else:
			logger.error("user connection failed (jid: %s)" % source)
			result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Incorrect password or access token!"))
	sender(cl, result)
コード例 #20
0
def initializeUser(user, cl, iq, kwargs):
	result = iq.buildReply("result")
	connect = False
	resource = iq.getFrom().getResource()
	source = user.source
	try:
		connect = user.connect(**kwargs)
	except (api.TokenError, api.AuthError) as e:
		result = utils.buildIQError(iq, xmpp.ERR_NOT_AUTHORIZED, _(str(e) + " Try logging in by token."))
	else:
		if connect:
			user.initialize(resource=resource)
			executeHandlers("evt08", (source,))
		else:
			logger.error("user connection failed (jid: %s)" % source)
			result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Incorrect password or access token!"))
	sender(cl, result)
コード例 #21
0
ファイル: mod_xhtml.py プロジェクト: opiums9/vk4xmpp
def sendPhoto(user, data, type, address, mType):
    mask = user.vk.permissions
    if mType == "chat_id":
        address = address.split("@")[0].split("#")[1]
        send = False
    else:
        destination = address
        address = vk2xmpp(address)
        send = True

    if address == TransportID:
        answer = _("Are you kidding me?")
    elif mask:
        if mask & 4 == 4:  # we have enough access?
            ext = type.split("/")[1]
            name = "vk4xmpp_%s.%s" % (random.randint(1000, 9000), ext)
            server = str(
                user.vk.method("photos.getMessagesUploadServer")["upload_url"])
            response = json.loads(
                user.vk.engine.post(server,
                                    user.vk.engine.multipart(
                                        "photo", str(name), str(type), data),
                                    urlencode=False)[0])

            id = user.vk.method("photos.saveMessagesPhoto", response)
            if id:
                photo = "photo%(owner_id)d_%(id)s" % id[0]
                user.vk.sendMessage("", address, mType, {"attachment": photo})
                logger.debug(
                    "sendPhoto: image was successfully sent by user %s" %
                    user.source)
                answer = _("Your image was successfully sent.")
            else:
                answer = _(
                    "Sorry but we have failed to send this image."
                    " Seems you haven't enough permissions. Your token should be updated, register again."
                )
        else:
            answer = _(
                "Sorry but we have failed to send this image."
                " Seems you haven't enough permissions. Your token should be updated, register again."
            )
    else:
        answer = _("Something went wrong. We are so sorry.")
    if send:
        sendMessage(user.source, destination, answer, timestamp=1)
コード例 #22
0
def handleChatPresences(source, prs):
    """
	Makes the old users leave
	Args:
		source: stanza source
		prs: xmpp.Presence object
	"""
    jid = prs.getJid() or ""
    if "@" in jid:
        user = Chat.getUserObject(source)
        if user and source in getattr(user, "chats", {}):
            chat = user.chats[source]
            if jid.split("@")[1] == TransportID and chat.created:
                id = vk2xmpp(jid)
                if id != TransportID and id not in chat.users.keys():
                    if (time.gmtime().tm_mon, time.gmtime().tm_mday) == (4, 1):
                        setAffiliation(source,
                                       "outcast",
                                       jid,
                                       reason=_("Get the hell outta here!"))
                    else:
                        leaveChat(source, jid, _("I am not welcomed here"))

                if (prs.getRole(), prs.getAffiliation()) == ("moderator",
                                                             "owner"):
                    if jid != TransportID:
                        runDatabaseQuery(
                            "update groupchats set owner=? where jid=?",
                            (source, jid),
                            set=True)

                if chat.isUpdateRequired():
                    updateLastUsed(chat)

            # TODO: don't rewrite it every time we get a presence
            if jid.split("/")[0] == user.source:
                chat.owner_nickname = prs.getFrom().getResource()
                runDatabaseQuery("update groupchats set nick=? where jid=? ",
                                 (chat.owner_nickname, source),
                                 set=True)
            raise xmpp.NodeProcessed()

        elif user and prs.getType() != "unavailable":
            chat = createChat(user, source)
            chat.invited = True  # assume the user's joined themselves
コード例 #23
0
ファイル: mod_msg_main.py プロジェクト: mikken/vk4xmpp
def acceptCaptcha(key, source, destination):
	"""
	Accepts the captcha value in 2 possible ways:
		1. User sent a message
		2. User sent an IQ with the captcha value
	"""
	if args:
		answer = _("Captcha invalid.")
		user = Transport[source]
		logger.debug("user %s called captcha challenge" % source)
		try:
			user.captchaChallenge(key)
		except api.CaptchaNeeded:
			pass
		else:
			logger.debug("retry for user %s successed!" % source)
			answer = _("Captcha valid.")
			sendPresence(source, TransportID, caps=True)
		sendMessage(Component, source, destination, answer)
コード例 #24
0
ファイル: mod_prs_main.py プロジェクト: alexeycv/vk4xmpp
def presence_handler(cl, prs):
	pType = prs.getType()
	jidFrom = prs.getFrom()
	jidTo = prs.getTo()
	source = jidFrom.getStripped()
	destination = jidTo.getStripped()
	resource = jidFrom.getResource()
	if source in Transport:
		user = Transport[source]
		if pType in ("available", "probe", None):
			if jidTo == TransportID:
				if resource not in user.resources:
					logger.debug("Received presence %s from user. Will send sendInitPresence (jid: %s)" % (pType, source))
					user.resources.add(resource)
					runThread(user.sendInitPresence, ())
				runThread(executeHandlers, ("prs01", (source, prs)))

		elif pType == "unavailable":
			if jidTo == TransportID and resource in user.resources:
				user.resources.remove(resource)
				if user.resources:
					user.sendOutPresence(jidFrom)
			if not user.resources:
				sender(cl, xmpp.Presence(jidFrom, "unavailable", frm = TransportID))
				user.vk.disconnect()
				try:
					del Transport[source]
				except KeyError:
					pass
	
		elif pType == "error":
			eCode = prs.getErrorCode()
			if eCode == "404":
				user.vk.disconnect()

		elif pType == "subscribe":
			if destination == TransportID:
				sender(cl, xmpp.Presence(source, "subscribed", frm = TransportID))
				sender(cl, xmpp.Presence(jidFrom, frm = TransportID))
			else:
				sender(cl, xmpp.Presence(source, "subscribed", frm = jidTo))
				if user.friends:
					id = vk2xmpp(destination)
					if id in user.friends:
						if user.friends[id]["online"]:
							sender(cl, xmpp.Presence(jidFrom, frm = jidTo))
	
		elif pType == "unsubscribe":
			if source in Transport and destination == TransportID:
				removeUser(user, True, False)
				watcherMsg(_("User removed his registration: %s") % source)


	elif pType in ("available", None) and destination == TransportID:
		runThread(initializeUser, args=(source, resource, prs))
コード例 #25
0
ファイル: mod_iq_vcard.py プロジェクト: CSRedRat/vk4xmpp
def vcard_handler(cl, iq):
	# Vcard feature makes transport hang (especially the photo part)
	# Many clients love to query vcards so much, so the solution was in adding a semaphore here and sleep() at the bottom
	# This is probably not a good idea, but for now this is the best one
	with VCARD_SEMAPHORE:
		jidFrom = iq.getFrom()
		jidTo = iq.getTo()
		source = jidFrom.getStripped()
		destination = jidTo.getStripped()
		result = iq.buildReply("result")

		if destination == TransportID:
			vcard = buildVcard(VCARD_FIELDS)
			result.setPayload([vcard])

		elif source in Transport:
			user = Transport[source]
			if user.friends:
				id = vk2xmpp(destination)
				args = ["screen_name"]
				values = VCARD_FIELDS.copy()
				if id in user.friends.keys():
					args.append(PhotoSize)
				data = user.vk.getUserData(id, args)
				name = data.get("name", str(data))
				screen_name = data.get("screen_name")
				if not user.settings.use_nicknames:
					screen_name = name
				values["NICKNAME"] = screen_name
				values["FN"] = name
				values["URL"] = "http://vk.com/id%s" % id
				if id in user.friends.keys():
					values["PHOTO"] = data.get(PhotoSize) or URL_VCARD_NO_IMAGE
				vCard = buildVcard(values)
				result.setPayload([vCard])
			else:
				result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Your friend-list is empty."))
		else:
			result = utils.buildIQError(iq, xmpp.ERR_REGISTRATION_REQUIRED, _("You're not registered for this action."))
		sender(cl, result)
		time.sleep(1.5)
コード例 #26
0
ファイル: forms.py プロジェクト: CSRedRat/vk4xmpp
    def getComlicatedForm(cls):
        form = cls.getSimpleForm()
        # This is why we have a fixed order
        form[1]["label"] = _("Password/Access-token")
        form[1]["desc"] = _("Enter the token or password")

        form.insert(
            1,
            {
                "var": "phone",
                "type": "text-single",
                "label": _("Phone number"),
                "value": "+",
                "desc": _("Enter phone number in format +71234567890"),
            },
        )
        form.insert(
            2,
            {
                "var": "use_password",
                "type": "boolean",
                "label": _("Get access-token automatically"),
                "desc": _("Tries to get access-token automatically. (It's recommended to use a token)"),
            },
        )
        return form
コード例 #27
0
ファイル: mod_msg_main.py プロジェクト: tonal/vk4xmpp
def acceptCaptcha(key, source, destination):
	"""
	Accepts the captcha value in 2 possible ways:
		1. User sent a message
		2. User sent an IQ with the captcha value
	"""
	if args:
		user = Transport[source]
		logger.debug("user %s called captcha challenge" % source)
		try:
			user.captchaChallenge(key)
			valid = True
		except api.CaptchaNeeded:
			valid = False
			answer = _("Captcha invalid.")
		else:
			logger.debug("retry for user %s successed!" % source)
			answer = _("Captcha valid.")
			sendPresence(source, TransportID, hash=TRANSPORT_CAPS_HASH)

		sendMessage(source, destination, answer, mtype="normal")
		if not valid:
			executeHandlers("evt04", (user, user.vk.engine.captcha["img"]))
コード例 #28
0
ファイル: mod_prs_main.py プロジェクト: alexeycv/vk4xmpp
def initializeUser(source, resource, prs):
	logger.debug("User not in the transport, but presence received. Searching in database (jid: %s)" % source)
	with Database(DatabaseFile, Semaphore) as db:
		db("select jid,username from users where jid=?", (source,))
		data = db.fetchone()
	if data:
		logger.debug("User has been found in database (jid: %s)" % source)
		jid, phone = data
		Transport[jid] = user = User((phone, None), jid)
		try:
			if user.connect():
				user.initialize(False, True, resource)
				runThread(executeHandlers, ("prs01", (source, prs)))
			else:
				crashLog("user.connect", False)
				sendMessage(Component, jid, TransportID, _("Auth failed! If this error repeated, please register again. This incident will be reported."))
		except Exception:
			crashLog("prs.init")
コード例 #29
0
	def getComlicatedForm(cls):
		form = cls.getSimpleForm()
		# This is why we have a fixed order
		form[1]["label"] = _("Password/Access-token")
		form[1]["desc"] = _("Enter the token or password")

		form.insert(1, {"var": "phone", "type": "text-single",
			"label": _("Phone number"), "value": "+",
			"desc": _("Enter phone number in format +71234567890")})
		form.insert(2, {"var": "use_password", "type": "boolean", 
			"label": _("Get access-token automatically"), 
			"desc": _("Tries to get access-token automatically. (It's recommended to use a token)")})
		return form
コード例 #30
0
ファイル: mod_prs_main.py プロジェクト: sysx1000/vk4xmpp
def initializeUser(source, resource, prs):
	"""
	Initializes user for the first time after they connected
	"""
	logger.debug("Got a presence. Searching jid in the database. (jid: %s)", source)
	user = User(source)
	try:
		connect = user.connect()
	except RuntimeError:
		pass
	except Exception:
		sendMessage(source, TransportID, 
			_("Auth failed! If this error repeated, "
				"please register again. This incident will be reported."))
		crashLog("user.connect")
	else:
		user.initialize(send=True, resource=resource)  # probably we need to know resource a bit earlier than this time
		utils.runThread(executeHandlers, ("prs01", (source, prs)))

	if source in USERS_ON_INIT:
		USERS_ON_INIT.remove(source)
コード例 #31
0
ファイル: rostermanager.py プロジェクト: eg-astrouka/vk4xmpp
	def checkRosterx(cls, user, resource):
		"""
		Checks if the client supports XEP-0144: Roster Item Exchange
		If it doesn't, or it didn't answer us, then transport will use the old method
		"""
		jid = "%s/%s" % (user.source, resource)
		sendPresence(jid, TransportID, "subscribe", IDENTIFIER["name"])
		sendPresence(jid, TransportID, nick=IDENTIFIER["name"],
			reason=_("You are being initialized, please wait..."), show="xa")
		def answer(cl, stanza):
			if xmpp.isResultNode(stanza):
				query = stanza.getTag("query")
				if query.getTags("feature", attrs={"var": xmpp.NS_ROSTERX}):
					logger.debug("using the RosterX method to add items to user's roster (jid: %s)", jid)
					cls.manageRoster(user, jid, user.friends)
				else:
					logger.debug("using the old method to add items to user's roster (jid: %s)", jid)
					user.sendSubPresence(user.friends)

		iq = xmpp.Iq("get", to=jid, frm=TransportID)
		iq.addChild("query", namespace=xmpp.NS_DISCO_INFO)
		sender(Component, iq, cb=answer)
コード例 #32
0
def handleChatPresences(source, prs):
	"""
	Makes the old users leave
	Args:
		source: stanza source
		prs: xmpp.Presence object
	"""
	jid = prs.getJid() or ""
	if "@" in jid and prs.getType() != "unavailable":
		user = Chat.getUserObject(source)
		if user and source in getattr(user, "chats", {}):
			chat = user.chats[source]
			if jid.split("@")[1] == TransportID and chat.created:
				id = vk2xmpp(jid)
				if id != TransportID and id not in chat.users.keys():
					if (time.gmtime().tm_mon, time.gmtime().tm_mday) == (4, 1):
						setAffiliation(source, "outcast", jid, reason=_("Get the hell outta here!"))
					else:
						leaveChat(source, jid)

				if (prs.getRole(), prs.getAffiliation()) == ("moderator", "owner"):
					if jid != TransportID:
						runDatabaseQuery("update groupchats set owner=? where jid=?", (source, jid), set=True)

				if chat.isUpdateRequired():
					updateLastUsed(chat)

			# TODO: don't rewrite it every time we get a presence
			if jid.split("/")[0] == user.source:
				nick = prs.getFrom().getResource()
				chat.owner_nickname = nick
				runDatabaseQuery("update groupchats set nick=? where jid=? ", (nick, source), set=True)
				logger.debug("mod_groupchat_prs: setting user nickname to: %s for chat %s and user: %s", nick, source, user.source)
			raise xmpp.NodeProcessed()

		elif user:
			chat = createChat(user, source)
			chat.invited = True  # assume the user's joined themselves
コード例 #33
0
ファイル: mod_prs_main.py プロジェクト: mrDoctorWho/vk4xmpp
def initializeUser(source, resource, prs):
	"""
	Initializes user for the first time after they connected
	"""
	logger.debug("Got a presence. Searching jid in the database. (jid: %s)", source)
	user = User(source)
	try:
		user.connect()
	except RuntimeError:
		pass
	except Exception as e:
		if not isinstance(e, api.TokenError):
			report(crashLog("user.connect"))
		sendMessage(source, TransportID,
			_("Auth failed! If this error repeated, "
				"please register again."
				" This incident will be reported.\nCause: %s") % returnExc())
		logger.error("Failed to authenicate user! Error: %s (jid: %s)", e.message, source)
	else:
		user.initialize(send=True, resource=resource)  # probably we need to know resource a bit earlier than this time
		utils.runThread(executeHandlers, ("prs01", (source, prs)))
	finally:
		if source in USERS_ON_INIT:
			USERS_ON_INIT.remove(source)
コード例 #34
0
ファイル: mod_iq_register.py プロジェクト: alexeycv/vk4xmpp
def register_handler(cl, iq):
	jidTo = iq.getTo()
	jidFrom = iq.getFrom()
	source = jidFrom.getStripped()
	destination = jidTo.getStripped()
	iType = iq.getType()
	queryChildren = iq.getQueryChildren()
	result = iq.buildReply("result")
	if USER_LIMIT:
		count = calcStats()[0]
		if count >= USER_LIMIT and not source in Transport:
			cl.send(utils.buildIQError(iq, xmpp.ERR_NOT_ALLOWED, _("Transport's admins limited registrations, sorry.")))
			raise xmpp.NodeProcessed()

	if destination == TransportID:
		if iType == "get" and not queryChildren:
			logger.debug("Send registration form to user (jid: %s)" % source)
			form = utils.buildDataForm(fields = [
				{"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": "use_password", "type": "boolean", "label": _("Get access-token automatically"), "desc": _("Try to get access-token automatically. (NOT recommended, password required!)")}, #"value": "0"},#, "0"}
				{"var": "password", "type": "text-private", "label": _("Password/Access-token"), "desc": _("Type password, access-token or url (recommended)")}], 
			data = [_("Type data in fields")])
			result.setQueryPayload([form])

		elif iType == "set" and queryChildren:
			phone, password, use_password, token = False, False, False, False #?
			query = iq.getTag("query")
			data = query.getTag("x", namespace=xmpp.NS_DATA)
			if data:
				form = xmpp.DataForm(node=data).asDict()
				phone = form.get("phone", "")
				password = form.get("password", "")
				use_password = utils.normalizeValue(form.get("use_password", ""))

				if not password:
					result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Empty password/token field"))

	## Some clients send "true" or "false" instead of 1/0
				user = User(source=source)
				use_password = int(use_password)


	## If user won't use password so we need token
				if not use_password:
					logger.debug("user won't use a password (jid: %s)" % source)
					token = password
					password = False
				else:
					logger.debug("user want to use a password (jid: %s)" % source)
					if not phone:
						result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Phone incorrect."))
					user.password = password
					user.username = phone
		
	## Check if user already registered. If registered, delete him then
				if source in Transport:
					user = Transport[source]
					removeUser(user, semph=False)

	## If we not using a password so we need to check if there a link or token. Or maybe user's wrong and that's his password.
				if not use_password:
					_token = api.token_exp.search(token)
					if _token:
						_token = _token.group(0)
						user.token = _token
					else:
						user.password = token
						user.username = phone
					
		## Check if all data is correct.
				runThread(initializeUser, (user, cl, iq))
				result = None

			elif query.getTag("remove"):
				logger.debug("user %s want to remove me..." % source)
				if source in Transport:
					user = Transport[source]
					removeUser(user, True, False)
					result.setPayload([], add = 0)
					watcherMsg(_("User has removed registration: %s") % source)
				else:
					logger.debug("... but he don't know that he was removed already!")

		else:
			result = utils.buildIQError(iq, 0, _("Feature not implemented."))
	if result: sender(cl, result) 
コード例 #35
0
ファイル: mod_iq_disco.py プロジェクト: mrDoctorWho/vk4xmpp
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)
コード例 #36
0
def sendRegisterForm(cl, iq):
	logger.debug("Send registration form to user (jid: %s)", iq.getFrom().getStripped())
	form = utils.buildDataForm(fields=forms.Forms.getComlicatedForm(), data=[_("Fill the fields below")])
	result = iq.buildReply("result")
	result.setQueryPayload([form])
	sender(cl, result)
コード例 #37
0
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)
コード例 #38
0
ファイル: mod_iq_register.py プロジェクト: alexeycv/vk4xmpp
	source = user.source
	result = iq.buildReply("result")
	connect = False
	try:
		connect = user.connect(True)
	except api.AuthError, e:
		result = utils.buildIQError(iq, xmpp.ERR_NOT_AUTHORIZED, _(str(e) + " Try to logging in by token."))
	else:
		if connect:
			try:
				user.initialize()
			except api.CaptchaNeeded:
				user.vk.captchaChallenge()
			except Exception: ## is there could be any other exception?
				crashLog("user.init")
				result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Initialization failed."))
			else:
##				Transport[source] = user
				watcherMsg(_("New user registered: %s") % source)
		else:
			logger.error("user connection failed (jid: %s)" % source)
			result = utils.buildIQError(iq, xmpp.ERR_BAD_REQUEST, _("Incorrect password or access token!"))
	sender(cl, result)

def register_handler(cl, iq):
	jidTo = iq.getTo()
	jidFrom = iq.getFrom()
	source = jidFrom.getStripped()
	destination = jidTo.getStripped()
	iType = iq.getType()
	queryChildren = iq.getQueryChildren()
コード例 #39
0
ファイル: mod_iq_disco.py プロジェクト: CSRedRat/vk4xmpp
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": "text", "type": "text-multi", "label": _("Message"), "required": True}], 
							title=_("Enter the message text"))
					else:
						if dictForm.has_key("text"):
							text = "\n".join(dictForm["text"])
							utils.runThread(sendGlobalMessage, (text,))
						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:
					user = Transport[source]
					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)