index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
9,014
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/__init__.py
|
from . import aio
from . import glib
from .constants import (BusType, MessageType, MessageFlag, NameFlag, RequestNameReply,
ReleaseNameReply, PropertyAccess, ArgDirection, ErrorType)
from .errors import (SignatureBodyMismatchError, InvalidSignatureError, InvalidAddressError,
AuthError, InvalidMessageError, InvalidIntrospectionError,
InterfaceNotFoundError, SignalDisabledError, InvalidBusNameError,
InvalidObjectPathError, InvalidInterfaceNameError, InvalidMemberNameError,
DBusError)
from . import introspection
from .message import Message
from . import message_bus
from . import proxy_object
from . import service
from .signature import SignatureType, SignatureTree, Variant
from .validators import (is_bus_name_valid, is_object_path_valid, is_interface_name_valid,
is_member_name_valid, assert_bus_name_valid, assert_object_path_valid,
assert_interface_name_valid, assert_member_name_valid)
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,015
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/validators.py
|
import re
from .errors import InvalidBusNameError, InvalidObjectPathError, InvalidInterfaceNameError, InvalidMemberNameError
from functools import lru_cache
_bus_name_re = re.compile(r'^[A-Za-z_-][A-Za-z0-9_-]*$')
_path_re = re.compile(r'^[A-Za-z0-9_]+$')
_element_re = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')
_member_re = re.compile(r'^[A-Za-z_][A-Za-z0-9_-]*$')
@lru_cache(maxsize=32)
def is_bus_name_valid(name: str) -> bool:
"""Whether this is a valid bus name.
.. seealso:: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-bus
:param name: The bus name to validate.
:type name: str
:returns: Whether the name is a valid bus name.
:rtype: bool
"""
if not isinstance(name, str):
return False
if not name or len(name) > 255:
return False
if name.startswith(':'):
# a unique bus name
return True
if name.startswith('.'):
return False
if name.find('.') == -1:
return False
for element in name.split('.'):
if _bus_name_re.search(element) is None:
return False
return True
@lru_cache(maxsize=1024)
def is_object_path_valid(path: str) -> bool:
"""Whether this is a valid object path.
.. seealso:: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling-object-path
:param path: The object path to validate.
:type path: str
:returns: Whether the object path is valid.
:rtype: bool
"""
if not isinstance(path, str):
return False
if not path:
return False
if not path.startswith('/'):
return False
if len(path) == 1:
return True
for element in path[1:].split('/'):
if _path_re.search(element) is None:
return False
return True
@lru_cache(maxsize=32)
def is_interface_name_valid(name: str) -> bool:
"""Whether this is a valid interface name.
.. seealso:: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-interface
:param name: The interface name to validate.
:type name: str
:returns: Whether the name is a valid interface name.
:rtype: bool
"""
if not isinstance(name, str):
return False
if not name or len(name) > 255:
return False
if name.startswith('.'):
return False
if name.find('.') == -1:
return False
for element in name.split('.'):
if _element_re.search(element) is None:
return False
return True
@lru_cache(maxsize=512)
def is_member_name_valid(member: str) -> bool:
"""Whether this is a valid member name.
.. seealso:: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-member
:param member: The member name to validate.
:type member: str
:returns: Whether the name is a valid member name.
:rtype: bool
"""
if not isinstance(member, str):
return False
if not member or len(member) > 255:
return False
if _member_re.search(member) is None:
return False
return True
def assert_bus_name_valid(name: str):
"""Raise an error if this is not a valid bus name.
.. seealso:: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-bus
:param name: The bus name to validate.
:type name: str
:raises:
- :class:`InvalidBusNameError` - If this is not a valid bus name.
"""
if not is_bus_name_valid(name):
raise InvalidBusNameError(name)
def assert_object_path_valid(path: str):
"""Raise an error if this is not a valid object path.
.. seealso:: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-marshaling-object-path
:param path: The object path to validate.
:type path: str
:raises:
- :class:`InvalidObjectPathError` - If this is not a valid object path.
"""
if not is_object_path_valid(path):
raise InvalidObjectPathError(path)
def assert_interface_name_valid(name: str):
"""Raise an error if this is not a valid interface name.
.. seealso:: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-interface
:param name: The interface name to validate.
:type name: str
:raises:
- :class:`InvalidInterfaceNameError` - If this is not a valid object path.
"""
if not is_interface_name_valid(name):
raise InvalidInterfaceNameError(name)
def assert_member_name_valid(member):
"""Raise an error if this is not a valid member name.
.. seealso:: https://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-names-member
:param member: The member name to validate.
:type member: str
:raises:
- :class:`InvalidMemberNameError` - If this is not a valid object path.
"""
if not is_member_name_valid(member):
raise InvalidMemberNameError(member)
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,016
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/test/test_introspection.py
|
from dbus_next import introspection as intr, ArgDirection, PropertyAccess, SignatureType
import os
example_data = open(f'{os.path.dirname(__file__)}/data/introspection.xml', 'r').read()
def test_example_introspection_from_xml():
node = intr.Node.parse(example_data)
assert len(node.interfaces) == 1
interface = node.interfaces[0]
assert len(node.nodes) == 2
assert len(interface.methods) == 3
assert len(interface.signals) == 2
assert len(interface.properties) == 1
assert type(node.nodes[0]) is intr.Node
assert node.nodes[0].name == 'child_of_sample_object'
assert type(node.nodes[1]) is intr.Node
assert node.nodes[1].name == 'another_child_of_sample_object'
assert interface.name == 'com.example.SampleInterface0'
frobate = interface.methods[0]
assert type(frobate) is intr.Method
assert frobate.name == 'Frobate'
assert len(frobate.in_args) == 1
assert len(frobate.out_args) == 2
foo = frobate.in_args[0]
assert type(foo) is intr.Arg
assert foo.name == 'foo'
assert foo.direction == ArgDirection.IN
assert foo.signature == 'i'
assert type(foo.type) is SignatureType
assert foo.type.token == 'i'
bar = frobate.out_args[0]
assert type(bar) is intr.Arg
assert bar.name == 'bar'
assert bar.direction == ArgDirection.OUT
assert bar.signature == 's'
assert type(bar.type) is SignatureType
assert bar.type.token == 's'
prop = interface.properties[0]
assert type(prop) is intr.Property
assert prop.name == 'Bar'
assert prop.signature == 'y'
assert type(prop.type) is SignatureType
assert prop.type.token == 'y'
assert prop.access == PropertyAccess.WRITE
changed = interface.signals[0]
assert type(changed) is intr.Signal
assert changed.name == 'Changed'
assert len(changed.args) == 1
new_value = changed.args[0]
assert type(new_value) is intr.Arg
assert new_value.name == 'new_value'
assert new_value.signature == 'b'
def test_example_introspection_to_xml():
node = intr.Node.parse(example_data)
tree = node.to_xml()
assert tree.tag == 'node'
assert tree.attrib.get('name') == '/com/example/sample_object0'
assert len(tree) == 3
interface = tree[0]
assert interface.tag == 'interface'
assert interface.get('name') == 'com.example.SampleInterface0'
assert len(interface) == 6
method = interface[0]
assert method.tag == 'method'
assert method.get('name') == 'Frobate'
# TODO annotations
assert len(method) == 3
arg = method[0]
assert arg.tag == 'arg'
assert arg.attrib.get('name') == 'foo'
assert arg.attrib.get('type') == 'i'
assert arg.attrib.get('direction') == 'in'
signal = interface[3]
assert signal.tag == 'signal'
assert signal.attrib.get('name') == 'Changed'
assert len(signal) == 1
arg = signal[0]
assert arg.tag == 'arg'
assert arg.attrib.get('name') == 'new_value'
assert arg.attrib.get('type') == 'b'
signal = interface[4]
assert signal.tag == 'signal'
assert signal.attrib.get('name') == 'ChangedMulti'
assert len(signal) == 2
arg = signal[0]
assert arg.tag == 'arg'
assert arg.attrib.get('name') == 'new_value1'
assert arg.attrib.get('type') == 'b'
arg = signal[1]
assert arg.tag == 'arg'
assert arg.attrib.get('name') == 'new_value2'
assert arg.attrib.get('type') == 'y'
prop = interface[5]
assert prop.attrib.get('name') == 'Bar'
assert prop.attrib.get('type') == 'y'
assert prop.attrib.get('access') == 'write'
def test_default_interfaces():
# just make sure it doesn't throw
default = intr.Node.default()
assert type(default) is intr.Node
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,017
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/constants.py
|
from enum import Enum, IntFlag
class BusType(Enum):
"""An enum that indicates a type of bus. On most systems, there are
normally two different kinds of buses running.
"""
SESSION = 1 #: A bus for the current graphical user session.
SYSTEM = 2 #: A persistent bus for the whole machine.
class MessageType(Enum):
"""An enum that indicates a type of message."""
METHOD_CALL = 1 #: An outgoing method call.
METHOD_RETURN = 2 #: A return to a previously sent method call
ERROR = 3 #: A return to a method call that has failed
SIGNAL = 4 #: A broadcast signal to subscribed connections
MESSAGE_TYPE_MAP = {field.value: field for field in MessageType}
class MessageFlag(IntFlag):
"""Flags that affect the behavior of sent and received messages
"""
NONE = 0
NO_REPLY_EXPECTED = 1 #: The method call does not expect a method return.
NO_AUTOSTART = 2
ALLOW_INTERACTIVE_AUTHORIZATION = 4
MESSAGE_FLAG_MAP = {field.value: field for field in MessageFlag}
class NameFlag(IntFlag):
"""A flag that affects the behavior of a name request.
"""
NONE = 0
ALLOW_REPLACEMENT = 1 #: If another client requests this name, let them have it.
REPLACE_EXISTING = 2 #: If another client owns this name, try to take it.
DO_NOT_QUEUE = 4 #: Name requests normally queue and wait for the owner to release the name. Do not enter this queue.
class RequestNameReply(Enum):
"""An enum that describes the result of a name request.
"""
PRIMARY_OWNER = 1 #: The bus owns the name.
IN_QUEUE = 2 #: The bus is in a queue and may receive the name after it is relased by the primary owner.
EXISTS = 3 #: The name has an owner and NameFlag.DO_NOT_QUEUE was given.
ALREADY_OWNER = 4 #: The bus already owns the name.
class ReleaseNameReply(Enum):
"""An enum that describes the result of a name release request
"""
RELEASED = 1
NON_EXISTENT = 2
NOT_OWNER = 3
class PropertyAccess(Enum):
"""An enum that describes whether a DBus property can be gotten or set with
the ``org.freedesktop.DBus.Properties`` interface.
"""
READ = 'read' #: The property is readonly.
WRITE = 'write' #: The property is writeonly.
READWRITE = 'readwrite' #: The property can be read or written to.
def readable(self):
"""Get whether the property can be read.
"""
return self == PropertyAccess.READ or self == PropertyAccess.READWRITE
def writable(self):
"""Get whether the property can be written to.
"""
return self == PropertyAccess.WRITE or self == PropertyAccess.READWRITE
class ArgDirection(Enum):
"""For an introspected argument, indicates whether it is an input parameter or a return value.
"""
IN = 'in'
OUT = 'out'
class ErrorType(Enum):
"""An enum for the type of an error for a message reply.
:seealso: http://man7.org/linux/man-pages/man3/sd-bus-errors.3.html
"""
SERVICE_ERROR = 'com.dubstepdish.dbus.next.ServiceError' #: A custom error to indicate an exported service threw an exception.
INTERNAL_ERROR = 'com.dubstepdish.dbus.next.InternalError' #: A custom error to indicate something went wrong with the library.
CLIENT_ERROR = 'com.dubstepdish.dbus.next.ClientError' #: A custom error to indicate something went wrong with the client.
FAILED = "org.freedesktop.DBus.Error.Failed"
NO_MEMORY = "org.freedesktop.DBus.Error.NoMemory"
SERVICE_UNKNOWN = "org.freedesktop.DBus.Error.ServiceUnknown"
NAME_HAS_NO_OWNER = "org.freedesktop.DBus.Error.NameHasNoOwner"
NO_REPLY = "org.freedesktop.DBus.Error.NoReply"
IO_ERROR = "org.freedesktop.DBus.Error.IOError"
BAD_ADDRESS = "org.freedesktop.DBus.Error.BadAddress"
NOT_SUPPORTED = "org.freedesktop.DBus.Error.NotSupported"
LIMITS_EXCEEDED = "org.freedesktop.DBus.Error.LimitsExceeded"
ACCESS_DENIED = "org.freedesktop.DBus.Error.AccessDenied"
AUTH_FAILED = "org.freedesktop.DBus.Error.AuthFailed"
NO_SERVER = "org.freedesktop.DBus.Error.NoServer"
TIMEOUT = "org.freedesktop.DBus.Error.Timeout"
NO_NETWORK = "org.freedesktop.DBus.Error.NoNetwork"
ADDRESS_IN_USE = "org.freedesktop.DBus.Error.AddressInUse"
DISCONNECTED = "org.freedesktop.DBus.Error.Disconnected"
INVALID_ARGS = "org.freedesktop.DBus.Error.InvalidArgs"
FILE_NOT_FOUND = "org.freedesktop.DBus.Error.FileNotFound"
FILE_EXISTS = "org.freedesktop.DBus.Error.FileExists"
UNKNOWN_METHOD = "org.freedesktop.DBus.Error.UnknownMethod"
UNKNOWN_OBJECT = "org.freedesktop.DBus.Error.UnknownObject"
UNKNOWN_INTERFACE = "org.freedesktop.DBus.Error.UnknownInterface"
UNKNOWN_PROPERTY = "org.freedesktop.DBus.Error.UnknownProperty"
PROPERTY_READ_ONLY = "org.freedesktop.DBus.Error.PropertyReadOnly"
UNIX_PROCESS_ID_UNKNOWN = "org.freedesktop.DBus.Error.UnixProcessIdUnknown"
INVALID_SIGNATURE = "org.freedesktop.DBus.Error.InvalidSignature"
INCONSISTENT_MESSAGE = "org.freedesktop.DBus.Error.InconsistentMessage"
MATCH_RULE_NOT_FOUND = "org.freedesktop.DBus.Error.MatchRuleNotFound"
MATCH_RULE_INVALID = "org.freedesktop.DBus.Error.MatchRuleInvalid"
INTERACTIVE_AUTHORIZATION_REQUIRED = "org.freedesktop.DBus.Error.InteractiveAuthorizationRequired"
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,018
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/examples/example-service.py
|
#!/usr/bin/env python3
import sys
import os
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/..'))
from dbus_next.service import ServiceInterface, method, signal, dbus_property
from dbus_next.aio.message_bus import MessageBus
from dbus_next import Variant
import asyncio
class ExampleInterface(ServiceInterface):
def __init__(self, name):
super().__init__(name)
self._string_prop = 'kevin'
@method()
def Echo(self, what: 's') -> 's':
return what
@method()
def EchoMultiple(self, what1: 's', what2: 's') -> 'ss':
return [what1, what2]
@method()
def GetVariantDict(self) -> 'a{sv}':
return {
'foo': Variant('s', 'bar'),
'bat': Variant('x', -55),
'a_list': Variant('as', ['hello', 'world'])
}
@dbus_property(name='StringProp')
def string_prop(self) -> 's':
return self._string_prop
@string_prop.setter
def string_prop_setter(self, val: 's'):
self._string_prop = val
@signal()
def signal_simple(self) -> 's':
return 'hello'
@signal()
def signal_multiple(self) -> 'ss':
return ['hello', 'world']
async def main():
name = 'dbus.next.example.service'
path = '/example/path'
interface_name = 'example.interface'
bus = await MessageBus().connect()
interface = ExampleInterface(interface_name)
bus.export('/example/path', interface)
await bus.request_name(name)
print(f'service up on name: "{name}", path: "{path}", interface: "{interface_name}"')
await bus.wait_for_disconnect()
asyncio.get_event_loop().run_until_complete(main())
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,019
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/__version__.py
|
__title__ = 'dbus_next'
__description__ = 'A zero-dependency DBus library for Python with asyncio support'
__url__ = 'https://github.com/altdesktop/python-dbus-next'
__version__ = '0.2.3'
__author__ = 'Tony Crisci'
__author_email__ = 'tony@dubstepdish.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019 Tony Crisci'
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,020
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/aio/proxy_object.py
|
from ..proxy_object import BaseProxyObject, BaseProxyInterface
from ..message_bus import BaseMessageBus
from ..message import Message, MessageFlag
from ..signature import Variant
from ..errors import DBusError
from ..constants import ErrorType
from .._private.util import replace_idx_with_fds, replace_fds_with_idx
from .. import introspection as intr
import xml.etree.ElementTree as ET
from typing import Union, List
class ProxyInterface(BaseProxyInterface):
"""A class representing a proxy to an interface exported on the bus by
another client for the asyncio :class:`MessageBus
<dbus_next.aio.MessageBus>` implementation.
This class is not meant to be constructed directly by the user. Use
:func:`ProxyObject.get_interface()
<dbus_next.aio.ProxyObject.get_interface>` on a asyncio proxy object to get
a proxy interface.
This class exposes methods to call DBus methods, listen to signals, and get
and set properties on the interface that are created dynamically based on
the introspection data passed to the proxy object that made this proxy
interface.
A *method call* takes this form:
.. code-block:: python3
result = await interface.call_[METHOD](*args)
Where ``METHOD`` is the name of the method converted to snake case.
DBus methods are exposed as coroutines that take arguments that correpond
to the *in args* of the interface method definition and return a ``result``
that corresponds to the *out arg*. If the method has more than one out arg,
they are returned within a :class:`list`.
To *listen to a signal* use this form:
.. code-block:: python3
interface.on_[SIGNAL](callback)
To *stop listening to a signal* use this form:
.. code-block:: python3
interface.off_[SIGNAL](callback)
Where ``SIGNAL`` is the name of the signal converted to snake case.
DBus signals are exposed with an event-callback interface. The provided
``callback`` will be called when the signal is emitted with arguments that
correspond to the *out args* of the interface signal definition.
To *get or set a property* use this form:
.. code-block:: python3
value = await interface.get_[PROPERTY]()
await interface.set_[PROPERTY](value)
Where ``PROPERTY`` is the name of the property converted to snake case.
DBus property getters and setters are exposed as coroutines. The ``value``
must correspond to the type of the property in the interface definition.
If the service returns an error for a DBus call, a :class:`DBusError
<dbus_next.DBusError>` will be raised with information about the error.
"""
def _add_method(self, intr_method):
async def method_fn(*args, flags=MessageFlag.NONE):
input_body, unix_fds = replace_fds_with_idx(intr_method.in_signature, list(args))
msg = await self.bus.call(
Message(destination=self.bus_name,
path=self.path,
interface=self.introspection.name,
member=intr_method.name,
signature=intr_method.in_signature,
body=input_body,
flags=flags,
unix_fds=unix_fds))
if flags & MessageFlag.NO_REPLY_EXPECTED:
return None
BaseProxyInterface._check_method_return(msg, intr_method.out_signature)
out_len = len(intr_method.out_args)
body = replace_idx_with_fds(msg.signature_tree, msg.body, msg.unix_fds)
if not out_len:
return None
elif out_len == 1:
return body[0]
else:
return body
method_name = f'call_{BaseProxyInterface._to_snake_case(intr_method.name)}'
setattr(self, method_name, method_fn)
def _add_property(self, intr_property):
async def property_getter():
msg = await self.bus.call(
Message(destination=self.bus_name,
path=self.path,
interface='org.freedesktop.DBus.Properties',
member='Get',
signature='ss',
body=[self.introspection.name, intr_property.name]))
BaseProxyInterface._check_method_return(msg, 'v')
variant = msg.body[0]
if variant.signature != intr_property.signature:
raise DBusError(ErrorType.CLIENT_ERROR,
f'property returned unexpected signature "{variant.signature}"',
msg)
return replace_idx_with_fds('v', msg.body, msg.unix_fds)[0].value
async def property_setter(val):
variant = Variant(intr_property.signature, val)
body, unix_fds = replace_fds_with_idx(
'ssv', [self.introspection.name, intr_property.name, variant])
msg = await self.bus.call(
Message(destination=self.bus_name,
path=self.path,
interface='org.freedesktop.DBus.Properties',
member='Set',
signature='ssv',
body=body,
unix_fds=unix_fds))
BaseProxyInterface._check_method_return(msg)
snake_case = BaseProxyInterface._to_snake_case(intr_property.name)
setattr(self, f'get_{snake_case}', property_getter)
setattr(self, f'set_{snake_case}', property_setter)
class ProxyObject(BaseProxyObject):
"""The proxy object implementation for the GLib :class:`MessageBus <dbus_next.glib.MessageBus>`.
For more information, see the :class:`BaseProxyObject <dbus_next.proxy_object.BaseProxyObject>`.
"""
def __init__(self, bus_name: str, path: str, introspection: Union[intr.Node, str, ET.Element],
bus: BaseMessageBus):
super().__init__(bus_name, path, introspection, bus, ProxyInterface)
def get_interface(self, name: str) -> ProxyInterface:
return super().get_interface(name)
def get_children(self) -> List['ProxyObject']:
return super().get_children()
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,021
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/test/test_aio_low_level.py
|
from dbus_next.aio import MessageBus
from dbus_next import Message, MessageType, MessageFlag
import pytest
@pytest.mark.asyncio
async def test_standard_interfaces():
bus = await MessageBus().connect()
msg = Message(destination='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus',
member='ListNames',
serial=bus.next_serial())
reply = await bus.call(msg)
assert reply.message_type == MessageType.METHOD_RETURN
assert reply.reply_serial == msg.serial
assert reply.signature == 'as'
assert bus.unique_name in reply.body[0]
msg.interface = 'org.freedesktop.DBus.Introspectable'
msg.member = 'Introspect'
msg.serial = bus.next_serial()
reply = await bus.call(msg)
assert reply.message_type == MessageType.METHOD_RETURN
assert reply.reply_serial == msg.serial
assert reply.signature == 's'
assert type(reply.body[0]) is str
msg.member = 'MemberDoesNotExist'
msg.serial = bus.next_serial()
reply = await bus.call(msg)
assert reply.message_type == MessageType.ERROR
assert reply.reply_serial == msg.serial
assert reply.error_name
assert reply.signature == 's'
assert type(reply.body[0]) is str
@pytest.mark.asyncio
async def test_sending_messages_between_buses():
bus1 = await MessageBus().connect()
bus2 = await MessageBus().connect()
msg = Message(destination=bus1.unique_name,
path='/org/test/path',
interface='org.test.iface',
member='SomeMember',
serial=bus2.next_serial())
def message_handler(sent):
if sent.sender == bus2.unique_name and sent.serial == msg.serial:
assert sent.path == msg.path
assert sent.serial == msg.serial
assert sent.interface == msg.interface
assert sent.member == msg.member
bus1.send(Message.new_method_return(sent, 's', ['got it']))
bus1.remove_message_handler(message_handler)
return True
bus1.add_message_handler(message_handler)
reply = await bus2.call(msg)
assert reply.message_type == MessageType.METHOD_RETURN
assert reply.sender == bus1.unique_name
assert reply.signature == 's'
assert reply.body == ['got it']
assert reply.reply_serial == msg.serial
def message_handler_error(sent):
if sent.sender == bus2.unique_name and sent.serial == msg.serial:
assert sent.path == msg.path
assert sent.serial == msg.serial
assert sent.interface == msg.interface
assert sent.member == msg.member
bus1.send(Message.new_error(sent, 'org.test.Error', 'throwing an error'))
bus1.remove_message_handler(message_handler_error)
return True
bus1.add_message_handler(message_handler_error)
msg.serial = bus2.next_serial()
reply = await bus2.call(msg)
assert reply.message_type == MessageType.ERROR
assert reply.sender == bus1.unique_name
assert reply.reply_serial == msg.serial
assert reply.error_name == 'org.test.Error'
assert reply.signature == 's'
assert reply.body == ['throwing an error']
msg.serial = bus2.next_serial()
msg.flags = MessageFlag.NO_REPLY_EXPECTED
reply = await bus2.call(msg)
assert reply is None
@pytest.mark.asyncio
async def test_sending_signals_between_buses(event_loop):
bus1 = await MessageBus().connect()
bus2 = await MessageBus().connect()
add_match_msg = Message(destination='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus',
member='AddMatch',
signature='s',
body=[f'sender={bus2.unique_name}'])
await bus1.call(add_match_msg)
async def wait_for_message():
future = event_loop.create_future()
def message_handler(signal):
if signal.sender == bus2.unique_name:
bus1.remove_message_handler(message_handler)
future.set_result(signal)
bus1.add_message_handler(message_handler)
return await future
bus2.send(
Message.new_signal('/org/test/path', 'org.test.interface', 'SomeSignal', 's', ['a signal']))
signal = await wait_for_message()
assert signal.message_type == MessageType.SIGNAL
assert signal.path == '/org/test/path'
assert signal.interface == 'org.test.interface'
assert signal.member == 'SomeSignal'
assert signal.signature == 's'
assert signal.body == ['a signal']
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,022
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/_private/util.py
|
from typing import List, Any, Union
import inspect
from ..signature import SignatureTree, Variant
import ast
def signature_contains_type(signature: Union[str, SignatureTree], body: List[Any],
token: str) -> bool:
'''For a given signature and body, check to see if it contains any members
with the given token'''
if type(signature) is str:
signature = SignatureTree._get(signature)
queue = []
contains_variants = False
for st in signature.types:
queue.append(st)
while True:
if not queue:
break
st = queue.pop()
if st.token == token:
return True
elif st.token == 'v':
contains_variants = True
queue.extend(st.children)
if not contains_variants:
return False
for member in body:
queue.append(member)
while True:
if not queue:
return False
member = queue.pop()
if type(member) is Variant and \
signature_contains_type(member.signature, [member.value], token):
return True
elif type(member) is list:
queue.extend(member)
elif type(member) is dict:
queue.extend(member.values())
def replace_fds_with_idx(signature: Union[str, SignatureTree],
body: List[Any]) -> (List[Any], List[int]):
'''Take the high level body format and convert it into the low level body
format. Type 'h' refers directly to the fd in the body. Replace that with
an index and return the corresponding list of unix fds that can be set on
the Message'''
if type(signature) is str:
signature = SignatureTree._get(signature)
if not signature_contains_type(signature, body, 'h'):
return body, []
unix_fds = []
def _replace(fd):
try:
return unix_fds.index(fd)
except ValueError:
unix_fds.append(fd)
return len(unix_fds) - 1
_replace_fds(body, signature.types, _replace)
return body, unix_fds
def replace_idx_with_fds(signature: Union[str, SignatureTree], body: List[Any],
unix_fds: List[int]) -> List[Any]:
'''Take the low level body format and return the high level body format.
Type 'h' refers to an index in the unix_fds array. Replace those with the
actual file descriptor or `None` if one does not exist.'''
if type(signature) is str:
signature = SignatureTree._get(signature)
if not signature_contains_type(signature, body, 'h'):
return body
def _replace(idx):
try:
return unix_fds[idx]
except IndexError:
return None
_replace_fds(body, signature.types, _replace)
return body
def parse_annotation(annotation: str) -> str:
'''
Because of PEP 563, if `from __future__ import annotations` is used in code
or on Python version >=3.10 where this is the default, return annotations
from the `inspect` module will return annotations as "forward definitions".
In this case, we must eval the result which we do only when given a string
constant.
'''
def raise_value_error():
raise ValueError(f'service annotations must be a string constant (got {annotation})')
if not annotation or annotation is inspect.Signature.empty:
return ''
if type(annotation) is not str:
raise_value_error()
try:
body = ast.parse(annotation).body
if len(body) == 1 and type(body[0].value) is ast.Constant:
if type(body[0].value.value) is not str:
raise_value_error()
return body[0].value.value
except SyntaxError:
pass
return annotation
def _replace_fds(body_obj: List[Any], children, replace_fn):
'''Replace any type 'h' with the value returned by replace_fn() given the
value of the fd field. This is used by the high level interfaces which
allow type 'h' to be the fd directly instead of an index in an external
array such as in the spec.'''
for index, st in enumerate(children):
if not any(sig in st.signature for sig in 'hv'):
continue
if st.signature == 'h':
body_obj[index] = replace_fn(body_obj[index])
elif st.token == 'a':
if st.children[0].token == '{':
_replace_fds(body_obj[index], st.children, replace_fn)
else:
for i, child in enumerate(body_obj[index]):
if st.signature == 'ah':
body_obj[index][i] = replace_fn(child)
else:
_replace_fds([child], st.children, replace_fn)
elif st.token in '(':
_replace_fds(body_obj[index], st.children, replace_fn)
elif st.token in '{':
for key, value in list(body_obj.items()):
body_obj.pop(key)
if st.children[0].signature == 'h':
key = replace_fn(key)
if st.children[1].signature == 'h':
value = replace_fn(value)
else:
_replace_fds([value], [st.children[1]], replace_fn)
body_obj[key] = value
elif st.signature == 'v':
if body_obj[index].signature == 'h':
body_obj[index].value = replace_fn(body_obj[index].value)
else:
_replace_fds([body_obj[index].value], [body_obj[index].type], replace_fn)
elif st.children:
_replace_fds(body_obj[index], st.children, replace_fn)
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,023
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/examples/aio-list-names.py
|
#!/usr/bin/env python3
import sys
import os
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/..'))
from dbus_next import Message, MessageType
from dbus_next.aio import MessageBus
import asyncio
import json
loop = asyncio.get_event_loop()
async def main():
bus = await MessageBus().connect()
reply = await bus.call(
Message(destination='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus',
member='ListNames'))
if reply.message_type == MessageType.ERROR:
raise Exception(reply.body[0])
print(json.dumps(reply.body[0], indent=2))
loop.run_until_complete(main())
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,024
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/test/service/test_decorators.py
|
from dbus_next import PropertyAccess, introspection as intr
from dbus_next.service import method, signal, dbus_property, ServiceInterface
class ExampleInterface(ServiceInterface):
def __init__(self):
super().__init__('test.interface')
self._some_prop = 55
self._another_prop = 101
self._weird_prop = 500
@method()
def some_method(self, one: 's', two: 's') -> 's':
return 'hello'
@method(name='renamed_method', disabled=True)
def another_method(self, eight: 'o', six: 't'):
pass
@signal()
def some_signal(self) -> 'as':
return ['result']
@signal(name='renamed_signal', disabled=True)
def another_signal(self) -> '(dodo)':
return [1, '/', 1, '/']
@dbus_property(name='renamed_readonly_property', access=PropertyAccess.READ, disabled=True)
def another_prop(self) -> 't':
return self._another_prop
@dbus_property()
def some_prop(self) -> 'u':
return self._some_prop
@some_prop.setter
def some_prop(self, val: 'u'):
self._some_prop = val + 1
# for this one, the setter has a different name than the getter which is a
# special case in the code
@dbus_property()
def weird_prop(self) -> 't':
return self._weird_prop
@weird_prop.setter
def setter_for_weird_prop(self, val: 't'):
self._weird_prop = val
def test_method_decorator():
interface = ExampleInterface()
assert interface.name == 'test.interface'
properties = ServiceInterface._get_properties(interface)
methods = ServiceInterface._get_methods(interface)
signals = ServiceInterface._get_signals(interface)
assert len(methods) == 2
method = methods[0]
assert method.name == 'renamed_method'
assert method.in_signature == 'ot'
assert method.out_signature == ''
assert method.disabled
assert type(method.introspection) is intr.Method
method = methods[1]
assert method.name == 'some_method'
assert method.in_signature == 'ss'
assert method.out_signature == 's'
assert not method.disabled
assert type(method.introspection) is intr.Method
assert len(signals) == 2
signal = signals[0]
assert signal.name == 'renamed_signal'
assert signal.signature == '(dodo)'
assert signal.disabled
assert type(signal.introspection) is intr.Signal
signal = signals[1]
assert signal.name == 'some_signal'
assert signal.signature == 'as'
assert not signal.disabled
assert type(signal.introspection) is intr.Signal
assert len(properties) == 3
renamed_readonly_prop = properties[0]
assert renamed_readonly_prop.name == 'renamed_readonly_property'
assert renamed_readonly_prop.signature == 't'
assert renamed_readonly_prop.access == PropertyAccess.READ
assert renamed_readonly_prop.disabled
assert type(renamed_readonly_prop.introspection) is intr.Property
weird_prop = properties[1]
assert weird_prop.name == 'weird_prop'
assert weird_prop.access == PropertyAccess.READWRITE
assert weird_prop.signature == 't'
assert not weird_prop.disabled
assert weird_prop.prop_getter is not None
assert weird_prop.prop_getter.__name__ == 'weird_prop'
assert weird_prop.prop_setter is not None
assert weird_prop.prop_setter.__name__ == 'setter_for_weird_prop'
assert type(weird_prop.introspection) is intr.Property
prop = properties[2]
assert prop.name == 'some_prop'
assert prop.access == PropertyAccess.READWRITE
assert prop.signature == 'u'
assert not prop.disabled
assert prop.prop_getter is not None
assert prop.prop_setter is not None
assert type(prop.introspection) is intr.Property
# make sure the getter and setter actually work
assert interface._some_prop == 55
interface._some_prop = 555
assert interface.some_prop == 555
assert interface._weird_prop == 500
assert weird_prop.prop_getter(interface) == 500
interface._weird_prop = 1001
assert interface._weird_prop == 1001
weird_prop.prop_setter(interface, 600)
assert interface._weird_prop == 600
def test_interface_introspection():
interface = ExampleInterface()
intr_interface = interface.introspect()
assert type(intr_interface) is intr.Interface
xml = intr_interface.to_xml()
assert xml.tag == 'interface'
assert xml.attrib.get('name', None) == 'test.interface'
methods = xml.findall('method')
signals = xml.findall('signal')
properties = xml.findall('property')
assert len(xml) == 4
assert len(methods) == 1
assert len(signals) == 1
assert len(properties) == 2
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,025
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/examples/dbus-next-send.py
|
#!/usr/bin/env python3
import sys
import os
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/..'))
from dbus_next.validators import (is_bus_name_valid, is_member_name_valid, is_object_path_valid,
is_interface_name_valid)
from dbus_next.aio import MessageBus
from dbus_next import MessageType, BusType, Message, Variant
from argparse import ArgumentParser, OPTIONAL
import json
import asyncio
parser = ArgumentParser()
parser.add_argument('--system', help='Use the system bus', action='store_true')
parser.add_argument('--session', help='Use the session bus', action='store_true')
parser.add_argument('--dest', help='The destination address for the message', required=True)
parser.add_argument('--signature', help='The signature for the message body')
parser.add_argument('--type',
help='The type of message to send',
choices=[e.name for e in MessageType],
default=MessageType.METHOD_CALL.name,
nargs=OPTIONAL)
parser.add_argument('object_path', help='The object path for the message')
parser.add_argument('interface.member', help='The interface and member for the message')
parser.add_argument('body',
help='The JSON encoded body of the message. Must match the signature',
nargs=OPTIONAL)
args = parser.parse_args()
def exit_error(message):
parser.print_usage()
print()
print(message)
sys.exit(1)
interface_member = vars(args)['interface.member'].split('.')
if len(interface_member) < 2:
exit_error(
f'Expecting an interface and member separated by a dot: {vars(args)["interface.member"]}')
destination = args.dest
member = interface_member[-1]
interface = '.'.join(interface_member[:len(interface_member) - 1])
object_path = args.object_path
signature = args.signature
body = args.body
message_type = MessageType[args.type]
signature = args.signature
bus_type = BusType.SESSION
if args.system:
bus_type = BusType.SYSTEM
if message_type is not MessageType.METHOD_CALL:
exit_error('only message type METHOD_CALL is supported right now')
if not is_bus_name_valid(destination):
exit_error(f'got invalid bus name: {destination}')
if not is_object_path_valid(object_path):
exit_error(f'got invalid object path: {object_path}')
if not is_interface_name_valid(interface):
exit_error(f'got invalid interface name: {interface}')
if not is_member_name_valid(member):
exit_error(f'got invalid member name: {member}')
if body is None:
body = []
signature = ''
else:
try:
body = json.loads(body)
except json.JSONDecodeError as e:
exit_error(f'could not parse body as JSON: ({e})')
if type(body) is not list:
exit_error('body must be an array of arguments')
if not signature:
exit_error('--signature is a required argument when passing a message body')
loop = asyncio.get_event_loop()
async def main():
bus = await MessageBus(bus_type=bus_type).connect()
message = Message(destination=destination,
member=member,
interface=interface,
path=object_path,
signature=signature,
body=body)
result = await bus.call(message)
ret = 0
if result.message_type is MessageType.ERROR:
print(f'Error: {result.error_name}', file=sys.stderr)
ret = 1
def default(o):
if type(o) is Variant:
return [o.signature, o.value]
else:
raise json.JSONDecodeError()
print(json.dumps(result.body, indent=2, default=default))
sys.exit(ret)
loop.run_until_complete(main())
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,026
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/errors.py
|
class SignatureBodyMismatchError(ValueError):
pass
class InvalidSignatureError(ValueError):
pass
class InvalidAddressError(ValueError):
pass
class AuthError(Exception):
pass
class InvalidMessageError(ValueError):
pass
class InvalidIntrospectionError(ValueError):
pass
class InterfaceNotFoundError(Exception):
pass
class SignalDisabledError(Exception):
pass
class InvalidBusNameError(TypeError):
def __init__(self, name):
super().__init__(f'invalid bus name: {name}')
class InvalidObjectPathError(TypeError):
def __init__(self, path):
super().__init__(f'invalid object path: {path}')
class InvalidInterfaceNameError(TypeError):
def __init__(self, name):
super().__init__(f'invalid interface name: {name}')
class InvalidMemberNameError(TypeError):
def __init__(self, member):
super().__init__(f'invalid member name: {member}')
from .message import Message
from .validators import assert_interface_name_valid
from .constants import ErrorType, MessageType
class DBusError(Exception):
def __init__(self, type_, text, reply=None):
super().__init__(text)
if type(type_) is ErrorType:
type_ = type_.value
assert_interface_name_valid(type_)
if reply is not None and type(reply) is not Message:
raise TypeError('reply must be of type Message')
self.type = type_
self.text = text
self.reply = reply
@staticmethod
def _from_message(msg):
assert msg.message_type == MessageType.ERROR
return DBusError(msg.error_name, msg.body[0], reply=msg)
def _as_message(self, msg):
return Message.new_error(msg, self.type, self.text)
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,027
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/message.py
|
from ._private.marshaller import Marshaller
from .constants import MessageType, MessageFlag, ErrorType
from ._private.constants import PROTOCOL_VERSION, HeaderField, LITTLE_ENDIAN
from .validators import assert_bus_name_valid, assert_member_name_valid, assert_object_path_valid, assert_interface_name_valid
from .errors import InvalidMessageError
from .signature import SignatureTree, Variant
from typing import List, Any
REQUIRED_FIELDS = {
MessageType.METHOD_CALL: ('path', 'member'),
MessageType.SIGNAL: ('path', 'member', 'interface'),
MessageType.ERROR: ('error_name', 'reply_serial'),
MessageType.METHOD_RETURN: ('reply_serial', ),
}
class Message:
"""A class for sending and receiving messages through the
:class:`MessageBus <dbus_next.message_bus.BaseMessageBus>` with the
low-level api.
A ``Message`` can be constructed by the user to send over the message bus.
When messages are received, such as from method calls or signal emissions,
they will use this class as well.
:ivar destination: The address of the client for which this message is intended.
:vartype destination: str
:ivar path: The intended object path exported on the destination bus.
:vartype path: str
:ivar interface: The intended interface on the object path.
:vartype interface: str
:ivar member: The intended member on the interface.
:vartype member: str
:ivar message_type: The type of this message. A method call, signal, method return, or error.
:vartype message_type: :class:`MessageType`
:ivar flags: Flags that affect the behavior of this message.
:vartype flags: :class:`MessageFlag`
:ivar error_name: If this message is an error, the name of this error. Must be a valid interface name.
:vartype error_name: str
:ivar reply_serial: If this is a return type, the serial this message is in reply to.
:vartype reply_serial: int
:ivar sender: The address of the sender of this message. Will be a unique name.
:vartype sender: str
:ivar unix_fds: A list of unix fds that were sent in the header of this message.
:vartype unix_fds: list(int)
:ivar signature: The signature of the body of this message.
:vartype signature: str
:ivar signature_tree: The signature parsed as a signature tree.
:vartype signature_tree: :class:`SignatureTree`
:ivar body: The body of this message. Must match the signature.
:vartype body: list(Any)
:ivar serial: The serial of the message. Will be automatically set during message sending if not present. Use the ``new_serial()`` method of the bus to generate a serial.
:vartype serial: int
:raises:
- :class:`InvalidMessageError` - If the message is malformed or missing fields for the message type.
- :class:`InvalidSignatureError` - If the given signature is not valid.
- :class:`InvalidObjectPathError` - If ``path`` is not a valid object path.
- :class:`InvalidBusNameError` - If ``destination`` is not a valid bus name.
- :class:`InvalidMemberNameError` - If ``member`` is not a valid member name.
- :class:`InvalidInterfaceNameError` - If ``error_name`` or ``interface`` is not a valid interface name.
"""
def __init__(self,
destination: str = None,
path: str = None,
interface: str = None,
member: str = None,
message_type: MessageType = MessageType.METHOD_CALL,
flags: MessageFlag = MessageFlag.NONE,
error_name: str = None,
reply_serial: int = None,
sender: str = None,
unix_fds: List[int] = [],
signature: str = '',
body: List[Any] = [],
serial: int = 0):
self.destination = destination
self.path = path
self.interface = interface
self.member = member
self.message_type = message_type
self.flags = flags if type(flags) is MessageFlag else MessageFlag(bytes([flags]))
self.error_name = error_name if type(error_name) is not ErrorType else error_name.value
self.reply_serial = reply_serial
self.sender = sender
self.unix_fds = unix_fds
self.signature = signature.signature if type(signature) is SignatureTree else signature
self.signature_tree = signature if type(signature) is SignatureTree else SignatureTree._get(
signature)
self.body = body
self.serial = serial
if self.destination is not None:
assert_bus_name_valid(self.destination)
if self.interface is not None:
assert_interface_name_valid(self.interface)
if self.path is not None:
assert_object_path_valid(self.path)
if self.member is not None:
assert_member_name_valid(self.member)
if self.error_name is not None:
assert_interface_name_valid(self.error_name)
required_fields = REQUIRED_FIELDS.get(self.message_type)
if not required_fields:
raise InvalidMessageError(f'got unknown message type: {self.message_type}')
for field in required_fields:
if not getattr(self, field):
raise InvalidMessageError(f'missing required field: {field}')
@staticmethod
def new_error(msg: 'Message', error_name: str, error_text: str) -> 'Message':
"""A convenience constructor to create an error message in reply to the given message.
:param msg: The message this error is in reply to.
:type msg: :class:`Message`
:param error_name: The name of this error. Must be a valid interface name.
:type error_name: str
:param error_text: Human-readable text for the error.
:returns: The error message.
:rtype: :class:`Message`
:raises:
- :class:`InvalidInterfaceNameError` - If the error_name is not a valid interface name.
"""
return Message(message_type=MessageType.ERROR,
reply_serial=msg.serial,
destination=msg.sender,
error_name=error_name,
signature='s',
body=[error_text])
@staticmethod
def new_method_return(msg: 'Message',
signature: str = '',
body: List[Any] = [],
unix_fds: List[int] = []) -> 'Message':
"""A convenience constructor to create a method return to the given method call message.
:param msg: The method call message this is a reply to.
:type msg: :class:`Message`
:param signature: The signature for the message body.
:type signature: str
:param body: The body of this message. Must match the signature.
:type body: list(Any)
:param unix_fds: List integer file descriptors to send with this message.
:type body: list(int)
:returns: The method return message
:rtype: :class:`Message`
:raises:
- :class:`InvalidSignatureError` - If the signature is not a valid signature.
"""
return Message(message_type=MessageType.METHOD_RETURN,
reply_serial=msg.serial,
destination=msg.sender,
signature=signature,
body=body,
unix_fds=unix_fds)
@staticmethod
def new_signal(path: str,
interface: str,
member: str,
signature: str = '',
body: List[Any] = None,
unix_fds: List[int] = None) -> 'Message':
"""A convenience constructor to create a new signal message.
:param path: The path of this signal.
:type path: str
:param interface: The interface of this signal.
:type interface: str
:param member: The member name of this signal.
:type member: str
:param signature: The signature of the signal body.
:type signature: str
:param body: The body of this signal message.
:type body: list(Any)
:param unix_fds: List integer file descriptors to send with this message.
:type body: list(int)
:returns: The signal message.
:rtype: :class:`Message`
:raises:
- :class:`InvalidSignatureError` - If the signature is not a valid signature.
- :class:`InvalidObjectPathError` - If ``path`` is not a valid object path.
- :class:`InvalidInterfaceNameError` - If ``interface`` is not a valid interface name.
- :class:`InvalidMemberNameError` - If ``member`` is not a valid member name.
"""
body = body if body else []
return Message(message_type=MessageType.SIGNAL,
interface=interface,
path=path,
member=member,
signature=signature,
body=body,
unix_fds=unix_fds)
def _matches(self, **kwargs):
for attr, val in kwargs.items():
if getattr(self, attr) != val:
return False
return True
def _marshall(self, negotiate_unix_fd=False):
# TODO maximum message size is 134217728 (128 MiB)
body_block = Marshaller(self.signature, self.body)
body_block.marshall()
fields = []
if self.path:
fields.append([HeaderField.PATH.value, Variant('o', self.path)])
if self.interface:
fields.append([HeaderField.INTERFACE.value, Variant('s', self.interface)])
if self.member:
fields.append([HeaderField.MEMBER.value, Variant('s', self.member)])
if self.error_name:
fields.append([HeaderField.ERROR_NAME.value, Variant('s', self.error_name)])
if self.reply_serial:
fields.append([HeaderField.REPLY_SERIAL.value, Variant('u', self.reply_serial)])
if self.destination:
fields.append([HeaderField.DESTINATION.value, Variant('s', self.destination)])
if self.signature:
fields.append([HeaderField.SIGNATURE.value, Variant('g', self.signature)])
if self.unix_fds and negotiate_unix_fd:
fields.append([HeaderField.UNIX_FDS.value, Variant('u', len(self.unix_fds))])
header_body = [
LITTLE_ENDIAN, self.message_type.value, self.flags.value, PROTOCOL_VERSION,
len(body_block.buffer), self.serial, fields
]
header_block = Marshaller('yyyyuua(yv)', header_body)
header_block.marshall()
header_block.align(8)
return header_block.buffer + body_block.buffer
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,028
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/test/test_marshaller.py
|
from typing import Any, Dict
from dbus_next._private.unmarshaller import Unmarshaller
from dbus_next import Message, Variant, SignatureTree, MessageType, MessageFlag
import json
import os
import io
import pytest
def print_buf(buf):
i = 0
while True:
p = buf[i:i + 8]
if not p:
break
print(p)
i += 8
# these messages have been verified with another library
table = json.load(open(os.path.dirname(__file__) + "/data/messages.json"))
def json_to_message(message: Dict[str, Any]) -> Message:
copy = dict(message)
if "message_type" in copy:
copy["message_type"] = MessageType(copy["message_type"])
if "flags" in copy:
copy["flags"] = MessageFlag(copy["flags"])
return Message(**copy)
# variants are an object in the json
def replace_variants(type_, item):
if type_.token == "v" and type(item) is not Variant:
item = Variant(
item["signature"],
replace_variants(SignatureTree(item["signature"]).types[0], item["value"]),
)
elif type_.token == "a":
for i, item_child in enumerate(item):
if type_.children[0].token == "{":
for k, v in item.items():
item[k] = replace_variants(type_.children[0].children[1], v)
else:
item[i] = replace_variants(type_.children[0], item_child)
elif type_.token == "(":
for i, item_child in enumerate(item):
if type_.children[0].token == "{":
assert False
else:
item[i] = replace_variants(type_.children[i], item_child)
return item
def json_dump(what):
def dumper(obj):
try:
return obj.toJSON()
except Exception:
return obj.__dict__
return json.dumps(what, default=dumper, indent=2)
def test_marshalling_with_table():
for item in table:
message = json_to_message(item["message"])
body = []
for i, type_ in enumerate(message.signature_tree.types):
body.append(replace_variants(type_, message.body[i]))
message.body = body
buf = message._marshall()
data = bytes.fromhex(item["data"])
if buf != data:
print("message:")
print(json_dump(item["message"]))
print("")
print("mine:")
print_buf(bytes(buf))
print("")
print("theirs:")
print_buf(data)
assert buf == data
@pytest.mark.parametrize("unmarshall_table", (table, ))
def test_unmarshalling_with_table(unmarshall_table):
for item in unmarshall_table:
stream = io.BytesIO(bytes.fromhex(item["data"]))
unmarshaller = Unmarshaller(stream)
try:
unmarshaller.unmarshall()
except Exception as e:
print("message failed to unmarshall:")
print(json_dump(item["message"]))
raise e
message = json_to_message(item["message"])
body = []
for i, type_ in enumerate(message.signature_tree.types):
body.append(replace_variants(type_, message.body[i]))
message.body = body
for attr in [
"body",
"signature",
"message_type",
"destination",
"path",
"interface",
"member",
"flags",
"serial",
]:
assert getattr(unmarshaller.message,
attr) == getattr(message, attr), f"attr doesnt match: {attr}"
def test_unmarshall_can_resume():
"""Verify resume works."""
bluez_rssi_message = (
"6c04010134000000e25389019500000001016f00250000002f6f72672f626c75657a2f686369302f6465"
"765f30385f33415f46325f31455f32425f3631000000020173001f0000006f72672e667265656465736b"
"746f702e444275732e50726f7065727469657300030173001100000050726f706572746965734368616e"
"67656400000000000000080167000873617b73767d617300000007017300040000003a312e3400000000"
"110000006f72672e626c75657a2e446576696365310000000e0000000000000004000000525353490001"
"6e00a7ff000000000000")
message_bytes = bytes.fromhex(bluez_rssi_message)
class SlowStream(io.IOBase):
"""A fake stream that will only give us one byte at a time."""
def __init__(self):
self.data = message_bytes
self.pos = 0
def read(self, n) -> bytes:
data = self.data[self.pos:self.pos + 1]
self.pos += 1
return data
stream = SlowStream()
unmarshaller = Unmarshaller(stream)
for _ in range(len(bluez_rssi_message)):
if unmarshaller.unmarshall():
break
assert unmarshaller.message is not None
def test_ay_buffer():
body = [bytes(10000)]
msg = Message(path="/test", member="test", signature="ay", body=body)
marshalled = msg._marshall()
unmarshalled_msg = Unmarshaller(io.BytesIO(marshalled)).unmarshall()
assert unmarshalled_msg.body[0] == body[0]
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,029
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/examples/glib-list-names.py
|
#!/usr/bin/env python3
import sys
import os
sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/..'))
from dbus_next import Message
from dbus_next.glib import MessageBus
import json
import signal
from gi.repository import GLib
main = GLib.MainLoop()
bus = MessageBus().connect_sync()
def reply_handler(reply, err):
main.quit()
if err:
raise err
print(json.dumps(reply.body[0], indent=2))
bus.call(
Message('org.freedesktop.DBus', '/org/freedesktop/DBus', 'org.freedesktop.DBus', 'ListNames'),
reply_handler)
signal.signal(signal.SIGINT, signal.SIG_DFL)
main.run()
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,030
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/message_bus.py
|
from ._private.address import get_bus_address, parse_address
from ._private.util import replace_fds_with_idx, replace_idx_with_fds
from .message import Message
from .constants import BusType, MessageFlag, MessageType, ErrorType, NameFlag, RequestNameReply, ReleaseNameReply
from .service import ServiceInterface
from .validators import assert_object_path_valid, assert_bus_name_valid
from .errors import DBusError, InvalidAddressError
from .signature import Variant
from .proxy_object import BaseProxyObject
from . import introspection as intr
import inspect
import socket
import logging
import xml.etree.ElementTree as ET
import traceback
from typing import Type, Callable, Optional, Union
class BaseMessageBus:
"""An abstract class to manage a connection to a DBus message bus.
The message bus class is the entry point into all the features of the
library. It sets up a connection to the DBus daemon and exposes an
interface to send and receive messages and expose services.
This class is not meant to be used directly by users. For more information,
see the documentation for the implementation of the message bus you plan to
use.
:param bus_type: The type of bus to connect to. Affects the search path for
the bus address.
:type bus_type: :class:`BusType <dbus_next.BusType>`
:param bus_address: A specific bus address to connect to. Should not be
used under normal circumstances.
:type bus_address: str
:param ProxyObject: The proxy object implementation for this message bus.
Must be passed in by an implementation that supports the high-level client.
:type ProxyObject: Type[:class:`BaseProxyObject
<dbus_next.proxy_object.BaseProxyObject>`]
:ivar unique_name: The unique name of the message bus connection. It will
be :class:`None` until the message bus connects.
:vartype unique_name: str
:ivar connected: True if this message bus is expected to be able to send
and receive messages.
:vartype connected: bool
"""
def __init__(self,
bus_address: Optional[str] = None,
bus_type: BusType = BusType.SESSION,
ProxyObject: Optional[Type[BaseProxyObject]] = None):
self.unique_name = None
self._disconnected = False
# True if the user disconnected himself, so don't throw errors out of
# the main loop.
self._user_disconnect = False
self._method_return_handlers = {}
self._serial = 0
self._user_message_handlers = []
# the key is the name and the value is the unique name of the owner.
# This cache is kept up to date by the NameOwnerChanged signal and is
# used to route messages to the correct proxy object. (used for the
# high level client only)
self._name_owners = {}
# used for the high level service
self._path_exports = {}
self._bus_address = parse_address(bus_address) if bus_address else parse_address(
get_bus_address(bus_type))
# the bus implementations need this rule for the high level client to
# work correctly.
self._name_owner_match_rule = "sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',path='/org/freedesktop/DBus',member='NameOwnerChanged'"
# _match_rules: the keys are match rules and the values are ref counts
# (used for the high level client only)
self._match_rules = {}
self._high_level_client_initialized = False
self._ProxyObject = ProxyObject
# machine id is lazy loaded
self._machine_id = None
self._setup_socket()
@property
def connected(self):
if self.unique_name is None or self._disconnected or self._user_disconnect:
return False
return True
def export(self, path: str, interface: ServiceInterface):
"""Export the service interface on this message bus to make it available
to other clients.
:param path: The object path to export this interface on.
:type path: str
:param interface: The service interface to export.
:type interface: :class:`ServiceInterface
<dbus_next.service.ServiceInterface>`
:raises:
- :class:`InvalidObjectPathError <dbus_next.InvalidObjectPathError>` - If the given object path is not valid.
- :class:`ValueError` - If an interface with this name is already exported on the message bus at this path
"""
assert_object_path_valid(path)
if not isinstance(interface, ServiceInterface):
raise TypeError('interface must be a ServiceInterface')
if path not in self._path_exports:
self._path_exports[path] = []
for f in self._path_exports[path]:
if f.name == interface.name:
raise ValueError(
f'An interface with this name is already exported on this bus at path "{path}": "{interface.name}"'
)
self._path_exports[path].append(interface)
ServiceInterface._add_bus(interface, self)
self._emit_interface_added(path, interface)
def unexport(self, path: str, interface: Optional[Union[ServiceInterface, str]] = None):
"""Unexport the path or service interface to make it no longer
available to clients.
:param path: The object path to unexport.
:type path: str
:param interface: The interface instance or the name of the interface
to unexport. If ``None``, unexport every interface on the path.
:type interface: :class:`ServiceInterface
<dbus_next.service.ServiceInterface>` or str or None
:raises:
- :class:`InvalidObjectPathError <dbus_next.InvalidObjectPathError>` - If the given object path is not valid.
"""
assert_object_path_valid(path)
if type(interface) not in [str, type(None)] and not isinstance(interface, ServiceInterface):
raise TypeError('interface must be a ServiceInterface or interface name')
if path not in self._path_exports:
return
exports = self._path_exports[path]
if type(interface) is str:
try:
interface = next(iface for iface in exports if iface.name == interface)
except StopIteration:
return
removed_interfaces = []
if interface is None:
del self._path_exports[path]
for iface in filter(lambda e: not self._has_interface(e), exports):
removed_interfaces.append(iface.name)
ServiceInterface._remove_bus(iface, self)
else:
for i, iface in enumerate(exports):
if iface is interface:
removed_interfaces.append(iface.name)
del self._path_exports[path][i]
if not self._path_exports[path]:
del self._path_exports[path]
if not self._has_interface(iface):
ServiceInterface._remove_bus(iface, self)
break
self._emit_interface_removed(path, removed_interfaces)
def introspect(self, bus_name: str, path: str,
callback: Callable[[Optional[intr.Node], Optional[Exception]], None]):
"""Get introspection data for the node at the given path from the given
bus name.
Calls the standard ``org.freedesktop.DBus.Introspectable.Introspect``
on the bus for the path.
:param bus_name: The name to introspect.
:type bus_name: str
:param path: The path to introspect.
:type path: str
:param callback: A callback that will be called with the introspection
data as a :class:`Node <dbus_next.introspection.Node>`.
:type callback: :class:`Callable`
:raises:
- :class:`InvalidObjectPathError <dbus_next.InvalidObjectPathError>` - If the given object path is not valid.
- :class:`InvalidBusNameError <dbus_next.InvalidBusNameError>` - If the given bus name is not valid.
"""
BaseMessageBus._check_callback_type(callback)
def reply_notify(reply, err):
try:
BaseMessageBus._check_method_return(reply, err, 's')
result = intr.Node.parse(reply.body[0])
except Exception as e:
callback(None, e)
return
callback(result, None)
self._call(
Message(destination=bus_name,
path=path,
interface='org.freedesktop.DBus.Introspectable',
member='Introspect'), reply_notify)
def _emit_interface_added(self, path, interface):
"""Emit the ``org.freedesktop.DBus.ObjectManager.InterfacesAdded`` signal.
This signal is intended to be used to alert clients when
a new interface has been added.
:param path: Path of exported object.
:type path: str
:param interface: Exported service interface.
:type interface: :class:`ServiceInterface
<dbus_next.service.ServiceInterface>`
"""
if self._disconnected:
return
def get_properties_callback(interface, result, user_data, e):
if e is not None:
try:
raise e
except Exception:
logging.error(
'An exception ocurred when emitting ObjectManager.InterfacesAdded for %s. '
'Some properties will not be included in the signal.',
interface.name,
exc_info=True)
body = {interface.name: result}
self.send(
Message.new_signal(path=path,
interface='org.freedesktop.DBus.ObjectManager',
member='InterfacesAdded',
signature='oa{sa{sv}}',
body=[path, body]))
ServiceInterface._get_all_property_values(interface, get_properties_callback)
def _emit_interface_removed(self, path, removed_interfaces):
"""Emit the ``org.freedesktop.DBus.ObjectManager.InterfacesRemoved` signal.
This signal is intended to be used to alert clients when
a interface has been removed.
:param path: Path of removed (unexported) object.
:type path: str
:param removed_interfaces: List of unexported service interfaces.
:type removed_interfaces: list[str]
"""
if self._disconnected:
return
self.send(
Message.new_signal(path=path,
interface='org.freedesktop.DBus.ObjectManager',
member='InterfacesRemoved',
signature='oas',
body=[path, removed_interfaces]))
def request_name(self,
name: str,
flags: NameFlag = NameFlag.NONE,
callback: Optional[Callable[[Optional[RequestNameReply], Optional[Exception]],
None]] = None):
"""Request that this message bus owns the given name.
:param name: The name to request.
:type name: str
:param flags: Name flags that affect the behavior of the name request.
:type flags: :class:`NameFlag <dbus_next.NameFlag>`
:param callback: A callback that will be called with the reply of the
request as a :class:`RequestNameReply <dbus_next.RequestNameReply>`.
:type callback: :class:`Callable`
:raises:
- :class:`InvalidBusNameError <dbus_next.InvalidBusNameError>` - If the given bus name is not valid.
"""
assert_bus_name_valid(name)
if callback is not None:
BaseMessageBus._check_callback_type(callback)
def reply_notify(reply, err):
try:
BaseMessageBus._check_method_return(reply, err, 'u')
result = RequestNameReply(reply.body[0])
except Exception as e:
callback(None, e)
return
callback(result, None)
if type(flags) is not NameFlag:
flags = NameFlag(flags)
self._call(
Message(destination='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus',
member='RequestName',
signature='su',
body=[name, flags]), reply_notify if callback else None)
def release_name(self,
name: str,
callback: Optional[Callable[[Optional[ReleaseNameReply], Optional[Exception]],
None]] = None):
"""Request that this message bus release the given name.
:param name: The name to release.
:type name: str
:param callback: A callback that will be called with the reply of the
release request as a :class:`ReleaseNameReply
<dbus_next.ReleaseNameReply>`.
:type callback: :class:`Callable`
:raises:
- :class:`InvalidBusNameError <dbus_next.InvalidBusNameError>` - If the given bus name is not valid.
"""
assert_bus_name_valid(name)
if callback is not None:
BaseMessageBus._check_callback_type(callback)
def reply_notify(reply, err):
try:
BaseMessageBus._check_method_return(reply, err, 'u')
result = ReleaseNameReply(reply.body[0])
except Exception as e:
callback(None, e)
return
callback(result, None)
self._call(
Message(destination='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus',
member='ReleaseName',
signature='s',
body=[name]), reply_notify if callback else None)
def get_proxy_object(self, bus_name: str, path: str,
introspection: Union[intr.Node, str, ET.Element]) -> BaseProxyObject:
"""Get a proxy object for the path exported on the bus that owns the
name. The object is expected to export the interfaces and nodes
specified in the introspection data.
This is the entry point into the high-level client.
:param bus_name: The name on the bus to get the proxy object for.
:type bus_name: str
:param path: The path on the client for the proxy object.
:type path: str
:param introspection: XML introspection data used to build the
interfaces on the proxy object.
:type introspection: :class:`Node <dbus_next.introspection.Node>` or str or :class:`ElementTree`
:returns: A proxy object for the given path on the given name.
:rtype: :class:`BaseProxyObject <dbus_next.proxy_object.BaseProxyObject>`
:raises:
- :class:`InvalidBusNameError <dbus_next.InvalidBusNameError>` - If the given bus name is not valid.
- :class:`InvalidObjectPathError <dbus_next.InvalidObjectPathError>` - If the given object path is not valid.
- :class:`InvalidIntrospectionError <dbus_next.InvalidIntrospectionError>` - If the introspection data for the node is not valid.
"""
if self._ProxyObject is None:
raise Exception('the message bus implementation did not provide a proxy object class')
self._init_high_level_client()
return self._ProxyObject(bus_name, path, introspection, self)
def disconnect(self):
"""Disconnect the message bus by closing the underlying connection asynchronously.
All pending and future calls will error with a connection error.
"""
self._user_disconnect = True
try:
self._sock.shutdown(socket.SHUT_RDWR)
except Exception:
logging.warning('could not shut down socket', exc_info=True)
def next_serial(self) -> int:
"""Get the next serial for this bus. This can be used as the ``serial``
attribute of a :class:`Message <dbus_next.Message>` to manually handle
the serial of messages.
:returns: The next serial for the bus.
:rtype: int
"""
self._serial += 1
return self._serial
def add_message_handler(self, handler: Callable[[Message], Optional[Union[Message, bool]]]):
"""Add a custom message handler for incoming messages.
The handler should be a callable that takes a :class:`Message
<dbus_next.Message>`. If the message is a method call, you may return
another Message as a reply and it will be marked as handled. You may
also return ``True`` to mark the message as handled without sending a
reply.
:param handler: A handler that will be run for every message the bus
connection received.
:type handler: :class:`Callable` or None
"""
error_text = 'a message handler must be callable with a single parameter'
if not callable(handler):
raise TypeError(error_text)
handler_signature = inspect.signature(handler)
if len(handler_signature.parameters) != 1:
raise TypeError(error_text)
self._user_message_handlers.append(handler)
def remove_message_handler(self, handler: Callable[[Message], Optional[Union[Message, bool]]]):
"""Remove a message handler that was previously added by
:func:`add_message_handler()
<dbus_next.message_bus.BaseMessageBus.add_message_handler>`.
:param handler: A message handler.
:type handler: :class:`Callable`
"""
for i, h in enumerate(self._user_message_handlers):
if h == handler:
del self._user_message_handlers[i]
break
def send(self, msg: Message) -> None:
"""Asynchronously send a message on the message bus.
:param msg: The message to send.
:type msg: :class:`Message <dbus_next.Message>`
"""
raise NotImplementedError('the "send" method must be implemented in the inheriting class')
def _finalize(self, err):
'''should be called after the socket disconnects with the disconnection
error to clean up resources and put the bus in a disconnected state'''
if self._disconnected:
return
self._disconnected = True
for handler in self._method_return_handlers.values():
try:
handler(None, err)
except Exception:
logging.warning('a message handler threw an exception on shutdown', exc_info=True)
self._method_return_handlers.clear()
for path in list(self._path_exports.keys()):
self.unexport(path)
self._user_message_handlers.clear()
def _has_interface(self, interface: ServiceInterface) -> bool:
for _, exports in self._path_exports.items():
for iface in exports:
if iface is interface:
return True
return False
def _interface_signal_notify(self,
interface,
interface_name,
member,
signature,
body,
unix_fds=[]):
path = None
for p, ifaces in self._path_exports.items():
for i in ifaces:
if i is interface:
path = p
if path is None:
raise Exception('Could not find interface on bus (this is a bug in dbus-next)')
self.send(
Message.new_signal(path=path,
interface=interface_name,
member=member,
signature=signature,
body=body,
unix_fds=unix_fds))
def _introspect_export_path(self, path):
assert_object_path_valid(path)
if path in self._path_exports:
node = intr.Node.default(path)
for interface in self._path_exports[path]:
node.interfaces.append(interface.introspect())
else:
node = intr.Node(path)
children = set()
for export_path in self._path_exports:
try:
child_path = export_path.split(path, maxsplit=1)[1]
except IndexError:
continue
child_path = child_path.lstrip('/')
child_name = child_path.split('/', maxsplit=1)[0]
children.add(child_name)
node.nodes = [intr.Node(name) for name in children if name]
return node
def _setup_socket(self):
err = None
for transport, options in self._bus_address:
filename = None
ip_addr = ''
ip_port = 0
if transport == 'unix':
self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self._stream = self._sock.makefile('rwb')
self._fd = self._sock.fileno()
if 'path' in options:
filename = options['path']
elif 'abstract' in options:
filename = f'\0{options["abstract"]}'
else:
raise InvalidAddressError('got unix transport with unknown path specifier')
try:
self._sock.connect(filename)
self._sock.setblocking(False)
break
except Exception as e:
err = e
elif transport == 'tcp':
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._stream = self._sock.makefile('rwb')
self._fd = self._sock.fileno()
if 'host' in options:
ip_addr = options['host']
if 'port' in options:
ip_port = int(options['port'])
try:
self._sock.connect((ip_addr, ip_port))
self._sock.setblocking(False)
break
except Exception as e:
err = e
else:
raise InvalidAddressError(f'got unknown address transport: {transport}')
if err:
raise err
def _call(self, msg, callback):
BaseMessageBus._check_callback_type(callback)
if not msg.serial:
msg.serial = self.next_serial()
def reply_notify(reply, err):
if reply:
self._name_owners[msg.destination] = reply.sender
callback(reply, err)
self.send(msg)
if msg.flags & MessageFlag.NO_REPLY_EXPECTED:
callback(None, None)
else:
self._method_return_handlers[msg.serial] = reply_notify
@staticmethod
def _check_callback_type(callback):
"""Raise a TypeError if the user gives an invalid callback as a parameter"""
text = 'a callback must be callable with two parameters'
if not callable(callback):
raise TypeError(text)
fn_signature = inspect.signature(callback)
if len(fn_signature.parameters) != 2:
raise TypeError(text)
@staticmethod
def _check_method_return(msg, err, signature):
if err:
raise err
elif msg.message_type == MessageType.METHOD_RETURN and msg.signature == signature:
return
elif msg.message_type == MessageType.ERROR:
raise DBusError._from_message(msg)
else:
raise DBusError(ErrorType.INTERNAL_ERROR, 'invalid message type for method call', msg)
def _on_message(self, msg):
try:
self._process_message(msg)
except Exception as e:
logging.error(
f'got unexpected error processing a message: {e}.\n{traceback.format_exc()}')
def _send_reply(self, msg):
bus = self
class SendReply:
def __enter__(self):
return self
def __call__(self, reply):
if msg.flags & MessageFlag.NO_REPLY_EXPECTED:
return
bus.send(reply)
def _exit(self, exc_type, exc_value, tb):
if exc_type is None:
return
if issubclass(exc_type, DBusError):
self(exc_value._as_message(msg))
return True
if issubclass(exc_type, Exception):
self(
Message.new_error(
msg, ErrorType.SERVICE_ERROR,
f'The service interface raised an error: {exc_value}.\n{traceback.format_tb(tb)}'
))
return True
def __exit__(self, exc_type, exc_value, tb):
self._exit(exc_type, exc_value, tb)
def send_error(self, exc):
self._exit(exc.__class__, exc, exc.__traceback__)
return SendReply()
def _process_message(self, msg):
handled = False
for handler in self._user_message_handlers:
try:
result = handler(msg)
if result:
if type(result) is Message:
self.send(result)
handled = True
break
except DBusError as e:
if msg.message_type == MessageType.METHOD_CALL:
self.send(e._as_message(msg))
handled = True
break
else:
logging.error(
f'A message handler raised an exception: {e}.\n{traceback.format_exc()}')
except Exception as e:
logging.error(
f'A message handler raised an exception: {e}.\n{traceback.format_exc()}')
if msg.message_type == MessageType.METHOD_CALL:
self.send(
Message.new_error(
msg, ErrorType.INTERNAL_ERROR,
f'An internal error occurred: {e}.\n{traceback.format_exc()}'))
handled = True
break
if msg.message_type == MessageType.SIGNAL:
if msg._matches(sender='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus',
member='NameOwnerChanged'):
[name, old_owner, new_owner] = msg.body
if new_owner:
self._name_owners[name] = new_owner
elif name in self._name_owners:
del self._name_owners[name]
elif msg.message_type == MessageType.METHOD_CALL:
if not handled:
handler = self._find_message_handler(msg)
send_reply = self._send_reply(msg)
with send_reply:
if handler:
handler(msg, send_reply)
else:
send_reply(
Message.new_error(
msg, ErrorType.UNKNOWN_METHOD,
f'{msg.interface}.{msg.member} with signature "{msg.signature}" could not be found'
))
else:
# An ERROR or a METHOD_RETURN
if msg.reply_serial in self._method_return_handlers:
if not handled:
handler = self._method_return_handlers[msg.reply_serial]
handler(msg, None)
del self._method_return_handlers[msg.reply_serial]
def _make_method_handler(self, interface, method):
def handler(msg, send_reply):
args = ServiceInterface._msg_body_to_args(msg)
result = method.fn(interface, *args)
body, fds = ServiceInterface._fn_result_to_body(
result, signature_tree=method.out_signature_tree)
send_reply(Message.new_method_return(msg, method.out_signature, body, fds))
return handler
def _find_message_handler(self, msg):
handler = None
if msg._matches(interface='org.freedesktop.DBus.Introspectable',
member='Introspect',
signature=''):
handler = self._default_introspect_handler
elif msg._matches(interface='org.freedesktop.DBus.Properties'):
handler = self._default_properties_handler
elif msg._matches(interface='org.freedesktop.DBus.Peer'):
if msg._matches(member='Ping', signature=''):
handler = self._default_ping_handler
elif msg._matches(member='GetMachineId', signature=''):
handler = self._default_get_machine_id_handler
elif msg._matches(interface='org.freedesktop.DBus.ObjectManager',
member='GetManagedObjects'):
handler = self._default_get_managed_objects_handler
else:
for interface in self._path_exports.get(msg.path, []):
for method in ServiceInterface._get_methods(interface):
if method.disabled:
continue
if msg._matches(interface=interface.name,
member=method.name,
signature=method.in_signature):
handler = self._make_method_handler(interface, method)
break
if handler:
break
return handler
def _default_introspect_handler(self, msg, send_reply):
introspection = self._introspect_export_path(msg.path).tostring()
send_reply(Message.new_method_return(msg, 's', [introspection]))
def _default_ping_handler(self, msg, send_reply):
send_reply(Message.new_method_return(msg))
def _default_get_machine_id_handler(self, msg, send_reply):
if self._machine_id:
send_reply(Message.new_method_return(msg, 's', self._machine_id))
return
def reply_handler(reply, err):
if err:
# the bus has been disconnected, cannot send a reply
return
if reply.message_type == MessageType.METHOD_RETURN:
self._machine_id = reply.body[0]
send_reply(Message.new_method_return(msg, 's', [self._machine_id]))
elif reply.message_type == MessageType.ERROR:
send_reply(Message.new_error(msg, reply.error_name, reply.body))
else:
send_reply(Message.new_error(msg, ErrorType.FAILED, 'could not get machine_id'))
self._call(
Message(destination='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus.Peer',
member='GetMachineId'), reply_handler)
def _default_get_managed_objects_handler(self, msg, send_reply):
result = {}
result_signature = 'a{oa{sa{sv}}}'
error_handled = False
def is_result_complete():
if not result:
return True
for n, interfaces in result.items():
for value in interfaces.values():
if value is None:
return False
return True
nodes = [
node for node in self._path_exports
if msg.path == '/' or node.startswith(msg.path + '/')
]
# first build up the result object to know when it's complete
for node in nodes:
result[node] = {}
for interface in self._path_exports[node]:
result[node][interface.name] = None
if is_result_complete():
send_reply(Message.new_method_return(msg, result_signature, [result]))
return
def get_all_properties_callback(interface, values, node, err):
nonlocal error_handled
if err is not None:
if not error_handled:
error_handled = True
send_reply.send_error(err)
return
result[node][interface.name] = values
if is_result_complete():
send_reply(Message.new_method_return(msg, result_signature, [result]))
for node in nodes:
for interface in self._path_exports[node]:
ServiceInterface._get_all_property_values(interface, get_all_properties_callback,
node)
def _default_properties_handler(self, msg, send_reply):
methods = {'Get': 'ss', 'Set': 'ssv', 'GetAll': 's'}
if msg.member not in methods or methods[msg.member] != msg.signature:
raise DBusError(
ErrorType.UNKNOWN_METHOD,
f'properties interface doesn\'t have method "{msg.member}" with signature "{msg.signature}"'
)
interface_name = msg.body[0]
if interface_name == '':
raise DBusError(
ErrorType.NOT_SUPPORTED,
'getting and setting properties with an empty interface string is not supported yet'
)
elif msg.path not in self._path_exports:
raise DBusError(ErrorType.UNKNOWN_OBJECT, f'no interfaces at path: "{msg.path}"')
match = [iface for iface in self._path_exports[msg.path] if iface.name == interface_name]
if not match:
if interface_name in [
'org.freedesktop.DBus.Properties', 'org.freedesktop.DBus.Introspectable',
'org.freedesktop.DBus.Peer', 'org.freedesktop.DBus.ObjectManager'
]:
# the standard interfaces do not have properties
if msg.member == 'Get' or msg.member == 'Set':
prop_name = msg.body[1]
raise DBusError(
ErrorType.UNKNOWN_PROPERTY,
f'interface "{interface_name}" does not have property "{prop_name}"')
elif msg.member == 'GetAll':
send_reply(Message.new_method_return(msg, 'a{sv}', [{}]))
return
else:
assert False
raise DBusError(
ErrorType.UNKNOWN_INTERFACE,
f'could not find an interface "{interface_name}" at path: "{msg.path}"')
interface = match[0]
properties = ServiceInterface._get_properties(interface)
if msg.member == 'Get' or msg.member == 'Set':
prop_name = msg.body[1]
match = [prop for prop in properties if prop.name == prop_name and not prop.disabled]
if not match:
raise DBusError(
ErrorType.UNKNOWN_PROPERTY,
f'interface "{interface_name}" does not have property "{prop_name}"')
prop = match[0]
if msg.member == 'Get':
if not prop.access.readable():
raise DBusError(ErrorType.UNKNOWN_PROPERTY,
'the property does not have read access')
def get_property_callback(interface, prop, prop_value, err):
try:
if err is not None:
send_reply.send_error(err)
return
body, unix_fds = replace_fds_with_idx(prop.signature, [prop_value])
send_reply(
Message.new_method_return(msg,
'v', [Variant(prop.signature, body[0])],
unix_fds=unix_fds))
except Exception as e:
send_reply.send_error(e)
ServiceInterface._get_property_value(interface, prop, get_property_callback)
elif msg.member == 'Set':
if not prop.access.writable():
raise DBusError(ErrorType.PROPERTY_READ_ONLY, 'the property is readonly')
value = msg.body[2]
if value.signature != prop.signature:
raise DBusError(ErrorType.INVALID_SIGNATURE,
f'wrong signature for property. expected "{prop.signature}"')
assert prop.prop_setter
def set_property_callback(interface, prop, err):
if err is not None:
send_reply.send_error(err)
return
send_reply(Message.new_method_return(msg))
body = replace_idx_with_fds(value.signature, [value.value], msg.unix_fds)
ServiceInterface._set_property_value(interface, prop, body[0],
set_property_callback)
elif msg.member == 'GetAll':
def get_all_properties_callback(interface, values, user_data, err):
if err is not None:
send_reply.send_error(err)
return
body, unix_fds = replace_fds_with_idx('a{sv}', [values])
send_reply(Message.new_method_return(msg, 'a{sv}', body, unix_fds=unix_fds))
ServiceInterface._get_all_property_values(interface, get_all_properties_callback)
else:
assert False
def _init_high_level_client(self):
'''The high level client is initialized when the first proxy object is
gotten. Currently just sets up the match rules for the name owner cache
so signals can be routed to the right objects.'''
if self._high_level_client_initialized:
return
self._high_level_client_initialized = True
def add_match_notify(msg, err):
if err:
logging.error(
f'add match request failed. match="{self._name_owner_match_rule}", {err}')
if msg.message_type == MessageType.ERROR:
logging.error(
f'add match request failed. match="{self._name_owner_match_rule}", {msg.body[0]}'
)
self._call(
Message(destination='org.freedesktop.DBus',
interface='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
member='AddMatch',
signature='s',
body=[self._name_owner_match_rule]), add_match_notify)
def _add_match_rule(self, match_rule):
'''Add a match rule. Match rules added by this function are refcounted
and must be removed by _remove_match_rule(). This is for use in the
high level client only.'''
if match_rule == self._name_owner_match_rule:
return
if match_rule in self._match_rules:
self._match_rules[match_rule] += 1
return
self._match_rules[match_rule] = 1
def add_match_notify(msg, err):
if err:
logging.error(f'add match request failed. match="{match_rule}", {err}')
if msg.message_type == MessageType.ERROR:
logging.error(f'add match request failed. match="{match_rule}", {msg.body[0]}')
self._call(
Message(destination='org.freedesktop.DBus',
interface='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
member='AddMatch',
signature='s',
body=[match_rule]), add_match_notify)
def _remove_match_rule(self, match_rule):
'''Remove a match rule added with _add_match_rule(). This is for use in
the high level client only.'''
if match_rule == self._name_owner_match_rule:
return
if match_rule in self._match_rules:
self._match_rules[match_rule] -= 1
if self._match_rules[match_rule] > 0:
return
del self._match_rules[match_rule]
def remove_match_notify(msg, err):
if self._disconnected:
return
if err:
logging.error(f'remove match request failed. match="{match_rule}", {err}')
if msg.message_type == MessageType.ERROR:
logging.error(f'remove match request failed. match="{match_rule}", {msg.body[0]}')
self._call(
Message(destination='org.freedesktop.DBus',
interface='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
member='RemoveMatch',
signature='s',
body=[match_rule]), remove_match_notify)
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,031
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/test/test_big_message.py
|
from dbus_next import aio, glib, Message, MessageType
from dbus_next.service import ServiceInterface, method
from test.util import check_gi_repository, skip_reason_no_gi
import pytest
has_gi = check_gi_repository()
class ExampleInterface(ServiceInterface):
def __init__(self):
super().__init__('example.interface')
@method()
def echo_bytes(self, what: 'ay') -> 'ay':
return what
@pytest.mark.asyncio
async def test_aio_big_message():
'this tests that nonblocking reads and writes actually work for aio'
bus1 = await aio.MessageBus().connect()
bus2 = await aio.MessageBus().connect()
interface = ExampleInterface()
bus1.export('/test/path', interface)
# two megabytes
big_body = [bytes(1000000) * 2]
result = await bus2.call(
Message(destination=bus1.unique_name,
path='/test/path',
interface=interface.name,
member='echo_bytes',
signature='ay',
body=big_body))
assert result.message_type == MessageType.METHOD_RETURN, result.body[0]
assert result.body[0] == big_body[0]
@pytest.mark.skipif(not has_gi, reason=skip_reason_no_gi)
def test_glib_big_message():
'this tests that nonblocking reads and writes actually work for glib'
bus1 = glib.MessageBus().connect_sync()
bus2 = glib.MessageBus().connect_sync()
interface = ExampleInterface()
bus1.export('/test/path', interface)
# two megabytes
big_body = [bytes(1000000) * 2]
result = bus2.call_sync(
Message(destination=bus1.unique_name,
path='/test/path',
interface=interface.name,
member='echo_bytes',
signature='ay',
body=big_body))
assert result.message_type == MessageType.METHOD_RETURN, result.body[0]
assert result.body[0] == big_body[0]
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,032
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/aio/message_bus.py
|
from ..message_bus import BaseMessageBus
from .._private.unmarshaller import Unmarshaller
from ..message import Message
from ..constants import BusType, NameFlag, RequestNameReply, ReleaseNameReply, MessageType, MessageFlag
from ..service import ServiceInterface
from ..errors import AuthError
from .proxy_object import ProxyObject
from .. import introspection as intr
from ..auth import Authenticator, AuthExternal
import logging
import array
import asyncio
from asyncio import Queue
import socket
from copy import copy
from typing import Optional
def _future_set_exception(fut, exc):
if fut is not None and not fut.done():
fut.set_exception(exc)
def _future_set_result(fut, result):
if fut is not None and not fut.done():
fut.set_result(result)
class _MessageWriter:
def __init__(self, bus):
self.messages = Queue()
self.negotiate_unix_fd = bus._negotiate_unix_fd
self.bus = bus
self.sock = bus._sock
self.loop = bus._loop
self.buf = None
self.fd = bus._fd
self.offset = 0
self.unix_fds = None
self.fut = None
def write_callback(self):
try:
while True:
if self.buf is None:
if self.messages.qsize() == 0:
# nothing more to write
self.loop.remove_writer(self.fd)
return
buf, unix_fds, fut = self.messages.get_nowait()
self.unix_fds = unix_fds
self.buf = memoryview(buf)
self.offset = 0
self.fut = fut
if self.unix_fds and self.negotiate_unix_fd:
ancdata = [(socket.SOL_SOCKET, socket.SCM_RIGHTS,
array.array("i", self.unix_fds))]
self.offset += self.sock.sendmsg([self.buf[self.offset:]], ancdata)
self.unix_fds = None
else:
self.offset += self.sock.send(self.buf[self.offset:])
if self.offset >= len(self.buf):
# finished writing
self.buf = None
_future_set_result(self.fut, None)
else:
# wait for writable
return
except Exception as e:
_future_set_exception(self.fut, e)
self.bus._finalize(e)
def buffer_message(self, msg: Message, future=None):
self.messages.put_nowait(
(msg._marshall(negotiate_unix_fd=self.negotiate_unix_fd), copy(msg.unix_fds), future))
def schedule_write(self, msg: Message = None, future=None):
if msg is not None:
self.buffer_message(msg, future)
if self.bus.unique_name:
# don't run the writer until the bus is ready to send messages
self.loop.add_writer(self.fd, self.write_callback)
class MessageBus(BaseMessageBus):
"""The message bus implementation for use with asyncio.
The message bus class is the entry point into all the features of the
library. It sets up a connection to the DBus daemon and exposes an
interface to send and receive messages and expose services.
You must call :func:`connect() <dbus_next.aio.MessageBus.connect>` before
using this message bus.
:param bus_type: The type of bus to connect to. Affects the search path for
the bus address.
:type bus_type: :class:`BusType <dbus_next.BusType>`
:param bus_address: A specific bus address to connect to. Should not be
used under normal circumstances.
:param auth: The authenticator to use, defaults to an instance of
:class:`AuthExternal <dbus_next.auth.AuthExternal>`.
:type auth: :class:`Authenticator <dbus_next.auth.Authenticator>`
:param negotiate_unix_fd: Allow the bus to send and receive Unix file
descriptors (DBus type 'h'). This must be supported by the transport.
:type negotiate_unix_fd: bool
:ivar unique_name: The unique name of the message bus connection. It will
be :class:`None` until the message bus connects.
:vartype unique_name: str
:ivar connected: True if this message bus is expected to be able to send
and receive messages.
:vartype connected: bool
"""
def __init__(self,
bus_address: str = None,
bus_type: BusType = BusType.SESSION,
auth: Authenticator = None,
negotiate_unix_fd=False):
super().__init__(bus_address, bus_type, ProxyObject)
self._negotiate_unix_fd = negotiate_unix_fd
self._loop = asyncio.get_event_loop()
self._unmarshaller = self._create_unmarshaller()
self._writer = _MessageWriter(self)
if auth is None:
self._auth = AuthExternal()
else:
self._auth = auth
self._disconnect_future = self._loop.create_future()
async def connect(self) -> 'MessageBus':
"""Connect this message bus to the DBus daemon.
This method must be called before the message bus can be used.
:returns: This message bus for convenience.
:rtype: :class:`MessageBus <dbus_next.aio.MessageBus>`
:raises:
- :class:`AuthError <dbus_next.AuthError>` - If authorization to \
the DBus daemon failed.
- :class:`Exception` - If there was a connection error.
"""
await self._authenticate()
future = self._loop.create_future()
self._loop.add_reader(self._fd, self._message_reader)
def on_hello(reply, err):
try:
if err:
raise err
self.unique_name = reply.body[0]
self._writer.schedule_write()
_future_set_result(future, self)
except Exception as e:
_future_set_exception(future, e)
self.disconnect()
self._finalize(err)
hello_msg = Message(destination='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus',
member='Hello',
serial=self.next_serial())
self._method_return_handlers[hello_msg.serial] = on_hello
self._stream.write(hello_msg._marshall())
self._stream.flush()
return await future
async def introspect(self, bus_name: str, path: str, timeout: float = 30.0) -> intr.Node:
"""Get introspection data for the node at the given path from the given
bus name.
Calls the standard ``org.freedesktop.DBus.Introspectable.Introspect``
on the bus for the path.
:param bus_name: The name to introspect.
:type bus_name: str
:param path: The path to introspect.
:type path: str
:param timeout: The timeout to introspect.
:type timeout: float
:returns: The introspection data for the name at the path.
:rtype: :class:`Node <dbus_next.introspection.Node>`
:raises:
- :class:`InvalidObjectPathError <dbus_next.InvalidObjectPathError>` \
- If the given object path is not valid.
- :class:`InvalidBusNameError <dbus_next.InvalidBusNameError>` - If \
the given bus name is not valid.
- :class:`DBusError <dbus_next.DBusError>` - If the service threw \
an error for the method call or returned an invalid result.
- :class:`Exception` - If a connection error occurred.
- :class:`asyncio.TimeoutError` - Waited for future but time run out.
"""
future = self._loop.create_future()
def reply_handler(reply, err):
if err:
_future_set_exception(future, err)
else:
_future_set_result(future, reply)
super().introspect(bus_name, path, reply_handler)
return await asyncio.wait_for(future, timeout=timeout)
async def request_name(self, name: str, flags: NameFlag = NameFlag.NONE) -> RequestNameReply:
"""Request that this message bus owns the given name.
:param name: The name to request.
:type name: str
:param flags: Name flags that affect the behavior of the name request.
:type flags: :class:`NameFlag <dbus_next.NameFlag>`
:returns: The reply to the name request.
:rtype: :class:`RequestNameReply <dbus_next.RequestNameReply>`
:raises:
- :class:`InvalidBusNameError <dbus_next.InvalidBusNameError>` - If \
the given bus name is not valid.
- :class:`DBusError <dbus_next.DBusError>` - If the service threw \
an error for the method call or returned an invalid result.
- :class:`Exception` - If a connection error occurred.
"""
future = self._loop.create_future()
def reply_handler(reply, err):
if err:
_future_set_exception(future, err)
else:
_future_set_result(future, reply)
super().request_name(name, flags, reply_handler)
return await future
async def release_name(self, name: str) -> ReleaseNameReply:
"""Request that this message bus release the given name.
:param name: The name to release.
:type name: str
:returns: The reply to the release request.
:rtype: :class:`ReleaseNameReply <dbus_next.ReleaseNameReply>`
:raises:
- :class:`InvalidBusNameError <dbus_next.InvalidBusNameError>` - If \
the given bus name is not valid.
- :class:`DBusError <dbus_next.DBusError>` - If the service threw \
an error for the method call or returned an invalid result.
- :class:`Exception` - If a connection error occurred.
"""
future = self._loop.create_future()
def reply_handler(reply, err):
if err:
_future_set_exception(future, err)
else:
_future_set_result(future, reply)
super().release_name(name, reply_handler)
return await future
async def call(self, msg: Message) -> Optional[Message]:
"""Send a method call and wait for a reply from the DBus daemon.
:param msg: The method call message to send.
:type msg: :class:`Message <dbus_next.Message>`
:returns: A message in reply to the message sent. If the message does
not expect a reply based on the message flags or type, returns
``None`` after the message is sent.
:rtype: :class:`Message <dbus_next.Message>` or :class:`None` if no reply is expected.
:raises:
- :class:`Exception` - If a connection error occurred.
"""
if msg.flags & MessageFlag.NO_REPLY_EXPECTED or msg.message_type is not MessageType.METHOD_CALL:
await self.send(msg)
return None
future = self._loop.create_future()
def reply_handler(reply, err):
if not future.done():
if err:
_future_set_exception(future, err)
else:
_future_set_result(future, reply)
self._call(msg, reply_handler)
await future
return future.result()
def send(self, msg: Message):
"""Asynchronously send a message on the message bus.
.. note:: This method may change to a couroutine function in the 1.0
release of the library.
:param msg: The message to send.
:type msg: :class:`Message <dbus_next.Message>`
:returns: A future that resolves when the message is sent or a
connection error occurs.
:rtype: :class:`Future <asyncio.Future>`
"""
if not msg.serial:
msg.serial = self.next_serial()
future = self._loop.create_future()
self._writer.schedule_write(msg, future)
return future
def get_proxy_object(self, bus_name: str, path: str, introspection: intr.Node) -> ProxyObject:
return super().get_proxy_object(bus_name, path, introspection)
async def wait_for_disconnect(self):
"""Wait for the message bus to disconnect.
:returns: :class:`None` when the message bus has disconnected.
:rtype: :class:`None`
:raises:
- :class:`Exception` - If connection was terminated unexpectedly or \
an internal error occurred in the library.
"""
return await self._disconnect_future
def _make_method_handler(self, interface, method):
if not asyncio.iscoroutinefunction(method.fn):
return super()._make_method_handler(interface, method)
def handler(msg, send_reply):
def done(fut):
with send_reply:
result = fut.result()
body, unix_fds = ServiceInterface._fn_result_to_body(
result, method.out_signature_tree)
send_reply(Message.new_method_return(msg, method.out_signature, body, unix_fds))
args = ServiceInterface._msg_body_to_args(msg)
fut = asyncio.ensure_future(method.fn(interface, *args))
fut.add_done_callback(done)
return handler
def _message_reader(self):
try:
while True:
if self._unmarshaller.unmarshall():
self._on_message(self._unmarshaller.message)
self._unmarshaller = self._create_unmarshaller()
else:
break
except Exception as e:
self._finalize(e)
async def _auth_readline(self):
buf = b''
while buf[-2:] != b'\r\n':
buf += await self._loop.sock_recv(self._sock, 2)
return buf[:-2].decode()
async def _authenticate(self):
await self._loop.sock_sendall(self._sock, b'\0')
first_line = self._auth._authentication_start(negotiate_unix_fd=self._negotiate_unix_fd)
if first_line is not None:
if type(first_line) is not str:
raise AuthError('authenticator gave response not type str')
await self._loop.sock_sendall(self._sock, Authenticator._format_line(first_line))
while True:
response = self._auth._receive_line(await self._auth_readline())
if response is not None:
await self._loop.sock_sendall(self._sock, Authenticator._format_line(response))
self._stream.flush()
if response == 'BEGIN':
break
def _create_unmarshaller(self):
sock = None
if self._negotiate_unix_fd:
sock = self._sock
return Unmarshaller(self._stream, sock)
def _finalize(self, err=None):
try:
self._loop.remove_reader(self._fd)
except Exception:
logging.warning('could not remove message reader', exc_info=True)
try:
self._loop.remove_writer(self._fd)
except Exception:
logging.warning('could not remove message writer', exc_info=True)
super()._finalize(err)
if self._disconnect_future.done():
return
if err and not self._user_disconnect:
_future_set_exception(self._disconnect_future, err)
else:
_future_set_result(self._disconnect_future, None)
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,033
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/test/util.py
|
_has_gi = None
skip_reason_no_gi = 'glib tests require python3-gi'
def check_gi_repository():
global _has_gi
if _has_gi is not None:
return _has_gi
try:
from gi.repository import GLib
_has_gi = True
return _has_gi
except ImportError:
_has_gi = False
return _has_gi
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,034
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/test/client/test_properties.py
|
from dbus_next import aio, glib, Message, DBusError
from dbus_next.service import ServiceInterface, dbus_property, PropertyAccess
from test.util import check_gi_repository, skip_reason_no_gi
import pytest
has_gi = check_gi_repository()
class ExampleInterface(ServiceInterface):
def __init__(self):
super().__init__('test.interface')
self._some_property = 'foo'
self.error_name = 'test.error'
self.error_text = 'i am bad'
self._int64_property = -10000
@dbus_property()
def SomeProperty(self) -> 's':
return self._some_property
@SomeProperty.setter
def SomeProperty(self, val: 's'):
self._some_property = val
@dbus_property(access=PropertyAccess.READ)
def Int64Property(self) -> 'x':
return self._int64_property
@dbus_property()
def ErrorThrowingProperty(self) -> 's':
raise DBusError(self.error_name, self.error_text)
@ErrorThrowingProperty.setter
def ErrorThrowingProperty(self, val: 's'):
raise DBusError(self.error_name, self.error_text)
@pytest.mark.asyncio
async def test_aio_properties():
service_bus = await aio.MessageBus().connect()
service_interface = ExampleInterface()
service_bus.export('/test/path', service_interface)
bus = await aio.MessageBus().connect()
obj = bus.get_proxy_object(service_bus.unique_name, '/test/path',
service_bus._introspect_export_path('/test/path'))
interface = obj.get_interface(service_interface.name)
prop = await interface.get_some_property()
assert prop == service_interface._some_property
prop = await interface.get_int64_property()
assert prop == service_interface._int64_property
await interface.set_some_property('different')
assert service_interface._some_property == 'different'
with pytest.raises(DBusError):
try:
prop = await interface.get_error_throwing_property()
assert False, prop
except DBusError as e:
assert e.type == service_interface.error_name
assert e.text == service_interface.error_text
assert type(e.reply) is Message
raise e
with pytest.raises(DBusError):
try:
await interface.set_error_throwing_property('different')
except DBusError as e:
assert e.type == service_interface.error_name
assert e.text == service_interface.error_text
assert type(e.reply) is Message
raise e
service_bus.disconnect()
bus.disconnect()
@pytest.mark.skipif(not has_gi, reason=skip_reason_no_gi)
def test_glib_properties():
service_bus = glib.MessageBus().connect_sync()
service_interface = ExampleInterface()
service_bus.export('/test/path', service_interface)
bus = glib.MessageBus().connect_sync()
obj = bus.get_proxy_object(service_bus.unique_name, '/test/path',
service_bus._introspect_export_path('/test/path'))
interface = obj.get_interface(service_interface.name)
prop = interface.get_some_property_sync()
assert prop == service_interface._some_property
interface.set_some_property_sync('different')
assert service_interface._some_property == 'different'
with pytest.raises(DBusError):
try:
prop = interface.get_error_throwing_property_sync()
assert False, prop
except DBusError as e:
assert e.type == service_interface.error_name
assert e.text == service_interface.error_text
assert type(e.reply) is Message
raise e
with pytest.raises(DBusError):
try:
interface.set_error_throwing_property_sync('different2')
except DBusError as e:
assert e.type == service_interface.error_name
assert e.text == service_interface.error_text
assert type(e.reply) is Message
raise e
service_bus.disconnect()
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,035
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/_private/marshaller.py
|
from ..signature import SignatureTree
from struct import pack
class Marshaller:
def __init__(self, signature, body):
self.signature_tree = SignatureTree._get(signature)
self.signature_tree.verify(body)
self.buffer = bytearray()
self.body = body
self.writers = {
'y': self.write_byte,
'b': self.write_boolean,
'n': self.write_int16,
'q': self.write_uint16,
'i': self.write_int32,
'u': self.write_uint32,
'x': self.write_int64,
't': self.write_uint64,
'd': self.write_double,
'h': self.write_uint32,
'o': self.write_string,
's': self.write_string,
'g': self.write_signature,
'a': self.write_array,
'(': self.write_struct,
'{': self.write_dict_entry,
'v': self.write_variant
}
def align(self, n):
offset = n - len(self.buffer) % n
if offset == 0 or offset == n:
return 0
self.buffer.extend(bytes(offset))
return offset
def write_byte(self, byte, _=None):
self.buffer.append(byte)
return 1
def write_boolean(self, boolean, _=None):
if boolean:
return self.write_uint32(1)
else:
return self.write_uint32(0)
def write_int16(self, int16, _=None):
written = self.align(2)
self.buffer.extend(pack('<h', int16))
return written + 2
def write_uint16(self, uint16, _=None):
written = self.align(2)
self.buffer.extend(pack('<H', uint16))
return written + 2
def write_int32(self, int32, _):
written = self.align(4)
self.buffer.extend(pack('<i', int32))
return written + 4
def write_uint32(self, uint32, _=None):
written = self.align(4)
self.buffer.extend(pack('<I', uint32))
return written + 4
def write_int64(self, int64, _=None):
written = self.align(8)
self.buffer.extend(pack('<q', int64))
return written + 8
def write_uint64(self, uint64, _=None):
written = self.align(8)
self.buffer.extend(pack('<Q', uint64))
return written + 8
def write_double(self, double, _=None):
written = self.align(8)
self.buffer.extend(pack('<d', double))
return written + 8
def write_signature(self, signature, _=None):
signature = signature.encode()
signature_len = len(signature)
self.buffer.append(signature_len)
self.buffer.extend(signature)
self.buffer.append(0)
return signature_len + 2
def write_string(self, value, _=None):
value = value.encode()
value_len = len(value)
written = self.write_uint32(value_len)
self.buffer.extend(value)
written += value_len
self.buffer.append(0)
written += 1
return written
def write_variant(self, variant, _=None):
written = self.write_signature(variant.signature)
written += self.write_single(variant.type, variant.value)
return written
def write_array(self, array, type_):
# TODO max array size is 64MiB (67108864 bytes)
written = self.align(4)
# length placeholder
offset = len(self.buffer)
written += self.write_uint32(0)
child_type = type_.children[0]
if child_type.token in 'xtd{(':
# the first alignment is not included in array size
written += self.align(8)
array_len = 0
if child_type.token == '{':
for key, value in array.items():
array_len += self.write_dict_entry([key, value], child_type)
elif child_type.token == 'y':
array_len = len(array)
self.buffer.extend(array)
else:
for value in array:
array_len += self.write_single(child_type, value)
array_len_packed = pack('<I', array_len)
for i in range(offset, offset + 4):
self.buffer[i] = array_len_packed[i - offset]
return written + array_len
def write_struct(self, array, type_):
written = self.align(8)
for i, value in enumerate(array):
written += self.write_single(type_.children[i], value)
return written
def write_dict_entry(self, dict_entry, type_):
written = self.align(8)
written += self.write_single(type_.children[0], dict_entry[0])
written += self.write_single(type_.children[1], dict_entry[1])
return written
def write_single(self, type_, body):
t = type_.token
if t not in self.writers:
raise NotImplementedError(f'type isnt implemented yet: "{t}"')
return self.writers[t](body, type_)
def marshall(self):
self.buffer.clear()
for i, type_ in enumerate(self.signature_tree.types):
self.write_single(type_, self.body[i])
return self.buffer
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,036
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/test/test_address_parser.py
|
from dbus_next._private.address import parse_address
def test_valid_addresses():
valid_addresses = {
'unix:path=/run/user/1000/bus': [('unix', {
'path': '/run/user/1000/bus'
})],
'unix:abstract=/tmp/dbus-ft9sODWpZk,guid=a7b1d5912379c2d471165e9b5cb74a03': [('unix', {
'abstract':
'/tmp/dbus-ft9sODWpZk',
'guid':
'a7b1d5912379c2d471165e9b5cb74a03'
})],
'unix1:key1=val1;unix2:key2=val2': [('unix1', {
'key1': 'val1'
}), ('unix2', {
'key2': 'val2'
})],
'unix:escaped=hello%20world': [('unix', {
'escaped': 'hello world'
})],
'tcp:host=127.0.0.1,port=55556': [('tcp', {
'host': '127.0.0.1',
'port': '55556'
})]
}
for address, parsed in valid_addresses.items():
assert parse_address(address) == parsed
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,037
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/test/test_tcp_address.py
|
from dbus_next.aio import MessageBus
from dbus_next import Message
from dbus_next._private.address import parse_address
import asyncio
import pytest
import os
@pytest.mark.asyncio
async def test_tcp_connection_with_forwarding(event_loop):
closables = []
host = '127.0.0.1'
port = '55556'
addr_info = parse_address(os.environ.get('DBUS_SESSION_BUS_ADDRESS'))
assert addr_info
assert 'abstract' in addr_info[0][1]
path = f'\0{addr_info[0][1]["abstract"]}'
async def handle_connection(tcp_reader, tcp_writer):
unix_reader, unix_writer = await asyncio.open_unix_connection(path)
closables.append(tcp_writer)
closables.append(unix_writer)
async def handle_read():
while True:
data = await tcp_reader.read(1)
if not data:
break
unix_writer.write(data)
async def handle_write():
while True:
data = await unix_reader.read(1)
if not data:
break
tcp_writer.write(data)
asyncio.run_coroutine_threadsafe(handle_read(), event_loop)
asyncio.run_coroutine_threadsafe(handle_write(), event_loop)
server = await asyncio.start_server(handle_connection, host, port)
closables.append(server)
bus = await MessageBus(bus_address=f'tcp:host={host},port={port}').connect()
# basic tests to see if it works
result = await bus.call(
Message(destination='org.freedesktop.DBus',
path='/org/freedesktop/DBus',
interface='org.freedesktop.DBus.Peer',
member='Ping'))
assert result
intr = await bus.introspect('org.freedesktop.DBus', '/org/freedesktop/DBus')
obj = bus.get_proxy_object('org.freedesktop.DBus', '/org/freedesktop/DBus', intr)
iface = obj.get_interface('org.freedesktop.DBus.Peer')
await iface.call_ping()
assert bus._sock.getpeername()[0] == host
assert bus._sock.getsockname()[0] == host
assert bus._sock.gettimeout() == 0
assert bus._stream.closed is False
for c in closables:
c.close()
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,038
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/bench/unmarshall.py
|
import io
import timeit
from dbus_next._private.unmarshaller import Unmarshaller
bluez_rssi_message = (
"6c04010134000000e25389019500000001016f00250000002f6f72672f626c75657a2f686369302f6465"
"765f30385f33415f46325f31455f32425f3631000000020173001f0000006f72672e667265656465736b"
"746f702e444275732e50726f7065727469657300030173001100000050726f706572746965734368616e"
"67656400000000000000080167000873617b73767d617300000007017300040000003a312e3400000000"
"110000006f72672e626c75657a2e446576696365310000000e0000000000000004000000525353490001"
"6e00a7ff000000000000"
)
def unmarhsall_bluez_rssi_message():
Unmarshaller(io.BytesIO(bytes.fromhex(bluez_rssi_message))).unmarshall()
count = 1000000
time = timeit.Timer(unmarhsall_bluez_rssi_message).timeit(count)
print(f"Unmarshalling {count} bluetooth rssi messages took {time} seconds")
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,039
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/test/test_signature.py
|
from dbus_next import SignatureTree, SignatureBodyMismatchError, Variant
from dbus_next._private.util import signature_contains_type
import pytest
def assert_simple_type(signature, type_):
assert type_.token == signature
assert type_.signature == signature
assert len(type_.children) == 0
def test_simple():
tree = SignatureTree('s')
assert len(tree.types) == 1
assert_simple_type('s', tree.types[0])
def test_multiple_simple():
tree = SignatureTree('sss')
assert len(tree.types) == 3
for i in range(0, 3):
assert_simple_type('s', tree.types[i])
def test_array():
tree = SignatureTree('as')
assert len(tree.types) == 1
child = tree.types[0]
assert child.signature == 'as'
assert child.token == 'a'
assert len(child.children) == 1
assert_simple_type('s', child.children[0])
def test_array_multiple():
tree = SignatureTree('asasass')
assert len(tree.types) == 4
assert_simple_type('s', tree.types[3])
for i in range(0, 3):
array_child = tree.types[i]
assert array_child.token == 'a'
assert array_child.signature == 'as'
assert len(array_child.children) == 1
assert_simple_type('s', array_child.children[0])
def test_array_nested():
tree = SignatureTree('aas')
assert len(tree.types) == 1
child = tree.types[0]
assert child.token == 'a'
assert child.signature == 'aas'
assert len(child.children) == 1
nested_child = child.children[0]
assert nested_child.token == 'a'
assert nested_child.signature == 'as'
assert len(nested_child.children) == 1
assert_simple_type('s', nested_child.children[0])
def test_simple_struct():
tree = SignatureTree('(sss)')
assert len(tree.types) == 1
child = tree.types[0]
assert child.signature == '(sss)'
assert len(child.children) == 3
for i in range(0, 3):
assert_simple_type('s', child.children[i])
def test_nested_struct():
tree = SignatureTree('(s(s(s)))')
assert len(tree.types) == 1
child = tree.types[0]
assert child.signature == '(s(s(s)))'
assert child.token == '('
assert len(child.children) == 2
assert_simple_type('s', child.children[0])
first_nested = child.children[1]
assert first_nested.token == '('
assert first_nested.signature == '(s(s))'
assert len(first_nested.children) == 2
assert_simple_type('s', first_nested.children[0])
second_nested = first_nested.children[1]
assert second_nested.token == '('
assert second_nested.signature == '(s)'
assert len(second_nested.children) == 1
assert_simple_type('s', second_nested.children[0])
def test_struct_multiple():
tree = SignatureTree('(s)(s)(s)')
assert len(tree.types) == 3
for i in range(0, 3):
child = tree.types[0]
assert child.token == '('
assert child.signature == '(s)'
assert len(child.children) == 1
assert_simple_type('s', child.children[0])
def test_array_of_structs():
tree = SignatureTree('a(ss)')
assert len(tree.types) == 1
child = tree.types[0]
assert child.token == 'a'
assert child.signature == 'a(ss)'
assert len(child.children) == 1
struct_child = child.children[0]
assert struct_child.token == '('
assert struct_child.signature == '(ss)'
assert len(struct_child.children) == 2
for i in range(0, 2):
assert_simple_type('s', struct_child.children[i])
def test_dict_simple():
tree = SignatureTree('a{ss}')
assert len(tree.types) == 1
child = tree.types[0]
assert child.signature == 'a{ss}'
assert child.token == 'a'
assert len(child.children) == 1
dict_child = child.children[0]
assert dict_child.token == '{'
assert dict_child.signature == '{ss}'
assert len(dict_child.children) == 2
assert_simple_type('s', dict_child.children[0])
assert_simple_type('s', dict_child.children[1])
def test_dict_of_structs():
tree = SignatureTree('a{s(ss)}')
assert len(tree.types) == 1
child = tree.types[0]
assert child.token == 'a'
assert child.signature == 'a{s(ss)}'
assert len(child.children) == 1
dict_child = child.children[0]
assert dict_child.token == '{'
assert dict_child.signature == '{s(ss)}'
assert len(dict_child.children) == 2
assert_simple_type('s', dict_child.children[0])
struct_child = dict_child.children[1]
assert struct_child.token == '('
assert struct_child.signature == '(ss)'
assert len(struct_child.children) == 2
for i in range(0, 2):
assert_simple_type('s', struct_child.children[i])
def test_contains_type():
tree = SignatureTree('h')
assert signature_contains_type(tree, [0], 'h')
assert not signature_contains_type(tree, [0], 'u')
tree = SignatureTree('ah')
assert signature_contains_type(tree, [[0]], 'h')
assert signature_contains_type(tree, [[0]], 'a')
assert not signature_contains_type(tree, [[0]], 'u')
tree = SignatureTree('av')
body = [[Variant('u', 0), Variant('i', 0), Variant('x', 0), Variant('v', Variant('s', 'hi'))]]
assert signature_contains_type(tree, body, 'u')
assert signature_contains_type(tree, body, 'x')
assert signature_contains_type(tree, body, 'v')
assert signature_contains_type(tree, body, 's')
assert not signature_contains_type(tree, body, 'o')
tree = SignatureTree('a{sv}')
body = {
'foo': Variant('h', 0),
'bar': Variant('i', 0),
'bat': Variant('x', 0),
'baz': Variant('v', Variant('o', '/hi'))
}
for expected in 'hixvso':
assert signature_contains_type(tree, [body], expected)
assert not signature_contains_type(tree, [body], 'b')
def test_invalid_variants():
tree = SignatureTree('a{sa{sv}}')
s_con = {
'type': '802-11-wireless',
'uuid': '1234',
'id': 'SSID',
}
s_wifi = {
'ssid': 'SSID',
'mode': 'infrastructure',
'hidden': True,
}
s_wsec = {
'key-mgmt': 'wpa-psk',
'auth-alg': 'open',
'psk': 'PASSWORD',
}
s_ip4 = {'method': 'auto'}
s_ip6 = {'method': 'auto'}
con = {
'connection': s_con,
'802-11-wireless': s_wifi,
'802-11-wireless-security': s_wsec,
'ipv4': s_ip4,
'ipv6': s_ip6
}
with pytest.raises(SignatureBodyMismatchError):
tree.verify([con])
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,040
|
altdesktop/python-dbus-next
|
refs/heads/master
|
/dbus_next/_private/address.py
|
from ..constants import BusType
from ..errors import InvalidAddressError
from urllib.parse import unquote
import re
import os
invalid_address_chars_re = re.compile(r'[^-0-9A-Za-z_/.%]')
def parse_address(address_str):
addresses = []
for address in filter(lambda a: a, address_str.split(';')):
if address.find(':') == -1:
raise InvalidAddressError('address did not contain a transport')
transport, opt_string = address.split(':', 1)
options = {}
for kv in filter(lambda s: s, opt_string.split(',')):
if kv.find('=') == -1:
raise InvalidAddressError('address option did not contain a value')
k, v = kv.split('=', 1)
if invalid_address_chars_re.search(v):
raise InvalidAddressError('address contains invalid characters')
# XXX the actual unquote rules are simpler than this
v = unquote(v)
options[k] = v
addresses.append((transport, options))
if not addresses:
raise InvalidAddressError(f'address string contained no addresses: "{address_str}"')
return addresses
def get_system_bus_address():
if 'DBUS_SYSTEM_BUS_ADDRESS' in os.environ:
return os.environ['DBUS_SYSTEM_BUS_ADDRESS']
else:
return 'unix:path=/var/run/dbus/system_bus_socket'
display_re = re.compile(r'.*:([0-9]+)\.?.*')
remove_quotes_re = re.compile(r'''^['"]?(.*?)['"]?$''')
def get_session_bus_address():
if 'DBUS_SESSION_BUS_ADDRESS' in os.environ:
return os.environ['DBUS_SESSION_BUS_ADDRESS']
home = os.environ['HOME']
if 'DISPLAY' not in os.environ:
raise InvalidAddressError(
'DBUS_SESSION_BUS_ADDRESS not set and could not get DISPLAY environment variable to get bus address'
)
display = os.environ['DISPLAY']
try:
display = display_re.search(display).group(1)
except Exception:
raise InvalidAddressError(
f'DBUS_SESSION_BUS_ADDRESS not set and could not parse DISPLAY environment variable to get bus address: {display}'
)
# XXX: this will block but they're very small files and fs operations
# should be fairly reliable. fix this by passing in an async func to read
# the file for each io backend.
machine_id = None
with open('/var/lib/dbus/machine-id') as f:
machine_id = f.read().rstrip()
dbus_info_file_name = f'{home}/.dbus/session-bus/{machine_id}-{display}'
dbus_info = None
try:
with open(dbus_info_file_name) as f:
dbus_info = f.read().rstrip()
except Exception:
raise InvalidAddressError(f'could not open dbus info file: {dbus_info_file_name}')
for line in dbus_info.split('\n'):
if line.strip().startswith('DBUS_SESSION_BUS_ADDRESS='):
_, addr = line.split('=', 1)
if not addr:
raise InvalidAddressError(
f'DBUS_SESSION_BUS_ADDRESS variable not set correctly in dbus info file: {dbus_info_file_name}'
)
addr = remove_quotes_re.search(addr).group(1)
return addr
raise InvalidAddressError('could not find dbus session bus address')
def get_bus_address(bus_type):
if bus_type == BusType.SESSION:
return get_session_bus_address()
elif bus_type == BusType.SYSTEM:
return get_system_bus_address()
else:
raise Exception('got unknown bus type: {bus_type}')
|
{"/test/service/test_methods.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/glib/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/constants.py", "/dbus_next/__init__.py"], "/test/service/test_properties.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/introspection.py", "/dbus_next/constants.py"], "/dbus_next/auth.py": ["/dbus_next/errors.py"], "/dbus_next/glib/message_bus.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/constants.py", "/dbus_next/message.py", "/dbus_next/message_bus.py", "/dbus_next/errors.py", "/dbus_next/glib/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/dbus_next/_private/unmarshaller.py": ["/dbus_next/message.py", "/dbus_next/_private/constants.py", "/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/errors.py"], "/examples/aio-tcp-notification.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/introspection.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/validators.py", "/dbus_next/errors.py"], "/dbus_next/aio/__init__.py": ["/dbus_next/aio/message_bus.py", "/dbus_next/aio/proxy_object.py"], "/test/test_glib_low_level.py": ["/dbus_next/__init__.py", "/test/util.py"], "/dbus_next/proxy_object.py": ["/dbus_next/validators.py", "/dbus_next/__init__.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/dbus_next/service.py": ["/dbus_next/constants.py", "/dbus_next/signature.py", "/dbus_next/__init__.py", "/dbus_next/errors.py", "/dbus_next/_private/util.py"], "/test/service/test_export.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_fd_passing.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/client/test_methods.py": ["/dbus_next/message.py", "/dbus_next/service.py", "/dbus_next/introspection.py", "/dbus_next/__init__.py", "/test/util.py"], "/test/service/test_standard_interfaces.py": ["/dbus_next/service.py", "/dbus_next/signature.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py"], "/test/test_validators.py": ["/dbus_next/__init__.py"], "/test/test_disconnect.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/test/test_request_name.py": ["/dbus_next/__init__.py", "/test/util.py"], "/examples/mpris.py": ["/dbus_next/aio/__init__.py"], "/dbus_next/signature.py": ["/dbus_next/validators.py", "/dbus_next/errors.py"], "/test/service/test_signals.py": ["/dbus_next/service.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/constants.py", "/dbus_next/signature.py"], "/dbus_next/__init__.py": ["/dbus_next/constants.py", "/dbus_next/errors.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/validators.py"], "/dbus_next/validators.py": ["/dbus_next/errors.py"], "/test/test_introspection.py": ["/dbus_next/__init__.py"], "/examples/example-service.py": ["/dbus_next/service.py", "/dbus_next/aio/message_bus.py", "/dbus_next/__init__.py"], "/dbus_next/aio/proxy_object.py": ["/dbus_next/proxy_object.py", "/dbus_next/message_bus.py", "/dbus_next/message.py", "/dbus_next/signature.py", "/dbus_next/errors.py", "/dbus_next/constants.py", "/dbus_next/_private/util.py", "/dbus_next/__init__.py"], "/test/test_aio_low_level.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/_private/util.py": ["/dbus_next/signature.py"], "/examples/aio-list-names.py": ["/dbus_next/__init__.py", "/dbus_next/aio/__init__.py"], "/test/service/test_decorators.py": ["/dbus_next/__init__.py", "/dbus_next/service.py"], "/examples/dbus-next-send.py": ["/dbus_next/validators.py", "/dbus_next/aio/__init__.py", "/dbus_next/__init__.py"], "/dbus_next/errors.py": ["/dbus_next/message.py", "/dbus_next/validators.py", "/dbus_next/constants.py"], "/dbus_next/message.py": ["/dbus_next/_private/marshaller.py", "/dbus_next/constants.py", "/dbus_next/_private/constants.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py"], "/test/test_marshaller.py": ["/dbus_next/_private/unmarshaller.py", "/dbus_next/__init__.py"], "/examples/glib-list-names.py": ["/dbus_next/__init__.py"], "/dbus_next/message_bus.py": ["/dbus_next/_private/address.py", "/dbus_next/_private/util.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/validators.py", "/dbus_next/errors.py", "/dbus_next/signature.py", "/dbus_next/proxy_object.py", "/dbus_next/__init__.py"], "/test/test_big_message.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/aio/message_bus.py": ["/dbus_next/message_bus.py", "/dbus_next/_private/unmarshaller.py", "/dbus_next/message.py", "/dbus_next/constants.py", "/dbus_next/service.py", "/dbus_next/errors.py", "/dbus_next/aio/proxy_object.py", "/dbus_next/__init__.py", "/dbus_next/auth.py"], "/test/client/test_properties.py": ["/dbus_next/__init__.py", "/dbus_next/service.py", "/test/util.py"], "/dbus_next/_private/marshaller.py": ["/dbus_next/signature.py"], "/test/test_address_parser.py": ["/dbus_next/_private/address.py"], "/test/test_tcp_address.py": ["/dbus_next/aio/__init__.py", "/dbus_next/__init__.py", "/dbus_next/_private/address.py"], "/bench/unmarshall.py": ["/dbus_next/_private/unmarshaller.py"], "/test/test_signature.py": ["/dbus_next/__init__.py", "/dbus_next/_private/util.py"], "/dbus_next/_private/address.py": ["/dbus_next/constants.py", "/dbus_next/errors.py"]}
|
9,058
|
12wzy/bilibili
|
refs/heads/master
|
/bili/pipelines.py
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import json
import codecs
import time
from .videoItems import videoItem
from .videoTagItems import videoTagItem
import logging
import os
from bili.util.database.mysql import MySQL
class TutorialPipeline(object):
def __init__(self):
self.mysql = MySQL()
self.connection = self.mysql.createConnection()
def process_item(self, item, spider):
sql = ""
try:
if isinstance(item, videoItem):
sql = self.mysql.insert2video(item, self.connection)
elif isinstance(item, videoTagItem):
sql = self.mysql.insert2tag(item, self.connection)
logging.info("[EXCUTE SQL] {sql}".format(sql=sql))
except Exception as e:
with open('{}/bilibiliSpider/log/exception_log_{}.txt'.format(os.getcwd(), time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime(time.time()))), 'w') as f:
f.write("=============================================\n")
f.write(sql+'\n')
f.write(str(e)+'\n')
return item
def spider_closed(self, spider):
self.mysql.closeConnection(self.connection)
|
{"/bili/pipelines.py": ["/bili/videoTagItems.py", "/bili/util/database/mysql.py"], "/bili/spiders/video.py": ["/bili/videoTagItems.py"]}
|
9,059
|
12wzy/bilibili
|
refs/heads/master
|
/bili/spiders/video.py
|
import scrapy
import logging
import json
from scrapy.contrib.spiders import CrawlSpider
from ..videoItems import videoItem
from ..videoTagItems import videoTagItem
HTTPS = "https:"
HOST = "https://api.bilibili.com"
class biliSpider(CrawlSpider):
name = "biliSpider"
start_urls = []
tags_url = "https://api.bilibili.com/x/tag/archive/tags?aid={}"
for i in range(50, 100):
start_urls.append("{}/x/web-interface/view?aid={}".format(HOST, str(i + 1)))
def parse(self, response):
self.log('Hi, this is an item page! %s' % response.url, level=logging.WARNING)
videoInfo = response.body.decode('utf-8')
videoInfoJson = json.loads(videoInfo)
exist = int(videoInfoJson['code'])
if exist == 0:
video = videoItem()
video["videoId"] = videoInfoJson['data']['aid']
video["videoLabelId"] = videoInfoJson['data']['tid']
video["videoLabelName"] = videoInfoJson['data']['tname']
video["videoTitle"] = videoInfoJson['data']['title']
video["pubDate"] = videoInfoJson['data']['pubdate']
video["view"] = videoInfoJson['data']['stat']['view']
video["danmaku"] = videoInfoJson['data']['stat']['danmaku']
video["reply"] = videoInfoJson['data']['stat']['reply']
video["favorite"] = videoInfoJson['data']['stat']['favorite']
video["coin"] = videoInfoJson['data']['stat']['coin']
video["share"] = videoInfoJson['data']['stat']['share']
video["ownerId"] = videoInfoJson['data']['owner']['mid']
video["ownerName"] = videoInfoJson['data']['owner']['name']
yield video
yield scrapy.Request(self.tags_url.format(video["videoId"]), callback=self.parse_tags)
def parse_tags(self, response):
tag_info = response.body.decode('utf-8')
tag_info_json = json.loads(tag_info)
tags = tag_info_json['data']
video_id = response.url.split('?aid=')[1]
if tags is not None:
self.log('Tag is not none and the number is %d' % len(tags), level=logging.INFO)
tag_item = videoTagItem()
tag_item['videoId'] = int(video_id)
for tag in tags:
tag_item['tagId'] = tag['tag_id']
tag_item['tagName'] = tag['tag_name']
self.log('tag item: %s' % str(tag_item), level=logging.INFO)
yield tag_item
|
{"/bili/pipelines.py": ["/bili/videoTagItems.py", "/bili/util/database/mysql.py"], "/bili/spiders/video.py": ["/bili/videoTagItems.py"]}
|
9,060
|
12wzy/bilibili
|
refs/heads/master
|
/bili/util/database/mysql.py
|
import pymysql
import time
class MySQL():
def __init__(self):
self.host = "localhost"
self.user = 'root'
self.password = 'root'
self.dbname = 'bili'
self.charset = 'utf8mb4'
self.cursorclass = pymysql.cursors.DictCursor
self.dateFormat = "%Y-%m-%d %H:%M:%S"
def createConnection(self):
connection = pymysql.connect(host=self.host,
user=self.user,
password=self.password,
db=self.dbname,
charset=self.charset,
cursorclass=self.cursorclass)
return connection
def insert2video(self, item, connection):
s = "123'123"
s.replace("'", "")
insertIntoVideo = "INSERT INTO bili.video (`videoId`, `videoLabelId`, `videoLabelName`, `videoTitle`, `pubDate`, `view`, `danmaku`, `reply`, `favorite`, `coin`, `share`, `ownerId`, `ownerName`) VALUES ({}, {}, '{}', '{}', '{}', {}, {}, {}, {}, {}, {}, {}, '{}')"
videoId = item['videoId']
videoLabelId = item['videoLabelId']
videoLabelName = item['videoLabelName'].replace("'", "")
videoTitle = item['videoTitle'].replace("'", "")
pubDate = time.strftime(self.dateFormat, time.localtime(item['pubDate']))
view = item['view']
danmaku = item['danmaku']
reply = item['reply']
favorite = item['favorite']
coin = item['coin']
share = item['share']
ownerId = item['ownerId']
ownerName = item['ownerName'].replace("'", "")
sql = insertIntoVideo.format(videoId, videoLabelId, videoLabelName, videoTitle, pubDate, view, danmaku, reply,
favorite, coin, share, ownerId, ownerName)
with connection.cursor() as cursor:
cursor.execute(sql)
connection.commit()
return sql
def insert2tag(self, item, connection):
insertIntoTag = "INSERT INTO bili.tag (`videoId`, `tagId`, `tagName`) VALUES ({}, {}, '{}')"
videoId = item['videoId']
tagId = item['tagId']
tagName = item['tagName'].replace("'", "")
sql = insertIntoTag.format(videoId, tagId, tagName)
with connection.cursor() as cursor:
cursor.execute(sql)
connection.commit()
return sql
def closeConnection(self, connection):
connection.close()
|
{"/bili/pipelines.py": ["/bili/videoTagItems.py", "/bili/util/database/mysql.py"], "/bili/spiders/video.py": ["/bili/videoTagItems.py"]}
|
9,061
|
12wzy/bilibili
|
refs/heads/master
|
/bili/settings.py
|
# -*- coding: utf-8 -*-
# Scrapy settings for bilibiliSpider project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'bilibiliSpider'
SPIDER_MODULES = ['bilibiliSpider.spiders']
NEWSPIDER_MODULE = 'bilibiliSpider.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENTS = [
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)",
"Mozilla/4.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)",
"Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)",
"Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))",
"Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8; Zune 4.7)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8; Zune 4.7",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Zune 4.0; InfoPath.3; MS-RTC LM 8; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Zune 4.0; Tablet PC 2.0; InfoPath.3; .NET4.0C; .NET4.0E)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; chromeframe/11.0.696.57)",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0) chromeframe/10.0.648.205",
"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; chromeframe/11.0.696.57)",
"Mozilla/5.0 ( ; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)",
"Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 5.1; Trident/5.0)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 7.1; Trident/5.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; AskTB5.5)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.2; .NET4.0C; .NET4.0E)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 2.0.50727; SLCC2; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; FDM; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E; Tablet PC 2.0)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; Media Center PC 4.0; SLCC1; .NET CLR 3.0.04320)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.0; Trident/4.0; InfoPath.1; SV1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 3.0.04506.30)",
"Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.0; Trident/4.0; FBSMTWB; .NET CLR 2.0.34861; .NET CLR 3.0.3746.3218; .NET CLR 3.5.33652; msn OptimizedIE8;ENUS)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; Media Center PC 6.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.3; .NET4.0C; .NET4.0E; .NET CLR 3.5.30729; .NET CLR 3.0.30729; MS-RTC LM 8)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Zune 3.0)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; msn OptimizedIE8;ZHCN)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MS-RTC LM 8; InfoPath.3; .NET4.0C; .NET4.0E) chromeframe/8.0.552.224",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MS-RTC LM 8; .NET4.0C; .NET4.0E; Zune 4.7; InfoPath.3)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MS-RTC LM 8; .NET4.0C; .NET4.0E; Zune 4.7)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MS-RTC LM 8)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; Zune 4.0)",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E; MS-RTC LM 8; Zune 4.7)",
"Mozilla/5.0 (X11; Linux x86_64; rv:2.0b9pre) Gecko/20110111 Firefox/4.0b9pre",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b9pre) Gecko/20101228 Firefox/4.0b9pre",
"Mozilla/5.0 (Windows NT 5.1; rv:2.0b9pre) Gecko/20110105 Firefox/4.0b9pre",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b8pre) Gecko/20101114 Firefox/4.0b8pre",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b8pre) Gecko/20101213 Firefox/4.0b8pre",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b8pre) Gecko/20101128 Firefox/4.0b8pre",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b8pre) Gecko/20101114 Firefox/4.0b8pre",
"Mozilla/5.0 (Windows NT 5.1; rv:2.0b8pre) Gecko/20101127 Firefox/4.0b8pre",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b8) Gecko/20100101 Firefox/4.0b8",
"Mozilla/5.0 (Windows NT 6.1; rv:2.0b7pre) Gecko/20100921 Firefox/4.0b7pre",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b7) Gecko/20101111 Firefox/4.0b7",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b7) Gecko/20100101 Firefox/4.0b7",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b6pre) Gecko/20100903 Firefox/4.0b6pre",
"Mozilla/5.0 (Windows NT 6.1; rv:2.0b6pre) Gecko/20100903 Firefox/4.0b6pre Firefox/4.0b6pre",
"Mozilla/5.0 (X11; Linux x86_64; rv:2.0b4) Gecko/20100818 Firefox/4.0b4",
"Mozilla/5.0 (X11; Linux i686; rv:2.0b3pre) Gecko/20100731 Firefox/4.0b3pre",
"Mozilla/5.0 (Windows NT 5.2; rv:2.0b13pre) Gecko/20110304 Firefox/4.0b13pre",
"Mozilla/5.0 (Windows NT 5.1; rv:2.0b13pre) Gecko/20110223 Firefox/4.0b13pre",
"Mozilla/5.0 (X11; Linux i686; rv:2.0b12pre) Gecko/20110204 Firefox/4.0b12pre",
"Mozilla/5.0 (X11; Linux i686; rv:2.0b12pre) Gecko/20100101 Firefox/4.0b12pre",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b11pre) Gecko/20110128 Firefox/4.0b11pre",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b11pre) Gecko/20110131 Firefox/4.0b11pre",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b11pre) Gecko/20110129 Firefox/4.0b11pre",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b11pre) Gecko/20110128 Firefox/4.0b11pre",
"Mozilla/5.0 (Windows NT 6.1; rv:2.0b11pre) Gecko/20110126 Firefox/4.0b11pre",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b11pre) Gecko/20110126 Firefox/4.0b11pre",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b10pre) Gecko/20110118 Firefox/4.0b10pre",
"Mozilla/5.0 (Windows NT 6.1; rv:2.0b10pre) Gecko/20110113 Firefox/4.0b10pre",
"Mozilla/5.0 (X11; Linux i686; rv:2.0b10) Gecko/20100101 Firefox/4.0b10",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:2.0b10) Gecko/20110126 Firefox/4.0b10",
"Mozilla/5.0 (Windows NT 6.1; rv:2.0b10) Gecko/20110126 Firefox/4.0b10",
"Mozilla/5.0 (X11; U; Linux i686; ru; rv:1.9.3a5pre) Gecko/20100526 Firefox/3.7a5pre",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2b5) Gecko/20091204 Firefox/3.6b5",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2b5) Gecko/20091204 Firefox/3.6b5",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.9.2b5) Gecko/20091204 Firefox/3.6b5",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2) Gecko/20091218 Firefox 3.6b5",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.9.2b4) Gecko/20091124 Firefox/3.6b4 (.NET CLR 3.5.30729)",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2b4) Gecko/20091124 Firefox/3.6b4",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2b1) Gecko/20091014 Firefox/3.6b1 GTB5",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2a1pre) Gecko/20090428 Firefox/3.6a1pre",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2a1pre) Gecko/20090405 Firefox/3.6a1pre",
"Mozilla/5.0 (X11; U; Linux i686; ru-RU; rv:1.9.2a1pre) Gecko/20090405 Ubuntu/9.04 (jaunty) Firefox/3.6a1pre",
"Mozilla/5.0 (Windows; Windows NT 5.1; es-ES; rv:1.9.2a1pre) Gecko/20090402 Firefox/3.6a1pre",
"Mozilla/5.0 (Windows; Windows NT 5.1; en-US; rv:1.9.2a1pre) Gecko/20090402 Firefox/3.6a1pre",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; ja; rv:1.9.2a1pre) Gecko/20090402 Firefox/3.6a1pre (.NET CLR 3.5.30729)",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.9) Gecko/20100915 Gentoo Firefox/3.6.9",
"Mozilla/5.0 (X11; U; FreeBSD i386; en-US; rv:1.9.2.9) Gecko/20100913 Firefox/3.6.9",
"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.2.9) Gecko/20100824 Firefox/3.6.9 ( .NET CLR 3.5.30729; .NET CLR 4.0.20506)",
"Mozilla/5.0 (Windows; U; Windows NT 5.2; en-GB; rv:1.9.2.9) Gecko/20100824 Firefox/3.6.9",
"Mozilla/5.0 (X11; U; OpenBSD i386; en-US; rv:1.9.2.8) Gecko/20101230 Firefox/3.6.8",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.8) Gecko/20100804 Gentoo Firefox/3.6.8",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.8) Gecko/20100723 SUSE/3.6.8-0.1.1 Firefox/3.6.8",
"Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.2.8) Gecko/20100722 Ubuntu/10.04 (lucid) Firefox/3.6.8",
"Mozilla/5.0 (X11; U; Linux i686; ru; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8",
"Mozilla/5.0 (X11; U; Linux i686; fi-FI; rv:1.9.2.8) Gecko/20100723 Ubuntu/10.04 (lucid) Firefox/3.6.8",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.8) Gecko/20100727 Firefox/3.6.8",
"Mozilla/5.0 (X11; U; Linux i686; de-DE; rv:1.9.2.8) Gecko/20100725 Gentoo Firefox/3.6.8",
"Mozilla/5.0 (X11; U; FreeBSD i386; de-CH; rv:1.9.2.8) Gecko/20100729 Firefox/3.6.8",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; pt-BR; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 GTB7.1",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; it; rv:1.9.2.8) Gecko/20100722 AskTbADAP/3.9.1.14019 Firefox/3.6.8",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; fr; rv:1.9.2.8) Gecko/20100722 Firefox 3.6.8 GTB7.1",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 ( .NET CLR 3.5.30729; .NET4.0C)",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.8) Gecko/20100722 Firefox 3.6.8",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.3) Gecko/20121221 Firefox/3.6.8",
]
PROXIES = [
{'ip_port': 'ip:port', 'user_pass': ''},
{'ip_port': 'ip:port', 'user_pass': ''},
{'ip_port': 'ip:port', 'user_pass': ''},
{'ip_port': 'ip:port', 'user_pass': ''},
]
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
CONCURRENT_REQUESTS_PER_DOMAIN = 16
CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spiders middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'bilibiliSpider.middlewares.TutorialSpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
'bilibiliSpider.middlewares.TutorialDownloaderMiddleware': 543,
'bilibiliSpider.middlewares.RandomUserAgent': 1,
# 'spiders.middlewares.ProxyMiddleware': 100,
}
# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
'bilibiliSpider.pipelines.TutorialPipeline': 300,
}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
|
{"/bili/pipelines.py": ["/bili/videoTagItems.py", "/bili/util/database/mysql.py"], "/bili/spiders/video.py": ["/bili/videoTagItems.py"]}
|
9,062
|
12wzy/bilibili
|
refs/heads/master
|
/bili/videoTagItems.py
|
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class videoTagItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
videoId = scrapy.Field() # av Number
tagId = scrapy.Field()
tagName = scrapy.Field()
pass
|
{"/bili/pipelines.py": ["/bili/videoTagItems.py", "/bili/util/database/mysql.py"], "/bili/spiders/video.py": ["/bili/videoTagItems.py"]}
|
9,079
|
Harrison-Brown/Qolygen
|
refs/heads/main
|
/Qolygen.py
|
from Qolynomial import *
def Qolygen(points):
result = Qolynomial(0)
for i in range(len(points)):
point = points.pop(i)
q = Qolynomial(1)
d = 1
for p in points:
q *= Qolynomial(-p[0], 1)
d *= (point[0] - p[0])
q *= Qolynomial(Q(point[1], d))
result += q
points.insert(i, point)
return result
def main():
points = [(2, 3), (10, 3), (-2, 1), (7, 6)]
print('Points given:')
print(points)
q = Qolygen(points)
print('Function found:')
print('f(x) = ' + str(q))
for p in points:
print('f({}) = {}'.format(p[0], q(p[0])))
if __name__ == '__main__':
main()
|
{"/Qolygen.py": ["/Qolynomial.py"]}
|
9,080
|
Harrison-Brown/Qolygen
|
refs/heads/main
|
/Qolynomial.py
|
class Q:
def __init__(self, n, d = 1):
self.n = n
if n == 0:
d = 1
self.d = d
self.reduce()
def __add__(self, other):
n = (self.n * other.d) + (self.d * other.n)
d = self.d * other.d
return Q(n, d)
def __sub__(self, other):
other.n = -other.n
return self + other
def __mul__(self, other):
n = self.n * other.n
d = self.d * other.d
return Q(n, d)
def __pow__(self, power):
return Q(self.n**power, self.d**power)
def __truediv__(self, other):
other.n, other.d = other.d, other.n
return self * other
def reduce(self):
if self.d < 0:
self.d *= -1
self.n *= -1
a = max(self.n, self.d)
b = min(self.n, self.d)
while b:
a, b = b, a % b
a = abs(a)
self.n = self.n // a
self.d = self.d // a
def __repr__(self):
if self.d == 1:
return 'Q({})'.format(self.n)
else:
return 'Q({}, {})'.format(self.n, self.d)
def __str__(self):
if self.d == 1:
return '{}'.format(self.n)
else:
return '{}/{}'.format(self.n, self.d)
def __eq__(self, other):
if self.n == other.n and self.d == other.d:
return True
else:
return False
class Qolynomial():
def __init__(self, *coeffs):
if coeffs == ():
coeffs = [0]
self.coeffs = list(coeffs)
for i in range(len(self.coeffs)):
if type(self.coeffs[i]) is int:
self.coeffs[i] = Q(self.coeffs[i])
self.unpad()
self.degree = len(self.coeffs) - 1
def unpad(self):
if self.coeffs[-1] == Q(0) and len(self.coeffs) > 1:
self.coeffs.pop(-1)
self.unpad()
def __call__(self, x):
if type(x) is int:
x = Q(x)
l = self.coeffs.copy()
while len(l) > 1:
a = l.pop(-1)
l[-1] += a * x
return l[0]
def __repr__(self):
return "Qolynomial{}".format(tuple(self.coeffs))
def __str__(self):
if self.degree == 0:
return str(self.coeffs[0])
elif self.degree == 1:
return str(self.coeffs[0]) + ' + ' + str(self.coeffs[1]) + 'x'
else:
s = str(self.coeffs[0]) + ' + ' + str(self.coeffs[1]) + 'x'
for i in range(2, self.degree + 1):
s += ' + ' + str(self.coeffs[i]) + 'x^' + str(i)
return s
def __add__(self, other):
if self.degree < other.degree:
larger = other.coeffs.copy()
smaller = self.coeffs.copy()
else:
larger = self.coeffs.copy()
smaller = other.coeffs.copy()
for i in range(len(smaller)):
larger[i] += smaller[i]
return Qolynomial(*larger)
def __sub__(self, other):
l = [-1 * x for x in other.coeffs]
return self + Qolynomial(*l)
def __mul__(self, other):
l = [Q(0) for x in range(self.degree + other.degree + 1)]
for i in range(len(self.coeffs)):
for j in range(len(other.coeffs)):
l[i + j] += self.coeffs[i] * other.coeffs[j]
return Qolynomial(*l)
def __pow__(self, power):
q = Qolynomial(*self.coeffs.copy())
for i in range(power -1):
q *= Qolynomial(*self.coeffs.copy())
return q
|
{"/Qolygen.py": ["/Qolynomial.py"]}
|
9,083
|
sschwa12/aoc2020
|
refs/heads/master
|
/02.py
|
from collections import Counter
from typing import Tuple, List
from utils import read_file
data = read_file('02')
def split_pass(password: str) -> Tuple[int, int, str, str]:
policy, char, pw = password.split(' ')
policy_range = policy.split('-')
sanitized_char = char[0]
start, end = [int(p) for p in policy_range]
return start, end, sanitized_char, pw
def is_valid(password: str) -> bool:
start, end, char, pw = split_pass(password)
char_count = Counter(pw)
if start <= char_count[char] <= end:
return True
return False
def is_valid2(password: str) -> bool:
i, j, char, pw = split_pass(password)
first = pw[i - 1]
second = pw[j - 1]
return len([c for c in [first, second] if c == char]) == 1
print('part 1', Counter((is_valid(pw) for pw in data))[True])
print('part 2', Counter((is_valid2(pw) for pw in data))[True])
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,084
|
sschwa12/aoc2020
|
refs/heads/master
|
/utils.py
|
from pathlib import Path
def read_file(name, *, do_strip=True):
path = Path(f'/Users/scottschwartz/code/aoc2020/inputs')
if isinstance(name, int):
name = f'{name:02d}'
with open(path / name) as f:
res = f.readlines()
if do_strip:
res = list(map(str.strip, res))
return res
def flatten(l):
return [item for sublist in l for item in sublist]
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,085
|
sschwa12/aoc2020
|
refs/heads/master
|
/03.py
|
from functools import reduce
from typing import List, Tuple
from utils import read_file
data = [list(r) for r in read_file('03')]
def count_trees(tree_map: List[str], slope: Tuple[int, int]) -> int:
right, down = slope
count = 0
idx = right
for i in range(down, len(tree_map), down):
row = tree_map[i]
row_length = len(row)
if idx >= row_length:
idx -= row_length
if row[idx] == '#':
count += 1
idx += right
return count
print('p1', count_trees(data, (3, 1)))
SLOPES = [
(1, 1),
(3, 1),
(5, 1),
(7, 1),
(1, 2),
]
def mult_slopes(slopes: Tuple[int, int]) -> int:
counts = [count_trees(data, slope) for slope in slopes]
return reduce((lambda x, y: x * y), counts)
print('p2', mult_slopes(SLOPES))
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,086
|
sschwa12/aoc2020
|
refs/heads/master
|
/09.py
|
from typing import List
from utils import read_file
data = [int(line) for line in read_file(9)]
def is_sum_of_addends(num: int, addends: List[int]) -> bool:
sums = set()
for i, n1 in enumerate(addends):
for n2 in addends[i + 1:]:
sums.add(n1 + n2)
return num in sums
def first_sum(min_i, max_i):
cur = max_i
while cur < len(data):
num = data[cur]
addends = data[min_i:max_i]
if not is_sum_of_addends(num, addends):
return num
min_i += 1
max_i += 1
cur += 1
p1 = first_sum(0, 25)
print('p1', p1)
def get_all_subarrays(arr):
for i in range(1, len(arr) + 1):
for j in range(len(arr) - i + 1):
yield arr[j:j + i]
def get_sum_range(tgt, nums):
for subarray in get_all_subarrays(nums):
subarray_sum = sum(subarray)
if subarray_sum == tgt and len(subarray) > 1:
return min(subarray) + max(subarray)
print('p2', get_sum_range(p1, data))
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,087
|
sschwa12/aoc2020
|
refs/heads/master
|
/01.py
|
from typing import List, Tuple
from utils import read_file
data = [int(n) for n in read_file('01')]
# part 1
def find_addends(nums: List[int], tgt: int) -> Tuple[int, int]:
num_map = {}
for i, num in enumerate(nums):
diff = tgt - num
if num_map.get(diff):
return nums[num_map[diff]], nums[i]
num_map[num] = i
return 'not found'
x, y = find_addends(data, 2020)
print('part 1', x * y)
# part 2
def find_three_addends(nums: List[int], tgt: int) -> Tuple[int, int]:
for num in nums:
new_tgt = tgt - num
addends = find_addends(nums, new_tgt)
if addends != 'not found':
add1, add2 = addends
return tgt - new_tgt, add1, add2
a1, a2, a3 = find_three_addends(data, 2020)
print('part 2', a1 * a2 * a3)
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,088
|
sschwa12/aoc2020
|
refs/heads/master
|
/06.py
|
from utils import read_file
data = read_file('06', do_strip=False)
# part 1
forms = [set(''.join(l.split('\n'))) for l in ''.join(data).split('\n\n')]
print('p1', sum([len(f) for f in forms]))
# part 2
forms = [l.split('\n') for l in ''.join(data).split('\n\n')]
print('p2', sum([len(set(f[0]).intersection(*f)) for f in forms]))
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,089
|
sschwa12/aoc2020
|
refs/heads/master
|
/11.py
|
from utils import read_file, flatten
data = [list(row) for row in read_file(11)]
def safe_get(d, i, j):
if i == -1 or j == -1:
return None
try:
return d[i][j]
except IndexError:
return None
def get_immediately_adjacent_els(d, i, j):
return [safe_get(d, i + x, j + y) for x in range(-1, 2) for y in range(-1, 2) if (x, y) != (0, 0)]
# write me
# we can probably cache something here, ie if you're at 0,0 you only need to check the first row once for horizontal
def get_first_seat_in_each_direction(d, i, j):
pass
def run_model(seat_map, fn, tolerance):
d = [[0 for x in range(len(seat_map[0]))] for y in range(len(seat_map))]
for i, row in enumerate(seat_map):
for j, seat in enumerate(row):
adjacent_els = fn(seat_map, i, j)
if seat == 'L' and all([el != '#' for el in adjacent_els]):
d[i][j] = '#'
elif seat == '#' and len([el for el in adjacent_els if el == '#']) >= tolerance:
d[i][j] = 'L'
else:
d[i][j] = seat_map[i][j]
return d
def solve(fn, tolerance=4):
seat_map = data
while True:
model = run_model(seat_map, fn, tolerance)
if model == seat_map:
return len([el for el in flatten(model) if el == '#'])
seat_map = model
print('p1', solve(get_immediately_adjacent_els))
print('p2', solve(get_first_seat_in_each_direction, 5))
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,090
|
sschwa12/aoc2020
|
refs/heads/master
|
/05.py
|
import math
from utils import read_file
data = read_file('05')
def get_middle(num1: int, num2: int, round='up') -> int:
if round == 'down':
return (num1 + num2) // 2
return math.ceil((num1 + num2) / 2)
def get_seat_id(boarding_pass: str) -> int:
lower_row = 0
upper_row = 127
lower_col = 0
upper_col = 7
for pos in boarding_pass:
if pos == 'F':
upper_row = get_middle(lower_row, upper_row, 'down')
if pos == 'B':
lower_row = get_middle(lower_row, upper_row)
if pos == 'R':
lower_col = get_middle(lower_col, upper_col)
if pos == 'L':
upper_col = get_middle(lower_col, upper_col, 'down')
return lower_row * 8 + lower_col
seat_ids = [get_seat_id(bp) for bp in data]
print('p1', max(seat_ids))
sorted_seat_ids = sorted(seat_ids)
for i, sid in enumerate(sorted_seat_ids):
if sorted_seat_ids[i + 1] != sid + 1:
print('p2', sid + 1)
break
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,091
|
sschwa12/aoc2020
|
refs/heads/master
|
/08.py
|
from utils import read_file
data = read_file(8)
class Interpreter:
def __init__(self, instructions):
self.pc = 0
self.accumulator = 0
self.instructions = instructions
self.executed = set()
def nop(self, _):
self.pc += 1
def acc(self, val):
self.accumulator += val
self.pc += 1
def jmp(self, val):
self.pc += val
def execute(self, inst, val):
self.executed.add(self.pc)
getattr(self, inst)(val)
def run(self):
while True:
if self.pc in self.executed:
return 'busted', self.accumulator
try:
inst, val = self.instructions[self.pc].split(' ')
self.execute(inst, int(val))
except IndexError:
return 'fixed', self.accumulator
def p1():
i = Interpreter(data)
return i.run()[1]
print('p1', p1())
# got lucky and this worked just changing the jmps -> nops without trying nops -> jmps
def p2():
jmps = [i for i, val in enumerate(data) if val.startswith('jmp')]
for index in jmps:
new_dataset = data.copy()
new_dataset[index] = str.replace(new_dataset[index], 'jmp', 'nop')
i = Interpreter(new_dataset)
flag, acc = i.run()
if flag == 'fixed':
return acc
print('p2', p2())
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,092
|
sschwa12/aoc2020
|
refs/heads/master
|
/07.py
|
from typing import List, Tuple
from utils import read_file
data = read_file(7)
def get_bag_color(bag: str):
return bag.rsplit(' ', 1)[0]
def parse_bag_str(bag_str: str) -> Tuple[str, List[Tuple[str, int]]]:
outer, inner = bag_str.split(' contain ')
outer = get_bag_color(outer)
contents = []
for bag in inner.split(', '):
if bag != 'no other bags.':
num_bags, bag_type = bag.split(' ', 1)
bag_type = get_bag_color(bag_type)
contents.append((bag_type, int(num_bags)))
return outer, contents
bag_map = dict([parse_bag_str(bag) for bag in data])
def p1():
def find_gold_bags(bag_name: str):
res = 0
for contents in bag_map[bag_name]:
if not contents:
return 0
if contents[0] == 'shiny gold':
res = 1
res = res or find_gold_bags(contents[0])
return res
return sum(find_gold_bags(b) for b in bag_map)
print(p1())
def p2():
def get_bag_count(color='shiny gold'):
if not bag_map.get(color):
return 0
total_sub_bags = 0
for child_color, amt in bag_map[color]:
total_sub_bags += amt * (get_bag_count(child_color) + 1)
return total_sub_bags
return get_bag_count()
print(p2())
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,093
|
sschwa12/aoc2020
|
refs/heads/master
|
/10.py
|
from collections import Counter
from functools import reduce, lru_cache
from operator import mul
from utils import read_file
data = [int(d) for d in read_file(10)]
d = sorted(data)
d.append(d[-1] + 3)
d.insert(0, 0)
def get_jolt_differences() -> int:
diffs = []
for i in range(1, len(d)):
num = d[i]
prev_num = d[i - 1]
diffs.append(num - prev_num)
return reduce(mul, Counter(diffs).values())
print('p1', get_jolt_differences())
def get_paths(joltages, cache={}):
key = ','.join([str(j) for j in joltages])
if key in cache:
return cache[key]
cnt = 1
for i in range(1, len(joltages) - 1):
if joltages[i + 1] - joltages[i - 1] <= 3:
new_joltages = [joltages[i - 1]] + joltages[i + 1:]
cnt += get_paths(new_joltages, cache)
cache[key] = cnt
return cnt
print(d)
print(get_paths(d))
lru_cache
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,094
|
sschwa12/aoc2020
|
refs/heads/master
|
/04.py
|
import re
from typing import List
from utils import read_file
data = read_file('04', do_strip=False)
REQUIRED_FIELDS = ('byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid')
EYE_COLORS = ('amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth')
class PassportValidator:
def __init__(self, passports):
self.passports = passports
def byr(self, year):
return 1920 <= int(year) <= 2002
def iyr(self, year):
return 2010 <= int(year) <= 2020
def eyr(self, year):
return 2020 <= int(year) <= 2030
def hgt(self, height):
value = height[:-2]
unit_of_measurement = height[-2:]
if unit_of_measurement == 'cm':
return 150 <= int(value) <= 193
elif unit_of_measurement == 'in':
return 59 <= int(value) <= 76
return False
def hcl(self, hair_color):
if hair_color[0] != '#':
return False
hex = hair_color[1:]
if len(hex) != 6:
return False
return bool(re.match('^[a-f0-9]*$', hex))
def ecl(self, eye_color):
return eye_color in EYE_COLORS
def pid(self, passport_id):
# this could definitely break in some edge cases but let's see what happens
return len(passport_id) == 9
def validate_field(self, field):
f_name, f_val = field.split(':')
return getattr(self, f_name)(f_val)
def cid(self, _):
return True
def run(self):
return [all([self.validate_field(field) for field in passport]) for passport in self.passports]
def split_passports(passport: str) -> List[str]:
split_by_newline = passport.split('\n')
split_by_spaces = ' '.join(split_by_newline).split(' ')
return [s for s in split_by_spaces]
passports = [split_passports(p) for p in ''.join(data).split('\n\n')]
def is_valid(passport: List[str]) -> bool:
field_names_only = [f[:3] for f in passport]
return all(field in field_names_only for field in REQUIRED_FIELDS)
def get_passports_with_reqd_fields() -> List[str]:
return [p for p in passports if is_valid(p)]
passports_with_reqd_fields = get_passports_with_reqd_fields()
print('p1', len(passports_with_reqd_fields))
v = PassportValidator(passports_with_reqd_fields)
print('p2', len([res for res in v.run() if res]))
|
{"/02.py": ["/utils.py"], "/03.py": ["/utils.py"], "/09.py": ["/utils.py"], "/01.py": ["/utils.py"], "/06.py": ["/utils.py"], "/11.py": ["/utils.py"], "/05.py": ["/utils.py"], "/08.py": ["/utils.py"], "/07.py": ["/utils.py"], "/10.py": ["/utils.py"], "/04.py": ["/utils.py"]}
|
9,102
|
kostans3k/teextme
|
refs/heads/master
|
/messaging/forms.py
|
from django.forms import ModelForm
from messaging.models import Message
class MessageForm(ModelForm):
class Meta:
model = Message
exclude = (
'user',
'sender',
'recepient',
'date_sent',
'date_received',
'other_message')
def __init__(self, user, contact, *args, **kwargs):
self.user = user
self.recepient_contact = contact
super(MessageForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
instance = super(MessageForm, self).save(commit=False)
if self.user: # in ostala polja k jih je treba narest:
instance.user = self.user
instance.recepient = self.recepient_contact
# in ostala polja
instance.save()
instance.send()
return instance
|
{"/messaging/views.py": ["/messaging/forms.py"], "/contacts/views.py": ["/contacts/forms.py"], "/contacts/urls.py": ["/contacts/views.py"]}
|
9,103
|
kostans3k/teextme
|
refs/heads/master
|
/messaging/urls.py
|
from django.conf.urls import patterns, url
urlpatterns = patterns(
'messaging.views',
url(r'^(?P<contact_id>\d+)$',
'messages_contact',
name='messages_contact'),
)
|
{"/messaging/views.py": ["/messaging/forms.py"], "/contacts/views.py": ["/contacts/forms.py"], "/contacts/urls.py": ["/contacts/views.py"]}
|
9,104
|
kostans3k/teextme
|
refs/heads/master
|
/messaging/views.py
|
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.db.models import Q
from messaging.models import Message
from contacts.models import Contact
from messaging.forms import *
def messages_contact(request, contact_id):
user = request.user
qs = Message.objects.filter(user=user)
if contact_id:
contact = Contact.objects.get(pk=contact_id)
qs = qs.filter(Q(recepient=contact) | Q(sender=contact))
messages = qs.order_by('id')
form = MessageForm(user=user, contact=contact)
if request.method == 'POST':
form = MessageForm(user=user, contact=contact, data=request.POST)
if form.is_valid():
form.save()
return redirect('messages_contact', contact_id=contact_id)
return render_to_response('messaging/messages.html', {
'user': user,
'contact_id': contact_id,
'form': form,
'messages': messages,
}, RequestContext(request))
|
{"/messaging/views.py": ["/messaging/forms.py"], "/contacts/views.py": ["/contacts/forms.py"], "/contacts/urls.py": ["/contacts/views.py"]}
|
9,105
|
kostans3k/teextme
|
refs/heads/master
|
/contacts/views.py
|
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
from contacts.models import Contact
from contacts.forms import ContactForm
from contacts.serializers import ContactSerializer
def contacts(request):
user = request.user
contacts = Contact.objects.filter(user=user)
return render_to_response('contacts/index.html', {
'user': user,
'contacts': contacts,
}, RequestContext(request))
def contacts_add(request):
if request.method == 'POST':
form = ContactForm(user=request.user, data=request.POST)
if form.is_valid():
new_contact = form.save()
return HttpResponseRedirect("/contacts")
else:
form = ContactForm(user=request.user)
return render_to_response("contacts/new.html", {
'form': form
}, RequestContext(request))
class ContactList(generics.ListCreateAPIView):
model = Contact
serializer_class = ContactSerializer
permission_classes = (IsAuthenticated,)
def get_queryset(self):
return Contact.objects.filter(user=self.request.user)
|
{"/messaging/views.py": ["/messaging/forms.py"], "/contacts/views.py": ["/contacts/forms.py"], "/contacts/urls.py": ["/contacts/views.py"]}
|
9,106
|
kostans3k/teextme
|
refs/heads/master
|
/customregistration/urls.py
|
from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
urlpatterns = patterns(
'',
url(r'^register/$',
'customregistration.views.register',
name='registration_register'),
url(r'^activate/$',
'customregistration.views.activate',
name='registration_activate'),
url(r'^login/$',
auth_views.login,
{'template_name': 'customregistration/login.html'},
name='auth_login'),
url(r'^logout/$',
auth_views.logout,
{'template_name': 'customregistration/logout.html'},
name='auth_logout'),
url(r'^password/change/$',
auth_views.password_change,
name='auth_password_change'),
url(r'^password/change/done/$',
auth_views.password_change_done,
name='auth_password_change_done'),
)
|
{"/messaging/views.py": ["/messaging/forms.py"], "/contacts/views.py": ["/contacts/forms.py"], "/contacts/urls.py": ["/contacts/views.py"]}
|
9,107
|
kostans3k/teextme
|
refs/heads/master
|
/contacts/urls.py
|
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
from contacts.views import ContactList
urlpatterns = patterns(
'contacts.views',
url(r'^$', 'contacts', name='contacts'),
url(r'^add$', 'contacts_add', name='contacts_add'),
url(r'^api$', ContactList.as_view(), name='contact-list'),
)
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api'])
|
{"/messaging/views.py": ["/messaging/forms.py"], "/contacts/views.py": ["/contacts/forms.py"], "/contacts/urls.py": ["/contacts/views.py"]}
|
9,108
|
kostans3k/teextme
|
refs/heads/master
|
/teextme/urls.py
|
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.contrib import admin
from django.contrib.auth.decorators import login_required
admin.autodiscover()
class RequestTemplateView(TemplateView):
def get_context_data(self, **kwargs):
context = super(RequestTemplateView, self).get_context_data(**kwargs)
context['request'] = self.request
return context
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'),
url(r'^accounts/', include('customregistration.urls')),
url(r'^messages/', include('messaging.urls')),
url(r'^contacts/', include('contacts.urls')),
url(r'^app$', login_required(RequestTemplateView.as_view(template_name='app.html')), name='app'),
)
|
{"/messaging/views.py": ["/messaging/forms.py"], "/contacts/views.py": ["/contacts/forms.py"], "/contacts/urls.py": ["/contacts/views.py"]}
|
9,109
|
kostans3k/teextme
|
refs/heads/master
|
/contacts/forms.py
|
from django.forms import ModelForm
from contacts.models import Contact
class ContactForm(ModelForm):
class Meta:
model = Contact
exclude = ('user', 'contact_user')
def __init__(self, user, *args, **kwargs):
self.user = user
super(ContactForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
instance = super(ContactForm, self).save(commit=False)
if self.user:
instance.user = self.user
instance.save()
return instance
|
{"/messaging/views.py": ["/messaging/forms.py"], "/contacts/views.py": ["/contacts/forms.py"], "/contacts/urls.py": ["/contacts/views.py"]}
|
9,110
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/models/pkmn/moves/PokemonMove.py
|
from enum import Enum
from os.path import join
from json import load
from models.pkmn.types.PokemonType import PokemonType
from models.pkmn.stats.StatsDict import StatsDict
from database.DatabaseConfig import database_dir
class MoveCategory(Enum):
Physical = "[Ph]"
Special = "[Sp]"
Status = "[St]"
class PokemonMove:
def __init__(self, name: str, move_type: PokemonType, category: MoveCategory, pp: int,
power: int = 0, accuracy: int = 100, priority: int = 0, effect_rate: int = 0,
self_stat_mod: StatsDict = None, trgt_stat_mod: StatsDict = None):
self.name = name
self.type = move_type
self.category = category
self.pp = pp
self.max_pp = pp
self.power = power
self.accuracy = accuracy
self.priority = priority
self.effect_rate = effect_rate
self.self_stat_mod = self_stat_mod if self_stat_mod is not None else StatsDict()
self.trgt_stat_mod = trgt_stat_mod if trgt_stat_mod is not None else StatsDict()
def __str__(self):
prio_str = f"prio:{'+' if self.priority > 0 else ''}{self.priority}"
return f"{str(self.type):^15} {self.category.value}{self.pp:>9}/{self.max_pp:<3}\n" \
f"{self.name:^34}\n" \
f" {str(self.power):>3}BP -{str(self.accuracy) + '% acc.':^15}- {prio_str:>8} \n" \
f"{'-':^34}" if self.effect_rate == 0 else \
f"{self.effect_rate:<3}%: " if self.effect_rate != 100 else "" \
+ f"{', '.join([key + ' x' + val for key, val in self.self_stat_mod if val != 0]):^20} [Self]" \
if self.self_stat_mod != StatsDict() else \
f"{', '.join([key + ' x' + val for key, val in self.trgt_stat_mod if val != 0]):^18} [Target]" \
if self.trgt_stat_mod != StatsDict() else \
""
@staticmethod
def fromDb(name: str):
with open(join(str(database_dir), "moves", f"{name.lower()}.json")) as move_data_file:
move_data = load(move_data_file)
return PokemonMove(
name=name,
move_type=PokemonType[move_data["type"]],
category=MoveCategory[move_data["category"]],
pp=int(move_data["pp"]),
power=int(move_data["power"])
if "power" in move_data and move_data["power"] is not None else 0,
accuracy=int(move_data["accuracy"])
if "accuracy" in move_data and move_data["accuracy"] is not None else 100,
priority=int(move_data["priority"])
if "priority" in move_data and move_data["priority"] else 0,
effect_rate=int(move_data["effect_rate"])
if "effect_rate" in move_data and move_data["effect_rate"] is not None else 0,
self_stat_mod=StatsDict(move_data["self_stat_mod"])
if "self_stat_mod" in move_data and move_data["self_stat_mode"] is not None else StatsDict(),
trgt_stat_mod=StatsDict(move_data["trgt_stat_mod"])
if "trgt_stat_mod" in move_data and move_data["trgt_stat_mode"] else StatsDict()
)
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,111
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/tests/models/game/battle/test_BattleGameState.py
|
from unittest import TestCase
from models.game.battle.BattleGameState import BattleGameState
from models.game.trainer.PokemonTrainer import PokemonTrainer
from models.game.trainer.utils.ArenaBadge import ArenaBadge
from models.pkmn.PokemonModel import PokemonModel
from models.pkmn.moves.PokemonMove import MoveCategory, PokemonMove
from models.pkmn.natures.PokemonNature import PokemonNature
from models.pkmn.stats.StatsDict import StatsDict
from models.pkmn.types.PokemonType import PokemonType
class TestBattleGameState(TestCase):
def setUp(self) -> None:
self.Pikachu = PokemonModel(
name="Pikachu",
types=(PokemonType.Electric, None),
level=100,
nature=PokemonNature.Jolly,
moves=[
PokemonMove(
name="Volt Tackle",
move_type=PokemonType.Electric,
category=MoveCategory.Physical,
pp=24,
power=120
),
PokemonMove(
name="Iron Tail",
move_type=PokemonType.Steel,
category=MoveCategory.Physical,
pp=24,
power=100,
accuracy=75
),
PokemonMove(
name="Thunderbolt",
move_type=PokemonType.Electric,
category=MoveCategory.Special,
pp=24,
power=90
)
],
base_stats=StatsDict(hp=35, atk=55, phys_def=40, spe_atk=50, spe_def=50, spd=90),
evs=StatsDict(hp=0, atk=252, phys_def=0, spe_atk=4, spe_def=0, spd=252),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
self.Charizard = PokemonModel(
name="Charizard",
types=(PokemonType.Fire, PokemonType.Flying),
level=100,
nature=PokemonNature.Jolly,
moves=[
PokemonMove(
name="Fire Blast",
move_type=PokemonType.Fire,
category=MoveCategory.Special,
pp=8,
power=110,
accuracy=85
),
PokemonMove(
name="Hurricane",
move_type=PokemonType.Flying,
category=MoveCategory.Special,
pp=16,
power=110,
accuracy=70
)
],
base_stats=StatsDict(hp=78, atk=84, phys_def=78, spe_atk=109, spe_def=85, spd=100),
evs=StatsDict(hp=0, atk=0, phys_def=0, spe_atk=252, spe_def=4, spd=252),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
self.Pidgeot = PokemonModel(
name="Pidgeot",
types=(PokemonType.Flying, PokemonType.Normal),
level=100,
nature=PokemonNature.Jolly,
moves=[
PokemonMove(
name="Double Edge",
move_type=PokemonType.Normal,
category=MoveCategory.Physical,
pp=24,
power=120
),
PokemonMove(
name="Brave Bird",
move_type=PokemonType.Flying,
category=MoveCategory.Physical,
pp=24,
power=120
)
],
base_stats=StatsDict(hp=83, atk=80, phys_def=75, spe_atk=70, spe_def=70, spd=101),
evs=StatsDict(hp=0, atk=252, phys_def=0, spe_atk=0, spe_def=4, spd=252),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
self.Blastoise = PokemonModel(
name="Blastoise",
types=(PokemonType.Water, None),
level=100,
nature=PokemonNature.Modest,
moves=[
PokemonMove(
name="Hydro Pump",
move_type=PokemonType.Water,
category=MoveCategory.Special,
pp=8,
power=110,
accuracy=80
),
PokemonMove(
name="Ice Beam",
move_type=PokemonType.Ice,
category=MoveCategory.Special,
pp=16,
power=90
)
],
base_stats=StatsDict(hp=79, atk=83, phys_def=100, spe_atk=85, spe_def=105, spd=78),
evs=StatsDict(hp=252, atk=0, phys_def=0, spe_atk=252, spe_def=4, spd=0),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
self.Red = PokemonTrainer(
name="Red",
team=[self.Pikachu, self.Charizard],
badges=[ArenaBadge.Boulder, ArenaBadge.Cascade, ArenaBadge.Thunder, ArenaBadge.Rainbow,
ArenaBadge.Soul, ArenaBadge.Marsh, ArenaBadge.Marsh, ArenaBadge.Earth]
)
self.Blue = PokemonTrainer(
name="Blue",
team=[self.Pidgeot, self.Blastoise],
badges=[ArenaBadge.Boulder, ArenaBadge.Cascade, ArenaBadge.Thunder, ArenaBadge.Rainbow,
ArenaBadge.Soul, ArenaBadge.Marsh, ArenaBadge.Marsh, ArenaBadge.Earth]
)
self.BattleGameState = BattleGameState(player=self.Red, opponent=self.Blue)
def test_battle_game_state(self):
assert self.BattleGameState.player.name == "Red" and self.BattleGameState.opponent.name == "Blue"
assert self.BattleGameState.turn == 1
assert self.BattleGameState.getPlayerActivePkmn() == self.Pikachu
assert self.BattleGameState.getOpponentActivePkmn() == self.Pidgeot
self.BattleGameState.setPlayerActivePkmn(1)
assert self.BattleGameState.getPlayerActivePkmn() == self.Charizard
assert self.BattleGameState.getOpponentActivePkmn() == self.Pidgeot
self.BattleGameState.setOpponentActivePkmn(1)
assert self.BattleGameState.getPlayerActivePkmn() == self.Charizard
assert self.BattleGameState.getOpponentActivePkmn() == self.Blastoise
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,112
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/engine/pkmn/types/ClassicTypesRuleSet.py
|
from pandas import DataFrame
from engine.pkmn.types.TypesBaseRuleSet import TypesBaseRuleSet
from models.pkmn.types.PokemonType import PokemonType
class ClassicTypesRuleSet(TypesBaseRuleSet):
def __init__(self):
# Init all at 1
type_effectiveness_chart = DataFrame({ref_pkmn_type: {pkmn_type: float(1) for pkmn_type in PokemonType}
for ref_pkmn_type in PokemonType})
# Normal is:
# ineffective against
type_effectiveness_chart[PokemonType.Normal][PokemonType.Ghost] = float(0)
# not very effective against
type_effectiveness_chart[PokemonType.Normal][PokemonType.Steel] = float(.5)
type_effectiveness_chart[PokemonType.Normal][PokemonType.Rock] = float(.5)
# Fire is:
# very effective against
type_effectiveness_chart[PokemonType.Fire][PokemonType.Steel] = float(2)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Grass] = float(2)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Ice] = float(2)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Bug] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Fire][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Water] = float(.5)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Rock] = float(.5)
type_effectiveness_chart[PokemonType.Fire][PokemonType.Dragon] = float(.5)
# Water is:
# very effective against
type_effectiveness_chart[PokemonType.Water][PokemonType.Fire] = float(2)
type_effectiveness_chart[PokemonType.Water][PokemonType.Ground] = float(2)
type_effectiveness_chart[PokemonType.Water][PokemonType.Rock] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Water][PokemonType.Water] = float(.5)
type_effectiveness_chart[PokemonType.Water][PokemonType.Grass] = float(.5)
type_effectiveness_chart[PokemonType.Water][PokemonType.Dragon] = float(.5)
# Electric is:
# ineffective against
type_effectiveness_chart[PokemonType.Electric][PokemonType.Ground] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Electric][PokemonType.Water] = float(2)
type_effectiveness_chart[PokemonType.Electric][PokemonType.Flying] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Electric][PokemonType.Electric] = float(.5)
type_effectiveness_chart[PokemonType.Electric][PokemonType.Grass] = float(.5)
type_effectiveness_chart[PokemonType.Electric][PokemonType.Dragon] = float(.5)
# Grass is:
# very effective against
type_effectiveness_chart[PokemonType.Grass][PokemonType.Water] = float(2)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Ground] = float(2)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Rock] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Grass][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Grass] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Poison] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Flying] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Bug] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Dragon] = float(.5)
type_effectiveness_chart[PokemonType.Grass][PokemonType.Steel] = float(.5)
# Ice is:
# very effective against
type_effectiveness_chart[PokemonType.Ice][PokemonType.Grass] = float(2)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Ground] = float(2)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Flying] = float(2)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Dragon] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Ice][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Water] = float(.5)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Ice] = float(.5)
type_effectiveness_chart[PokemonType.Ice][PokemonType.Steel] = float(.5)
# Fighting is:
# ineffective against
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Ghost] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Normal] = float(2)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Ice] = float(2)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Rock] = float(2)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Dark] = float(2)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Steel] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Poison] = float(.5)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Flying] = float(.5)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Psychic] = float(.5)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Bug] = float(.5)
type_effectiveness_chart[PokemonType.Fighting][PokemonType.Fairy] = float(.5)
# Poison is:
# ineffective against
type_effectiveness_chart[PokemonType.Poison][PokemonType.Steel] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Poison][PokemonType.Grass] = float(2)
type_effectiveness_chart[PokemonType.Poison][PokemonType.Fairy] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Poison][PokemonType.Poison] = float(.5)
type_effectiveness_chart[PokemonType.Poison][PokemonType.Ground] = float(.5)
type_effectiveness_chart[PokemonType.Poison][PokemonType.Rock] = float(.5)
type_effectiveness_chart[PokemonType.Poison][PokemonType.Ghost] = float(.5)
# Ground is:
# ineffective against
type_effectiveness_chart[PokemonType.Ground][PokemonType.Flying] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Ground][PokemonType.Fire] = float(2)
type_effectiveness_chart[PokemonType.Ground][PokemonType.Electric] = float(2)
type_effectiveness_chart[PokemonType.Ground][PokemonType.Poison] = float(2)
type_effectiveness_chart[PokemonType.Ground][PokemonType.Rock] = float(2)
type_effectiveness_chart[PokemonType.Ground][PokemonType.Steel] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Ground][PokemonType.Grass] = float(.5)
type_effectiveness_chart[PokemonType.Ground][PokemonType.Bug] = float(.5)
# Flying is:
# very effective against
type_effectiveness_chart[PokemonType.Flying][PokemonType.Grass] = float(2)
type_effectiveness_chart[PokemonType.Flying][PokemonType.Fighting] = float(2)
type_effectiveness_chart[PokemonType.Flying][PokemonType.Bug] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Flying][PokemonType.Electric] = float(.5)
type_effectiveness_chart[PokemonType.Flying][PokemonType.Rock] = float(.5)
type_effectiveness_chart[PokemonType.Flying][PokemonType.Steel] = float(.5)
# Psychic is:
# ineffective against
type_effectiveness_chart[PokemonType.Psychic][PokemonType.Dark] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Psychic][PokemonType.Poison] = float(2)
type_effectiveness_chart[PokemonType.Psychic][PokemonType.Fighting] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Psychic][PokemonType.Psychic] = float(.5)
type_effectiveness_chart[PokemonType.Psychic][PokemonType.Steel] = float(.5)
# Bug is:
# very effective against
type_effectiveness_chart[PokemonType.Bug][PokemonType.Grass] = float(2)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Psychic] = float(2)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Dark] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Bug][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Fighting] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Poison] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Flying] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Rock] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Ghost] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Steel] = float(.5)
type_effectiveness_chart[PokemonType.Bug][PokemonType.Fairy] = float(.5)
# Rock is:
# very effective against
type_effectiveness_chart[PokemonType.Rock][PokemonType.Fire] = float(2)
type_effectiveness_chart[PokemonType.Rock][PokemonType.Ice] = float(2)
type_effectiveness_chart[PokemonType.Rock][PokemonType.Flying] = float(2)
type_effectiveness_chart[PokemonType.Rock][PokemonType.Bug] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Rock][PokemonType.Fighting] = float(.5)
type_effectiveness_chart[PokemonType.Rock][PokemonType.Ground] = float(.5)
type_effectiveness_chart[PokemonType.Rock][PokemonType.Steel] = float(.5)
# Ghost is:
# ineffective against
type_effectiveness_chart[PokemonType.Ghost][PokemonType.Normal] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Ghost][PokemonType.Psychic] = float(2)
type_effectiveness_chart[PokemonType.Ghost][PokemonType.Ghost] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Ghost][PokemonType.Dark] = float(.5)
# Dragon is:
# ineffective against
type_effectiveness_chart[PokemonType.Dragon][PokemonType.Fairy] = float(0)
# very effective against
type_effectiveness_chart[PokemonType.Dragon][PokemonType.Dragon] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Dragon][PokemonType.Steel] = float(.5)
# Dark is:
# very effective against
type_effectiveness_chart[PokemonType.Dark][PokemonType.Psychic] = float(2)
type_effectiveness_chart[PokemonType.Dark][PokemonType.Ghost] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Dark][PokemonType.Fighting] = float(.5)
type_effectiveness_chart[PokemonType.Dark][PokemonType.Dark] = float(.5)
type_effectiveness_chart[PokemonType.Dark][PokemonType.Fairy] = float(.5)
# Steel is:
# very effective against
type_effectiveness_chart[PokemonType.Steel][PokemonType.Ice] = float(2)
type_effectiveness_chart[PokemonType.Steel][PokemonType.Rock] = float(2)
type_effectiveness_chart[PokemonType.Steel][PokemonType.Fairy] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Steel][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Steel][PokemonType.Water] = float(.5)
type_effectiveness_chart[PokemonType.Steel][PokemonType.Electric] = float(.5)
type_effectiveness_chart[PokemonType.Steel][PokemonType.Steel] = float(.5)
# Fairy is:
# very effective against
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Fighting] = float(2)
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Dark] = float(2)
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Dragon] = float(2)
# not very effective against
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Fire] = float(.5)
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Poison] = float(.5)
type_effectiveness_chart[PokemonType.Fairy][PokemonType.Steel] = float(.5)
super().__init__(type_effectiveness_chart=type_effectiveness_chart)
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,113
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/database/DatabaseConfig.py
|
from os.path import join, dirname, realpath
from pathlib import Path
from typing import List
from json import dump
from requests import request
from re import sub
database_dir = Path(dirname(realpath(__file__)))
__pokeApi_url = "https://pokeapi.co/api/v2/"
def updatePkmnDatabase(pkmn_list: List):
for pkmn_name, pkmn_data in getPkmnDatabase(pkmn_list).items():
print(f"Uploaded {pkmn_name}.json")
with open(join(database_dir, "pkmn", f"{pkmn_name}.json"), mode='w') as pkmn_data_file:
dump(pkmn_data, pkmn_data_file)
def getPkmnDatabase(pkmn_list: List[str]) -> {}:
db = {}
for pkmn in pkmn_list:
res = request("GET", f"{__pokeApi_url}/pokemon/{pkmn}")
if res.status_code == 200:
pkmn_json = {
"type": {str(pkmn_type["slot"] - 1): pkmn_type["type"]["name"].capitalize()
for pkmn_type in res.json()["types"]},
"base_stats": {__convertApiStatNameToDbStatName(pkmn_stat["stat"]["name"]): pkmn_stat["base_stat"]
for pkmn_stat in res.json()["stats"]}
}
db[res.json()["name"]] = pkmn_json
return db
def updateMoveDatabase(move_list: List):
for move_name, move_data in getMoveDatabase(move_list).items():
print(f"Uploaded {move_name.lower()}.json")
with open(join(database_dir, "moves", f"{move_name.lower()}.json"), mode='w') as move_data_file:
dump(move_data, move_data_file)
def getMoveDatabase(move_list: List[str]) -> {}:
db = {}
for move in move_list:
move_url = sub('\\s', '-', move.lower())
res = request("GET", f"{__pokeApi_url}/move/{move_url}")
if res.status_code == 200:
move_json = {
"type": res.json()["type"]["name"].capitalize(),
"category": res.json()["damage_class"]["name"].capitalize(),
"pp": res.json()["pp"],
"power": res.json()["power"],
"accuracy": res.json()["accuracy"],
"priority": res.json()["priority"],
"effect_rate": res.json()["effect_chance"],
"self_stat_mod": {__convertApiStatNameToDbStatName(pkmn_stat["stat"]["name"]): pkmn_stat["change"]
for pkmn_stat in res.json()["stat_changes"]} if res.json()["target"]["name"] == "user"
else {},
"trgt_stat_mod": {__convertApiStatNameToDbStatName(pkmn_stat["stat"]["name"]): pkmn_stat["change"]
for pkmn_stat in res.json()["stat_changes"]} if res.json()["target"]["name"] != "user"
else {}
}
db[move] = move_json
return db
def __convertApiStatNameToDbStatName(api_stat: str) -> str:
return "atk" if api_stat == "attack" \
else "phys_def" if api_stat == "defense" \
else "spe_atk" if api_stat == "special-attack" \
else "spe_def" if api_stat == "special-defense" \
else "spd" if api_stat == "speed" \
else "hp"
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,114
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/models/pkmn/PokemonBaseModel.py
|
from models.pkmn.stats.StatsDict import StatsDict
from models.pkmn.types.PokemonType import PokemonType, format_types_tuple, type_equals
class PokemonBaseModel:
def __init__(self, name: str, types: (PokemonType, PokemonType), base_stats: StatsDict):
self.name = name
self.type = format_types_tuple(types)
self.base_stats = base_stats
def __eq__(self, other):
if self.__class__ != other.__class__:
return NotImplementedError
return self.name == other.name and type_equals(self.type, other.type) \
and self.base_stats == other.base_stats
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,115
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/tests/database/test_DatabaseInit.py
|
from unittest import TestCase
from database.DatabaseConfig import getPkmnDatabase
from models.game.trainer.PokemonTrainer import PokemonTrainer
from models.pkmn.natures.PokemonNature import PokemonNature
from models.pkmn.stats.StatsDict import StatsDict
from models.pkmn.types.PokemonType import PokemonType
class TestDatabaseInit(TestCase):
def test_database_init(self):
trainer_json = {
"name": "Red",
"team": {
"0": {
"name": "Scizor",
"level": 100,
"nature": "Adamant",
"moves": ["Bullet Punch"],
"evs": {"hp": 120, "atk": 252, "phys_def": 0, "spe_atk": 0, "spe_def": 0, "spd": 136},
"ivs": {"hp": 31, "atk": 31, "phys_def": 31, "spe_atk": 31, "spe_def": 31, "spd": 31}
}
}
}
trainer = PokemonTrainer.fromJson(trainer_json)
assert trainer.name == "Red"
assert trainer.team[1] is None
assert trainer.team[0].name == "Scizor"
assert trainer.team[0].level == 100
assert trainer.team[0]._nature == PokemonNature.Adamant
assert trainer.team[0].moves[0].type == PokemonType.Steel
assert trainer.team[0].moves[0].power == 40
assert trainer.team[0].moves[0].accuracy == 100
assert trainer.team[0].base_stats == StatsDict(hp=70, atk=130, phys_def=100, spe_atk=55, spe_def=80, spd=65)
assert trainer.team[0].stats == StatsDict(hp=311, atk=394, phys_def=236, spe_atk=131, spe_def=196, spd=200)
def test_database_update(self):
db = getPkmnDatabase(["tyranitar"])
assert "tyranitar" in db
expected_json = {
"type": {"0": "rock", "1": "dark"},
"base_stats": {
"hp": 100,
"atk": 134,
"phys_def": 110,
"spe_atk": 95,
"spe_def": 100,
"spd": 61
}
}
assert db["tyranitar"] == expected_json
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,116
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/engine/game/BattleEngine.py
|
from random import randint
from engine.game import InputHandler
from engine.game.BattleDisplay import displayPlayers, displayBattleGameState, displayUsedMove, \
displaySwitch, displayEndOfBattle
from engine.pkmn.types.TypesBaseRuleSet import TypesBaseRuleSet
from models.game.battle.BattleGameState import BattleGameState
from models.pkmn.PokemonModel import PokemonModel
from models.pkmn.moves.PokemonMove import PokemonMove, MoveCategory
from models.pkmn.stats.StatsDict import StatsDict
class BattleEngine:
def __init__(self, battleGameState: BattleGameState, typesRuleSet: TypesBaseRuleSet):
self.gameState = battleGameState
self.typesRuleSet = typesRuleSet
def startGame(self) -> bool:
displayPlayers(self.gameState)
# Lead Phase
player_pkmn_selection = InputHandler.pkmnSelection(self.gameState.player.team)
self.gameState.setPlayerActivePkmn(player_pkmn_selection)
# Battle Phase
self.__battlePhase()
win = not self.gameState.player.hasLost()
displayEndOfBattle(win, self.gameState)
return win
def __battlePhase(self):
while not self.gameState.player.hasLost() and not self.gameState.opponent.hasLost():
# Move Selection Phase
if self.gameState.getPlayerActivePkmn().isKO():
self.__switchPlayerPokemon()
if self.gameState.getOpponentActivePkmn().isKO():
self.__switchOpponentPokemon()
displayBattleGameState(self.gameState)
plyr_move, plyr_switch = InputHandler.turnDecision(self.gameState.getPlayerActivePkmn(),
self.gameState.player.team)
rand = randint(0, len(self.gameState.getOpponentActivePkmn().moves) - 1)
opponent_move = self.gameState.getOpponentActivePkmn().moves[rand]
self.gameState.setTurnState(plyr_move=plyr_move, opponent_move=opponent_move)
if plyr_switch:
self.__switchPlayerPokemon(plyr_switch)
first, second = self.__getMoveOrder()
self.__useMove(first[0], first[1], second[0])
if not second[0].isKO() and second[1] is not None:
self.__useMove(second[0], second[1], first[0])
self.gameState.turn += 1
def __useMove(self, caster: PokemonModel, caster_move: PokemonMove, trgt: PokemonModel) \
-> bool:
damage = 0
type_effectiveness = 1
if caster_move.category != MoveCategory.Status:
offensive_stat = caster.stats.atk if caster_move.category == MoveCategory.Physical \
else caster.stats.spe_atk
defensive_stat = trgt.stats.phys_def if caster_move.category == MoveCategory.Physical \
else trgt.stats.spe_def
damage = (((2 * caster.level / 5 + 2) * caster_move.power * offensive_stat / defensive_stat) / 50 + 2)
type_effectiveness = self.typesRuleSet.getEffectiveness(caster_move.type, trgt.type)
modifier = (1.5 if caster_move.type == caster.type else 1) \
* type_effectiveness \
* randint(85, 100) / 100 \
* (1 if randint(0, 100) <= caster_move.accuracy else 0)
damage = int(damage * modifier)
if damage != 0:
trgt.takeDamage(damage)
displayUsedMove(caster, caster_move, trgt, type_effectiveness, damage)
if randint(0, 100) <= caster_move.effect_rate:
for stat_key in StatsDict.__dict__.keys():
caster.stats[stat_key] *= caster_move.self_stat_mod[stat_key]
trgt.stats[stat_key] *= caster_move.trgt_stat_mod[stat_key]
return True
def __switchPlayerPokemon(self, selection: int = None):
out = self.gameState.getPlayerActivePkmn()
coming_in = self.gameState.setPlayerActivePkmn(InputHandler.pkmnSelection(self.gameState.player.team)) \
if selection is None else selection
displaySwitch(player_name=self.gameState.player.name, out=out, coming_in=coming_in)
def __switchOpponentPokemon(self):
out = self.gameState.getOpponentActivePkmn()
coming_in = self.gameState.sendNextOpponentActivePkmn()
displaySwitch(player_name=self.gameState.opponent.name, out=out, coming_in=coming_in)
def __getMoveOrder(self) -> ((PokemonModel, PokemonMove), (PokemonModel, PokemonMove)):
move_order = self.gameState.getTurnState()
(plyr_pkmn, plyr_move), (opponent_pkmn, opponent_move) = move_order
if plyr_move is None:
return move_order[1], move_order[0]
if plyr_move.priority == opponent_move.priority:
if plyr_pkmn.stats.spd == opponent_pkmn.stats.spd:
if randint(0, 1) == 1:
move_order = move_order[1], move_order[0]
else:
if plyr_pkmn.stats.spd < opponent_pkmn.stats.spd:
move_order = move_order[1], move_order[0]
else:
if plyr_move.priority < opponent_move.priority:
move_order = move_order[1], move_order[0]
return move_order
def __getActivePkmns(self):
return self.gameState.getPlayerActivePkmn(), self.gameState.getOpponentActivePkmn()
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,117
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/models/pkmn/PokemonModel.py
|
from typing import List
from os.path import join
from json import load
from models.pkmn.PokemonBaseModel import PokemonBaseModel
from models.pkmn.stats.StatsDict import StatsDict
from models.pkmn.types.PokemonType import PokemonType
from models.pkmn.natures.PokemonNature import PokemonNature
from models.pkmn.moves.PokemonMove import PokemonMove
from database.DatabaseConfig import database_dir
class PokemonModel(PokemonBaseModel):
__bar_len = 50
def __init__(self, name: str, types: (PokemonType, PokemonType), level: int, nature: PokemonNature,
moves: List[PokemonMove], base_stats: StatsDict, evs: StatsDict, ivs: StatsDict):
super().__init__(name=name, types=types, base_stats=base_stats)
self.level = level
self._nature = nature
self.moves = moves
self._evs = evs
self._ivs = ivs
self.stats = self.__stats_compute()
self.max_hp = self.stats.hp
def __str__(self):
hp_percentage = self.stats.hp / self.max_hp
ticks = int(hp_percentage * self.__bar_len + .5)
return f"{self.name} (lvl.{self.level}):\n" \
f"{'█'.join('' for _ in range(ticks))}{'▁'.join('' for _ in range(self.__bar_len - ticks))}\n" \
f"{self.stats.hp}/{self.max_hp} ({int(hp_percentage * 100)}%)"
def moveListAsStr(self) -> str:
split_lines = [str(move).splitlines() for move in self.moves]
return "\n".join(["| |".join([split_lines[x][y] for x in range(len(split_lines))])
for y in range(len(split_lines[0]))])
def takeDamage(self, damage: int):
self.stats.hp -= min(damage, self.stats.hp)
def isKO(self):
return self.stats.hp == 0
@staticmethod
def __compute_stat_baseline(level: int, base_stat: int, iv: int, ev: int) -> int:
return int((2 * base_stat + iv + ev / 4) * level / 100)
def __stats_compute(self) -> StatsDict:
stat_values = StatsDict(**{
stat_key:
self.__compute_stat_baseline(level=self.level, base_stat=self.base_stats.hp,
iv=self._ivs.hp, ev=self._evs.hp) + self.level + 10
if stat_key == "hp" else
self.__compute_stat_baseline(level=self.level, base_stat=self.base_stats[stat_key],
iv=self._ivs[stat_key], ev=self._evs[stat_key]) + 5
for stat_key in self.base_stats.__dict__.keys()
})
self._nature.apply_modifier(stat_values)
return stat_values
@staticmethod
def fromJson(json: {}):
keys = ["name", "level", "nature", "moves", "evs", "ivs"]
if all(key in json for key in keys):
with open(join(str(database_dir), "pkmn", f"{json['name'].lower()}.json")) as pkmn_data_file:
pkmn_data = load(pkmn_data_file)
return PokemonModel(
name=json["name"],
types=(PokemonType[pkmn_data["type"]['0']],
PokemonType[pkmn_data["type"]['1']] if 1 in pkmn_data["type"] else None),
level=int(json["level"]),
nature=PokemonNature[json["nature"]],
moves=[PokemonMove.fromDb(move) for move in json["moves"]],
base_stats=StatsDict(**pkmn_data["base_stats"]),
evs=StatsDict(**json["evs"]),
ivs=StatsDict(**json["ivs"])
)
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,118
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/engine/pkmn/types/TypesBaseRuleSet.py
|
from pandas import DataFrame
from models.pkmn.types.PokemonType import PokemonType
class TypesBaseRuleSet:
# .loc on DataFrame: effectiveness of attack on defense
# .iloc on DataFrame: effectiveness of defense on attack
def __init__(self, type_effectiveness_chart: DataFrame):
self.type_effectiveness_chart = type_effectiveness_chart
def __getitem__(self, item: PokemonType) -> (DataFrame, DataFrame):
return self.type_effectiveness_chart.loc(item), self.type_effectiveness_chart.iloc(item)
def getEffectiveness(self, attack_type: PokemonType, defender_type: (PokemonType, PokemonType)) -> float:
return self.type_effectiveness_chart[attack_type][defender_type[0]] \
* self.type_effectiveness_chart[attack_type][defender_type[1]] if defender_type[1] is not None else 1
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,119
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/tests/models/game/trainer/test_PokemonTrainer.py
|
from unittest import TestCase
from models.game.trainer.PokemonTrainer import PokemonTrainer
from models.pkmn.PokemonModel import PokemonModel
from models.pkmn.moves.PokemonMove import PokemonMove, MoveCategory
from models.pkmn.stats.StatsDict import StatsDict
from models.pkmn.types.PokemonType import PokemonType
from models.pkmn.natures.PokemonNature import PokemonNature
from models.game.trainer.utils.ArenaBadge import ArenaBadge
class TestPokemonTrainer(TestCase):
def setUp(self) -> None:
self.Pikachu = PokemonModel(
name="Pikachu",
types=(PokemonType.Electric, None),
level=100,
nature=PokemonNature.Jolly,
moves=[
PokemonMove(
name="Volt Tackle",
move_type=PokemonType.Electric,
category=MoveCategory.Physical,
pp=24,
power=120
),
PokemonMove(
name="Iron Tail",
move_type=PokemonType.Steel,
category=MoveCategory.Physical,
pp=24,
power=100,
accuracy=75
),
PokemonMove(
name="Thunderbolt",
move_type=PokemonType.Electric,
category=MoveCategory.Special,
pp=24,
power=90
)
],
base_stats=StatsDict(hp=35, atk=55, phys_def=40, spe_atk=50, spe_def=50, spd=90),
evs=StatsDict(hp=0, atk=252, phys_def=0, spe_atk=4, spe_def=0, spd=252),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
self.Charizard = PokemonModel(
name="Charizard",
types=(PokemonType.Fire, PokemonType.Flying),
level=100,
nature=PokemonNature.Jolly,
moves=[
PokemonMove(
name="Fire Blast",
move_type=PokemonType.Fire,
category=MoveCategory.Special,
pp=8,
power=110,
accuracy=85
),
PokemonMove(
name="Hurricane",
move_type=PokemonType.Flying,
category=MoveCategory.Special,
pp=16,
power=110,
accuracy=70
)
],
base_stats=StatsDict(hp=78, atk=84, phys_def=78, spe_atk=109, spe_def=85, spd=100),
evs=StatsDict(hp=0, atk=0, phys_def=0, spe_atk=252, spe_def=4, spd=252),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
self.Red = PokemonTrainer(
name="Red",
team=[self.Pikachu, self.Charizard],
badges=[ArenaBadge.Boulder, ArenaBadge.Cascade, ArenaBadge.Thunder, ArenaBadge.Rainbow,
ArenaBadge.Soul, ArenaBadge.Marsh, ArenaBadge.Marsh, ArenaBadge.Earth]
)
def testPokemonTrainer(self):
assert self.Red.team[0] == self.Pikachu
assert self.Red.team[1] == self.Charizard
assert self.Red.team[2] is None and self.Red.team[5] is None
assert self.Red.badges == [ArenaBadge.Boulder, ArenaBadge.Cascade, ArenaBadge.Thunder, ArenaBadge.Rainbow,
ArenaBadge.Soul, ArenaBadge.Marsh, ArenaBadge.Marsh, ArenaBadge.Earth]
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,120
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/tests/models/pkmn/test_PokemonModel.py
|
from unittest import TestCase
from models.pkmn.PokemonModel import PokemonModel
from models.pkmn.moves.PokemonMove import PokemonMove, MoveCategory
from models.pkmn.types.PokemonType import PokemonType, type_equals
from models.pkmn.natures.PokemonNature import PokemonNature
from models.pkmn.stats.StatsDict import StatsDict
class TestPokemonModel(TestCase):
def test_pokemon_model(self):
scizor = PokemonModel(
name="Scizor",
types=(PokemonType.Bug, PokemonType.Steel),
level=100,
nature=PokemonNature.Adamant,
moves=[
PokemonMove(
name="Bullet Punch",
move_type=PokemonType.Steel,
category=MoveCategory.Physical,
pp=48,
power=40,
priority=1
),
PokemonMove(
name="U-Turn",
move_type=PokemonType.Bug,
category=MoveCategory.Physical,
pp=32,
power=70
),
PokemonMove(
name="Steel Beam",
move_type=PokemonType.Steel,
category=MoveCategory.Special,
pp=8,
power=140,
accuracy=95
),
PokemonMove(
name="Swords Dance",
move_type=PokemonType.Normal,
category=MoveCategory.Status,
pp=32,
effect_rate=100,
self_stat_mod=StatsDict(atk=2)
)
],
base_stats=StatsDict(hp=70, atk=130, phys_def=100, spe_atk=55, spe_def=80, spd=65),
evs=StatsDict(hp=120, atk=252, phys_def=0, spe_atk=0, spe_def=0, spd=136),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
assert scizor.name == "Scizor"
assert type_equals(scizor.type, (PokemonType.Steel, PokemonType.Bug))
assert scizor.level == 100
assert scizor._nature == PokemonNature.Adamant
assert not scizor._nature == PokemonNature.Jolly
assert scizor.base_stats == StatsDict(hp=70, atk=130, phys_def=100, spe_atk=55, spe_def=80, spd=65)
assert scizor.base_stats.atk == 130
assert scizor._evs == StatsDict(hp=120, atk=252, phys_def=0, spe_atk=0, spe_def=0, spd=136)
assert scizor._ivs == StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
expected_stat_values = StatsDict(hp=311, atk=394, phys_def=236, spe_atk=131, spe_def=196, spd=200)
assert scizor.stats == expected_stat_values
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,121
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/tests/models/pkmn/test_PokemonBaseModel.py
|
from unittest import TestCase
from models.pkmn.PokemonBaseModel import PokemonBaseModel
from models.pkmn.types.PokemonType import PokemonType, type_equals
from models.pkmn.stats.StatsDict import StatsDict
class TestPokemonBaseModel(TestCase):
def test_double_type_pokemon(self):
scizor = PokemonBaseModel(
name="Scizor",
types=(PokemonType.Bug, PokemonType.Steel),
base_stats=StatsDict(hp=70, atk=130, phys_def=100, spe_atk=55, spe_def=80, spd=65)
)
assert scizor.name == "Scizor"
assert type_equals(scizor.type, (PokemonType.Bug, PokemonType.Steel))
assert scizor.base_stats == StatsDict(hp=70, atk=130, phys_def=100, spe_atk=55, spe_def=80, spd=65)
assert scizor.base_stats.atk == 130
def test_double_type_pokemon_valid_comparison(self):
scizor = PokemonBaseModel(
name="Scizor",
types=(PokemonType.Bug, PokemonType.Steel),
base_stats=StatsDict(hp=70, atk=130, phys_def=100, spe_atk=55, spe_def=80, spd=65)
)
definitely_not_scizor = PokemonBaseModel(
name="Scizor",
types=(PokemonType.Steel, PokemonType.Bug),
base_stats=StatsDict(hp=70, atk=130, phys_def=100, spe_atk=55, spe_def=80, spd=65)
)
assert scizor.name == definitely_not_scizor.name
assert type_equals(scizor.type, definitely_not_scizor.type)
assert scizor.base_stats == definitely_not_scizor.base_stats
assert scizor.base_stats.atk == definitely_not_scizor.base_stats.atk
assert scizor == definitely_not_scizor
def test_double_type_pokemon_invalid_comparison(self):
scizor = PokemonBaseModel(
name="Scizor",
types=(PokemonType.Bug, PokemonType.Steel),
base_stats=StatsDict(hp=70, atk=130, phys_def=100, spe_atk=55, spe_def=80, spd=65)
)
crawdaunt = PokemonBaseModel(
name="Crawdaunt",
types=(PokemonType.Water, PokemonType.Dark),
base_stats=StatsDict(hp=63, atk=130, phys_def=85, spe_atk=90, spe_def=55, spd=55)
)
assert scizor.name != crawdaunt.name
assert not type_equals(scizor.type, crawdaunt.type)
assert scizor.base_stats != crawdaunt.base_stats
assert scizor.base_stats.atk == crawdaunt.base_stats.atk
assert scizor != crawdaunt
def test_simple_type_pokemon(self):
blissey = PokemonBaseModel(
name="Blissey",
types=(PokemonType.Normal, None),
base_stats=StatsDict(hp=255, atk=10, phys_def=10, spe_atk=75, spe_def=135, spd=55)
)
assert blissey.name == "Blissey"
assert type_equals(blissey.type, (PokemonType.Normal, None))
assert blissey.base_stats == StatsDict(hp=255, atk=10, phys_def=10, spe_atk=75, spe_def=135, spd=55)
assert blissey.base_stats.hp == 255
def test_simple_type_pokemon_valid_comparison(self):
blissey = PokemonBaseModel(
name="Blissey",
types=(PokemonType.Normal, None),
base_stats=StatsDict(hp=255, atk=10, phys_def=10, spe_atk=75, spe_def=135, spd=55)
)
definitely_not_blissey = PokemonBaseModel(
name="Blissey",
types=(None, PokemonType.Normal),
base_stats=StatsDict(hp=255, atk=10, phys_def=10, spe_atk=75, spe_def=135, spd=55)
)
assert blissey.name == definitely_not_blissey.name
assert type_equals(blissey.type, definitely_not_blissey.type)
assert blissey.base_stats == definitely_not_blissey.base_stats
assert blissey.base_stats.atk == definitely_not_blissey.base_stats.atk
assert blissey == definitely_not_blissey
def test_simple_type_pokemon_invalid_comparison(self):
blissey = PokemonBaseModel(
name="Blissey",
types=(PokemonType.Normal, None),
base_stats=StatsDict(hp=255, atk=10, phys_def=10, spe_atk=75, spe_def=135, spd=55)
)
barraskewda = PokemonBaseModel(
name="Barraskewda",
types=(PokemonType.Water, None),
base_stats=StatsDict(hp=61, atk=123, phys_def=60, spe_atk=60, spe_def=50, spd=136)
)
assert blissey.name != barraskewda.name
assert not type_equals(blissey.type, barraskewda.type)
assert blissey.base_stats != barraskewda.base_stats
assert blissey.base_stats.atk != barraskewda.base_stats.atk
assert blissey != barraskewda
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,122
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/tests/engine/game/test_BattleEngine.py
|
import builtins
from unittest import TestCase
import mock
from engine.game import InputHandler
from engine.game.BattleEngine import BattleEngine
from engine.pkmn.types.ClassicTypesRuleSet import ClassicTypesRuleSet
from models.game.battle.BattleGameState import BattleGameState
from models.game.trainer.PokemonTrainer import PokemonTrainer
from models.game.trainer.utils.ArenaBadge import ArenaBadge
from models.pkmn.PokemonModel import PokemonModel
from models.pkmn.moves.PokemonMove import PokemonMove, MoveCategory
from models.pkmn.natures.PokemonNature import PokemonNature
from models.pkmn.stats.StatsDict import StatsDict
from models.pkmn.types.PokemonType import PokemonType
class TestBattleEngine(TestCase):
def setUp(self) -> None:
self.Pikachu = PokemonModel(
name="Pikachu",
types=(PokemonType.Electric, None),
level=100,
nature=PokemonNature.Jolly,
moves=[
PokemonMove(
name="Volt Tackle",
move_type=PokemonType.Electric,
category=MoveCategory.Physical,
pp=24,
power=120
),
PokemonMove(
name="Iron Tail",
move_type=PokemonType.Steel,
category=MoveCategory.Physical,
pp=24,
power=100,
accuracy=75
),
PokemonMove(
name="Thunderbolt",
move_type=PokemonType.Electric,
category=MoveCategory.Special,
pp=24,
power=90
)
],
base_stats=StatsDict(hp=35, atk=55, phys_def=40, spe_atk=50, spe_def=50, spd=90),
evs=StatsDict(hp=0, atk=252, phys_def=0, spe_atk=4, spe_def=0, spd=252),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
self.Pidgeot = PokemonModel(
name="Pidgeot",
types=(PokemonType.Flying, PokemonType.Normal),
level=100,
nature=PokemonNature.Jolly,
moves=[
PokemonMove(
name="Double Edge",
move_type=PokemonType.Normal,
category=MoveCategory.Physical,
pp=24,
power=120
),
PokemonMove(
name="Brave Bird",
move_type=PokemonType.Flying,
category=MoveCategory.Physical,
pp=24,
power=120
)
],
base_stats=StatsDict(hp=83, atk=80, phys_def=75, spe_atk=70, spe_def=70, spd=101),
evs=StatsDict(hp=0, atk=252, phys_def=0, spe_atk=0, spe_def=4, spd=252),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
self.Blastoise = PokemonModel(
name="Blastoise",
types=(PokemonType.Water, None),
level=100,
nature=PokemonNature.Modest,
moves=[
PokemonMove(
name="Hydro Pump",
move_type=PokemonType.Water,
category=MoveCategory.Special,
pp=8,
power=110,
accuracy=80
),
PokemonMove(
name="Ice Beam",
move_type=PokemonType.Ice,
category=MoveCategory.Special,
pp=16,
power=90
)
],
base_stats=StatsDict(hp=79, atk=83, phys_def=100, spe_atk=85, spe_def=105, spd=78),
evs=StatsDict(hp=252, atk=0, phys_def=0, spe_atk=252, spe_def=4, spd=0),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
self.Red = PokemonTrainer(
name="Red",
team=[self.Pikachu],
badges=[ArenaBadge.Boulder, ArenaBadge.Cascade, ArenaBadge.Thunder, ArenaBadge.Rainbow,
ArenaBadge.Soul, ArenaBadge.Marsh, ArenaBadge.Marsh, ArenaBadge.Earth]
)
self.Blue = PokemonTrainer(
name="Blue",
team=[self.Pidgeot, self.Blastoise],
badges=[ArenaBadge.Boulder, ArenaBadge.Cascade, ArenaBadge.Thunder, ArenaBadge.Rainbow,
ArenaBadge.Soul, ArenaBadge.Marsh, ArenaBadge.Marsh, ArenaBadge.Earth]
)
self.BattleGameState = BattleGameState(player=self.Red, opponent=self.Blue)
def test_red_blue_battle(self):
with mock.patch.object(InputHandler, 'getCancelableNumberInput', return_value=0):
with mock.patch.object(InputHandler, 'getNumberInput', return_value=0):
with mock.patch.object(InputHandler, 'getDecisionType', return_value='m'):
with mock.patch.object(builtins, 'input', return_value=''):
engine = BattleEngine(battleGameState=self.BattleGameState, typesRuleSet=ClassicTypesRuleSet())
assert not engine.startGame()
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,123
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/miniShowdown.py
|
from argparse import ArgumentParser
from json import load
from database.DatabaseConfig import updatePkmnDatabase, updateMoveDatabase
from engine.game.BattleEngine import BattleEngine
from engine.pkmn.types.ClassicTypesRuleSet import ClassicTypesRuleSet
from models.game.battle.BattleGameState import BattleGameState
from models.game.trainer.PokemonTrainer import PokemonTrainer
from models.game.trainer.utils.ArenaBadge import ArenaBadge
from models.pkmn.PokemonModel import PokemonModel
from models.pkmn.moves.PokemonMove import PokemonMove, MoveCategory
from models.pkmn.natures.PokemonNature import PokemonNature
from models.pkmn.stats.StatsDict import StatsDict
from models.pkmn.types.PokemonType import PokemonType
parser = ArgumentParser()
parser.add_argument("--update_db", "-u", help="Fill out Pkmn info as json in database folder for future use",
type=bool, required=False)
parser.add_argument("--player_trainer_json", "-p", help="Path to player's pokemon trainer json",
type=str, required=False)
parser.add_argument("--opponent_trainer_json", "-o", help="Path to opponent's pokemon trainer json",
type=str, required=False)
args = parser.parse_args()
def setUpDefaultTeams():
pikachu = PokemonModel(
name="Pikachu",
types=(PokemonType.Electric, None),
level=100,
nature=PokemonNature.Jolly,
moves=[
PokemonMove(
name="Volt Tackle",
move_type=PokemonType.Electric,
category=MoveCategory.Physical,
pp=24,
power=120
),
PokemonMove(
name="Iron Tail",
move_type=PokemonType.Steel,
category=MoveCategory.Physical,
pp=24,
power=100,
accuracy=75
),
PokemonMove(
name="Thunderbolt",
move_type=PokemonType.Electric,
category=MoveCategory.Special,
pp=24,
power=90
)
],
base_stats=StatsDict(hp=35, atk=55, phys_def=40, spe_atk=50, spe_def=50, spd=90),
evs=StatsDict(hp=0, atk=252, phys_def=0, spe_atk=4, spe_def=0, spd=252),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
charizard = PokemonModel(
name="Charizard",
types=(PokemonType.Fire, PokemonType.Flying),
level=100,
nature=PokemonNature.Jolly,
moves=[
PokemonMove(
name="Fire Blast",
move_type=PokemonType.Fire,
category=MoveCategory.Special,
pp=8,
power=110,
accuracy=85
),
PokemonMove(
name="Hurricane",
move_type=PokemonType.Flying,
category=MoveCategory.Special,
pp=16,
power=110,
accuracy=70
)
],
base_stats=StatsDict(hp=78, atk=84, phys_def=78, spe_atk=109, spe_def=85, spd=100),
evs=StatsDict(hp=0, atk=0, phys_def=0, spe_atk=252, spe_def=4, spd=252),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
pidgeot = PokemonModel(
name="Pidgeot",
types=(PokemonType.Flying, PokemonType.Normal),
level=100,
nature=PokemonNature.Jolly,
moves=[
PokemonMove(
name="Double Edge",
move_type=PokemonType.Normal,
category=MoveCategory.Physical,
pp=24,
power=120
),
PokemonMove(
name="Brave Bird",
move_type=PokemonType.Flying,
category=MoveCategory.Physical,
pp=24,
power=120
)
],
base_stats=StatsDict(hp=83, atk=80, phys_def=75, spe_atk=70, spe_def=70, spd=101),
evs=StatsDict(hp=0, atk=252, phys_def=0, spe_atk=0, spe_def=4, spd=252),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
blastoise = PokemonModel(
name="Blastoise",
types=(PokemonType.Water, None),
level=100,
nature=PokemonNature.Modest,
moves=[
PokemonMove(
name="Hydro Pump",
move_type=PokemonType.Water,
category=MoveCategory.Special,
pp=8,
power=110,
accuracy=80
),
PokemonMove(
name="Ice Beam",
move_type=PokemonType.Ice,
category=MoveCategory.Special,
pp=16,
power=90
)
],
base_stats=StatsDict(hp=79, atk=83, phys_def=100, spe_atk=85, spe_def=105, spd=78),
evs=StatsDict(hp=252, atk=0, phys_def=0, spe_atk=252, spe_def=4, spd=0),
ivs=StatsDict(hp=31, atk=31, phys_def=31, spe_atk=31, spe_def=31, spd=31)
)
red = PokemonTrainer(
name="Red",
team=[pikachu, charizard],
badges=[ArenaBadge.Boulder, ArenaBadge.Cascade, ArenaBadge.Thunder, ArenaBadge.Rainbow,
ArenaBadge.Soul, ArenaBadge.Marsh, ArenaBadge.Marsh, ArenaBadge.Earth]
)
blue = PokemonTrainer(
name="Blue",
team=[pidgeot, blastoise],
badges=[ArenaBadge.Boulder, ArenaBadge.Cascade, ArenaBadge.Thunder, ArenaBadge.Rainbow,
ArenaBadge.Soul, ArenaBadge.Marsh, ArenaBadge.Marsh, ArenaBadge.Earth]
)
return red, blue
def main():
if args.update_db:
updatePkmnDatabase([str(_) for _ in range(10)])
updateMoveDatabase(["Swords Dance", "Meteor Mash", "Close Combat", "Mach Punch", "Aura Sphere", "Bug Bite",
"Hydro Pump", "Surf", "Waterfall", "Moonblast", "Play Rough", "Solar Beam", "Wood Hammer",
"Stone Edge", "Meteor Gem", "Sludge Bomb", "Poison Jab", "Draco Meteor", "Outrage",
"Dragon Dance", "Psychic", "Zen Headbutt", "Mystical Fire", "Fire Blast", "Flare Blitz",
"Hurricane", "Brave Bird", "Earthquake", "Earth Power"])
player, opponent = setUpDefaultTeams()
if args.player_trainer_json:
with open(args.player_trainer_json) as player_trainer_json_file:
player = PokemonTrainer.fromJson(load(player_trainer_json_file))
if args.opponent_trainer_json:
with open(args.opponent_trainer_json) as opponent_trainer_json_file:
opponent = PokemonTrainer.fromJson(load(opponent_trainer_json_file))
engine = BattleEngine(battleGameState=BattleGameState(player=player, opponent=opponent),
typesRuleSet=ClassicTypesRuleSet())
engine.startGame()
if __name__ == "__main__":
main()
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,124
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/models/pkmn/types/PokemonType.py
|
from enum import Enum
from re import sub
class PokemonType(Enum):
Normal = 1
Fighting = 2
Flying = 3
Poison = 4
Ground = 5
Rock = 6
Bug = 7
Ghost = 8
Psychic = 9
Grass = 10
Fire = 11
Water = 12
Electric = 13
Ice = 14
Dragon = 15
Steel = 16
Dark = 17
Fairy = 18
def __lt__(self, other):
if self.__class__ != other.__class__:
return NotImplementedError
return self.value < other.value
def __str__(self):
return sub("PokemonType\\.", "", super().__str__())
def format_types_tuple(types: (PokemonType, PokemonType)):
if types[0] is None:
if types[1] is None:
raise Exception("PokemonBaseModel - init: Unhandled type (None; None)")
else:
return types[1], None
else:
if types[0] == types[1]:
raise Exception(f"PokemonBaseModel - init: Unhandled type ({str(types[0])}; {str(types[1])})")
return types if types[1] is None or types[0] < types[1] else (types[1], types[0])
def type_equals(self, other: (PokemonType, PokemonType)):
return format_types_tuple(self) == format_types_tuple(other)
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,125
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/engine/game/BattleDisplay.py
|
from re import sub, M
from models.game.battle.BattleGameState import BattleGameState
from models.pkmn.PokemonModel import PokemonModel
from models.pkmn.moves.PokemonMove import PokemonMove
__separation_line = '-'.join('' for _ in range(150))
def __shiftDisplayBox(box: str, shift: int):
return sub("^", "\t".join("" for _ in range(shift)), box, flags=M)
def __displaySideBySide(box_1: str, box_2: str):
split_lines = (box_1.splitlines(), box_2.splitlines())
print("\n".join([f"{split_lines[0][_]:<50}{split_lines[1][_]:>50}" for _ in range(len(split_lines[0]))]))
def displayPlayers(battleGameState: BattleGameState):
__displaySideBySide(str(battleGameState.player), str(battleGameState.opponent))
def displayBattleGameState(battleGameState: BattleGameState):
displayPlayers(battleGameState)
print(f"Turn: {battleGameState.turn}\n")
__displaySideBySide(str(battleGameState.getPlayerActivePkmn()), str(battleGameState.getOpponentActivePkmn()))
print(f"{__separation_line}")
print(battleGameState.getPlayerActivePkmn().moveListAsStr())
print(f"{__separation_line}")
def displayUsedMove(caster: PokemonModel, caster_move: PokemonMove, trgt: PokemonModel,
type_effectiveness: float, damage: int):
print(f"{caster.name} uses {caster_move.name}")
if type_effectiveness != 1:
print("It's super effective!" if type_effectiveness > 1
else f"It doesn't affect {trgt.name}" if type_effectiveness == 0
else "It's not very effective...")
if damage != 0:
print(f"{trgt.name} loses {damage} HP")
if trgt.isKO():
print(f"{trgt.name} is K.O !")
input()
def displaySwitch(player_name: str, out: PokemonModel, coming_in: PokemonModel):
print(f"{out.name} goes back into its PokeBall.")
print(f"{player_name} sends {coming_in.name} out !")
input()
def displayEndOfBattle(win: bool, battleGameState: BattleGameState):
print("# Finished #")
displayPlayers(battleGameState)
print(f"Winner: {battleGameState.player.name if win else battleGameState.opponent.name}")
print(f"{'-'.join(__separation_line)}")
input()
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,126
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/models/game/battle/BattleGameState.py
|
from models.game.trainer.PokemonTrainer import PokemonTrainer
from models.pkmn.PokemonModel import PokemonModel
from models.pkmn.moves.PokemonMove import PokemonMove
class BattleGameState:
def __init__(self, player: PokemonTrainer, opponent: PokemonTrainer):
self.turn = 1
self.player = player.makeCopy()
self.__player_active_pkmn_slot = 0
self.player_move_selection = None
self.opponent = opponent.makeCopy()
self.opponent_move_selection = None
self.__opponent_active_pkmn_slot = 0
def getPlayerActivePkmn(self) -> PokemonModel:
return self.player.team[self.__player_active_pkmn_slot]
def setPlayerActivePkmn(self, index: int) -> PokemonModel:
self.__player_active_pkmn_slot = index
return self.player.team[self.__player_active_pkmn_slot]
def getOpponentActivePkmn(self) -> PokemonModel:
return self.opponent.team[self.__opponent_active_pkmn_slot]
def setOpponentActivePkmn(self, index: int) -> PokemonModel:
self.__opponent_active_pkmn_slot = index
return self.opponent.team[self.__opponent_active_pkmn_slot]
def sendNextOpponentActivePkmn(self) -> PokemonModel:
self.__opponent_active_pkmn_slot += 1
return self.opponent.team[self.__opponent_active_pkmn_slot]
def getTurnState(self):
return (self.getPlayerActivePkmn(), self.player_move_selection),\
(self.getOpponentActivePkmn(), self.opponent_move_selection)
def setTurnState(self, plyr_move: PokemonMove, opponent_move: PokemonMove):
self.player_move_selection = plyr_move
self.opponent_move_selection = opponent_move
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,127
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/models/game/trainer/PokemonTrainer.py
|
from typing import List
from models.game.trainer.utils.ArenaBadge import ArenaBadge
from models.pkmn.PokemonModel import PokemonModel
class PokemonTrainer:
def __init__(self, name: str, team: List[PokemonModel], badges: List[ArenaBadge]):
self.name = name
self.team = [team[i] if i < len(team) else None for i in range(6)]
self.badges = list(badges)
self.badges.sort()
def __str__(self):
team_str_list = [f"{x}. {self.team[x].name} ({self.team[x].stats.hp}/{self.team[x].max_hp})"
for x in range(len(self.team)) if self.team[x] is not None]
return f"Trainer: {self.name}\n" \
f"{' - '.join(team_str_list[0:2])}\n" \
f"{' - '.join(team_str_list[2:4])}\n" \
f"{' - '.join(team_str_list[4:6])}\n"
def hasLost(self):
return all(pkmn.isKO() if pkmn is not None else True for pkmn in self.team)
def makeCopy(self):
return PokemonTrainer(name=self.name, team=list(self.team), badges=list(self.badges))
@staticmethod
def fromJson(json: {}):
if "name" in json and "team" in json:
return PokemonTrainer(
name=json["name"],
team=[PokemonModel.fromJson(json["team"][_]) for _ in json["team"]],
badges=[]
)
raise AttributeError("PokemonTrainer - fromJson: Invalid JSON Input")
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,128
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/models/pkmn/natures/PokemonNature.py
|
from enum import Enum
from models.pkmn.stats.StatsDict import StatsDict
# Bonus/Malus percentage from natures
nature_base_modifier = 100
nature_bonus = 10
nature_bonus_modifier = nature_base_modifier + nature_bonus
nature_malus = 10
nature_malus_modifier = nature_base_modifier - nature_malus
class _PokemonNatureImplm:
def __init__(self, hp: int = nature_base_modifier,
atk: int = nature_base_modifier, phys_def: int = nature_base_modifier,
spe_atk: int = nature_base_modifier, spe_def: int = nature_base_modifier,
spd: int = nature_base_modifier):
super().__init__()
self.__stats_table = StatsDict(hp=hp, atk=atk, phys_def=phys_def, spe_atk=spe_atk, spe_def=spe_def, spd=spd)
def apply_modifier(self, stats: StatsDict):
for stat_key in self.__stats_table.__dict__.keys():
stats[stat_key] *= self.__stats_table[stat_key] / 100
class PokemonNature(Enum):
Lonely = _PokemonNatureImplm(atk=nature_bonus_modifier, phys_def=nature_malus_modifier)
Adamant = _PokemonNatureImplm(atk=nature_bonus_modifier, spe_atk=nature_malus_modifier)
Naughty = _PokemonNatureImplm(atk=nature_bonus_modifier, spe_def=nature_malus_modifier)
Brave = _PokemonNatureImplm(atk=nature_bonus_modifier, spd=nature_malus_modifier)
Bold = _PokemonNatureImplm(phys_def=nature_bonus_modifier, atk=nature_malus_modifier)
Impish = _PokemonNatureImplm(phys_def=nature_bonus_modifier, spe_atk=nature_malus_modifier)
Lax = _PokemonNatureImplm(phys_def=nature_bonus_modifier, spe_def=nature_malus_modifier)
Relaxed = _PokemonNatureImplm(phys_def=nature_bonus_modifier, spd=nature_malus_modifier)
Modest = _PokemonNatureImplm(spe_atk=nature_bonus_modifier, atk=nature_malus_modifier)
Mild = _PokemonNatureImplm(spe_atk=nature_bonus_modifier, phys_def=nature_malus_modifier)
Rash = _PokemonNatureImplm(spe_atk=nature_bonus_modifier, spe_def=nature_malus_modifier)
Quiet = _PokemonNatureImplm(spe_atk=nature_bonus_modifier, spd=nature_malus_modifier)
Calm = _PokemonNatureImplm(spe_def=nature_bonus_modifier, atk=nature_malus_modifier)
Gentle = _PokemonNatureImplm(spe_def=nature_bonus_modifier, phys_def=nature_malus_modifier)
Careful = _PokemonNatureImplm(spe_def=nature_bonus_modifier, spe_atk=nature_malus_modifier)
Sassy = _PokemonNatureImplm(spe_def=nature_bonus_modifier, spd=nature_malus_modifier)
Timid = _PokemonNatureImplm(spd=nature_bonus_modifier, atk=nature_malus_modifier)
Hasty = _PokemonNatureImplm(spd=nature_bonus_modifier, phys_def=nature_malus_modifier)
Jolly = _PokemonNatureImplm(spd=nature_bonus_modifier, spe_atk=nature_malus_modifier)
Naive = _PokemonNatureImplm(spd=nature_bonus_modifier, spe_def=nature_malus_modifier)
Quirky = _PokemonNatureImplm()
Docile = _PokemonNatureImplm()
Hardy = _PokemonNatureImplm()
Bashful = _PokemonNatureImplm()
Serious = _PokemonNatureImplm()
def apply_modifier(self, stats: StatsDict):
self.value.apply_modifier(stats)
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,129
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/models/pkmn/stats/StatsDict.py
|
class StatsDict:
def __init__(self, hp: int = 0, atk: int = 0, phys_def: int = 0, spe_atk: int = 0, spe_def: int = 0, spd: int = 0):
self.hp = int(hp)
self.atk = int(atk)
self.phys_def = int(phys_def)
self.spe_atk = int(spe_atk)
self.spe_def = int(spe_def)
self.spd = int(spd)
def __eq__(self, other):
if self.__class__ != other.__class__:
return NotImplementedError
return self.__dict__ == other.__dict__
def __getitem__(self, item: str):
return self.__dict__[item]
def __setitem__(self, key, value):
self.__dict__[key] = int(value)
@classmethod
def from_json(cls, json: {}):
keys = cls.__dict__.keys()
if all(keys) in json:
return StatsDict(**{key: json[key] for key in keys})
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,130
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/engine/game/InputHandler.py
|
from typing import List
from models.pkmn.PokemonModel import PokemonModel
from models.pkmn.moves.PokemonMove import PokemonMove
def repeatOnError(*exceptions):
def checking(function):
def checked(*args, **kwargs):
while True:
try:
result = function(*args, **kwargs)
except exceptions as ex:
print("Invalid Input!")
else:
return result
return checked
return checking
@repeatOnError(NotImplementedError)
def getDecisionType():
i = input("Enter 'm' to use a move or 's' to switch out: ")
if i != "m" and i != "s":
raise NotImplementedError()
return i
@repeatOnError(ValueError)
def getNumberInput(max_range: int):
i = input(f'Enter your selection (0 - {max_range - 1}): ')
val = int(i)
if val < 0 or val >= max_range:
raise ValueError
return val
@repeatOnError(ValueError)
def getCancelableNumberInput(max_range: int):
i = input(f'Enter your selection (0 - {max_range - 1}) or Cancel (C): ')
if i == "C":
return -1
val = int(i)
if val < 0 or val >= max_range:
raise ValueError
return val
def pkmnSelection(team: List[PokemonModel]) -> int:
print("\nChoose a Pkmn.")
while True:
i = getNumberInput(len([_ for _ in team if _ is not None]))
if team[i].isKO():
print(f"{team[i].name} is K.O ! It cannot fight anymore...")
else:
break
return i
def turnDecision(active_pkmn: PokemonModel, team: List[PokemonModel]) -> (PokemonMove, int):
while True:
t = getDecisionType()
max_range = len([_ for _ in active_pkmn.moves if _ is not None]) if t == "m" \
else len([_ for _ in team if _ is not None])
i = getCancelableNumberInput(max_range=max_range)
if i != -1:
break
return (active_pkmn.moves[i], None) if t == "m" else (None, i)
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,131
|
LiquidNalee/MiniPkmnShowdown
|
refs/heads/main
|
/models/game/trainer/utils/ArenaBadge.py
|
from enum import Enum
class ArenaBadge(Enum):
Boulder = 1
Cascade = 2
Thunder = 3
Rainbow = 4
Soul = 5
Marsh = 6
Volcano = 7
Earth = 8
def __lt__(self, other):
if self.__class__ != other.__class__:
return NotImplementedError
return self.value < other.value
|
{"/models/pkmn/moves/PokemonMove.py": ["/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py", "/database/DatabaseConfig.py"], "/tests/models/game/battle/test_BattleGameState.py": ["/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/pkmn/types/ClassicTypesRuleSet.py": ["/engine/pkmn/types/TypesBaseRuleSet.py", "/models/pkmn/types/PokemonType.py"], "/models/pkmn/PokemonBaseModel.py": ["/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/tests/database/test_DatabaseInit.py": ["/database/DatabaseConfig.py", "/models/game/trainer/PokemonTrainer.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleEngine.py": ["/engine/game/BattleDisplay.py", "/engine/pkmn/types/TypesBaseRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py"], "/models/pkmn/PokemonModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/moves/PokemonMove.py", "/database/DatabaseConfig.py"], "/engine/pkmn/types/TypesBaseRuleSet.py": ["/models/pkmn/types/PokemonType.py"], "/tests/models/game/trainer/test_PokemonTrainer.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/game/trainer/utils/ArenaBadge.py"], "/tests/models/pkmn/test_PokemonModel.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py"], "/tests/models/pkmn/test_PokemonBaseModel.py": ["/models/pkmn/PokemonBaseModel.py", "/models/pkmn/types/PokemonType.py", "/models/pkmn/stats/StatsDict.py"], "/tests/engine/game/test_BattleEngine.py": ["/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/miniShowdown.py": ["/database/DatabaseConfig.py", "/engine/game/BattleEngine.py", "/engine/pkmn/types/ClassicTypesRuleSet.py", "/models/game/battle/BattleGameState.py", "/models/game/trainer/PokemonTrainer.py", "/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py", "/models/pkmn/natures/PokemonNature.py", "/models/pkmn/stats/StatsDict.py", "/models/pkmn/types/PokemonType.py"], "/engine/game/BattleDisplay.py": ["/models/game/battle/BattleGameState.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/battle/BattleGameState.py": ["/models/game/trainer/PokemonTrainer.py", "/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"], "/models/game/trainer/PokemonTrainer.py": ["/models/game/trainer/utils/ArenaBadge.py", "/models/pkmn/PokemonModel.py"], "/models/pkmn/natures/PokemonNature.py": ["/models/pkmn/stats/StatsDict.py"], "/engine/game/InputHandler.py": ["/models/pkmn/PokemonModel.py", "/models/pkmn/moves/PokemonMove.py"]}
|
9,132
|
BlueDragon23/Hearthstone
|
refs/heads/master
|
/renamescript.py
|
import os
for file in os.listdir('./cards'):
tokens = file.split("-")
if tokens[0].isdigit():
try:
os.rename(file, "-".join(tokens[1:]))
except Exception as e:
print(e)
|
{"/main2.py": ["/data.py"]}
|
9,133
|
BlueDragon23/Hearthstone
|
refs/heads/master
|
/hearthpwnscraper.py
|
import requests
from bs4 import BeautifulSoup
import shutil
def download_images(url):
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
for link in soup.find_all('img'):
pic = requests.get(link.get('src'), stream=True)
if pic.status_code == 200:
with open(link.get('data-href')[1:] + ".png", 'wb') as f:
pic.raw.decode_content = True
shutil.copyfileobj(pic.raw, f)
if __name__ == "__main__":
for i in range(1, 7):
url = "http://www.hearthpwn.com/cards/minion?display=3&filter-premium=1&page={}".format(i)
download_images(url)
for i in range(1, 3):
url = "http://www.hearthpwn.com/cards/ability?display=3&filter-premium=1&page={}".format(i)
download_images(url)
|
{"/main2.py": ["/data.py"]}
|
9,134
|
BlueDragon23/Hearthstone
|
refs/heads/master
|
/data.py
|
import json
import numpy
def read_json():
"""
Read the file, and convert the json to a python format
:return:
"""
file = open("C:\\Users\\Aidan\\Dropbox\\University\\COSC3000\ComputerGraphics\\cards.collectible.json")
cards = json.load(file)
return cards
def get_minions(cards) -> []:
"""
Read data from the card data file. Returns a list of {}
"""
keys = ["cost", "health", "attack", "name", "text", "type"]
values = [{key: card.get(key, "") for key in keys} for card in cards if card['type'] == 'MINION']
return values
def get_spells(cards):
"""
:return: all spells in the game
"""
keys = ["name", "cost", "text", "type"]
spells = [{key: card[key] for key in keys} for card in cards if card['type'] == 'SPELL']
return spells
def select_minion(minions, name:str):
for minion in minions:
if minion['name'] == name:
return minion
def load_obj(filename: str):
file = open(filename, "r")
vertices = []
textures = [[0, 0]]
normals = []
faces = []
objects = []
object = {} # material, vertices, textures, normals, faces
for line in file:
tokens = line.split()
if tokens[0] == "v":
vertices.append([float(x) for x in tokens[1:]])
elif tokens[0] == "vt":
textures.append([float(x) for x in tokens[1:]])
elif tokens[0] == "vn":
normals.append([float(x) for x in tokens[1:]])
elif tokens[0] == "f":
faces.append([[int(y) if y != "" else 1 for y in x.split("/")] for x in tokens[1:]])
elif tokens[0] == "usemtl":
object["material"] = tokens[1]
elif tokens[0] == "o":
# New object
if len(object) > 0:
object["faces"] = faces # Still need to be resolved
objects.append(object)
object = {"name" : tokens[1]}
faces = []
object["faces"] = faces # Still need to be resolved
objects.append(object)
# Resolve faces
for obj in objects:
for face in obj["faces"]:
for i in range(len(face)):
# Subtract 1 as .obj indices start from 1
face[i] = (vertices[face[i][0] - 1],
textures[face[i][1] - 1],
normals[face[i][2] - 1])
obj["vertices"] = get_obj_vertices(obj["faces"])
obj["normals"] = get_obj_normals(obj["faces"])
return objects
def get_obj_vertices(faces):
vertices = numpy.array([[coord[0] for coord in face] for face in faces], float)
vertices = vertices.flatten()
return vertices
def get_obj_normals(faces):
normals = numpy.array([[coord[2] for coord in face] for face in faces], float)
normals = normals.flatten()
return normals
def load_mtl(filename: str):
file = open(filename, "r")
materials = []
material = {}
for line in file:
line = line.strip()
tokens = line.split()
if len(tokens) == 0:
continue
if tokens[0] == "newmtl":
if material != {}:
materials.append(material)
material = {"name" : tokens[1]}
elif tokens[0] == "Ka":
material["ambient"] = [float(x) for x in tokens[1:4]]
elif tokens[0] == "Kd":
material["diffuse"] = [float(x) for x in tokens[1:4]]
elif tokens[0] == "Ks":
material["specular"] = [float(x) for x in tokens[1:4]]
materials.append(material)
return materials
def find_mtl(name: str, materials):
for material in materials:
if material["name"] == name:
return material
if __name__ == "__main__":
cards = read_json()
minions = get_minions(cards)
for i in range(5):
print(minions[i])
faces = load_obj("C:\\Users\Aidan\Dropbox\\University\COSC3000\ComputerGraphics\cardback.obj")
for i in range(5):
print(faces[i])
|
{"/main2.py": ["/data.py"]}
|
9,135
|
BlueDragon23/Hearthstone
|
refs/heads/master
|
/main.py
|
"""
Hearthstone Computer Graphics
@author: Aidan Goldthorpe
----------------------
Graphical display of Hearthstone card statistics
ESC: exit
"""
import json
import colorsys
from math import *
import time
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
#####################################################################
CamPhi = 30
CamTheta = 60
CamRange = 250
PerspectiveAngle = 45
MaximumDataPoint = 0
# Initialise GLUT and a few other things
# create and return a window
def InitGLUT(nWidth, nHeight, title=""):
glutInit(title)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)
glutInitWindowSize(nWidth, nHeight)
glutInitWindowPosition(0, 0)
#
# A general OpenGL initialisation function that sets various initial parameters.
# We call this right after out OpenGL window is created.
#
def InitGL(nWidth, nHeight):
# use black when clearing the colour buffers -- this will give us a black
# background for the window
glClearColor(0.0, 0.0, 0.0, 0.0)
# enable the depth buffer to be cleared
glClearDepth(1.0)
# set which type of depth test to use
glDepthFunc(GL_LESS)
# enable depth testing
glEnable(GL_DEPTH_TEST)
# enable smooth colour shading
glShadeModel(GL_SMOOTH)
ResizeGLScene(nWidth, nHeight)
#
# The function called when our window is resized. This won't happen if we run
# in full screen mode.
#
def ResizeGLScene(nWidth, nHeight):
# prevent a divide-by-zero error if the window is too small
if nHeight == 0:
nHeight = 1
# reset the current viewport and recalculate the perspective transformation
# for the projection matrix
glViewport(0, 0, nWidth, nHeight)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(PerspectiveAngle, float(nWidth) / float(nHeight), 0.1, 1000.0)
# glOrtho(-w,w,-h,h,1,20000)
glMatrixMode(GL_MODELVIEW)
# glLoadIdentity()
def readData() -> []:
global MaximumDataPoint
file = open("C:\\Users\\Aidan\\Dropbox\\University\\COSC3000\ComputerGraphics\\cards.collectible.json")
cards = json.load(file)
mana = []
health = []
attack = []
for card in cards:
if card['type'] != 'MINION':
continue
mana.append(card['cost'])
health.append(card['health'])
attack.append(card['attack'])
values = [(mana[i], health[i], attack[i]) for i in range(len(mana))]
MaximumDataPoint = max([max(x[i] for x in values) for i in range(3)]) * 10
return values
def getDrawable(values: []) -> []:
unique = set(values)
counts = {x: values.count(x) for x in values}
return [(counts[val], val[0], val[1], val[2]) for val in unique]
def handler(button, state, x: int, y: int):
if state != GLUT_DOWN:
return
print("x = {}, y = {}".format(x, y))
# getColor
# color = scale*x/maxX + minVal
# x = (color - minVal)*maxX/scale
window_height = glutGet(GLUT_WINDOW_HEIGHT)
pixel = glReadPixels(x, window_height - y - 1, 1, 1, GL_RGB, GL_FLOAT)
# Access the first and only list of colours
pixel = pixel[0][0]
# Select object based on colour
print(pixel)
coords = [round(x, -1)//10 for x in getCoordsFromColour(pixel)]
print(coords)
return None
#####################################################################
def drawVertices(x):
for i in range(len(x)):
glVertex3fv(x[i])
def drawAxes(h):
# h : length of the axes
# draw axis X in red
# draw axis Y in green
# draw axis Z in blue
x = [h, 0, 0]
y = [0, h, 0]
z = [0, 0, h]
o = [0, 0, 0]
glBegin(GL_LINES)
glColor3fv([1, 0, 0])
glVertex3fv(o)
glVertex3fv(x)
glColor3fv([0, 1, 0])
glVertex3fv(o)
glVertex3fv(y)
glColor3fv([0, 0, 1])
glVertex3fv(o)
glVertex3fv(z)
glEnd()
def getColour(val):
minVal = 0.2
scale = 0.8
return 1 - (scale * val / MaximumDataPoint + minVal)
def getCoordsFromColour(pixel):
minVal = 0.2
scale = 0.8
[x, y, z] = [(- (col - 1) - minVal)*MaximumDataPoint/scale for col in pixel]
return [x, y, z]
def drawSphere(radius: int, x: int, y: int, z: int) -> None:
# Modify in isolation
glPushMatrix()
glTranslate(x, y, z)
glColor4f(1, 1, 1, 1)
#glEnable(GL_LIGHT0)
#glEnable(GL_LIGHTING)
xColour = getColour(x)
yColour = getColour(y)
zColour = getColour(z)
glColor3fv([xColour, yColour, zColour])
# glMaterialfv(GL_FRONT, GL_DIFFUSE, [1*x/100, 1*y/100, 1*z/100, 1])
# Sphere model
quadric = gluNewQuadric()
gluQuadricNormals(quadric, GLU_SMOOTH)
gluQuadricTexture(quadric, GL_TRUE)
gluSphere(quadric, radius, 32, 32)
#glDisable(GL_LIGHTING)
glPopMatrix()
#####################################################################
def drawCube(size):
a = [size, size, -size]
b = [-size, size, -size]
c = [-size, size, size]
d = [size, size, size]
e = [-size, -size, size]
f = [-size, -size, -size]
g = [size, -size, size]
h = [size, -size, -size]
glBegin(GL_QUADS)
drawVertices([a, b, c, d])
drawVertices([b, f, e, c])
drawVertices([c, d, g, e])
drawVertices([d, g, h, a])
drawVertices([e, f, h, g])
drawVertices([f, b, a, h])
glEnd()
#####################################################################
def DrawGLScene():
# clear the screen and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# reset the matrix stack with the identity matrix
glLoadIdentity()
spacing = 10
# camera setup
r_xz = CamRange * cos(CamPhi * pi / 180)
x = r_xz * sin(CamTheta * pi / 180)
y = CamRange * sin(CamPhi * pi / 180)
z = r_xz * cos(CamTheta * pi / 180)
gluLookAt(x, y, z,
0.0, 0.0, 0.0,
0.0, 0.0, 1.0)
drawAxes(1500)
# data is a 4-tuple containing (numElems, mana, health, attack)
mostPopular = max([x[0] for x in data])
for i in range(len(data)):
drawSphere(data[i][0] * (spacing / 2) / mostPopular, data[i][1] * spacing, data[i][2] * spacing,
data[i][3] * spacing)
# since this is double buffered, we need to swap the buffers in order to
# display what we just drew
glutSwapBuffers()
# Added for graphics processors that do not employ frame-rate limiting
time.sleep(0.01)
def KeyPressed(key, x, y):
global show_axes, fill_polygons
global CamPhi, CamTheta, CamRange
# 'ord' gives the ascii int code of a character
# 'chr' gives the character associated to the ascii int code.
key = ord(key)
if key == 27: # Escape
glutDestroyWindow(hWindow)
sys.exit()
elif key == ord('S') or key == ord('s'):
CamPhi -= 1
if CamPhi < -90:
CamPhi = -90 # Limit
elif key == ord('W') or key == ord('w'):
CamPhi += 1
if CamPhi > 90:
CamPhi = 90 # Limit
elif key == ord('A') or key == ord('a'):
CamTheta -= 1
if CamTheta < 0:
CamTheta += 360 # Modulus
elif key == ord('D') or key == ord('d'):
CamTheta += 1
if CamTheta > 360:
CamTheta -= 360 # Modulus
elif key == ord('E') or key == ord('e'):
CamRange -= 1
elif key == ord('Q') or key == ord('q'):
CamRange += 1
if __name__ == "__main__":
# Info about the OpenGL version
# print "GPU = ",glGetString(GL_VENDOR)
# print "Renderer = ",glGetString(GL_RENDERER)
# print "OpenGL = ",glGetString(GL_VERSION)
# Defining global variables
global hWindow, nWidth, nHeight
global show_axes, fill_polygons
global data
# screen size
nWidth = 1080
nHeight = 720
# Initialise GLUT and a few other things
InitGLUT(nWidth, nHeight)
# create our window
hWindow = glutCreateWindow(b"Hearthstone Cards")
show_axes = True
fill_polygons = True
camera_rotation = 60
# Read in our data
data = readData()
data = getDrawable(data)
# setup the display function callback
glutDisplayFunc(DrawGLScene)
# setup the idle function callback -- if we idle, we just want to keep
# drawing the screen
glutIdleFunc(DrawGLScene)
# setup the window resize callback -- this is only needed if we arent going
# full-screen
glutReshapeFunc(ResizeGLScene)
# setup the keyboard function callback to handle key presses
glutKeyboardFunc(KeyPressed)
# setup the mouse callback
glutMouseFunc(handler)
# Tell people how to exit, then start the program...
print("To quit: Select OpenGL display window with mouse, then press ESC key.")
InitGL(nWidth, nHeight)
# enter the window's main loop to set things rolling
glutMainLoop()
|
{"/main2.py": ["/data.py"]}
|
9,136
|
BlueDragon23/Hearthstone
|
refs/heads/master
|
/testplot.py
|
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import json
file = open("C:\\Users\Aidan\Dropbox\\University\COSC3000\ComputerGraphics\cards.collectible.json")
cards = json.load(file)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
mana = []
health = []
attack = []
for card in cards:
if card['type'] != 'MINION':
continue
mana.append(card['cost'])
health.append(card['health'])
attack.append(card['attack'])
ax.scatter(mana, health, attack)
ax.set_xlabel('Mana')
ax.set_ylabel('Health')
ax.set_zlabel('Attack')
plt.show()
|
{"/main2.py": ["/data.py"]}
|
9,137
|
BlueDragon23/Hearthstone
|
refs/heads/master
|
/main2.py
|
import json
from math import *
import time
from OpenGL.GL import *
import logging
# logging.basicConfig(level=logging.DEBUG)
# OpenGL.FULL_LOGGING = True
# OpenGL.ERROR_ON_COPY = True
from OpenGL.GLU import *
from OpenGL.GLUT import *
import data
import sys
from PIL import Image
from io import BytesIO
import numpy
from OpenGL.arrays import vbo
import random
# Globals
CamPhi = 30
CamTheta = 90
CamRange = -3000
PhiRate = 3
ThetaRate = 3
RangeRate = 20
PerspectiveAngle = 45
MaximumDataPoint = 0
cardback = []
vertexBuffers = 0
boardWidth = 3080
boardHeight = 1400
mana = 3
TimeRemaining = 0
CamStep = 0
PhiStep = 0
ThetaStep = 0
previousTime = 0
UpdateFunction = lambda : 1
Transitioning = False
# Textures
textureIds = []
BoardId = 0
BoardImage = None
hand = []
friendlyBoard = []
enemyBoard = []
potentialBoard1 = {"friendly" : [], "enemy" : []}
potentialBoard2 = {}
potentialBoard3 = {}
previousBoard = {}
textureDict = {} # Map card names to their textures
def InitGLUT(nWidth, nHeight, title=""):
glutInit(title)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)
glutInitWindowSize(nWidth, nHeight)
glutInitWindowPosition(0, 0)
#
# A general OpenGL initialisation function that sets various initial parameters.
# We call this right after out OpenGL window is created.
#
def InitGL(nWidth, nHeight):
global BoardImage
# use black when clearing the colour buffers -- this will give us a black
# background for the window
glClearColor(0.0, 0.0, 0.0, 0.0)
# enable the depth buffer to be cleared
glClearDepth(1.0)
# set which type of depth test to use
glDepthFunc(GL_LESS)
# enable depth testing
glEnable(GL_DEPTH_TEST)
# enable smooth colour shading
glShadeModel(GL_SMOOTH)
# Load textures
BoardImage = Image.open("cards/Board.png")
InitTexturing()
ResizeGLScene(nWidth, nHeight)
#
# Initialises the textures being used for the scene
#
def InitTexturing():
global BoardId, BoardImage
# create textures
BoardId = glGenTextures(1)
print(BoardImage, BoardId)
# just use linear filtering
glBindTexture(GL_TEXTURE_2D, BoardId)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
data = BytesIO()
r, g, b, a = BoardImage.split()
dup = Image.merge("RGB", (r, g, b))
dup.save(data, format="BMP")
glTexImage2D(GL_TEXTURE_2D, 0, 4,
dup.width, dup.height,
0, GL_BGR, GL_UNSIGNED_BYTE, data.getvalue())
def init_texture(origName: str):
if origName in textureDict:
return
name = origName.lower()
name = "-".join(name.split())
name = str.replace(name, "'", "")
image = Image.open("cards/{}.png".format(name))
# create textures
id = glGenTextures(1)
textureIds.append(id)
# just use linear filtering
glBindTexture(GL_TEXTURE_2D, id)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
data = BytesIO()
r, g, b, a = image.split()
dup = Image.merge("RGB", (r, g, b))
dup.save(data, format="BMP")
glTexImage2D(GL_TEXTURE_2D, 0, 4,
dup.width, dup.height,
0, GL_BGR, GL_UNSIGNED_BYTE, data.getvalue())
textureDict[origName] = id
#
# The function called when our window is resized. This won't happen if we run
# in full screen mode.
#
def ResizeGLScene(nWidth, nHeight):
# prevent a divide-by-zero error if the window is too small
if nHeight == 0:
nHeight = 1
# reset the current viewport and recalculate the perspective transformation
# for the projection matrix
glViewport(0, 0, nWidth, nHeight)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(PerspectiveAngle, float(nWidth) / float(nHeight), 0.1, 10000.0)
glMatrixMode(GL_MODELVIEW)
def handler(button, state, x: int, y: int):
if state != GLUT_DOWN:
return
window_width = glutGet(GLUT_WINDOW_WIDTH)
window_height = glutGet(GLUT_WINDOW_HEIGHT)
# The following values are based on how the overlay is constructed
# If that changes, this will break
size = 50
pixel = glReadPixels(x, window_height - y, 1, 1, GL_RGB, GL_FLOAT)[0][0]
if x < size and y < size:
KeyPressed('1', x, y)
elif window_width/2 - size/2 < x < window_width/2 + size/2 \
and y < size:
KeyPressed('2', x, y)
elif x > window_width - size and y < size:
KeyPressed('3', x, y)
elif 0.105 < pixel[0] < 0.115:
# Decrease
modify_value(x, window_width, lambda a, b: a - b)
elif 0.115 < pixel[0] < 0.125:
modify_value(x, window_width, lambda a, b: a + b)
elif 0.095 < pixel[0] < 0.105:
set_value(x, window_width)
def modify_value(x, window_width, op):
global ThetaRate, RangeRate, PhiRate
if x < window_width/3:
ThetaRate = min(max(op(ThetaRate, 1), 1), 50)
print(ThetaRate)
elif x > 2*window_width/3:
RangeRate = min(max(op(RangeRate, 1), 1), 50)
else:
PhiRate = min(max(op(PhiRate, 1), 1), 50)
def set_value(x, window_width):
global ThetaRate, PhiRate, RangeRate
padding = 50
if x < window_width/3:
ThetaRate = 50 * ((x - padding)/(window_width/3 - 2*padding))
elif x > 2*window_width/3:
x = x - 2*window_width/3
RangeRate = 50 * ((x - padding)/(window_width/3 - 2*padding))
else:
x = x - window_width/3
PhiRate = 50 * ((x - padding)/(window_width/3 - 2*padding))
###################################################################################
def drawAxes(h):
# h : length of the axes
# draw axis X in red
# draw axis Y in green
# draw axis Z in blue
x = [h, 0, 0]
y = [0, h, 0]
z = [0, 0, h]
o = [0, 0, 0]
glBegin(GL_LINES)
glColor3fv([1, 0, 0])
glVertex3fv(o)
glVertex3fv(x)
glColor3fv([0, 1, 0])
glVertex3fv(o)
glVertex3fv(y)
glColor3fv([0, 0, 1])
glVertex3fv(o)
glVertex3fv(z)
glEnd()
def draw_board():
"""
:param x0:
:param y0:
:param z0:
:param x1:
:param y1:
:param z1:
:param isVertical: Orientation should be true for vertical, false for flat
:return:
"""
glPushMatrix()
glBindTexture(GL_TEXTURE_2D, BoardId)
width = boardWidth
height = boardHeight
glColor3f(1, 1, 1)
glBegin(GL_QUADS)
glTexCoord2f(0, 0)
glVertex3f(-width/2, -height/2, 0)
glTexCoord2f(1, 0)
glVertex3f(width/2, -height/2, 0)
glTexCoord2f(1, 1)
glVertex3f(width/2, height/2, 0)
glTexCoord2f(0, 1)
glVertex3f(-width/2, height/2, 0)
glEnd()
glPopMatrix()
def draw_minions(minions):
numCards = len(minions)
for i, minion in enumerate(minions):
glPushMatrix()
glBindTexture(GL_TEXTURE_2D, textureDict[minion['name']])
position = ((numCards) * ( -150 ) + 300 * i , -500, 0)
glTranslatef(position[0], position[1], position[2])
draw_card()
draw_cardback()
if minion['type'] == 'MINION':
draw_status_bars(minion)
glPopMatrix()
def draw_card():
glDisable(GL_LIGHTING)
height = 400
width = 275
glColor3f(1,1,1)
glBegin(GL_QUADS)
glTexCoord2f(0, 0)
glVertex3f(0, 0, 0)
glTexCoord2f(1, 0)
glVertex3f(width, 0, 0)
glTexCoord2f(1, 1)
glVertex3f(width, height, 0)
glTexCoord2f(0, 1)
glVertex3f(0, height, 0)
glEnd()
glEnable(GL_LIGHTING)
def draw_status_bars(minion):
width = 25
scaling = 25
attack = int(minion['attack'])
health = int(minion['health'])
def draw_rect(height):
glRectf(0, 0, width, height)
glDisable(GL_LIGHTING)
glDisable(GL_TEXTURE_2D)
# Draw attack
glPushMatrix()
glColor3fv([1, 1, 0])
glTranslatef(50, 70, 0)
glRotatef(90, 1, 0, 0)
draw_rect(attack*scaling)
glTranslatef( width, 0, 0 )
glRotatef( 90, 0, 1, 0 )
draw_rect(attack*scaling)
glTranslatef( width, 0, 0 )
glRotatef( 90, 0, 1, 0 )
draw_rect(attack*scaling)
glTranslatef( width, 0, 0 )
glRotatef( 90, 0, 1, 0 )
draw_rect(attack*scaling)
glTranslatef( 0, attack*scaling, -width)
glRotatef(90, 1, 0, 0)
glRectf(0, 0, width, width)
glPopMatrix()
# Draw health
glPushMatrix()
glColor3fv([1, 0, 0])
glTranslatef(300 - 50, 70, 0)
glRotatef(90, 1, 0, 0)
draw_rect(health*scaling)
glTranslatef( width, 0, 0 )
glRotatef( 90, 0, 1, 0 )
draw_rect(health*scaling)
glTranslatef( width, 0, 0 )
glRotatef( 90, 0, 1, 0 )
draw_rect(health*scaling)
glTranslatef( width, 0, 0 )
glRotatef( 90, 0, 1, 0 )
draw_rect(health*scaling)
glTranslatef( 0, health*scaling, -width)
glRotatef(90, 1, 0, 0)
glRectf(0, 0, width, width)
glPopMatrix()
glColor3fv([1, 1, 1])
glEnable(GL_LIGHTING)
glEnable(GL_TEXTURE_2D)
def draw_cardback():
glDisable(GL_TEXTURE_2D)
glPushMatrix()
glTranslate(275/2, 400/2, -10)
glScale(6.66, 6.875, 1)
glRotate(90, 0, 1, 0)
for i in range(len(cardback)):
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_NORMAL_ARRAY)
cardbackNormals[i].bind()
glNormalPointer(GL_FLOAT, 0, cardbackNormals[i])
cardbackVertices[i].bind()
material = data.find_mtl(cardback[i]["material"], materials)
# print(material)
glMaterialfv(GL_FRONT, GL_SPECULAR, [0.1, 0.1, 0.1])
# glMaterialfv(GL_FRONT, GL_SPECULAR, material["specular"])
# glMaterialfv(GL_FRONT, GL_SHININESS, [2])
# glMaterialfv(GL_FRONT, GL_AMBIENT, material["ambient"])
glMaterialfv(GL_FRONT, GL_DIFFUSE, material["diffuse"])
glVertexPointer(3, GL_FLOAT, 0, cardbackVertices[i])
glDrawArrays(GL_TRIANGLES, 0, len(cardbackVertices[i]))
glDisableClientState(GL_NORMAL_ARRAY)
glDisableClientState(GL_VERTEX_ARRAY)
glPopMatrix()
glEnable(GL_TEXTURE_2D)
def draw_decks():
glPushMatrix()
glTranslate(boardWidth/2 - 500, 0, -250)
glRotate(90, 0, 0, 1)
glRotate(90, 1, 0, 0)
difference = 20
for _ in range(5):
draw_cardback()
glTranslate(0, 0, difference)
glTranslate(-boardHeight/4, 0, -difference*5)
for _ in range(5):
draw_cardback()
glTranslate(0, 0, difference)
glPopMatrix()
def draw_mana():
glDisable(GL_TEXTURE_2D)
glPushMatrix()
glTranslate(boardWidth/5, -boardHeight/2, -5)
radius = 30
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, [41/255, 85/255, 146/255])
glEnable(GL_NORMALIZE)
for _ in range(mana):
glBegin(GL_TRIANGLE_FAN)
glNormal3f(0, 0, 1)
glVertex3f(0, 0, 10)
glNormal3f(-0.33, 0, 1)
glVertex3f(-radius, 0, 0)
glNormal3f(-0.25, 0.25, 1)
glVertex3f(-radius/2, radius, 0)
glNormal3f(0.25, 0.25, 1)
glVertex3f(radius/2, radius, 0)
glNormal3f(0.33, 0, 1)
glVertex3f(radius, 0, 0)
glNormal3f(0.25, -0.25, 1)
glVertex3f(radius/2, -radius, 0)
glNormal3f(-0.25, -0.25, 1)
glVertex3f(-radius/2, -radius, 0)
glNormal3f(-0.33, 0, 1)
glVertex3f(-radius, 0, 0)
glEnd()
glTranslate(radius*2, 0, 0)
glDisable(GL_NORMALIZE)
glPopMatrix()
glEnable(GL_TEXTURE_2D)
def draw_game(friendlyMinions, enemyMinions):
glPushMatrix()
draw_minions(friendlyMinions)
glPushMatrix()
glTranslate(0, 500, 0)
draw_minions(enemyMinions)
glPopMatrix()
draw_decks()
draw_mana()
glTranslate(0, -100, -20)
draw_board()
glPopMatrix()
def draw_numbers(width, height):
def draw_square(x, y, size):
"""
Treats the top left corner as 0, 0
"""
glColor([0.8 * x for x in [1, 1, 1]])
glBegin(GL_QUADS)
glVertex2f(x, height - y)
glVertex2f(x, height - y - size)
glVertex2f(x + size, height - y - size)
glVertex2f(x + size, height - y)
glEnd()
size = 50
margin = 10
draw_square(0, 0, size)
glColor(0, 0, 0)
glBegin(GL_LINE_STRIP)
glVertex2f(size / 2, height - margin)
glVertex2f(size / 2, height - (size - margin))
glEnd()
draw_square(width / 2 - size / 2, 0, size)
glColor(0, 0, 0)
glBegin(GL_LINE_STRIP)
glVertex2f(width / 2 - size / 2 + margin, height - margin)
glVertex2f(width / 2 + size / 2 - margin, height - margin) # -
glVertex2f(width / 2 + size / 2 - margin, height - size / 2) # |
glVertex2f(width / 2 - size / 2 + margin, height - size / 2) # -
glVertex2f(width / 2 - size / 2 + margin, height - size + margin) # |
glVertex2f(width / 2 + size / 2 - margin, height - size + margin) # -
glEnd()
draw_square(width - size, 0, size)
glColor(0, 0, 0)
glBegin(GL_LINE_STRIP)
glVertex2f(width - size + margin, height - margin)
glVertex2f(width - margin, height - margin) # -
glVertex2f(width - margin, height - size / 2) # |
glVertex2f(width - size + margin, height - size / 2) # -
glVertex2f(width - margin, height - size / 2) # -
glVertex2f(width - margin, height - size + margin) # |
glVertex2f(width - (size - margin), height - size + margin) # -
glEnd()
def draw_overlay():
"""
Draws a 2D overlay on top of the screen, as a HUD allowing some user interaction
Warning: If this function is changed, the handler may need
to be modified
:return:
"""
glDisable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
width = glutGet(GLUT_WINDOW_WIDTH)
height = glutGet(GLUT_WINDOW_HEIGHT)
gluOrtho2D(0, width, 0, height)
glMatrixMode(GL_MODELVIEW)
glPushMatrix()
glLoadIdentity()
draw_numbers(width, height)
# Bottom Panel
glColor(0.8, 0.8, 0.8)
glRectf(0, 0, width, height/8)
# Sliders
padding = width / 20
def draw_slider(x):
glBegin(GL_TRIANGLES)
glColor(0.11, 0.11, 0.11)
glVertex2f(x + padding/3, height/10/2)
glVertex2f(x + 2*padding/3, 2*height/10/3)
glVertex2f(x + 2*padding/3, height/10/3)
glColor(0.12, 0.12, 0.12)
glVertex2f(x + width/3 - padding/3, height/10/2)
glVertex2f(x + width/3 - 2*padding/3, 2*height/10/3)
glVertex2f(x + width/3 - 2*padding/3, height/10/3)
glEnd()
glColor(0.1, 0.1, 0.1)
glRectf(x + padding, padding, x + width/3 - padding, height/10 - padding)
draw_slider(0)
draw_slider(width/3)
draw_slider(2*width/3)
# Slider position
glColor(0.5, 0.5, 0.5)
vars = []
vars.extend([ThetaRate, PhiRate, RangeRate])
for i in range(3):
x = i*width/3 + padding + vars[i]/50*(width/3 - padding*2)
glRectf(x - 5, padding, x + 5, height/10 - padding)
# Text
labels = ["Horizontal Pan", "Vertical Pan", "Zoom Rate"]
for i in range(3):
glRasterPos2f(i*width/3 + padding, height/10-10)
text = labels[i]
for c in text:
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, ord(c))
glPopMatrix()
def DrawGLScene():
global CamRange, CamPhi, CamTheta, TimeRemaining, previousTime, CamStep, ThetaStep, PhiStep, Transitioning
glEnable(GL_DEPTH_TEST)
# clear the screen and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
width = glutGet(GLUT_WINDOW_WIDTH)
height = glutGet(GLUT_WINDOW_HEIGHT)
ResizeGLScene(width, height)
glMatrixMode(GL_MODELVIEW)
# reset the matrix stack with the identity matrix
glLoadIdentity()
# camera setup
# r_xz = CamRange * cos(CamPhi * pi / 180)
# x = r_xz * sin(CamTheta * pi / 180)
# y = CamRange * sin(CamPhi * pi / 180)
# z = r_xz * cos(CamTheta * pi / 180)
#
# gluLookAt(x, y, z,
# 0.0, 0.0, 0.0,
# 0.0, 0.0, 1.0)
if (TimeRemaining >= 0):
CamRange += CamStep
CamPhi += PhiStep
CamTheta += ThetaStep
TimeRemaining -= 100
if TimeRemaining <= 0 and Transitioning:
UpdateFunction()
CamPhi = -90
CamTheta = 90
CamRange = -800
# Reset to normal view
TimeRemaining = 2000
CamStep = (-3000 - CamRange) / (TimeRemaining / 100)
PhiStep = (30 - CamPhi) / (TimeRemaining / 100)
ThetaStep = (90 - CamTheta) / (TimeRemaining / 100)
Transitioning = False
print("Theta: {}, Phi: {}, Range: {}".format(CamTheta, CamPhi, CamRange))
x = CamRange * cos(CamTheta * pi / 180)
y = CamRange * sin(CamTheta * pi / 180)
lookX = boardHeight * cos(CamTheta * pi / 180)
lookY = boardHeight * sin(CamTheta * pi / 180)
lookZ = boardHeight * sin(CamPhi * pi / 180)
gluLookAt(x, y, boardHeight/2,
lookX, lookY, lookZ,
0.0, 0.0, 1.0)
# 3D
glEnable(GL_TEXTURE_2D)
glEnable(GL_LIGHTING)
glLightfv(GL_LIGHT0, GL_AMBIENT, [0.3, 0.3, 0.3, 1])
glEnable(GL_LIGHT0)
# drawAxes(100)
glLightfv(GL_LIGHT4, GL_POSITION, [0, 0, 2*boardHeight, 1])
glLightfv(GL_LIGHT4, GL_SPOT_DIRECTION, [0, 0, -1])
glLightfv(GL_LIGHT4, GL_SPOT_CUTOFF, 45)
glLightfv(GL_LIGHT4, GL_AMBIENT, [1, 1, 1, 1])
glEnable(GL_LIGHT4)
draw_game(friendlyBoard, enemyBoard) # Current board
glPushMatrix()
glTranslate(0, -boardHeight/2, 0)
draw_minions(hand)
glPopMatrix()
glDisable(GL_LIGHT4)
glTranslate(0, boardHeight + sqrt(2)*boardHeight/2, boardHeight/2)
glRotate(90, 1, 0, 0)
glLightfv(GL_LIGHT1, GL_POSITION, [0, boardHeight, 0, 1])
glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, [0, -1, 0])
glLightfv(GL_LIGHT1, GL_SPOT_CUTOFF, 45)
glLightfv(GL_LIGHT1, GL_AMBIENT, [0, 1, 0, 1])
glLightfv(GL_LIGHT1, GL_DIFFUSE, [0, 1, 0, 1])
glLightfv(GL_LIGHT1, GL_SPECULAR, [0, 1, 0, 1])
glEnable(GL_LIGHT1)
draw_game(potentialBoard1["friendly"], potentialBoard1["enemy"]) # Middle board
glPushMatrix()
glTranslate(0, boardHeight - 200, 0)
draw_minions(getPlayed(hand, potentialBoard1['hand']))
glPopMatrix()
glDisable(GL_LIGHT1)
glTranslate(-boardWidth, 0, sqrt(2)*boardHeight/2)
glRotate(45, 0, 1, 0)
glLightfv(GL_LIGHT2, GL_POSITION, [0, boardHeight, 0, 1])
glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, [-1, -1, 0])
glLightfv(GL_LIGHT2, GL_SPOT_CUTOFF, 45)
glLightfv(GL_LIGHT2, GL_AMBIENT, [1, 0, 0, 1])
glLightfv(GL_LIGHT2, GL_DIFFUSE, [1, 0, 0, 1])
glLightfv(GL_LIGHT2, GL_SPECULAR, [1, 0, 0, 1])
glEnable(GL_LIGHT2)
draw_game(potentialBoard2["friendly"], potentialBoard2["enemy"]) # Left board
glPushMatrix()
glTranslate(0, boardHeight - 200, 0)
draw_minions(getPlayed(hand, potentialBoard2['hand']))
glPopMatrix()
glDisable(GL_LIGHT2)
glRotate(-45, 0, 1, 0)
glTranslate(2*boardWidth, 0, 0)
glRotate(-45, 0, 1, 0)
glLightfv(GL_LIGHT3, GL_POSITION, [0, boardHeight, 0, 1])
glLightfv(GL_LIGHT3, GL_SPOT_DIRECTION, [1, -1, 0])
glLightfv(GL_LIGHT2, GL_SPOT_CUTOFF, 45)
glLightfv(GL_LIGHT3, GL_AMBIENT, [0, 0, 1, 1])
glLightfv(GL_LIGHT3, GL_DIFFUSE, [0, 0, 1, 1])
glLightfv(GL_LIGHT3, GL_SPECULAR, [0, 0, 1, 1])
glEnable(GL_LIGHT3)
draw_game(potentialBoard3["friendly"], potentialBoard3["enemy"]) # Right board
glPushMatrix()
glTranslate(0, boardHeight - 200, 0)
draw_minions(getPlayed(hand, potentialBoard3['hand']))
glPopMatrix()
glDisable(GL_LIGHT3)
glDisable(GL_LIGHT0)
glDisable(GL_LIGHTING)
glDisable(GL_TEXTURE_2D)
# Render 2D Overlay
draw_overlay()
glutSwapBuffers()
time.sleep(0.01)
def getPlayed(hand, potentialHand):
resultant = [card['name'] for card in potentialHand]
played = []
for card in hand:
if card['name'] not in resultant:
played.append(card)
return played
def KeyPressed(key, x, y):
global CamPhi, CamTheta, CamRange
global friendlyBoard, enemyBoard, potentialBoard1, potentialBoard2, potentialBoard3, previousBoard, hand
global mana
global CamStep, PhiStep, ThetaStep, TimeRemaining, UpdateFunction, Transitioning
# 'ord' gives the ascii int code of a character
# 'chr' gives the character associated to the ascii int code.
key = ord(key)
usedKeys = ['a', 's', 'w', 'd', 'q', 'e']
if key == 27: # Escape
glutDestroyWindow(hWindow)
sys.exit()
elif 's' in usedKeys and key == ord('S') or key == ord('s'):
CamPhi -= PhiRate
if CamPhi < -90:
CamPhi = -90 # Limit
elif 'w' in usedKeys and key == ord('W') or key == ord('w'):
CamPhi += PhiRate
if CamPhi > 90:
CamPhi = 90 # Limit
elif 'a' in usedKeys and key == ord('A') or key == ord('a'):
CamTheta += ThetaRate
if CamTheta > 360:
CamTheta -= 360 # Modulus
elif 'd' in usedKeys and key == ord('D') or key == ord('d'):
CamTheta -= ThetaRate
if CamTheta < 0:
CamTheta += 360 # Modulus
elif 'e' in usedKeys and key == ord('E') or key == ord('e'):
CamRange -= RangeRate
elif 'q' in usedKeys and key == ord('Q') or key == ord('q'):
CamRange += RangeRate
elif ord('1') <= key <= ord('3'):
previousBoard = {"friendly" : friendlyBoard[:], "enemy" : enemyBoard[:], "hand" : hand[:]}
mana = min(10, mana + 1)
TimeRemaining = 2000
CamStep = (-400 - CamRange) / (TimeRemaining / 100)
PhiStep = (30 - CamPhi) / (TimeRemaining / 100)
Transitioning = True
if key == ord('2'):
ThetaStep = (90 - CamTheta) / (TimeRemaining / 100)
UpdateFunction = selected_2
elif key == ord('1'):
ThetaStep = (60 - CamTheta) / (TimeRemaining / 100)
UpdateFunction = selected_1
elif key == ord('3'):
ThetaStep = (120 - CamTheta) / (TimeRemaining / 100)
UpdateFunction = selected_3
# Redefine potential boards
elif key == ord('0'):
# Go backwards
friendlyBoard = previousBoard["friendly"]
enemyBoard = previousBoard["enemy"]
def selected_3():
global friendlyBoard, enemyBoard, hand, potentialBoard1, potentialBoard2, potentialBoard3
# Third selection
friendlyBoard = potentialBoard3["friendly"][:]
enemyBoard = potentialBoard3["enemy"][:]
hand = potentialBoard3["hand"][:]
# Next turn
enemyBoard.append(data.select_minion(minions, "Acolyte of Pain"))
init_texture(enemyBoard[-1]['name'])
hand.append(data.select_minion(cards, "Soulfire"))
init_texture(hand[-1]['name'])
potentialBoard1 = {"friendly": friendlyBoard[:], "enemy": enemyBoard[:], "hand": hand[:]}
potentialBoard2 = {"friendly": friendlyBoard[:], "enemy": enemyBoard[:], "hand": hand[:]}
potentialBoard3 = {"friendly": friendlyBoard[:], "enemy": enemyBoard[:], "hand": hand[:]}
def selected_1():
global friendlyBoard, enemyBoard, hand, potentialBoard1, potentialBoard2, potentialBoard3
# Second selection
friendlyBoard = potentialBoard2["friendly"][:]
enemyBoard = potentialBoard2["enemy"][:]
hand = potentialBoard2["hand"][:]
# Next turn
enemyBoard.append(data.select_minion(minions, "Acolyte of Pain"))
init_texture(enemyBoard[-1]['name'])
hand.append(data.select_minion(cards, "Soulfire"))
init_texture(hand[-1]['name'])
potentialBoard1 = {"friendly": friendlyBoard[:], "enemy": enemyBoard[:], "hand": hand[:]}
potentialBoard1["friendly"].append(data.select_minion(minions, "Imp Gang Boss"))
index = \
[i for i in range(len(potentialBoard1["hand"])) if
potentialBoard1["hand"][i]['name'] == "Imp Gang Boss"][0]
potentialBoard1["hand"].remove(potentialBoard1["hand"][index])
index = \
[i for i in range(len(potentialBoard1["hand"])) if potentialBoard1["hand"][i]['name'] == "Soulfire"][0]
potentialBoard1["hand"].remove(potentialBoard1["hand"][index])
index = \
[i for i in range(len(potentialBoard1["enemy"])) if potentialBoard1["enemy"][i]['name'] == "Acolyte of Pain"][0]
potentialBoard1["enemy"].remove(potentialBoard1["enemy"][index])
potentialBoard2 = {"friendly": friendlyBoard[:], "enemy": enemyBoard[:], "hand": hand[:]}
potentialBoard2["friendly"].append(data.select_minion(minions, "Imp Gang Boss"))
index = \
[i for i in range(len(potentialBoard2["hand"])) if potentialBoard2["hand"][i]['name'] == "Imp Gang Boss"][0]
potentialBoard2["hand"].remove(potentialBoard2["hand"][index])
index = \
[i for i in range(len(potentialBoard2["hand"])) if potentialBoard2["hand"][i]['name'] == "Soulfire"][0]
potentialBoard2["hand"].remove(potentialBoard2["hand"][index])
potentialBoard3 = {"friendly": friendlyBoard[:], "enemy": enemyBoard[:], "hand": hand[:]}
index = \
[i for i in range(len(potentialBoard3["enemy"])) if potentialBoard3["enemy"][i]['name'] == "Acolyte of Pain"][0]
potentialBoard3["enemy"].remove(potentialBoard3["enemy"][index])
index = \
[i for i in range(len(potentialBoard3["friendly"])) if potentialBoard3["friendly"][i]['name'] == "Flame Imp"][0]
potentialBoard3["friendly"][index] = potentialBoard3["friendly"][index].copy()
potentialBoard3["friendly"][index]["health"] = 1
index = \
[i for i in range(len(potentialBoard3["hand"])) if potentialBoard3["hand"][i]['name'] == "Mortal Coil"][0]
potentialBoard3["hand"].remove(potentialBoard3["hand"][index])
def selected_2():
global friendlyBoard, enemyBoard, hand, potentialBoard1, potentialBoard2, potentialBoard3
# First selection
friendlyBoard = potentialBoard1["friendly"][:]
enemyBoard = potentialBoard1["enemy"][:]
hand = potentialBoard1["hand"][:]
# Next turn
enemyBoard.append(data.select_minion(minions, "Acolyte of Pain"))
init_texture(enemyBoard[-1]['name'])
hand.append(data.select_minion(cards, "Soulfire"))
init_texture(hand[-1]['name'])
potentialBoard1 = {"friendly": friendlyBoard[:], "enemy": enemyBoard[:], "hand": hand[:]}
potentialBoard1["friendly"].append(data.select_minion(minions, "Imp Gang Boss"))
potentialBoard1["friendly"].append(data.select_minion(minions, "Flame Imp"))
potentialBoard1["hand"].remove(potentialBoard1["hand"][0])
potentialBoard1["hand"].remove(potentialBoard1["hand"][0])
index = \
[i for i in range(len(potentialBoard1["friendly"])) if potentialBoard1["friendly"][i]['name'] == "Flame Imp"][0]
potentialBoard1["friendly"][index] = potentialBoard1["friendly"][index].copy()
potentialBoard1["friendly"][index]["health"] = 1
index = \
[i for i in range(len(potentialBoard1["enemy"])) if potentialBoard1["enemy"][i]['name'] == "Acolyte of Pain"][0]
potentialBoard1["enemy"].remove(potentialBoard1["enemy"][index])
potentialBoard2 = {"friendly": friendlyBoard[:], "enemy": enemyBoard[:], "hand": hand[:]}
potentialBoard2["friendly"].append(data.select_minion(minions, "Imp Gang Boss"))
potentialBoard2["friendly"].append(data.select_minion(minions, "Flame Imp"))
potentialBoard2["hand"].remove(potentialBoard2["hand"][0])
potentialBoard2["hand"].remove(potentialBoard2["hand"][0])
potentialBoard3 = potentialBoard1
if __name__ == "__main__":
# Info about the OpenGL version
# print "GPU = ",glGetString(GL_VENDOR)
# print "Renderer = ",glGetString(GL_RENDERER)
# print "OpenGL = ",glGetString(GL_VERSION)
# Defining global variables
global hWindow, nWidth, nHeight
global show_axes, fill_polygons
global cardback, vertexBuffers
# screen size
nWidth = 1080
nHeight = 720
# Initialise GLUT and a few other things
InitGLUT(nWidth, nHeight)
# create our window
hWindow = glutCreateWindow(b"Hearthstone Cards")
show_axes = True
fill_polygons = True
camera_rotation = 60
print(CamRange)
# Read in our data
cards = data.read_json()
minions = data.get_minions(cards)
handNames = ['Knife Juggler', 'Mortal Coil', 'Flame Imp', 'Imp Gang Boss']
friendlyBoardNames = ['Flame Imp', 'Flame Juggler']
enemyBoardNames = ['Loot Hoarder']
hand = [data.select_minion(cards, name) for name in handNames]
friendlyBoard = [data.select_minion(minions, name) for name in friendlyBoardNames]
enemyBoard = [data.select_minion(minions, name) for name in enemyBoardNames]
potentialBoard1 = {"friendly" : friendlyBoard[:], "enemy" : enemyBoard[:], "hand" : hand[:]} # Balanced
potentialBoard1["friendly"].append(data.select_minion(minions, "Knife Juggler"))
potentialBoard1["hand"].remove(potentialBoard1["hand"][0]) # Knife Juggler
potentialBoard1["hand"].remove(potentialBoard1["hand"][0]) # Mortal Coil
potentialBoard1["enemy"].remove(enemyBoard[0])
potentialBoard2 = {"friendly" : friendlyBoard[:], "enemy" : enemyBoard[:], "hand" : hand[:]} # Aggro
potentialBoard2["friendly"].append(data.select_minion(minions, "Knife Juggler"))
potentialBoard2["hand"].remove(potentialBoard2["hand"][0])
potentialBoard2["friendly"].append(data.select_minion(minions, "Flame Imp"))
potentialBoard2["hand"].remove(potentialBoard2["hand"][1])
if random.randint(0, 1) == 0:
potentialBoard2["enemy"].remove(potentialBoard2["enemy"][0])
potentialBoard3 = {"friendly" : friendlyBoard[:], "enemy" : enemyBoard[:], "hand" : hand[:]} # Control
potentialBoard3["friendly"].append(data.select_minion(minions, "Imp Gang Boss"))
potentialBoard3["hand"].remove(potentialBoard3["hand"][3])
potentialBoard3["friendly"][1] = potentialBoard3["friendly"][1].copy()
potentialBoard3["friendly"][1]["health"] = 1
potentialBoard3["enemy"].remove(enemyBoard[0])
for minion in hand:
init_texture(minion['name'])
for minion in friendlyBoard:
init_texture(minion['name'])
for minion in enemyBoard:
init_texture(minion['name'])
cardback = data.load_obj("cardback.obj")
materials = data.load_mtl("cardback.mtl")
cardbackVertices = []
for obj in cardback:
cardbackVertices.append(vbo.VBO(numpy.array(obj["vertices"], 'f')))
cardbackNormals = []
for obj in cardback:
cardbackNormals.append(vbo.VBO(numpy.array(obj["normals"], 'f')))
# setup the display function callback
glutDisplayFunc(DrawGLScene)
# setup the idle function callback -- if we idle, we just want to keep
# drawing the screen
glutIdleFunc(DrawGLScene)
# setup the window resize callback -- this is only needed if we arent going
# full-screen
glutReshapeFunc(ResizeGLScene)
# setup the keyboard function callback to handle key presses
glutKeyboardFunc(KeyPressed)
# setup the mouse callback
glutMouseFunc(handler)
# Tell people how to exit, then start the program...
print("To quit: Select OpenGL display window with mouse, then press ESC key.")
InitGL(nWidth, nHeight)
# enter the window's main loop to set things rolling
glutMainLoop()
|
{"/main2.py": ["/data.py"]}
|
9,138
|
lioenel/mybookshelf2
|
refs/heads/master
|
/manage.py
|
#!/usr/bin/env python
from flask_script import Manager, prompt_pass, prompt_bool
from flask_script.commands import InvalidCommand
from app import app,db
import app.model as model
from app.utils import hash_pwd
import app.schema as schema
import sys
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from sqlalchemy import or_
import os.path
DATA_DIR='./app/data'
manager = Manager(app)
def read_pwd():
password=prompt_pass('Password')
again=prompt_pass('Repeat password')
if password!=again:
raise InvalidCommand('Repeated password differs!')
return password
@manager.command
def create_user(user, email, password=None, role='user'):
if not password:
password=read_pwd()
data=dict(user_name=user, email=email, password=hash_pwd(password), active=True)
errors=schema.UserSchema(exclude=('version_id',)).validate(data, db.session)
if errors:
raise InvalidCommand('Validation Error: %s'%errors)
role=model.Role.query.filter_by(name=role).one()
u=model.User(**data)
u.roles.append(role)
db.session.add(u) # @UndefinedVariable
db.session.commit() # @UndefinedVariable
@manager.command
def change_password(user, password=None):
try:
u=model.User.query.filter(or_(model.User.user_name == user, model.User.email == user)).one() # @UndefinedVariable
except NoResultFound:
raise InvalidCommand('No such User')
if not password:
password=read_pwd()
u.password=hash_pwd(password)
db.session.commit() # @UndefinedVariable
@manager.command
def create_tables():
db.create_all()
connection = db.engine.raw_connection() # @UndefinedVariable
try:
c=connection.cursor()
for fname in ('create_ts.sql', 'create_functions.sql'):
script=open(os.path.join(os.path.dirname(__file__), DATA_DIR, fname), 'rt', encoding='utf-8-sig').read()
#print(script)
res=c.execute(script)
connection.commit()
finally:
connection.close()
@manager.command
def update_fulltext():
connection = db.engine.raw_connection() # @UndefinedVariable
try:
c=connection.cursor()
res=c.execute("update ebook set full_text=to_tsvector('custom', ebook_full_title(id))")
connection.commit()
finally:
connection.close()
#
@manager.command
def drop_tables():
if prompt_bool('Are you REALLY sure? You will loose all data!'):
db.drop_all()
if __name__ == "__main__":
try:
manager.run()
except InvalidCommand as err:
print(err, file=sys.stderr)
sys.exit(1)
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,139
|
lioenel/mybookshelf2
|
refs/heads/master
|
/app/api.py
|
from flask import Blueprint, request, abort, current_app, jsonify
from flask_restful import Resource as BaseResource, Api
import app.model as model
import app.schema as schema
import app.logic as logic
from app.utils import success_error, mimetype_from_file_name
from app import db
from app.cors import add_cors_headers
from app.access import role_required
from werkzeug import secure_filename
import os.path
import logging
import tempfile
logger = logging.getLogger('api')
bp = Blueprint('api', __name__)
api = Api(bp)
@bp.after_request
def after_request(response):
return add_cors_headers(response)
class Resource(BaseResource):
decorators = [role_required('user')]
pass
class Ebooks(Resource):
@logic.paginated(sortings=model.sortings['ebook'])
def get(self, page=1, page_size=20, sort=None, **kwargs):
q = model.Ebook.query
return logic.paginate(q, page, page_size, sort, schema.ebooks_list_serializer())
def post(self):
pass
class Authors(Resource):
@logic.paginated(sortings=model.sortings['author'])
def get(self, page=1, page_size=20, sort=None, **kwargs):
q = model.Author.query
return logic.paginate(q, page, page_size, sort, schema.authors_list_serializer())
class Series(Resource):
@logic.paginated(sortings=model.sortings['series'])
def get(self, page=1, page_size=20, sort=None, **kwargs):
q = model.Series.query
return logic.paginate(q, page, page_size, sort, schema.series_list_serializer())
class Ebook(Resource):
def get(self, id):
b = model.Ebook.query.get_or_404(id)
return schema.ebook_serializer().dump(b).data # @UndefinedVariable
@role_required('superuser')
def delete(self, id):
b = model.Ebook.query.get_or_404(id)
r = db.session.delete(b) # @UndefinedVariable
db.session.commit()
def put(self, id):
pass
class Author(Resource):
def get(self, id):
a = model.Author.query.get_or_404(id)
return schema.author_serializer().dump(a).data
class Search(Resource):
@logic.paginated()
def get(self, search, page=1, page_size=20, **kwargs):
q = logic.search_query(model.Ebook.query, search)
return logic.paginate(q, page, page_size, None, schema.ebooks_list_serializer())
class AuthorEbooks(Resource):
@logic.paginated(sortings=model.sortings['ebook'])
def get(self, id, page=1, page_size=20, sort=None):
q = model.Ebook.query.join(
model.Author, model.Ebook.authors).filter(model.Author.id == id)
if request.args.get('filter'):
q = logic.filter_ebooks(q, request.args.get('filter'))
return logic.paginate(q, page, page_size, sort, schema.ebooks_list_serializer())
class UploadMeta(Resource):
def get(self, id):
upload = model.Upload.query.get_or_404(id)
data = schema.upload_serializer().dump(upload).data
# search = upload.meta.get('title', '') + ' ' + ' '.join(upload.meta.get('authors', []))
# search = search.strip()
# if search:
# q = logic.search_query(model.Ebook.query, search)
# if q:
# data['proposed_ebook'] = schema.ebook_serializer().dump(q[0]).data
return data
@bp.route('/upload', methods=['POST'])
@role_required('user')
def upload():
file = request.files['file']
if file:
filename = secure_filename(file.filename)
temp_dir = tempfile.mkdtemp(dir=current_app.config['UPLOAD_DIR'])
tdir = os.path.split(temp_dir)[1]
full_name = os.path.join(temp_dir, filename)
file.save(full_name)
result = logic.check_uploaded_file(file.mimetype, full_name)
if result:
os.remove(full_name)
return jsonify(**result)
return jsonify(result='ok', file=os.path.join(tdir, filename))
return jsonify(error='no file')
@bp.route('/upload/check', methods=['POST'])
@role_required('user')
def check_upload():
file_info = request.json
logger.debug('File info %s' % file_info)
err = schema.FileInfoSchema().validate(file_info)
print(err, file_info)
if err:
logger.warn('Invalid file info: %s', err)
return jsonify(error='Invalid schema')
r = logic.check_file(**file_info)
if r:
return jsonify(**r)
return jsonify(result='ok')
@bp.route('/download/<int:id>')
@role_required('user')
def download(id):
return logic.download(id)
@bp.route('/cover-meta/<int:id>/<string:size>')
@role_required('user')
def cover_meta(id, size='normal'):
upload = model.Upload.query.get_or_404(id)
if not upload.cover:
abort(404, 'No cover')
fname = os.path.join(current_app.config['UPLOAD_DIR'], upload.cover)
mimetype = mimetype_from_file_name(fname)
if not mimetype:
abort(500, 'Invalid cover file')
return logic.stream_response(fname, mimetype)
@bp.route('/series/index/<string:start>')
@role_required('user')
def series_index(start):
total, items = logic.series_index(start)
serializer = schema.series_list_serializer()
return jsonify(total=total,
items=serializer.dump(items).data)
@bp.route('/authors/index/<string:start>')
@role_required('user')
def authors_index(start):
total, items = logic.authors_index(start)
serializer = schema.authors_list_serializer()
return jsonify(total=total,
items=serializer.dump(items).data)
@bp.route('/ebooks/index/<string:start>')
@role_required('user')
def ebookss_index(start):
total, items = logic.ebooks_index(start)
serializer = schema.ebooks_list_serializer()
return jsonify(total=total,
items=serializer.dump(items).data)
api.add_resource(Ebooks, '/ebooks')
api.add_resource(Ebook, '/ebooks/<int:id>')
api.add_resource(AuthorEbooks, '/ebooks/author/<int:id>')
api.add_resource(Authors, '/authors')
api.add_resource(Author, '/authors/<int:id>')
api.add_resource(Series, '/series')
api.add_resource(Search, '/search/<string:search>')
api.add_resource(UploadMeta, '/uploads-meta/<int:id>')
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,140
|
lioenel/mybookshelf2
|
refs/heads/master
|
/engine/tasks.py
|
import os.path
import re
import asyncio
from asexor.task import BaseTask, TaskError
from settings import UPLOAD_DIR, IMAGE_MAGIC
from app.utils import file_hash
import logging
import engine.dal as dal
logger = logging.getLogger('tasks')
class MetadataTask(BaseTask):
NAME = 'metadata'
COMMAND = 'ebook-meta'
MAX_TIME = 60
async def validate_args(self, *args, **kwargs):
f = args[0]
fname = os.path.join(UPLOAD_DIR, f)
base_name = os.path.splitext(f)[0]
self.cover_name = base_name + '_tmp.jpg'
if not os.access(fname, os.R_OK):
raise TaskError('File %s does not exists or is not readable')
self.fname = f
self.fname_full = fname
return ('--get-cover=%s' % os.path.join(UPLOAD_DIR, self.cover_name), fname)
AUTHORS_RE = re.compile(
r'^Author\(s\)\s*:\s*(.+)', re.UNICODE | re.MULTILINE)
TITLE_RE = re.compile(r'^Title\s*:\s*(.+)', re.UNICODE | re.MULTILINE)
TAGS_RE = re.compile(r'^Tags\s*:\s*(.+)', re.UNICODE | re.MULTILINE)
SERIES_RE = re.compile(r'^Series\s*:\s*(.+)', re.UNICODE | re.MULTILINE)
LANGUAGES_RE = re.compile(
r'^Languages\s*:\s*(.+)', re.UNICODE | re.MULTILINE)
async def _parse_data(self, data):
def strip(l):
return list(map(lambda x: x.strip(), filter(None, l)))
meta = {}
title = self.TITLE_RE.search(data)
if title:
meta['title'] = title.group(1).strip()
authors = self.AUTHORS_RE.search(data)
if authors:
authors = re.sub(r'\[[^\]]+\]', '', authors.group(1))
meta['authors'] = strip(authors.split('&'))
tags = self.TAGS_RE.search(data)
if tags:
meta['tags'] = strip(tags.group(1).split(','))
languages = self.LANGUAGES_RE.search(data)
if languages:
meta['language'] = languages.group(1).split(',')[0].strip()
series = self.SERIES_RE.search(data)
if series:
series = re.match(r'(.*) #(\d+)', series.group(1))
if series:
meta['series'] = series.group(1)
meta['series_index'] = int(series.group(2))
return meta
async def parse_result(self, data):
data = data.decode(self.output_encoding)
meta = await self._parse_data(data)
cover_in = os.path.join(UPLOAD_DIR, self.cover_name)
loop = asyncio.get_event_loop()
hash = await loop.run_in_executor(None, file_hash, self.fname_full)
size = await loop.run_in_executor(None, lambda f: os.stat(f).st_size, self.fname_full)
cover = None
if os.path.exists(cover_in):
cover_file = self.cover_name[:-8] + '_cover.jpg'
cover_file_full = os.path.join(UPLOAD_DIR, cover_file)
proc = await asyncio.create_subprocess_exec(IMAGE_MAGIC, cover_in, '-fuzz', '7%',
'-trim', cover_file_full)
return_code = await proc.wait()
if return_code == 0 and os.path.exists(cover_file_full):
os.remove(cover_in)
else:
logger.warn(
'Image Magic failed triming file %s with code %d', cover_in, return_code)
os.rename(cover_in, cover_file_full)
cover = cover_file
else:
logger.warn('Cannot get cover image')
upload_id = await dal.add_upload(self.fname, cover, meta, size, hash, self.user)
return upload_id
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,141
|
lioenel/mybookshelf2
|
refs/heads/master
|
/app/tests/test_logic.py
|
from app import db, app
import app.model as model
import app.logic as logic
from .basecase import TestCase
import os.path
ebook_file = os.path.join(os.path.dirname(
__file__), '../data/books/Kissinger, Henry/Roky v Bilem dome/Kissinger, Henry - Roky v Bilem dome.epub')
class TestLogic(TestCase):
def test_logic(self):
b1 = model.Ebook.query.get(33837)
self.assertEqual(b1.authors_str, 'Crichton Michael')
b2 = model.Ebook.query.get(37157)
self.assertEqual(b2.authors_str, 'Strugackij A N, Strugackij B N')
b3 = model.Ebook.query.get(62546)
self.assertEqual(b3.authors_str, 'Wilkins G, Dalton M, Young K')
b3.authors.append(b1.authors[0])
self.assertEqual(
b3.authors_str, 'Wilkins G, Dalton M, Young K and others')
b1.authors = []
self.assertEqual(b1.authors_str, 'No Authors')
source = model.Source.query.get(46519)
name = logic.norm_file_name(source)
self.assertEqual(
name, 'Strugackij A N, Strugackij B N/Noc na Marse/Strugackij A N, Strugackij B N - Noc na Marse.doc')
source = model.Source.query.get(63546)
name = logic.norm_file_name(source)
self.assertEqual(
name, 'Monroe Lucy/Nevesty od Stredozemniho more/Nevesty od Stredozemniho more 2 - Spanelova milenka/Monroe Lucy - Nevesty od Stredozemniho more 2 - Spanelova milenka.doc')
res = logic.check_uploaded_file('application/epub+zip', ebook_file)
self.assertEqual(res['error'], 'file already exists')
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,142
|
lioenel/mybookshelf2
|
refs/heads/master
|
/app/utils.py
|
from functools import wraps
import bcrypt
import jwt
from datetime import datetime, timedelta
import unicodedata
import hashlib
import logging
import mimetypes
logger = logging.getLogger('utils')
def mimetype_from_file_name(fname):
return mimetypes.guess_type(fname, False)[0]
def success_error(fn):
@wraps(fn)
def inner(*args, **kwargs):
try:
fn(*args, **kwargs)
return {'success': True}
except Exception as e:
return {'error': str(e)}
return inner
READ_BLOCK = 8192
def file_hash(fname):
h = hashlib.sha1()
with open(fname, 'rb') as f:
s = f.read(READ_BLOCK)
if not s:
raise ValueError("Empty file!")
while s:
h.update(s)
s = f.read(READ_BLOCK)
return h.hexdigest()
def hash_pwd(p):
if isinstance(p, str):
p = p.encode('utf-8')
return bcrypt.hashpw(p, bcrypt.gensalt()).decode('ascii')
def check_pwd(p, hash):
if isinstance(p, str):
p = p.encode('utf-8')
if isinstance(hash, str):
hash = hash.encode('ascii')
return hash == bcrypt.hashpw(p, hash)
def create_token(user, secret, valid_minutes=24 * 60):
token = jwt.encode({'id': user.id,
'user_name': user.user_name,
'email': user.email,
'roles': list(user.all_roles),
'exp': datetime.utcnow() + timedelta(hours=valid_minutes)}, secret, algorithm='HS256')
return token.decode('ascii')
def verify_token(token, secret):
try:
token = token.encode('ascii')
except UnicodeEncodeError:
logger.exception('Invalid token - char encoding')
return
try:
claim = jwt.decode(token, secret)
except jwt.InvalidTokenError:
logger.exception('Invalid token')
return None
return claim
def extract_token(token):
try:
return jwt.decode(token, verify=False)
except jwt.InvalidTokenError as e:
raise ValueError('Invalid token %s' % e)
def initials(name):
names = name.split()
return ' '.join(map(lambda n: n[0].upper(), names))
nd_charmap = {
u'\N{Latin capital letter AE}': 'AE',
u'\N{Latin small letter ae}': 'ae',
u'\N{Latin capital letter Eth}': 'D',
u'\N{Latin small letter eth}': 'd',
u'\N{Latin capital letter O with stroke}': 'O',
u'\N{Latin small letter o with stroke}': 'o', #
u'\N{Latin capital letter Thorn}': 'Th',
u'\N{Latin small letter thorn}': 'th',
u'\N{Latin small letter sharp s}': 's',
u'\N{Latin capital letter D with stroke}': 'D',
u'\N{Latin small letter d with stroke}': 'd',
u'\N{Latin capital letter H with stroke}': 'H',
u'\N{Latin small letter h with stroke}': 'h',
u'\N{Latin small letter dotless i}': 'i',
u'\N{Latin small letter kra}': 'k',
u'\N{Latin capital letter L with stroke}': 'L',
u'\N{Latin small letter l with stroke}': 'l',
u'\N{Latin capital letter Eng}': 'N',
u'\N{Latin small letter eng}': 'n',
u'\N{Latin capital ligature OE}': 'Oe',
u'\N{Latin small ligature oe}': 'oe',
u'\N{Latin capital letter T with stroke}': 'T',
u'\N{Latin small letter t with stroke}': 't',
}
def remove_diacritics(text):
"Removes diacritics from the string"
if not text:
return text
s = unicodedata.normalize('NFKD', text)
b = []
for ch in s:
if unicodedata.category(ch) != 'Mn':
if ch in nd_charmap:
b.append(nd_charmap[ch])
elif ord(ch) < 128:
b.append(ch)
else:
b.append(' ')
return ''.join(b)
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,143
|
lioenel/mybookshelf2
|
refs/heads/master
|
/app/tests/test_schema.py
|
'''
Created on Apr 21, 2016
@author: ivan
'''
import unittest
from app import app,db
import app.schema as schema
import app.model as model
from .basecase import TestCase
#app.config['SQLALCHEMY_ECHO']=True
class Test(TestCase):
def test_schema_ebook(self):
ebook_data={'title': 'Sedm lumpu slohlo pumpu'}
errors=schema.ebook_deserializer_insert().validate(ebook_data)
self.assertFalse(errors)
errors=schema.ebook_deserializer_insert().validate({})
self.assertTrue(errors)
ebook_data={'title':'Povidky o nicem', 'language':'cs',
'rating':100,
'authors':[{'first_name':'Jan', 'last_name': 'Kan'}],
'series':{'id':5, 'title':'Za co'},
'series_index':1,
'genres':[ {'id':23,'name':'Romance'}, {'id':9, 'name':'Fantasy'}, {'id':13, 'name':'Horror'}],
'version_id':1
}
eb,errors=schema.ebook_deserializer_update().load(ebook_data)
print (errors)
self.assertFalse(errors)
self.assertEqual(eb.title, ebook_data['title'])
db.session.flush()
self.assertFalse(db.session.new)
self.assertFalse(db.session.dirty)
db.session.add(eb)
db.session.commit()
self.assertEqual(eb.authors[0].last_name, ebook_data['authors'][0]['last_name'] )
self.assertEqual(eb.series.title, ebook_data['series']['title'])
db.session.remove()
eb=model.Ebook.query.filter_by(title='Povidky o nicem').one()
self.assertEqual(eb.authors[0].last_name, ebook_data['authors'][0]['last_name'] )
self.assertEqual(eb.series.title, ebook_data['series']['title'])
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,144
|
lioenel/mybookshelf2
|
refs/heads/master
|
/engine/dal.py
|
import aiopg
from aiopg.sa import create_engine
import settings
import asyncio
import os
import sys
import app.model as model
from psycopg2.extras import Json
from sqlalchemy.sql import select, or_
DSN = 'dbname={db} user={user} password={password} host={host}'.format(db=settings.DB_NAME,
host=settings.DB_HOST,
user=settings.DB_USER,
password=settings.DB_PASSWORD
)
engine = None
def init():
global engine
loop = asyncio.get_event_loop()
engine = loop.run_until_complete(create_engine(DSN))
def close(wait=False):
engine.close()
if wait:
loop = asyncio.get_event_loop()
loop.run_until_complete(engine.wait_closed())
async def add_upload(fname, cover, meta, size, hash, user_email):
async with engine.acquire() as conn:
format = model.Format.__table__
ext = os.path.splitext(fname)[1].lower()[1:]
res = await conn.execute(select([format.c.id]).where(format.c.extension == ext))
format_id = (await res.fetchone())[0]
user = model.User.__table__
res = await conn.execute(select([user.c.id]).where(user.c.email == user_email))
user_id = (await res.fetchone())[0]
upload = model.Upload.__table__
source_name = os.path.split(fname)[-1]
res = await conn.execute(upload.insert().values(file=fname, cover=cover,
load_source=source_name,
size=size, hash=hash,
format_id=format_id,
version_id=1,
created_by_id=user_id,
modified_by_id=user_id,
meta=meta
))
new_id = (await res.fetchone())[0]
return new_id
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,145
|
lioenel/mybookshelf2
|
refs/heads/master
|
/engine/tests/test_meta.py
|
import unittest
from unittest.mock import Mock
import engine.dal as dal
import shutil
import os.path
import asyncio
from settings import UPLOAD_DIR
from engine.tasks import MetadataTask
class TestMeta(unittest.TestCase):
def setUp(self):
fname = os.path.join(os.path.dirname(__file__),
'../../app/data/books/Adams, Douglas/Stoparuv pruvodce/Stoparuv pruvodce 1 - Stoparuv pruvodce po Galaxii/Adams, Douglas - Stoparuv pruvodce 1 - Stoparuv pruvodce po Galaxii.epub'
)
shutil.copy(fname, UPLOAD_DIR)
self.fname = os.path.split(fname)[1]
def tearDown(self):
try:
os.remove(os.path.join(UPLOAD_DIR, self.fname))
except IOError:
pass
def test_meta1(self):
result=[]
upload = Mock(side_effect=lambda *args: result.extend(args) or 1)
async def dummy(*args, **kwargs):
return upload(*args, **kwargs)
dal.add_upload = dummy
t = MetadataTask(user='ivan')
loop = asyncio.get_event_loop()
res = loop.run_until_complete(t.run(self.fname))
self.assertEqual(res, 1)
meta = result[2]
self.assertEqual(meta['authors'], ['Douglas Adams'])
self.assertEqual(meta['title'], 'Stopařův průvodce po Galaxii')
self.assertEqual(meta['tags'], ['Fantasy', 'Humor', 'Sci-fi'])
self.assertEqual(result[3], 200134)
self.assertEqual(result[4], 'f75a07f5ad1da3a27035742eb978868b1a912a1a')
self.assertEqual(result[5], 'ivan')
cover = result[1]
self.assertTrue(cover)
os.remove(os.path.join(UPLOAD_DIR, cover))
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,146
|
lioenel/mybookshelf2
|
refs/heads/master
|
/app/minimal.py
|
from flask import Blueprint, render_template, request, flash
from flask_login import login_required
import app.model as model
import app.logic as logic
import app.access as access
bp = Blueprint('minimal', __name__)
@bp.route('/search', methods=['GET'])
@login_required
def search():
search = ''
ebooks = None
if request.args.get('search'):
search = request.args['search'].strip()
if search:
ebooks = logic.search_query(model.Ebook.query, search).limit(50).all()
if not ebooks:
flash('No ebooks found!')
return render_template('search.html', search=search, ebooks=ebooks)
@bp.route('/ebooks/<int:id>')
@login_required
def ebook_detail(id):
ebook = model.Ebook.query.get(id)
return render_template('ebook.html', ebook=ebook)
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,147
|
lioenel/mybookshelf2
|
refs/heads/master
|
/engine/backend.py
|
import os.path
import sys
import asyncio
import logging
from asexor.runner import ApplicationRunnerRawSocket
from asexor.executor import Executor
from asexor.config import Config
from asexor.task import load_tasks_from
from autobahn.wamp.exception import ApplicationError
import time
import engine.dal as dal
# sys.path.append(os.path.join(os.path.dirname(__file__),'..'))
from app.utils import verify_token
import settings
log = logging.getLogger('engine')
def authenticate(realm, user_id, details):
log.debug('Got auth request for %s')
token = details.get('ticket')
payload = verify_token(token, settings.SECRET_KEY)
if payload and user_id == payload['email']:
if 'user' in payload['roles']:
log.debug('Authenticaticated user %s to role user', user_id)
return 'user'
return 'anonymous'
if __name__ == '__main__':
import argparse
# for testing
load_tasks_from('engine.tasks')
parser = argparse.ArgumentParser()
parser.add_argument(
'-d', '--debug', action='store_true', help='enable debug')
opts = parser.parse_args()
level = 'info'
if opts.debug:
level = 'debug'
Config.AUTHENTICATION_PROCEDUTE = authenticate
Config.AUTHENTICATION_PROCEDURE_NAME = "eu.zderadicka.mybookshelf.authenticate"
path = os.path.join(os.path.dirname(__file__), '.crossbar/socket1')
runner = ApplicationRunnerRawSocket(
path,
u"realm1",
)
dal.init()
runner.run(Executor, logging_level=level)
dal.close()
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,148
|
lioenel/mybookshelf2
|
refs/heads/master
|
/server.py
|
#! /usr/bin/env python
import sys
from app import app
if __name__ == "__main__":
dbg=True
host='127.0.0.1'
if len(sys.argv)>1 and 'NO_DEBUG' in sys.argv[1:]:
dbg=False
if len(sys.argv)>1 and 'VISIBLE' in sys.argv[1:]:
host='0.0.0.0'
app.run(debug=dbg, host=host, port=6006)
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,149
|
lioenel/mybookshelf2
|
refs/heads/master
|
/engine/dal2.py
|
import aiopg
import aiopg.sa
import settings
import asyncio
import os
import sys
DSN = 'dbname={db} user={user} password={password} host={host}'.format(db=settings.DB_NAME,
host=settings.DB_HOST,
user=settings.DB_USER,
password=settings.DB_PASSWORD
)
pool = None
def init():
global pool
loop = asyncio.get_event_loop()
pool = loop.run_until_complete(aiopg.create_pool(DSN))
def close(wait=False):
pool.terminate()
if wait:
loop = asyncio.get_event_loop()
loop.run_until_complete(pool.wait_closed())
if __name__ == '__main__':
print (sys.version)
init()
assert pool
async def do():
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute('select * from format')
async for row in cur:
print(row)
loop=asyncio.get_event_loop()
loop.run_until_complete(do())
close()
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,150
|
lioenel/mybookshelf2
|
refs/heads/master
|
/app/access.py
|
from flask import request, redirect, flash, render_template, url_for, jsonify, Blueprint, abort
from flask_login import LoginManager, login_user, logout_user, current_user, login_required
from functools import wraps
from app.utils import check_pwd, create_token, verify_token
import app.model as model
from sqlalchemy import or_
from sqlalchemy.orm.exc import NoResultFound
import logging
logger=logging.getLogger('access')
from app.cors import cors_enabled
bp=Blueprint('access', __name__)
lm=LoginManager()
SECRET_KEY=''
TOKEN_VALIDITY_HOURS=4
@bp.record_once
def on_load(state):
global SECRET_KEY, TOKEN_VALIDITY_HOURS
lm.init_app(state.app)
SECRET_KEY=state.app.config.get('SECRET_KEY')
TOKEN_VALIDITY_HOURS=state.app.config.get('TOKEN_VALIDITY_HOURS')
@lm.request_loader
def load_user_from_request(request):
user_token = request.args.get('bearer_token')
if not user_token:
token=request.headers.get('Authorization')
if token and token.lower().startswith('bearer '):
user_token=token[7:].strip()
if not user_token:
return
claim=verify_token(user_token, SECRET_KEY)
if claim:
user=model.User.query.get(claim['id']) # @UndefinedVariable
if user and user.is_active:
return user
# finally, return None if both methods did not login the user
return None
@lm.user_loader
def load_user(user_id):
return model.User.query.get(int(user_id)) # @UndefinedVariable
def role_required(*roles):
def wrapper(fn):
@wraps(fn)
def inner(*args,**kwargs):
user=current_user
if not(user.is_authenticated and user.has_role(*roles)):
abort(401, 'Access denied')
return fn(*args, **kwargs)
return inner
return wrapper
def role_required_owning(*roles, if_own=None, owning_role=None):
assert roles or (if_own and owning_role)
user=current_user
if user.is_authenticated and user.has_role(*roles):
return
if if_own and if_own.created_by == user and user.is_authenticated and user.has_role(owning_role):
return
abort(401, 'Access denied')
@bp.route('/login', methods=['GET', 'POST'])
@cors_enabled
def login():
def check_user(username, pwd):
user= model.User.query.filter(or_(model.User.user_name == username, # @UndefinedVariable
model.User.email ==username)).one_or_none() # @UndefinedVariable
if user and check_pwd(pwd, user.password):
return user
username=""
if request.method=='POST':
if request.mimetype == 'application/json':
credentials=request.get_json()
if credentials and (credentials.get('email') or credentials.get('username')) and credentials.get('password'):
q=model.User.query
if 'username' in credentials:
q=q.filter(model.User.user_name == credentials['username'])
else:
q=q.filter(model.User.email == credentials['email'] )
try:
user=q.one()
except NoResultFound:
return jsonify(error= 'Invalid Login')
if not user.is_active:
return jsonify(error= 'Invalid Login')
if not check_pwd(credentials['password'], user.password):
return jsonify(error= 'Invalid Login')
resp= jsonify(access_token=create_token(user, SECRET_KEY, TOKEN_VALIDITY_HOURS or 4))
#resp.headers.extend(cors_headers)
return resp
else:
logger.info('Failed JSON login with %s', credentials)
abort(400,'Provide credentials')
else:
user=check_user(request.form['username'], request.form['password'] )
if user:
logger.info('User logged in %s ', user.user_name)
login_user(user)
#request.args.get("next")
return redirect('/')
else:
flash('Invalid user name or password!')
return render_template('login.html', username=username)
@bp.route('/logoff')
@login_required
def logoff():
logout_user()
return redirect(url_for('access.login'))
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,151
|
lioenel/mybookshelf2
|
refs/heads/master
|
/engine/tests/test_dal.py
|
import unittest
import asyncio
import engine.dal as dal
from settings import Testing
from app.tests.basecase import TestCase
import app.model as model
dal.DSN = 'dbname={db} user={user} password={password} host={host}'.format(db=Testing.DB_NAME,
host=Testing.DB_HOST,
user=Testing.DB_USER,
password=Testing.DB_PASSWORD
)
class TestDAL(TestCase):
def test_dal1(self):
from app.model import Format
dal.init()
assert dal.engine
fmt_table = Format.__table__
formats = []
async def do():
async with dal.engine.acquire() as conn:
async for row in conn.execute(fmt_table.select(fmt_table)):
formats.append(row.mime_type)
loop = asyncio.get_event_loop()
loop.run_until_complete(do())
self.assertEqual(len(formats), 17)
self.assertTrue('application/x-aportisdoc' in formats)
# ----
insert = dal.add_upload(fname='ebook.epub', cover='cover.jpg', meta={'authors': ['Douglas Adams'],
'title': 'Stoparuv pruvodce'}, size=1233455,
hash='12345678901234567890123456789010',
user_email='admin@example.com')
new_id = loop.run_until_complete(insert)
self.assertEqual(new_id, 1)
dal.close()
upload = model.Upload.query.get(new_id)
self.assertEqual(upload.created_by.email, 'admin@example.com')
self.assertEqual(upload.meta['title'], 'Stoparuv pruvodce')
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,152
|
lioenel/mybookshelf2
|
refs/heads/master
|
/engine/client.py
|
from autobahn.asyncio.wamp import ApplicationSession
from asyncio import coroutine, get_event_loop
import logging
import requests
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(__file__),'..'))
from app.utils import extract_token
log=logging.getLogger('client')
class ClientSession(ApplicationSession):
# must be set before session
TOKEN=''
USER=''
def onConnect(self):
log.debug('Connected')
self.join(self.config.realm, [u"ticket"], self.USER)
def onChallenge(self, ch):
if ch.method=='ticket':
log.debug('Got challenge %s', ch)
return self.TOKEN
else:
raise Exception('Invalid authentication method')
@ coroutine
def onJoin(self, details):
log.debug('Session joined %s', details)
self.subscribe(lambda t: print('#Notification', t), 'eu.zderadicka.mybookshelf2.heartbeat')
def onLeave(self, details):
log.debug("Leaving session %s", details)
self.disconnect()
def onDisconnect(self):
log.debug('Disconnected')
get_event_loop().stop()
if __name__=='__main__':
#logging.basicConfig(level=logging.DEBUG)
log.setLevel(logging.DEBUG)
resp=requests.post('http://localhost:6006/login', json={'username':'admin', 'password':'admin'})
token = resp.json().get('access_token')
if token:
ClientSession.TOKEN=token
ClientSession.USER=extract_token(token)['email']
print('Starting client for user %s'% (ClientSession.USER))
from autobahn.asyncio.wamp import ApplicationRunner
app=ApplicationRunner(url='ws://localhost:8080/ws', realm='realm1')
app.run(ClientSession)
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,153
|
lioenel/mybookshelf2
|
refs/heads/master
|
/app/tests/test_api.py
|
from .basecase import TestCase
from urllib.parse import quote
import flask
from flask_login import current_user
import app
class TestApi(TestCase):
def __init__(self, *args, **kwargs):
super(TestApi, self).__init__(*args, **kwargs)
self.headers = None
self.token = None
def login(self, user='admin', pwd='admin'):
res = self.client.post('/login', data='{"username":"%s", "password":"%s"}' % (user, pwd),
content_type='application/json')
token = res.json.get('access_token')
self.assertTrue(token)
self.headers = {'Authorization': 'Bearer %s' % token}
self.token = token
def __getattr__(self, name):
name = name.upper()
if name in ('GET', 'POST', 'DELETE', 'PUT', 'OPTIONS'):
def req(*args, **kwargs):
kwargs['method'] = name
if 'headers' in kwargs:
kwargs['headers'].update(self.headers)
else:
kwargs['headers'] = self.headers
failure = kwargs.pop('failure', False)
not_json = kwargs.pop('not_json', False)
resp = self.client.open(*args, **kwargs)
if not failure:
self.assert200(resp)
if not not_json and not failure:
return resp.json
return resp
return req
raise AttributeError('Attribute %s not found' % name)
def test_api(self):
res = self.get('/api/ebooks', failure=True)
self.assert401(res)
self.login()
res = self.get('/api/ebooks')
self.assertTrue(len(res['items']) > 5)
self.assertEqual(res['page'], 1)
# current user is anonymous outside of request
self.assertFalse(current_user.is_authenticated)
for b in res['items']:
self.assertTrue(b['title'] and b['id'], 'Invalid ebook %s' % b)
res = self.get(
'/api/ebooks', query_string={'page': 1, 'page_size': 12, 'sort': 'title'})
self.assertEqual(res['page'], 1)
self.assertEqual(res['total'], 100)
self.assertEqual(res['page_size'], 12)
self.assertEqual(len(res['items']), 12)
self.assertEqual(
res['items'][0]['title'], 'Alenka v říši kvant - Alegorie kvantové fyziky')
first_book = res['items'][0]
res = self.get(
'/api/ebooks', query_string={'page': 9, 'page_size': 12, 'sort': '-title'})
self.assertEqual(res['page'], 9)
self.assertEqual(len(res['items']), 4)
self.assertEqual(res['total'], 100)
self.assertEqual(res['page_size'], 12)
self.assertEqual(
res['items'][-1]['title'], 'Alenka v říši kvant - Alegorie kvantové fyziky')
last_book = res['items'][-1]
self.assertEqual(first_book, last_book)
res = self.get(
'/api/ebooks', query_string={'page': 9, 'page_size': 12, 'sort': 'blba'}, failure=True)
self.assert400(res)
res = self.get(
'/api/ebooks', query_string={'page': 0, 'page_size': 12, 'sort': '-title'}, failure=True)
self.assert400(res)
res = self.get(
'/api/ebooks', query_string={'page': 1, 'page_size': -1, 'sort': '-title'}, failure=True)
self.assert400(res)
res = self.get(
'/api/ebooks', query_string={'page': 1, 'page_size': 101, 'sort': '-title'}, failure=True)
self.assert400(res)
res = self.get(
'/api/ebooks', query_string={'page': 10, 'page_size': 12, 'sort': 'title'}, failure=True)
self.assert404(res)
id = first_book['id']
res = self.get('/api/ebooks/%s' % id)
self.assertEqual(res['id'], id)
self.assertEqual(
res['title'], 'Alenka v říši kvant - Alegorie kvantové fyziky')
#------------
res = self.get(
'/api/authors', query_string={'page': 1, 'page_size': 50, 'sort': 'name'})
self.assertEqual(len(res['items']), 50)
self.assertEqual(res['total'], 102)
self.assertEqual(res['items'][0]['last_name'], 'Adornetto')
res = self.get(
'/api/series', query_string={'page': 2, 'page_size': 14, 'sort': 'title'})
self.assertEqual(res['total'], 28)
self.assertEqual(res['items'][-1]['title'], 'Zář')
res = self.get('/api/search/%s' % quote('Zápas boh'))
self.assertEqual(res['total'], 1)
self.assertEqual(res['items'][0]['title'], 'Podobni bohům')
res = self.get('/api/search/%s' % quote('prip'))
self.assertEqual(res['total'], 4)
res = self.get('/api/search/%s' % quote('henry dome'))
self.assertEqual(res['total'], 1)
self.assertEqual(res['items'][0]['title'], 'Roky v Bílém domě')
res = self.get('/api/ebooks/author/8015')
self.assertEqual(res['total'], 4)
self.assertEqual(len(res['items']), 4)
def test_api2(self):
#---------------
self.login('guest', 'guest')
res = self.get('/api/ebooks', failure=True)
self.assert401(res)
self.login('user', 'user')
res = self.get('/api/ebooks')
id = 62241
res = self.delete('/api/ebooks/%d' % id, failure=True)
self.assert401(res)
self.login('superuser', 'superuser')
res = self.delete('/api/ebooks/%d' % id)
res = self.get('/api/ebooks/%s' % id, failure=True)
print (res.json)
self.assert404(res)
res = self.get(
'/api/download/86060', query_string={'bearer_token': self.token}, not_json=True)
self.assertEqual(int(res.headers['Content-Length']), 3147900)
self.assertEqual(res.headers['Content-Type'], 'application/epub+zip')
self.assertEqual(len(res.data), 3147900)
res = self.post('/api/upload/check', data='{"mime_type":"application/pdf", "size":10000, "hash":null}',
content_type='application/json')
self.assertEqual(res['result'], 'ok')
# indexes
res = self.get('/api/series/index/a')
self.assertEqual(res['total'], 3)
res = self.get('/api/series/index/á')
self.assertEqual(res['total'], 3)
res = self.get('/api/authors/index/c')
self.assertEqual(res['total'], 4)
res = self.get('/api/authors/index/č')
self.assertEqual(res['total'], 4)
res = self.get('/api/ebooks/index/r')
self.assertEqual(res['total'], 1)
print(res)
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,154
|
lioenel/mybookshelf2
|
refs/heads/master
|
/settings.py
|
import os.path
_base_dir = os.path.dirname(__file__)
DB_NAME = 'ebooks'
DB_HOST = 'localhost'
DB_USER = 'ebooks'
DB_PASSWORD = 'ebooks'
SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}/{db}'.format(db=DB_NAME,
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD)
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = 'Pjk5EzGOcCOG5Rf1deqpZAvz17uUdZmWxJa3X/izSns'
MAX_CONTENT_LENGTH = 100 * 1024 * 1024
CACHE_CONTROL = 'max-age=20'
CACHE_EXPIRES = 20
# CORS
CORS_HOSTS = '*' # or list of hosts ['localhost']
CORS_PORTS = None # or (lower, upper) or []
CORS_SECURE = False # if cors is allowed only for https
UPLOAD_DIR = os.path.join(_base_dir, 'app/data/uploads')
BOOKS_BASE_DIR = os.path.join(_base_dir, 'app/data/books')
BOOKS_FILE_SCHEMA = "%(author)s/%(title)s/%(author)s - %(title)s"
BOOKS_FILE_SCHEMA_SERIE = "%(author)s/%(serie)s/%(serie)s %(serie_index)d - %(title)s/%(author)s - %(serie)s %(serie_index)d - %(title)s"
BOOKS_RECON_DIR = "/books/books_recon"
BOOKS_DIR_UMASK = 0 # umask for uploaded files and their directories - consider that it should be RW for both web server and console user
# Conversion related
BOOKS_CONVERTED_DIR = "/books/books_converted"
CONVERSION_FORMATS = ['epub', 'mobi', 'fb2']
IMAGE_MAGIC = '/usr/bin/convert'
class Testing:
DB_NAME = 'ebooks_test'
DB_HOST = 'localhost'
DB_USER = 'ebooks_test'
DB_PASSWORD = 'ebooks'
SQLALCHEMY_DATABASE_URI = 'postgresql://{user}:{password}@{host}/{db}'.format(db=DB_NAME,
host=DB_HOST,
user=DB_USER,
password=DB_PASSWORD)
TESTING = True
DEBUG = True
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
9,155
|
lioenel/mybookshelf2
|
refs/heads/master
|
/app/logic.py
|
from flask import abort, request, current_app, Response, jsonify
from sqlalchemy.sql import text, desc, func
from functools import wraps
import app.model as model
import app.schema as schema
from sqlalchemy.orm.exc import NoResultFound
from app.utils import remove_diacritics, file_hash
import os.path
import logging
import re
logger = logging.getLogger('logic')
def safe_int(v, for_=''):
if v is None or v == ' ':
return
try:
v = int(v)
if v <= 0:
abort(400, 'Not positive number %s' % for_)
return v
except ValueError:
abort(400, 'Invalid number for %s' % for_)
def preprocess_search_query(text):
tokens = text.split()
tokens = map(lambda t: re.sub('[:.;]', ' ', t, re.UNICODE).strip(), tokens)
return ' & '.join(['%s:*' % t for t in tokens])
def search_query(q, search):
# works only for pg backend
search = preprocess_search_query(search)
return q.filter(model.Ebook.full_text.match(search))\
.order_by(desc(func.ts_rank_cd(model.Ebook.full_text, func.to_tsquery(text("'custom'"), search))))
def filter_ebooks(q, filter):
return q.filter(func.unaccent(model.Ebook.title).ilike(func.unaccent(text("'%%%s%%'" % filter))))
def paginated(default_page_size=10, max_page_size=100, sortings=None):
def wrapper(fn):
@wraps(fn)
def inner(*args, **kwargs):
page_size = safe_int(
request.args.get('page_size'), 'page_size') or default_page_size
if page_size > max_page_size:
abort(400, 'Page size bigger then maximum')
kwargs['page_size'] = page_size
kwargs['page'] = safe_int(request.args.get('page'), 'page') or 1
sort_in = request.args.get('sort')
if sortings:
sort = sortings.get(sort_in)
if sort_in and not sort:
abort(400, 'Invalid sort key %s' % sort_in)
kwargs['sort'] = sortings.get(request.args.get('sort'))
else:
if sort_in:
abort(400, 'Sorting not supported')
return fn(*args, **kwargs)
return inner
return wrapper
def paginate(q, page, page_size, sort, serializer):
if sort:
q = q.order_by(*sort)
pager = q.paginate(page, page_size)
return {'page': pager.page,
'page_size': pager.per_page,
'total': pager.total,
'items': serializer.dump(pager.items).data}
def norm_file_name(source):
new_name_rel = norm_file_name_base(source.ebook)
for ch in [':', '*', '%', '|', '"', '<', '>', '?', '\\']:
new_name_rel = new_name_rel.replace(ch, '')
new_name_rel += '.' + source.format.extension
return new_name_rel
def norm_file_name_base(ebook):
config = current_app.config
if ebook.series and config.get('BOOKS_FILE_SCHEMA_SERIE'):
new_name_rel = config.get('BOOKS_FILE_SCHEMA_SERIE') % {'author': ebook.authors_str,
'title': ebook.title,
'serie': ebook.series.title,
'serie_index': ebook.series_index or 0}
# TODO: might need to spplit base part
else:
new_name_rel = config.get('BOOKS_FILE_SCHEMA') % {'author': ebook.authors_str,
'title': ebook.title}
new_name_rel = remove_diacritics(new_name_rel)
assert(len(new_name_rel) < 4096)
return new_name_rel
def stream_response(fname, mimetype, headers={}):
def stream_file(f):
buf_size = 8192
try:
while True:
data = f.read(buf_size)
if not data:
break
yield data
finally:
f.close()
try:
outfile = open(fname, 'rb')
except IOError as e:
logger.exception('File %s error %s', fname, e)
abort(404, 'File not found')
headers['Content-Length'] = os.stat(fname).st_size
response = Response(
stream_file(outfile), mimetype=mimetype, headers=headers)
return response
def download(id):
try:
source = model.Source.query.get(id)
except NoResultFound:
abort(404, 'Source not found')
fname = os.path.join(current_app.config['BOOKS_BASE_DIR'], source.location)
down_name = norm_file_name(source)
down_name = os.path.split(fname)[-1]
response = stream_response(fname, mimetype=source.format.mime_type,
headers={'Content-Disposition': 'attachment; filename="%s"' % down_name})
return response
def check_file(mime_type, size, hash):
if size > current_app.config['MAX_CONTENT_LENGTH']:
logger.warn('File too big %d (limit is %d)', size,
current_app.config['MAX_CONTENT_LENGTH'])
return {'error': 'file too big'}
t = model.Format.query.filter_by(mime_type=mime_type.lower()).all()
if not t:
logger.warn('Unsupported mime type %s', mime_type)
return {'error': 'unsupported file type'}
sources = model.Source.query.filter_by(size=size, hash=hash).all()
if sources:
logger.warn('File already exists - %s', sources[0])
return {'error': 'file already exists'}
def check_uploaded_file(mime_type, fname):
size = os.stat(fname).st_size
hash = file_hash(fname)
return check_file(mime_type, size, hash)
def _run_query(q):
return q.count(), q.limit(current_app.config.get('MAX_INDEX_SIZE', 100)).all()
def series_index(start):
q = model.Series.query
q = q.filter(func.unaccent(model.Series.title).ilike(
func.unaccent(start + '%'))).order_by(model.Series.title)
return _run_query(q)
def ebooks_index(start):
q = model.Ebook.query
q = q.filter(func.unaccent(model.Ebook.title).ilike(
func.unaccent(start + '%'))).order_by(model.Ebook.title)
return _run_query(q)
def authors_index(start):
q = model.Author.query
q = q.filter(func.unaccent(model.Author.last_name + ', ' + model.Author.first_name)
.ilike(func.unaccent(start + '%'))).order_by(model.Author.last_name, model.Author.first_name)
return _run_query(q)
|
{"/manage.py": ["/app/utils.py", "/app/schema.py"], "/app/api.py": ["/app/schema.py", "/app/logic.py", "/app/utils.py", "/app/access.py"], "/engine/tasks.py": ["/settings.py", "/app/utils.py", "/engine/dal.py"], "/app/tests/test_logic.py": ["/app/logic.py"], "/app/tests/test_schema.py": ["/app/schema.py"], "/engine/dal.py": ["/settings.py"], "/engine/tests/test_meta.py": ["/engine/dal.py", "/settings.py", "/engine/tasks.py"], "/app/minimal.py": ["/app/logic.py", "/app/access.py"], "/engine/backend.py": ["/engine/dal.py", "/app/utils.py", "/settings.py"], "/engine/dal2.py": ["/settings.py"], "/app/access.py": ["/app/utils.py"], "/engine/tests/test_dal.py": ["/engine/dal.py", "/settings.py"], "/engine/client.py": ["/app/utils.py"], "/app/logic.py": ["/app/schema.py", "/app/utils.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.