repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
locationlabs/mockredis | mockredis/client.py | MockRedis.lset | def lset(self, key, index, value):
"""Emulate lset."""
redis_list = self._get_list(key, 'LSET')
if redis_list is None:
raise ResponseError("no such key")
try:
redis_list[index] = self._encode(value)
except IndexError:
raise ResponseError("index out of range") | python | def lset(self, key, index, value):
"""Emulate lset."""
redis_list = self._get_list(key, 'LSET')
if redis_list is None:
raise ResponseError("no such key")
try:
redis_list[index] = self._encode(value)
except IndexError:
raise ResponseError("index out of range") | Emulate lset. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L792-L800 |
locationlabs/mockredis | mockredis/client.py | MockRedis._common_scan | def _common_scan(self, values_function, cursor='0', match=None, count=10, key=None):
"""
Common scanning skeleton.
:param key: optional function used to identify what 'match' is applied to
"""
if count is None:
count = 10
cursor = int(cursor)
count = int(count)
if not count:
raise ValueError('if specified, count must be > 0: %s' % count)
values = values_function()
if cursor + count >= len(values):
# we reached the end, back to zero
result_cursor = 0
else:
result_cursor = cursor + count
values = values[cursor:cursor+count]
if match is not None:
regex = re.compile(b'^' + re.escape(self._encode(match)).replace(b'\\*', b'.*') + b'$')
if not key:
key = lambda v: v
values = [v for v in values if regex.match(key(v))]
return [result_cursor, values] | python | def _common_scan(self, values_function, cursor='0', match=None, count=10, key=None):
"""
Common scanning skeleton.
:param key: optional function used to identify what 'match' is applied to
"""
if count is None:
count = 10
cursor = int(cursor)
count = int(count)
if not count:
raise ValueError('if specified, count must be > 0: %s' % count)
values = values_function()
if cursor + count >= len(values):
# we reached the end, back to zero
result_cursor = 0
else:
result_cursor = cursor + count
values = values[cursor:cursor+count]
if match is not None:
regex = re.compile(b'^' + re.escape(self._encode(match)).replace(b'\\*', b'.*') + b'$')
if not key:
key = lambda v: v
values = [v for v in values if regex.match(key(v))]
return [result_cursor, values] | Common scanning skeleton.
:param key: optional function used to identify what 'match' is applied to | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L882-L910 |
locationlabs/mockredis | mockredis/client.py | MockRedis.scan | def scan(self, cursor='0', match=None, count=10):
"""Emulate scan."""
def value_function():
return sorted(self.redis.keys()) # sorted list for consistent order
return self._common_scan(value_function, cursor=cursor, match=match, count=count) | python | def scan(self, cursor='0', match=None, count=10):
"""Emulate scan."""
def value_function():
return sorted(self.redis.keys()) # sorted list for consistent order
return self._common_scan(value_function, cursor=cursor, match=match, count=count) | Emulate scan. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L912-L916 |
locationlabs/mockredis | mockredis/client.py | MockRedis.sscan | def sscan(self, name, cursor='0', match=None, count=10):
"""Emulate sscan."""
def value_function():
members = list(self.smembers(name))
members.sort() # sort for consistent order
return members
return self._common_scan(value_function, cursor=cursor, match=match, count=count) | python | def sscan(self, name, cursor='0', match=None, count=10):
"""Emulate sscan."""
def value_function():
members = list(self.smembers(name))
members.sort() # sort for consistent order
return members
return self._common_scan(value_function, cursor=cursor, match=match, count=count) | Emulate sscan. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L926-L932 |
locationlabs/mockredis | mockredis/client.py | MockRedis.zscan | def zscan(self, name, cursor='0', match=None, count=10):
"""Emulate zscan."""
def value_function():
values = self.zrange(name, 0, -1, withscores=True)
values.sort(key=lambda x: x[1]) # sort for consistent order
return values
return self._common_scan(value_function, cursor=cursor, match=match, count=count, key=lambda v: v[0]) | python | def zscan(self, name, cursor='0', match=None, count=10):
"""Emulate zscan."""
def value_function():
values = self.zrange(name, 0, -1, withscores=True)
values.sort(key=lambda x: x[1]) # sort for consistent order
return values
return self._common_scan(value_function, cursor=cursor, match=match, count=count, key=lambda v: v[0]) | Emulate zscan. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L943-L949 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hscan | def hscan(self, name, cursor='0', match=None, count=10):
"""Emulate hscan."""
def value_function():
values = self.hgetall(name)
values = list(values.items()) # list of tuples for sorting and matching
values.sort(key=lambda x: x[0]) # sort for consistent order
return values
scanned = self._common_scan(value_function, cursor=cursor, match=match, count=count, key=lambda v: v[0]) # noqa
scanned[1] = dict(scanned[1]) # from list of tuples back to dict
return scanned | python | def hscan(self, name, cursor='0', match=None, count=10):
"""Emulate hscan."""
def value_function():
values = self.hgetall(name)
values = list(values.items()) # list of tuples for sorting and matching
values.sort(key=lambda x: x[0]) # sort for consistent order
return values
scanned = self._common_scan(value_function, cursor=cursor, match=match, count=count, key=lambda v: v[0]) # noqa
scanned[1] = dict(scanned[1]) # from list of tuples back to dict
return scanned | Emulate hscan. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L960-L969 |
locationlabs/mockredis | mockredis/client.py | MockRedis.hscan_iter | def hscan_iter(self, name, match=None, count=10):
"""Emulate hscan_iter."""
cursor = '0'
while cursor != 0:
cursor, data = self.hscan(name, cursor=cursor,
match=match, count=count)
for item in data.items():
yield item | python | def hscan_iter(self, name, match=None, count=10):
"""Emulate hscan_iter."""
cursor = '0'
while cursor != 0:
cursor, data = self.hscan(name, cursor=cursor,
match=match, count=count)
for item in data.items():
yield item | Emulate hscan_iter. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L971-L978 |
locationlabs/mockredis | mockredis/client.py | MockRedis.sadd | def sadd(self, key, *values):
"""Emulate sadd."""
if len(values) == 0:
raise ResponseError("wrong number of arguments for 'sadd' command")
redis_set = self._get_set(key, 'SADD', create=True)
before_count = len(redis_set)
redis_set.update(map(self._encode, values))
after_count = len(redis_set)
return after_count - before_count | python | def sadd(self, key, *values):
"""Emulate sadd."""
if len(values) == 0:
raise ResponseError("wrong number of arguments for 'sadd' command")
redis_set = self._get_set(key, 'SADD', create=True)
before_count = len(redis_set)
redis_set.update(map(self._encode, values))
after_count = len(redis_set)
return after_count - before_count | Emulate sadd. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L982-L990 |
locationlabs/mockredis | mockredis/client.py | MockRedis.sdiff | def sdiff(self, keys, *args):
"""Emulate sdiff."""
func = lambda left, right: left.difference(right)
return self._apply_to_sets(func, "SDIFF", keys, *args) | python | def sdiff(self, keys, *args):
"""Emulate sdiff."""
func = lambda left, right: left.difference(right)
return self._apply_to_sets(func, "SDIFF", keys, *args) | Emulate sdiff. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L997-L1000 |
locationlabs/mockredis | mockredis/client.py | MockRedis.sdiffstore | def sdiffstore(self, dest, keys, *args):
"""Emulate sdiffstore."""
result = self.sdiff(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | python | def sdiffstore(self, dest, keys, *args):
"""Emulate sdiffstore."""
result = self.sdiff(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | Emulate sdiffstore. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1002-L1006 |
locationlabs/mockredis | mockredis/client.py | MockRedis.sinter | def sinter(self, keys, *args):
"""Emulate sinter."""
func = lambda left, right: left.intersection(right)
return self._apply_to_sets(func, "SINTER", keys, *args) | python | def sinter(self, keys, *args):
"""Emulate sinter."""
func = lambda left, right: left.intersection(right)
return self._apply_to_sets(func, "SINTER", keys, *args) | Emulate sinter. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1008-L1011 |
locationlabs/mockredis | mockredis/client.py | MockRedis.sinterstore | def sinterstore(self, dest, keys, *args):
"""Emulate sinterstore."""
result = self.sinter(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | python | def sinterstore(self, dest, keys, *args):
"""Emulate sinterstore."""
result = self.sinter(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | Emulate sinterstore. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1013-L1017 |
locationlabs/mockredis | mockredis/client.py | MockRedis.sismember | def sismember(self, name, value):
"""Emulate sismember."""
redis_set = self._get_set(name, 'SISMEMBER')
if not redis_set:
return 0
result = self._encode(value) in redis_set
return 1 if result else 0 | python | def sismember(self, name, value):
"""Emulate sismember."""
redis_set = self._get_set(name, 'SISMEMBER')
if not redis_set:
return 0
result = self._encode(value) in redis_set
return 1 if result else 0 | Emulate sismember. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1019-L1026 |
locationlabs/mockredis | mockredis/client.py | MockRedis.smove | def smove(self, src, dst, value):
"""Emulate smove."""
src_set = self._get_set(src, 'SMOVE')
dst_set = self._get_set(dst, 'SMOVE')
value = self._encode(value)
if value not in src_set:
return False
src_set.discard(value)
dst_set.add(value)
self.redis[self._encode(src)], self.redis[self._encode(dst)] = src_set, dst_set
return True | python | def smove(self, src, dst, value):
"""Emulate smove."""
src_set = self._get_set(src, 'SMOVE')
dst_set = self._get_set(dst, 'SMOVE')
value = self._encode(value)
if value not in src_set:
return False
src_set.discard(value)
dst_set.add(value)
self.redis[self._encode(src)], self.redis[self._encode(dst)] = src_set, dst_set
return True | Emulate smove. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1032-L1044 |
locationlabs/mockredis | mockredis/client.py | MockRedis.spop | def spop(self, name):
"""Emulate spop."""
redis_set = self._get_set(name, 'SPOP')
if not redis_set:
return None
member = choice(list(redis_set))
redis_set.remove(member)
if len(redis_set) == 0:
self.delete(name)
return member | python | def spop(self, name):
"""Emulate spop."""
redis_set = self._get_set(name, 'SPOP')
if not redis_set:
return None
member = choice(list(redis_set))
redis_set.remove(member)
if len(redis_set) == 0:
self.delete(name)
return member | Emulate spop. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1046-L1055 |
locationlabs/mockredis | mockredis/client.py | MockRedis.srandmember | def srandmember(self, name, number=None):
"""Emulate srandmember."""
redis_set = self._get_set(name, 'SRANDMEMBER')
if not redis_set:
return None if number is None else []
if number is None:
return choice(list(redis_set))
elif number > 0:
return sample(list(redis_set), min(number, len(redis_set)))
else:
return [choice(list(redis_set)) for _ in xrange(abs(number))] | python | def srandmember(self, name, number=None):
"""Emulate srandmember."""
redis_set = self._get_set(name, 'SRANDMEMBER')
if not redis_set:
return None if number is None else []
if number is None:
return choice(list(redis_set))
elif number > 0:
return sample(list(redis_set), min(number, len(redis_set)))
else:
return [choice(list(redis_set)) for _ in xrange(abs(number))] | Emulate srandmember. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1057-L1067 |
locationlabs/mockredis | mockredis/client.py | MockRedis.srem | def srem(self, key, *values):
"""Emulate srem."""
redis_set = self._get_set(key, 'SREM')
if not redis_set:
return 0
before_count = len(redis_set)
for value in values:
redis_set.discard(self._encode(value))
after_count = len(redis_set)
if before_count > 0 and len(redis_set) == 0:
self.delete(key)
return before_count - after_count | python | def srem(self, key, *values):
"""Emulate srem."""
redis_set = self._get_set(key, 'SREM')
if not redis_set:
return 0
before_count = len(redis_set)
for value in values:
redis_set.discard(self._encode(value))
after_count = len(redis_set)
if before_count > 0 and len(redis_set) == 0:
self.delete(key)
return before_count - after_count | Emulate srem. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1069-L1080 |
locationlabs/mockredis | mockredis/client.py | MockRedis.sunion | def sunion(self, keys, *args):
"""Emulate sunion."""
func = lambda left, right: left.union(right)
return self._apply_to_sets(func, "SUNION", keys, *args) | python | def sunion(self, keys, *args):
"""Emulate sunion."""
func = lambda left, right: left.union(right)
return self._apply_to_sets(func, "SUNION", keys, *args) | Emulate sunion. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1082-L1085 |
locationlabs/mockredis | mockredis/client.py | MockRedis.sunionstore | def sunionstore(self, dest, keys, *args):
"""Emulate sunionstore."""
result = self.sunion(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | python | def sunionstore(self, dest, keys, *args):
"""Emulate sunionstore."""
result = self.sunion(keys, *args)
self.redis[self._encode(dest)] = result
return len(result) | Emulate sunionstore. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1087-L1091 |
locationlabs/mockredis | mockredis/client.py | MockRedis.eval | def eval(self, script, numkeys, *keys_and_args):
"""Emulate eval"""
sha = self.script_load(script)
return self.evalsha(sha, numkeys, *keys_and_args) | python | def eval(self, script, numkeys, *keys_and_args):
"""Emulate eval"""
sha = self.script_load(script)
return self.evalsha(sha, numkeys, *keys_and_args) | Emulate eval | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1306-L1309 |
locationlabs/mockredis | mockredis/client.py | MockRedis.evalsha | def evalsha(self, sha, numkeys, *keys_and_args):
"""Emulates evalsha"""
if not self.script_exists(sha)[0]:
raise RedisError("Sha not registered")
script_callable = Script(self, self.shas[sha], self.load_lua_dependencies)
numkeys = max(numkeys, 0)
keys = keys_and_args[:numkeys]
args = keys_and_args[numkeys:]
return script_callable(keys, args) | python | def evalsha(self, sha, numkeys, *keys_and_args):
"""Emulates evalsha"""
if not self.script_exists(sha)[0]:
raise RedisError("Sha not registered")
script_callable = Script(self, self.shas[sha], self.load_lua_dependencies)
numkeys = max(numkeys, 0)
keys = keys_and_args[:numkeys]
args = keys_and_args[numkeys:]
return script_callable(keys, args) | Emulates evalsha | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1311-L1319 |
locationlabs/mockredis | mockredis/client.py | MockRedis.script_load | def script_load(self, script):
"""Emulate script_load"""
sha_digest = sha1(script.encode("utf-8")).hexdigest()
self.shas[sha_digest] = script
return sha_digest | python | def script_load(self, script):
"""Emulate script_load"""
sha_digest = sha1(script.encode("utf-8")).hexdigest()
self.shas[sha_digest] = script
return sha_digest | Emulate script_load | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1334-L1338 |
locationlabs/mockredis | mockredis/client.py | MockRedis.call | def call(self, command, *args):
"""
Sends call to the function, whose name is specified by command.
Used by Script invocations and normalizes calls using standard
Redis arguments to use the expected redis-py arguments.
"""
command = self._normalize_command_name(command)
args = self._normalize_command_args(command, *args)
redis_function = getattr(self, command)
value = redis_function(*args)
return self._normalize_command_response(command, value) | python | def call(self, command, *args):
"""
Sends call to the function, whose name is specified by command.
Used by Script invocations and normalizes calls using standard
Redis arguments to use the expected redis-py arguments.
"""
command = self._normalize_command_name(command)
args = self._normalize_command_args(command, *args)
redis_function = getattr(self, command)
value = redis_function(*args)
return self._normalize_command_response(command, value) | Sends call to the function, whose name is specified by command.
Used by Script invocations and normalizes calls using standard
Redis arguments to use the expected redis-py arguments. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1344-L1356 |
locationlabs/mockredis | mockredis/client.py | MockRedis._normalize_command_args | def _normalize_command_args(self, command, *args):
"""
Modifies the command arguments to match the
strictness of the redis client.
"""
if command == 'zadd' and not self.strict and len(args) >= 3:
# Reorder score and name
zadd_args = [x for tup in zip(args[2::2], args[1::2]) for x in tup]
return [args[0]] + zadd_args
if command in ('zrangebyscore', 'zrevrangebyscore'):
# expected format is: <command> name min max start num with_scores score_cast_func
if len(args) <= 3:
# just plain min/max
return args
start, num = None, None
withscores = False
for i, arg in enumerate(args[3:], 3):
# keywords are case-insensitive
lower_arg = self._encode(arg).lower()
# handle "limit"
if lower_arg == b"limit" and i + 2 < len(args):
start, num = args[i + 1], args[i + 2]
# handle "withscores"
if lower_arg == b"withscores":
withscores = True
# do not expect to set score_cast_func
return args[:3] + (start, num, withscores)
return args | python | def _normalize_command_args(self, command, *args):
"""
Modifies the command arguments to match the
strictness of the redis client.
"""
if command == 'zadd' and not self.strict and len(args) >= 3:
# Reorder score and name
zadd_args = [x for tup in zip(args[2::2], args[1::2]) for x in tup]
return [args[0]] + zadd_args
if command in ('zrangebyscore', 'zrevrangebyscore'):
# expected format is: <command> name min max start num with_scores score_cast_func
if len(args) <= 3:
# just plain min/max
return args
start, num = None, None
withscores = False
for i, arg in enumerate(args[3:], 3):
# keywords are case-insensitive
lower_arg = self._encode(arg).lower()
# handle "limit"
if lower_arg == b"limit" and i + 2 < len(args):
start, num = args[i + 1], args[i + 2]
# handle "withscores"
if lower_arg == b"withscores":
withscores = True
# do not expect to set score_cast_func
return args[:3] + (start, num, withscores)
return args | Modifies the command arguments to match the
strictness of the redis client. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1369-L1404 |
locationlabs/mockredis | mockredis/client.py | MockRedis.config_get | def config_get(self, pattern='*'):
"""
Get one or more configuration parameters.
"""
result = {}
for name, value in self.redis_config.items():
if fnmatch.fnmatch(name, pattern):
try:
result[name] = int(value)
except ValueError:
result[name] = value
return result | python | def config_get(self, pattern='*'):
"""
Get one or more configuration parameters.
"""
result = {}
for name, value in self.redis_config.items():
if fnmatch.fnmatch(name, pattern):
try:
result[name] = int(value)
except ValueError:
result[name] = value
return result | Get one or more configuration parameters. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1421-L1432 |
locationlabs/mockredis | mockredis/client.py | MockRedis._get_list | def _get_list(self, key, operation, create=False):
"""
Get (and maybe create) a list by name.
"""
return self._get_by_type(key, operation, create, b'list', []) | python | def _get_list(self, key, operation, create=False):
"""
Get (and maybe create) a list by name.
"""
return self._get_by_type(key, operation, create, b'list', []) | Get (and maybe create) a list by name. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1441-L1445 |
locationlabs/mockredis | mockredis/client.py | MockRedis._get_set | def _get_set(self, key, operation, create=False):
"""
Get (and maybe create) a set by name.
"""
return self._get_by_type(key, operation, create, b'set', set()) | python | def _get_set(self, key, operation, create=False):
"""
Get (and maybe create) a set by name.
"""
return self._get_by_type(key, operation, create, b'set', set()) | Get (and maybe create) a set by name. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1447-L1451 |
locationlabs/mockredis | mockredis/client.py | MockRedis._get_hash | def _get_hash(self, name, operation, create=False):
"""
Get (and maybe create) a hash by name.
"""
return self._get_by_type(name, operation, create, b'hash', {}) | python | def _get_hash(self, name, operation, create=False):
"""
Get (and maybe create) a hash by name.
"""
return self._get_by_type(name, operation, create, b'hash', {}) | Get (and maybe create) a hash by name. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1453-L1457 |
locationlabs/mockredis | mockredis/client.py | MockRedis._get_zset | def _get_zset(self, name, operation, create=False):
"""
Get (and maybe create) a sorted set by name.
"""
return self._get_by_type(name, operation, create, b'zset', SortedSet(), return_default=False) | python | def _get_zset(self, name, operation, create=False):
"""
Get (and maybe create) a sorted set by name.
"""
return self._get_by_type(name, operation, create, b'zset', SortedSet(), return_default=False) | Get (and maybe create) a sorted set by name. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1459-L1463 |
locationlabs/mockredis | mockredis/client.py | MockRedis._get_by_type | def _get_by_type(self, key, operation, create, type_, default, return_default=True):
"""
Get (and maybe create) a redis data structure by name and type.
"""
key = self._encode(key)
if self.type(key) in [type_, b'none']:
if create:
return self.redis.setdefault(key, default)
else:
return self.redis.get(key, default if return_default else None)
raise TypeError("{} requires a {}".format(operation, type_)) | python | def _get_by_type(self, key, operation, create, type_, default, return_default=True):
"""
Get (and maybe create) a redis data structure by name and type.
"""
key = self._encode(key)
if self.type(key) in [type_, b'none']:
if create:
return self.redis.setdefault(key, default)
else:
return self.redis.get(key, default if return_default else None)
raise TypeError("{} requires a {}".format(operation, type_)) | Get (and maybe create) a redis data structure by name and type. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1465-L1476 |
locationlabs/mockredis | mockredis/client.py | MockRedis._translate_range | def _translate_range(self, len_, start, end):
"""
Translate range to valid bounds.
"""
if start < 0:
start += len_
start = max(0, min(start, len_))
if end < 0:
end += len_
end = max(-1, min(end, len_ - 1))
return start, end | python | def _translate_range(self, len_, start, end):
"""
Translate range to valid bounds.
"""
if start < 0:
start += len_
start = max(0, min(start, len_))
if end < 0:
end += len_
end = max(-1, min(end, len_ - 1))
return start, end | Translate range to valid bounds. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1478-L1488 |
locationlabs/mockredis | mockredis/client.py | MockRedis._translate_limit | def _translate_limit(self, len_, start, num):
"""
Translate limit to valid bounds.
"""
if start > len_ or num <= 0:
return 0, 0
return min(start, len_), num | python | def _translate_limit(self, len_, start, num):
"""
Translate limit to valid bounds.
"""
if start > len_ or num <= 0:
return 0, 0
return min(start, len_), num | Translate limit to valid bounds. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1490-L1496 |
locationlabs/mockredis | mockredis/client.py | MockRedis._range_func | def _range_func(self, withscores, score_cast_func):
"""
Return a suitable function from (score, member)
"""
if withscores:
return lambda score_member: (score_member[1], score_cast_func(self._encode(score_member[0]))) # noqa
else:
return lambda score_member: score_member[1] | python | def _range_func(self, withscores, score_cast_func):
"""
Return a suitable function from (score, member)
"""
if withscores:
return lambda score_member: (score_member[1], score_cast_func(self._encode(score_member[0]))) # noqa
else:
return lambda score_member: score_member[1] | Return a suitable function from (score, member) | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1498-L1505 |
locationlabs/mockredis | mockredis/client.py | MockRedis._aggregate_func | def _aggregate_func(self, aggregate):
"""
Return a suitable aggregate score function.
"""
funcs = {"sum": add, "min": min, "max": max}
func_name = aggregate.lower() if aggregate else 'sum'
try:
return funcs[func_name]
except KeyError:
raise TypeError("Unsupported aggregate: {}".format(aggregate)) | python | def _aggregate_func(self, aggregate):
"""
Return a suitable aggregate score function.
"""
funcs = {"sum": add, "min": min, "max": max}
func_name = aggregate.lower() if aggregate else 'sum'
try:
return funcs[func_name]
except KeyError:
raise TypeError("Unsupported aggregate: {}".format(aggregate)) | Return a suitable aggregate score function. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1507-L1516 |
locationlabs/mockredis | mockredis/client.py | MockRedis._apply_to_sets | def _apply_to_sets(self, func, operation, keys, *args):
"""Helper function for sdiff, sinter, and sunion"""
keys = self._list_or_args(keys, args)
if not keys:
raise TypeError("{} takes at least two arguments".format(operation.lower()))
left = self._get_set(keys[0], operation) or set()
for key in keys[1:]:
right = self._get_set(key, operation) or set()
left = func(left, right)
return left | python | def _apply_to_sets(self, func, operation, keys, *args):
"""Helper function for sdiff, sinter, and sunion"""
keys = self._list_or_args(keys, args)
if not keys:
raise TypeError("{} takes at least two arguments".format(operation.lower()))
left = self._get_set(keys[0], operation) or set()
for key in keys[1:]:
right = self._get_set(key, operation) or set()
left = func(left, right)
return left | Helper function for sdiff, sinter, and sunion | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1518-L1527 |
locationlabs/mockredis | mockredis/client.py | MockRedis._list_or_args | def _list_or_args(self, keys, args):
"""
Shamelessly copied from redis-py.
"""
# returns a single list combining keys and args
try:
iter(keys)
# a string can be iterated, but indicates
# keys wasn't passed as a list
if isinstance(keys, basestring):
keys = [keys]
except TypeError:
keys = [keys]
if args:
keys.extend(args)
return keys | python | def _list_or_args(self, keys, args):
"""
Shamelessly copied from redis-py.
"""
# returns a single list combining keys and args
try:
iter(keys)
# a string can be iterated, but indicates
# keys wasn't passed as a list
if isinstance(keys, basestring):
keys = [keys]
except TypeError:
keys = [keys]
if args:
keys.extend(args)
return keys | Shamelessly copied from redis-py. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1529-L1544 |
locationlabs/mockredis | mockredis/client.py | MockRedis._encode | def _encode(self, value):
"Return a bytestring representation of the value. Taken from redis-py connection.py"
if isinstance(value, bytes):
return value
elif isinstance(value, (int, long)):
value = str(value).encode('utf-8')
elif isinstance(value, float):
value = repr(value).encode('utf-8')
elif not isinstance(value, basestring):
value = str(value).encode('utf-8')
else:
value = value.encode('utf-8', 'strict')
return value | python | def _encode(self, value):
"Return a bytestring representation of the value. Taken from redis-py connection.py"
if isinstance(value, bytes):
return value
elif isinstance(value, (int, long)):
value = str(value).encode('utf-8')
elif isinstance(value, float):
value = repr(value).encode('utf-8')
elif not isinstance(value, basestring):
value = str(value).encode('utf-8')
else:
value = value.encode('utf-8', 'strict')
return value | Return a bytestring representation of the value. Taken from redis-py connection.py | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/client.py#L1551-L1563 |
locationlabs/mockredis | mockredis/sortedset.py | SortedSet.insert | def insert(self, member, score):
"""
Identical to __setitem__, but returns whether a member was
inserted (True) or updated (False)
"""
found = self.remove(member)
index = bisect_left(self._scores, (score, member))
self._scores.insert(index, (score, member))
self._members[member] = score
return not found | python | def insert(self, member, score):
"""
Identical to __setitem__, but returns whether a member was
inserted (True) or updated (False)
"""
found = self.remove(member)
index = bisect_left(self._scores, (score, member))
self._scores.insert(index, (score, member))
self._members[member] = score
return not found | Identical to __setitem__, but returns whether a member was
inserted (True) or updated (False) | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/sortedset.py#L78-L87 |
locationlabs/mockredis | mockredis/sortedset.py | SortedSet.remove | def remove(self, member):
"""
Identical to __delitem__, but returns whether a member was removed.
"""
if member not in self:
return False
score = self._members[member]
score_index = bisect_left(self._scores, (score, member))
del self._scores[score_index]
del self._members[member]
return True | python | def remove(self, member):
"""
Identical to __delitem__, but returns whether a member was removed.
"""
if member not in self:
return False
score = self._members[member]
score_index = bisect_left(self._scores, (score, member))
del self._scores[score_index]
del self._members[member]
return True | Identical to __delitem__, but returns whether a member was removed. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/sortedset.py#L89-L99 |
locationlabs/mockredis | mockredis/sortedset.py | SortedSet.rank | def rank(self, member):
"""
Get the rank (index of a member).
"""
score = self._members.get(member)
if score is None:
return None
return bisect_left(self._scores, (score, member)) | python | def rank(self, member):
"""
Get the rank (index of a member).
"""
score = self._members.get(member)
if score is None:
return None
return bisect_left(self._scores, (score, member)) | Get the rank (index of a member). | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/sortedset.py#L108-L115 |
locationlabs/mockredis | mockredis/sortedset.py | SortedSet.range | def range(self, start, end, desc=False):
"""
Return (score, member) pairs between min and max ranks.
"""
if not self:
return []
if desc:
return reversed(self._scores[len(self) - end - 1:len(self) - start])
else:
return self._scores[start:end + 1] | python | def range(self, start, end, desc=False):
"""
Return (score, member) pairs between min and max ranks.
"""
if not self:
return []
if desc:
return reversed(self._scores[len(self) - end - 1:len(self) - start])
else:
return self._scores[start:end + 1] | Return (score, member) pairs between min and max ranks. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/sortedset.py#L117-L127 |
locationlabs/mockredis | mockredis/sortedset.py | SortedSet.scorerange | def scorerange(self, start, end, start_inclusive=True, end_inclusive=True):
"""
Return (score, member) pairs between min and max scores.
"""
if not self:
return []
left = bisect_left(self._scores, (start,))
right = bisect_right(self._scores, (end,))
if end_inclusive:
# end is inclusive
while right < len(self) and self._scores[right][0] == end:
right += 1
if not start_inclusive:
while left < right and self._scores[left][0] == start:
left += 1
return self._scores[left:right] | python | def scorerange(self, start, end, start_inclusive=True, end_inclusive=True):
"""
Return (score, member) pairs between min and max scores.
"""
if not self:
return []
left = bisect_left(self._scores, (start,))
right = bisect_right(self._scores, (end,))
if end_inclusive:
# end is inclusive
while right < len(self) and self._scores[right][0] == end:
right += 1
if not start_inclusive:
while left < right and self._scores[left][0] == start:
left += 1
return self._scores[left:right] | Return (score, member) pairs between min and max scores. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/sortedset.py#L129-L147 |
locationlabs/mockredis | mockredis/pipeline.py | MockRedisPipeline.watch | def watch(self, *keys):
"""
Put the pipeline into immediate execution mode.
Does not actually watch any keys.
"""
if self.explicit_transaction:
raise RedisError("Cannot issue a WATCH after a MULTI")
self.watching = True
for key in keys:
self._watched_keys[key] = deepcopy(self.mock_redis.redis.get(self.mock_redis._encode(key))) | python | def watch(self, *keys):
"""
Put the pipeline into immediate execution mode.
Does not actually watch any keys.
"""
if self.explicit_transaction:
raise RedisError("Cannot issue a WATCH after a MULTI")
self.watching = True
for key in keys:
self._watched_keys[key] = deepcopy(self.mock_redis.redis.get(self.mock_redis._encode(key))) | Put the pipeline into immediate execution mode.
Does not actually watch any keys. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/pipeline.py#L33-L42 |
locationlabs/mockredis | mockredis/pipeline.py | MockRedisPipeline.multi | def multi(self):
"""
Start a transactional block of the pipeline after WATCH commands
are issued. End the transactional block with `execute`.
"""
if self.explicit_transaction:
raise RedisError("Cannot issue nested calls to MULTI")
if self.commands:
raise RedisError("Commands without an initial WATCH have already been issued")
self.explicit_transaction = True | python | def multi(self):
"""
Start a transactional block of the pipeline after WATCH commands
are issued. End the transactional block with `execute`.
"""
if self.explicit_transaction:
raise RedisError("Cannot issue nested calls to MULTI")
if self.commands:
raise RedisError("Commands without an initial WATCH have already been issued")
self.explicit_transaction = True | Start a transactional block of the pipeline after WATCH commands
are issued. End the transactional block with `execute`. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/pipeline.py#L44-L53 |
locationlabs/mockredis | mockredis/pipeline.py | MockRedisPipeline.execute | def execute(self):
"""
Execute all of the saved commands and return results.
"""
try:
for key, value in self._watched_keys.items():
if self.mock_redis.redis.get(self.mock_redis._encode(key)) != value:
raise WatchError("Watched variable changed.")
return [command() for command in self.commands]
finally:
self._reset() | python | def execute(self):
"""
Execute all of the saved commands and return results.
"""
try:
for key, value in self._watched_keys.items():
if self.mock_redis.redis.get(self.mock_redis._encode(key)) != value:
raise WatchError("Watched variable changed.")
return [command() for command in self.commands]
finally:
self._reset() | Execute all of the saved commands and return results. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/pipeline.py#L55-L65 |
locationlabs/mockredis | mockredis/pipeline.py | MockRedisPipeline._reset | def _reset(self):
"""
Reset instance variables.
"""
self.commands = []
self.watching = False
self._watched_keys = {}
self.explicit_transaction = False | python | def _reset(self):
"""
Reset instance variables.
"""
self.commands = []
self.watching = False
self._watched_keys = {}
self.explicit_transaction = False | Reset instance variables. | https://github.com/locationlabs/mockredis/blob/fd4e3117066ff0c24e86ebca007853a8092e3254/mockredis/pipeline.py#L67-L74 |
FraBle/python-duckling | duckling/language.py | Language.convert_to_duckling_language_id | def convert_to_duckling_language_id(cls, lang):
"""Ensure a language identifier has the correct duckling format and is supported."""
if lang is not None and cls.is_supported(lang):
return lang
elif lang is not None and cls.is_supported(lang + "$core"): # Support ISO 639-1 Language Codes (e.g. "en")
return lang + "$core"
else:
raise ValueError("Unsupported language '{}'. Supported languages: {}".format(
lang, ", ".join(cls.SUPPORTED_LANGUAGES))) | python | def convert_to_duckling_language_id(cls, lang):
"""Ensure a language identifier has the correct duckling format and is supported."""
if lang is not None and cls.is_supported(lang):
return lang
elif lang is not None and cls.is_supported(lang + "$core"): # Support ISO 639-1 Language Codes (e.g. "en")
return lang + "$core"
else:
raise ValueError("Unsupported language '{}'. Supported languages: {}".format(
lang, ", ".join(cls.SUPPORTED_LANGUAGES))) | Ensure a language identifier has the correct duckling format and is supported. | https://github.com/FraBle/python-duckling/blob/e6a34192e35fd4fc287b4bc93c938fcd5c2d9024/duckling/language.py#L51-L60 |
FraBle/python-duckling | duckling/duckling.py | Duckling.load | def load(self, languages=[]):
"""Loads the Duckling corpus.
Languages can be specified, defaults to all.
Args:
languages: Optional parameter to specify languages,
e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"])
"""
duckling_load = self.clojure.var("duckling.core", "load!")
clojure_hashmap = self.clojure.var("clojure.core", "hash-map")
clojure_list = self.clojure.var("clojure.core", "list")
if languages:
# Duckling's load function expects ISO 639-1 Language Codes (e.g. "en")
iso_languages = [Language.convert_to_iso(lang) for lang in languages]
duckling_load.invoke(
clojure_hashmap.invoke(
self.clojure.read(':languages'),
clojure_list.invoke(*iso_languages)
)
)
else:
duckling_load.invoke()
self._is_loaded = True | python | def load(self, languages=[]):
"""Loads the Duckling corpus.
Languages can be specified, defaults to all.
Args:
languages: Optional parameter to specify languages,
e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"])
"""
duckling_load = self.clojure.var("duckling.core", "load!")
clojure_hashmap = self.clojure.var("clojure.core", "hash-map")
clojure_list = self.clojure.var("clojure.core", "list")
if languages:
# Duckling's load function expects ISO 639-1 Language Codes (e.g. "en")
iso_languages = [Language.convert_to_iso(lang) for lang in languages]
duckling_load.invoke(
clojure_hashmap.invoke(
self.clojure.read(':languages'),
clojure_list.invoke(*iso_languages)
)
)
else:
duckling_load.invoke()
self._is_loaded = True | Loads the Duckling corpus.
Languages can be specified, defaults to all.
Args:
languages: Optional parameter to specify languages,
e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"]) | https://github.com/FraBle/python-duckling/blob/e6a34192e35fd4fc287b4bc93c938fcd5c2d9024/duckling/duckling.py#L81-L107 |
FraBle/python-duckling | duckling/duckling.py | Duckling.parse | def parse(self, input_str, language=Language.ENGLISH, dim_filter=None, reference_time=''):
"""Parses datetime information out of string input.
It invokes the Duckling.parse() function in Clojure.
A language can be specified, default is English.
Args:
input_str: The input as string that has to be parsed.
language: Optional parameter to specify language,
e.g. Duckling.ENGLISH or supported ISO 639-1 Code (e.g. "en")
dim_filter: Optional parameter to specify a single filter or
list of filters for dimensions in Duckling.
reference_time: Optional reference time for Duckling.
Returns:
A list of dicts with the result from the Duckling.parse() call.
Raises:
RuntimeError: An error occurres when Duckling model is not loaded
via load().
"""
if self._is_loaded is False:
raise RuntimeError(
'Please load the model first by calling load()')
if threading.activeCount() > 1:
if not jpype.isThreadAttachedToJVM():
jpype.attachThreadToJVM()
language = Language.convert_to_duckling_language_id(language)
duckling_parse = self.clojure.var("duckling.core", "parse")
duckling_time = self.clojure.var("duckling.time.obj", "t")
clojure_hashmap = self.clojure.var("clojure.core", "hash-map")
filter_str = '[]'
if isinstance(dim_filter, string_types):
filter_str = '[:{filter}]'.format(filter=dim_filter)
elif isinstance(dim_filter, list):
filter_str = '[{filter}]'.format(filter=' :'.join(dim_filter))
if reference_time:
duckling_result = duckling_parse.invoke(
language,
input_str,
self.clojure.read(filter_str),
clojure_hashmap.invoke(
self.clojure.read(':reference-time'),
duckling_time.invoke(
*self._parse_reference_time(reference_time))
)
)
else:
duckling_result = duckling_parse.invoke(
language, input_str, self.clojure.read(filter_str))
return self._parse_result(duckling_result) | python | def parse(self, input_str, language=Language.ENGLISH, dim_filter=None, reference_time=''):
"""Parses datetime information out of string input.
It invokes the Duckling.parse() function in Clojure.
A language can be specified, default is English.
Args:
input_str: The input as string that has to be parsed.
language: Optional parameter to specify language,
e.g. Duckling.ENGLISH or supported ISO 639-1 Code (e.g. "en")
dim_filter: Optional parameter to specify a single filter or
list of filters for dimensions in Duckling.
reference_time: Optional reference time for Duckling.
Returns:
A list of dicts with the result from the Duckling.parse() call.
Raises:
RuntimeError: An error occurres when Duckling model is not loaded
via load().
"""
if self._is_loaded is False:
raise RuntimeError(
'Please load the model first by calling load()')
if threading.activeCount() > 1:
if not jpype.isThreadAttachedToJVM():
jpype.attachThreadToJVM()
language = Language.convert_to_duckling_language_id(language)
duckling_parse = self.clojure.var("duckling.core", "parse")
duckling_time = self.clojure.var("duckling.time.obj", "t")
clojure_hashmap = self.clojure.var("clojure.core", "hash-map")
filter_str = '[]'
if isinstance(dim_filter, string_types):
filter_str = '[:{filter}]'.format(filter=dim_filter)
elif isinstance(dim_filter, list):
filter_str = '[{filter}]'.format(filter=' :'.join(dim_filter))
if reference_time:
duckling_result = duckling_parse.invoke(
language,
input_str,
self.clojure.read(filter_str),
clojure_hashmap.invoke(
self.clojure.read(':reference-time'),
duckling_time.invoke(
*self._parse_reference_time(reference_time))
)
)
else:
duckling_result = duckling_parse.invoke(
language, input_str, self.clojure.read(filter_str))
return self._parse_result(duckling_result) | Parses datetime information out of string input.
It invokes the Duckling.parse() function in Clojure.
A language can be specified, default is English.
Args:
input_str: The input as string that has to be parsed.
language: Optional parameter to specify language,
e.g. Duckling.ENGLISH or supported ISO 639-1 Code (e.g. "en")
dim_filter: Optional parameter to specify a single filter or
list of filters for dimensions in Duckling.
reference_time: Optional reference time for Duckling.
Returns:
A list of dicts with the result from the Duckling.parse() call.
Raises:
RuntimeError: An error occurres when Duckling model is not loaded
via load(). | https://github.com/FraBle/python-duckling/blob/e6a34192e35fd4fc287b4bc93c938fcd5c2d9024/duckling/duckling.py#L109-L160 |
FraBle/python-duckling | duckling/wrapper.py | DucklingWrapper.parse_time | def parse_time(self, input_str, reference_time=''):
"""Parses input with Duckling for occurences of times.
Args:
input_str: An input string, e.g. 'Let's meet at 11:45am'.
reference_time: Optional reference time for Duckling.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"time",
"end":21,
"start":11,
"value":{
"value":"2016-10-11T11:45:00.000-07:00",
"others":[
"2016-10-11T11:45:00.000-07:00",
"2016-10-12T11:45:00.000-07:00",
"2016-10-13T11:45:00.000-07:00"
]
},
"text":"at 11:45am"
}
]
"""
return self._parse(input_str, dim=Dim.TIME,
reference_time=reference_time) | python | def parse_time(self, input_str, reference_time=''):
"""Parses input with Duckling for occurences of times.
Args:
input_str: An input string, e.g. 'Let's meet at 11:45am'.
reference_time: Optional reference time for Duckling.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"time",
"end":21,
"start":11,
"value":{
"value":"2016-10-11T11:45:00.000-07:00",
"others":[
"2016-10-11T11:45:00.000-07:00",
"2016-10-12T11:45:00.000-07:00",
"2016-10-13T11:45:00.000-07:00"
]
},
"text":"at 11:45am"
}
]
"""
return self._parse(input_str, dim=Dim.TIME,
reference_time=reference_time) | Parses input with Duckling for occurences of times.
Args:
input_str: An input string, e.g. 'Let's meet at 11:45am'.
reference_time: Optional reference time for Duckling.
Returns:
A preprocessed list of results (dicts) from Duckling output. For
example:
[
{
"dim":"time",
"end":21,
"start":11,
"value":{
"value":"2016-10-11T11:45:00.000-07:00",
"others":[
"2016-10-11T11:45:00.000-07:00",
"2016-10-12T11:45:00.000-07:00",
"2016-10-13T11:45:00.000-07:00"
]
},
"text":"at 11:45am"
}
] | https://github.com/FraBle/python-duckling/blob/e6a34192e35fd4fc287b4bc93c938fcd5c2d9024/duckling/wrapper.py#L258-L287 |
horazont/aioxmpp | aioxmpp/adhoc/service.py | AdHocClient.get_commands | def get_commands(self, peer_jid):
"""
Return the list of commands offered by the peer.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:rtype: :class:`list` of :class:`~.disco.xso.Item`
:return: List of command items
In the returned list, each :class:`~.disco.xso.Item` represents one
command supported by the peer. The :attr:`~.disco.xso.Item.node`
attribute is the identifier of the command which can be used with
:meth:`get_command_info` and :meth:`execute`.
"""
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_items(
peer_jid,
node=namespaces.xep0050_commands,
)
return response.items | python | def get_commands(self, peer_jid):
"""
Return the list of commands offered by the peer.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:rtype: :class:`list` of :class:`~.disco.xso.Item`
:return: List of command items
In the returned list, each :class:`~.disco.xso.Item` represents one
command supported by the peer. The :attr:`~.disco.xso.Item.node`
attribute is the identifier of the command which can be used with
:meth:`get_command_info` and :meth:`execute`.
"""
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_items(
peer_jid,
node=namespaces.xep0050_commands,
)
return response.items | Return the list of commands offered by the peer.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:rtype: :class:`list` of :class:`~.disco.xso.Item`
:return: List of command items
In the returned list, each :class:`~.disco.xso.Item` represents one
command supported by the peer. The :attr:`~.disco.xso.Item.node`
attribute is the identifier of the command which can be used with
:meth:`get_command_info` and :meth:`execute`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L72-L92 |
horazont/aioxmpp | aioxmpp/adhoc/service.py | AdHocClient.get_command_info | def get_command_info(self, peer_jid, command_name):
"""
Obtain information about a command.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command
:type command_name: :class:`str`
:rtype: :class:`~.disco.xso.InfoQuery`
:return: Service discovery information about the command
Sends a service discovery query to the service discovery node of the
command. The returned object contains information about the command,
such as the namespaces used by its implementation (generally the
:xep:`4` data forms namespace) and possibly localisations of the
commands name.
The `command_name` can be obtained by inspecting the listing from
:meth:`get_commands` or from well-known command names as defined for
example in :xep:`133`.
"""
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_info(
peer_jid,
node=command_name,
)
return response | python | def get_command_info(self, peer_jid, command_name):
"""
Obtain information about a command.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command
:type command_name: :class:`str`
:rtype: :class:`~.disco.xso.InfoQuery`
:return: Service discovery information about the command
Sends a service discovery query to the service discovery node of the
command. The returned object contains information about the command,
such as the namespaces used by its implementation (generally the
:xep:`4` data forms namespace) and possibly localisations of the
commands name.
The `command_name` can be obtained by inspecting the listing from
:meth:`get_commands` or from well-known command names as defined for
example in :xep:`133`.
"""
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_info(
peer_jid,
node=command_name,
)
return response | Obtain information about a command.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command
:type command_name: :class:`str`
:rtype: :class:`~.disco.xso.InfoQuery`
:return: Service discovery information about the command
Sends a service discovery query to the service discovery node of the
command. The returned object contains information about the command,
such as the namespaces used by its implementation (generally the
:xep:`4` data forms namespace) and possibly localisations of the
commands name.
The `command_name` can be obtained by inspecting the listing from
:meth:`get_commands` or from well-known command names as defined for
example in :xep:`133`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L95-L122 |
horazont/aioxmpp | aioxmpp/adhoc/service.py | AdHocClient.supports_commands | def supports_commands(self, peer_jid):
"""
Detect whether a peer supports :xep:`50` Ad-Hoc commands.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`aioxmpp.JID`
:rtype: :class:`bool`
:return: True if the peer supports the Ad-Hoc commands protocol, false
otherwise.
Note that the fact that a peer supports the protocol does not imply
that it offers any commands.
"""
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_info(
peer_jid,
)
return namespaces.xep0050_commands in response.features | python | def supports_commands(self, peer_jid):
"""
Detect whether a peer supports :xep:`50` Ad-Hoc commands.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`aioxmpp.JID`
:rtype: :class:`bool`
:return: True if the peer supports the Ad-Hoc commands protocol, false
otherwise.
Note that the fact that a peer supports the protocol does not imply
that it offers any commands.
"""
disco = self.dependencies[aioxmpp.disco.DiscoClient]
response = yield from disco.query_info(
peer_jid,
)
return namespaces.xep0050_commands in response.features | Detect whether a peer supports :xep:`50` Ad-Hoc commands.
:param peer_jid: JID of the peer to query
:type peer_jid: :class:`aioxmpp.JID`
:rtype: :class:`bool`
:return: True if the peer supports the Ad-Hoc commands protocol, false
otherwise.
Note that the fact that a peer supports the protocol does not imply
that it offers any commands. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L125-L144 |
horazont/aioxmpp | aioxmpp/adhoc/service.py | AdHocClient.execute | def execute(self, peer_jid, command_name):
"""
Start execution of a command with a peer.
:param peer_jid: JID of the peer to start the command at.
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command to execute.
:type command_name: :class:`str`
:rtype: :class:`~.adhoc.service.ClientSession`
:return: A started command execution session.
Initialises a client session and starts execution of the command. The
session is returned.
This may raise any exception which may be raised by
:meth:`~.adhoc.service.ClientSession.start`.
"""
session = ClientSession(
self.client.stream,
peer_jid,
command_name,
)
yield from session.start()
return session | python | def execute(self, peer_jid, command_name):
"""
Start execution of a command with a peer.
:param peer_jid: JID of the peer to start the command at.
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command to execute.
:type command_name: :class:`str`
:rtype: :class:`~.adhoc.service.ClientSession`
:return: A started command execution session.
Initialises a client session and starts execution of the command. The
session is returned.
This may raise any exception which may be raised by
:meth:`~.adhoc.service.ClientSession.start`.
"""
session = ClientSession(
self.client.stream,
peer_jid,
command_name,
)
yield from session.start()
return session | Start execution of a command with a peer.
:param peer_jid: JID of the peer to start the command at.
:type peer_jid: :class:`~aioxmpp.JID`
:param command_name: Node name of the command to execute.
:type command_name: :class:`str`
:rtype: :class:`~.adhoc.service.ClientSession`
:return: A started command execution session.
Initialises a client session and starts execution of the command. The
session is returned.
This may raise any exception which may be raised by
:meth:`~.adhoc.service.ClientSession.start`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L147-L171 |
horazont/aioxmpp | aioxmpp/adhoc/service.py | AdHocServer.register_stateless_command | def register_stateless_command(self, node, name, handler, *,
is_allowed=None,
features={namespaces.xep0004_data}):
"""
Register a handler for a stateless command.
:param node: Name of the command (``node`` in the service discovery
list).
:type node: :class:`str`
:param name: Human-readable name of the command
:type name: :class:`str` or :class:`~.LanguageMap`
:param handler: Coroutine function to run to get the response for a
request.
:param is_allowed: A predicate which determines whether the command is
shown and allowed for a given peer.
:type is_allowed: function or :data:`None`
:param features: Set of features to announce for the command
:type features: :class:`set` of :class:`str`
When a request for the command is received, `handler` is invoked. The
semantics of `handler` are the same as for
:meth:`~.StanzaStream.register_iq_request_handler`. It must produce a
valid :class:`~.adhoc.xso.Command` response payload.
If `is_allowed` is not :data:`None`, it is invoked whenever a command
listing is generated and whenever a command request is received. The
:class:`aioxmpp.JID` of the requester is passed as positional argument
to `is_allowed`. If `is_allowed` returns false, the command is not
included in the list and attempts to execute it are rejected with
``<forbidden/>`` without calling `handler`.
If `is_allowed` is :data:`None`, the command is always visible and
allowed.
The `features` are returned on a service discovery info request for the
command node. By default, the :xep:`4` (Data Forms) namespace is
included, but this can be overridden by passing a different set without
that feature to `features`.
"""
info = CommandEntry(
name,
handler,
is_allowed=is_allowed,
features=features,
)
self._commands[node] = info
self._disco.mount_node(
node,
info,
) | python | def register_stateless_command(self, node, name, handler, *,
is_allowed=None,
features={namespaces.xep0004_data}):
"""
Register a handler for a stateless command.
:param node: Name of the command (``node`` in the service discovery
list).
:type node: :class:`str`
:param name: Human-readable name of the command
:type name: :class:`str` or :class:`~.LanguageMap`
:param handler: Coroutine function to run to get the response for a
request.
:param is_allowed: A predicate which determines whether the command is
shown and allowed for a given peer.
:type is_allowed: function or :data:`None`
:param features: Set of features to announce for the command
:type features: :class:`set` of :class:`str`
When a request for the command is received, `handler` is invoked. The
semantics of `handler` are the same as for
:meth:`~.StanzaStream.register_iq_request_handler`. It must produce a
valid :class:`~.adhoc.xso.Command` response payload.
If `is_allowed` is not :data:`None`, it is invoked whenever a command
listing is generated and whenever a command request is received. The
:class:`aioxmpp.JID` of the requester is passed as positional argument
to `is_allowed`. If `is_allowed` returns false, the command is not
included in the list and attempts to execute it are rejected with
``<forbidden/>`` without calling `handler`.
If `is_allowed` is :data:`None`, the command is always visible and
allowed.
The `features` are returned on a service discovery info request for the
command node. By default, the :xep:`4` (Data Forms) namespace is
included, but this can be overridden by passing a different set without
that feature to `features`.
"""
info = CommandEntry(
name,
handler,
is_allowed=is_allowed,
features=features,
)
self._commands[node] = info
self._disco.mount_node(
node,
info,
) | Register a handler for a stateless command.
:param node: Name of the command (``node`` in the service discovery
list).
:type node: :class:`str`
:param name: Human-readable name of the command
:type name: :class:`str` or :class:`~.LanguageMap`
:param handler: Coroutine function to run to get the response for a
request.
:param is_allowed: A predicate which determines whether the command is
shown and allowed for a given peer.
:type is_allowed: function or :data:`None`
:param features: Set of features to announce for the command
:type features: :class:`set` of :class:`str`
When a request for the command is received, `handler` is invoked. The
semantics of `handler` are the same as for
:meth:`~.StanzaStream.register_iq_request_handler`. It must produce a
valid :class:`~.adhoc.xso.Command` response payload.
If `is_allowed` is not :data:`None`, it is invoked whenever a command
listing is generated and whenever a command request is received. The
:class:`aioxmpp.JID` of the requester is passed as positional argument
to `is_allowed`. If `is_allowed` returns false, the command is not
included in the list and attempts to execute it are rejected with
``<forbidden/>`` without calling `handler`.
If `is_allowed` is :data:`None`, the command is always visible and
allowed.
The `features` are returned on a service discovery info request for the
command node. By default, the :xep:`4` (Data Forms) namespace is
included, but this can be overridden by passing a different set without
that feature to `features`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L299-L349 |
horazont/aioxmpp | aioxmpp/adhoc/service.py | ClientSession.allowed_actions | def allowed_actions(self):
"""
Shorthand to access :attr:`~.xso.Actions.allowed_actions` of the
:attr:`response`.
If no response has been received yet or if the response specifies no
set of valid actions, this is the minimal set of allowed actions (
:attr:`~.ActionType.EXECUTE` and :attr:`~.ActionType.CANCEL`).
"""
if self._response is not None and self._response.actions is not None:
return self._response.actions.allowed_actions
return {adhoc_xso.ActionType.EXECUTE,
adhoc_xso.ActionType.CANCEL} | python | def allowed_actions(self):
"""
Shorthand to access :attr:`~.xso.Actions.allowed_actions` of the
:attr:`response`.
If no response has been received yet or if the response specifies no
set of valid actions, this is the minimal set of allowed actions (
:attr:`~.ActionType.EXECUTE` and :attr:`~.ActionType.CANCEL`).
"""
if self._response is not None and self._response.actions is not None:
return self._response.actions.allowed_actions
return {adhoc_xso.ActionType.EXECUTE,
adhoc_xso.ActionType.CANCEL} | Shorthand to access :attr:`~.xso.Actions.allowed_actions` of the
:attr:`response`.
If no response has been received yet or if the response specifies no
set of valid actions, this is the minimal set of allowed actions (
:attr:`~.ActionType.EXECUTE` and :attr:`~.ActionType.CANCEL`). | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L464-L477 |
horazont/aioxmpp | aioxmpp/adhoc/service.py | ClientSession.start | def start(self):
"""
Initiate the session by starting to execute the command with the peer.
:return: The :attr:`~.xso.Command.first_payload` of the response
This sends an empty command IQ request with the
:attr:`~.ActionType.EXECUTE` action.
The :attr:`status`, :attr:`response` and related attributes get updated
with the newly received values.
"""
if self._response is not None:
raise RuntimeError("command execution already started")
request = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
to=self._peer_jid,
payload=adhoc_xso.Command(self._command_name),
)
self._response = yield from self._stream.send_iq_and_wait_for_reply(
request,
)
return self._response.first_payload | python | def start(self):
"""
Initiate the session by starting to execute the command with the peer.
:return: The :attr:`~.xso.Command.first_payload` of the response
This sends an empty command IQ request with the
:attr:`~.ActionType.EXECUTE` action.
The :attr:`status`, :attr:`response` and related attributes get updated
with the newly received values.
"""
if self._response is not None:
raise RuntimeError("command execution already started")
request = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
to=self._peer_jid,
payload=adhoc_xso.Command(self._command_name),
)
self._response = yield from self._stream.send_iq_and_wait_for_reply(
request,
)
return self._response.first_payload | Initiate the session by starting to execute the command with the peer.
:return: The :attr:`~.xso.Command.first_payload` of the response
This sends an empty command IQ request with the
:attr:`~.ActionType.EXECUTE` action.
The :attr:`status`, :attr:`response` and related attributes get updated
with the newly received values. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L480-L506 |
horazont/aioxmpp | aioxmpp/adhoc/service.py | ClientSession.proceed | def proceed(self, *,
action=adhoc_xso.ActionType.EXECUTE,
payload=None):
"""
Proceed command execution to the next stage.
:param action: Action type for proceeding
:type action: :class:`~.ActionTyp`
:param payload: Payload for the request, or :data:`None`
:return: The :attr:`~.xso.Command.first_payload` of the response
`action` must be one of the actions returned by
:attr:`allowed_actions`. It defaults to :attr:`~.ActionType.EXECUTE`,
which is (alongside with :attr:`~.ActionType.CANCEL`) always allowed.
`payload` may be a sequence of XSOs, a single XSO or :data:`None`. If
it is :data:`None`, the XSOs from the request are re-used. This is
useful if you modify the payload in-place (e.g. via
:attr:`first_payload`). Otherwise, the payload on the request is set to
the `payload` argument; if it is a single XSO, it is wrapped in a
sequence.
The :attr:`status`, :attr:`response` and related attributes get updated
with the newly received values.
"""
if self._response is None:
raise RuntimeError("command execution not started yet")
if action not in self.allowed_actions:
raise ValueError("action {} not allowed in this stage".format(
action
))
cmd = adhoc_xso.Command(
self._command_name,
action=action,
payload=self._response.payload if payload is None else payload,
sessionid=self.sessionid,
)
request = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
to=self._peer_jid,
payload=cmd,
)
try:
self._response = \
yield from self._stream.send_iq_and_wait_for_reply(
request,
)
except (aioxmpp.errors.XMPPModifyError,
aioxmpp.errors.XMPPCancelError) as exc:
if isinstance(exc.application_defined_condition,
(adhoc_xso.BadSessionID,
adhoc_xso.SessionExpired)):
yield from self.close()
raise SessionError(exc.text)
if isinstance(exc, aioxmpp.errors.XMPPCancelError):
yield from self.close()
raise
return self._response.first_payload | python | def proceed(self, *,
action=adhoc_xso.ActionType.EXECUTE,
payload=None):
"""
Proceed command execution to the next stage.
:param action: Action type for proceeding
:type action: :class:`~.ActionTyp`
:param payload: Payload for the request, or :data:`None`
:return: The :attr:`~.xso.Command.first_payload` of the response
`action` must be one of the actions returned by
:attr:`allowed_actions`. It defaults to :attr:`~.ActionType.EXECUTE`,
which is (alongside with :attr:`~.ActionType.CANCEL`) always allowed.
`payload` may be a sequence of XSOs, a single XSO or :data:`None`. If
it is :data:`None`, the XSOs from the request are re-used. This is
useful if you modify the payload in-place (e.g. via
:attr:`first_payload`). Otherwise, the payload on the request is set to
the `payload` argument; if it is a single XSO, it is wrapped in a
sequence.
The :attr:`status`, :attr:`response` and related attributes get updated
with the newly received values.
"""
if self._response is None:
raise RuntimeError("command execution not started yet")
if action not in self.allowed_actions:
raise ValueError("action {} not allowed in this stage".format(
action
))
cmd = adhoc_xso.Command(
self._command_name,
action=action,
payload=self._response.payload if payload is None else payload,
sessionid=self.sessionid,
)
request = aioxmpp.IQ(
type_=aioxmpp.IQType.SET,
to=self._peer_jid,
payload=cmd,
)
try:
self._response = \
yield from self._stream.send_iq_and_wait_for_reply(
request,
)
except (aioxmpp.errors.XMPPModifyError,
aioxmpp.errors.XMPPCancelError) as exc:
if isinstance(exc.application_defined_condition,
(adhoc_xso.BadSessionID,
adhoc_xso.SessionExpired)):
yield from self.close()
raise SessionError(exc.text)
if isinstance(exc, aioxmpp.errors.XMPPCancelError):
yield from self.close()
raise
return self._response.first_payload | Proceed command execution to the next stage.
:param action: Action type for proceeding
:type action: :class:`~.ActionTyp`
:param payload: Payload for the request, or :data:`None`
:return: The :attr:`~.xso.Command.first_payload` of the response
`action` must be one of the actions returned by
:attr:`allowed_actions`. It defaults to :attr:`~.ActionType.EXECUTE`,
which is (alongside with :attr:`~.ActionType.CANCEL`) always allowed.
`payload` may be a sequence of XSOs, a single XSO or :data:`None`. If
it is :data:`None`, the XSOs from the request are re-used. This is
useful if you modify the payload in-place (e.g. via
:attr:`first_payload`). Otherwise, the payload on the request is set to
the `payload` argument; if it is a single XSO, it is wrapped in a
sequence.
The :attr:`status`, :attr:`response` and related attributes get updated
with the newly received values. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/adhoc/service.py#L509-L572 |
horazont/aioxmpp | aioxmpp/ibb/service.py | IBBTransport.write | def write(self, data):
"""
Send `data` over the IBB. If `data` is larger than the block size
is is chunked and sent in chunks.
Chunks from one call of :meth:`write` will always be sent in
series.
"""
if self.is_closing():
return
self._write_buffer += data
if len(self._write_buffer) >= self._output_buffer_limit_high:
self._protocol.pause_writing()
if self._write_buffer:
self._can_write.set() | python | def write(self, data):
"""
Send `data` over the IBB. If `data` is larger than the block size
is is chunked and sent in chunks.
Chunks from one call of :meth:`write` will always be sent in
series.
"""
if self.is_closing():
return
self._write_buffer += data
if len(self._write_buffer) >= self._output_buffer_limit_high:
self._protocol.pause_writing()
if self._write_buffer:
self._can_write.set() | Send `data` over the IBB. If `data` is larger than the block size
is is chunked and sent in chunks.
Chunks from one call of :meth:`write` will always be sent in
series. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibb/service.py#L232-L250 |
horazont/aioxmpp | aioxmpp/ibb/service.py | IBBTransport.close | def close(self):
"""
Close the session.
"""
if self.is_closing():
return
self._closing = True
# make sure the writer wakes up
self._can_write.set() | python | def close(self):
"""
Close the session.
"""
if self.is_closing():
return
self._closing = True
# make sure the writer wakes up
self._can_write.set() | Close the session. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibb/service.py#L265-L274 |
horazont/aioxmpp | aioxmpp/ibb/service.py | IBBService.expect_session | def expect_session(self, protocol_factory, peer_jid, sid):
"""
Whitelist the session with `peer_jid` and the session id `sid` and
return it when it is established. This is meant to be used
with signalling protocols like Jingle and is the counterpart
to :meth:`open_session`.
:returns: an awaitable object, whose result is the tuple
`(transport, protocol)`
"""
def on_done(fut):
del self._expected_sessions[sid, peer_jid]
_, fut = self._expected_sessions[sid, peer_jid] = (
protocol_factory, asyncio.Future()
)
fut.add_done_callback(on_done)
return fut | python | def expect_session(self, protocol_factory, peer_jid, sid):
"""
Whitelist the session with `peer_jid` and the session id `sid` and
return it when it is established. This is meant to be used
with signalling protocols like Jingle and is the counterpart
to :meth:`open_session`.
:returns: an awaitable object, whose result is the tuple
`(transport, protocol)`
"""
def on_done(fut):
del self._expected_sessions[sid, peer_jid]
_, fut = self._expected_sessions[sid, peer_jid] = (
protocol_factory, asyncio.Future()
)
fut.add_done_callback(on_done)
return fut | Whitelist the session with `peer_jid` and the session id `sid` and
return it when it is established. This is meant to be used
with signalling protocols like Jingle and is the counterpart
to :meth:`open_session`.
:returns: an awaitable object, whose result is the tuple
`(transport, protocol)` | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibb/service.py#L399-L416 |
horazont/aioxmpp | aioxmpp/ibb/service.py | IBBService.open_session | def open_session(self, protocol_factory, peer_jid, *,
stanza_type=ibb_xso.IBBStanzaType.IQ,
block_size=4096, sid=None):
"""
Establish an in-band bytestream session with `peer_jid` and
return the transport and protocol.
:param protocol_factory: the protocol factory
:type protocol_factory: a nullary callable returning an
:class:`asyncio.Protocol` instance
:param peer_jid: the JID with which to establish the byte-stream.
:type peer_jid: :class:`aioxmpp.JID`
:param stanza_type: the stanza type to use
:type stanza_type: class:`~aioxmpp.ibb.IBBStanzaType`
:param block_size: the maximal size of blocks to transfer
:type block_size: :class:`int`
:param sid: the session id to use
:type sid: :class:`str` (must be a valid NMTOKEN)
:returns: the transport and protocol
:rtype: a tuple of :class:`aioxmpp.ibb.service.IBBTransport`
and :class:`asyncio.Protocol`
"""
if block_size > MAX_BLOCK_SIZE:
raise ValueError("block_size too large")
if sid is None:
sid = utils.to_nmtoken(random.getrandbits(8*8))
open_ = ibb_xso.Open()
open_.stanza = stanza_type
open_.sid = sid
open_.block_size = block_size
# XXX: retry on XMPPModifyError with RESOURCE_CONSTRAINT
yield from self.client.send(
aioxmpp.IQ(
aioxmpp.IQType.SET,
to=peer_jid,
payload=open_,
)
)
handle = self._sessions[sid, peer_jid] = IBBTransport(
self,
peer_jid,
sid,
stanza_type,
block_size,
)
protocol = protocol_factory()
handle.set_protocol(protocol)
return handle, protocol | python | def open_session(self, protocol_factory, peer_jid, *,
stanza_type=ibb_xso.IBBStanzaType.IQ,
block_size=4096, sid=None):
"""
Establish an in-band bytestream session with `peer_jid` and
return the transport and protocol.
:param protocol_factory: the protocol factory
:type protocol_factory: a nullary callable returning an
:class:`asyncio.Protocol` instance
:param peer_jid: the JID with which to establish the byte-stream.
:type peer_jid: :class:`aioxmpp.JID`
:param stanza_type: the stanza type to use
:type stanza_type: class:`~aioxmpp.ibb.IBBStanzaType`
:param block_size: the maximal size of blocks to transfer
:type block_size: :class:`int`
:param sid: the session id to use
:type sid: :class:`str` (must be a valid NMTOKEN)
:returns: the transport and protocol
:rtype: a tuple of :class:`aioxmpp.ibb.service.IBBTransport`
and :class:`asyncio.Protocol`
"""
if block_size > MAX_BLOCK_SIZE:
raise ValueError("block_size too large")
if sid is None:
sid = utils.to_nmtoken(random.getrandbits(8*8))
open_ = ibb_xso.Open()
open_.stanza = stanza_type
open_.sid = sid
open_.block_size = block_size
# XXX: retry on XMPPModifyError with RESOURCE_CONSTRAINT
yield from self.client.send(
aioxmpp.IQ(
aioxmpp.IQType.SET,
to=peer_jid,
payload=open_,
)
)
handle = self._sessions[sid, peer_jid] = IBBTransport(
self,
peer_jid,
sid,
stanza_type,
block_size,
)
protocol = protocol_factory()
handle.set_protocol(protocol)
return handle, protocol | Establish an in-band bytestream session with `peer_jid` and
return the transport and protocol.
:param protocol_factory: the protocol factory
:type protocol_factory: a nullary callable returning an
:class:`asyncio.Protocol` instance
:param peer_jid: the JID with which to establish the byte-stream.
:type peer_jid: :class:`aioxmpp.JID`
:param stanza_type: the stanza type to use
:type stanza_type: class:`~aioxmpp.ibb.IBBStanzaType`
:param block_size: the maximal size of blocks to transfer
:type block_size: :class:`int`
:param sid: the session id to use
:type sid: :class:`str` (must be a valid NMTOKEN)
:returns: the transport and protocol
:rtype: a tuple of :class:`aioxmpp.ibb.service.IBBTransport`
and :class:`asyncio.Protocol` | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/ibb/service.py#L419-L471 |
horazont/aioxmpp | docs/sphinx-data/extensions/aioxmppspecific.py | xep_role | def xep_role(typ, rawtext, text, lineno, inliner,
options={}, content=[]):
"""Role for PEP/RFC references that generate an index entry."""
env = inliner.document.settings.env
if not typ:
typ = env.config.default_role
else:
typ = typ.lower()
has_explicit_title, title, target = split_explicit_title(text)
title = utils.unescape(title)
target = utils.unescape(target)
targetid = 'index-%s' % env.new_serialno('index')
anchor = ''
anchorindex = target.find('#')
if anchorindex > 0:
target, anchor = target[:anchorindex], target[anchorindex:]
try:
xepnum = int(target)
except ValueError:
msg = inliner.reporter.error('invalid XEP number %s' % target,
line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
target = "{:04d}".format(xepnum)
if not has_explicit_title:
title = "XEP-" + target
indexnode = addnodes.index()
targetnode = nodes.target('', '', ids=[targetid])
inliner.document.note_explicit_target(targetnode)
indexnode['entries'] = [
('single', _('XMPP Extension Protocols (XEPs); XEP %s') % target,
targetid, '')]
ref = inliner.document.settings.xep_base_url + 'xep-%04d.html' % xepnum
rn = nodes.reference(title, title, internal=False, refuri=ref+anchor,
classes=[typ])
return [indexnode, targetnode, rn], [] | python | def xep_role(typ, rawtext, text, lineno, inliner,
options={}, content=[]):
"""Role for PEP/RFC references that generate an index entry."""
env = inliner.document.settings.env
if not typ:
typ = env.config.default_role
else:
typ = typ.lower()
has_explicit_title, title, target = split_explicit_title(text)
title = utils.unescape(title)
target = utils.unescape(target)
targetid = 'index-%s' % env.new_serialno('index')
anchor = ''
anchorindex = target.find('#')
if anchorindex > 0:
target, anchor = target[:anchorindex], target[anchorindex:]
try:
xepnum = int(target)
except ValueError:
msg = inliner.reporter.error('invalid XEP number %s' % target,
line=lineno)
prb = inliner.problematic(rawtext, rawtext, msg)
return [prb], [msg]
target = "{:04d}".format(xepnum)
if not has_explicit_title:
title = "XEP-" + target
indexnode = addnodes.index()
targetnode = nodes.target('', '', ids=[targetid])
inliner.document.note_explicit_target(targetnode)
indexnode['entries'] = [
('single', _('XMPP Extension Protocols (XEPs); XEP %s') % target,
targetid, '')]
ref = inliner.document.settings.xep_base_url + 'xep-%04d.html' % xepnum
rn = nodes.reference(title, title, internal=False, refuri=ref+anchor,
classes=[typ])
return [indexnode, targetnode, rn], [] | Role for PEP/RFC references that generate an index entry. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/docs/sphinx-data/extensions/aioxmppspecific.py#L136-L171 |
horazont/aioxmpp | aioxmpp/xso/types.py | EnumType | def EnumType(enum_class, nested_type=_Undefined, **kwargs):
"""
Create and return a :class:`EnumCDataType` or :class:`EnumElementType`,
depending on the type of `nested_type`.
If `nested_type` is a :class:`AbstractCDataType` or omitted, a
:class:`EnumCDataType` is constructed. Otherwise, :class:`EnumElementType`
is used.
The arguments are forwarded to the respective class’ constructor.
.. versionadded:: 0.10
.. deprecated:: 0.10
This function was introduced to ease the transition in 0.10 from
a unified :class:`EnumType` to split :class:`EnumCDataType` and
:class:`EnumElementType`.
It will be removed in 1.0.
"""
if nested_type is _Undefined:
return EnumCDataType(enum_class, **kwargs)
if isinstance(nested_type, AbstractCDataType):
return EnumCDataType(enum_class, nested_type, **kwargs)
else:
return EnumElementType(enum_class, nested_type, **kwargs) | python | def EnumType(enum_class, nested_type=_Undefined, **kwargs):
"""
Create and return a :class:`EnumCDataType` or :class:`EnumElementType`,
depending on the type of `nested_type`.
If `nested_type` is a :class:`AbstractCDataType` or omitted, a
:class:`EnumCDataType` is constructed. Otherwise, :class:`EnumElementType`
is used.
The arguments are forwarded to the respective class’ constructor.
.. versionadded:: 0.10
.. deprecated:: 0.10
This function was introduced to ease the transition in 0.10 from
a unified :class:`EnumType` to split :class:`EnumCDataType` and
:class:`EnumElementType`.
It will be removed in 1.0.
"""
if nested_type is _Undefined:
return EnumCDataType(enum_class, **kwargs)
if isinstance(nested_type, AbstractCDataType):
return EnumCDataType(enum_class, nested_type, **kwargs)
else:
return EnumElementType(enum_class, nested_type, **kwargs) | Create and return a :class:`EnumCDataType` or :class:`EnumElementType`,
depending on the type of `nested_type`.
If `nested_type` is a :class:`AbstractCDataType` or omitted, a
:class:`EnumCDataType` is constructed. Otherwise, :class:`EnumElementType`
is used.
The arguments are forwarded to the respective class’ constructor.
.. versionadded:: 0.10
.. deprecated:: 0.10
This function was introduced to ease the transition in 0.10 from
a unified :class:`EnumType` to split :class:`EnumCDataType` and
:class:`EnumElementType`.
It will be removed in 1.0. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/xso/types.py#L1169-L1196 |
horazont/aioxmpp | aioxmpp/muc/service.py | _extract_one_pair | def _extract_one_pair(body):
"""
Extract one language-text pair from a :class:`~.LanguageMap`.
This is used for tracking.
"""
if not body:
return None, None
try:
return None, body[None]
except KeyError:
return min(body.items(), key=lambda x: x[0]) | python | def _extract_one_pair(body):
"""
Extract one language-text pair from a :class:`~.LanguageMap`.
This is used for tracking.
"""
if not body:
return None, None
try:
return None, body[None]
except KeyError:
return min(body.items(), key=lambda x: x[0]) | Extract one language-text pair from a :class:`~.LanguageMap`.
This is used for tracking. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L48-L60 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.members | def members(self):
"""
A copy of the list of occupants. The local user is always the first
item in the list, unless the :meth:`on_enter` has not fired yet.
"""
if self._this_occupant is not None:
items = [self._this_occupant]
else:
items = []
items += list(self._occupant_info.values())
return items | python | def members(self):
"""
A copy of the list of occupants. The local user is always the first
item in the list, unless the :meth:`on_enter` has not fired yet.
"""
if self._this_occupant is not None:
items = [self._this_occupant]
else:
items = []
items += list(self._occupant_info.values())
return items | A copy of the list of occupants. The local user is always the first
item in the list, unless the :meth:`on_enter` has not fired yet. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L986-L997 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.features | def features(self):
"""
The set of features supported by this MUC. This may vary depending on
features exported by the MUC service, so be sure to check this for each
individual MUC.
"""
return {
aioxmpp.im.conversation.ConversationFeature.BAN,
aioxmpp.im.conversation.ConversationFeature.BAN_WITH_KICK,
aioxmpp.im.conversation.ConversationFeature.KICK,
aioxmpp.im.conversation.ConversationFeature.SEND_MESSAGE,
aioxmpp.im.conversation.ConversationFeature.SEND_MESSAGE_TRACKED,
aioxmpp.im.conversation.ConversationFeature.SET_TOPIC,
aioxmpp.im.conversation.ConversationFeature.SET_NICK,
aioxmpp.im.conversation.ConversationFeature.INVITE,
aioxmpp.im.conversation.ConversationFeature.INVITE_DIRECT,
} | python | def features(self):
"""
The set of features supported by this MUC. This may vary depending on
features exported by the MUC service, so be sure to check this for each
individual MUC.
"""
return {
aioxmpp.im.conversation.ConversationFeature.BAN,
aioxmpp.im.conversation.ConversationFeature.BAN_WITH_KICK,
aioxmpp.im.conversation.ConversationFeature.KICK,
aioxmpp.im.conversation.ConversationFeature.SEND_MESSAGE,
aioxmpp.im.conversation.ConversationFeature.SEND_MESSAGE_TRACKED,
aioxmpp.im.conversation.ConversationFeature.SET_TOPIC,
aioxmpp.im.conversation.ConversationFeature.SET_NICK,
aioxmpp.im.conversation.ConversationFeature.INVITE,
aioxmpp.im.conversation.ConversationFeature.INVITE_DIRECT,
} | The set of features supported by this MUC. This may vary depending on
features exported by the MUC service, so be sure to check this for each
individual MUC. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1018-L1035 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.send_message | def send_message(self, msg):
"""
Send a message to the MUC.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
:return: The stanza token of the message.
:rtype: :class:`~aioxmpp.stream.StanzaToken`
There is no need to set the address attributes or the type of the
message correctly; those will be overridden by this method to conform
to the requirements of a message to the MUC. Other attributes are left
untouched (except that :meth:`~.StanzaBase.autoset_id` is called) and
can be used as desired for the message.
.. seealso::
:meth:`.AbstractConversation.send_message` for the full interface
specification.
"""
msg.type_ = aioxmpp.MessageType.GROUPCHAT
msg.to = self._mucjid
# see https://mail.jabber.org/pipermail/standards/2017-January/032048.html # NOQA
# for a full discussion on the rationale for this.
# TL;DR: we want to help entities to discover that a message is related
# to a MUC.
msg.xep0045_muc_user = muc_xso.UserExt()
result = self.service.client.enqueue(msg)
return result | python | def send_message(self, msg):
"""
Send a message to the MUC.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
:return: The stanza token of the message.
:rtype: :class:`~aioxmpp.stream.StanzaToken`
There is no need to set the address attributes or the type of the
message correctly; those will be overridden by this method to conform
to the requirements of a message to the MUC. Other attributes are left
untouched (except that :meth:`~.StanzaBase.autoset_id` is called) and
can be used as desired for the message.
.. seealso::
:meth:`.AbstractConversation.send_message` for the full interface
specification.
"""
msg.type_ = aioxmpp.MessageType.GROUPCHAT
msg.to = self._mucjid
# see https://mail.jabber.org/pipermail/standards/2017-January/032048.html # NOQA
# for a full discussion on the rationale for this.
# TL;DR: we want to help entities to discover that a message is related
# to a MUC.
msg.xep0045_muc_user = muc_xso.UserExt()
result = self.service.client.enqueue(msg)
return result | Send a message to the MUC.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
:return: The stanza token of the message.
:rtype: :class:`~aioxmpp.stream.StanzaToken`
There is no need to set the address attributes or the type of the
message correctly; those will be overridden by this method to conform
to the requirements of a message to the MUC. Other attributes are left
untouched (except that :meth:`~.StanzaBase.autoset_id` is called) and
can be used as desired for the message.
.. seealso::
:meth:`.AbstractConversation.send_message` for the full interface
specification. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1470-L1498 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.send_message_tracked | def send_message_tracked(self, msg):
"""
Send a message to the MUC with tracking.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
.. warning::
Please read :ref:`api-tracking-memory`. This is especially relevant
for MUCs because tracking is not guaranteed to work due to how
:xep:`45` is written. It will work in many cases, probably in all
cases you test during development, but it may fail to work for some
individual messages and it may fail to work consistently for some
services. See the implementation details below for reasons.
The message is tracked and is considered
:attr:`~.MessageState.DELIVERED_TO_RECIPIENT` when it is reflected back
to us by the MUC service. The reflected message is then available in
the :attr:`~.MessageTracker.response` attribute.
.. note::
Two things:
1. The MUC service may change the contents of the message. An
example of this is the Prosody developer MUC which replaces
messages with more than a few lines with a pastebin link.
2. Reflected messages which are caught by tracking are not emitted
through :meth:`on_message`.
There is no need to set the address attributes or the type of the
message correctly; those will be overridden by this method to conform
to the requirements of a message to the MUC. Other attributes are left
untouched (except that :meth:`~.StanzaBase.autoset_id` is called) and
can be used as desired for the message.
.. warning::
Using :meth:`send_message_tracked` before :meth:`on_join` has
emitted will cause the `member` object in the resulting
:meth:`on_message` event to be :data:`None` (the message will be
delivered just fine).
Using :meth:`send_message_tracked` before history replay is over
will cause the :meth:`on_message` event to be emitted during
history replay, even though everyone else in the MUC will -- of
course -- only see the message after the history.
:meth:`send_message` is not affected by these quirks.
.. seealso::
:meth:`.AbstractConversation.send_message_tracked` for the full
interface specification.
**Implementation details:** Currently, we try to detect reflected
messages using two different criteria. First, if we see a message with
the same message ID (note that message IDs contain 120 bits of entropy)
as the message we sent, we consider it as the reflection. As some MUC
services re-write the message ID in the reflection, as a fallback, we
also consider messages which originate from the correct sender and have
the correct body a reflection.
Obviously, this fails consistently in MUCs which re-write the body and
re-write the ID and randomly if the MUC always re-writes the ID but
only sometimes the body.
"""
msg.type_ = aioxmpp.MessageType.GROUPCHAT
msg.to = self._mucjid
# see https://mail.jabber.org/pipermail/standards/2017-January/032048.html # NOQA
# for a full discussion on the rationale for this.
# TL;DR: we want to help entities to discover that a message is related
# to a MUC.
msg.xep0045_muc_user = muc_xso.UserExt()
msg.autoset_id()
tracking_svc = self.service.dependencies[
aioxmpp.tracking.BasicTrackingService
]
tracker = aioxmpp.tracking.MessageTracker()
id_key = msg.id_
body_key = _extract_one_pair(msg.body)
self._tracking_by_id[id_key] = tracker
self._tracking_metadata[tracker] = (
id_key,
body_key,
)
self._tracking_by_body.setdefault(
body_key,
[]
).append(tracker)
tracker.on_closed.connect(functools.partial(
self._tracker_closed,
tracker,
))
token = tracking_svc.send_tracked(msg, tracker)
self.on_message(
msg,
self._this_occupant,
aioxmpp.im.dispatcher.MessageSource.STREAM,
tracker=tracker,
)
return token, tracker | python | def send_message_tracked(self, msg):
"""
Send a message to the MUC with tracking.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
.. warning::
Please read :ref:`api-tracking-memory`. This is especially relevant
for MUCs because tracking is not guaranteed to work due to how
:xep:`45` is written. It will work in many cases, probably in all
cases you test during development, but it may fail to work for some
individual messages and it may fail to work consistently for some
services. See the implementation details below for reasons.
The message is tracked and is considered
:attr:`~.MessageState.DELIVERED_TO_RECIPIENT` when it is reflected back
to us by the MUC service. The reflected message is then available in
the :attr:`~.MessageTracker.response` attribute.
.. note::
Two things:
1. The MUC service may change the contents of the message. An
example of this is the Prosody developer MUC which replaces
messages with more than a few lines with a pastebin link.
2. Reflected messages which are caught by tracking are not emitted
through :meth:`on_message`.
There is no need to set the address attributes or the type of the
message correctly; those will be overridden by this method to conform
to the requirements of a message to the MUC. Other attributes are left
untouched (except that :meth:`~.StanzaBase.autoset_id` is called) and
can be used as desired for the message.
.. warning::
Using :meth:`send_message_tracked` before :meth:`on_join` has
emitted will cause the `member` object in the resulting
:meth:`on_message` event to be :data:`None` (the message will be
delivered just fine).
Using :meth:`send_message_tracked` before history replay is over
will cause the :meth:`on_message` event to be emitted during
history replay, even though everyone else in the MUC will -- of
course -- only see the message after the history.
:meth:`send_message` is not affected by these quirks.
.. seealso::
:meth:`.AbstractConversation.send_message_tracked` for the full
interface specification.
**Implementation details:** Currently, we try to detect reflected
messages using two different criteria. First, if we see a message with
the same message ID (note that message IDs contain 120 bits of entropy)
as the message we sent, we consider it as the reflection. As some MUC
services re-write the message ID in the reflection, as a fallback, we
also consider messages which originate from the correct sender and have
the correct body a reflection.
Obviously, this fails consistently in MUCs which re-write the body and
re-write the ID and randomly if the MUC always re-writes the ID but
only sometimes the body.
"""
msg.type_ = aioxmpp.MessageType.GROUPCHAT
msg.to = self._mucjid
# see https://mail.jabber.org/pipermail/standards/2017-January/032048.html # NOQA
# for a full discussion on the rationale for this.
# TL;DR: we want to help entities to discover that a message is related
# to a MUC.
msg.xep0045_muc_user = muc_xso.UserExt()
msg.autoset_id()
tracking_svc = self.service.dependencies[
aioxmpp.tracking.BasicTrackingService
]
tracker = aioxmpp.tracking.MessageTracker()
id_key = msg.id_
body_key = _extract_one_pair(msg.body)
self._tracking_by_id[id_key] = tracker
self._tracking_metadata[tracker] = (
id_key,
body_key,
)
self._tracking_by_body.setdefault(
body_key,
[]
).append(tracker)
tracker.on_closed.connect(functools.partial(
self._tracker_closed,
tracker,
))
token = tracking_svc.send_tracked(msg, tracker)
self.on_message(
msg,
self._this_occupant,
aioxmpp.im.dispatcher.MessageSource.STREAM,
tracker=tracker,
)
return token, tracker | Send a message to the MUC with tracking.
:param msg: The message to send.
:type msg: :class:`aioxmpp.Message`
.. warning::
Please read :ref:`api-tracking-memory`. This is especially relevant
for MUCs because tracking is not guaranteed to work due to how
:xep:`45` is written. It will work in many cases, probably in all
cases you test during development, but it may fail to work for some
individual messages and it may fail to work consistently for some
services. See the implementation details below for reasons.
The message is tracked and is considered
:attr:`~.MessageState.DELIVERED_TO_RECIPIENT` when it is reflected back
to us by the MUC service. The reflected message is then available in
the :attr:`~.MessageTracker.response` attribute.
.. note::
Two things:
1. The MUC service may change the contents of the message. An
example of this is the Prosody developer MUC which replaces
messages with more than a few lines with a pastebin link.
2. Reflected messages which are caught by tracking are not emitted
through :meth:`on_message`.
There is no need to set the address attributes or the type of the
message correctly; those will be overridden by this method to conform
to the requirements of a message to the MUC. Other attributes are left
untouched (except that :meth:`~.StanzaBase.autoset_id` is called) and
can be used as desired for the message.
.. warning::
Using :meth:`send_message_tracked` before :meth:`on_join` has
emitted will cause the `member` object in the resulting
:meth:`on_message` event to be :data:`None` (the message will be
delivered just fine).
Using :meth:`send_message_tracked` before history replay is over
will cause the :meth:`on_message` event to be emitted during
history replay, even though everyone else in the MUC will -- of
course -- only see the message after the history.
:meth:`send_message` is not affected by these quirks.
.. seealso::
:meth:`.AbstractConversation.send_message_tracked` for the full
interface specification.
**Implementation details:** Currently, we try to detect reflected
messages using two different criteria. First, if we see a message with
the same message ID (note that message IDs contain 120 bits of entropy)
as the message we sent, we consider it as the reflection. As some MUC
services re-write the message ID in the reflection, as a fallback, we
also consider messages which originate from the correct sender and have
the correct body a reflection.
Obviously, this fails consistently in MUCs which re-write the body and
re-write the ID and randomly if the MUC always re-writes the ID but
only sometimes the body. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1508-L1610 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.set_nick | def set_nick(self, new_nick):
"""
Change the nick name of the occupant.
:param new_nick: New nickname to use
:type new_nick: :class:`str`
This sends the request to change the nickname and waits for the request
to be sent over the stream.
The nick change may or may not happen, or the service may modify the
nickname; observe the :meth:`on_nick_change` event.
.. seealso::
:meth:`.AbstractConversation.set_nick` for the full interface
specification.
"""
stanza = aioxmpp.Presence(
type_=aioxmpp.PresenceType.AVAILABLE,
to=self._mucjid.replace(resource=new_nick),
)
yield from self._service.client.send(
stanza
) | python | def set_nick(self, new_nick):
"""
Change the nick name of the occupant.
:param new_nick: New nickname to use
:type new_nick: :class:`str`
This sends the request to change the nickname and waits for the request
to be sent over the stream.
The nick change may or may not happen, or the service may modify the
nickname; observe the :meth:`on_nick_change` event.
.. seealso::
:meth:`.AbstractConversation.set_nick` for the full interface
specification.
"""
stanza = aioxmpp.Presence(
type_=aioxmpp.PresenceType.AVAILABLE,
to=self._mucjid.replace(resource=new_nick),
)
yield from self._service.client.send(
stanza
) | Change the nick name of the occupant.
:param new_nick: New nickname to use
:type new_nick: :class:`str`
This sends the request to change the nickname and waits for the request
to be sent over the stream.
The nick change may or may not happen, or the service may modify the
nickname; observe the :meth:`on_nick_change` event.
.. seealso::
:meth:`.AbstractConversation.set_nick` for the full interface
specification. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1613-L1638 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.kick | def kick(self, member, reason=None):
"""
Kick an occupant from the MUC.
:param member: The member to kick.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the kicked member.
:type reason: :class:`str`
:raises aioxmpp.errors.XMPPError: if the server returned an error for
the kick command.
.. seealso::
:meth:`.AbstractConversation.kick` for the full interface
specification.
"""
yield from self.muc_set_role(
member.nick,
"none",
reason=reason
) | python | def kick(self, member, reason=None):
"""
Kick an occupant from the MUC.
:param member: The member to kick.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the kicked member.
:type reason: :class:`str`
:raises aioxmpp.errors.XMPPError: if the server returned an error for
the kick command.
.. seealso::
:meth:`.AbstractConversation.kick` for the full interface
specification.
"""
yield from self.muc_set_role(
member.nick,
"none",
reason=reason
) | Kick an occupant from the MUC.
:param member: The member to kick.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the kicked member.
:type reason: :class:`str`
:raises aioxmpp.errors.XMPPError: if the server returned an error for
the kick command.
.. seealso::
:meth:`.AbstractConversation.kick` for the full interface
specification. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1641-L1662 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.muc_set_role | def muc_set_role(self, nick, role, *, reason=None):
"""
Change the role of an occupant.
:param nick: The nickname of the occupant whose role shall be changed.
:type nick: :class:`str`
:param role: The new role for the occupant.
:type role: :class:`str`
:param reason: An optional reason to show to the occupant (and all
others).
Change the role of an occupant, identified by their `nick`, to the
given new `role`. Optionally, a `reason` for the role change can be
provided.
Setting the different roles require different privilegues of the local
user. The details can be checked in :xep:`0045` and are enforced solely
by the server, not local code.
The coroutine returns when the role change has been acknowledged by the
server. If the server returns an error, an appropriate
:class:`aioxmpp.errors.XMPPError` subclass is raised.
"""
if nick is None:
raise ValueError("nick must not be None")
if role is None:
raise ValueError("role must not be None")
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=self._mucjid
)
iq.payload = muc_xso.AdminQuery(
items=[
muc_xso.AdminItem(nick=nick,
reason=reason,
role=role)
]
)
yield from self.service.client.send(iq) | python | def muc_set_role(self, nick, role, *, reason=None):
"""
Change the role of an occupant.
:param nick: The nickname of the occupant whose role shall be changed.
:type nick: :class:`str`
:param role: The new role for the occupant.
:type role: :class:`str`
:param reason: An optional reason to show to the occupant (and all
others).
Change the role of an occupant, identified by their `nick`, to the
given new `role`. Optionally, a `reason` for the role change can be
provided.
Setting the different roles require different privilegues of the local
user. The details can be checked in :xep:`0045` and are enforced solely
by the server, not local code.
The coroutine returns when the role change has been acknowledged by the
server. If the server returns an error, an appropriate
:class:`aioxmpp.errors.XMPPError` subclass is raised.
"""
if nick is None:
raise ValueError("nick must not be None")
if role is None:
raise ValueError("role must not be None")
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=self._mucjid
)
iq.payload = muc_xso.AdminQuery(
items=[
muc_xso.AdminItem(nick=nick,
reason=reason,
role=role)
]
)
yield from self.service.client.send(iq) | Change the role of an occupant.
:param nick: The nickname of the occupant whose role shall be changed.
:type nick: :class:`str`
:param role: The new role for the occupant.
:type role: :class:`str`
:param reason: An optional reason to show to the occupant (and all
others).
Change the role of an occupant, identified by their `nick`, to the
given new `role`. Optionally, a `reason` for the role change can be
provided.
Setting the different roles require different privilegues of the local
user. The details can be checked in :xep:`0045` and are enforced solely
by the server, not local code.
The coroutine returns when the role change has been acknowledged by the
server. If the server returns an error, an appropriate
:class:`aioxmpp.errors.XMPPError` subclass is raised. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1665-L1708 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.ban | def ban(self, member, reason=None, *, request_kick=True):
"""
Ban an occupant from re-joining the MUC.
:param member: The occupant to ban.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the banned member.
:type reason: :class:`str`
:param request_kick: A flag indicating that the member should be
removed from the conversation immediately, too.
:type request_kick: :class:`bool`
`request_kick` is supported by MUC, but setting it to false has no
effect: banned members are always immediately kicked.
.. seealso::
:meth:`.AbstractConversation.ban` for the full interface
specification.
"""
if member.direct_jid is None:
raise ValueError(
"cannot ban members whose direct JID is not "
"known")
yield from self.muc_set_affiliation(
member.direct_jid,
"outcast",
reason=reason
) | python | def ban(self, member, reason=None, *, request_kick=True):
"""
Ban an occupant from re-joining the MUC.
:param member: The occupant to ban.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the banned member.
:type reason: :class:`str`
:param request_kick: A flag indicating that the member should be
removed from the conversation immediately, too.
:type request_kick: :class:`bool`
`request_kick` is supported by MUC, but setting it to false has no
effect: banned members are always immediately kicked.
.. seealso::
:meth:`.AbstractConversation.ban` for the full interface
specification.
"""
if member.direct_jid is None:
raise ValueError(
"cannot ban members whose direct JID is not "
"known")
yield from self.muc_set_affiliation(
member.direct_jid,
"outcast",
reason=reason
) | Ban an occupant from re-joining the MUC.
:param member: The occupant to ban.
:type member: :class:`Occupant`
:param reason: A reason to show to the members of the conversation
including the banned member.
:type reason: :class:`str`
:param request_kick: A flag indicating that the member should be
removed from the conversation immediately, too.
:type request_kick: :class:`bool`
`request_kick` is supported by MUC, but setting it to false has no
effect: banned members are always immediately kicked.
.. seealso::
:meth:`.AbstractConversation.ban` for the full interface
specification. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1711-L1741 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.muc_set_affiliation | def muc_set_affiliation(self, jid, affiliation, *, reason=None):
"""
Convenience wrapper around :meth:`.MUCClient.set_affiliation`. See
there for details, and consider its `mucjid` argument to be set to
:attr:`mucjid`.
"""
return (yield from self.service.set_affiliation(
self._mucjid,
jid, affiliation,
reason=reason)) | python | def muc_set_affiliation(self, jid, affiliation, *, reason=None):
"""
Convenience wrapper around :meth:`.MUCClient.set_affiliation`. See
there for details, and consider its `mucjid` argument to be set to
:attr:`mucjid`.
"""
return (yield from self.service.set_affiliation(
self._mucjid,
jid, affiliation,
reason=reason)) | Convenience wrapper around :meth:`.MUCClient.set_affiliation`. See
there for details, and consider its `mucjid` argument to be set to
:attr:`mucjid`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1744-L1753 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.set_topic | def set_topic(self, new_topic):
"""
Change the (possibly publicly) visible topic of the conversation.
:param new_topic: The new topic for the conversation.
:type new_topic: :class:`str`
Request to set the subject to `new_topic`. `new_topic` must be a
mapping which maps :class:`~.structs.LanguageTag` tags to strings;
:data:`None` is a valid key.
"""
msg = aioxmpp.stanza.Message(
type_=aioxmpp.structs.MessageType.GROUPCHAT,
to=self._mucjid
)
msg.subject.update(new_topic)
yield from self.service.client.send(msg) | python | def set_topic(self, new_topic):
"""
Change the (possibly publicly) visible topic of the conversation.
:param new_topic: The new topic for the conversation.
:type new_topic: :class:`str`
Request to set the subject to `new_topic`. `new_topic` must be a
mapping which maps :class:`~.structs.LanguageTag` tags to strings;
:data:`None` is a valid key.
"""
msg = aioxmpp.stanza.Message(
type_=aioxmpp.structs.MessageType.GROUPCHAT,
to=self._mucjid
)
msg.subject.update(new_topic)
yield from self.service.client.send(msg) | Change the (possibly publicly) visible topic of the conversation.
:param new_topic: The new topic for the conversation.
:type new_topic: :class:`str`
Request to set the subject to `new_topic`. `new_topic` must be a
mapping which maps :class:`~.structs.LanguageTag` tags to strings;
:data:`None` is a valid key. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1756-L1774 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.leave | def leave(self):
"""
Leave the MUC.
"""
fut = self.on_exit.future()
def cb(**kwargs):
fut.set_result(None)
return True # disconnect
self.on_exit.connect(cb)
presence = aioxmpp.stanza.Presence(
type_=aioxmpp.structs.PresenceType.UNAVAILABLE,
to=self._mucjid
)
yield from self.service.client.send(presence)
yield from fut | python | def leave(self):
"""
Leave the MUC.
"""
fut = self.on_exit.future()
def cb(**kwargs):
fut.set_result(None)
return True # disconnect
self.on_exit.connect(cb)
presence = aioxmpp.stanza.Presence(
type_=aioxmpp.structs.PresenceType.UNAVAILABLE,
to=self._mucjid
)
yield from self.service.client.send(presence)
yield from fut | Leave the MUC. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1777-L1795 |
horazont/aioxmpp | aioxmpp/muc/service.py | Room.muc_request_voice | def muc_request_voice(self):
"""
Request voice (participant role) in the room and wait for the request
to be sent.
The participant role allows occupants to send messages while the room
is in moderated mode.
There is no guarantee that the request will be granted. To detect that
voice has been granted, observe the :meth:`on_role_change` signal.
.. versionadded:: 0.8
"""
msg = aioxmpp.Message(
to=self._mucjid,
type_=aioxmpp.MessageType.NORMAL
)
data = aioxmpp.forms.Data(
aioxmpp.forms.DataType.SUBMIT,
)
data.fields.append(
aioxmpp.forms.Field(
type_=aioxmpp.forms.FieldType.HIDDEN,
var="FORM_TYPE",
values=["http://jabber.org/protocol/muc#request"],
),
)
data.fields.append(
aioxmpp.forms.Field(
type_=aioxmpp.forms.FieldType.LIST_SINGLE,
var="muc#role",
values=["participant"],
)
)
msg.xep0004_data.append(data)
yield from self.service.client.send(msg) | python | def muc_request_voice(self):
"""
Request voice (participant role) in the room and wait for the request
to be sent.
The participant role allows occupants to send messages while the room
is in moderated mode.
There is no guarantee that the request will be granted. To detect that
voice has been granted, observe the :meth:`on_role_change` signal.
.. versionadded:: 0.8
"""
msg = aioxmpp.Message(
to=self._mucjid,
type_=aioxmpp.MessageType.NORMAL
)
data = aioxmpp.forms.Data(
aioxmpp.forms.DataType.SUBMIT,
)
data.fields.append(
aioxmpp.forms.Field(
type_=aioxmpp.forms.FieldType.HIDDEN,
var="FORM_TYPE",
values=["http://jabber.org/protocol/muc#request"],
),
)
data.fields.append(
aioxmpp.forms.Field(
type_=aioxmpp.forms.FieldType.LIST_SINGLE,
var="muc#role",
values=["participant"],
)
)
msg.xep0004_data.append(data)
yield from self.service.client.send(msg) | Request voice (participant role) in the room and wait for the request
to be sent.
The participant role allows occupants to send messages while the room
is in moderated mode.
There is no guarantee that the request will be granted. To detect that
voice has been granted, observe the :meth:`on_role_change` signal.
.. versionadded:: 0.8 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L1798-L1838 |
horazont/aioxmpp | aioxmpp/muc/service.py | MUCClient.join | def join(self, mucjid, nick, *,
password=None, history=None, autorejoin=True):
"""
Join a multi-user chat and create a conversation for it.
:param mucjid: The bare JID of the room to join.
:type mucjid: :class:`~aioxmpp.JID`.
:param nick: The nickname to use in the room.
:type nick: :class:`str`
:param password: The password to join the room, if required.
:type password: :class:`str`
:param history: Specification for how much and which history to fetch.
:type history: :class:`.xso.History`
:param autorejoin: Flag to indicate that the MUC should be
automatically rejoined after a disconnect.
:type autorejoin: :class:`bool`
:raises ValueError: if the MUC JID is invalid.
:return: The :term:`Conversation` and a future on the join.
:rtype: tuple of :class:`~.Room` and :class:`asyncio.Future`.
Join a multi-user chat at `mucjid` with `nick`. Return a :class:`Room`
instance which is used to track the MUC locally and a
:class:`aioxmpp.Future` which becomes done when the join succeeded
(with a :data:`None` value) or failed (with an exception).
In addition, the :meth:`~.ConversationService.on_conversation_added`
signal is emitted immediately with the new :class:`Room`.
It is recommended to attach the desired signals to the :class:`Room`
before yielding next (e.g. in a non-deferred event handler to the
:meth:`~.ConversationService.on_conversation_added` signal), to avoid
races with the server. It is guaranteed that no signals are emitted
before the next yield, and thus, it is safe to attach the signals right
after :meth:`join` returned. (This is also the reason why :meth:`join`
is not a coroutine, but instead returns the room and a future to wait
for.)
Any other interaction with the room must go through the :class:`Room`
instance.
If the multi-user chat at `mucjid` is already or currently being
joined, the existing :class:`Room` and future is returned. The `nick`
and other options for the new join are ignored.
If the `mucjid` is not a bare JID, :class:`ValueError` is raised.
`password` may be a string used as password for the MUC. It will be
remembered and stored at the returned :class:`Room` instance.
`history` may be a :class:`History` instance to request a specific
amount of history; otherwise, the server will return a default amount
of history.
If `autorejoin` is true, the MUC will be re-joined after the stream has
been destroyed and re-established. In that case, the service will
request history since the stream destruction and ignore the `history`
object passed here.
If the stream is currently not established, the join is deferred until
the stream is established.
"""
if history is not None and not isinstance(history, muc_xso.History):
raise TypeError("history must be {!s}, got {!r}".format(
muc_xso.History.__name__,
history))
if not mucjid.is_bare:
raise ValueError("MUC JID must be bare")
try:
room, fut, *_ = self._pending_mucs[mucjid]
except KeyError:
pass
else:
return room, fut
try:
room = self._joined_mucs[mucjid]
except KeyError:
pass
else:
fut = asyncio.Future()
fut.set_result(None)
return room, fut
room = Room(self, mucjid)
room.muc_autorejoin = autorejoin
room.muc_password = password
room.on_exit.connect(
functools.partial(
self._muc_exited,
room
)
)
room.on_muc_enter.connect(
self._pending_on_enter,
)
fut = asyncio.Future()
fut.add_done_callback(functools.partial(
self._pending_join_done,
mucjid,
room,
))
self._pending_mucs[mucjid] = room, fut, nick, history
if self.client.established:
self._send_join_presence(mucjid, history, nick, password)
self.on_conversation_new(room)
self.dependencies[
aioxmpp.im.service.ConversationService
]._add_conversation(room)
return room, fut | python | def join(self, mucjid, nick, *,
password=None, history=None, autorejoin=True):
"""
Join a multi-user chat and create a conversation for it.
:param mucjid: The bare JID of the room to join.
:type mucjid: :class:`~aioxmpp.JID`.
:param nick: The nickname to use in the room.
:type nick: :class:`str`
:param password: The password to join the room, if required.
:type password: :class:`str`
:param history: Specification for how much and which history to fetch.
:type history: :class:`.xso.History`
:param autorejoin: Flag to indicate that the MUC should be
automatically rejoined after a disconnect.
:type autorejoin: :class:`bool`
:raises ValueError: if the MUC JID is invalid.
:return: The :term:`Conversation` and a future on the join.
:rtype: tuple of :class:`~.Room` and :class:`asyncio.Future`.
Join a multi-user chat at `mucjid` with `nick`. Return a :class:`Room`
instance which is used to track the MUC locally and a
:class:`aioxmpp.Future` which becomes done when the join succeeded
(with a :data:`None` value) or failed (with an exception).
In addition, the :meth:`~.ConversationService.on_conversation_added`
signal is emitted immediately with the new :class:`Room`.
It is recommended to attach the desired signals to the :class:`Room`
before yielding next (e.g. in a non-deferred event handler to the
:meth:`~.ConversationService.on_conversation_added` signal), to avoid
races with the server. It is guaranteed that no signals are emitted
before the next yield, and thus, it is safe to attach the signals right
after :meth:`join` returned. (This is also the reason why :meth:`join`
is not a coroutine, but instead returns the room and a future to wait
for.)
Any other interaction with the room must go through the :class:`Room`
instance.
If the multi-user chat at `mucjid` is already or currently being
joined, the existing :class:`Room` and future is returned. The `nick`
and other options for the new join are ignored.
If the `mucjid` is not a bare JID, :class:`ValueError` is raised.
`password` may be a string used as password for the MUC. It will be
remembered and stored at the returned :class:`Room` instance.
`history` may be a :class:`History` instance to request a specific
amount of history; otherwise, the server will return a default amount
of history.
If `autorejoin` is true, the MUC will be re-joined after the stream has
been destroyed and re-established. In that case, the service will
request history since the stream destruction and ignore the `history`
object passed here.
If the stream is currently not established, the join is deferred until
the stream is established.
"""
if history is not None and not isinstance(history, muc_xso.History):
raise TypeError("history must be {!s}, got {!r}".format(
muc_xso.History.__name__,
history))
if not mucjid.is_bare:
raise ValueError("MUC JID must be bare")
try:
room, fut, *_ = self._pending_mucs[mucjid]
except KeyError:
pass
else:
return room, fut
try:
room = self._joined_mucs[mucjid]
except KeyError:
pass
else:
fut = asyncio.Future()
fut.set_result(None)
return room, fut
room = Room(self, mucjid)
room.muc_autorejoin = autorejoin
room.muc_password = password
room.on_exit.connect(
functools.partial(
self._muc_exited,
room
)
)
room.on_muc_enter.connect(
self._pending_on_enter,
)
fut = asyncio.Future()
fut.add_done_callback(functools.partial(
self._pending_join_done,
mucjid,
room,
))
self._pending_mucs[mucjid] = room, fut, nick, history
if self.client.established:
self._send_join_presence(mucjid, history, nick, password)
self.on_conversation_new(room)
self.dependencies[
aioxmpp.im.service.ConversationService
]._add_conversation(room)
return room, fut | Join a multi-user chat and create a conversation for it.
:param mucjid: The bare JID of the room to join.
:type mucjid: :class:`~aioxmpp.JID`.
:param nick: The nickname to use in the room.
:type nick: :class:`str`
:param password: The password to join the room, if required.
:type password: :class:`str`
:param history: Specification for how much and which history to fetch.
:type history: :class:`.xso.History`
:param autorejoin: Flag to indicate that the MUC should be
automatically rejoined after a disconnect.
:type autorejoin: :class:`bool`
:raises ValueError: if the MUC JID is invalid.
:return: The :term:`Conversation` and a future on the join.
:rtype: tuple of :class:`~.Room` and :class:`asyncio.Future`.
Join a multi-user chat at `mucjid` with `nick`. Return a :class:`Room`
instance which is used to track the MUC locally and a
:class:`aioxmpp.Future` which becomes done when the join succeeded
(with a :data:`None` value) or failed (with an exception).
In addition, the :meth:`~.ConversationService.on_conversation_added`
signal is emitted immediately with the new :class:`Room`.
It is recommended to attach the desired signals to the :class:`Room`
before yielding next (e.g. in a non-deferred event handler to the
:meth:`~.ConversationService.on_conversation_added` signal), to avoid
races with the server. It is guaranteed that no signals are emitted
before the next yield, and thus, it is safe to attach the signals right
after :meth:`join` returned. (This is also the reason why :meth:`join`
is not a coroutine, but instead returns the room and a future to wait
for.)
Any other interaction with the room must go through the :class:`Room`
instance.
If the multi-user chat at `mucjid` is already or currently being
joined, the existing :class:`Room` and future is returned. The `nick`
and other options for the new join are ignored.
If the `mucjid` is not a bare JID, :class:`ValueError` is raised.
`password` may be a string used as password for the MUC. It will be
remembered and stored at the returned :class:`Room` instance.
`history` may be a :class:`History` instance to request a specific
amount of history; otherwise, the server will return a default amount
of history.
If `autorejoin` is true, the MUC will be re-joined after the stream has
been destroyed and re-established. In that case, the service will
request history since the stream destruction and ignore the `history`
object passed here.
If the stream is currently not established, the join is deferred until
the stream is established. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L2265-L2379 |
horazont/aioxmpp | aioxmpp/muc/service.py | MUCClient.set_affiliation | def set_affiliation(self, mucjid, jid, affiliation, *, reason=None):
"""
Change the affiliation of an entity with a MUC.
:param mucjid: The bare JID identifying the MUC.
:type mucjid: :class:`~aioxmpp.JID`
:param jid: The bare JID of the entity whose affiliation shall be
changed.
:type jid: :class:`~aioxmpp.JID`
:param affiliation: The new affiliation for the entity.
:type affiliation: :class:`str`
:param reason: Optional reason for the affiliation change.
:type reason: :class:`str` or :data:`None`
Change the affiliation of the given `jid` with the MUC identified by
the bare `mucjid` to the given new `affiliation`. Optionally, a
`reason` can be given.
If you are joined in the MUC, :meth:`Room.muc_set_affiliation` may be
more convenient, but it is possible to modify the affiliations of a MUC
without being joined, given sufficient privilegues.
Setting the different affiliations require different privilegues of the
local user. The details can be checked in :xep:`0045` and are enforced
solely by the server, not local code.
The coroutine returns when the change in affiliation has been
acknowledged by the server. If the server returns an error, an
appropriate :class:`aioxmpp.errors.XMPPError` subclass is raised.
"""
if mucjid is None or not mucjid.is_bare:
raise ValueError("mucjid must be bare JID")
if jid is None:
raise ValueError("jid must not be None")
if affiliation is None:
raise ValueError("affiliation must not be None")
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=mucjid
)
iq.payload = muc_xso.AdminQuery(
items=[
muc_xso.AdminItem(jid=jid,
reason=reason,
affiliation=affiliation)
]
)
yield from self.client.send(iq) | python | def set_affiliation(self, mucjid, jid, affiliation, *, reason=None):
"""
Change the affiliation of an entity with a MUC.
:param mucjid: The bare JID identifying the MUC.
:type mucjid: :class:`~aioxmpp.JID`
:param jid: The bare JID of the entity whose affiliation shall be
changed.
:type jid: :class:`~aioxmpp.JID`
:param affiliation: The new affiliation for the entity.
:type affiliation: :class:`str`
:param reason: Optional reason for the affiliation change.
:type reason: :class:`str` or :data:`None`
Change the affiliation of the given `jid` with the MUC identified by
the bare `mucjid` to the given new `affiliation`. Optionally, a
`reason` can be given.
If you are joined in the MUC, :meth:`Room.muc_set_affiliation` may be
more convenient, but it is possible to modify the affiliations of a MUC
without being joined, given sufficient privilegues.
Setting the different affiliations require different privilegues of the
local user. The details can be checked in :xep:`0045` and are enforced
solely by the server, not local code.
The coroutine returns when the change in affiliation has been
acknowledged by the server. If the server returns an error, an
appropriate :class:`aioxmpp.errors.XMPPError` subclass is raised.
"""
if mucjid is None or not mucjid.is_bare:
raise ValueError("mucjid must be bare JID")
if jid is None:
raise ValueError("jid must not be None")
if affiliation is None:
raise ValueError("affiliation must not be None")
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=mucjid
)
iq.payload = muc_xso.AdminQuery(
items=[
muc_xso.AdminItem(jid=jid,
reason=reason,
affiliation=affiliation)
]
)
yield from self.client.send(iq) | Change the affiliation of an entity with a MUC.
:param mucjid: The bare JID identifying the MUC.
:type mucjid: :class:`~aioxmpp.JID`
:param jid: The bare JID of the entity whose affiliation shall be
changed.
:type jid: :class:`~aioxmpp.JID`
:param affiliation: The new affiliation for the entity.
:type affiliation: :class:`str`
:param reason: Optional reason for the affiliation change.
:type reason: :class:`str` or :data:`None`
Change the affiliation of the given `jid` with the MUC identified by
the bare `mucjid` to the given new `affiliation`. Optionally, a
`reason` can be given.
If you are joined in the MUC, :meth:`Room.muc_set_affiliation` may be
more convenient, but it is possible to modify the affiliations of a MUC
without being joined, given sufficient privilegues.
Setting the different affiliations require different privilegues of the
local user. The details can be checked in :xep:`0045` and are enforced
solely by the server, not local code.
The coroutine returns when the change in affiliation has been
acknowledged by the server. If the server returns an error, an
appropriate :class:`aioxmpp.errors.XMPPError` subclass is raised. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L2382-L2435 |
horazont/aioxmpp | aioxmpp/muc/service.py | MUCClient.get_room_config | def get_room_config(self, mucjid):
"""
Query and return the room configuration form for the given MUC.
:param mucjid: JID of the room to query
:type mucjid: bare :class:`~.JID`
:return: data form template for the room configuration
:rtype: :class:`aioxmpp.forms.Data`
.. seealso::
:class:`~.ConfigurationForm`
for a form template to work with the returned form
.. versionadded:: 0.7
"""
if mucjid is None or not mucjid.is_bare:
raise ValueError("mucjid must be bare JID")
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.GET,
to=mucjid,
payload=muc_xso.OwnerQuery(),
)
return (yield from self.client.send(iq)).form | python | def get_room_config(self, mucjid):
"""
Query and return the room configuration form for the given MUC.
:param mucjid: JID of the room to query
:type mucjid: bare :class:`~.JID`
:return: data form template for the room configuration
:rtype: :class:`aioxmpp.forms.Data`
.. seealso::
:class:`~.ConfigurationForm`
for a form template to work with the returned form
.. versionadded:: 0.7
"""
if mucjid is None or not mucjid.is_bare:
raise ValueError("mucjid must be bare JID")
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.GET,
to=mucjid,
payload=muc_xso.OwnerQuery(),
)
return (yield from self.client.send(iq)).form | Query and return the room configuration form for the given MUC.
:param mucjid: JID of the room to query
:type mucjid: bare :class:`~.JID`
:return: data form template for the room configuration
:rtype: :class:`aioxmpp.forms.Data`
.. seealso::
:class:`~.ConfigurationForm`
for a form template to work with the returned form
.. versionadded:: 0.7 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L2438-L2464 |
horazont/aioxmpp | aioxmpp/muc/service.py | MUCClient.set_room_config | def set_room_config(self, mucjid, data):
"""
Set the room configuration using a :xep:`4` data form.
:param mucjid: JID of the room to query
:type mucjid: bare :class:`~.JID`
:param data: Filled-out configuration form
:type data: :class:`aioxmpp.forms.Data`
.. seealso::
:class:`~.ConfigurationForm`
for a form template to generate the required form
A sensible workflow to, for example, set a room to be moderated, could
be this::
form = aioxmpp.muc.ConfigurationForm.from_xso(
(await muc_service.get_room_config(mucjid))
)
form.moderatedroom = True
await muc_service.set_rooom_config(mucjid, form.render_reply())
.. versionadded:: 0.7
"""
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=mucjid,
payload=muc_xso.OwnerQuery(form=data),
)
yield from self.client.send(iq) | python | def set_room_config(self, mucjid, data):
"""
Set the room configuration using a :xep:`4` data form.
:param mucjid: JID of the room to query
:type mucjid: bare :class:`~.JID`
:param data: Filled-out configuration form
:type data: :class:`aioxmpp.forms.Data`
.. seealso::
:class:`~.ConfigurationForm`
for a form template to generate the required form
A sensible workflow to, for example, set a room to be moderated, could
be this::
form = aioxmpp.muc.ConfigurationForm.from_xso(
(await muc_service.get_room_config(mucjid))
)
form.moderatedroom = True
await muc_service.set_rooom_config(mucjid, form.render_reply())
.. versionadded:: 0.7
"""
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.structs.IQType.SET,
to=mucjid,
payload=muc_xso.OwnerQuery(form=data),
)
yield from self.client.send(iq) | Set the room configuration using a :xep:`4` data form.
:param mucjid: JID of the room to query
:type mucjid: bare :class:`~.JID`
:param data: Filled-out configuration form
:type data: :class:`aioxmpp.forms.Data`
.. seealso::
:class:`~.ConfigurationForm`
for a form template to generate the required form
A sensible workflow to, for example, set a room to be moderated, could
be this::
form = aioxmpp.muc.ConfigurationForm.from_xso(
(await muc_service.get_room_config(mucjid))
)
form.moderatedroom = True
await muc_service.set_rooom_config(mucjid, form.render_reply())
.. versionadded:: 0.7 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/muc/service.py#L2467-L2499 |
horazont/aioxmpp | aioxmpp/httpupload/__init__.py | request_slot | def request_slot(client,
service: JID,
filename: str,
size: int,
content_type: str):
"""
Request an HTTP upload slot.
:param client: The client to request the slot with.
:type client: :class:`aioxmpp.Client`
:param service: Address of the HTTP upload service.
:type service: :class:`~aioxmpp.JID`
:param filename: Name of the file (without path), may be used by the server
to generate the URL.
:type filename: :class:`str`
:param size: Size of the file in bytes
:type size: :class:`int`
:param content_type: The MIME type of the file
:type content_type: :class:`str`
:return: The assigned upload slot.
:rtype: :class:`.xso.Slot`
Sends a :xep:`363` slot request to the XMPP service to obtain HTTP
PUT and GET URLs for a file upload.
The upload slot is returned as a :class:`~.xso.Slot` object.
"""
payload = Request(filename, size, content_type)
return (yield from client.send(IQ(
type_=IQType.GET,
to=service,
payload=payload
))) | python | def request_slot(client,
service: JID,
filename: str,
size: int,
content_type: str):
"""
Request an HTTP upload slot.
:param client: The client to request the slot with.
:type client: :class:`aioxmpp.Client`
:param service: Address of the HTTP upload service.
:type service: :class:`~aioxmpp.JID`
:param filename: Name of the file (without path), may be used by the server
to generate the URL.
:type filename: :class:`str`
:param size: Size of the file in bytes
:type size: :class:`int`
:param content_type: The MIME type of the file
:type content_type: :class:`str`
:return: The assigned upload slot.
:rtype: :class:`.xso.Slot`
Sends a :xep:`363` slot request to the XMPP service to obtain HTTP
PUT and GET URLs for a file upload.
The upload slot is returned as a :class:`~.xso.Slot` object.
"""
payload = Request(filename, size, content_type)
return (yield from client.send(IQ(
type_=IQType.GET,
to=service,
payload=payload
))) | Request an HTTP upload slot.
:param client: The client to request the slot with.
:type client: :class:`aioxmpp.Client`
:param service: Address of the HTTP upload service.
:type service: :class:`~aioxmpp.JID`
:param filename: Name of the file (without path), may be used by the server
to generate the URL.
:type filename: :class:`str`
:param size: Size of the file in bytes
:type size: :class:`int`
:param content_type: The MIME type of the file
:type content_type: :class:`str`
:return: The assigned upload slot.
:rtype: :class:`.xso.Slot`
Sends a :xep:`363` slot request to the XMPP service to obtain HTTP
PUT and GET URLs for a file upload.
The upload slot is returned as a :class:`~.xso.Slot` object. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/httpupload/__init__.py#L76-L109 |
horazont/aioxmpp | aioxmpp/version/service.py | query_version | def query_version(stream: aioxmpp.stream.StanzaStream,
target: aioxmpp.JID) -> version_xso.Query:
"""
Query the software version of an entity.
:param stream: A stanza stream to send the query on.
:type stream: :class:`aioxmpp.stream.StanzaStream`
:param target: The address of the entity to query.
:type target: :class:`aioxmpp.JID`
:raises OSError: if a connection issue occured before a reply was received
:raises aioxmpp.errors.XMPPError: if an XMPP error was returned instead
of a reply.
:rtype: :class:`aioxmpp.version.xso.Query`
:return: The response from the peer.
The response is returned as :class:`~aioxmpp.version.xso.Query` object. The
attributes hold the data returned by the peer. Each attribute may be
:data:`None` if the peer chose to omit that information. In an extreme
case, all attributes are :data:`None`.
"""
return (yield from stream.send(
aioxmpp.IQ(
type_=aioxmpp.IQType.GET,
to=target,
payload=version_xso.Query(),
)
)) | python | def query_version(stream: aioxmpp.stream.StanzaStream,
target: aioxmpp.JID) -> version_xso.Query:
"""
Query the software version of an entity.
:param stream: A stanza stream to send the query on.
:type stream: :class:`aioxmpp.stream.StanzaStream`
:param target: The address of the entity to query.
:type target: :class:`aioxmpp.JID`
:raises OSError: if a connection issue occured before a reply was received
:raises aioxmpp.errors.XMPPError: if an XMPP error was returned instead
of a reply.
:rtype: :class:`aioxmpp.version.xso.Query`
:return: The response from the peer.
The response is returned as :class:`~aioxmpp.version.xso.Query` object. The
attributes hold the data returned by the peer. Each attribute may be
:data:`None` if the peer chose to omit that information. In an extreme
case, all attributes are :data:`None`.
"""
return (yield from stream.send(
aioxmpp.IQ(
type_=aioxmpp.IQType.GET,
to=target,
payload=version_xso.Query(),
)
)) | Query the software version of an entity.
:param stream: A stanza stream to send the query on.
:type stream: :class:`aioxmpp.stream.StanzaStream`
:param target: The address of the entity to query.
:type target: :class:`aioxmpp.JID`
:raises OSError: if a connection issue occured before a reply was received
:raises aioxmpp.errors.XMPPError: if an XMPP error was returned instead
of a reply.
:rtype: :class:`aioxmpp.version.xso.Query`
:return: The response from the peer.
The response is returned as :class:`~aioxmpp.version.xso.Query` object. The
attributes hold the data returned by the peer. Each attribute may be
:data:`None` if the peer chose to omit that information. In an extreme
case, all attributes are :data:`None`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/version/service.py#L185-L212 |
horazont/aioxmpp | aioxmpp/bookmarks/xso.py | as_bookmark_class | def as_bookmark_class(xso_class):
"""
Decorator to register `xso_class` as a custom bookmark class.
This is necessary to store and retrieve such bookmarks.
The registered class must be a subclass of the abstract base class
:class:`Bookmark`.
:raises TypeError: if `xso_class` is not a subclass of :class:`Bookmark`.
"""
if not issubclass(xso_class, Bookmark):
raise TypeError(
"Classes registered as bookmark types must be Bookmark subclasses"
)
Storage.register_child(
Storage.bookmarks,
xso_class
)
return xso_class | python | def as_bookmark_class(xso_class):
"""
Decorator to register `xso_class` as a custom bookmark class.
This is necessary to store and retrieve such bookmarks.
The registered class must be a subclass of the abstract base class
:class:`Bookmark`.
:raises TypeError: if `xso_class` is not a subclass of :class:`Bookmark`.
"""
if not issubclass(xso_class, Bookmark):
raise TypeError(
"Classes registered as bookmark types must be Bookmark subclasses"
)
Storage.register_child(
Storage.bookmarks,
xso_class
)
return xso_class | Decorator to register `xso_class` as a custom bookmark class.
This is necessary to store and retrieve such bookmarks.
The registered class must be a subclass of the abstract base class
:class:`Bookmark`.
:raises TypeError: if `xso_class` is not a subclass of :class:`Bookmark`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/xso.py#L241-L262 |
horazont/aioxmpp | aioxmpp/structs.py | basic_filter_languages | def basic_filter_languages(languages, ranges):
"""
Filter languages using the string-based basic filter algorithm described in
RFC4647.
`languages` must be a sequence of :class:`LanguageTag` instances which are
to be filtered.
`ranges` must be an iterable which represent the basic language ranges to
filter with, in priority order. The language ranges must be given as
:class:`LanguageRange` objects.
Return an iterator of languages which matched any of the `ranges`. The
sequence produced by the iterator is in match order and duplicate-free. The
first range to match a language yields the language into the iterator, no
other range can yield that language afterwards.
"""
if LanguageRange.WILDCARD in ranges:
yield from languages
return
found = set()
for language_range in ranges:
range_str = language_range.match_str
for language in languages:
if language in found:
continue
match_str = language.match_str
if match_str == range_str:
yield language
found.add(language)
continue
if len(range_str) < len(match_str):
if (match_str[:len(range_str)] == range_str and
match_str[len(range_str)] == "-"):
yield language
found.add(language)
continue | python | def basic_filter_languages(languages, ranges):
"""
Filter languages using the string-based basic filter algorithm described in
RFC4647.
`languages` must be a sequence of :class:`LanguageTag` instances which are
to be filtered.
`ranges` must be an iterable which represent the basic language ranges to
filter with, in priority order. The language ranges must be given as
:class:`LanguageRange` objects.
Return an iterator of languages which matched any of the `ranges`. The
sequence produced by the iterator is in match order and duplicate-free. The
first range to match a language yields the language into the iterator, no
other range can yield that language afterwards.
"""
if LanguageRange.WILDCARD in ranges:
yield from languages
return
found = set()
for language_range in ranges:
range_str = language_range.match_str
for language in languages:
if language in found:
continue
match_str = language.match_str
if match_str == range_str:
yield language
found.add(language)
continue
if len(range_str) < len(match_str):
if (match_str[:len(range_str)] == range_str and
match_str[len(range_str)] == "-"):
yield language
found.add(language)
continue | Filter languages using the string-based basic filter algorithm described in
RFC4647.
`languages` must be a sequence of :class:`LanguageTag` instances which are
to be filtered.
`ranges` must be an iterable which represent the basic language ranges to
filter with, in priority order. The language ranges must be given as
:class:`LanguageRange` objects.
Return an iterator of languages which matched any of the `ranges`. The
sequence produced by the iterator is in match order and duplicate-free. The
first range to match a language yields the language into the iterator, no
other range can yield that language afterwards. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/structs.py#L1228-L1269 |
horazont/aioxmpp | aioxmpp/structs.py | lookup_language | def lookup_language(languages, ranges):
"""
Look up a single language in the sequence `languages` using the lookup
mechansim described in RFC4647. If no match is found, :data:`None` is
returned. Otherwise, the first matching language is returned.
`languages` must be a sequence of :class:`LanguageTag` objects, while
`ranges` must be an iterable of :class:`LanguageRange` objects.
"""
for language_range in ranges:
while True:
try:
return next(iter(basic_filter_languages(
languages,
[language_range])))
except StopIteration:
pass
try:
language_range = language_range.strip_rightmost()
except ValueError:
break | python | def lookup_language(languages, ranges):
"""
Look up a single language in the sequence `languages` using the lookup
mechansim described in RFC4647. If no match is found, :data:`None` is
returned. Otherwise, the first matching language is returned.
`languages` must be a sequence of :class:`LanguageTag` objects, while
`ranges` must be an iterable of :class:`LanguageRange` objects.
"""
for language_range in ranges:
while True:
try:
return next(iter(basic_filter_languages(
languages,
[language_range])))
except StopIteration:
pass
try:
language_range = language_range.strip_rightmost()
except ValueError:
break | Look up a single language in the sequence `languages` using the lookup
mechansim described in RFC4647. If no match is found, :data:`None` is
returned. Otherwise, the first matching language is returned.
`languages` must be a sequence of :class:`LanguageTag` objects, while
`ranges` must be an iterable of :class:`LanguageRange` objects. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/structs.py#L1272-L1294 |
horazont/aioxmpp | aioxmpp/structs.py | JID.replace | def replace(self, **kwargs):
"""
Construct a new :class:`JID` object, using the values of the current
JID. Use the arguments to override specific attributes on the new
object.
All arguments are keyword arguments.
:param localpart: Set the local part of the resulting JID.
:param domain: Set the domain of the resulting JID.
:param resource: Set the resource part of the resulting JID.
:raises: See :class:`JID`
:return: A new :class:`JID` object with the corresponding
substitutions performed.
:rtype: :class:`JID`
The attributes of parameters which are omitted are not modified and
copied down to the result.
"""
new_kwargs = {}
strict = kwargs.pop("strict", True)
try:
localpart = kwargs.pop("localpart")
except KeyError:
pass
else:
if localpart:
localpart = nodeprep(
localpart,
allow_unassigned=not strict
)
new_kwargs["localpart"] = localpart
try:
domain = kwargs.pop("domain")
except KeyError:
pass
else:
if not domain:
raise ValueError("domain must not be empty or None")
new_kwargs["domain"] = nameprep(
domain,
allow_unassigned=not strict
)
try:
resource = kwargs.pop("resource")
except KeyError:
pass
else:
if resource:
resource = resourceprep(
resource,
allow_unassigned=not strict
)
new_kwargs["resource"] = resource
if kwargs:
raise TypeError("replace() got an unexpected keyword argument"
" {!r}".format(
next(iter(kwargs))))
return super()._replace(**new_kwargs) | python | def replace(self, **kwargs):
"""
Construct a new :class:`JID` object, using the values of the current
JID. Use the arguments to override specific attributes on the new
object.
All arguments are keyword arguments.
:param localpart: Set the local part of the resulting JID.
:param domain: Set the domain of the resulting JID.
:param resource: Set the resource part of the resulting JID.
:raises: See :class:`JID`
:return: A new :class:`JID` object with the corresponding
substitutions performed.
:rtype: :class:`JID`
The attributes of parameters which are omitted are not modified and
copied down to the result.
"""
new_kwargs = {}
strict = kwargs.pop("strict", True)
try:
localpart = kwargs.pop("localpart")
except KeyError:
pass
else:
if localpart:
localpart = nodeprep(
localpart,
allow_unassigned=not strict
)
new_kwargs["localpart"] = localpart
try:
domain = kwargs.pop("domain")
except KeyError:
pass
else:
if not domain:
raise ValueError("domain must not be empty or None")
new_kwargs["domain"] = nameprep(
domain,
allow_unassigned=not strict
)
try:
resource = kwargs.pop("resource")
except KeyError:
pass
else:
if resource:
resource = resourceprep(
resource,
allow_unassigned=not strict
)
new_kwargs["resource"] = resource
if kwargs:
raise TypeError("replace() got an unexpected keyword argument"
" {!r}".format(
next(iter(kwargs))))
return super()._replace(**new_kwargs) | Construct a new :class:`JID` object, using the values of the current
JID. Use the arguments to override specific attributes on the new
object.
All arguments are keyword arguments.
:param localpart: Set the local part of the resulting JID.
:param domain: Set the domain of the resulting JID.
:param resource: Set the resource part of the resulting JID.
:raises: See :class:`JID`
:return: A new :class:`JID` object with the corresponding
substitutions performed.
:rtype: :class:`JID`
The attributes of parameters which are omitted are not modified and
copied down to the result. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/structs.py#L689-L754 |
horazont/aioxmpp | aioxmpp/structs.py | JID.fromstr | def fromstr(cls, s, *, strict=True):
"""
Construct a JID out of a string containing it.
:param s: The string to parse.
:type s: :class:`str`
:param strict: Whether to enable strict parsing.
:type strict: :class:`bool`
:raises: See :class:`JID`
:return: The parsed JID
:rtype: :class:`JID`
See the :class:`JID` class level documentation for the semantics of
`strict`.
"""
nodedomain, sep, resource = s.partition("/")
if not sep:
resource = None
localpart, sep, domain = nodedomain.partition("@")
if not sep:
domain = localpart
localpart = None
return cls(localpart, domain, resource, strict=strict) | python | def fromstr(cls, s, *, strict=True):
"""
Construct a JID out of a string containing it.
:param s: The string to parse.
:type s: :class:`str`
:param strict: Whether to enable strict parsing.
:type strict: :class:`bool`
:raises: See :class:`JID`
:return: The parsed JID
:rtype: :class:`JID`
See the :class:`JID` class level documentation for the semantics of
`strict`.
"""
nodedomain, sep, resource = s.partition("/")
if not sep:
resource = None
localpart, sep, domain = nodedomain.partition("@")
if not sep:
domain = localpart
localpart = None
return cls(localpart, domain, resource, strict=strict) | Construct a JID out of a string containing it.
:param s: The string to parse.
:type s: :class:`str`
:param strict: Whether to enable strict parsing.
:type strict: :class:`bool`
:raises: See :class:`JID`
:return: The parsed JID
:rtype: :class:`JID`
See the :class:`JID` class level documentation for the semantics of
`strict`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/structs.py#L792-L815 |
horazont/aioxmpp | aioxmpp/structs.py | LanguageRange.strip_rightmost | def strip_rightmost(self):
"""
Strip the rightmost part of the language range. If the new rightmost
part is a singleton or ``x`` (i.e. starts an extension or private use
part), it is also stripped.
Return the newly created :class:`LanguageRange`.
"""
parts = self.print_str.split("-")
parts.pop()
if parts and len(parts[-1]) == 1:
parts.pop()
return type(self).fromstr("-".join(parts)) | python | def strip_rightmost(self):
"""
Strip the rightmost part of the language range. If the new rightmost
part is a singleton or ``x`` (i.e. starts an extension or private use
part), it is also stripped.
Return the newly created :class:`LanguageRange`.
"""
parts = self.print_str.split("-")
parts.pop()
if parts and len(parts[-1]) == 1:
parts.pop()
return type(self).fromstr("-".join(parts)) | Strip the rightmost part of the language range. If the new rightmost
part is a singleton or ``x`` (i.e. starts an extension or private use
part), it is also stripped.
Return the newly created :class:`LanguageRange`. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/structs.py#L1209-L1222 |
horazont/aioxmpp | aioxmpp/structs.py | LanguageMap.lookup | def lookup(self, language_ranges):
"""
Perform an RFC4647 language range lookup on the keys in the
dictionary. `language_ranges` must be a sequence of
:class:`LanguageRange` instances.
Return the entry in the dictionary with a key as produced by
`lookup_language`. If `lookup_language` does not find a match and the
mapping contains an entry with key :data:`None`, that entry is
returned, otherwise :class:`KeyError` is raised.
"""
keys = list(self.keys())
try:
keys.remove(None)
except ValueError:
pass
keys.sort()
key = lookup_language(keys, language_ranges)
return self[key] | python | def lookup(self, language_ranges):
"""
Perform an RFC4647 language range lookup on the keys in the
dictionary. `language_ranges` must be a sequence of
:class:`LanguageRange` instances.
Return the entry in the dictionary with a key as produced by
`lookup_language`. If `lookup_language` does not find a match and the
mapping contains an entry with key :data:`None`, that entry is
returned, otherwise :class:`KeyError` is raised.
"""
keys = list(self.keys())
try:
keys.remove(None)
except ValueError:
pass
keys.sort()
key = lookup_language(keys, language_ranges)
return self[key] | Perform an RFC4647 language range lookup on the keys in the
dictionary. `language_ranges` must be a sequence of
:class:`LanguageRange` instances.
Return the entry in the dictionary with a key as produced by
`lookup_language`. If `lookup_language` does not find a match and the
mapping contains an entry with key :data:`None`, that entry is
returned, otherwise :class:`KeyError` is raised. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/structs.py#L1310-L1328 |
horazont/aioxmpp | aioxmpp/im/p2p.py | Service.get_conversation | def get_conversation(self, peer_jid, *, current_jid=None):
"""
Get or create a new one-to-one conversation with a peer.
:param peer_jid: The JID of the peer to converse with.
:type peer_jid: :class:`aioxmpp.JID`
:param current_jid: The current JID to lock the conversation to (see
:rfc:`6121`).
:type current_jid: :class:`aioxmpp.JID`
:rtype: :class:`Conversation`
:return: The new or existing conversation with the peer.
`peer_jid` must be a full or bare JID. See the :class:`Service`
documentation for details.
.. versionchanged:: 0.10
In 0.9, this was a coroutine. Sorry.
"""
try:
return self._conversationmap[peer_jid]
except KeyError:
pass
return self._make_conversation(peer_jid, False) | python | def get_conversation(self, peer_jid, *, current_jid=None):
"""
Get or create a new one-to-one conversation with a peer.
:param peer_jid: The JID of the peer to converse with.
:type peer_jid: :class:`aioxmpp.JID`
:param current_jid: The current JID to lock the conversation to (see
:rfc:`6121`).
:type current_jid: :class:`aioxmpp.JID`
:rtype: :class:`Conversation`
:return: The new or existing conversation with the peer.
`peer_jid` must be a full or bare JID. See the :class:`Service`
documentation for details.
.. versionchanged:: 0.10
In 0.9, this was a coroutine. Sorry.
"""
try:
return self._conversationmap[peer_jid]
except KeyError:
pass
return self._make_conversation(peer_jid, False) | Get or create a new one-to-one conversation with a peer.
:param peer_jid: The JID of the peer to converse with.
:type peer_jid: :class:`aioxmpp.JID`
:param current_jid: The current JID to lock the conversation to (see
:rfc:`6121`).
:type current_jid: :class:`aioxmpp.JID`
:rtype: :class:`Conversation`
:return: The new or existing conversation with the peer.
`peer_jid` must be a full or bare JID. See the :class:`Service`
documentation for details.
.. versionchanged:: 0.10
In 0.9, this was a coroutine. Sorry. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/im/p2p.py#L204-L228 |
horazont/aioxmpp | aioxmpp/network.py | reconfigure_resolver | def reconfigure_resolver():
"""
Reset the resolver configured for this thread to a fresh instance. This
essentially re-reads the system-wide resolver configuration.
If a custom resolver has been set using :func:`set_resolver`, the flag
indicating that no automatic re-configuration shall take place is cleared.
"""
global _state
_state.resolver = dns.resolver.Resolver()
_state.overridden_resolver = False | python | def reconfigure_resolver():
"""
Reset the resolver configured for this thread to a fresh instance. This
essentially re-reads the system-wide resolver configuration.
If a custom resolver has been set using :func:`set_resolver`, the flag
indicating that no automatic re-configuration shall take place is cleared.
"""
global _state
_state.resolver = dns.resolver.Resolver()
_state.overridden_resolver = False | Reset the resolver configured for this thread to a fresh instance. This
essentially re-reads the system-wide resolver configuration.
If a custom resolver has been set using :func:`set_resolver`, the flag
indicating that no automatic re-configuration shall take place is cleared. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/network.py#L116-L127 |
horazont/aioxmpp | aioxmpp/network.py | repeated_query | def repeated_query(qname, rdtype,
nattempts=None,
resolver=None,
require_ad=False,
executor=None):
"""
Repeatedly fire a DNS query until either the number of allowed attempts
(`nattempts`) is excedeed or a non-error result is returned (NXDOMAIN is
a non-error result).
If `nattempts` is :data:`None`, it is set to 3 if `resolver` is
:data:`None` and to 2 otherwise. This way, no query is made without a
possible change to a local parameter. (When using the thread-local
resolver, it will be re-configured after the first failed query and after
the second failed query, TCP is used. With a fixed resolver, TCP is used
after the first failed query.)
`qname` must be the (IDNA encoded, as :class:`bytes`) name to query,
`rdtype` the record type to query for. If `resolver` is not :data:`None`,
it must be a DNSPython :class:`dns.resolver.Resolver` instance; if it is
:data:`None`, the resolver obtained from :func:`get_resolver` is used.
If `require_ad` is :data:`True`, the peer resolver is asked to do DNSSEC
validation and if the AD flag is missing in the response,
:class:`ValueError` is raised. If `require_ad` is :data:`False`, the
resolver is asked to do DNSSEC validation nevertheless, but missing
validation (in constrast to failed validation) is not an error.
.. note::
This function modifies the flags of the `resolver` instance, no matter
if it uses the thread-local resolver instance or the resolver passed as
an argument.
If the first query fails and `resolver` is :data:`None` and the
thread-local resolver has not been overridden with :func:`set_resolver`,
:func:`reconfigure_resolver` is called and the query is re-attempted
immediately.
If the next query after reconfiguration of the resolver (if the
preconditions for resolver reconfigurations are not met, this applies to
the first failing query), :func:`repeated_query` switches to TCP.
If no result is received before the number of allowed attempts is exceeded,
:class:`TimeoutError` is raised.
Return the result set or :data:`None` if the domain does not exist.
This is a coroutine; the query is executed in an `executor` using the
:meth:`asyncio.BaseEventLoop.run_in_executor` of the current event loop. By
default, the default executor provided by the event loop is used, but it
can be overridden using the `executor` argument.
If the used resolver raises :class:`dns.resolver.NoNameservers`
(semantically, that no nameserver was able to answer the request), this
function suspects that DNSSEC validation failed, as responding with
SERVFAIL is what unbound does. To test that case, a simple check is made:
the query is repeated, but with a flag set which indicates that we would
like to do the validation ourselves. If that query succeeds, we assume that
the error is in fact due to DNSSEC validation failure and raise
:class:`ValidationError`. Otherwise, the answer is discarded and the
:class:`~dns.resolver.NoNameservers` exception is treated as normal
timeout. If the exception re-occurs in the second query, it is re-raised,
as it indicates a serious configuration problem.
"""
global _state
loop = asyncio.get_event_loop()
# tlr = thread-local resolver
use_tlr = False
if resolver is None:
resolver = get_resolver()
use_tlr = not _state.overridden_resolver
if nattempts is None:
if use_tlr:
nattempts = 3
else:
nattempts = 2
if nattempts <= 0:
raise ValueError("query cannot succeed with non-positive amount "
"of attempts")
qname = qname.decode("ascii")
def handle_timeout():
nonlocal use_tlr, resolver, use_tcp
if use_tlr and i == 0:
reconfigure_resolver()
resolver = get_resolver()
else:
use_tcp = True
use_tcp = False
for i in range(nattempts):
resolver.set_flags(dns.flags.RD | dns.flags.AD)
try:
answer = yield from loop.run_in_executor(
executor,
functools.partial(
resolver.query,
qname,
rdtype,
tcp=use_tcp
)
)
if require_ad and not (answer.response.flags & dns.flags.AD):
raise ValueError("DNSSEC validation not available")
except (TimeoutError, dns.resolver.Timeout):
handle_timeout()
continue
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
return None
except (dns.resolver.NoNameservers):
# make sure we have the correct config
if use_tlr and i == 0:
reconfigure_resolver()
resolver = get_resolver()
continue
resolver.set_flags(dns.flags.RD | dns.flags.AD | dns.flags.CD)
try:
yield from loop.run_in_executor(
executor,
functools.partial(
resolver.query,
qname,
rdtype,
tcp=use_tcp,
raise_on_no_answer=False
))
except (dns.resolver.Timeout, TimeoutError):
handle_timeout()
continue
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
pass
raise ValidationError(
"nameserver error, most likely DNSSEC validation failed",
)
break
else:
raise TimeoutError()
return answer | python | def repeated_query(qname, rdtype,
nattempts=None,
resolver=None,
require_ad=False,
executor=None):
"""
Repeatedly fire a DNS query until either the number of allowed attempts
(`nattempts`) is excedeed or a non-error result is returned (NXDOMAIN is
a non-error result).
If `nattempts` is :data:`None`, it is set to 3 if `resolver` is
:data:`None` and to 2 otherwise. This way, no query is made without a
possible change to a local parameter. (When using the thread-local
resolver, it will be re-configured after the first failed query and after
the second failed query, TCP is used. With a fixed resolver, TCP is used
after the first failed query.)
`qname` must be the (IDNA encoded, as :class:`bytes`) name to query,
`rdtype` the record type to query for. If `resolver` is not :data:`None`,
it must be a DNSPython :class:`dns.resolver.Resolver` instance; if it is
:data:`None`, the resolver obtained from :func:`get_resolver` is used.
If `require_ad` is :data:`True`, the peer resolver is asked to do DNSSEC
validation and if the AD flag is missing in the response,
:class:`ValueError` is raised. If `require_ad` is :data:`False`, the
resolver is asked to do DNSSEC validation nevertheless, but missing
validation (in constrast to failed validation) is not an error.
.. note::
This function modifies the flags of the `resolver` instance, no matter
if it uses the thread-local resolver instance or the resolver passed as
an argument.
If the first query fails and `resolver` is :data:`None` and the
thread-local resolver has not been overridden with :func:`set_resolver`,
:func:`reconfigure_resolver` is called and the query is re-attempted
immediately.
If the next query after reconfiguration of the resolver (if the
preconditions for resolver reconfigurations are not met, this applies to
the first failing query), :func:`repeated_query` switches to TCP.
If no result is received before the number of allowed attempts is exceeded,
:class:`TimeoutError` is raised.
Return the result set or :data:`None` if the domain does not exist.
This is a coroutine; the query is executed in an `executor` using the
:meth:`asyncio.BaseEventLoop.run_in_executor` of the current event loop. By
default, the default executor provided by the event loop is used, but it
can be overridden using the `executor` argument.
If the used resolver raises :class:`dns.resolver.NoNameservers`
(semantically, that no nameserver was able to answer the request), this
function suspects that DNSSEC validation failed, as responding with
SERVFAIL is what unbound does. To test that case, a simple check is made:
the query is repeated, but with a flag set which indicates that we would
like to do the validation ourselves. If that query succeeds, we assume that
the error is in fact due to DNSSEC validation failure and raise
:class:`ValidationError`. Otherwise, the answer is discarded and the
:class:`~dns.resolver.NoNameservers` exception is treated as normal
timeout. If the exception re-occurs in the second query, it is re-raised,
as it indicates a serious configuration problem.
"""
global _state
loop = asyncio.get_event_loop()
# tlr = thread-local resolver
use_tlr = False
if resolver is None:
resolver = get_resolver()
use_tlr = not _state.overridden_resolver
if nattempts is None:
if use_tlr:
nattempts = 3
else:
nattempts = 2
if nattempts <= 0:
raise ValueError("query cannot succeed with non-positive amount "
"of attempts")
qname = qname.decode("ascii")
def handle_timeout():
nonlocal use_tlr, resolver, use_tcp
if use_tlr and i == 0:
reconfigure_resolver()
resolver = get_resolver()
else:
use_tcp = True
use_tcp = False
for i in range(nattempts):
resolver.set_flags(dns.flags.RD | dns.flags.AD)
try:
answer = yield from loop.run_in_executor(
executor,
functools.partial(
resolver.query,
qname,
rdtype,
tcp=use_tcp
)
)
if require_ad and not (answer.response.flags & dns.flags.AD):
raise ValueError("DNSSEC validation not available")
except (TimeoutError, dns.resolver.Timeout):
handle_timeout()
continue
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
return None
except (dns.resolver.NoNameservers):
# make sure we have the correct config
if use_tlr and i == 0:
reconfigure_resolver()
resolver = get_resolver()
continue
resolver.set_flags(dns.flags.RD | dns.flags.AD | dns.flags.CD)
try:
yield from loop.run_in_executor(
executor,
functools.partial(
resolver.query,
qname,
rdtype,
tcp=use_tcp,
raise_on_no_answer=False
))
except (dns.resolver.Timeout, TimeoutError):
handle_timeout()
continue
except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer):
pass
raise ValidationError(
"nameserver error, most likely DNSSEC validation failed",
)
break
else:
raise TimeoutError()
return answer | Repeatedly fire a DNS query until either the number of allowed attempts
(`nattempts`) is excedeed or a non-error result is returned (NXDOMAIN is
a non-error result).
If `nattempts` is :data:`None`, it is set to 3 if `resolver` is
:data:`None` and to 2 otherwise. This way, no query is made without a
possible change to a local parameter. (When using the thread-local
resolver, it will be re-configured after the first failed query and after
the second failed query, TCP is used. With a fixed resolver, TCP is used
after the first failed query.)
`qname` must be the (IDNA encoded, as :class:`bytes`) name to query,
`rdtype` the record type to query for. If `resolver` is not :data:`None`,
it must be a DNSPython :class:`dns.resolver.Resolver` instance; if it is
:data:`None`, the resolver obtained from :func:`get_resolver` is used.
If `require_ad` is :data:`True`, the peer resolver is asked to do DNSSEC
validation and if the AD flag is missing in the response,
:class:`ValueError` is raised. If `require_ad` is :data:`False`, the
resolver is asked to do DNSSEC validation nevertheless, but missing
validation (in constrast to failed validation) is not an error.
.. note::
This function modifies the flags of the `resolver` instance, no matter
if it uses the thread-local resolver instance or the resolver passed as
an argument.
If the first query fails and `resolver` is :data:`None` and the
thread-local resolver has not been overridden with :func:`set_resolver`,
:func:`reconfigure_resolver` is called and the query is re-attempted
immediately.
If the next query after reconfiguration of the resolver (if the
preconditions for resolver reconfigurations are not met, this applies to
the first failing query), :func:`repeated_query` switches to TCP.
If no result is received before the number of allowed attempts is exceeded,
:class:`TimeoutError` is raised.
Return the result set or :data:`None` if the domain does not exist.
This is a coroutine; the query is executed in an `executor` using the
:meth:`asyncio.BaseEventLoop.run_in_executor` of the current event loop. By
default, the default executor provided by the event loop is used, but it
can be overridden using the `executor` argument.
If the used resolver raises :class:`dns.resolver.NoNameservers`
(semantically, that no nameserver was able to answer the request), this
function suspects that DNSSEC validation failed, as responding with
SERVFAIL is what unbound does. To test that case, a simple check is made:
the query is repeated, but with a flag set which indicates that we would
like to do the validation ourselves. If that query succeeds, we assume that
the error is in fact due to DNSSEC validation failure and raise
:class:`ValidationError`. Otherwise, the answer is discarded and the
:class:`~dns.resolver.NoNameservers` exception is treated as normal
timeout. If the exception re-occurs in the second query, it is re-raised,
as it indicates a serious configuration problem. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/network.py#L146-L291 |
horazont/aioxmpp | aioxmpp/network.py | lookup_srv | def lookup_srv(
domain: bytes,
service: str,
transport: str = "tcp",
**kwargs):
"""
Query the DNS for SRV records describing how the given `service` over the
given `transport` is implemented for the given `domain`. `domain` must be
an IDNA-encoded :class:`bytes` object; `service` must be a normal
:class:`str`.
Keyword arguments are passed to :func:`repeated_query`.
Return a list of tuples ``(prio, weight, (hostname, port))``, where
`hostname` is a IDNA-encoded :class:`bytes` object containing the hostname
obtained from the SRV record. The other fields are also as obtained from
the SRV records. The trailing dot is stripped from the `hostname`.
If the DNS query returns an empty result, :data:`None` is returned. If any
of the found SRV records has the root zone (``.``) as `hostname`, this
indicates that the service is not available at the given `domain` and
:class:`ValueError` is raised.
"""
record = b".".join([
b"_" + service.encode("ascii"),
b"_" + transport.encode("ascii"),
domain])
answer = yield from repeated_query(
record,
dns.rdatatype.SRV,
**kwargs)
if answer is None:
return None
items = [
(rec.priority, rec.weight, (str(rec.target), rec.port))
for rec in answer
]
for i, (prio, weight, (host, port)) in enumerate(items):
if host == ".":
raise ValueError(
"protocol {!r} over {!r} not supported at {!r}".format(
service,
transport,
domain
)
)
items[i] = (prio, weight, (
host.rstrip(".").encode("ascii"),
port))
return items | python | def lookup_srv(
domain: bytes,
service: str,
transport: str = "tcp",
**kwargs):
"""
Query the DNS for SRV records describing how the given `service` over the
given `transport` is implemented for the given `domain`. `domain` must be
an IDNA-encoded :class:`bytes` object; `service` must be a normal
:class:`str`.
Keyword arguments are passed to :func:`repeated_query`.
Return a list of tuples ``(prio, weight, (hostname, port))``, where
`hostname` is a IDNA-encoded :class:`bytes` object containing the hostname
obtained from the SRV record. The other fields are also as obtained from
the SRV records. The trailing dot is stripped from the `hostname`.
If the DNS query returns an empty result, :data:`None` is returned. If any
of the found SRV records has the root zone (``.``) as `hostname`, this
indicates that the service is not available at the given `domain` and
:class:`ValueError` is raised.
"""
record = b".".join([
b"_" + service.encode("ascii"),
b"_" + transport.encode("ascii"),
domain])
answer = yield from repeated_query(
record,
dns.rdatatype.SRV,
**kwargs)
if answer is None:
return None
items = [
(rec.priority, rec.weight, (str(rec.target), rec.port))
for rec in answer
]
for i, (prio, weight, (host, port)) in enumerate(items):
if host == ".":
raise ValueError(
"protocol {!r} over {!r} not supported at {!r}".format(
service,
transport,
domain
)
)
items[i] = (prio, weight, (
host.rstrip(".").encode("ascii"),
port))
return items | Query the DNS for SRV records describing how the given `service` over the
given `transport` is implemented for the given `domain`. `domain` must be
an IDNA-encoded :class:`bytes` object; `service` must be a normal
:class:`str`.
Keyword arguments are passed to :func:`repeated_query`.
Return a list of tuples ``(prio, weight, (hostname, port))``, where
`hostname` is a IDNA-encoded :class:`bytes` object containing the hostname
obtained from the SRV record. The other fields are also as obtained from
the SRV records. The trailing dot is stripped from the `hostname`.
If the DNS query returns an empty result, :data:`None` is returned. If any
of the found SRV records has the root zone (``.``) as `hostname`, this
indicates that the service is not available at the given `domain` and
:class:`ValueError` is raised. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/network.py#L295-L351 |
horazont/aioxmpp | aioxmpp/network.py | lookup_tlsa | def lookup_tlsa(hostname, port, transport="tcp", require_ad=True, **kwargs):
"""
Query the DNS for TLSA records describing the certificates and/or keys to
expect when contacting `hostname` at the given `port` over the given
`transport`. `hostname` must be an IDNA-encoded :class:`bytes` object.
The keyword arguments are passed to :func:`repeated_query`; `require_ad`
defaults to :data:`True` here.
Return a list of tuples ``(usage, selector, mtype, cert)`` which contains
the information from the TLSA records.
If no data is returned by the query, :data:`None` is returned instead.
"""
record = b".".join([
b"_" + str(port).encode("ascii"),
b"_" + transport.encode("ascii"),
hostname
])
answer = yield from repeated_query(
record,
dns.rdatatype.TLSA,
require_ad=require_ad,
**kwargs)
if answer is None:
return None
items = [
(rec.usage, rec.selector, rec.mtype, rec.cert)
for rec in answer
]
return items | python | def lookup_tlsa(hostname, port, transport="tcp", require_ad=True, **kwargs):
"""
Query the DNS for TLSA records describing the certificates and/or keys to
expect when contacting `hostname` at the given `port` over the given
`transport`. `hostname` must be an IDNA-encoded :class:`bytes` object.
The keyword arguments are passed to :func:`repeated_query`; `require_ad`
defaults to :data:`True` here.
Return a list of tuples ``(usage, selector, mtype, cert)`` which contains
the information from the TLSA records.
If no data is returned by the query, :data:`None` is returned instead.
"""
record = b".".join([
b"_" + str(port).encode("ascii"),
b"_" + transport.encode("ascii"),
hostname
])
answer = yield from repeated_query(
record,
dns.rdatatype.TLSA,
require_ad=require_ad,
**kwargs)
if answer is None:
return None
items = [
(rec.usage, rec.selector, rec.mtype, rec.cert)
for rec in answer
]
return items | Query the DNS for TLSA records describing the certificates and/or keys to
expect when contacting `hostname` at the given `port` over the given
`transport`. `hostname` must be an IDNA-encoded :class:`bytes` object.
The keyword arguments are passed to :func:`repeated_query`; `require_ad`
defaults to :data:`True` here.
Return a list of tuples ``(usage, selector, mtype, cert)`` which contains
the information from the TLSA records.
If no data is returned by the query, :data:`None` is returned instead. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/network.py#L355-L389 |
horazont/aioxmpp | aioxmpp/network.py | group_and_order_srv_records | def group_and_order_srv_records(all_records, rng=None):
"""
Order a list of SRV record information (as returned by :func:`lookup_srv`)
and group and order them as specified by the RFC.
Return an iterable, yielding each ``(hostname, port)`` tuple inside the
SRV records in the order specified by the RFC. For hosts with the same
priority, the given `rng` implementation is used (if none is given, the
:mod:`random` module is used).
"""
rng = rng or random
all_records.sort(key=lambda x: x[:2])
for priority, records in itertools.groupby(
all_records,
lambda x: x[0]):
records = list(records)
total_weight = sum(
weight
for _, weight, _ in records)
while records:
if len(records) == 1:
yield records[0][-1]
break
value = rng.randint(0, total_weight)
running_weight_sum = 0
for i, (_, weight, addr) in enumerate(records):
running_weight_sum += weight
if running_weight_sum >= value:
yield addr
del records[i]
total_weight -= weight
break | python | def group_and_order_srv_records(all_records, rng=None):
"""
Order a list of SRV record information (as returned by :func:`lookup_srv`)
and group and order them as specified by the RFC.
Return an iterable, yielding each ``(hostname, port)`` tuple inside the
SRV records in the order specified by the RFC. For hosts with the same
priority, the given `rng` implementation is used (if none is given, the
:mod:`random` module is used).
"""
rng = rng or random
all_records.sort(key=lambda x: x[:2])
for priority, records in itertools.groupby(
all_records,
lambda x: x[0]):
records = list(records)
total_weight = sum(
weight
for _, weight, _ in records)
while records:
if len(records) == 1:
yield records[0][-1]
break
value = rng.randint(0, total_weight)
running_weight_sum = 0
for i, (_, weight, addr) in enumerate(records):
running_weight_sum += weight
if running_weight_sum >= value:
yield addr
del records[i]
total_weight -= weight
break | Order a list of SRV record information (as returned by :func:`lookup_srv`)
and group and order them as specified by the RFC.
Return an iterable, yielding each ``(hostname, port)`` tuple inside the
SRV records in the order specified by the RFC. For hosts with the same
priority, the given `rng` implementation is used (if none is given, the
:mod:`random` module is used). | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/network.py#L392-L428 |
horazont/aioxmpp | aioxmpp/service.py | add_handler_spec | def add_handler_spec(f, handler_spec, *, kwargs=None):
"""
Attach a handler specification (see :class:`HandlerSpec`) to a function.
:param f: Function to attach the handler specification to.
:param handler_spec: Handler specification to attach to the function.
:type handler_spec: :class:`HandlerSpec`
:param kwargs: additional keyword arguments passed to the function
carried in the handler spec.
:type kwargs: :class:`dict`
:raises ValueError: if the handler was registered with
different `kwargs` before
This uses a private attribute, whose exact name is an implementation
detail. The `handler_spec` is stored in a :class:`dict` bound to the
attribute.
.. versionadded:: 0.11
The `kwargs` argument. If two handlers with the same spec, but
different arguments are registered for one function, an error
will be raised. So you should always include all possible
arguments, this is the responsibility of the calling decorator.
"""
handler_dict = automake_magic_attr(f)
if kwargs is None:
kwargs = {}
if kwargs != handler_dict.setdefault(handler_spec, kwargs):
raise ValueError(
"The additional keyword arguments to the handler are incompatible") | python | def add_handler_spec(f, handler_spec, *, kwargs=None):
"""
Attach a handler specification (see :class:`HandlerSpec`) to a function.
:param f: Function to attach the handler specification to.
:param handler_spec: Handler specification to attach to the function.
:type handler_spec: :class:`HandlerSpec`
:param kwargs: additional keyword arguments passed to the function
carried in the handler spec.
:type kwargs: :class:`dict`
:raises ValueError: if the handler was registered with
different `kwargs` before
This uses a private attribute, whose exact name is an implementation
detail. The `handler_spec` is stored in a :class:`dict` bound to the
attribute.
.. versionadded:: 0.11
The `kwargs` argument. If two handlers with the same spec, but
different arguments are registered for one function, an error
will be raised. So you should always include all possible
arguments, this is the responsibility of the calling decorator.
"""
handler_dict = automake_magic_attr(f)
if kwargs is None:
kwargs = {}
if kwargs != handler_dict.setdefault(handler_spec, kwargs):
raise ValueError(
"The additional keyword arguments to the handler are incompatible") | Attach a handler specification (see :class:`HandlerSpec`) to a function.
:param f: Function to attach the handler specification to.
:param handler_spec: Handler specification to attach to the function.
:type handler_spec: :class:`HandlerSpec`
:param kwargs: additional keyword arguments passed to the function
carried in the handler spec.
:type kwargs: :class:`dict`
:raises ValueError: if the handler was registered with
different `kwargs` before
This uses a private attribute, whose exact name is an implementation
detail. The `handler_spec` is stored in a :class:`dict` bound to the
attribute.
.. versionadded:: 0.11
The `kwargs` argument. If two handlers with the same spec, but
different arguments are registered for one function, an error
will be raised. So you should always include all possible
arguments, this is the responsibility of the calling decorator. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L880-L910 |
horazont/aioxmpp | aioxmpp/service.py | iq_handler | def iq_handler(type_, payload_cls, *, with_send_reply=False):
"""
Register the decorated function or coroutine function as IQ request
handler.
:param type_: IQ type to listen for
:type type_: :class:`~.IQType`
:param payload_cls: Payload XSO class to listen for
:type payload_cls: :class:`~.XSO` subclass
:param with_send_reply: Whether to pass a function to send a reply
to the decorated callable as second argument.
:type with_send_reply: :class:`bool`
:raises ValueError: if `payload_cls` is not a registered IQ payload
If the decorated function is not a coroutine function, it must return an
awaitable instead.
.. seealso::
:meth:`~.StanzaStream.register_iq_request_handler` for more
details on the `type_`, `payload_cls` and
`with_send_reply` arguments, as well as behaviour expected
from the decorated function.
:meth:`aioxmpp.IQ.as_payload_class`
for a way to register a XSO as IQ payload
.. versionadded:: 0.11
The `with_send_reply` argument.
.. versionchanged:: 0.10
The decorator now checks if `payload_cls` is a valid, registered IQ
payload and raises :class:`ValueError` if not.
"""
if (not hasattr(payload_cls, "TAG") or
(aioxmpp.IQ.CHILD_MAP.get(payload_cls.TAG) is not
aioxmpp.IQ.payload.xq_descriptor) or
payload_cls not in aioxmpp.IQ.payload._classes):
raise ValueError(
"{!r} is not a valid IQ payload "
"(use IQ.as_payload_class decorator)".format(
payload_cls,
)
)
def decorator(f):
add_handler_spec(
f,
HandlerSpec(
(_apply_iq_handler, (type_, payload_cls)),
require_deps=(),
),
kwargs=dict(with_send_reply=with_send_reply),
)
return f
return decorator | python | def iq_handler(type_, payload_cls, *, with_send_reply=False):
"""
Register the decorated function or coroutine function as IQ request
handler.
:param type_: IQ type to listen for
:type type_: :class:`~.IQType`
:param payload_cls: Payload XSO class to listen for
:type payload_cls: :class:`~.XSO` subclass
:param with_send_reply: Whether to pass a function to send a reply
to the decorated callable as second argument.
:type with_send_reply: :class:`bool`
:raises ValueError: if `payload_cls` is not a registered IQ payload
If the decorated function is not a coroutine function, it must return an
awaitable instead.
.. seealso::
:meth:`~.StanzaStream.register_iq_request_handler` for more
details on the `type_`, `payload_cls` and
`with_send_reply` arguments, as well as behaviour expected
from the decorated function.
:meth:`aioxmpp.IQ.as_payload_class`
for a way to register a XSO as IQ payload
.. versionadded:: 0.11
The `with_send_reply` argument.
.. versionchanged:: 0.10
The decorator now checks if `payload_cls` is a valid, registered IQ
payload and raises :class:`ValueError` if not.
"""
if (not hasattr(payload_cls, "TAG") or
(aioxmpp.IQ.CHILD_MAP.get(payload_cls.TAG) is not
aioxmpp.IQ.payload.xq_descriptor) or
payload_cls not in aioxmpp.IQ.payload._classes):
raise ValueError(
"{!r} is not a valid IQ payload "
"(use IQ.as_payload_class decorator)".format(
payload_cls,
)
)
def decorator(f):
add_handler_spec(
f,
HandlerSpec(
(_apply_iq_handler, (type_, payload_cls)),
require_deps=(),
),
kwargs=dict(with_send_reply=with_send_reply),
)
return f
return decorator | Register the decorated function or coroutine function as IQ request
handler.
:param type_: IQ type to listen for
:type type_: :class:`~.IQType`
:param payload_cls: Payload XSO class to listen for
:type payload_cls: :class:`~.XSO` subclass
:param with_send_reply: Whether to pass a function to send a reply
to the decorated callable as second argument.
:type with_send_reply: :class:`bool`
:raises ValueError: if `payload_cls` is not a registered IQ payload
If the decorated function is not a coroutine function, it must return an
awaitable instead.
.. seealso::
:meth:`~.StanzaStream.register_iq_request_handler` for more
details on the `type_`, `payload_cls` and
`with_send_reply` arguments, as well as behaviour expected
from the decorated function.
:meth:`aioxmpp.IQ.as_payload_class`
for a way to register a XSO as IQ payload
.. versionadded:: 0.11
The `with_send_reply` argument.
.. versionchanged:: 0.10
The decorator now checks if `payload_cls` is a valid, registered IQ
payload and raises :class:`ValueError` if not. | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1001-L1060 |
horazont/aioxmpp | aioxmpp/service.py | message_handler | def message_handler(type_, from_):
"""
Deprecated alias of :func:`.dispatcher.message_handler`.
.. deprecated:: 0.9
"""
import aioxmpp.dispatcher
return aioxmpp.dispatcher.message_handler(type_, from_) | python | def message_handler(type_, from_):
"""
Deprecated alias of :func:`.dispatcher.message_handler`.
.. deprecated:: 0.9
"""
import aioxmpp.dispatcher
return aioxmpp.dispatcher.message_handler(type_, from_) | Deprecated alias of :func:`.dispatcher.message_handler`.
.. deprecated:: 0.9 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1063-L1070 |
horazont/aioxmpp | aioxmpp/service.py | presence_handler | def presence_handler(type_, from_):
"""
Deprecated alias of :func:`.dispatcher.presence_handler`.
.. deprecated:: 0.9
"""
import aioxmpp.dispatcher
return aioxmpp.dispatcher.presence_handler(type_, from_) | python | def presence_handler(type_, from_):
"""
Deprecated alias of :func:`.dispatcher.presence_handler`.
.. deprecated:: 0.9
"""
import aioxmpp.dispatcher
return aioxmpp.dispatcher.presence_handler(type_, from_) | Deprecated alias of :func:`.dispatcher.presence_handler`.
.. deprecated:: 0.9 | https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/service.py#L1073-L1080 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.