summaryrefslogtreecommitdiffstats
path: root/common/misc.py
blob: edfe3a056dc115c02844ba20af09def25f447e9b (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
# -*- coding: utf-8 -*-
import validators
from common.strings import StaticAnswers


def deduplicate(reply):
	"""
	list deduplication method
	:param list reply: list containing non unique items
	:return: list containing unique items
	"""
	reply_dedup = list()
	for item in reply:
		if item not in reply_dedup:
			reply_dedup.append(item)

	return reply_dedup


def validate(keyword, target):
	"""
	validation method to reduce malformed querys and unnecessary connection attempts
	:param keyword: used keyword
	:param target: provided target
	:return: true if valid
	"""
	# if keyword is in noarg list return True
	if keyword in StaticAnswers().keys("noarg"):
		return True

	# prevent AttributeError if target is NoneType
	if target is None:
		return False

	# if keyword in domain list
	if keyword in StaticAnswers().keys('domain'):
		# if target is a domain / email return True
		if validators.domain(target) or validators.email(target):
			return True

	# check if keyword is in number list
	elif keyword in StaticAnswers().keys('number'):
		return target.isdigit()

	# if keyword in expand list return True
	elif keyword in StaticAnswers().keys("expand"):
		return True

	# if the target could not be validated until this return False
	return False


def arg_abbr(value, possible_values):
	"""
	optional argument abbreviation
	if the provided string value > 2 characters the most likely value will be chosen
	:return: completes the value to the most likely one
	"""
	# prevent traceback if value is None
	if value and possible_values is not None:
		# if opt_argument is smaller then 2 pass to prohibit multiple answers
		if len(value) < 2:
			return value

		abbr = str(value)

		# searches the best match in the list of possible_abbr and completes the opt_arg to that
		new_value = [s for s in list(possible_values) if s.startswith(abbr)]

		# prevent index error if abbreviation has not result
		if new_value:
			value = new_value[0]

	return value


class HandleError:
	"""
	simple XMPP error / exception class formating the error condition
	"""
	def __init__(self, error, key, target):
		# init all necessary variables
		self.text = error.text
		self.condition = error.condition
		self.key = key
		self.target = target

	def report(self):
		# return the formatted result string to the user
		text = "%s %s resulted in: %s" % (self.key, self.target, self.condition)

		return text