コード例 #1
0
    def test08_mainTests_emptyQueue(self):
        """test08_mainTests_emptyQueue

        This test creates a dummy PokerLock.__init__() so that a MockQueue
        can be used that force-raises a Queue.Empty() exception, which is
        caught by the running loop in the lock and ends it."""
        import Queue
        import threading
        from pokernetwork.pokerlock import PokerLock
        from pokernetwork import log as network_log

        class MockQueue:
            def __init__(qSelf):
                qSelf.qSizeCallCount = 0
                qSelf.getCallCount = 0

            def qsize(qSelf):
                qSelf.qSizeCallCount += 1
                return 1

            def get(qSelf, timeout=1):
                qSelf.getCallCount += 1
                raise Queue.Empty("MOCK")

            def empty(qSelf):
                return False

            def put(qSelf, val):
                pass

        myMockQueue = MockQueue()
        log = network_log.getChild('pokerlock')

        class MockInitLock(PokerLock):
            def __init__(self, parameters):
                self.log = log.getChild(self.__class__.__name__)
                self.q = myMockQueue
                self.lock = threading.Lock()
                self.db = None
                self.running = True
                self.connect(parameters)
                threading.Thread.__init__(self, target=self.main)

        log_history.reset()()
        mockLocker = MockInitLock(self.parameters)
        mockLocker.start()
        mockLocker.close()
        self.failUnless(log_history.search("timeout"),
                        "output does not contain 'timeout'")
        self.failUnless(log_history.search("loop"),
                        "output does not contain 'loop'")
        self.failUnless(myMockQueue.qSizeCallCount > 0,
                        "MockQueue.qSize() should be called at least once.")
        self.failUnless(myMockQueue.getCallCount > 0,
                        "MockQueue.get() should be called at least once.")
コード例 #2
0
    def test08_mainTests_emptyQueue(self):
        """test08_mainTests_emptyQueue

        This test creates a dummy PokerLock.__init__() so that a MockQueue
        can be used that force-raises a Queue.Empty() exception, which is
        caught by the running loop in the lock and ends it."""
        import Queue
        import threading
        from pokernetwork.pokerlock import PokerLock
        from pokernetwork import log as network_log
        
        class  MockQueue:
            def __init__(qSelf):
                qSelf.qSizeCallCount = 0
                qSelf.getCallCount = 0
            def qsize(qSelf):
                qSelf.qSizeCallCount += 1
                return 1
            def get(qSelf, timeout = 1):
                qSelf.getCallCount += 1
                raise Queue.Empty("MOCK")
            def empty(qSelf):
                return False
            def put(qSelf, val):
                pass
            
        myMockQueue = MockQueue()
        log = network_log.getChild('pokerlock')
        
        class MockInitLock(PokerLock):
            def __init__(self, parameters):
                self.log = log.getChild(self.__class__.__name__)
                self.q = myMockQueue
                self.lock = threading.Lock()
                self.db = None
                self.running = True
                self.connect(parameters)
                threading.Thread.__init__(self, target = self.main)

        log_history.reset()()
        mockLocker = MockInitLock(self.parameters)
        mockLocker.start()
        mockLocker.close()
        self.failUnless(log_history.search("timeout"),
                          "output does not contain 'timeout'")
        self.failUnless(log_history.search("loop"),
                          "output does not contain 'loop'")
        self.failUnless(myMockQueue.qSizeCallCount > 0,
                        "MockQueue.qSize() should be called at least once.")
        self.failUnless(myMockQueue.getCallCount > 0,
                        "MockQueue.get() should be called at least once.")
コード例 #3
0
ファイル: pokerauth.py プロジェクト: Usr-X/poker-network
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#  Johan Euphrosine <*****@*****.**>
#  Henry Precheur <*****@*****.**> (2004)
#  Cedric Pinson <*****@*****.**> (2004-2006)

from twisted.python.runtime import seconds
from pokernetwork.user import User
from pokernetwork.packets import PACKET_LOGIN, PACKET_AUTH
from pokernetwork import log as network_log
log = network_log.getChild("pokerauth")

class PokerAuth:

    def __init__(self, db, memcache, settings):
        self.log = log.getChild(self.__class__.__name__)
        self.db = db
        self.memcache = memcache
        self.type2auth = {}
        self.auto_create_account = settings.headerGet("/server/@auto_create_account") != 'no'

    def SetLevel(self, type, level):
        self.type2auth[type] = level

    def GetLevel(self, type):
        return type in self.type2auth and self.type2auth[type]
コード例 #4
0
ファイル: proxyfilter.py プロジェクト: Usr-X/poker-network
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#

from twisted.internet import defer, protocol, reactor, error
from twisted.web import http

from pokernetwork import log as network_log
log = network_log.getChild('proxyfilter')

local_reactor = reactor

class ProxyClient(http.HTTPClient):
    """
    Used by ProxyClientFactory to implement a simple web proxy.
    """

    def __init__(self, command, rest, version, headers, data, father):
        self.father = father
        self.command = command
        self.rest = rest
        if "proxy-connection" in headers:
            del headers["proxy-connection"]
        headers["connection"] = "close"
コード例 #5
0
ファイル: server.py プロジェクト: Usr-X/poker-network
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#  Henry Precheur <*****@*****.**> (2004)
#
#
import sys
from twisted.internet import reactor, protocol, defer

from pokernetwork import log as network_log
log = network_log.getChild('server')

from pokernetwork.protocol import UGAMEProtocol
from pokernetwork.packets import PacketError

class PokerServerProtocol(UGAMEProtocol):
    """UGAMEServerProtocol"""

    def __init__(self):
        self.log = log.getChild(self.__class__.__name__)
        self._ping_timer = None
        self.bufferized_packets = []
        self.avatar = None
        UGAMEProtocol.__init__(self)
        self._ping_delay = 10
コード例 #6
0
ファイル: pokerlock.py プロジェクト: Usr-X/poker-network
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#

from twisted.internet import reactor, defer
from twisted.python import failure
import threading
import thread
import MySQLdb
import Queue
import time

from pokernetwork import log as network_log
log = network_log.getChild('pokerlock')

class PokerLock(threading.Thread):

    TIMED_OUT = 1
    DEAD = 2
    RELEASE = 3

    acquire_timeout = 60
    queue_timeout = 2 * 60
    acquire_sleep = 0.1
    
    def __init__(self, parameters):
        self.log = log.getChild(self.__class__.__name__)
        self.q = Queue.Queue()
        self.lock = threading.Lock()
コード例 #7
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#  Johan Euphrosine <*****@*****.**>
#  Henry Precheur <*****@*****.**> (2004)
#  Cedric Pinson <*****@*****.**> (2004-2006)

from pokernetwork.user import User
from pokernetwork import log as network_log
log = network_log.getChild("pokerauthnopassword")
    
class PokerAuth:

    def __init__(self, db, settings):
        self.log = log.getChild(self.__class__.__name__)
        self.db = db
        self.type2auth = {}
        self.auto_create_account = settings.headerGet("/server/@auto_create_account") != 'no'

    def SetLevel(self, type, level):
        self.type2auth[type] = level

    def GetLevel(self, type):
        return type in self.type2auth and self.type2auth[type]
コード例 #8
0
ファイル: protocol.py プロジェクト: Usr-X/poker-network
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#
# 
from twisted.internet import reactor, protocol
from twisted.python.runtime import seconds

from pokernetwork.packets import Packet, PacketFactory
from pokernetwork import protocol_number
from pokernetwork.version import Version
from pokernetwork import log as network_log
log = network_log.getChild('protocol')

protocol_version = Version(protocol_number)

PROTOCOL_MAJOR = "%03d" % protocol_version.major()
PROTOCOL_MINOR = "%d%02d" % ( protocol_version.medium(), protocol_version.minor() )

class Queue:
    def __init__(self):
        self.delay = 0
        self.packets = []
        
class UGAMEProtocol(protocol.Protocol):
    """UGAMEProtocol"""

    _stats_read = 0
コード例 #9
0
ファイル: currencyclient.py プロジェクト: Usr-X/poker-network
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#
from types import *
from twisted.web import client
from twisted.internet import defer, reactor

from pokernetwork import log as network_log
log = network_log.getChild('currencyclient')

class RealCurrencyClient:

    def __init__(self):
        self.log = log.getChild(self.__class__.__name__)
        self.getPage = client.getPage

    def request(self, *args, **kwargs):
        base = kwargs['url']
        if "?" in base:
            base += '&'
        else:
            base += '?'
            
        args = [ base + "command=" + kwargs.get('command', 'get_note') ]
コード例 #10
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#
import libxml2

from pokerengine import pokerengineconfig
from pokernetwork.version import version
from pokernetwork import log as network_log
log = network_log.getChild('pokernetworkconfig')

class Config(pokerengineconfig.Config):

    upgrades_repository = None

    def __init__(self, *args, **kwargs):
        pokerengineconfig.Config.__init__(self, *args, **kwargs)
        self.log = log.getChild(self.__class__.__name__)
        self.version = version
        self.notify_updates = []

    def loadFromString(self, string):
        self.path = "<string>"
        self.doc = libxml2.parseMemory(string, len(string))
        self.header = self.doc.xpathNewContext()
コード例 #11
0
ファイル: packets.py プロジェクト: Usr-X/poker-network
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#  Henry Precheur <*****@*****.**> (2004)
#
from struct import pack, unpack, calcsize
from copy import deepcopy
import simplejson

from pokernetwork import log as network_log
log = network_log.getChild('packets')

PacketFactory = {}
PacketNames = {}

PACKET_NONE = 0
PacketNames[PACKET_NONE] = "NONE"

class Packet:
    """

     Packet base class
    
    """
    JSON = simplejson.JSONEncoder()
    
コード例 #12
0
# the GNU Affero General Public License (AGPL) as published by the Free
# Software Foundation (FSF), either version 3 of the License, or (at your
# option) any later version of the AGPL published by the FSF.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
from pokerengine.pokergame import PokerGameClient
from pokernetwork import log as network_log
log = network_log.getChild('pokergameclient')

class PokerNetworkGameClient(PokerGameClient):
    SERIAL_IN_POSITION = 0
    POSITION_OBSOLETE = 1

    def __init__(self, url, dirs):
        PokerGameClient.__init__(self, url, dirs)
        self.log = log.getChild(self.__class__.__name__)
        self.level_skin = ""
        self.currency_serial = 0
        self.history_index = 0
        self.position_info = [ 0, 0 ]

    def reset(self):
        PokerGameClient.reset(self)
コード例 #13
0
ファイル: lockcheck.py プロジェクト: Usr-X/poker-network
from twisted.internet import reactor

from pokernetwork import log as network_log
log = network_log.getChild('lockcheck')

class LockCheck(object):

    def __init__(self, timeout, callback, cb_args=()):
        self.log = log.getChild(self.__class__.__name__)
        self._timeout = timeout
        self._callback = callback
        self._callback_args = cb_args
        self._timer = None

    def start(self):
        try:
            if self._timer is None or not self._timer.active():
                self._timer = reactor.callLater(self._timeout, self._callback, *self._callback_args)
            else:
                self._timer.reset(self._timeout)
        except:
            self.log.error("Exception on start()", exc_info=1)

    def stop(self):
        try:
            if self._timer is None:
                return
            if self._timer.active():
                self._timer.cancel()
            self._timer = None
        except:
コード例 #14
0
ファイル: client.py プロジェクト: Usr-X/poker-network
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#
#
from twisted.internet import reactor, protocol, error, defer

from pokernetwork.packets import *
from pokernetwork.protocol import UGAMEProtocol
from pokernetwork.user import User
from pokernetwork import log as network_log

log = network_log.getChild("client")


class UGAMEClientProtocol(UGAMEProtocol):
    """ """

    def __init__(self):
        self.log = log.getChild(
            self.__class__.__name__, refs=[("User", self, lambda x: x.user.serial if x.user.serial > 0 else None)]
        )
        self._ping_timer = None
        self.user = User()
        self.bufferized_packets = []
        UGAMEProtocol.__init__(self)
        self._ping_delay = 5
        self.connection_lost_deferred = defer.Deferred()
コード例 #15
0
ファイル: pokerbot.py プロジェクト: Usr-X/poker-network
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Johan Euphrosine <*****@*****.**>
#  Loic Dachary <*****@*****.**>
#  Henry Precheur <*****@*****.**> (2004)
#
import sys
sys.path.insert(0, "..")

import platform
from os.path import exists
from random import randint

from pokernetwork import log as network_log
log = network_log.getChild('pokerbot')

from twisted.application import internet, service, app

if platform.system() != "Windows":
    if 'twisted.internet.reactor' not in sys.modules:
        from twisted.internet import epollreactor
        log.debug("installing epoll reactor")
        epollreactor.install()
    else:
        log.debug("reactor already installed")

from twisted.internet import reactor
from twisted.python import components
from twisted.persisted import sob
from twisted.internet import error
コード例 #16
0
ファイル: pokersite.py プロジェクト: Usr-X/poker-network
import time
import base64

from traceback import format_exc

from twisted.web import server, resource, util, http
from twisted.internet import defer
from twisted.python import log
from twisted.python.runtime import seconds

from pokernetwork.pokerpackets import *
from pokernetwork.packets import *
PacketFactoryWithNames = dict((packet_class.__name__,packet_class) for packet_class in PacketFactory.itervalues())

from pokernetwork import log as network_log
log = network_log.getChild('site')

# Disabled Unicode encoding. It is not required anymore since it is only used
# for the (dealer) chat. We measured a higher sit out count with Unicode
# activated FIXME a better solution would be to refactor the engine to only
# encode chat packets than to disable it altogether
def fromutf8(tree, encoding = 'ISO-8859-1'):
    return tree

def toutf8(tree, encoding = 'ISO-8859-1'):
    return tree

def __walk(tree, convert):
    if type(tree) is tuple or type(tree) is list:
        result = map(lambda x: __walk(x, convert), tree)
        if type(tree) is tuple:
コード例 #17
0
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#

from twisted.internet import defer, protocol, reactor, error
from twisted.internet.defer import CancelledError
from twisted.web import http, client
from twisted.python.util import InsensitiveDict
from twisted.python.runtime import seconds

from pokernetwork.pokerpackets import *
from pokernetwork import pokersite
from pokernetwork import log as network_log
log = network_log.getChild('pokerrestclient')


class RestClientFactory(protocol.ClientFactory):

    protocol = client.HTTPPageGetter
    noisy = False
    
    def __init__(self, host, port, path, data, timeout = 60):
        self.log = log.getChild('ClientFactory')
        self.timeout = timeout
        self.agent = "RestClient"
        self.headers = InsensitiveDict()
        self.headers.setdefault('Content-Length', len(data))
        self.headers.setdefault("connection", "close")
        self.method = 'POST'
コード例 #18
0
ファイル: pokerdatabase.py プロジェクト: Usr-X/poker-network
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#
import os
from os.path import exists
import MySQLdb
from MySQLdb.cursors import DictCursor

from pokernetwork import log as network_log
log = network_log.getChild('pokerdatabase')

class ExceptionDatabaseTooOld(Exception): pass
class ExceptionSoftwareTooOld(Exception): pass
class ExceptionUpgradeMissing(Exception): pass
class ExceptionUpgradeFailed(Exception): pass

from pokernetwork.version import Version, version

class PokerDatabase:

    def __init__(self, settings):
        self.log = log.getChild(self.__class__.__name__)
        self.parameters = settings.headerGetProperties("/server/database")[0]
        self.mysql_command = settings.headerGet("/server/database/@command")
        try:
コード例 #19
0
ファイル: pokerbotlogic.py プロジェクト: Usr-X/poker-network
#
import sys
sys.path.insert(0, "..")

from os import popen
from string import rstrip
from random import randint

from twisted.internet import reactor

from pokerengine.pokertournament import *
from pokernetwork.user import checkName
from pokernetwork.pokerpackets import *
from pokernetwork.pokerclientpackets import *
from pokernetwork import log as network_log
log = network_log.getChild('pokerbotlogic')

LEVEL2ITERATIONS = {
    0: 10,
    1: 1000,
    2: 10000,
    3: 50000,
    4: 100000,
    5: 200000
    }

STATE_RUNNING = 0
STATE_RECONNECTING = 1
STATE_SEARCHING = 2
STATE_BATCH = 3
コード例 #20
0
ファイル: pokerexplain.py プロジェクト: Usr-X/poker-network
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#

from string import lower

from twisted.python.runtime import seconds

from pokerengine.pokerchips import PokerChips
from pokerengine.pokergame import history2messages
from pokernetwork.pokergameclient import PokerNetworkGameClient
from pokernetwork.pokerpackets import * #@UnusedWildImport
from pokernetwork.pokerclientpackets import * #@UnusedWildImport
from pokernetwork import log as network_log
log = network_log.getChild('explain')

DEFAULT_PLAYER_USER_DATA = { 'timeout': None }

class PokerGames:

    def __init__(self, **kwargs):
        self.log = log.getChild(self.__class__.__name__)
        self.games = {}
        self.dirs = kwargs.get("dirs", [])
        self.prefix = kwargs.get("prefix", "")
    
    def getGame(self, game_id):
        if not hasattr(self, "games") or game_id not in self.games:
            return False
        else:
コード例 #21
0
ファイル: pokerauthmysql.py プロジェクト: Usr-X/poker-network
# General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program in a file in the toplevel directory called
# "AGPLv3".  If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
#  Loic Dachary <*****@*****.**>
#  Johan Euphrosine <*****@*****.**>
#  Henry Precheur <*****@*****.**> (2004)
#  Cedric Pinson <*****@*****.**> (2004-2006)

import MySQLdb
from pokernetwork.packets import PACKET_LOGIN
from pokernetwork import log as network_log
log = network_log.getChild('pokerauthmysql')

class PokerAuth:

    def __init__(self, db, memcache, settings):
        self.log = log.getChild(self.__class__.__name__)
        self.db = db
        self.memcache = memcache
        self.type2auth = {}
        self.settings = settings
        self.parameters = self.settings.headerGetProperties("/server/auth")[0]
        self.auth_db = MySQLdb.connect(host = self.parameters["host"],
                                  port = int(self.parameters.get("port", '3306')),
                                  user = self.parameters["user"],
                                  passwd = self.parameters["password"],
                                  db = self.parameters["db"])