Пример #1
0
 def logout_player(self, avatar_id):
     """
     Register a player as logged out.
     """
     self.connection.runOperation(
         sql.build_update('player', dict(last_logout=sql.RAW('now()')),
                          dict(avatar_id=avatar_id)))
Пример #2
0
 def iterate_task(self, responder):
     """
     Check for waiting tasks using the given ampoule TransactionChild.
     
     Returns False if there's no task waiting
     Returns None if an exception occurs
     Returns True if it processes a task
     """
     next_task = self.connection.runQuery(
         """SELECT t.*
             FROM task t
             WHERE t.created + (t.delay * interval '1 second') < NOW()
               AND t.killed = 0
             ORDER BY t.created ASC
             LIMIT 1
         """)
     
     if not(next_task):
         return False
     
     try:
         responder.run_task(
             user_id        = next_task[0]['user_id'],
             task_id        = next_task[0]['id'],
         )
     except Exception as e:
         import traceback
         trace = traceback.format_exc()
         err = '%s: %s' % (e.__class__.__name__, str(e))
         self.connection.runOperation(sql.build_update('task', dict(killed=True, error=err, trace=trace), dict(id=next_task[0]['id'])))
         return None
     else:
         self.connection.runOperation(sql.build_delete('task', dict(id=next_task[0]['id'])))
         return True
Пример #3
0
    def set_player(self,
                   object_id,
                   player=None,
                   wizard=None,
                   passwd=None,
                   test_salt=None,
                   **attribs):
        """
        Edit the player attributes of an object.
        """
        crypt = None
        if (passwd is not None):
            crypt = attribs['crypt'] = hash_password(passwd, salt=test_salt)
        elif (player is False):
            crypt = attribs['crypt'] = '!'

        attribs['enabled'] = player is True
        attribs['wizard'] = wizard is True

        if (self.is_player(object_id)):
            if not (attribs):
                return
            self.connection.runOperation(
                sql.build_update('player', attribs, dict(avatar_id=object_id)))
        else:
            self.connection.runOperation(
                sql.build_insert('player', dict(avatar_id=object_id,
                                                **attribs)))
Пример #4
0
 def login_player(self, avatar_id, session_id):
     """
     Register a player as logged in.
     """
     self.connection.runOperation(
         sql.build_update(
             'player',
             dict(session_id=session_id, last_login=sql.RAW('now()')),
             dict(avatar_id=avatar_id)))
Пример #5
0
    def save(self, obj):
        """
        Save the provided model back into the database.
        """
        obj_type = type(obj).__name__.lower()
        obj_id = obj.get_id()

        if (obj_type == 'object'):
            attribs = dict(
                name=obj._name,
                unique_name=('f', 't')[obj._unique_name],
                owner_id=obj._owner_id,
                location_id=obj._location_id,
            )
        elif (obj_type == 'verb'):
            attribs = dict(
                code=obj._code,
                filename=obj._filename,
                owner_id=obj._owner_id,
                origin_id=obj._origin_id,
                ability=('f', 't')[obj._ability],
                method=('f', 't')[obj._method],
            )
        elif (obj_type == 'property'):

            def check(v):
                if (v is None):
                    return False
                elif (v is ""):
                    return False
                return True

            attribs = dict(
                name=obj._name,
                value=ason.dumps(obj._value)
                if check(obj._value) else obj._value,
                owner_id=obj._owner_id,
                origin_id=obj._origin_id,
                type=obj._type,
            )
        else:
            raise RuntimeError(
                "Don't know how to save an object of type '%s'" % obj_type)

        if (obj_id):
            self.connection.runOperation(
                sql.build_update(obj_type, attribs, dict(id=obj_id)))
        else:
            attribs['id'] = sql.RAW('DEFAULT')
            result = self.connection.runQuery(
                sql.build_insert(obj_type, attribs) + ' RETURNING id')
            obj.set_id(result[0]['id'])

        object_key = '%s-%s' % (obj_type, obj.get_id())
        if (object_key not in self.cache):
            self.cache[object_key] = obj
Пример #6
0
    def update_access(self, access_id, rule, access, accessor, permission,
                      weight, subject, deleted):
        """
        Modify an access rule.
        """
        record = {} if not access_id else self.connection.runQuery(
            sql.interp(
                """SELECT a.*, p.name AS permission
                FROM access a
                    INNER JOIN permission p ON a.permission_id = p.id
                WHERE a.id = %s
            """, access_id))
        if (record):
            record = record[0]
        else:
            record = {}

        if (deleted):
            self.connection.runOperation(
                sql.build_delete('access', id=access_id))
            return

        record['rule'] = rule
        record['type'] = access
        record['weight'] = weight

        record.pop('group', '')
        if (access == 'group'):
            record['"group"'] = accessor
            record['accessor_id'] = None
        else:
            record['"group"'] = None
            record['accessor_id'] = accessor.get_id()

        if (record.pop('permission', '') != permission):
            if (permission not in self.permission_list):
                raise ValueError("Unknown permission: %s" % permission)
            record['permission_id'] = self.permission_list[permission]

        if (subject.get_type() == 'object'):
            record['object_id'] = subject.get_id()
        elif (subject.get_type() == 'verb'):
            record['verb_id'] = subject.get_id()
        elif (subject.get_type() == 'property'):
            record['property_id'] = subject.get_id()

        if (access_id):
            self.connection.runOperation(
                sql.build_update('access', record, dict(id=access_id)))
        else:
            self.connection.runOperation(sql.build_insert('access', **record))
Пример #7
0
 def save(self, obj):
     """
     Save the provided model back into the database.
     """
     obj_type = type(obj).__name__.lower()
     obj_id = obj.get_id()
     
     if(obj_type == 'object'):
         attribs = dict(
             name        = obj._name,
             unique_name = ('f', 't')[obj._unique_name],
             owner_id    = obj._owner_id,
             location_id = obj._location_id,
         )
     elif(obj_type == 'verb'):
         attribs = dict(
             code        = obj._code,
             filename    = obj._filename,
             owner_id    = obj._owner_id,
             origin_id    = obj._origin_id,
             ability        = ('f', 't')[obj._ability],
             method        = ('f', 't')[obj._method],
         )
     elif(obj_type == 'property'):
         def check(v):
             if(v is None):
                 return False
             elif(v is ""):
                 return False
             return True
         
         attribs = dict(
             name        = obj._name,
             value        = json.dumps(obj._value) if check(obj._value) else obj._value,
             owner_id    = obj._owner_id,
             origin_id    = obj._origin_id,
             type        = obj._type,
         )
     else:
         raise RuntimeError("Don't know how to save an object of type '%s'" % obj_type)
     
     if(obj_id):
         self.pool.runOperation(sql.build_update(obj_type, attribs, dict(id=obj_id)))
     else:
         attribs['id'] = sql.RAW('DEFAULT')
         result = self.pool.runQuery(sql.build_insert(obj_type, attribs) + ' RETURNING id')
         obj.set_id(result[0]['id'])
     
     object_key = '%s-%s' % (obj_type, obj.get_id())
     if(object_key not in self.cache):
         self.cache[object_key] = obj
Пример #8
0
 def save(self, obj):
     """
     Save the provided model back into the database.
     """
     obj_type = type(obj).__name__.lower()
     obj_id = obj.get_id()
     
     if(obj_type == 'object'):
         attribs = dict(
             name        = obj._name,
             unique_name = str(int(obj._unique_name)),
             owner_id    = obj._owner_id,
             location_id = obj._location_id,
         )
     elif(obj_type == 'verb'):
         attribs = dict(
             code        = obj._code,
             filename    = obj._filename,
             owner_id    = obj._owner_id,
             origin_id    = obj._origin_id,
             ability        = str(int(obj._ability)),
             method        = str(int(obj._method)),
         )
     elif(obj_type == 'property'):
         def check(v):
             if(v is None):
                 return False
             elif(v is ""):
                 return False
             return True
         
         attribs = dict(
             name        = obj._name,
             value        = ason.dumps(obj._value) if check(obj._value) else obj._value,
             owner_id    = obj._owner_id,
             origin_id    = obj._origin_id,
             type        = obj._type,
         )
     else:
         raise RuntimeError("Don't know how to save an object of type '%s'" % obj_type)
     
     if(obj_id):
         self.connection.runOperation(sql.build_update(obj_type, attribs, dict(id=obj_id)))
     else:
         self.connection.runOperation(sql.build_insert(obj_type, attribs))
         obj.set_id(self.connection.getLastInsertId(obj_type))
     
     object_key = '%s-%s' % (obj_type, obj.get_id())
     if(object_key not in self.cache):
         self.cache[object_key] = obj
Пример #9
0
 def update_access(self, access_id, rule, access, accessor, permission, weight, subject, deleted):
     """
     Modify an access rule.
     """
     record = {} if not access_id else self.connection.runQuery(sql.interp(
         """SELECT a.*, p.name AS permission
             FROM access a
                 INNER JOIN permission p ON a.permission_id = p.id
             WHERE a.id = %s
         """, access_id))
     if(record):
         record = record[0]
     else:
         record = {}
     
     if(deleted):
         self.connection.runOperation(sql.build_delete('access', id=access_id))
         return
     
     record['rule'] = rule
     record['type'] = access
     record['weight'] = weight
     
     record.pop('group', '')
     if(access == 'group'):
         record['"group"'] = accessor
         record['accessor_id'] = None
     else:
         record['"group"'] = None
         record['accessor_id'] = accessor.get_id()
     
     if(record.pop('permission', '') != permission):
         if(permission not in self.permission_list):
             raise ValueError("Unknown permission: %s" % permission)
         record['permission_id'] = self.permission_list[permission]
     
     if(subject.get_type() == 'object'):
         record['object_id'] = subject.get_id()
     elif(subject.get_type() == 'verb'):
         record['verb_id'] = subject.get_id()
     elif(subject.get_type() == 'property'):
         record['property_id'] = subject.get_id()
     
     if(access_id):
         self.connection.runOperation(sql.build_update('access', record, dict(id=access_id)))
     else:
         self.connection.runOperation(sql.build_insert('access', **record))
Пример #10
0
 def set_player(self, object_id, player=None, wizard=None, passwd=None, test_salt=None, **attribs):
     """
     Edit the player attributes of an object.
     """
     crypt = None
     if(passwd is not None):
         crypt = attribs['crypt'] = hash_password(passwd, salt=test_salt)
     elif(player is False):
         crypt = attribs['crypt'] = '!'
     
     attribs['enabled'] = str(int(player is True))
     attribs['wizard'] = str(int(wizard is True))
     
     if(self.is_player(object_id)):
         if not(attribs):
             return
         self.connection.runOperation(sql.build_update('player', attribs, dict(avatar_id=object_id)))
     else:
         self.connection.runOperation(sql.build_insert('player', dict(avatar_id=object_id, **attribs)))
Пример #11
0
    def iterate_task(self, responder):
        """
        Check for waiting tasks using the given ampoule TransactionChild.
        
        Returns False if there's no task waiting
        Returns None if an exception occurs
        Returns True if it processes a task
        """
        next_task = self.connection.runQuery("""SELECT t.*
                FROM task t
                WHERE t.created + (t.delay * interval '1 second') < NOW()
                  AND t.killed = 'f'
                ORDER BY t.created ASC
                LIMIT 1
            """)

        if not (next_task):
            return False

        try:
            responder.run_task(
                user_id=next_task[0]['user_id'],
                task_id=next_task[0]['id'],
            )
        except Exception as e:
            import traceback
            trace = traceback.format_exc()
            err = '%s: %s' % (e.__class__.__name__, str(e))
            self.connection.runOperation(
                sql.build_update('task',
                                 dict(killed=True, error=err, trace=trace),
                                 dict(id=next_task[0]['id'])))
            return None
        else:
            self.connection.runOperation(
                sql.build_delete('task', dict(id=next_task[0]['id'])))
            return True
Пример #12
0
 def logout_player(self, avatar_id):
     """
     Register a player as logged out.
     """
     self.connection.runOperation(sql.build_update('player', dict(last_logout=sql.RAW('now()')), dict(avatar_id=avatar_id)))
Пример #13
0
 def login_player(self, avatar_id, session_id):
     """
     Register a player as logged in.
     """
     self.connection.runOperation(sql.build_update('player', dict(session_id=session_id, last_login=sql.RAW('now()')), dict(avatar_id=avatar_id)))