This file is indexed.

/usr/share/kde4/apps/kajongg/server.py is in kajongg 4:4.14.1-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Copyright (C) 2009-2014 Wolfgang Rohdewald <wolfgang@rohdewald.de>

Kajongg is free software you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation either version 2 of the License, or
(at your option) any later version.

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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

The DBPasswordChecker is based on an example from the book
Twisted Network Programming Essentials by Abe Fettig, 2006
O'Reilly Media, Inc., ISBN 0-596-10032-9
"""

import sys, os, random, traceback
if os.name != 'nt':
    import resource
import datetime, logging
from itertools import chain

def cleanExit(*dummyArgs):
    """we want to cleanly close sqlite3 files"""
    if Options.socket and os.name != 'nt':
        if os.path.exists(Options.socket):
            os.remove(Options.socket)
    try:
        if Internal.db:
            Internal.db.close() # setting to None does not call close(), do we need close?
        logging.shutdown()
        os._exit(0) # pylint: disable=protected-access
    except NameError:
        logging.shutdown()
    try:
        reactor.stop()
    except NameError:
        sys.exit(0)
    except ReactorNotRunning:
        pass

from signal import signal, SIGABRT, SIGINT, SIGTERM
signal(SIGABRT, cleanExit)
signal(SIGINT, cleanExit)
signal(SIGTERM, cleanExit)
if os.name != 'nt':
    from signal import SIGHUP, SIGQUIT
    signal(SIGHUP, cleanExit)
    signal(SIGQUIT, cleanExit)


from common import Options, Internal
Internal.isServer = True
Internal.logPrefix = 'S'

from twisted.spread import pb
from twisted.internet import error
from twisted.internet.defer import maybeDeferred, fail, succeed
from zope.interface import implements
from twisted.cred import checkers, portal, credentials, error as credError
from twisted.internet import reactor
from twisted.internet.error import ReactorNotRunning
reactor.addSystemEventTrigger('before', 'shutdown', cleanExit)
Internal.reactor = reactor

from tile import Tile, TileList, elements
from game import PlayingGame
from player import Players
from wall import WallEmpty
from client import Client, Table
from query import Query, initDb
from meld import Meld, MeldList
from log import m18n, m18nE, m18ncE, logDebug, logWarning, logError, SERVERMARK
from util import Duration, elapsedSince
from message import Message, ChatMessage
from common import Debug
from sound import Voice
from deferredutil import DeferredBlock
from rule import Ruleset

def srvMessage(*args):
    """concatenate all args needed for m18n encoded in one string.
    For an explanation see util.translateServerString"""
    strArgs = []
    for arg in args:
        if isinstance(arg, unicode):
            arg = arg.encode('utf-8')
        elif not isinstance(arg, str):
            arg = str(arg)
        strArgs.append(arg)
    return SERVERMARK+SERVERMARK.join(strArgs)+SERVERMARK

def srvError(cls, *args):
    """raise an exception, passing args as a single string"""
    raise cls(srvMessage(*args))

class DBPasswordChecker(object):
    """checks against our sqlite3 databases"""
    implements(checkers.ICredentialsChecker)
    credentialInterfaces = (credentials.IUsernamePassword,
                            credentials.IUsernameHashedPassword)

    def requestAvatarId(self, cred): # pylint: disable=no-self-use
        """get user id from database"""
        cred.username = cred.username.decode('utf-8')
        args = cred.username.split(SERVERMARK)
        if len(args) > 1:
            if args[0] == 'adduser':
                cred.username = args[1]
                password = args[2]
                query = Query('insert or ignore into player(name,password) values(?,?)', (cred.username, password))
            elif args[1] == 'deluser':
                pass
        query = Query('select id, password from player where name=?', (cred.username,))
        if not len(query.records):
            template = 'Wrong username: %1'
            if Debug.connections:
                logDebug(m18n(template, cred.username))
            return fail(credError.UnauthorizedLogin(srvMessage(template, cred.username)))
        userid, password = query.records[0]
        # checkPassword uses md5 which cannot handle unicode strings (python 2.7)
        defer1 = maybeDeferred(cred.checkPassword, password.encode('utf-8'))
        defer1.addCallback(DBPasswordChecker._checkedPassword, userid)
        return defer1

    @staticmethod
    def _checkedPassword(matched, userid):
        """after the password has been checked"""
        if not matched:
            return fail(credError.UnauthorizedLogin(srvMessage(m18nE('Wrong password'))))
        return userid

class ServerGame(PlayingGame):
    """the central game instance on the server"""
    # pylint: disable=too-many-arguments, too-many-public-methods
    def __init__(self, names, ruleset, gameid=None, wantedGame=None,
                client=None, playOpen=False, autoPlay=False):
        PlayingGame.__init__(self, names, ruleset, gameid, wantedGame, client, playOpen, autoPlay)
        self.shouldSave = True

    def throwDices(self):
        """sets random living and kongBox
        sets divideAt: an index for the wall break"""
        self.wall.tiles.sort()
        self.randomGenerator.shuffle(self.wall.tiles)
        PlayingGame.throwDices(self)

    def initHand(self):
        """Happens only on server: every player gets 13 tiles (including east)"""
        self.throwDices()
        self.wall.divide()
        for player in self.players:
            player.clearHand()
            # 13 tiles at least, with names as given by wall
            player.addConcealedTiles(self.wall.deal([None] * 13))
            # compensate boni
            while len(player.concealedTiles) != 13:
                player.addConcealedTiles(self.wall.deal())
        PlayingGame.initHand(self)

class ServerTable(Table):
    """a table on the game server"""
    # pylint: disable=too-many-arguments

    def __init__(self, server, owner, ruleset, suspendedAt, playOpen, autoPlay, wantedGame, tableId=None):
        if tableId is None:
            tableId = server.generateTableId()
        Table.__init__(self, tableId, ruleset, suspendedAt, False, playOpen, autoPlay, wantedGame)
        self.server = server
        self.owner = owner
        self.users = [owner] if owner else []
        self.remotes = {}   # maps client connections to users
        self.game = None
        self.client = None
        server.tables[self.tableid] = self
        if Debug.table:
            logDebug('new table %s' % self)

    def hasName(self, name):
        """returns True if one of the players in the game is named 'name'"""
        return bool(self.game) and any(x.name == name for x in self.game.players)

    def asSimpleList(self, withFullRuleset=False):
        """return the table attributes to be sent to the client"""
        game = self.game
        onlineNames = [x.name for x in self.users]
        if self.suspendedAt:
            names = tuple(x.name for x in game.players)
        else:
            names = tuple(x.name for x in self.users)
        online = tuple(bool(x in onlineNames) for x in names)
        if game:
            endValues = game.handctr, dict((x.wind, x.balance) for x in game.players)
        else:
            endValues = None
        if withFullRuleset:
            ruleset = self.ruleset.toList()
        else:
            ruleset = self.ruleset.hash
        return list([self.tableid, ruleset, game.gameid if game else None, self.suspendedAt, self.running, \
                self.playOpen, self.autoPlay, self.wantedGame, names, online, endValues])

    def maxSeats(self):
        """for a new game: 4. For a suspended game: The
        number of humans before suspending"""
        result = 4
        if self.suspendedAt:
            result -= sum(x.name.startswith('Robot ') for x in self.game.players)
        return result

    def sendChatMessage(self, chatLine):
        """sends a chat messages to all clients"""
        if Debug.chat:
            logDebug('server sends chat msg %s' % chatLine)
        if self.suspendedAt:
            chatters = []
            for player in self.game.players:
                chatters.extend(x for x in self.server.srvUsers if x.name == player.name)
        else:
            chatters = self.users
        for other in chatters:
            self.server.callRemote(other, 'chat', chatLine.asList())

    def addUser(self, user):
        """add user to this table"""
        if user.name in list(x.name for x in self.users):
            raise srvError(pb.Error, m18nE('You already joined this table'))
        if len(self.users) == self.maxSeats():
            raise srvError(pb.Error, m18nE('All seats are already taken'))
        self.users.append(user)
        if Debug.table:
            logDebug('%s seated on table %s' % (user.name, self))
        self.sendChatMessage(ChatMessage(self.tableid, user.name,
            m18nE('takes a seat'), isStatusMessage=True))

    def delUser(self, user):
        """remove user from this table"""
        if user in self.users:
            self.running = False
            self.users.remove(user)
            self.sendChatMessage(ChatMessage(self.tableid, user.name,
                m18nE('leaves the table'), isStatusMessage=True))
            if user is self.owner:
                # silently pass ownership
                if self.users:
                    self.owner = self.users[0]
                    if Debug.table:
                        logDebug('%s leaves table %d, %s is the new owner' % (
                            user.name, self.tableid, self.owner))
                else:
                    if Debug.table:
                        logDebug('%s leaves table %d, table is now empty' % (
                            user.name, self.tableid))
            else:
                if Debug.table:
                    logDebug('%s leaves table %d, %s stays owner' % (
                        user.name, self.tableid, self.owner))

    def __str__(self):
        """for debugging output"""
        onlineNames = list(x.name + ('(Owner)' if x == self.owner.name else '') for x in self.users)
        offlineString = ''
        if self.game:
            offlineNames = list(x.name for x in self.game.players if x.name not in onlineNames
                and not x.name.startswith('Robot'))
            if offlineNames:
                offlineString = ' offline:' + ','.join(offlineNames)
        return '%d(%s%s)' % (self.tableid, ','.join(onlineNames), offlineString)

    def __repr__(self):
        return 'ServerTable(%s)' % str(self)

    def calcGameId(self):
        """based upon the max gameids we got from the clients, propose
        a new one, we want to use the same gameid in all data bases"""
        serverMaxGameId = Query('select max(id) from game').records[0][0]
        serverMaxGameId = int(serverMaxGameId) if serverMaxGameId else 0
        gameIds = [x.maxGameId for x in self.users]
        gameIds.append(serverMaxGameId)
        return max(gameIds) + 1

    def __prepareNewGame(self):
        """returns a new game object"""
        names = list(x.name for x in self.users)
        # the server and all databases save the english name but we
        # want to make sure a translation exists for the client GUI
        robotNames = [
            m18ncE('kajongg, name of robot player, to be translated', 'Robot 1'),
            m18ncE('kajongg, name of robot player, to be translated', 'Robot 2'),
            m18ncE('kajongg, name of robot player, to be translated', 'Robot 3')]
        while len(names) < 4:
            names.append(robotNames[3 - len(names)])
        self.client = Client() # Game has a weakref to client, so we must keep it!
        return ServerGame(names, self.ruleset, client=self.client,
            playOpen=self.playOpen, autoPlay=self.autoPlay, wantedGame=self.wantedGame)

    def userForPlayer(self, player):
        """finds the table user corresponding to player"""
        for result in self.users:
            if result.name == player.name:
                return result

    def __connectPlayers(self):
        """connects client instances with the game players"""
        game = self.game
        for player in game.players:
            remote = self.userForPlayer(player)
            if not remote:
                # we found a robot player, its client runs in this server process
                remote = Client(player.name)
                remote.table = self
            self.remotes[player] = remote

    def __checkDbIdents(self):
        """for 4 players, we have up to 4 data bases:
        more than one player might use the same data base.
        However the server always needs to use its own data base.
        If a data base is used by more than one client, only one of
        them should update. Here we set shouldSave for all players,
        while the server always saves"""
        serverIdent = Internal.db.identifier
        dbIdents = set()
        game = self.game
        for player in game.players:
            player.shouldSave = False
            if isinstance(self.remotes[player], User):
                dbIdent = self.remotes[player].dbIdent
                assert dbIdent != serverIdent, \
                   'client and server try to use the same database:%s' % \
                   Internal.db.path
                player.shouldSave = dbIdent not in dbIdents
                dbIdents.add(dbIdent)

    def readyForGameStart(self, user):
        """the table initiator told us he wants to start the game"""
        if len(self.users) < self.maxSeats() and self.owner != user:
            raise srvError(pb.Error,
                m18nE('Only the initiator %1 can start this game, you are %2'),
                self.owner.name, user.name)
        if self.suspendedAt:
            self.__connectPlayers()
            self.__checkDbIdents()
            self.initGame()
        else:
            self.game = self.__prepareNewGame()
            self.__connectPlayers()
            self.__checkDbIdents()
            self.proposeGameId(self.calcGameId())
        # TODO: remove table for all other srvUsers out of sight

    def proposeGameId(self, gameid):
        """server proposes an id to the clients ands waits for answers"""
        while True:
            query = Query('insert into game(id,seed) values(?,?)',
                  (gameid, 'proposed'), mayFail=True, failSilent=True)
            if not query.failure:
                break
            gameid += random.randrange(1, 100)
        block = DeferredBlock(self)
        for player in self.game.players:
            if player.shouldSave and isinstance(self.remotes[player], User):
                # do not ask robot players, they use the server data base
                block.tellPlayer(player, Message.ProposeGameId, gameid=gameid)
        block.callback(self.collectGameIdAnswers, gameid)

    def collectGameIdAnswers(self, requests, gameid):
        """clients answered if the proposed game id is free"""
        if requests:
            # when errors happen, there might be no requests left
            for msg in requests:
                if msg.answer == Message.NO:
                    self.proposeGameId(gameid + 1)
                    return
                elif msg.answer != Message.OK:
                    raise srvError(pb.Error, 'collectGameIdAnswers got neither NO nor OK')
            self.game.gameid = gameid
            self.initGame()

    def initGame(self):
        """ask clients if they are ready to start"""
        game = self.game
        game.saveStartTime()
        block = DeferredBlock(self)
        for player in game.players:
            block.tellPlayer(player, Message.ReadyForGameStart, tableid=self.tableid,
                gameid=game.gameid, shouldSave=player.shouldSave,
                wantedGame=game.wantedGame, source=list((x.wind, x.name) for x in game.players))
        block.callback(self.startGame)

    def startGame(self, requests):
        """if all players said ready, start the game"""
        for user in self.users:
            userRequests = list(x for x in requests if x.user == user)
            if not userRequests or userRequests[0].answer == Message.NoGameStart:
                if Debug.table:
                    if not userRequests:
                        logDebug('Server.startGame: found no request for user %s' % user.name)
                    else:
                        logDebug('Server.startGame: %s said NoGameStart' % user.name)
                self.game = None
                return
        if Debug.table:
            logDebug('Game starts on table %s' % self)
        elementIter = iter(elements.all(self.game.ruleset))
        wallSize = len(self.game.wall.tiles)
        self.game.wall.tiles = []
        for _ in range(wallSize):
            self.game.wall.tiles.append(elementIter.next().concealed)
        assert isinstance(self.game, ServerGame), self.game
        self.running = True
        self.__adaptOtherTables()
        self.sendVoiceIds()

    def __adaptOtherTables(self):
        """if the players on this table also reserved seats on other tables, clear them
        make running table invisible for other users"""
        for user in self.users:
            for tableid in self.server.tablesWith(user):
                if tableid != self.tableid:
                    self.server.leaveTable(user, tableid)
        foreigners = list(x for x in self.server.srvUsers if x not in self.users)
        if foreigners:
            if Debug.table:
                logDebug('make running table %s invisible for %s' % (self, ','.join(str(x) for x in foreigners)))
            for srvUser in foreigners:
                self.server.callRemote(srvUser, 'tableRemoved', self.tableid, '')

    def sendVoiceIds(self):
        """tell each player what voice ids the others have. By now the client has a Game instance!"""
        humanPlayers = [x for x in self.game.players if isinstance(self.remotes[x], User)]
        if len(humanPlayers) < 2 or not any(self.remotes[x].voiceId for x in humanPlayers):
            # no need to pass around voice data
            self.assignVoices()
            return
        block = DeferredBlock(self)
        for player in humanPlayers:
            remote = self.remotes[player]
            if remote.voiceId:
                # send it to other human players:
                others = [x for x in humanPlayers if x != player]
                if Debug.sound:
                    logDebug('telling other human players that %s has voiceId %s' % (
                        player.name, remote.voiceId))
                block.tell(player, others, Message.VoiceId, source=remote.voiceId)
        block.callback(self.collectVoiceData)

    def collectVoiceData(self, requests):
        """collect voices of other players"""
        if not self.running:
            return
        block = DeferredBlock(self)
        voiceDataRequests = []
        for request in requests:
            if request.answer == Message.ClientWantsVoiceData:
                # another human player requests sounds for voiceId
                voiceId = request.args[0]
                voiceFor = [x for x in self.game.players if isinstance(self.remotes[x], User) \
                    and self.remotes[x].voiceId == voiceId][0]
                voiceFor.voice = Voice(voiceId)
                if Debug.sound:
                    logDebug('client %s wants voice data %s for %s' % (request.user.name, request.args[0], voiceFor))
                voiceDataRequests.append((request.user, voiceFor))
                if not voiceFor.voice.oggFiles():
                    # the server does not have it, ask the client with that voice
                    block.tell(voiceFor, voiceFor, Message.ServerWantsVoiceData)
        block.callback(self.sendVoiceData, voiceDataRequests)

    def sendVoiceData(self, requests, voiceDataRequests):
        """sends voice sounds to other human players"""
        self.processAnswers(requests)
        block = DeferredBlock(self)
        for voiceDataRequester, voiceFor in voiceDataRequests:
            # this player requested sounds for voiceFor
            voice = voiceFor.voice
            content = voice.archiveContent
            if content:
                if Debug.sound:
                    logDebug('server got voice data %s for %s from client' % (voiceFor.voice, voiceFor.name))
                block.tell(voiceFor, voiceDataRequester, Message.VoiceData, md5sum=voice.md5sum, source=content)
            elif Debug.sound:
                logDebug('server got empty voice data %s for %s from client' % (
                    voice, voiceFor.name))
        block.callback(self.assignVoices)

    def assignVoices(self, dummyResults=None):
        """now all human players have all voice data needed"""
        humanPlayers = [x for x in self.game.players if isinstance(self.remotes[x], User)]
        block = DeferredBlock(self)
        block.tell(None, humanPlayers, Message.AssignVoices)
        block.callback(self.startHand)

    def pickTile(self, dummyResults=None, deadEnd=False):
        """the active player gets a tile from wall. Tell all clients."""
        if not self.running:
            return
        player = self.game.activePlayer
        try:
            tile = player.pickedTile(deadEnd)
        except WallEmpty:
            self.endHand()
        else:
            self.game.lastDiscard = None
            block = DeferredBlock(self)
            block.tellPlayer(player, Message.PickedTile, tile=tile, deadEnd=deadEnd)
            if tile.isBonus or self.game.playOpen:
                block.tellOthers(player, Message.PickedTile, tile=tile, deadEnd=deadEnd)
            else:
                block.tellOthers(player, Message.PickedTile, tile=Tile.unknown, deadEnd=deadEnd)
            block.callback(self.moved)

    def pickKongReplacement(self, requests=None):
        """the active player gets a tile from the dead end. Tell all clients."""
        requests = self.prioritize(requests)
        if requests and requests[0].answer == Message.MahJongg:
            requests[0].answer.serverAction(self, requests[0])
        else:
            self.pickTile(requests, deadEnd=True)

    def clientDiscarded(self, msg):
        """client told us he discarded a tile. Check for consistency and tell others."""
        # pylint: disable=too-many-branches
        # too many branches
        if not self.running:
            return
        player = msg.player
        game = self.game
        assert player == game.activePlayer
        tile = Tile(msg.args[0])
        if tile not in player.concealedTiles:
            self.abort('player %s discarded %s but does not have it' % (player, tile))
            return
        txt = game.dangerousFor(player, tile)
        mustPlayDangerous = player.mustPlayDangerous()
        block = DeferredBlock(self)
        violates = player.violatesOriginalCall(tile)
        game.hasDiscarded(player, tile)
        block.tellAll(player, Message.Discard, tile=tile)
        if violates:
            if Debug.originalCall:
                logDebug('%s just violated OC with %s' % (player, tile))
            player.mayWin = False
            block.tellAll(player, Message.ViolatesOriginalCall)
        if game.ruleset.mustDeclareCallingHand and not player.isCalling:
            if player.hand.callingHands:
                player.isCalling = True
                block.tellAll(player, Message.Calling)
        if txt:
            if mustPlayDangerous and player.lastSource not in 'dZ':
                if Debug.dangerousGame:
                    logDebug('%s claims no choice. Discarded %s, keeping %s. %s' % \
                         (player, tile, ''.join(player.concealedTiles), ' / '.join(txt)))
                player.claimedNoChoice = True
                block.tellAll(player, Message.NoChoice, tiles=TileList(player.concealedTiles))
            else:
                player.playedDangerous = True
                if Debug.dangerousGame:
                    logDebug('%s played dangerous. Discarded %s, keeping %s. %s' % \
                         (player, tile, ''.join(player.concealedTiles), ' / '.join(txt)))
                block.tellAll(player, Message.DangerousGame, tiles=TileList(player.concealedTiles))
        if msg.answer == Message.OriginalCall:
            player.isCalling = True
            block.callback(self.clientMadeOriginalCall, msg)
        else:
            block.callback(self.askForClaims)

    def clientMadeOriginalCall(self, dummyResults, msg):
        """first tell everybody about original call
        and then treat the implicit discard"""
        msg.player.originalCall = True
        if Debug.originalCall:
            logDebug('server.clientMadeOriginalCall: %s' % msg.player)
        block = DeferredBlock(self)
        block.tellAll(msg.player, Message.OriginalCall)
        block.callback(self.askForClaims)

    def startHand(self, dummyResults=None):
        """all players are ready to start a hand, so do it"""
        if self.running:
            self.game.prepareHand()
            self.game.initHand()
            block = self.tellAll(None, Message.InitHand,
                divideAt=self.game.divideAt)
            block.callback(self.divided)

    def divided(self, dummyResults=None):
        """the wall is now divided for all clients"""
        if not self.running:
            return
        block = DeferredBlock(self)
        for clientPlayer in self.game.players:
            for player in self.game.players:
                if player == clientPlayer or self.game.playOpen:
                    tiles = player.concealedTiles
                else:
                    tiles = TileList(Tile.unknown * 13)
                block.tell(player, clientPlayer, Message.SetConcealedTiles,
                    tiles=TileList(chain(tiles, player.bonusTiles)))
        block.callback(self.dealt)

    def endHand(self, dummyResults=None):
        """hand is over, show all concealed tiles to all players"""
        if not self.running:
            return
        if self.game.playOpen:
            self.saveHand()
        else:
            block = DeferredBlock(self)
            for player in self.game.players:
                # there might be no winner, winner.others() would be wrong
                if player != self.game.winner:
                    # the winner tiles are already shown in claimMahJongg
                    block.tellOthers(player, Message.ShowConcealedTiles, show=True,
                        tiles=TileList(player.concealedTiles))
            block.callback(self.saveHand)

    def saveHand(self, dummyResults=None):
        """save the hand to the database and proceed to next hand"""
        if not self.running:
            return
        self.tellAll(None, Message.SaveHand, self.nextHand)
        self.game.saveHand()

    def nextHand(self, dummyResults):
        """next hand: maybe rotate"""
        if not self.running:
            return
        DeferredBlock.garbageCollection()
        for block in DeferredBlock.blocks:
            if block.table == self:
                logError('request left from previous hand: %s' % block.outstandingStr())
        token = self.game.handId.prompt(withAI=False) # we need to send the old token until the
                                   # clients started the new hand
        rotateWinds = self.game.maybeRotateWinds()
        if self.game.finished():
            self.server.removeTable(self, 'gameOver', m18nE('Game <numid>%1</numid> is over!'), self.game.seed)
            if Debug.process and os.name != 'nt':
                logDebug('MEM:%s' % resource.getrusage(resource.RUSAGE_SELF).ru_maxrss)
            return
        self.game.sortPlayers()
        playerNames = list((x.wind, x.name) for x in self.game.players)
        self.tellAll(None, Message.ReadyForHandStart, self.startHand,
            source=playerNames, rotateWinds=rotateWinds, token=token)

    def abort(self, message, *args):
        """abort the table. Reason: message/args"""
        self.server.removeTable(self, 'abort', message, *args)

    def claimTile(self, player, claim, meldTiles, nextMessage):
        """a player claims a tile for pung, kong or chow.
        meldTiles contains the claimed tile, concealed"""
        if not self.running:
            return
        lastDiscard = self.game.lastDiscard
        # if we rob a tile, self.game.lastDiscard has already been set to the robbed tile
        hasTiles = Meld(meldTiles[:])
        discardingPlayer = self.game.activePlayer
        hasTiles = hasTiles.without(lastDiscard)
        meld = Meld(meldTiles)
        if len(meld) != 4 and not (meld.isPair or meld.isPungKong or meld.isChow):
            msg = m18nE('%1 wrongly said %2 for meld %3')
            self.abort(msg, player.name, claim.name, str(meld))
            return
        if not player.hasConcealedTiles(hasTiles):
            msg = m18nE('%1 wrongly said %2: claims to have concealed tiles %3 but only has %4')
            self.abort(msg, player.name, claim.name, ' '.join(hasTiles), ''.join(player.concealedTiles))
            return
        # update our internal state before we listen to the clients again
        self.game.discardedTiles[lastDiscard.exposed] -= 1
        self.game.activePlayer = player
        if lastDiscard:
            player.lastTile = lastDiscard.exposed
            player.lastSource = 'd'
        player.exposeMeld(hasTiles, lastDiscard)
        self.game.lastDiscard = None
        block = DeferredBlock(self)
        if (nextMessage != Message.Kong
                and self.game.dangerousFor(discardingPlayer, lastDiscard)
                and discardingPlayer.playedDangerous):
            player.usedDangerousFrom = discardingPlayer
            if Debug.dangerousGame:
                logDebug('%s claims dangerous tile %s discarded by %s' % \
                         (player, lastDiscard, discardingPlayer))
            block.tellAll(player, Message.UsedDangerousFrom, source=discardingPlayer.name)
        block.tellAll(player, nextMessage, meld=meld)
        if claim == Message.Kong:
            block.callback(self.pickKongReplacement)
        else:
            block.callback(self.moved)

    def declareKong(self, player, meldTiles):
        """player declares a Kong, meldTiles is a list"""
        kongMeld = Meld(meldTiles)
        if not player.hasConcealedTiles(kongMeld) and kongMeld[0].exposed.pung not in player.exposedMelds:
            # pylint: disable=star-args
            msg = m18nE('declareKong:%1 wrongly said Kong for meld %2')
            args = (player.name, str(kongMeld))
            logDebug(m18n(msg, *args))
            logDebug('declareKong:concealedTiles:%s' % ''.join(player.concealedTiles))
            logDebug('declareKong:concealedMelds:%s' % \
                ' '.join(str(x) for x in player.concealedMelds))
            logDebug('declareKong:exposedMelds:%s' % \
                ' '.join(str(x) for x in player.exposedMelds))
            self.abort(msg, *args)
            return
        player.exposeMeld(kongMeld)
        self.tellAll(player, Message.DeclaredKong, self.pickKongReplacement, meld=kongMeld)

    def claimMahJongg(self, msg):
        """a player claims mah jongg. Check this and
        if correct, tell all. Otherwise abort game,  kajongg client is faulty"""
        if not self.running:
            return
        player = msg.player
        concealedMelds = MeldList(msg.args[0])
        withDiscard = Tile(msg.args[1]) if msg.args[1] else None
        lastMeld = Meld(msg.args[2])
        if self.game.ruleset.mustDeclareCallingHand:
            assert player.isCalling, '%s %s: concmelds:%s withdiscard:%s lastmeld:%s' % (
                self.game.handId, player, concealedMelds, withDiscard, lastMeld)
        discardingPlayer = self.game.activePlayer
        lastMove = self.game.lastMoves(withoutNotifications=True).next()
        robbedTheKong = lastMove.message == Message.DeclaredKong
        if robbedTheKong:
            player.lastSource = 'k'
            withDiscard = lastMove.meld[0].concealed
            lastMove.player.robTile(withDiscard)
        msgArgs = player.showConcealedMelds(concealedMelds, withDiscard)
        if msgArgs:
            self.abort(*msgArgs) # pylint: disable=star-args
        player.declaredMahJongg(concealedMelds, withDiscard, player.lastTile, lastMeld)
        if not player.hand.won:
            msg = m18nE('%1 claiming MahJongg: This is not a winning hand: %2')
            self.abort(msg, player.name, player.hand.string)
            return
        block = DeferredBlock(self)
        if robbedTheKong:
            block.tellAll(player, Message.RobbedTheKong, tile=withDiscard)
        if (player.lastSource == 'd'
                and self.game.dangerousFor(discardingPlayer, player.lastTile)
                and discardingPlayer.playedDangerous):
            player.usedDangerousFrom = discardingPlayer
            if Debug.dangerousGame:
                logDebug('%s wins with dangerous tile %s from %s' % \
                             (player, self.game.lastDiscard, discardingPlayer))
            block.tellAll(player, Message.UsedDangerousFrom, source=discardingPlayer.name)
        block.tellAll(player, Message.MahJongg, melds=concealedMelds, lastTile=player.lastTile,
                     lastMeld=lastMeld, withDiscardTile=withDiscard)
        block.callback(self.endHand)

    def dealt(self, dummyResults):
        """all tiles are dealt, ask east to discard a tile"""
        if self.running:
            self.tellAll(self.game.activePlayer, Message.ActivePlayer, self.pickTile)

    def nextTurn(self):
        """the next player becomes active"""
        if self.running:
            # the player might just have disconnected
            self.game.nextTurn()
            self.tellAll(self.game.activePlayer, Message.ActivePlayer, self.pickTile)

    def prioritize(self, requests):
        """returns only requests we want to execute"""
        if not self.running:
            return
        answers = [x for x in requests if x.answer not in [Message.NoClaim, Message.OK, None]]
        if len(answers) > 1:
            claims = [Message.MahJongg, Message.Kong, Message.Pung, Message.Chow]
            for claim in claims:
                if claim in [x.answer for x in answers]:
                    # ignore claims with lower priority:
                    answers = [x for x in answers if x.answer == claim or x.answer not in claims]
                    break
        mjAnswers = [x for x in answers if x.answer == Message.MahJongg]
        if len(mjAnswers) > 1:
            mjPlayers = [x.player for x in mjAnswers]
            nextPlayer = self.game.nextPlayer()
            while nextPlayer not in mjPlayers:
                nextPlayer = self.game.nextPlayer(nextPlayer)
            answers = [x for x in answers if x.player == nextPlayer or x.answer != Message.MahJongg]
        return answers

    def askForClaims(self, dummyRequests):
        """ask all players if they want to claim"""
        if self.running:
            self.tellOthers(self.game.activePlayer, Message.AskForClaims, self.moved)

    def processAnswers(self, requests):
        """a player did something"""
        if not self.running:
            return
        answers = self.prioritize(requests)
        if not answers:
            return
        for answer in answers:
            msg = '<-  %s' % unicode(answer)
            if Debug.traffic:
                logDebug(msg)
            with Duration(msg):
                answer.answer.serverAction(self, answer)
        return answers

    def moved(self, requests):
        """a player did something"""
        if Debug.stack:
            stck = traceback.extract_stack()
            if len(stck) > 30:
                logDebug('stack size:%d' % len(stck))
                logDebug(stck)
        answers = self.processAnswers(requests)
        if not answers:
            self.nextTurn()

    def tellAll(self, player, command, callback=None, **kwargs):
        """tell something about player to all players"""
        block = DeferredBlock(self)
        block.tellAll(player, command, **kwargs)
        block.callback(callback)
        return block

    def tellOthers(self, player, command, callback=None, **kwargs):
        """tell something about player to all other players"""
        block = DeferredBlock(self)
        block.tellOthers(player, command, **kwargs)
        block.callback(callback)
        return block

class MJServer(object):
    """the real mah jongg server"""
    def __init__(self):
        self.tables = {}
        self.srvUsers = list()
        Players.load()
        self.lastPing = None
        self.checkPings()

    def chat(self, chatString):
        """a client sent us a chat message"""
        chatLine = ChatMessage(chatString)
        if Debug.chat:
            logDebug('server got chat message %s' % chatLine)
        self.tables[chatLine.tableid].sendChatMessage(chatLine)

    def login(self, user):
        """accept a new user"""
        if not user in self.srvUsers:
            self.srvUsers.append(user)
            self.loadSuspendedTables(user)

    def callRemote(self, user, *args, **kwargs):
        """if we still have a connection, call remote, otherwise clean up"""
        if user.mind:
            try:
                args2, kwargs2 = Message.jellyAll(args, kwargs)
                # pylint: disable=star-args
                return user.mind.callRemote(*args2, **kwargs2).addErrback(MJServer.ignoreLostConnection)
            except (pb.DeadReferenceError, pb.PBConnectionLost):
                user.mind = None
                self.logout(user)

    @staticmethod
    def __stopAfterLastDisconnect():
        """as the name says"""
        if Options.socket and not Options.continueServer:
            try:
                reactor.stop()
                if Debug.connections:
                    logDebug('local server terminates from %s. Reason: last client disconnected' % (
                        Options.socket))
            except ReactorNotRunning:
                pass

    def checkPings(self):
        """are all clients still alive? If not log them out"""
        if not self.srvUsers and self.lastPing and elapsedSince(self.lastPing) > 30:
            # no user at all since 30 seconds, but we did already have a user
            self.__stopAfterLastDisconnect()
        for user in self.srvUsers:
            self.lastPing = max(self.lastPing, user.lastPing) if self.lastPing else user.lastPing
            if elapsedSince(user.lastPing) > 60:
                logDebug('No messages from %s since 60 seconds, clearing connection now' % user.name)
                user.mind = None
                self.logout(user)
        reactor.callLater(10, self.checkPings)

    @staticmethod
    def ignoreLostConnection(failure):
        """if the client went away, do not dump error messages on stdout"""
        failure.trap(pb.PBConnectionLost)

    def sendTables(self, user, tables=None):
        """send tables to user. If tables is None, he gets all new tables and those
        suspended tables he was sitting on"""
        if tables is None:
            tables = list(x for x in self.tables.values() \
                if not x.running and (not x.suspendedAt or x.hasName(user.name)))
        if len(tables):
            data = list(x.asSimpleList() for x in tables)
            if Debug.table:
                logDebug('sending %d tables to %s: %s' % (len(tables), user.name, data))
            return self.callRemote(user, 'newTables', data)
        else:
            return succeed([])

    def _lookupTable(self, tableid):
        """return table by id or raise exception"""
        if tableid not in self.tables:
            raise srvError(pb.Error, m18nE('table with id <numid>%1</numid> not found'), tableid)
        return self.tables[tableid]

    def generateTableId(self):
        """generates a new table id: the first free one"""
        usedIds = set(self.tables or [0])
        availableIds = set(x for x in range(1, 2+max(usedIds)))
        return min(availableIds - usedIds)

    def newTable(self, user, ruleset, playOpen, autoPlay, wantedGame, tableId=None):
        """user creates new table and joins it"""
        def gotRuleset(ruleset):
            """now we have the full ruleset definition from the client"""
            Ruleset.cached(ruleset).save() # make it known to the cache and save in db
        if tableId in self.tables:
            return fail(srvError(pb.Error,
                'You want a new table with id=%d but that id is already used for table %s' % (
                    tableId, self.tables[tableId])))
        if Ruleset.hashIsKnown(ruleset):
            return self.__newTable(None, user, ruleset, playOpen, autoPlay, wantedGame, tableId)
        else:
            return self.callRemote(user, 'needRuleset', ruleset).addCallback(
                gotRuleset).addCallback(
                self.__newTable, user, ruleset, playOpen, autoPlay, wantedGame, tableId)

    def __newTable(self, dummy, user, ruleset, playOpen, autoPlay, wantedGame, tableId=None):
        """now we know the ruleset"""
        def sent(dummy):
            """new table sent to user who created it"""
            return table.tableid
        table = ServerTable(self, user, ruleset, None, playOpen, autoPlay, wantedGame, tableId)
        result = None
        for srvUser in self.srvUsers:
            deferred = self.sendTables(srvUser, [table])
            if user == srvUser:
                result = deferred
                deferred.addCallback(sent)
        assert result
        return result

    def needRulesets(self, rulesetHashes):
        """the client wants those full rulesets"""
        result = []
        for table in self.tables.values():
            if table.ruleset.hash in rulesetHashes:
                result.append(table.ruleset.toList())
        return result

    def joinTable(self, user, tableid):
        """user joins table"""
        table = self._lookupTable(tableid)
        table.addUser(user)
        block = DeferredBlock(table)
        block.tell(None, self.srvUsers, Message.TableChanged, source=table.asSimpleList())
        if len(table.users) == table.maxSeats():
            if Debug.table:
                logDebug('Table %s: All seats taken, starting' % table)
            def startTable(dummy):
                """now all players know about our join"""
                table.readyForGameStart(table.owner)
            block.callback(startTable)
        else:
            block.callback(False)
        return True

    def tablesWith(self, user):
        """table ids with user, except table 'without'"""
        return (x.tableid for x in self.tables.values() if user in x.users)

    def leaveTable(self, user, tableid, message=None, *args):
        """user leaves table. If no human user is left on a new table, remove it"""
        if tableid in self.tables:
            table = self.tables[tableid]
            if user in table.users:
                if len(table.users) == 1 and not table.suspendedAt:
                    # silent: do not tell the user who left the table that he did
                    self.removeTable(table, 'silent', message, *args)
                else:
                    table.delUser(user)
                    if self.srvUsers:
                        block = DeferredBlock(table)
                        block.tell(None, self.srvUsers, Message.TableChanged, source=table.asSimpleList())
                        block.callback(False)
        return True

    def startGame(self, user, tableid):
        """try to start the game"""
        return self._lookupTable(tableid).readyForGameStart(user)

    def removeTable(self, table, reason, message=None, *args):
        """remove a table"""
        assert reason in ('silent', 'tableRemoved', 'gameOver', 'abort')
        # HumanClient implements methods remote_tableRemoved etc.
        message = message or ''
        if Debug.connections or reason == 'abort':
            logDebug('%s%s ' % (('%s:' % table.game.seed) if table.game else '',
                m18n(message, *args)), withGamePrefix=None)
        if table.tableid in self.tables:
            del self.tables[table.tableid]
            if reason == 'silent':
                tellUsers = []
            else:
                tellUsers = table.users if table.running else self.srvUsers
            for user in tellUsers:
                # this may in turn call removeTable again!
                self.callRemote(user, reason, table.tableid, message, *args)
            for user in table.users:
                table.delUser(user)
            if Debug.table:
                logDebug('removing table %d: %s %s' % (table.tableid, m18n(message, *args), reason))
        if table.game:
            table.game.close()

    def logout(self, user):
        """remove user from all tables"""
        if user not in self.srvUsers:
            return
        self.srvUsers.remove(user)
        for tableid in self.tablesWith(user):
            self.leaveTable(user, tableid, m18nE('Player %1 has logged out'), user.name)
        # wait a moment. We want the leaveTable message to arrive everywhere before
        # we say serverDisconnects. Sometimes the order was reversed.
        reactor.callLater(1, self.__logout2, user)

    def __logout2(self, user):
        """now the leaveTable message had a good chance to get to the clients first"""
        self.callRemote(user, 'serverDisconnects')
        user.mind = None
        for block in DeferredBlock.blocks:
            for request in block.requests:
                if request.user == user:
                    block.removeRequest(request)

    def loadSuspendedTables(self, user):
        """loads all yet unloaded suspended tables where this
        user is participating. We do not unload them if the
        user logs out, there are filters anyway returning only
        the suspended games for a certain user.
        Never load old autoplay games."""
        query = Query("select distinct g.id, g.starttime, " \
            "g.seed, " \
            "ruleset, s.scoretime " \
            "from game g, player p0, score s," \
            "player p1, player p2, player p3 " \
            "where autoplay=0 " \
            " and p0.id=g.p0 and p1.id=g.p1 " \
            " and p2.id=g.p2 and p3.id=g.p3 " \
            " and (p0.name=? or p1.name=? or p2.name=? or p3.name=?) " \
            " and s.game=g.id" \
            " and g.endtime is null" \
            " and exists(select 1 from ruleset where ruleset.id=g.ruleset)" \
            " and exists(select 1 from score where game=g.id)" \
            " and s.scoretime = (select max(scoretime) from score where game=g.id) limit 10",
            (user.name, user.name, user.name, user.name))
        for gameid, _, seed, ruleset, suspendTime in query.records:
            if gameid not in (x.game.gameid for x in self.tables.values() if x.game):
                table = ServerTable(self, None, ruleset, suspendTime, playOpen=False,
                    autoPlay=False, wantedGame=str(seed))
                table.game = ServerGame.loadFromDB(gameid)

class User(pb.Avatar):
    """the twisted avatar"""
    def __init__(self, userid):
        self.name = Query('select name from player where id=?', (userid,)).records[0][0]
        self.mind = None
        self.server = None
        self.dbIdent = None
        self.voiceId = None
        self.maxGameId = None
        self.lastPing = None
        self.pinged()

    def pinged(self):
        """time of last ping or message from user"""
        self.lastPing = datetime.datetime.now()

    def source(self):
        """how did he connect?"""
        result = str(self.mind.broker.transport.getPeer())
        if 'UNIXAddress' in result:
            # socket: we want to get the socket name
            result = Options.socket
        return result

    def attached(self, mind):
        """override pb.Avatar.attached"""
        self.mind = mind
        self.server.login(self)
    def detached(self, dummyMind):
        """override pb.Avatar.detached"""
        if Debug.connections:
            logDebug('%s: connection detached from %s' % (self, self.source()))
        self.server.logout(self)
        self.mind = None
    def perspective_setClientProperties(self, dbIdent, voiceId, maxGameId, clientVersion=None):
        """perspective_* methods are to be called remotely"""
        self.dbIdent = dbIdent
        self.voiceId = voiceId
        self.maxGameId = maxGameId
        serverVersion = Internal.version
        if clientVersion != serverVersion:
            # we assume that versions x.y.* are compatible
            if clientVersion is None:
                # client passed no version info
                return fail(srvError(pb.Error,
                    m18nE('Your client has a version older than 4.9.0 but you need %1 for this server'),
                        serverVersion))
            else:
                commonDigits = len([x for x in zip(
                    clientVersion.split('.'),
                    serverVersion.split('.'))
                    if x[0] == x[1]])
                if commonDigits < 2:
                    return fail(srvError(pb.Error,
                        m18nE('Your client has version %1 but you need %2 for this server'),
                            clientVersion or '<4.9.0',
                            '.'.join(serverVersion.split('.')[:2]) + '.*'))
        self.server.sendTables(self)
    def perspective_ping(self):
        """perspective_* methods are to be called remotely"""
        return self.pinged()
    def perspective_needRulesets(self, rulesetHashes):
        """perspective_* methods are to be called remotely"""
        return self.server.needRulesets(rulesetHashes)
    def perspective_joinTable(self, tableid):
        """perspective_* methods are to be called remotely"""
        return self.server.joinTable(self, tableid)
    def perspective_leaveTable(self, tableid):
        """perspective_* methods are to be called remotely"""
        return self.server.leaveTable(self, tableid)
    def perspective_newTable(self, ruleset, playOpen, autoPlay, wantedGame, tableId=None):
        """perspective_* methods are to be called remotely"""
        return self.server.newTable(self, ruleset, playOpen, autoPlay, wantedGame, tableId)
    def perspective_startGame(self, tableid):
        """perspective_* methods are to be called remotely"""
        return self.server.startGame(self, tableid)
    def perspective_logout(self):
        """perspective_* methods are to be called remotely"""
        self.detached(None)
    def perspective_chat(self, chatString):
        """perspective_* methods are to be called remotely"""
        return self.server.chat(chatString)
    def __str__(self):
        return self.name
    def __repr__(self):
        return 'User({!s})'.format(self)

class MJRealm(object):
    """connects mind and server"""
    implements(portal.IRealm)

    def __init__(self):
        self.server = None

    def requestAvatar(self, avatarId, mind, *interfaces):
        """as the tutorials do..."""
        if not pb.IPerspective in interfaces:
            raise NotImplementedError("No supported avatar interface")
        avatar = User(avatarId)
        avatar.server = self.server
        avatar.attached(mind)
        if Debug.connections:
            logDebug('Connection from %s ' % avatar.source())
        return pb.IPerspective, avatar, lambda a=avatar: a.detached(mind)

def parseArgs():
    """as the name says"""
    from optparse import OptionParser
    parser = OptionParser()
    defaultPort = Options.defaultPort()
    parser.add_option('', '--port', dest='port',
        help=m18n('the server will listen on PORT (%d)' % defaultPort),
        type=int, default=defaultPort)
    parser.add_option('', '--socket', dest='socket',
        help=m18n('the server will listen on SOCKET'), default=None)
    parser.add_option('', '--db', dest='dbpath', help=m18n('name of the database'), default=None)
    parser.add_option('', '--continue', dest='continueServer', action='store_true',
        help=m18n('do not terminate local game server after last client disconnects'), default=False)
    parser.add_option('', '--debug', dest='debug',
        help=Debug.help())
    parser.add_option('', '--nokde', dest='nokde', action='store_true',
        help=m18n('do not use KDE bindings. Only for testing'))
    parser.add_option('', '--qt5', dest='qt5', action='store_true',
        help=m18n('Force using Qt5. Currently Qt4 is used by default'))
    (options, args) = parser.parse_args()
    if args and ''.join(args):
        logWarning(m18n('unrecognized arguments:%1', ' '.join(args)))
        sys.exit(2)
    Options.continueServer |= options.continueServer
    if options.dbpath:
        Options.dbPath = os.path.expanduser(options.dbpath)
    if options.socket:
        Options.socket = options.socket
    Debug.setOptions(options.debug)
    Options.fixed = True # may not be changed anymore
    del parser           # makes Debug.gc quieter
    return options

def kajonggServer():
    """start the server"""
    # pylint: disable=too-many-branches
    options = parseArgs()
    if not initDb():
        sys.exit(1)
    realm = MJRealm()
    realm.server = MJServer()
    kajonggPortal = portal.Portal(realm, [DBPasswordChecker()])
    import predefined # pylint: disable=unused-variable
    try:
        if Options.socket:
            if os.name == 'nt':
                if Debug.connections:
                    logDebug('local server listening on 127.0.0.1 port %d' % options.port)
                reactor.listenTCP(options.port, pb.PBServerFactory(kajonggPortal), interface='127.0.0.1')
            else:
                if Debug.connections:
                    logDebug('local server listening on UNIX socket %s' % Options.socket)
                reactor.listenUNIX(Options.socket, pb.PBServerFactory(kajonggPortal))
        else:
            if Debug.connections:
                logDebug('server listening on port %d' % options.port)
            reactor.listenTCP(options.port, pb.PBServerFactory(kajonggPortal))
    except error.CannotListenError as errObj:
        logWarning(errObj)
        sys.exit(1)
    else:
        reactor.run()


def profileMe():
    """where do we lose time?"""
    import cProfile
    cProfile.run('kajonggServer()', 'prof')
    import pstats
    statistics = pstats.Stats('prof')
    statistics.sort_stats('cumulative')
    statistics.print_stats(40)