Esempio n. 1
0
import time
from base64 import b64decode

from lampost.db.exceptions import DataError
from lampost.di.app import on_app_start
from lampost.di.resource import Injected, module_inject
from lampost.server.domain import User
from lampost.util.encrypt import make_hash, check_password
from lampost.util.lputil import ClientError

log = Injected('log')
perm = Injected('perm')
db = Injected('datastore')
ev = Injected('dispatcher')
edit_update = Injected('edit_update_service')
module_inject(__name__)


@on_app_start
def _start():
    ev.register("user_connect", _user_connect)
    ev.register("player_connect", _player_connect)


def validate_user(user_name, password):
    user = find_user(user_name)
    if not user:
        raise ClientError()
    validate_password(user, password)
    return user
Esempio n. 2
0
from lampost.di.app import on_app_start
from lampost.di.config import config_value, on_config_change
from lampost.di.resource import Injected, module_inject
from lampost.util.lputil import PermError

db = Injected('datastore')
module_inject(__name__)

system_accounts = []
imm_levels = {}


@on_app_start(priority=500)
@on_config_change
def _init():
    global imm_levels
    global _level_to_name
    global immortals
    global system_accounts
    imm_levels = config_value('imm_levels')
    system_accounts = config_value('system_accounts')
    _level_to_name = {level: name for name, level in imm_levels.items()}
    system_level = config_value('system_level')
    immortals = db.get_all_hash('immortals')
    immortals.update({account: system_level for account in system_accounts})


def perm_name(num_level):
    return _level_to_name.get(num_level, 'player')

Esempio n. 3
0
from lampost.di.resource import Injected, module_inject
from lampost.meta.auto import AutoField
from lampost.meta.core import CoreMeta
from lampost.util.classes import call_mro

log = Injected('log')
ev = Injected('dispatcher')
module_inject(__name__)


class Attachable(metaclass=CoreMeta):
    attached = AutoField(False)

    def attach(self):
        if not self.attached:
            self.attached = True
            call_mro(self, '_on_attach')
        return self

    def detach(self):
        if self.attached:
            ev.detach_events(self)
            call_mro(self, '_on_detach')
            self.attached = False
        else:
            log.warn("Detaching already detached obj: {}", self)
Esempio n. 4
0
import sys
import inspect

from collections import namedtuple
from datetime import datetime

from tornado.websocket import WebSocketHandler

from lampost.di.app import on_app_start
from lampost.di.resource import Injected, module_inject
from lampost.util.lputil import ClientError

log = Injected('log')
perm = Injected('perm')
ev = Injected('dispatcher')
json_decode = Injected('json_decode')
json_encode = Injected('json_encode')
module_inject(__name__)

_routes = {}
_route_modules = []


@on_app_start(priority=2000)
def _add_routes():
    for module_name, root_path in _route_modules:
        module = sys.modules[module_name]
        root_path = root_path or module_name.split('.')[-1]
        for name, prop in module.__dict__.items():
            if not name.startswith('_') and hasattr(
                    prop, '__call__') and getattr(prop,
Esempio n. 5
0
import time
from datetime import datetime, timedelta
from os import urandom
from base64 import b64encode

from lampost.di.app import on_app_start
from lampost.di.resource import Injected, module_inject
from lampost.di.config import on_config_change, config_value
from lampost.event.zone import Attachable
from lampost.server.link import link_route
from lampost.util.lputil import ClientError

log = Injected('log')
ev = Injected('dispatcher')
um = Injected('user_manager')
json_encode = Injected('json_encode')
module_inject(__name__)

_session_map = {}
_player_info_map = {}
_player_session_map = {}
_link_status_reg = None
_broadcast_reg = None
_link_dead_prune = 0
_link_dead_interval = 0


@on_app_start
def _on_app_start():
    ev.register('player_logout', _player_logout)
    _config()
Esempio n. 6
0
from threading import local

from lampost.di.resource import Injected, module_inject
from lampost.meta.auto import AutoField, TemplateField
from lampost.db.registry import get_dbo_class

log = Injected('log')
db = Injected('datastore')
module_inject(__name__)

# This is used to collect child references while calculating save values, rather than attempting to pass this
# collection recursively
save_value_refs = local()


class DBOField(AutoField):
    def __init__(self, default=None, dbo_class_id=None, required=False):
        super().__init__(default)
        self.required = required
        self.dbo_class_id = dbo_class_id

    def _meta_init(self, field):
        self.field = field
        self._hydrate_func = get_hydrate_func(load_any, self.default,
                                              self.dbo_class_id)
        self.dto_value = value_transform(to_dto_repr,
                                         self.default,
                                         field,
                                         self.dbo_class_id,
                                         for_json=True)
        self.cmp_value = value_transform(to_save_repr, self.default, field,
Esempio n. 7
0
from lampost.di.app import on_app_start
from lampost.di.resource import Injected, module_inject
from lampost.di.config import on_config_change, config_value

ev = Injected('dispatcher')
module_inject(__name__)

client_displays = {}


@on_app_start
def _start():
    ev.register('session_connect', set_displays)
    _set_displays()


@on_config_change
def _set_displays():
    client_displays.clear()
    for display in config_value('default_displays'):
        client_displays[display['name']] = display['value']


def set_displays(session):
    session.append({'client_config': {'default_displays': client_displays}})

Esempio n. 8
0
import inspect

from lampost.server.link import link_route
from lampost.di.resource import Injected, module_inject

perm = Injected('perm')
module_inject(__name__)

admin_ops = {}


def admin_op(func):
    a_spec = inspect.getargspec(func)

    if a_spec.defaults:
        params = [''] * (len(a_spec.args) - len(a_spec.defaults)) + list(
            a_spec.defaults)
    else:
        params = [''] * len(a_spec.args)

    admin_ops[func.__name__] = {
        'func': func,
        'dto': {
            'name': func.__name__,
            'args': a_spec.args,
            'params': params
        }
    }
    return func

Esempio n. 9
0
import time

from collections import deque
from weakref import WeakValueDictionary

from redis import ConnectionPool
from redis.client import StrictRedis

from lampost.di.resource import Injected, module_inject
from lampost.db.registry import get_dbo_class, get_mixed_type
from lampost.db.exceptions import ObjectExistsError, NonUniqueError

log = Injected('log')
json_encode = Injected('json_encode')
json_decode = Injected('json_decode')
module_inject(__name__)


class RedisStore:
    def __init__(self, db_host, db_port, db_num, db_pw):
        self.pool = ConnectionPool(max_connections=2,
                                   db=db_num,
                                   host=db_host,
                                   port=db_port,
                                   password=db_pw,
                                   decode_responses=True)
        self.redis = StrictRedis(connection_pool=self.pool)
        self.redis.ping()
        self._object_map = WeakValueDictionary()

    def create_object(self, dbo_class, dbo_dict, update_timestamp=True):
Esempio n. 10
0
from lampost.di.app import on_app_start
from lampost.di.resource import Injected, module_inject, get_resource
from lampost.server.link import link_route

log = Injected('log')
sm = Injected('session_manager')
ev = Injected('dispatcher')
perm = Injected('perm')
module_inject(__name__)


@link_route('register_service')
def register_service(session, service_id, data=None, **_):
    client_service = get_resource(service_id)
    if client_service:
        client_service.register(session, data)
    else:
        log.warn("Attempting registration for missing service {}", service_id)


@link_route('unregister_service')
def unregister_service(session, service_id, **_):
    get_resource(service_id).unregister(session)


class ClientService():
    def __init__(self):
        self.sessions = set()
        on_app_start(self._start)

    def _start(self):
Esempio n. 11
0
from lampost.di.resource import Injected, module_inject
from lampost.gameops.target import target_gen

sm = Injected('session_manager')
um = Injected('user_manager')
db = Injected('datastore')
module_inject(__name__)


@target_gen
def player_online(key_type, target_key, entity, *_):
    if key_type == 'primary':
        session = sm.player_session(target_key)
        if session and session.player != entity:
            yield session.player


player_online.absent_msg = "Player {target} is not logged in."


@target_gen
def player_db(key_type, target_key, entity, *_):
    if key_type == 'primary':
        target_id = um.name_to_id(target_key)
        player = db.load_object(target_id, 'player')
        if player and player != entity:
            yield player


player_db.absent_msg = "Player {target} does not exist"
Esempio n. 12
0
from lampost.di.app import on_app_start
from lampost.di.resource import Injected, module_inject
from lampost.gameops.action import ActionError
from lampost.util.lputil import timestamp

log = Injected('log')
db = Injected('datastore')
ev = Injected('dispatcher')
sm = Injected('session_manager')
um = Injected('user_manager')
module_inject(__name__)


@on_app_start
def _start():
    ev.register("player_deleted", _remove_player_messages)
    ev.register("player_connect", _player_connect)
    ev.register("player_message", add_message)


def get_messages(player_id):
    return db.get_all_db_hash(_message_key(player_id))


def add_message(msg_type, content, player_id, source_id=None):
    msg_id = db.db_counter("message_id")
    message = {'msg_type': msg_type, 'msg_id': msg_id, 'content': content, 'source': um.id_to_name(source_id)}
    timestamp(message)
    db.set_db_hash(_message_key(player_id), msg_id, message)
    try:
        sm.player_session(player_id).append({'new_message': message})
Esempio n. 13
0
from tornado.httpserver import HTTPServer
from tornado.web import Application, URLSpec

from lampost.di.resource import Injected, module_inject

log = Injected('log')
module_inject(__name__)

service_root = '/'

_handlers = []


def add_route(url_regex, handler, **kwargs):
    add_raw_route(service_root + url_regex, handler, **kwargs)


def add_raw_route(url_regex, handler, **kwargs):
    _handlers.append(URLSpec(url_regex, handler, kwargs))


def add_routes(routes):
    for route in routes:
        try:
            add_route(route.url_regex, route.handler, **route.init_args)
        except AttributeError:
            add_route(*route)


def start_service(port, interface):
    application = Application(_handlers, websocket_ping_interval=30)